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: correct SparseSet sort mapping, shader leak, scene load races, and prefab save handling

esengine0aa58837175c
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 89f453119..280b11f60 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 l(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 c(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 l(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 c(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=512,F=4294967295,B=4294967295;function U(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(U);const t={};for(const s in e)t[s]=U(e[s]);return t}let k=0;function D(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...U(t),...e}:U(t)}}function L(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function $(e,t){const s=L(),n=s.get(e);if(n)return n;const r=D(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=L(),s=t.get(e);if(s)return s;const n=D(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return L().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=$("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const le=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=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_)}}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.value_=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_),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[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<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[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]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}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=Ue(t[e]),o=Ue(r);s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r})}return n}function Ue(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")}function De(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}:De(e)}}return t}class Le{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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)}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(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;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,De(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const $e=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 We;function ze(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(We=exports.BlendMode||(exports.BlendMode={}))[We.Normal=0]="Normal",We[We.Additive=1]="Additive",We[We.Multiply=2]="Multiply",We[We.Screen=3]="Screen",We[We.PremultipliedAlpha=4]="PremultipliedAlpha";let Oe=null,He=null,je=1;const Ne=new Map;function Ve(e){Oe=e,He=e.getResourceManager(),tt()}function Xe(){0!==Je&&Oe&&(Oe._free(Je),Je=0),Ne.clear(),je=1,Ye=!1,He=null,Oe=null}function Ge(){if(!He)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return He}const qe={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=je++,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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ye=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&Oe&&(Je=Oe._malloc(Ke)),Je);if(0===t||!Oe)return{ptr:0,count:0};let s=0,n=0;const r=Oe.HEAPU8,o=Oe.HEAPU32,i=Oe.HEAPF32;for(const[a,l]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!Oe||Ye)return;Oe.materialDataProvider=(e,t,s,n,r)=>{const o=Ne.get(e);if(!o)return Oe.HEAPU32[t>>2]=0,Oe.HEAPU32[s>>2]=0,Oe.HEAPU32[n>>2]=0,void(Oe.HEAPU32[r>>2]=0);Oe.HEAPU32[t>>2]=o.shader,Oe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=et(o.uniforms);Oe.HEAPU32[n>>2]=i,Oe.HEAPU32[r>>2]=a},Ye=!0}const st={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 nt{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)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 rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.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:qe.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 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 it(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)lt(e,t,s)}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 at(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=[],l=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}`;l.has(t)||(l.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 c=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);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.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=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]=c.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)lt(e,t,n)}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 lt(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=V(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class ct{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,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.module_=e,this.canvas_=i(I,I),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new rt(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))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}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(),qe.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===g(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}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 at(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);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return qe.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 qe.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 ut=fe(null,"Assets");class dt{build(e){const t=e.wasmModule;t?e.insertResource(ut,new ct(t)):console.warn("AssetPlugin: No WASM module available")}}const ht=new dt;async function pt(e,t,s){const{entities:n,rootId:r}=await ft(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 at(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}}async function ft(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];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 ft(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?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};gt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function gt(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 _t{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 pt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const mt=fe(null,"Prefabs");class yt{constructor(){this.name="PrefabsPlugin",this.dependencies=[ut]}build(e){const t=e.getResource(ut);e.insertResource(mt,new _t(e.world,t))}}const xt=new yt;let wt=null,vt=0,bt=0,St=0;const Pt=new Float32Array(256);function Tt(e){wt=e,vt=wt._malloc(64),bt=wt._malloc(64),St=wt._malloc(1024)}function Ct(){wt&&(vt&&(wt._free(vt),vt=0),bt&&(wt._free(bt),bt=0),St&&(wt._free(St),St=0)),wt=null}function At(){if(!wt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return wt}const Et={r:1,g:1,b:1,a:1},Mt={begin(e){const t=At();t.HEAPF32.set(e,vt/4),t.draw_begin(vt)},end(){At().draw_end()},line(e,t,s,n=1){At().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){At().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){At().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){At().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){At().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Et){At().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Et){At().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){At().draw_setLayer(e)},setDepth(e){At().draw_setDepth(e)},getDrawCallCount:()=>wt?wt.draw_getDrawCallCount():0,getPrimitiveCount:()=>wt?wt.draw_getPrimitiveCount():0,setBlendMode(e){At().draw_setBlendMode(e)},setDepthTest(e){At().draw_setDepthTest(e)},drawMesh(e,t,s){const n=At();n.HEAPF32.set(s,bt/4),n.draw_mesh(e,t,bt)},drawMeshWithMaterial(e,t,s){const n=At(),r=qe.get(t);if(!r)return;if(Mt.setBlendMode(r.blendMode),Mt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Mt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,bt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=It(t);if(!(n<0)){if(ze(s))Pt[o++]=10,Pt[o++]=n,Pt[o++]=s.slot??e++,Pt[o++]=s.textureId;else if("number"==typeof s)Pt[o++]=1,Pt[o++]=n,Pt[o++]=s;else if(Array.isArray(s)){Pt[o++]=s.length,Pt[o++]=n;for(let e=0;e<s.length;e++)Pt[o++]=s[e]}else"w"in s?(Pt[o++]=4,Pt[o++]=n,Pt[o++]=s.x,Pt[o++]=s.y,Pt[o++]=s.z,Pt[o++]=s.w):"z"in s?(Pt[o++]=3,Pt[o++]=n,Pt[o++]=s.x,Pt[o++]=s.y,Pt[o++]=s.z):(Pt[o++]=2,Pt[o++]=n,Pt[o++]=s.x,Pt[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(Pt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),St/4),n.draw_meshWithUniforms(e,r.shader,bt,St,o)):n.draw_mesh(e,r.shader,bt)}},Rt={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};function It(e){return Rt[e]??-1}var Ft;exports.DataType=void 0,(Ft=exports.DataType||(exports.DataType={}))[Ft.Float=1]="Float",Ft[Ft.Float2=2]="Float2",Ft[Ft.Float3=3]="Float3",Ft[Ft.Float4=4]="Float4",Ft[Ft.Int=5]="Int",Ft[Ft.Int2=6]="Int2",Ft[Ft.Int3=7]="Int3",Ft[Ft.Int4=8]="Int4";let Bt=null,Ut=0,kt=0,Dt=0;function Lt(e){Bt=e,Ut=Bt._malloc(262144),kt=Bt._malloc(65536),Dt=Bt._malloc(256)}function $t(){Bt&&(Ut&&Bt._free(Ut),kt&&Bt._free(kt),Dt&&Bt._free(Dt),Ut=0,kt=0,Dt=0),Bt=null}function Wt(){if(!Bt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Bt}const zt={create(e){const t=Wt(),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,Ut/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,Dt,r).set(o),t.geometry_init(s,Ut,n,Dt,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,kt,n).set(e.indices),t.geometry_setIndices16(s,kt,n)}else{new Uint32Array(t.HEAPU8.buffer,kt,n).set(e.indices),t.geometry_setIndices32(s,kt,n)}}return s},updateVertices(e,t,s=0){const n=Wt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ut/4),n.geometry_updateVertices(e,Ut,r,s)},release(e){e>0&&Wt().geometry_release(e)},isValid:e=>!(!Bt||e<=0)&&Bt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return zt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return zt.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 zt.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 Ot=null;function Ht(e){Ot=e}function jt(){Ot&&Vt.isInitialized()&&Vt.shutdown(),Ot=null}function Nt(){if(!Ot)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ot}const Vt={init:(e,t)=>Nt().postprocess_init(e,t),shutdown(){Nt().postprocess_shutdown()},resize(e,t){Nt().postprocess_resize(e,t)},addPass:(e,t)=>Nt().postprocess_addPass(e,t),removePass(e){Nt().postprocess_removePass(e)},setEnabled(e,t){Nt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Nt().postprocess_isPassEnabled(e),setUniform(e,t,s){Nt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Nt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Nt().postprocess_begin()},end(){Nt().postprocess_end()},getPassCount:()=>Nt().postprocess_getPassCount(),isInitialized:()=>!!Ot&&Ot.postprocess_isInitialized(),setBypass(e){Nt().postprocess_setBypass(e)},isBypassed:()=>!Ot||Ot.postprocess_isBypassed(),createBlur:()=>qe.createShader(Xt,"#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:()=>qe.createShader(Xt,"#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:()=>qe.createShader(Xt,"#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:()=>qe.createShader(Xt,"#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")},Xt="#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 Gt;exports.RenderStage=void 0,(Gt=exports.RenderStage||(exports.RenderStage={}))[Gt.Background=0]="Background",Gt[Gt.Opaque=1]="Opaque",Gt[Gt.Transparent=2]="Transparent",Gt[Gt.Overlay=3]="Overlay";let qt=null,Yt=0;function Jt(e){qt=e,Yt=qt._malloc(64)}function Kt(){qt&&Yt&&(qt._free(Yt),Yt=0),qt=null}const Qt={init(e,t){qt?.renderer_init(e,t)},resize(e,t){qt?.renderer_resize(e,t)},begin(e,t){qt&&Yt&&(qt.HEAPF32.set(e,Yt/4),qt.renderer_begin(Yt,t??0))},flush(){qt?.renderer_flush()},end(){qt?.renderer_end()},submitSprites(e){qt&&qt.renderer_submitSprites(e._cpp)},submitBitmapText(e){qt&&qt.renderer_submitBitmapText(e._cpp)},submitSpine(e){qt&&qt.renderer_submitSpine?.(e._cpp)},setStage(e){qt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>qt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){qt?.renderer_releaseTarget(e)},getTargetTexture:e=>qt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>qt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){qt?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){qt?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){qt?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){qt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>qt?qt.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>qt?{drawCalls:qt.renderer_getDrawCalls(),triangles:qt.renderer_getTriangles(),sprites:qt.renderer_getSprites(),text:qt.renderer_getText(),spine:qt.renderer_getSpine?.()??0,meshes:qt.renderer_getMeshes(),culled:qt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Zt=null;function es(e){Zt=e}function ts(){Zt=null}const ss={enable(){Zt?.gl_enableErrorCheck(!0)},disable(){Zt?.gl_enableErrorCheck(!1)},check:e=>Zt?.gl_checkErrors(e)??0,diagnose(){Zt?.renderer_diagnose()}},ns=new Map;function rs(e,t,s){ns.set(e,{fn:t,scene:s??""})}function os(e){ns.delete(e)}class is{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_||(Qt.resize(n,r),Vt.isInitialized()&&Vt.getPassCount()>0&&Vt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Qt.setViewport(0,0,n,r),Qt.clearBuffers(3),Qt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Qt.submitSprites(t),Qt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Qt.submitSpine(t),Qt.flush(),this.executeDrawCallbacks(s,o),Qt.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Qt.setViewport(n.x,n.y,n.w,n.h),Qt.setScissor(n.x,n.y,n.w,n.h,!0),Qt.clearBuffers(r),Qt.setScissor(0,0,0,0,!1),Qt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Qt.submitSprites(t),Qt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Qt.submitSpine(t),Qt.flush(),this.executeDrawCallbacks(s,o),Qt.end()}executeDrawCallbacks(e,t){const s=ns;if(s.size>0){Mt.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)}Mt.end();for(const e of n)os(e)}}}const as="__scene_transition_overlay__",ls={r:0,g:0,b:0,a:1};class cs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class us{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),rs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Vt.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Vt.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 ds{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.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){"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??.3,r=t.color??ls;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},rs(as,()=>{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;Mt.setLayer(9999),Mt.setDepth(9999),Mt.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)})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,os(as),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 cs(t);this.scenes_.set(e,s);const n=new us(s,this.app_);this.contexts_.set(e,n);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 at(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=ps(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}async loadAdditive(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 cs(t);this.scenes_.set(e,s);const n=new us(s,this.app_);this.contexts_.set(e,n);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 at(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=ps(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}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())os(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Vt.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{Vt.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 hs=fe(null,"SceneManager");function ps(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(hs).getSceneStatus(t)&&s._fn(...n)}}}const fs=Ce([_e(hs),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),gs={name:"SceneManager",build(e){const t=new ds(e);e.insertResource(hs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(hs),s=t.getInitial();s&&t.load(s)}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,fs)}};class _s{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=8&&(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 Le,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new _s}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}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_}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}onError(e){return this.error_handler_=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(hs).register(e),this}setInitialScene(e){return this.getResource(hs).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;const e=[ts,Kt,jt,$t,Xe,Ct];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){let t=this.systems_.get(e);if(t&&this.runner_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(xe);t.delta=e,t.elapsed+=e,t.frameCount++}}const ms=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ys(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 xs(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 l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.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,l){h=ys(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=vs(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ss(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Ts(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(As(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const ws=new Float32Array(16);function vs(e,t,s,n,r,o){const i=ws;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const bs=new Float32Array(16);function Ss(e,t,s,n){const r=bs;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 Ps=new Float32Array(16);function Ts(e,t,s){const n=Ps;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 Cs=new Float32Array(16);function As(e,t){const s=Cs;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 Es,Ms,Rs;exports.TextAlign=void 0,(Es=exports.TextAlign||(exports.TextAlign={}))[Es.Left=0]="Left",Es[Es.Center=1]="Center",Es[Es.Right=2]="Right",exports.TextVerticalAlign=void 0,(Ms=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Ms.Top=0]="Top",Ms[Ms.Middle=1]="Middle",Ms[Ms.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Rs=exports.TextOverflow||(exports.TextOverflow={}))[Rs.Visible=0]="Visible",Rs[Rs.Clip=1]="Clip",Rs[Rs.Ellipsis=2]="Ellipsis";const Is=$("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}),Fs=$("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 Bs{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I,I),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 l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=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/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[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=l.length*c;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 l){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+=c}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 Us(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 ks(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 Ds{build(e){N("Text",Is);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Bs(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Is));for(const e of r.keys())n.valid(e)&&n.has(e,Is)||r.delete(e);const e=n.getEntitiesWithComponents([Is]);for(const t of e){const e=n.get(t,Is),o=n.has(t,Fs)?n.get(t,Fs):null,i=r.get(t);if(i&&!ks(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),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,Us(e,o))}}))}}const Ls=new Ds,$s=$("UIMask",{enabled:!0});function Ws(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 zs(e,t,s,n,r,o,i,a,l,c,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)*c,l+(.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 Os(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],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*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,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]=(l*R-c*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]=(c*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-l*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]=(l*C-a*E-c*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 Hs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function js(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 Ns(e,t,s,n,r,o,i){if(!e.has(t,Fs)||!e.has(t,K))return null;const a=e.get(t,Fs),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return zs(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Vs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([$s]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,$s).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.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(c.has(s)){const e=Ns(t,s,r,o,i,a,l);e&&(n=Ws(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Ns(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Xs{build(e){if(N("UIMask",$s),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Vs(e.wasmModule,e.world))}}const Gs=new Xs,qs=$("Interactable",{enabled:!0}),Ys=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Js;exports.ButtonState=void 0,(Js=exports.ButtonState||(exports.ButtonState={}))[Js.Normal=0]="Normal",Js[Js.Hovered=1]="Hovered",Js[Js.Pressed=2]="Pressed",Js[Js.Disabled=3]="Disabled";const Ks=$("Button",{state:exports.ButtonState.Normal,transition:null});class Qs{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 Zs=fe(new Qs,"UIEvents"),en=W("ScreenSpace");function tn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(l===c&&u===d){const e=l+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=l+s.x,p=u+s.y,f=c+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 sn(e,t,s,n,r,o){if(!e.has(t,Fs))return;const i=e.get(t,Fs),a=tn(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 l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&sn(e,t,a.rect,a.centerX,a.centerY,!1)}class nn{build(e){N("UIRect",Fs);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge($e)],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([en,Fs,J]);for(const e of o)sn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const rn=new nn,on=new Float32Array(16),an=new Float32Array(16);let ln=!0,cn=1;class un{build(e){N("Interactable",qs),N("Button",Ks);const t=e.world,s=new Qs;e.insertResource(Zs,s);let n=null,r=null;cn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge($e)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Ys]);for(const e of i){const s=t.get(e,Ys);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*cn,l=o.screenH-e.mouseY*cn;!function(e){let t=!1;for(let s=0;s<16;s++)if(an[s]!==e[s]){t=!0;break}t&&(an.set(e),ln=!0)}(o.viewProjection),ln&&(Os(o.viewProjection,on),ln=!1);const c=Hs(a,l,on,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([qs,Fs,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Ys)||t.insert(e,Ys);if(!t.get(e,qs).enabled)continue;const s=t.get(e,K),n=t.get(e,Fs),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(js(c.x,c.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,Ys)){t.get(n,Ys).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Ys).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ys);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,Ys)){const e=t.get(r,Ys);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([Ks]);for(const s of e){if(t.has(s,qs)||t.insert(s,qs,{enabled:!0}),!t.has(s,Ys))continue;const e=t.get(s,Ys),n=t.get(s,Ks),r=t.get(s,qs),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 dn=new un,hn=$("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 pn{build(e){N("TextInput",hn);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,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!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;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,hn);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(Zs).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,m()}function g(e){if(a===e)return;_();const t=s.get(e,hn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),m())}function _(){if(null!==a&&s.valid(a)&&s.has(a,hn)){const e=s.get(a,hn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function m(){c=!0,u=0}function y(e,i,a,l){(r.width<a||r.height<l)&&(r.width=gn(Math.max(r.width,a)),r.height=gn(Math.max(r.height,l))),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,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),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=fn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=fn(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=(l-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,l),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,l,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=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,Q,b)}p.addEventListener("input",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void _();const n=s.get(a,hn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Zs).emit(a,"submit"),void _()}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,m())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,hn)){const e=s.get(a,hn);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Zs)],e=>{const t=s.getEntitiesWithComponents([hn,qs]);for(const e of t){if(!s.has(e,Ys))continue;if(s.get(e,Ys).justPressed)return void g(e)}if(null!==a){const e=s.getEntitiesWithComponents([qs]);for(const t of e){if(s.has(t,hn))continue;if(!s.has(t,Ys))continue;if(s.get(t,Ys).justPressed)return void _()}}},{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,c=!c,null!==a&&s.valid(a)&&s.has(a,hn)))){s.get(a,hn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,hn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([hn,Fs]);for(const e of i){const t=s.get(e,hn);if(!t.dirty)continue;const n=s.get(e,Fs),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}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function fn(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 gn(e){let t=1;for(;t<e;)t*=2;return t}const _n=new pn;async function mn(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 yn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),xn=fe(null,"PhysicsAPI");function wn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function vn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class bn{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(yn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=mn(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 l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=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=wn(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Sn(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=wn(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=l,p=c;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=wn(s.rotation),r=a-s.position.x,o=l-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=c-n}}u.position.x=d,u.position.y=h;const f=vn(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=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(yn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(xn,Pn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Sn(e,t,s){const n=e.world;if(n.has(s,ce)){const e=n.get(s,ce);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 Pn{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(Pn.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 Tn(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 Cn(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 An(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,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,_=a*p,m=l*h,y=l*p,x=c*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 En(e,t,s,n,r,o,i,a,l){const c=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]=Tn(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,c);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 l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===g(l)?.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=Cn(n),_=c.substring(0,c.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=Tn(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 bn("",{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("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.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 l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=Tn(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,c.width,c.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=qe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=qe.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),f=it(e.world,s);if(l&&e.hasResource(hs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,Q);r&&(r.texture=s[n.data.texture]||0,e.insert(t,Q,r))}}}(e.world,s,c,f),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,s,h,f),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}else if("SpineAnimation"===n.type){const s=e.get(t,oe);s&&(s.material=r,e.insert(t,oe,s))}}}}(e.world,s,p,f),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 l=n.get(o.id);void 0!==l&&(r[l]=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 l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=An(c.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,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(l);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(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(ut);t&&t.setAddressableManifest(a)}}class Mn{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 Rn="__preview__";const In={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Qt.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Qt.getTargetTexture(s),width:e.width,height:e.height}},release(e){Qt.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Qt.releaseRenderTarget(e._handle),In.create({width:t,height:s,depth:!0})),begin(e,t){Qt.begin(t,e._handle)},end(){Qt.end()},getDepthTexture:e=>Qt.getTargetDepthTexture(e._handle)};let Fn=!1;var Bn;exports.LogLevel=void 0,(Bn=exports.LogLevel||(exports.LogLevel={}))[Bn.Debug=0]="Debug",Bn[Bn.Info=1]="Info",Bn[Bn.Warn=2]="Warn",Bn[Bn.Error=3]="Error";class Un{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 kn{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Un)}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 Dn=new kn;const Ln=[Ls,Gs,rn,dn,_n];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 l(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 c(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=_s,exports.AssetPlugin=dt,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=ct,exports.Assets=ut,exports.AsyncCache=nt,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=Ks,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=I,exports.Draw=Mt,exports.EntityCommands=be,exports.GLDebug=ss,exports.Geometry=zt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=qs,exports.LocalTransform=J,exports.Logger=kn,exports.Material=qe,exports.MaterialLoader=rt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Pn,exports.PhysicsEvents=yn,exports.PhysicsPlugin=bn,exports.PostProcess=Vt,exports.PrefabServer=_t,exports.Prefabs=mt,exports.PrefabsPlugin=yt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(hs);t.register({name:Rn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Rn),this.loadPromise_=t.load(Rn).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 Mn(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await En(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Rn)}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(hs).getScene(Rn),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)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(hs);await e.switchTo(Rn),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=is,exports.RenderTexture=In,exports.Renderer=Qt,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=le,exports.ScaleMode=Y,exports.SceneManager=hs,exports.SceneManagerState=ds,exports.SceneOwner=ae,exports.ScreenSpace=en,exports.ShaderSources=st,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Is,exports.TextInput=hn,exports.TextInputPlugin=pn,exports.TextPlugin=Ds,exports.TextRenderer=Bs,exports.Time=xe,exports.UICameraInfo=$e,exports.UIEventQueue=Qs,exports.UIEvents=Zs,exports.UIInteraction=Ys,exports.UIInteractionPlugin=un,exports.UILayoutPlugin=nn,exports.UIMask=$s,exports.UIMaskPlugin=Xs,exports.UIRect=Fs,exports.Velocity=te,exports.WebAssetProvider=Mn,exports.World=Le,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.assetPlugin=ht,exports.clearDrawCallbacks=function(){ns.clear()},exports.clearUserComponents=function(){L().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=tn,exports.createMaskProcessor=Vs,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await En(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=_s.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Tt(e),Ve(e),Lt(e),Ht(e),Jt(e),es(e);const r=new is;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=xs(e,n,t,r));const i=s.getResource($e);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($e,{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}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Qt.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(Qt.resize(t,c),Vt.isInitialized()&&Vt.getPassCount()>0&&!Vt.isBypassed()&&Vt.resize(t,c),s.hasResource(hs)){const e=s.getResource(hs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=xs(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:ms,width:t,height:c,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)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:d})}Qt.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(ht),s.addPlugin(xt),s.addPlugin(Fe),s.addPlugin(gs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ln,...t})},exports.debug=function(e,t,s){Dn.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){Dn.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=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},exports.getComponentDefaults=function(e){const t=V(e);return t?U(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Dn},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){Dn.info(e,t,s)},exports.initDrawAPI=Tt,exports.initGLDebugAPI=es,exports.initGeometryAPI=Lt,exports.initMaterialAPI=Ve,exports.initPostProcessAPI=Ht,exports.initRendererAPI=Jt,exports.inputPlugin=Fe,exports.instantiatePrefab=pt,exports.intersectRects=Ws,exports.invertMatrix4=Os,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return Fn},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Fn},exports.isTextureRef=ze,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=lt,exports.loadPhysicsModule=mn,exports.loadRuntimeScene=En,exports.loadSceneData=it,exports.loadSceneWithAssets=at,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=js,exports.prefabsPlugin=xt,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){ot.set(e,t)},exports.registerDrawCallback=rs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ut);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tt,exports.sceneManagerPlugin=gs,exports.screenToWorld=Hs,exports.setEditorMode=function(e){Fn=e},exports.setLogLevel=function(e){Dn.setMinLevel(e)},exports.shutdownDrawAPI=Ct,exports.shutdownGLDebugAPI=ts,exports.shutdownGeometryAPI=$t,exports.shutdownMaterialAPI=Xe,exports.shutdownPostProcessAPI=jt,exports.shutdownRendererAPI=Kt,exports.textInputPlugin=_n,exports.textPlugin=Ls,exports.transitionTo=async function(e,t,s){const n=e.getResource(hs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=dn,exports.uiLayoutPlugin=rn,exports.uiMaskPlugin=Gs,exports.uiPlugins=Ln,exports.unregisterDrawCallback=os,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){Dn.warn(e,t,s)},exports.worldRectToScreen=zs,exports.wrapSceneSystem=ps,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 l(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 c(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 l(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 c(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=512,F=4294967295,B=4294967295;function k(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(k);const t={};for(const s in e)t[s]=k(e[s]);return t}let U=0;function L(e,t){const s=++U;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...k(t),...e}:k(t)}}function D(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function $(e,t){const s=D(),n=s.get(e);if(n)return n;const r=L(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=L(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=$("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const le=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=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_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[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<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[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=ke(t[e]),o=ke(r);s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r})}return n}function ke(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")}function Le(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}:Le(e)}}return t}class De{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(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;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Le(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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 l=o?o.keys():this.entities_;for(const t of l){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 $e=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 We;function ze(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(We=exports.BlendMode||(exports.BlendMode={}))[We.Normal=0]="Normal",We[We.Additive=1]="Additive",We[We.Multiply=2]="Multiply",We[We.Screen=3]="Screen",We[We.PremultipliedAlpha=4]="PremultipliedAlpha";let Oe=null,He=null,je=1;const Ne=new Map;function Ve(e){Oe=e,He=e.getResourceManager(),tt()}function Xe(){0!==Je&&Oe&&(Oe._free(Je),Je=0),Ne.clear(),je=1,Ye=!1,Qe.clear(),Ze=null,He=null,Oe=null}function Ge(){if(!He)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return He}const qe={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=je++,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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ye=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&Oe&&(Je=Oe._malloc(Ke)),Je);if(0===t||!Oe)return{ptr:0,count:0};let s=0,n=0;const r=Oe.HEAPU8,o=Oe.HEAPU32,i=Oe.HEAPF32;for(const[a,l]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!Oe||Ye)return;Oe.materialDataProvider=(e,t,s,n,r)=>{const o=Ne.get(e);if(!o)return Oe.HEAPU32[t>>2]=0,Oe.HEAPU32[s>>2]=0,Oe.HEAPU32[n>>2]=0,void(Oe.HEAPU32[r>>2]=0);Oe.HEAPU32[t>>2]=o.shader,Oe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=et(o.uniforms);Oe.HEAPU32[n>>2]=i,Oe.HEAPU32[r>>2]=a},Ye=!0}const st={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 nt{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 rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.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:qe.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 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 it(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)lt(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 at(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=[],l=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}`;l.has(t)||(l.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 c=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);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.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=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]=c.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)lt(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 lt(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 ct{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,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,I),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new rt(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(),qe.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===g(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}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 at(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return qe.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 qe.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 ut=fe(null,"Assets");class dt{build(e){const t=e.wasmModule;t?e.insertResource(ut,new ct(t)):console.warn("AssetPlugin: No WASM module available")}}const ht=new dt;async function pt(e,t,s){const{entities:n,rootId:r}=await gt(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 at(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 ft=10;async function gt(e,t,s,n,r,o=0){if(o>ft)throw new Error(`Prefab nesting depth exceeded ${ft}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){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 gt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,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};_t(d,t),l.push(d)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function _t(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 mt{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 pt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const yt=fe(null,"Prefabs");class xt{constructor(){this.name="PrefabsPlugin",this.dependencies=[ut]}build(e){const t=e.getResource(ut);e.insertResource(yt,new mt(e.world,t))}}const wt=new xt;let vt=null,bt=0,St=0,Pt=0;const Tt=new Float32Array(256);function Ct(e){vt=e,bt=vt._malloc(64),St=vt._malloc(64),Pt=vt._malloc(1024)}function At(){vt&&(bt&&(vt._free(bt),bt=0),St&&(vt._free(St),St=0),Pt&&(vt._free(Pt),Pt=0)),vt=null}function Et(){if(!vt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return vt}const Mt={r:1,g:1,b:1,a:1},Rt={begin(e){const t=Et();t.HEAPF32.set(e,bt/4),t.draw_begin(bt)},end(){Et().draw_end()},line(e,t,s,n=1){Et().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Et().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Et().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Et().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Et().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Mt){Et().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Mt){Et().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Et().draw_setLayer(e)},setDepth(e){Et().draw_setDepth(e)},getDrawCallCount:()=>vt?vt.draw_getDrawCallCount():0,getPrimitiveCount:()=>vt?vt.draw_getPrimitiveCount():0,setBlendMode(e){Et().draw_setBlendMode(e)},setDepthTest(e){Et().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Et();n.HEAPF32.set(s,St/4),n.draw_mesh(e,t,St)},drawMeshWithMaterial(e,t,s){const n=Et(),r=qe.get(t);if(!r)return;if(Rt.setBlendMode(r.blendMode),Rt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Rt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,St/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Ft(t);if(!(n<0)){if(ze(s))Tt[o++]=10,Tt[o++]=n,Tt[o++]=s.slot??e++,Tt[o++]=s.textureId;else if("number"==typeof s)Tt[o++]=1,Tt[o++]=n,Tt[o++]=s;else if(Array.isArray(s)){Tt[o++]=s.length,Tt[o++]=n;for(let e=0;e<s.length;e++)Tt[o++]=s[e]}else"w"in s?(Tt[o++]=4,Tt[o++]=n,Tt[o++]=s.x,Tt[o++]=s.y,Tt[o++]=s.z,Tt[o++]=s.w):"z"in s?(Tt[o++]=3,Tt[o++]=n,Tt[o++]=s.x,Tt[o++]=s.y,Tt[o++]=s.z):(Tt[o++]=2,Tt[o++]=n,Tt[o++]=s.x,Tt[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(Tt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Pt/4),n.draw_meshWithUniforms(e,r.shader,St,Pt,o)):n.draw_mesh(e,r.shader,St)}},It={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};function Ft(e){return It[e]??-1}const Bt=new Map;function kt(e,t,s){Bt.set(e,{fn:t,scene:s??""})}function Ut(e){Bt.delete(e)}function Lt(){Bt.clear()}var Dt;exports.DataType=void 0,(Dt=exports.DataType||(exports.DataType={}))[Dt.Float=1]="Float",Dt[Dt.Float2=2]="Float2",Dt[Dt.Float3=3]="Float3",Dt[Dt.Float4=4]="Float4",Dt[Dt.Int=5]="Int",Dt[Dt.Int2=6]="Int2",Dt[Dt.Int3=7]="Int3",Dt[Dt.Int4=8]="Int4";let $t=null,Wt=0,zt=0,Ot=0;function Ht(e){$t=e,Wt=$t._malloc(262144),zt=$t._malloc(65536),Ot=$t._malloc(256)}function jt(){$t&&(Wt&&$t._free(Wt),zt&&$t._free(zt),Ot&&$t._free(Ot),Wt=0,zt=0,Ot=0),$t=null}function Nt(){if(!$t)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return $t}const Vt={create(e){const t=Nt(),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,Wt/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,Ot,r).set(o),t.geometry_init(s,Wt,n,Ot,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,zt,n).set(e.indices),t.geometry_setIndices16(s,zt,n)}else{new Uint32Array(t.HEAPU8.buffer,zt,n).set(e.indices),t.geometry_setIndices32(s,zt,n)}}return s},updateVertices(e,t,s=0){const n=Nt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Wt/4),n.geometry_updateVertices(e,Wt,r,s)},release(e){e>0&&Nt().geometry_release(e)},isValid:e=>!(!$t||e<=0)&&$t.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Vt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Vt.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 Vt.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 Xt=null;function Gt(e){Xt=e}function qt(){Xt&&Jt.isInitialized()&&Jt.shutdown(),Xt=null}function Yt(){if(!Xt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Xt}const Jt={init:(e,t)=>Yt().postprocess_init(e,t),shutdown(){Yt().postprocess_shutdown()},resize(e,t){Yt().postprocess_resize(e,t)},addPass:(e,t)=>Yt().postprocess_addPass(e,t),removePass(e){Yt().postprocess_removePass(e)},setEnabled(e,t){Yt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Yt().postprocess_isPassEnabled(e),setUniform(e,t,s){Yt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Yt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Yt().postprocess_begin()},end(){Yt().postprocess_end()},getPassCount:()=>Yt().postprocess_getPassCount(),isInitialized:()=>!!Xt&&Xt.postprocess_isInitialized(),setBypass(e){Yt().postprocess_setBypass(e)},isBypassed:()=>!Xt||Xt.postprocess_isBypassed(),createBlur:()=>qe.createShader(Kt,"#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:()=>qe.createShader(Kt,"#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:()=>qe.createShader(Kt,"#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:()=>qe.createShader(Kt,"#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")},Kt="#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 Qt;exports.RenderStage=void 0,(Qt=exports.RenderStage||(exports.RenderStage={}))[Qt.Background=0]="Background",Qt[Qt.Opaque=1]="Opaque",Qt[Qt.Transparent=2]="Transparent",Qt[Qt.Overlay=3]="Overlay";let Zt=null,es=0;function ts(e){Zt=e,es=Zt._malloc(64)}function ss(){Zt&&es&&(Zt._free(es),es=0),Zt=null}const ns={init(e,t){Zt?.renderer_init(e,t)},resize(e,t){Zt?.renderer_resize(e,t)},begin(e,t){Zt&&es&&(Zt.HEAPF32.set(e,es/4),Zt.renderer_begin(es,t??0))},flush(){Zt?.renderer_flush()},end(){Zt?.renderer_end()},submitSprites(e){Zt&&Zt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Zt&&Zt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Zt&&Zt.renderer_submitSpine?.(e._cpp)},setStage(e){Zt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Zt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Zt?.renderer_releaseTarget(e)},getTargetTexture:e=>Zt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Zt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Zt?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Zt?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Zt?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Zt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Zt?Zt.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Zt?{drawCalls:Zt.renderer_getDrawCalls(),triangles:Zt.renderer_getTriangles(),sprites:Zt.renderer_getSprites(),text:Zt.renderer_getText(),spine:Zt.renderer_getSpine?.()??0,meshes:Zt.renderer_getMeshes(),culled:Zt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let rs=null;function os(e){rs=e}function is(){rs=null}const as={enable(){rs?.gl_enableErrorCheck(!0)},disable(){rs?.gl_enableErrorCheck(!1)},check:e=>rs?.gl_checkErrors(e)??0,diagnose(){rs?.renderer_diagnose()}};class ls{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(ns.resize(n,r),Jt.isInitialized()&&Jt.getPassCount()>0&&Jt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ns.setViewport(0,0,n,r),ns.clearBuffers(3),ns.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ns.submitSprites(t),ns.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ns.submitSpine(t),ns.flush(),this.executeDrawCallbacks(s,o),ns.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ns.setViewport(n.x,n.y,n.w,n.h),ns.setScissor(n.x,n.y,n.w,n.h,!0),ns.clearBuffers(r),ns.setScissor(0,0,0,0,!1),ns.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ns.submitSprites(t),ns.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ns.submitSpine(t),ns.flush(),this.executeDrawCallbacks(s,o),ns.end()}executeDrawCallbacks(e,t){const s=Bt;if(s.size>0){Rt.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)}Rt.end();for(const e of n)Ut(e)}}}const cs="__scene_transition_overlay__",us={r:0,g:0,b:0,a:1};class ds{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class hs{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,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),kt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Jt.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Jt.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 ps{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??.3,r=t.color??us;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},kt(cs,()=>{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;Rt.setLayer(9999),Rt.setDepth(9999),Rt.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,Ut(cs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ut(cs),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 ds(t);this.scenes_.set(e,s);const n=new hs(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 at(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=gs(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 ds(t);this.scenes_.set(e,s);const n=new hs(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 at(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=gs(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())Ut(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Jt.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{Jt.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 fs=fe(null,"SceneManager");function gs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(fs).getSceneStatus(t)&&s._fn(...n)}}}const _s=Ce([_e(fs),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ms={name:"SceneManager",build(e){const t=new ps(e);e.insertResource(fs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(fs),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,_s)}};class ys{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,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,.25);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<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=8&&(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 De,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ys}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}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_}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}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=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(fs).register(e),this}setInitialScene(e){return this.getResource(fs).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,Lt();const e=[is,ss,qt,jt,Xe,At];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){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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 xs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ws(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 vs(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 l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.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,l){h=ws(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=Ss(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ts(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=As(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Ms(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const bs=new Float32Array(16);function Ss(e,t,s,n,r,o){const i=bs;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Ps=new Float32Array(16);function Ts(e,t,s,n){const r=Ps;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 Cs=new Float32Array(16);function As(e,t,s){const n=Cs;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 Es=new Float32Array(16);function Ms(e,t){const s=Es;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 Rs,Is,Fs;exports.TextAlign=void 0,(Rs=exports.TextAlign||(exports.TextAlign={}))[Rs.Left=0]="Left",Rs[Rs.Center=1]="Center",Rs[Rs.Right=2]="Right",exports.TextVerticalAlign=void 0,(Is=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Is.Top=0]="Top",Is[Is.Middle=1]="Middle",Is[Is.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Fs=exports.TextOverflow||(exports.TextOverflow={}))[Fs.Visible=0]="Visible",Fs[Fs.Clip=1]="Clip",Fs[Fs.Ellipsis=2]="Ellipsis";const Bs=$("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}),ks=$("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 Us{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I,I),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 l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=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/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[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=l.length*c;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 l){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+=c}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 Ls(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 Ds(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 $s{build(e){N("Text",Bs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Us(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Bs));for(const e of r.keys())n.valid(e)&&n.has(e,Bs)||r.delete(e);const e=n.getEntitiesWithComponents([Bs]);for(const t of e){const e=n.get(t,Bs),o=n.has(t,ks)?n.get(t,ks):null,i=r.get(t);if(i&&!Ds(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),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,Ls(e,o))}}))}}const Ws=new $s,zs=$("UIMask",{enabled:!0});function Os(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 Hs(e,t,s,n,r,o,i,a,l,c,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)*c,l+(.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 js(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],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*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,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]=(l*R-c*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]=(c*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-l*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]=(l*C-a*E-c*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 Ns(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Vs(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 Xs(e,t,s,n,r,o,i){if(!e.has(t,ks)||!e.has(t,K))return null;const a=e.get(t,ks),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Hs(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Gs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([zs]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,zs).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.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(c.has(s)){const e=Xs(t,s,r,o,i,a,l);e&&(n=Os(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Xs(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class qs{build(e){if(N("UIMask",zs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Gs(e.wasmModule,e.world))}}const Ys=new qs,Js=$("Interactable",{enabled:!0}),Ks=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Qs;exports.ButtonState=void 0,(Qs=exports.ButtonState||(exports.ButtonState={}))[Qs.Normal=0]="Normal",Qs[Qs.Hovered=1]="Hovered",Qs[Qs.Pressed=2]="Pressed",Qs[Qs.Disabled=3]="Disabled";const Zs=$("Button",{state:exports.ButtonState.Normal,transition:null});class en{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 tn=fe(new en,"UIEvents"),sn=W("ScreenSpace");function nn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(l===c&&u===d){const e=l+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=l+s.x,p=u+s.y,f=c+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 rn(e,t,s,n,r,o){if(!e.has(t,ks))return;const i=e.get(t,ks),a=nn(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 l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&rn(e,t,a.rect,a.centerX,a.centerY,!1)}class on{build(e){N("UIRect",ks);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge($e)],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([sn,ks,J]);for(const e of o)rn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const an=new on,ln=new Float32Array(16),cn=new Float32Array(16);let un=!0,dn=1;class hn{build(e){N("Interactable",Js),N("Button",Zs);const t=e.world,s=new en;e.insertResource(tn,s);let n=null,r=null;dn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge($e)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Ks]);for(const e of i){const s=t.get(e,Ks);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*dn,l=o.screenH-e.mouseY*dn;!function(e){let t=!1;for(let s=0;s<16;s++)if(cn[s]!==e[s]){t=!0;break}t&&(cn.set(e),un=!0)}(o.viewProjection),un&&(js(o.viewProjection,ln),un=!1);const c=Ns(a,l,ln,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Js,ks,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Ks)||t.insert(e,Ks);if(!t.get(e,Js).enabled)continue;const s=t.get(e,K),n=t.get(e,ks),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Vs(c.x,c.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,Ks)){t.get(n,Ks).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Ks).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ks);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,Ks)){const e=t.get(r,Ks);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([Zs]);for(const s of e){if(t.has(s,Js)||t.insert(s,Js,{enabled:!0}),!t.has(s,Ks))continue;const e=t.get(s,Ks),n=t.get(s,Zs),r=t.get(s,Js),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 pn=new hn,fn=$("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 gn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",fn);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,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!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=()=>{l||null===a||x()},g=()=>{l=!0},_=()=>{l=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,fn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(tn).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,fn)){const e=s.get(a,fn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,fn);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(tn).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,fn);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,fn)){const e=s.get(a,fn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,u=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=mn(Math.max(r.width,a)),r.height=mn(Math.max(r.height,l))),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,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),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=_n(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=_n(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=(l-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,l),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,l,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=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,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(tn)],e=>{const t=s.getEntitiesWithComponents([fn,Js]);for(const e of t){if(!s.has(e,Ks))continue;if(s.get(e,Ks).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([Js]);for(const t of e){if(s.has(t,fn))continue;if(!s.has(t,Ks))continue;if(s.get(t,Ks).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,c=!c,null!==a&&s.valid(a)&&s.has(a,fn)))){s.get(a,fn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,fn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([fn,ks]);for(const e of i){const t=s.get(e,fn);if(!t.dirty)continue;const n=s.get(e,ks),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 _n(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 mn(e){let t=1;for(;t<e;)t*=2;return t}const yn=new gn;async function xn(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 wn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),vn=fe(null,"PhysicsAPI");function bn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Sn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Pn{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(wn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=xn(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 l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=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=bn(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Tn(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=bn(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=l,p=c;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=bn(s.rotation),r=a-s.position.x,o=l-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=c-n}}u.position.x=d,u.position.y=h;const f=Sn(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=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(wn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(vn,Cn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Tn(e,t,s){const n=e.world;if(n.has(s,ce)){const e=n.get(s,ce);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 Cn{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(Cn.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 An(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 En(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 Mn(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,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,_=a*p,m=l*h,y=l*p,x=c*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 Rn(e,t,s,n,r,o,i,a,l){const c=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]=An(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,c);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 l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===g(l)?.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=En(n),_=c.substring(0,c.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=An(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 Pn("",{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("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.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 l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=An(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,c.width,c.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=qe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=qe.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),f=it(e.world,s);if(l&&e.hasResource(fs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,Q);r&&(r.texture=s[n.data.texture]||0,e.insert(t,Q,r))}}}(e.world,s,c,f),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,s,h,f),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}else if("SpineAnimation"===n.type){const s=e.get(t,oe);s&&(s.material=r,e.insert(t,oe,s))}}}}(e.world,s,p,f),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 l=n.get(o.id);void 0!==l&&(r[l]=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 l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=Mn(c.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,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(l);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(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(ut);t&&t.setAddressableManifest(a)}}class In{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 Fn="__preview__";const Bn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ns.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ns.getTargetTexture(s),width:e.width,height:e.height}},release(e){ns.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ns.releaseRenderTarget(e._handle),Bn.create({width:t,height:s,depth:!0})),begin(e,t){ns.begin(t,e._handle)},end(){ns.end()},getDepthTexture:e=>ns.getTargetDepthTexture(e._handle)};let kn=!1;var Un;exports.LogLevel=void 0,(Un=exports.LogLevel||(exports.LogLevel={}))[Un.Debug=0]="Debug",Un[Un.Info=1]="Info",Un[Un.Warn=2]="Warn",Un[Un.Error=3]="Error";class Ln{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 Dn{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Ln)}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 $n=new Dn;const Wn=[Ws,Ys,an,pn,yn];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 l(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 c(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=ys,exports.AssetPlugin=dt,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=ct,exports.Assets=ut,exports.AsyncCache=nt,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=Zs,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=I,exports.Draw=Rt,exports.EntityCommands=be,exports.GLDebug=as,exports.Geometry=Vt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=Js,exports.LocalTransform=J,exports.Logger=Dn,exports.Material=qe,exports.MaterialLoader=rt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Cn,exports.PhysicsEvents=wn,exports.PhysicsPlugin=Pn,exports.PostProcess=Jt,exports.PrefabServer=mt,exports.Prefabs=yt,exports.PrefabsPlugin=xt,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(fs);t.register({name:Fn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Fn),this.loadPromise_=t.load(Fn).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 In(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Rn(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Fn)}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(fs).getScene(Fn),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(fs);await e.switchTo(Fn),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=ls,exports.RenderTexture=Bn,exports.Renderer=ns,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=le,exports.ScaleMode=Y,exports.SceneManager=fs,exports.SceneManagerState=ps,exports.SceneOwner=ae,exports.ScreenSpace=sn,exports.ShaderSources=st,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Bs,exports.TextInput=fn,exports.TextInputPlugin=gn,exports.TextPlugin=$s,exports.TextRenderer=Us,exports.Time=xe,exports.UICameraInfo=$e,exports.UIEventQueue=en,exports.UIEvents=tn,exports.UIInteraction=Ks,exports.UIInteractionPlugin=hn,exports.UILayoutPlugin=on,exports.UIMask=zs,exports.UIMaskPlugin=qs,exports.UIRect=ks,exports.Velocity=te,exports.WebAssetProvider=In,exports.World=De,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.assetPlugin=ht,exports.clearDrawCallbacks=Lt,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=nn,exports.createMaskProcessor=Gs,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await Rn(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=ys.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ct(e),Ve(e),Ht(e),Gt(e),ts(e),os(e);const r=new ls;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=vs(e,n,t,r));const i=s.getResource($e);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($e,{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}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;ns.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(ns.resize(t,c),Jt.isInitialized()&&Jt.getPassCount()>0&&!Jt.isBypassed()&&Jt.resize(t,c),s.hasResource(fs)){const e=s.getResource(fs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=vs(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:xs,width:t,height:c,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)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:d})}ns.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(ht),s.addPlugin(wt),s.addPlugin(Fe),s.addPlugin(ms),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Wn,...t})},exports.debug=function(e,t,s){$n.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){$n.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=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},exports.getComponentDefaults=function(e){const t=V(e);return t?k(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return $n},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){$n.info(e,t,s)},exports.initDrawAPI=Ct,exports.initGLDebugAPI=os,exports.initGeometryAPI=Ht,exports.initMaterialAPI=Ve,exports.initPostProcessAPI=Gt,exports.initRendererAPI=ts,exports.inputPlugin=Fe,exports.instantiatePrefab=pt,exports.intersectRects=Os,exports.invertMatrix4=js,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return kn},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!kn},exports.isTextureRef=ze,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=lt,exports.loadPhysicsModule=xn,exports.loadRuntimeScene=Rn,exports.loadSceneData=it,exports.loadSceneWithAssets=at,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=Vs,exports.prefabsPlugin=wt,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){ot.set(e,t)},exports.registerDrawCallback=kt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ut);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tt,exports.sceneManagerPlugin=ms,exports.screenToWorld=Ns,exports.setEditorMode=function(e){kn=e},exports.setLogLevel=function(e){$n.setMinLevel(e)},exports.shutdownDrawAPI=At,exports.shutdownGLDebugAPI=is,exports.shutdownGeometryAPI=jt,exports.shutdownMaterialAPI=Xe,exports.shutdownPostProcessAPI=qt,exports.shutdownRendererAPI=ss,exports.textInputPlugin=yn,exports.textPlugin=Ws,exports.transitionTo=async function(e,t,s){const n=e.getResource(fs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=pn,exports.uiLayoutPlugin=an,exports.uiMaskPlugin=Ys,exports.uiPlugins=Wn,exports.unregisterDrawCallback=Ut,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){$n.warn(e,t,s)},exports.worldRectToScreen=Hs,exports.wrapSceneSystem=gs,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 71c1d19f2..0e6ae29d4 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 u(e,s){return t().instantiateWasm(e,s)}function d(e,s){return t().createCanvas(e,s)}function h(){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}],g={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"},m=new Map,y=new Set;for(const e of _)for(const t of e.extensions)m.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 m.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 A(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function E(){return A().map(e=>({type:"suffix",value:e}))}function M(e){return g[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 k(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 B(e){return new Promise((t,s)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function U(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(k(e,t.errMsg)))}})})}function $(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 B(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return 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=0,Y=4294967295,J=4294967295,K=(e=0,t=0)=>({x:e,y:t}),Q=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),Z=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),ee=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),te=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function se(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(se);const t={};for(const s in e)t[s]=se(e[s]);return t}let ne=0;function re(e,t){const s=++ne;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...se(t),...e}:se(t)}}function ie(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function oe(e,t){const s=ie(),n=s.get(e);if(n)return n;const r=re(e,t);return s.set(e,r),ue(e,t,!1),r}function ae(e){const t=ie(),s=t.get(e);if(s)return s;const n=re(e,{});return t.set(e,n),ue(e,{},!0),n}function ce(e){return ie().get(e)}function le(){ie().clear()}function ue(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function de(e){return!0===e._builtin}const he=new Map;function fe(e,t){he.set(e,t)}function pe(e){return he.get(e)??ce(e)}function _e(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return he.set(e,s),s}const ge={Perspective:0,Orthographic:1},me={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ye={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},we=_e("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),xe=_e("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ve=_e("Sprite",{texture:Y,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}),be=_e("Camera",{projectionType:ge.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:me.ColorAndDepth}),Se=_e("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:ye.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Pe=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Te=_e("Children",{entities:[]}),Ae=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Ee=_e("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}),Me={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Re=oe("SceneOwner",{scene:"",persistent:!1});function Ie(e){const t=pe(e);return t?se(t._default):null}fe("Name",Me);const Fe=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ke=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Be=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$e={Static:0,Kinematic:1,Dynamic:2};let De=0;function ze(e,t){const s=++De;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function We(e){return{_type:"res",_resource:e}}function Oe(e){return{_type:"res_mut",_resource:e}}class Le{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_)}}class He{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.value_=this.get(e),t):(t=new Le(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const je=ze({delta:0,elapsed:0,frameCount:0},"Time");function Ne(e){return{_type:"mut",_component:e}}function Xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ve(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{Xe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class qe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Xe(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_),r=s.length,i=e.length>0,o=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&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){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(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(this.world_.endIteration(),null!==u&&i)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}}function Ge(){return{_type:"commands"}}class Ye{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=de(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 Je{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ye(this,null);return this.spawned_.push(e),e}entity(e){return new Ye(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 Ke;!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"}(Ke||(Ke={}));let Qe=0;function Ze(e,t,s){const n=++Qe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function et(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function tt(e){et().push({schedule:Ke.Update,system:e})}function st(e){et().push({schedule:Ke.Startup,system:e})}function nt(e,t){et().push({schedule:e,system:t})}class rt{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]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Je&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new qe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Je(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class it{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 ot=ze(new it,"Input");class at{constructor(e){this.target_=e??null}build(e){const s=new it;e.insertResource(ot,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(Ke.Last,Ze([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ct=new at;function lt(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=ut(t[e]),i=ut(r);s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r})}return n}function ut(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function dt(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")}function ht(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}:ht(e)}}return t}class ft{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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)}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return de(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return de(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return de(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(de(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");de(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=lt(t._name,t._default,n);if(e.length>0)throw new Error(dt(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,ht(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=lt(t._name,t._default,e);if(r.length>0)throw new Error(dt(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){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!de(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const i=this.queryPool_[this.queryPoolIdx_++];i.length=0;const o=n?n.keys():this.entities_;for(const t of o){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&i.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:i}),i}}const pt=ze({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var _t;function gt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(_t||(_t={}));let mt=null,yt=null,wt=1;const xt=new Map;function vt(e){mt=e,yt=e.getResourceManager(),It()}function bt(){0!==Tt&&mt&&(mt._free(Tt),Tt=0),xt.clear(),wt=1,Ct=!1,yt=null,mt=null}function St(){if(!yt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return yt}const Pt={createShader:(e,t)=>St().createShader(e,t),releaseShader(e){e>0&&St().releaseShader(e)},create(e){const t=wt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??_t.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return xt.set(t,s),t},get:e=>xt.get(e),setUniform(e,t,s){const n=xt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=xt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=xt.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=xt.get(e);return t?.blendMode??_t.Normal},setDepthTest(e,t){const s=xt.get(e);s&&(s.depthTest=t)},getShader(e){const t=xt.get(e);return t?.shader??0},release(e){xt.delete(e)},isValid:e=>xt.has(e),releaseAll(){xt.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??_t.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=xt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=wt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return xt.set(s,n),s},toAssetData(e,t){const s=xt.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=xt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ct=!1,Tt=0;const At=4096,Et=new Map;let Mt=null;function Rt(e){const t=(0===Tt&&mt&&(Tt=mt._malloc(At)),Tt);if(0===t||!mt)return{ptr:0,count:0};let s=0,n=0;const r=mt.HEAPU8,i=mt.HEAPU32,o=mt.HEAPF32;for(const[a,c]of e){if(s+128>At)break;let e=Et.get(a);e||(Mt||(Mt=new TextEncoder),e=Mt.encode(a),Et.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[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]);i[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function It(){if(!mt||Ct)return;mt.materialDataProvider=(e,t,s,n,r)=>{const i=xt.get(e);if(!i)return mt.HEAPU32[t>>2]=0,mt.HEAPU32[s>>2]=0,mt.HEAPU32[n>>2]=0,void(mt.HEAPU32[r>>2]=0);mt.HEAPU32[t>>2]=i.shader,mt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Rt(i.uniforms);mt.HEAPU32[n>>2]=o,mt.HEAPU32[r>>2]=a},Ct=!0}const Ft={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 kt{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)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 Bt{constructor(e,t=""){this.cache_=new kt,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&&(Pt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pt.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:Pt.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 Ut=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 $t(e,t){Ut.set(e,t)}function Dt(e){const t=Ut.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 zt(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,Me,{value:n.name}),!1!==n.visible)for(const s of n.components)Ot(e,t,s)}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 Wt(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=Ut.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,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}`,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)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 o)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=Ut.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,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Me,{value:s.name}),!1!==s.visible)for(const n of s.components)Ot(e,t,n)}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 Ot(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=pe(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}function Lt(e,t){const s=e.getEntitiesWithComponents([be]);for(const n of s){const s=e.get(n,be);s&&(s.aspectRatio=t,e.insert(n,be,s))}}function Ht(e,t){const s=e.getEntitiesWithComponents([Me]);for(const n of s){const s=e.get(n,Me);if(s&&s.value===t)return n}return null}class jt{constructor(e){this.textureCache_=new kt,this.shaderCache_=new kt,this.jsonCache_=new kt,this.textCache_=new kt,this.binaryCache_=new kt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new kt,this.prefabCache_=new kt,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.module_=e,this.canvas_=d(q,q),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Bt(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))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}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(),Pt.releaseAll(),this.textureCache_.clearAll(),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),u="binary"===x(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,i,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=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 Wt(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);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}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 Pt.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 Pt.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 Nt=ze(null,"Assets");class Xt{build(e){const t=e.wasmModule;t?e.insertResource(Nt,new jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Vt=new Xt;class qt{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 Gt(e,t){const s=e.getResource(Nt);s&&s.registerEmbeddedAssets(t)}async function Yt(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 Wt(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}}async function Jt(e,t,s,n,r){const i=new Map;let o;if(void 0===n){o=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,o++)}const a=[];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,o,r);i.set(n.prefabEntityId,t.rootId),o=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),a.push(...t.entities);continue}const c=i.get(n.prefabEntityId),l=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:l?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};Kt(u,t),a.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:c,nextId:o}}function Kt(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 Qt{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 Yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Zt=ze(null,"Prefabs");class es{constructor(){this.name="PrefabsPlugin",this.dependencies=[Nt]}build(e){const t=e.getResource(Nt);e.insertResource(Zt,new Qt(e.world,t))}}const ts=new es;let ss=null,ns=0,rs=0,is=0;const os=new Float32Array(256);function as(e){ss=e,ns=ss._malloc(64),rs=ss._malloc(64),is=ss._malloc(1024)}function cs(){ss&&(ns&&(ss._free(ns),ns=0),rs&&(ss._free(rs),rs=0),is&&(ss._free(is),is=0)),ss=null}function ls(){if(!ss)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ss}const us={r:1,g:1,b:1,a:1},ds={begin(e){const t=ls();t.HEAPF32.set(e,ns/4),t.draw_begin(ns)},end(){ls().draw_end()},line(e,t,s,n=1){ls().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){ls().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){ls().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){ls().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){ls().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=us){ls().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=us){ls().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){ls().draw_setLayer(e)},setDepth(e){ls().draw_setDepth(e)},getDrawCallCount:()=>ss?ss.draw_getDrawCallCount():0,getPrimitiveCount:()=>ss?ss.draw_getPrimitiveCount():0,setBlendMode(e){ls().draw_setBlendMode(e)},setDepthTest(e){ls().draw_setDepthTest(e)},drawMesh(e,t,s){const n=ls();n.HEAPF32.set(s,rs/4),n.draw_mesh(e,t,rs)},drawMeshWithMaterial(e,t,s){const n=ls(),r=Pt.get(t);if(!r)return;if(ds.setBlendMode(r.blendMode),ds.setDepthTest(r.depthTest),0===r.uniforms.size)return void ds.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,rs/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=fs(t);if(!(n<0)){if(gt(s))os[i++]=10,os[i++]=n,os[i++]=s.slot??e++,os[i++]=s.textureId;else if("number"==typeof s)os[i++]=1,os[i++]=n,os[i++]=s;else if(Array.isArray(s)){os[i++]=s.length,os[i++]=n;for(let e=0;e<s.length;e++)os[i++]=s[e]}else"w"in s?(os[i++]=4,os[i++]=n,os[i++]=s.x,os[i++]=s.y,os[i++]=s.z,os[i++]=s.w):"z"in s?(os[i++]=3,os[i++]=n,os[i++]=s.x,os[i++]=s.y,os[i++]=s.z):(os[i++]=2,os[i++]=n,os[i++]=s.x,os[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(os.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),is/4),n.draw_meshWithUniforms(e,r.shader,rs,is,i)):n.draw_mesh(e,r.shader,rs)}},hs={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};function fs(e){return hs[e]??-1}var ps;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(ps||(ps={}));let _s=null,gs=0,ms=0,ys=0;function ws(e){_s=e,gs=_s._malloc(262144),ms=_s._malloc(65536),ys=_s._malloc(256)}function xs(){_s&&(gs&&_s._free(gs),ms&&_s._free(ms),ys&&_s._free(ys),gs=0,ms=0,ys=0),_s=null}function vs(){if(!_s)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return _s}const bs={create(e){const t=vs(),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,gs/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,ys,r).set(i),t.geometry_init(s,gs,n,ys,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,ms,n).set(e.indices),t.geometry_setIndices16(s,ms,n)}else{new Uint32Array(t.HEAPU8.buffer,ms,n).set(e.indices),t.geometry_setIndices32(s,ms,n)}}return s},updateVertices(e,t,s=0){const n=vs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,gs/4),n.geometry_updateVertices(e,gs,r,s)},release(e){e>0&&vs().geometry_release(e)},isValid:e=>!(!_s||e<=0)&&_s.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return bs.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.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 bs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.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 bs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.Float2}],indices:new Uint16Array(o)})}};let Ss=null;function Ps(e){Ss=e}function Cs(){Ss&&As.isInitialized()&&As.shutdown(),Ss=null}function Ts(){if(!Ss)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ss}const As={init:(e,t)=>Ts().postprocess_init(e,t),shutdown(){Ts().postprocess_shutdown()},resize(e,t){Ts().postprocess_resize(e,t)},addPass:(e,t)=>Ts().postprocess_addPass(e,t),removePass(e){Ts().postprocess_removePass(e)},setEnabled(e,t){Ts().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ts().postprocess_isPassEnabled(e),setUniform(e,t,s){Ts().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Ts().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Ts().postprocess_begin()},end(){Ts().postprocess_end()},getPassCount:()=>Ts().postprocess_getPassCount(),isInitialized:()=>!!Ss&&Ss.postprocess_isInitialized(),setBypass(e){Ts().postprocess_setBypass(e)},isBypassed:()=>!Ss||Ss.postprocess_isBypassed(),createBlur:()=>Pt.createShader(Es,"#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:()=>Pt.createShader(Es,"#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:()=>Pt.createShader(Es,"#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:()=>Pt.createShader(Es,"#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")},Es="#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 Ms;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ms||(Ms={}));let Rs=null,Is=0;function Fs(e){Rs=e,Is=Rs._malloc(64)}function ks(){Rs&&Is&&(Rs._free(Is),Is=0),Rs=null}const Bs={init(e,t){Rs?.renderer_init(e,t)},resize(e,t){Rs?.renderer_resize(e,t)},begin(e,t){Rs&&Is&&(Rs.HEAPF32.set(e,Is/4),Rs.renderer_begin(Is,t??0))},flush(){Rs?.renderer_flush()},end(){Rs?.renderer_end()},submitSprites(e){Rs&&Rs.renderer_submitSprites(e._cpp)},submitBitmapText(e){Rs&&Rs.renderer_submitBitmapText(e._cpp)},submitSpine(e){Rs&&Rs.renderer_submitSpine?.(e._cpp)},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 Us=null;function $s(e){Us=e}function Ds(){Us=null}const zs={enable(){Us?.gl_enableErrorCheck(!0)},disable(){Us?.gl_enableErrorCheck(!1)},check:e=>Us?.gl_checkErrors(e)??0,diagnose(){Us?.renderer_diagnose()}},Ws=new Map;function Os(e,t,s){Ws.set(e,{fn:t,scene:s??""})}function Ls(e){Ws.delete(e)}function Hs(){Ws.clear()}class js{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Bs.resize(n,r),As.isInitialized()&&As.getPassCount()>0&&As.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Bs.setViewport(0,0,n,r),Bs.clearBuffers(3),Bs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Bs.submitSprites(t),Bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Bs.submitSpine(t),Bs.flush(),this.executeDrawCallbacks(s,i),Bs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Bs.setViewport(n.x,n.y,n.w,n.h),Bs.setScissor(n.x,n.y,n.w,n.h,!0),Bs.clearBuffers(r),Bs.setScissor(0,0,0,0,!1),Bs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Bs.submitSprites(t),Bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Bs.submitSpine(t),Bs.flush(),this.executeDrawCallbacks(s,i),Bs.end()}executeDrawCallbacks(e,t){const s=Ws;if(s.size>0){ds.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)}ds.end();for(const e of n)Ls(e)}}}const Ns="__scene_transition_overlay__",Xs={r:0,g:0,b:0,a:1};class Vs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class qs{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,Re,{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),Os(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=As.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){As.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,Re)){const s=this.app_.world.get(e,Re);s.persistent=t,this.app_.world.insert(e,Re,s)}}}class Gs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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){"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??.3,r=t.color??Xs;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Os(Ns,()=>{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;ds.setLayer(9999),ds.setDepth(9999),ds.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)})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ls(Ns),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 Vs(t);this.scenes_.set(e,s);const n=new qs(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Nt)?this.app_.getResource(Nt):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(Nt)&&(t.assetServer=this.app_.getResource(Nt));const n=await Wt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Re,{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}async loadAdditive(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 Vs(t);this.scenes_.set(e,s);const n=new qs(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Nt)?this.app_.getResource(Nt):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(Nt)&&(t.assetServer=this.app_.getResource(Nt));const n=await Wt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Re,{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}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,Re)){if(this.app_.world.get(e,Re).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Ls(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{As.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,ve)){const s=this.app_.world.get(e,ve);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,ve,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,ve)){const s=this.app_.world.get(e,ve),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,ve,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{As.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=ze(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(Ys).getSceneStatus(t)&&s._fn(...n)}}}const Ks=Ze([Oe(Ys),We(je)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qs={name:"SceneManager",build(e){const t=new Gs(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)}};e.addSystemToSchedule(Ke.Startup,s),e.addSystemToSchedule(Ke.Last,Ks)}};class Zs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(Ke.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ke.FixedPreUpdate),this.runSchedule(Ke.FixedUpdate),this.runSchedule(Ke.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(Ke.PreUpdate),this.runSchedule(Ke.Update),this.runSchedule(Ke.PostUpdate),this.runSchedule(Ke.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ft,this.resources_=new He;for(const e of Object.values(Ke))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zs}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}addSystem(e){return this.addSystemToSchedule(Ke.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ke.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_}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}onError(e){return this.error_handler_=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 rt(this.world_,this.resources_),this.resources_.insert(je,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ke.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[Ds,ks,Cs,xs,bt,cs];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){let t=this.systems_.get(e);if(t&&this.runner_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(je);t.delta=e,t.elapsed+=e,t.frameCount++}}function en(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 tn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function sn(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case ye.FixedWidth:return i;case ye.FixedHeight:return o;case ye.Expand:return Math.max(i,o);case ye.Shrink:return Math.min(i,o);case ye.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function nn(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,Re);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 u,d=0,h=0;if(r.projectionType===ge.Orthographic){if(h=r.orthoSize,c){h=sn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}d=h*a,u=on(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=cn(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=un(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(hn(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const rn=new Float32Array(16);function on(e,t,s,n,r,i){const o=rn;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 an=new Float32Array(16);function cn(e,t,s,n){const r=an;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 ln=new Float32Array(16);function un(e,t,s){const n=ln;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 dn=new Float32Array(16);function hn(e,t){const s=dn;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 fn,pn,_n;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(fn||(fn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(pn||(pn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(_n||(_n={}));const gn=oe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:fn.Left,verticalAlign:pn.Top,wordWrap:!0,overflow:_n.Visible,lineHeight:1.2}),mn=oe("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 yn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(q,q),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),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(c)),h=Math.ceil(c.length*l),f=r?Math.ceil(i):d+2*u,p=r?Math.ceil(o):h+2*u;if(r&&e.overflow===_n.Ellipsis&&h>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),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===_n.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 pn.Top:x=u;break;case pn.Middle:x=(p-w)/2;break;case pn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case fn.Left:n=u;break;case fn.Center:n=f/2;break;case fn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===_n.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 fn.Left:return"left";case fn.Center:return"center";case fn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function wn(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 xn(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 vn{build(e){fe("Text",gn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new yn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,gn));for(const e of r.keys())n.valid(e)&&n.has(e,gn)||r.delete(e);const e=n.getEntitiesWithComponents([gn]);for(const t of e){const e=n.get(t,gn),i=n.has(t,mn)?n.get(t,mn):null,o=r.get(t);if(o&&!xn(o,e,i))continue;n.has(t,ve)||n.insert(t,ve,{texture:Y,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,ve);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,ve,c),r.set(t,wn(e,i))}}))}}const bn=new vn,Sn=oe("UIMask",{enabled:!0});function Pn(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 Cn(e,t,s,n,r,i,o,a,c,l,u){const d=e-s*r,h=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)*u]}const[g,m]=_(d,f),[y,w]=_(h,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function Tn(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],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=d*g-h*_,T=d*m-f*_,A=d*y-p*_,E=h*m-f*g,M=h*y-p*g,R=f*y-p*m;let I=w*R-x*M+v*E+b*A-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*M+u*E)*I,s[1]=(i*M-r*R-o*E)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(l*A-a*R-u*T)*I,s[5]=(n*R-i*A+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(d*P-f*v+p*x)*I,s[8]=(a*M-c*A+u*C)*I,s[9]=(r*A-n*M-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(h*v-d*S-p*w)*I,s[12]=(c*T-a*E-l*C)*I,s[13]=(n*E-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(d*b-h*x+f*w)*I),s}function An(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],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 En(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 Mn(e,t,s,n,r,i,o){if(!e.has(t,mn)||!e.has(t,xe))return null;const a=e.get(t,mn),c=e.get(t,xe),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Cn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Rn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Sn]);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,Sn).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,Ce);){const e=t.get(n,Ce);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=Mn(t,s,r,i,o,a,c);e&&(n=Pn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Mn(t,e,r,i,o,a,c);s&&d(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class In{build(e){if(fe("UIMask",Sn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Rn(e.wasmModule,e.world))}}const Fn=new In,kn=oe("Interactable",{enabled:!0}),Bn=oe("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Un;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Un||(Un={}));const $n=oe("Button",{state:Un.Normal,transition:null});class Dn{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 zn=ze(new Dn,"UIEvents"),Wn=ae("ScreenSpace");function On(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,u=i.bottom+e.y*a,d=i.bottom+t.y*a;let h,f,p,_;if(c===l&&u===d){const e=c+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;h=e-n,f=t-i,p=e+n,_=t+i}else h=c+s.x,f=u+s.y,p=l+n.x,_=d+n.y;return{centerX:.5*(h+p),centerY:.5*(f+_),width:p-h,height:_-f,rect:{left:h,bottom:f,right:p,top:_}}}function Ln(e,t,s,n,r,i){if(!e.has(t,mn))return;const o=e.get(t,mn),a=On(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,we);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,we,c),!e.has(t,Te))return;const l=e.get(t,Te);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Ln(e,t,a.rect,a.centerX,a.centerY,!1)}class Hn{build(e){fe("UIRect",mn);const t=e.world;e.addSystemToSchedule(Ke.PreUpdate,Ze([We(pt)],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([Wn,mn,we]);for(const e of i)Ln(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const jn=new Hn,Nn=new Float32Array(16),Xn=new Float32Array(16);let Vn=!0,qn=1;class Gn{build(e){fe("Interactable",kn),fe("Button",$n);const t=e.world,s=new Dn;e.insertResource(zn,s);let n=null,r=null;qn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ke.PreUpdate,Ze([We(ot),We(pt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Bn]);for(const e of o){const s=t.get(e,Bn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*qn,c=i.screenH-e.mouseY*qn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Xn[s]!==e[s]){t=!0;break}t&&(Xn.set(e),Vn=!0)}(i.viewProjection),Vn&&(Tn(i.viewProjection,Nn),Vn=!1);const l=An(a,c,Nn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([kn,mn,xe]);let d=null,h=-1/0;for(const e of u){t.has(e,Bn)||t.insert(e,Bn);if(!t.get(e,kn).enabled)continue;const s=t.get(e,xe),n=t.get(e,mn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(En(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,ve)&&(s=t.get(e,ve).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,Bn)){t.get(n,Bn).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Bn).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Bn);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,Bn)){const e=t.get(r,Bn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ke.Update,Ze([],()=>{const e=t.getEntitiesWithComponents([$n]);for(const s of e){if(t.has(s,kn)||t.insert(s,kn,{enabled:!0}),!t.has(s,Bn))continue;const e=t.get(s,Bn),n=t.get(s,$n),r=t.get(s,kn),i=n.state;if(r.enabled?e.pressed?n.state=Un.Pressed:e.hovered?n.state=Un.Hovered:n.state=Un.Normal:n.state=Un.Disabled,i!==n.state&&n.transition&&t.has(s,ve)){const e=t.get(s,ve),r=n.transition;switch(n.state){case Un.Normal:e.color={...r.normalColor};break;case Un.Hovered:e.color={...r.hoveredColor};break;case Un.Pressed:e.color={...r.pressedColor};break;case Un.Disabled:e.color={...r.disabledColor}}t.insert(s,ve,e)}}},{name:"ButtonSystem"}))}}const Yn=new Gn,Jn=oe("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 Kn{build(e){fe("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=d(q,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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 f=h;function p(){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(zn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,m()}function _(e){if(o===e)return;g();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(),m())}function g(){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 m(){c=!0,l=0}function y(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Zn(Math.max(r.width,a)),r.height=Zn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 d=0===o.value.length,h=d?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=d?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=Qn(i,h,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(h,_,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=Qn(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 g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,ve);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,ve,b)}f.addEventListener("input",()=>{a||null===o||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===o)return;if("Escape"===t.key)return void g();const n=s.get(o,Jn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(zn).emit(o,"submit"),void g()}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,m())}),f.addEventListener("blur",()=>{if(null!==o&&s.valid(o)&&s.has(o,Jn)){const e=s.get(o,Jn);e.focused=!1,e.dirty=!0}o=null}),e.addSystemToSchedule(Ke.PreUpdate,Ze([We(zn)],e=>{const t=s.getEntitiesWithComponents([Jn,kn]);for(const e of t){if(!s.has(e,Bn))continue;if(s.get(e,Bn).justPressed)return void _(e)}if(null!==o){const e=s.getEntitiesWithComponents([kn]);for(const t of e){if(s.has(t,Jn))continue;if(!s.has(t,Bn))continue;if(s.get(t,Bn).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=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,mn]);for(const e of a){const t=s.get(e,Jn);if(!t.dirty)continue;const n=s.get(e,mn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,ve)||s.insert(e,ve,{texture:Y,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}),y(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Qn(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 Zn(e){let t=1;for(;t<e;)t*=2;return t}const er=new Kn;async function tr(e,t,s){const n=e.getResource(Ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function sr(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 nr=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),rr=ze(null,"PhysicsAPI");function ir(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function or(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ar{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(nr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=sr(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([Se]);for(const s of t){const t=e.world.get(s,Se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ke.PostUpdate,Ze([We(je)],a=>{const c=o.getEntitiesWithComponents([Fe,we,xe]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,Fe),c=o.get(r,xe);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=ir(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),cr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===$e.Kinematic){const e=ir(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 u=e.world.get(o,we);if(!u)continue;let d=a,h=c,f=l;if(e.world.has(o,Ce)){const t=e.world.get(o,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,xe)){const s=e.world.get(t.entity,xe),n=ir(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);d=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=d,u.position.y=h;const p=or(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,we,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 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=[],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(nr,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(rr,lr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function cr(e,t,s){const n=e.world;if(n.has(s,ke)){const e=n.get(s,ke);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,Be)){const e=n.get(s,Be);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,Ue)){const e=n.get(s,Ue);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 lr{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(lr.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 ur(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 dr(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 hr(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,u=e.rotation.w,d=a+a,h=c+c,f=l+l,p=a*d,_=a*h,g=a*f,m=c*h,y=c*f,w=l*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function fr(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]=ur(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 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),u="binary"===x(c)?.contentType;let d,h;if(u){const e=await r.readBinary(o);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const f=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),f<0)continue;i[o]=f;const p=dr(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=ur(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,d,s,n)),i){new ar("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).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,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),u=ur(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),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=Pt.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Pt.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n),p=zt(e.world,s);if(c&&e.hasResource(Ys))for(const t of p.values())e.world.insert(t,Re,{scene:c,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,ve);r&&(r.texture=s[n.data.texture]||0,e.insert(t,ve,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const i=e.get(t,Ae);i&&(i.font=r,e.insert(t,Ae,i))}}}(e.world,s,h,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,ve);s&&(s.material=r,e.insert(t,ve,s))}else if("SpineAnimation"===n.type){const s=e.get(t,Ee);s&&(s.material=r,e.insert(t,Ee,s))}}}}(e.world,s,f,p),r&&d){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}(d,s,u,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,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(o,c*d);let h=0;if(l.has(i,xe)){const e=hr(l.get(i,xe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>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),u=s._malloc(c),d=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,d,f);const p=s.HEAPU32[d>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,h),t._free(y),t._free(w),s._free(l),s._free(u),s._free(d),s._free(f)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(Nt);t&&t.setAddressableManifest(a)}}function pr(e,t,s){return{name:e,data:t,async setup(){await fr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class _r{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 gr="__preview__";class mr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Ys);t.register({name:gr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(gr),this.loadPromise_=t.load(gr).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 _r(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await fr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,gr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([be]);for(const n of s){if(e.get(n,be).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([Se]);for(const r of n){const n=e.get(r,Se);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(gr),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,we,o);const a={isActive:!0,projectionType:ge.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:me.ColorAndDepth};e.insert(i,be,a)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Ys);await e.switchTo(gr),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 yr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Bs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Bs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Bs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Bs.releaseRenderTarget(e._handle),yr.create({width:t,height:s,depth:!0})),begin(e,t){Bs.begin(t,e._handle)},end(){Bs.end()},getDepthTexture:e=>Bs.getTargetDepthTexture(e._handle)};let wr=!1;function xr(e){wr=e}function vr(){return wr}function br(){return!wr}var Sr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Sr||(Sr={}));class Pr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Sr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Sr.Debug:console.debug(t,s);break;case Sr.Info:console.log(t,s);break;case Sr.Warn:console.warn(t,s);break;case Sr.Error:console.error(t,s)}}}class Cr{constructor(){this.handlers_=[],this.minLevel_=Sr.Info,this.addHandler(new Pr)}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(Sr.Debug,e,t,s)}info(e,t,s){this.log(Sr.Info,e,t,s)}warn(e,t,s){this.log(Sr.Warn,e,t,s)}error(e,t,s){this.log(Sr.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 Tr=new Cr;function Ar(){return Tr}function Er(e){Tr.setMinLevel(e)}function Mr(e,t,s){Tr.debug(e,t,s)}function Rr(e,t,s){Tr.info(e,t,s)}function Ir(e,t,s){Tr.warn(e,t,s)}function Fr(e,t,s){Tr.error(e,t,s)}const kr=[bn,Fn,jn,Yn,er];function Br(e,t){return function(e,t){const s=Zs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),as(e),vt(e),ws(e),Ps(e),Fs(e),$s(e);const r=new js;s.pipeline_=r;let i=h();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=nn(e,n,t,r));const o=s.getResource(pt);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(pt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,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;Bs.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-i)/1e3;let d;if(Bs.resize(t,c),As.isInitialized()&&As.getPassCount()>0&&!As.isBypassed()&&As.resize(t,c),s.hasResource(Ys)){const e=s.getResource(Ys).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=nn(e,n,t,c,s.world,d);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:tn,width:t,height:c,elapsed:u});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:u})}Bs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ke.First,c),s.addSystemToSchedule(Ke.Last,l),s.addPlugin(Vt),s.addPlugin(ts),s.addPlugin(ct),s.addPlugin(Qs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:kr,...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{Zs as App,Xt as AssetPlugin,qt as AssetRefCounter,jt as AssetServer,Nt as Assets,kt as AsyncCache,Ae as BitmapText,_t as BlendMode,$e as BodyType,ke as BoxCollider,$n as Button,Un as ButtonState,be as Camera,Se as Canvas,Ue as CapsuleCollider,Te as Children,Be as CircleCollider,me as ClearFlags,Ge as Commands,Je as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,ps as DataType,ds as Draw,Ye as EntityCommands,zs as GLDebug,bs as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,at as InputPlugin,it as InputState,kn as Interactable,we as LocalTransform,Sr as LogLevel,Cr as Logger,Pt as Material,Bt as MaterialLoader,Ne as Mut,Me as Name,Ce as Parent,lr as Physics,nr as PhysicsEvents,ar as PhysicsPlugin,As as PostProcess,Qt as PrefabServer,Zt as Prefabs,es as PrefabsPlugin,mr as PreviewPlugin,ge as ProjectionType,Ve as Query,qe as QueryInstance,js as RenderPipeline,Ms as RenderStage,yr as RenderTexture,Bs as Renderer,We as Res,Oe as ResMut,Fe as RigidBody,ye as ScaleMode,Ys as SceneManager,Gs as SceneManagerState,Re as SceneOwner,Ke as Schedule,Wn as ScreenSpace,Ft as ShaderSources,Ee as SpineAnimation,ve as Sprite,rt as SystemRunner,gn as Text,fn as TextAlign,Jn as TextInput,Kn as TextInputPlugin,_n as TextOverflow,vn as TextPlugin,yn as TextRenderer,pn as TextVerticalAlign,je as Time,pt as UICameraInfo,Dn as UIEventQueue,zn as UIEvents,Bn as UIInteraction,Gn as UIInteractionPlugin,Hn as UILayoutPlugin,Sn as UIMask,In as UIMaskPlugin,mn as UIRect,Pe as Velocity,_r as WebAssetProvider,ft as World,xe as WorldTransform,st as addStartupSystem,tt as addSystem,nt as addSystemToSchedule,Vt as assetPlugin,Hs as clearDrawCallbacks,le as clearUserComponents,ee as color,On as computeUIRectLayout,Rn as createMaskProcessor,pr as createRuntimeSceneConfig,Br as createWebApp,Mr as debug,oe as defineComponent,ze as defineResource,Ze as defineSystem,ae as defineTag,Fr as error,Ht as findEntityByName,en as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,M as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,Dt as getComponentAssetFields,Ie as getComponentDefaults,A as getCustomExtensions,v as getEditorType,Ar as getLogger,t as getPlatform,n as getPlatformType,ce as getUserComponent,E as getWeChatPackOptions,Rr as info,as as initDrawAPI,$s as initGLDebugAPI,ws as initGeometryAPI,vt as initMaterialAPI,Ps as initPostProcessAPI,Fs as initRendererAPI,ct as inputPlugin,Yt as instantiatePrefab,Pn as intersectRects,Tn as invertMatrix4,de as isBuiltinComponent,R as isCustomExtension,vr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,br as isRuntime,gt as isTextureRef,r as isWeChat,i as isWeb,Ot as loadComponent,sr as loadPhysicsModule,fr as loadRuntimeScene,zt as loadSceneData,Wt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,En as pointInWorldRect,ts as prefabsPlugin,te as quat,fe as registerComponent,$t as registerComponentAssetFields,Os as registerDrawCallback,Gt as registerEmbeddedAssets,It as registerMaterialCallback,Qs as sceneManagerPlugin,An as screenToWorld,xr as setEditorMode,Er as setLogLevel,cs as shutdownDrawAPI,Ds as shutdownGLDebugAPI,xs as shutdownGeometryAPI,bt as shutdownMaterialAPI,Cs as shutdownPostProcessAPI,ks as shutdownRendererAPI,er as textInputPlugin,bn as textPlugin,tr as transitionTo,Yn as uiInteractionPlugin,jn as uiLayoutPlugin,Fn as uiMaskPlugin,kr as uiPlugins,Ls as unregisterDrawCallback,Lt as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,Ir as warn,Cn as worldRectToScreen,Js as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,L as wxLoadImagePixels,B as wxReadFile,U 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 u(e,s){return t().instantiateWasm(e,s)}function h(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}],g={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"},m=new Map,y=new Set;for(const e of _)for(const t of e.extensions)m.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 m.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 g[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 k(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 B(e){return new Promise((t,s)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function U(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(k(e,t.errMsg)))}})})}function $(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 L(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 O(e){return L(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 B(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return 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=0,Y=4294967295,J=4294967295,K=(e=0,t=0)=>({x:e,y:t}),Q=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),Z=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),ee=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),te=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function se(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(se);const t={};for(const s in e)t[s]=se(e[s]);return t}let ne=0;function re(e,t){const s=++ne;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...se(t),...e}:se(t)}}function ie(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function oe(e,t){const s=ie(),n=s.get(e);if(n)return n;const r=re(e,t);return s.set(e,r),ue(e,t,!1),r}function ae(e){const t=ie(),s=t.get(e);if(s)return s;const n=re(e,{});return t.set(e,n),ue(e,{},!0),n}function ce(e){return ie().get(e)}function le(){ie().clear()}function ue(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function he(e){return!0===e._builtin}const de=new Map;function fe(e,t){de.set(e,t)}function pe(e){return de.get(e)??ce(e)}function _e(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return de.set(e,s),s}const ge={Perspective:0,Orthographic:1},me={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ye={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},we=_e("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),xe=_e("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ve=_e("Sprite",{texture:Y,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}),be=_e("Camera",{projectionType:ge.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:me.ColorAndDepth}),Se=_e("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:ye.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Pe=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Te=_e("Children",{entities:[]}),Ee=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Me=_e("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}),Ae={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Re=oe("SceneOwner",{scene:"",persistent:!1});function Ie(e){const t=pe(e);return t?se(t._default):null}fe("Name",Ae);const Fe=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ke=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Be=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$e={Static:0,Kinematic:1,Dynamic:2};let De=0;function ze(e,t){const s=++De;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function We(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class Oe{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 He{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 Oe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const je=ze({delta:0,elapsed:0,frameCount:0},"Time");function Ne(e){return{_type:"mut",_component:e}}function Xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ve(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{Xe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class qe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Xe(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 u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)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}}function Ge(){return{_type:"commands"}}class Ye{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=he(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 Je{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ye(this,null);return this.spawned_.push(e),e}entity(e){return new Ye(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 Ke;!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"}(Ke||(Ke={}));let Qe=0;function Ze(e,t,s){const n=++Qe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function et(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function tt(e){et().push({schedule:Ke.Update,system:e})}function st(e){et().push({schedule:Ke.Startup,system:e})}function nt(e,t){et().push({schedule:e,system:t})}class rt{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 Je&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new qe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Je(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class it{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 ot=ze(new it,"Input");class at{constructor(e){this.target_=e??null}build(e){const s=new it;e.insertResource(ot,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(Ke.Last,Ze([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ct=new at;function lt(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=ut(t[e]),i=ut(r);s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r})}return n}function ut(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ht(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")}function dt(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}:dt(e)}}return t}class ft{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return he(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return he(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return he(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(he(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");he(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=lt(t._name,t._default,n);if(e.length>0)throw new Error(ht(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,dt(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=lt(t._name,t._default,e);if(r.length>0)throw new Error(ht(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(!he(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 pt=ze({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var _t;function gt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(_t||(_t={}));let mt=null,yt=null,wt=1;const xt=new Map;function vt(e){mt=e,yt=e.getResourceManager(),It()}function bt(){0!==Tt&&mt&&(mt._free(Tt),Tt=0),xt.clear(),wt=1,Ct=!1,Mt.clear(),At=null,yt=null,mt=null}function St(){if(!yt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return yt}const Pt={createShader:(e,t)=>St().createShader(e,t),releaseShader(e){e>0&&St().releaseShader(e)},create(e){const t=wt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??_t.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return xt.set(t,s),t},get:e=>xt.get(e),setUniform(e,t,s){const n=xt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=xt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=xt.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=xt.get(e);return t?.blendMode??_t.Normal},setDepthTest(e,t){const s=xt.get(e);s&&(s.depthTest=t)},getShader(e){const t=xt.get(e);return t?.shader??0},release(e){xt.delete(e)},isValid:e=>xt.has(e),releaseAll(){xt.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??_t.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=xt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=wt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return xt.set(s,n),s},toAssetData(e,t){const s=xt.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=xt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ct=!1,Tt=0;const Et=4096,Mt=new Map;let At=null;function Rt(e){const t=(0===Tt&&mt&&(Tt=mt._malloc(Et)),Tt);if(0===t||!mt)return{ptr:0,count:0};let s=0,n=0;const r=mt.HEAPU8,i=mt.HEAPU32,o=mt.HEAPF32;for(const[a,c]of e){if(s+128>Et)break;let e=Mt.get(a);e||(At||(At=new TextEncoder),e=At.encode(a),Mt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=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?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function It(){if(!mt||Ct)return;mt.materialDataProvider=(e,t,s,n,r)=>{const i=xt.get(e);if(!i)return mt.HEAPU32[t>>2]=0,mt.HEAPU32[s>>2]=0,mt.HEAPU32[n>>2]=0,void(mt.HEAPU32[r>>2]=0);mt.HEAPU32[t>>2]=i.shader,mt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Rt(i.uniforms);mt.HEAPU32[n>>2]=o,mt.HEAPU32[r>>2]=a},Ct=!0}const Ft={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 kt{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 Bt{constructor(e,t=""){this.cache_=new kt,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&&(Pt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pt.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:Pt.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 Ut=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 $t(e,t){Ut.set(e,t)}function Dt(e){const t=Ut.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 zt(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,Ae,{value:n.name}),!1!==n.visible)for(const s of n.components)Lt(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 Wt(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=Ut.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,u=new Map,h=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);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.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=Ut.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]=h.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,Ae,{value:s.name}),!1!==s.visible)for(const n of s.components)Lt(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 Lt(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=pe(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 Ot(e,t){const s=e.getEntitiesWithComponents([be]);for(const n of s){const s=e.get(n,be);s&&(s.aspectRatio=t,e.insert(n,be,s))}}function Ht(e,t){const s=e.getEntitiesWithComponents([Ae]);for(const n of s){const s=e.get(n,Ae);if(s&&s.value===t)return n}return null}class jt{constructor(e){this.textureCache_=new kt,this.shaderCache_=new kt,this.jsonCache_=new kt,this.textCache_=new kt,this.binaryCache_=new kt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new kt,this.prefabCache_=new kt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(q,q),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Bt(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(),Pt.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),u="binary"===x(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,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=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 Wt(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 Pt.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 Pt.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 Nt=ze(null,"Assets");class Xt{build(e){const t=e.wasmModule;t?e.insertResource(Nt,new jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Vt=new Xt;class qt{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 Gt(e,t){const s=e.getResource(Nt);s&&s.registerEmbeddedAssets(t)}async function Yt(e,t,s){const{entities:n,rootId:r}=await Kt(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 Wt(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 Jt=10;async function Kt(e,t,s,n,r,i=0){if(i>Jt)throw new Error(`Prefab nesting depth exceeded ${Jt}. 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 Kt(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),u=n.prefabEntityId===e.rootEntityId,h={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};Qt(h,t),c.push(h)}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 Qt(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 Zt{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 Yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const es=ze(null,"Prefabs");class ts{constructor(){this.name="PrefabsPlugin",this.dependencies=[Nt]}build(e){const t=e.getResource(Nt);e.insertResource(es,new Zt(e.world,t))}}const ss=new ts;let ns=null,rs=0,is=0,os=0;const as=new Float32Array(256);function cs(e){ns=e,rs=ns._malloc(64),is=ns._malloc(64),os=ns._malloc(1024)}function ls(){ns&&(rs&&(ns._free(rs),rs=0),is&&(ns._free(is),is=0),os&&(ns._free(os),os=0)),ns=null}function us(){if(!ns)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ns}const hs={r:1,g:1,b:1,a:1},ds={begin(e){const t=us();t.HEAPF32.set(e,rs/4),t.draw_begin(rs)},end(){us().draw_end()},line(e,t,s,n=1){us().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){us().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){us().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){us().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){us().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=hs){us().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=hs){us().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){us().draw_setLayer(e)},setDepth(e){us().draw_setDepth(e)},getDrawCallCount:()=>ns?ns.draw_getDrawCallCount():0,getPrimitiveCount:()=>ns?ns.draw_getPrimitiveCount():0,setBlendMode(e){us().draw_setBlendMode(e)},setDepthTest(e){us().draw_setDepthTest(e)},drawMesh(e,t,s){const n=us();n.HEAPF32.set(s,is/4),n.draw_mesh(e,t,is)},drawMeshWithMaterial(e,t,s){const n=us(),r=Pt.get(t);if(!r)return;if(ds.setBlendMode(r.blendMode),ds.setDepthTest(r.depthTest),0===r.uniforms.size)return void ds.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,is/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=ps(t);if(!(n<0)){if(gt(s))as[i++]=10,as[i++]=n,as[i++]=s.slot??e++,as[i++]=s.textureId;else if("number"==typeof s)as[i++]=1,as[i++]=n,as[i++]=s;else if(Array.isArray(s)){as[i++]=s.length,as[i++]=n;for(let e=0;e<s.length;e++)as[i++]=s[e]}else"w"in s?(as[i++]=4,as[i++]=n,as[i++]=s.x,as[i++]=s.y,as[i++]=s.z,as[i++]=s.w):"z"in s?(as[i++]=3,as[i++]=n,as[i++]=s.x,as[i++]=s.y,as[i++]=s.z):(as[i++]=2,as[i++]=n,as[i++]=s.x,as[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(as.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),os/4),n.draw_meshWithUniforms(e,r.shader,is,os,i)):n.draw_mesh(e,r.shader,is)}},fs={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};function ps(e){return fs[e]??-1}const _s=new Map;function gs(e,t,s){_s.set(e,{fn:t,scene:s??""})}function ms(e){_s.delete(e)}function ys(){_s.clear()}var ws;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(ws||(ws={}));let xs=null,vs=0,bs=0,Ss=0;function Ps(e){xs=e,vs=xs._malloc(262144),bs=xs._malloc(65536),Ss=xs._malloc(256)}function Cs(){xs&&(vs&&xs._free(vs),bs&&xs._free(bs),Ss&&xs._free(Ss),vs=0,bs=0,Ss=0),xs=null}function Ts(){if(!xs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return xs}const Es={create(e){const t=Ts(),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,vs/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,Ss,r).set(i),t.geometry_init(s,vs,n,Ss,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,bs,n).set(e.indices),t.geometry_setIndices16(s,bs,n)}else{new Uint32Array(t.HEAPU8.buffer,bs,n).set(e.indices),t.geometry_setIndices32(s,bs,n)}}return s},updateVertices(e,t,s=0){const n=Ts(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,vs/4),n.geometry_updateVertices(e,vs,r,s)},release(e){e>0&&Ts().geometry_release(e)},isValid:e=>!(!xs||e<=0)&&xs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Es.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:ws.Float2},{name:"a_texCoord",type:ws.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 Es.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ws.Float2},{name:"a_texCoord",type:ws.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 Es.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ws.Float2},{name:"a_texCoord",type:ws.Float2}],indices:new Uint16Array(o)})}};let Ms=null;function As(e){Ms=e}function Rs(){Ms&&Fs.isInitialized()&&Fs.shutdown(),Ms=null}function Is(){if(!Ms)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ms}const Fs={init:(e,t)=>Is().postprocess_init(e,t),shutdown(){Is().postprocess_shutdown()},resize(e,t){Is().postprocess_resize(e,t)},addPass:(e,t)=>Is().postprocess_addPass(e,t),removePass(e){Is().postprocess_removePass(e)},setEnabled(e,t){Is().postprocess_setPassEnabled(e,t)},isEnabled:e=>Is().postprocess_isPassEnabled(e),setUniform(e,t,s){Is().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Is().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Is().postprocess_begin()},end(){Is().postprocess_end()},getPassCount:()=>Is().postprocess_getPassCount(),isInitialized:()=>!!Ms&&Ms.postprocess_isInitialized(),setBypass(e){Is().postprocess_setBypass(e)},isBypassed:()=>!Ms||Ms.postprocess_isBypassed(),createBlur:()=>Pt.createShader(ks,"#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:()=>Pt.createShader(ks,"#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:()=>Pt.createShader(ks,"#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:()=>Pt.createShader(ks,"#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")},ks="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Bs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bs||(Bs={}));let Us=null,$s=0;function Ds(e){Us=e,$s=Us._malloc(64)}function zs(){Us&&$s&&(Us._free($s),$s=0),Us=null}const Ws={init(e,t){Us?.renderer_init(e,t)},resize(e,t){Us?.renderer_resize(e,t)},begin(e,t){Us&&$s&&(Us.HEAPF32.set(e,$s/4),Us.renderer_begin($s,t??0))},flush(){Us?.renderer_flush()},end(){Us?.renderer_end()},submitSprites(e){Us&&Us.renderer_submitSprites(e._cpp)},submitBitmapText(e){Us&&Us.renderer_submitBitmapText(e._cpp)},submitSpine(e){Us&&Us.renderer_submitSpine?.(e._cpp)},setStage(e){Us?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Us?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Us?.renderer_releaseTarget(e)},getTargetTexture:e=>Us?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Us?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Us?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Us?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Us?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Us?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Us?Us.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Us?{drawCalls:Us.renderer_getDrawCalls(),triangles:Us.renderer_getTriangles(),sprites:Us.renderer_getSprites(),text:Us.renderer_getText(),spine:Us.renderer_getSpine?.()??0,meshes:Us.renderer_getMeshes(),culled:Us.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ls=null;function Os(e){Ls=e}function Hs(){Ls=null}const js={enable(){Ls?.gl_enableErrorCheck(!0)},disable(){Ls?.gl_enableErrorCheck(!1)},check:e=>Ls?.gl_checkErrors(e)??0,diagnose(){Ls?.renderer_diagnose()}};class Ns{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_||(Ws.resize(n,r),Fs.isInitialized()&&Fs.getPassCount()>0&&Fs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ws.setViewport(0,0,n,r),Ws.clearBuffers(3),Ws.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ws.submitSprites(t),Ws.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ws.submitSpine(t),Ws.flush(),this.executeDrawCallbacks(s,i),Ws.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Ws.setViewport(n.x,n.y,n.w,n.h),Ws.setScissor(n.x,n.y,n.w,n.h,!0),Ws.clearBuffers(r),Ws.setScissor(0,0,0,0,!1),Ws.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ws.submitSprites(t),Ws.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ws.submitSpine(t),Ws.flush(),this.executeDrawCallbacks(s,i),Ws.end()}executeDrawCallbacks(e,t){const s=_s;if(s.size>0){ds.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)}ds.end();for(const e of n)ms(e)}}}const Xs="__scene_transition_overlay__",Vs={r:0,g:0,b:0,a:1};class qs{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,Re,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),gs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Fs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Fs.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,Re)){const s=this.app_.world.get(e,Re);s.persistent=t,this.app_.world.insert(e,Re,s)}}}class Ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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??.3,r=t.color??Vs;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},gs(Xs,()=>{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;ds.setLayer(9999),ds.setDepth(9999),ds.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,ms(Xs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ms(Xs),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 qs(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(Nt)?this.app_.getResource(Nt):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(Nt)&&(t.assetServer=this.app_.getResource(Nt));const n=await Wt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Re,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ks(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 qs(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(Nt)?this.app_.getResource(Nt):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(Nt)&&(t.assetServer=this.app_.getResource(Nt));const n=await Wt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Re,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ks(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,Re)){if(this.app_.world.get(e,Re).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())ms(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Fs.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,ve)){const s=this.app_.world.get(e,ve);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,ve,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,ve)){const s=this.app_.world.get(e,ve),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,ve,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Fs.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 Js=ze(null,"SceneManager");function Ks(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Js).getSceneStatus(t)&&s._fn(...n)}}}const Qs=Ze([Le(Js),We(je)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Zs={name:"SceneManager",build(e){const t=new Ys(e);e.insertResource(Js,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Js),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ke.Startup,s),e.addSystemToSchedule(Ke.Last,Qs)}};class en{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,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,.25);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Ke.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ke.FixedPreUpdate),this.runSchedule(Ke.FixedUpdate),this.runSchedule(Ke.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(Ke.PreUpdate),this.runSchedule(Ke.Update),this.runSchedule(Ke.PostUpdate),this.runSchedule(Ke.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ft,this.resources_=new He;for(const e of Object.values(Ke))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new en}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}addSystem(e){return this.addSystemToSchedule(Ke.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ke.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_}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}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=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(Js).register(e),this}setInitialScene(e){return this.getResource(Js).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new rt(this.world_,this.resources_),this.resources_.insert(je,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ke.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,ys();const e=[Hs,zs,Rs,Cs,bt,ls];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}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){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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(je);t.delta=e,t.elapsed+=e,t.frameCount++}}function tn(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 sn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function nn(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case ye.FixedWidth:return i;case ye.FixedHeight:return o;case ye.Expand:return Math.max(i,o);case ye.Shrink:return Math.min(i,o);case ye.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function rn(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,Re);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 u,h=0,d=0;if(r.projectionType===ge.Orthographic){if(d=r.orthoSize,c){d=nn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=an(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=ln(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=hn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(fn(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const on=new Float32Array(16);function an(e,t,s,n,r,i){const o=on;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 cn=new Float32Array(16);function ln(e,t,s,n){const r=cn;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 un=new Float32Array(16);function hn(e,t,s){const n=un;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 dn=new Float32Array(16);function fn(e,t){const s=dn;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 pn,_n,gn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(pn||(pn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(_n||(_n={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(gn||(gn={}));const mn=oe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:pn.Left,verticalAlign:_n.Top,wordWrap:!0,overflow:gn.Visible,lineHeight:1.2}),yn=oe("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 wn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(q,q),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),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===gn.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),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===gn.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 _n.Top:x=u;break;case _n.Middle:x=(p-w)/2;break;case _n.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case pn.Left:n=u;break;case pn.Center:n=f/2;break;case pn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===gn.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 pn.Left:return"left";case pn.Center:return"center";case pn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function xn(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 vn(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 bn{build(e){fe("Text",mn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new wn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,mn));for(const e of r.keys())n.valid(e)&&n.has(e,mn)||r.delete(e);const e=n.getEntitiesWithComponents([mn]);for(const t of e){const e=n.get(t,mn),i=n.has(t,yn)?n.get(t,yn):null,o=r.get(t);if(o&&!vn(o,e,i))continue;n.has(t,ve)||n.insert(t,ve,{texture:Y,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,ve);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,ve,c),r.set(t,xn(e,i))}}))}}const Sn=new bn,Pn=oe("UIMask",{enabled:!0});function Cn(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 Tn(e,t,s,n,r,i,o,a,c,l,u){const h=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)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function En(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],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;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+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function Mn(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],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function An(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 Rn(e,t,s,n,r,i,o){if(!e.has(t,yn)||!e.has(t,xe))return null;const a=e.get(t,yn),c=e.get(t,xe),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Tn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function In(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Pn]);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,Pn).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,Ce);){const e=t.get(n,Ce);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=Rn(t,s,r,i,o,a,c);e&&(n=Cn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=Rn(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Fn{build(e){if(fe("UIMask",Pn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(In(e.wasmModule,e.world))}}const kn=new Fn,Bn=oe("Interactable",{enabled:!0}),Un=oe("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var $n;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}($n||($n={}));const Dn=oe("Button",{state:$n.Normal,transition:null});class zn{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 Wn=ze(new zn,"UIEvents"),Ln=ae("ScreenSpace");function On(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,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+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=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Hn(e,t,s,n,r,i){if(!e.has(t,yn))return;const o=e.get(t,yn),a=On(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,we);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,we,c),!e.has(t,Te))return;const l=e.get(t,Te);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Hn(e,t,a.rect,a.centerX,a.centerY,!1)}class jn{build(e){fe("UIRect",yn);const t=e.world;e.addSystemToSchedule(Ke.PreUpdate,Ze([We(pt)],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([Ln,yn,we]);for(const e of i)Hn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Nn=new jn,Xn=new Float32Array(16),Vn=new Float32Array(16);let qn=!0,Gn=1;class Yn{build(e){fe("Interactable",Bn),fe("Button",Dn);const t=e.world,s=new zn;e.insertResource(Wn,s);let n=null,r=null;Gn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ke.PreUpdate,Ze([We(ot),We(pt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Un]);for(const e of o){const s=t.get(e,Un);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Gn,c=i.screenH-e.mouseY*Gn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Vn[s]!==e[s]){t=!0;break}t&&(Vn.set(e),qn=!0)}(i.viewProjection),qn&&(En(i.viewProjection,Xn),qn=!1);const l=Mn(a,c,Xn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([Bn,yn,xe]);let h=null,d=-1/0;for(const e of u){t.has(e,Un)||t.insert(e,Un);if(!t.get(e,Bn).enabled)continue;const s=t.get(e,xe),n=t.get(e,yn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(An(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,ve)&&(s=t.get(e,ve).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,Un)){t.get(n,Un).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,Un).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Un);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Un)){const e=t.get(r,Un);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ke.Update,Ze([],()=>{const e=t.getEntitiesWithComponents([Dn]);for(const s of e){if(t.has(s,Bn)||t.insert(s,Bn,{enabled:!0}),!t.has(s,Un))continue;const e=t.get(s,Un),n=t.get(s,Dn),r=t.get(s,Bn),i=n.state;if(r.enabled?e.pressed?n.state=$n.Pressed:e.hovered?n.state=$n.Hovered:n.state=$n.Normal:n.state=$n.Disabled,i!==n.state&&n.transition&&t.has(s,ve)){const e=t.get(s,ve),r=n.transition;switch(n.state){case $n.Normal:e.color={...r.normalColor};break;case $n.Hovered:e.color={...r.hoveredColor};break;case $n.Pressed:e.color={...r.pressedColor};break;case $n.Disabled:e.color={...r.disabledColor}}t.insert(s,ve,e)}}},{name:"ButtonSystem"}))}}const Jn=new Yn,Kn=oe("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 Qn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){fe("TextInput",Kn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(q,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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},g=()=>{a=!1,w()},m=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,Kn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Wn).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,Kn)){const e=s.get(o,Kn);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,Kn);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(Wn).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,Kn);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,Kn)){const e=s.get(o,Kn);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=er(Math.max(r.width,a)),r.height=er(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?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=Zn(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=Zn(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 g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,ve);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,ve,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",g),f.addEventListener("keydown",m),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",g),f.removeEventListener("keydown",m),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ke.PreUpdate,Ze([We(Wn)],e=>{const t=s.getEntitiesWithComponents([Kn,Bn]);for(const e of t){if(!s.has(e,Un))continue;if(s.get(e,Un).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([Bn]);for(const t of e){if(s.has(t,Kn))continue;if(!s.has(t,Un))continue;if(s.get(t,Un).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,Kn)))){s.get(o,Kn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Kn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Kn,yn]);for(const e of a){const t=s.get(e,Kn);if(!t.dirty)continue;const n=s.get(e,yn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,ve)||s.insert(e,ve,{texture:Y,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 Zn(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 er(e){let t=1;for(;t<e;)t*=2;return t}const tr=new Qn;async function sr(e,t,s){const n=e.getResource(Js);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function nr(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 rr=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ir=ze(null,"PhysicsAPI");function or(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ar(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class cr{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(rr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=nr(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([Se]);for(const s of t){const t=e.world.get(s,Se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ke.PostUpdate,Ze([We(je)],a=>{const c=o.getEntitiesWithComponents([Fe,we,xe]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,Fe),c=o.get(r,xe);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=or(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),lr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===$e.Kinematic){const e=or(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 u=e.world.get(o,we);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,Ce)){const t=e.world.get(o,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,xe)){const s=e.world.get(t.entity,xe),n=or(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=ar(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,we,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 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=[],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(rr,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ir,ur._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function lr(e,t,s){const n=e.world;if(n.has(s,ke)){const e=n.get(s,ke);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,Be)){const e=n.get(s,Be);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,Ue)){const e=n.get(s,Ue);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 ur{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(ur.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 hr(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 dr(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 fr(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,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function pr(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]=hr(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={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=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),u="binary"===x(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=dr(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=hr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new cr("",{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),u=hr(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,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=Pt.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Pt.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n),p=zt(e.world,s);if(c&&e.hasResource(Js))for(const t of p.values())e.world.insert(t,Re,{scene:c,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,ve);r&&(r.texture=s[n.data.texture]||0,e.insert(t,ve,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const i=e.get(t,Ee);i&&(i.font=r,e.insert(t,Ee,i))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,ve);s&&(s.material=r,e.insert(t,ve,s))}else if("SpineAnimation"===n.type){const s=e.get(t,Me);s&&(s.material=r,e.insert(t,Me,s))}}}}(e.world,s,f,p),r&&h){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}(h,s,u,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,Me)?l.get(i,Me):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,xe)){const e=fr(l.get(i,xe),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),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(Nt);t&&t.setAddressableManifest(a)}}function _r(e,t,s){return{name:e,data:t,async setup(){await pr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class gr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,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 mr="__preview__";class yr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Js);t.register({name:mr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(mr),this.loadPromise_=t.load(mr).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 gr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await pr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,mr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([be]);for(const n of s){if(e.get(n,be).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([Se]);for(const r of n){const n=e.get(r,Se);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(Js).getScene(mr),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,we,o);const a={isActive:!0,projectionType:ge.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:me.ColorAndDepth};e.insert(i,be,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Js);await e.switchTo(mr),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 wr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ws.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ws.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ws.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ws.releaseRenderTarget(e._handle),wr.create({width:t,height:s,depth:!0})),begin(e,t){Ws.begin(t,e._handle)},end(){Ws.end()},getDepthTexture:e=>Ws.getTargetDepthTexture(e._handle)};let xr=!1;function vr(e){xr=e}function br(){return xr}function Sr(){return!xr}var Pr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Pr||(Pr={}));class Cr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Pr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Pr.Debug:console.debug(t,s);break;case Pr.Info:console.log(t,s);break;case Pr.Warn:console.warn(t,s);break;case Pr.Error:console.error(t,s)}}}class Tr{constructor(){this.handlers_=[],this.minLevel_=Pr.Info,this.addHandler(new Cr)}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(Pr.Debug,e,t,s)}info(e,t,s){this.log(Pr.Info,e,t,s)}warn(e,t,s){this.log(Pr.Warn,e,t,s)}error(e,t,s){this.log(Pr.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 Er=new Tr;function Mr(){return Er}function Ar(e){Er.setMinLevel(e)}function Rr(e,t,s){Er.debug(e,t,s)}function Ir(e,t,s){Er.info(e,t,s)}function Fr(e,t,s){Er.warn(e,t,s)}function kr(e,t,s){Er.error(e,t,s)}const Br=[Sn,kn,Nn,Jn,tr];function Ur(e,t){return function(e,t){const s=en.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),cs(e),vt(e),Ps(e),As(e),Ds(e),Os(e);const r=new Ns;s.pipeline_=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=rn(e,n,t,r));const o=s.getResource(pt);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(pt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,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;Ws.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Ws.resize(t,c),Fs.isInitialized()&&Fs.getPassCount()>0&&!Fs.isBypassed()&&Fs.resize(t,c),s.hasResource(Js)){const e=s.getResource(Js).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=rn(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:sn,width:t,height:c,elapsed:u});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:u})}Ws.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ke.First,c),s.addSystemToSchedule(Ke.Last,l),s.addPlugin(Vt),s.addPlugin(ss),s.addPlugin(ct),s.addPlugin(Zs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Br,...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{en as App,Xt as AssetPlugin,qt as AssetRefCounter,jt as AssetServer,Nt as Assets,kt as AsyncCache,Ee as BitmapText,_t as BlendMode,$e as BodyType,ke as BoxCollider,Dn as Button,$n as ButtonState,be as Camera,Se as Canvas,Ue as CapsuleCollider,Te as Children,Be as CircleCollider,me as ClearFlags,Ge as Commands,Je as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,ws as DataType,ds as Draw,Ye as EntityCommands,js as GLDebug,Es as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,at as InputPlugin,it as InputState,Bn as Interactable,we as LocalTransform,Pr as LogLevel,Tr as Logger,Pt as Material,Bt as MaterialLoader,Ne as Mut,Ae as Name,Ce as Parent,ur as Physics,rr as PhysicsEvents,cr as PhysicsPlugin,Fs as PostProcess,Zt as PrefabServer,es as Prefabs,ts as PrefabsPlugin,yr as PreviewPlugin,ge as ProjectionType,Ve as Query,qe as QueryInstance,Ns as RenderPipeline,Bs as RenderStage,wr as RenderTexture,Ws as Renderer,We as Res,Le as ResMut,Fe as RigidBody,ye as ScaleMode,Js as SceneManager,Ys as SceneManagerState,Re as SceneOwner,Ke as Schedule,Ln as ScreenSpace,Ft as ShaderSources,Me as SpineAnimation,ve as Sprite,rt as SystemRunner,mn as Text,pn as TextAlign,Kn as TextInput,Qn as TextInputPlugin,gn as TextOverflow,bn as TextPlugin,wn as TextRenderer,_n as TextVerticalAlign,je as Time,pt as UICameraInfo,zn as UIEventQueue,Wn as UIEvents,Un as UIInteraction,Yn as UIInteractionPlugin,jn as UILayoutPlugin,Pn as UIMask,Fn as UIMaskPlugin,yn as UIRect,Pe as Velocity,gr as WebAssetProvider,ft as World,xe as WorldTransform,st as addStartupSystem,tt as addSystem,nt as addSystemToSchedule,Vt as assetPlugin,ys as clearDrawCallbacks,le as clearUserComponents,ee as color,On as computeUIRectLayout,In as createMaskProcessor,_r as createRuntimeSceneConfig,Ur as createWebApp,Rr as debug,oe as defineComponent,ze as defineResource,Ze as defineSystem,ae as defineTag,kr as error,Ht as findEntityByName,tn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,Dt as getComponentAssetFields,Ie as getComponentDefaults,E as getCustomExtensions,v as getEditorType,Mr as getLogger,t as getPlatform,n as getPlatformType,ce as getUserComponent,M as getWeChatPackOptions,Ir as info,cs as initDrawAPI,Os as initGLDebugAPI,Ps as initGeometryAPI,vt as initMaterialAPI,As as initPostProcessAPI,Ds as initRendererAPI,ct as inputPlugin,Yt as instantiatePrefab,Cn as intersectRects,En as invertMatrix4,he as isBuiltinComponent,R as isCustomExtension,br as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Sr as isRuntime,gt as isTextureRef,r as isWeChat,i as isWeb,Lt as loadComponent,nr as loadPhysicsModule,pr as loadRuntimeScene,zt as loadSceneData,Wt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,An as pointInWorldRect,ss as prefabsPlugin,te as quat,fe as registerComponent,$t as registerComponentAssetFields,gs as registerDrawCallback,Gt as registerEmbeddedAssets,It as registerMaterialCallback,Zs as sceneManagerPlugin,Mn as screenToWorld,vr as setEditorMode,Ar as setLogLevel,ls as shutdownDrawAPI,Hs as shutdownGLDebugAPI,Cs as shutdownGeometryAPI,bt as shutdownMaterialAPI,Rs as shutdownPostProcessAPI,zs as shutdownRendererAPI,tr as textInputPlugin,Sn as textPlugin,sr as transitionTo,Jn as uiInteractionPlugin,Nn as uiLayoutPlugin,kn as uiMaskPlugin,Br as uiPlugins,ms as unregisterDrawCallback,Ot as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,Fr as warn,Tn as worldRectToScreen,Ks as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,L as wxGetImagePixels,W as wxLoadImage,O as wxLoadImagePixels,B as wxReadFile,U 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 ec05c2c69..c5de4d852 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -266,6 +266,8 @@ declare class ResMutInstance<T> {
get(): T;
set(value: T): void;
modify(fn: (value: T) => void): void;
+ /** @internal */
+ updateValue(value: T): void;
}
declare class ResourceStorage {
private resources_;
@@ -646,6 +648,7 @@ declare class World {
getWorldVersion(): number;
beginIteration(): void;
endIteration(): void;
+ resetIterationDepth(): void;
isIterating(): boolean;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
@@ -666,7 +669,7 @@ declare class World {
private removeScript;
private getStorage;
resetQueryPool(): void;
- getEntitiesWithComponents(components: AnyComponentDef[]): Entity[];
+ getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
/**
@@ -723,7 +726,7 @@ interface CommandsDescriptor {
declare function Commands(): CommandsDescriptor;
interface SpawnComponentEntry {
component: AnyComponentDef;
- data: any;
+ data: unknown;
}
declare class EntityCommands {
private readonly commands_;
@@ -1325,6 +1328,7 @@ declare class AssetServer {
private groupAssets_;
private spineController_;
private spineSkeletons_;
+ private textureRefCounts_;
constructor(module: ESEngineModule);
registerEmbeddedAssets(assets: Record<string, string>): void;
setEmbeddedOnly(value: boolean): void;
@@ -1340,6 +1344,7 @@ declare class AssetServer {
loadTextureRaw(source: string): Promise<TextureInfo>;
getTexture(source: string): TextureInfo | undefined;
hasTexture(source: string): boolean;
+ getTextureRefCount(source: string): number;
releaseTexture(source: string): void;
releaseAll(): void;
private cleanupVirtualFS;
@@ -1451,7 +1456,7 @@ declare function registerComponentAssetFields(componentType: string, config: Com
declare function getComponentAssetFields(componentType: string): string[];
declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;
declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;
-declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;
+declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void;
declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;
declare function findEntityByName(world: World, name: string): Entity | null;
@@ -1506,6 +1511,7 @@ declare class SceneManagerState {
private activeScene_;
private initialScene_;
private transition_;
+ private loadPromises_;
constructor(app: App);
register(config: SceneConfig): void;
setInitial(name: string): void;
@@ -1563,6 +1569,8 @@ declare class App {
private physicsModule_?;
private readonly installed_plugins_;
private error_handler_;
+ private system_error_handler_;
+ private frame_paused_;
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
@@ -1585,6 +1593,7 @@ declare class App {
get world(): World;
setFixedTimestep(timestep: number): this;
onError(handler: (error: unknown, systemName: string) => void): this;
+ onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
@@ -1882,6 +1891,8 @@ interface TextInputData {
declare const TextInput: ComponentDef<TextInputData>;
declare class TextInputPlugin implements Plugin {
+ private cleanupListeners_;
+ cleanup(): void;
build(app: App): void;
}
declare const textInputPlugin: TextInputPlugin;
@@ -2083,6 +2094,8 @@ declare class PreviewPlugin implements Plugin {
private app_;
private loadPromise_;
private eventSource_;
+ private onMessage_;
+ private onError_;
constructor(sceneUrl: string, baseUrl?: string);
build(app: App): void;
/**
@@ -2091,6 +2104,7 @@ declare class PreviewPlugin implements Plugin {
waitForReady(): Promise<void>;
private loadRuntimeData;
private ensureCamera;
+ cleanup(): void;
private setupHotReload;
private reloadScene;
}
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index a508b3a69..c5e06f1d2 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 u(e,s){return t().instantiateWasm(e,s)}function h(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)}},u=()=>{e.onPointerUp(0)},h=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",u),s.addEventListener("wheel",h),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",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,g=100,m=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),S=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),P=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),C=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const s in e)t[s]=T(e[s]);return t}let E=0;function M(e,t){const s=++E;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...T(t),...e}:T(t)}}function A(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const s=A(),n=s.get(e);if(n)return n;const r=M(e,t);return s.set(e,r),B(e,t,!1),r}function I(e){const t=A(),s=t.get(e);if(s)return s;const n=M(e,{});return t.set(e,n),B(e,{},!0),n}function F(e){return A().get(e)}function k(){A().clear()}function B(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function U(e){return!0===e._builtin}const $=new Map;function z(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function L(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,s),s}const O={Perspective:0,Orthographic:1},H={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},j=L("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),N=L("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=L("Sprite",{texture:w,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}),X=L("Camera",{projectionType:O.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:H.ColorAndDepth}),Y=L("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=L("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=L("Parent",{entity:0}),J=L("Children",{entities:[]}),K=L("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=L("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Z={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ee=R("SceneOwner",{scene:"",persistent:!1});function te(e){const t=D(e);return t?T(t._default):null}z("Name",Z);const se=L("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ne=L("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=L("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ie=L("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe={Static:0,Kinematic:1,Dynamic:2};let ae=0;function ce(e,t){const s=++ae;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function le(e){return{_type:"res",_resource:e}}function ue(e){return{_type:"res_mut",_resource:e}}class he{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_)}}class de{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new he(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const fe=ce({delta:0,elapsed:0,frameCount:0},"Time");function pe(e){return{_type:"mut",_component:e}}function _e(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)=>{_e(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class me{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(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_),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a.slice()}}finally{if(this.world_.endIteration(),null!==u&&i)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}}function ye(){return{_type:"commands"}}class we{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=U(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 xe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new we(this,null);return this.spawned_.push(e),e}entity(e){return new we(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 ve;!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"}(ve||(ve={}));let be=0;function Se(e,t,s){const n=++be;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Pe().push({schedule:ve.Update,system:e})}function Te(e){Pe().push({schedule:ve.Startup,system:e})}function Ee(e,t){Pe().push({schedule:e,system:t})}class Me{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]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof xe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new me(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new xe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ae{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=ce(new Ae,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Ae;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(ve.Last,Se([],()=>{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 ke(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=Be(t[e]),i=Be(r);s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r})}return n}function Be(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")}function $e(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}:$e(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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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)}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return U(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return U(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return U(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(U(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");U(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=ke(t._name,t._default,n);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,$e(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=ke(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 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){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!U(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const i=this.queryPool_[this.queryPoolIdx_++];i.length=0;const o=n?n.keys():this.entities_;for(const t of o){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&i.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:i}),i}}const De=ce({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Le;function Oe(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"}(Le||(Le={}));let He=null,We=null,je=1;const Ne=new Map;function Ve(e){He=e,We=e.getResourceManager(),tt()}function Xe(){0!==Je&&He&&(He._free(Je),Je=0),Ne.clear(),je=1,Ge=!1,We=null,He=null}function Ye(){if(!We)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return We}const qe={createShader:(e,t)=>Ye().createShader(e,t),releaseShader(e){e>0&&Ye().releaseShader(e)},create(e){const t=je++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Le.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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??Le.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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??Le.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ge=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&He&&(Je=He._malloc(Ke)),Je);if(0===t||!He)return{ptr:0,count:0};let s=0,n=0;const r=He.HEAPU8,i=He.HEAPU32,o=He.HEAPF32;for(const[a,c]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=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?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!He||Ge)return;He.materialDataProvider=(e,t,s,n,r)=>{const i=Ne.get(e);if(!i)return He.HEAPU32[t>>2]=0,He.HEAPU32[s>>2]=0,He.HEAPU32[n>>2]=0,void(He.HEAPU32[r>>2]=0);He.HEAPU32[t>>2]=i.shader,He.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=et(i.uniforms);He.HEAPU32[n>>2]=o,He.HEAPU32[r>>2]=a},Ge=!0}const st={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 nt{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)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 rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.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:qe.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 it=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 ot(e,t){it.set(e,t)}function at(e){const t=it.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 ct(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,Z,{value:n.name}),!1!==n.visible)for(const s of n.components)ut(e,t,s)}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 lt(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=it.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,u=new Map,h=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);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.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=it.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]=h.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,Z,{value:s.name}),!1!==s.visible)for(const n of s.components)ut(e,t,n)}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 ut(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=D(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}function ht(e,t){const s=e.getEntitiesWithComponents([X]);for(const n of s){const s=e.get(n,X);s&&(s.aspectRatio=t,e.insert(n,X,s))}}function dt(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);if(s&&s.value===t)return n}return null}const ft=[{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}],pt={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"},_t=new Map,gt=new Set;for(const e of ft)for(const t of e.extensions)_t.set(t,e),gt.add(t);function mt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function yt(e){return _t.get(mt(e))}function wt(e){return yt(e)?.editorType??"unknown"}function xt(e){return yt(e)?.addressableType??null}function vt(e){for(const t of ft)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function bt(e){return gt.has(e.toLowerCase())}function St(){return gt}function Pt(e){return"string"==typeof e&&(!!e.includes("/")&&bt(mt(e)))}function Ct(){const e=[];for(const t of ft)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Tt(){return Ct().map(e=>({type:"suffix",value:e}))}function Et(e){return pt[e.toLowerCase()]}function Mt(e){const t=yt(e);return t?.wechatPackInclude??!1}class At{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,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.module_=e,this.canvas_=h(m,m),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new rt(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))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}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(),qe.releaseAll(),this.textureCache_.clearAll(),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),u="binary"===yt(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,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=yt(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 lt(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);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}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 qe.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 qe.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 Rt=ce(null,"Assets");class It{build(e){const t=e.wasmModule;t?e.insertResource(Rt,new At(t)):console.warn("AssetPlugin: No WASM module available")}}const Ft=new It;class kt{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 Bt(e,t){const s=e.getResource(Rt);s&&s.registerEmbeddedAssets(t)}async function Ut(e,t,s){const{entities:n,rootId:r}=await $t(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 lt(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}}async function $t(e,t,s,n,r){const i=new Map;let o;if(void 0===n){o=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,o++)}const a=[];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 $t(e,n.nestedPrefab.overrides,s,o,r);i.set(n.prefabEntityId,t.rootId),o=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),a.push(...t.entities);continue}const c=i.get(n.prefabEntityId),l=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:l?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};zt(u,t),a.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:c,nextId:o}}function zt(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 Dt{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 Ut(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Lt=ce(null,"Prefabs");class Ot{constructor(){this.name="PrefabsPlugin",this.dependencies=[Rt]}build(e){const t=e.getResource(Rt);e.insertResource(Lt,new Dt(e.world,t))}}const Ht=new Ot;let Wt=null,jt=0,Nt=0,Vt=0;const Xt=new Float32Array(256);function Yt(e){Wt=e,jt=Wt._malloc(64),Nt=Wt._malloc(64),Vt=Wt._malloc(1024)}function qt(){Wt&&(jt&&(Wt._free(jt),jt=0),Nt&&(Wt._free(Nt),Nt=0),Vt&&(Wt._free(Vt),Vt=0)),Wt=null}function Gt(){if(!Wt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Wt}const Jt={r:1,g:1,b:1,a:1},Kt={begin(e){const t=Gt();t.HEAPF32.set(e,jt/4),t.draw_begin(jt)},end(){Gt().draw_end()},line(e,t,s,n=1){Gt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Gt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Gt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Gt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Gt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Jt){Gt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Jt){Gt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Gt().draw_setLayer(e)},setDepth(e){Gt().draw_setDepth(e)},getDrawCallCount:()=>Wt?Wt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Wt?Wt.draw_getPrimitiveCount():0,setBlendMode(e){Gt().draw_setBlendMode(e)},setDepthTest(e){Gt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Gt();n.HEAPF32.set(s,Nt/4),n.draw_mesh(e,t,Nt)},drawMeshWithMaterial(e,t,s){const n=Gt(),r=qe.get(t);if(!r)return;if(Kt.setBlendMode(r.blendMode),Kt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Kt.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Nt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=Zt(t);if(!(n<0)){if(Oe(s))Xt[i++]=10,Xt[i++]=n,Xt[i++]=s.slot??e++,Xt[i++]=s.textureId;else if("number"==typeof s)Xt[i++]=1,Xt[i++]=n,Xt[i++]=s;else if(Array.isArray(s)){Xt[i++]=s.length,Xt[i++]=n;for(let e=0;e<s.length;e++)Xt[i++]=s[e]}else"w"in s?(Xt[i++]=4,Xt[i++]=n,Xt[i++]=s.x,Xt[i++]=s.y,Xt[i++]=s.z,Xt[i++]=s.w):"z"in s?(Xt[i++]=3,Xt[i++]=n,Xt[i++]=s.x,Xt[i++]=s.y,Xt[i++]=s.z):(Xt[i++]=2,Xt[i++]=n,Xt[i++]=s.x,Xt[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(Xt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Vt/4),n.draw_meshWithUniforms(e,r.shader,Nt,Vt,i)):n.draw_mesh(e,r.shader,Nt)}},Qt={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};function Zt(e){return Qt[e]??-1}var es;!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"}(es||(es={}));let ts=null,ss=0,ns=0,rs=0;function is(e){ts=e,ss=ts._malloc(262144),ns=ts._malloc(65536),rs=ts._malloc(256)}function os(){ts&&(ss&&ts._free(ss),ns&&ts._free(ns),rs&&ts._free(rs),ss=0,ns=0,rs=0),ts=null}function as(){if(!ts)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ts}const cs={create(e){const t=as(),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,ss/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,ss,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,ns,n).set(e.indices),t.geometry_setIndices16(s,ns,n)}else{new Uint32Array(t.HEAPU8.buffer,ns,n).set(e.indices),t.geometry_setIndices32(s,ns,n)}}return s},updateVertices(e,t,s=0){const n=as(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ss/4),n.geometry_updateVertices(e,ss,r,s)},release(e){e>0&&as().geometry_release(e)},isValid:e=>!(!ts||e<=0)&&ts.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return cs.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:es.Float2},{name:"a_texCoord",type:es.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 cs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:es.Float2},{name:"a_texCoord",type:es.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 cs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:es.Float2},{name:"a_texCoord",type:es.Float2}],indices:new Uint16Array(o)})}};let ls=null;function us(e){ls=e}function hs(){ls&&fs.isInitialized()&&fs.shutdown(),ls=null}function ds(){if(!ls)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ls}const fs={init:(e,t)=>ds().postprocess_init(e,t),shutdown(){ds().postprocess_shutdown()},resize(e,t){ds().postprocess_resize(e,t)},addPass:(e,t)=>ds().postprocess_addPass(e,t),removePass(e){ds().postprocess_removePass(e)},setEnabled(e,t){ds().postprocess_setPassEnabled(e,t)},isEnabled:e=>ds().postprocess_isPassEnabled(e),setUniform(e,t,s){ds().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){ds().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){ds().postprocess_begin()},end(){ds().postprocess_end()},getPassCount:()=>ds().postprocess_getPassCount(),isInitialized:()=>!!ls&&ls.postprocess_isInitialized(),setBypass(e){ds().postprocess_setBypass(e)},isBypassed:()=>!ls||ls.postprocess_isBypassed(),createBlur:()=>qe.createShader(ps,"#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:()=>qe.createShader(ps,"#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:()=>qe.createShader(ps,"#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:()=>qe.createShader(ps,"#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")},ps="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var _s;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(_s||(_s={}));let gs=null,ms=0;function ys(e){gs=e,ms=gs._malloc(64)}function ws(){gs&&ms&&(gs._free(ms),ms=0),gs=null}const xs={init(e,t){gs?.renderer_init(e,t)},resize(e,t){gs?.renderer_resize(e,t)},begin(e,t){gs&&ms&&(gs.HEAPF32.set(e,ms/4),gs.renderer_begin(ms,t??0))},flush(){gs?.renderer_flush()},end(){gs?.renderer_end()},submitSprites(e){gs&&gs.renderer_submitSprites(e._cpp)},submitBitmapText(e){gs&&gs.renderer_submitBitmapText(e._cpp)},submitSpine(e){gs&&gs.renderer_submitSpine?.(e._cpp)},setStage(e){gs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>gs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){gs?.renderer_releaseTarget(e)},getTargetTexture:e=>gs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>gs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){gs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){gs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){gs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){gs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>gs?gs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>gs?{drawCalls:gs.renderer_getDrawCalls(),triangles:gs.renderer_getTriangles(),sprites:gs.renderer_getSprites(),text:gs.renderer_getText(),spine:gs.renderer_getSpine?.()??0,meshes:gs.renderer_getMeshes(),culled:gs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let vs=null;function bs(e){vs=e}function Ss(){vs=null}const Ps={enable(){vs?.gl_enableErrorCheck(!0)},disable(){vs?.gl_enableErrorCheck(!1)},check:e=>vs?.gl_checkErrors(e)??0,diagnose(){vs?.renderer_diagnose()}},Cs=new Map;function Ts(e,t,s){Cs.set(e,{fn:t,scene:s??""})}function Es(e){Cs.delete(e)}function Ms(){Cs.clear()}class As{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_||(xs.resize(n,r),fs.isInitialized()&&fs.getPassCount()>0&&fs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),xs.setViewport(0,0,n,r),xs.clearBuffers(3),xs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),xs.submitSprites(t),xs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):xs.submitSpine(t),xs.flush(),this.executeDrawCallbacks(s,i),xs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;xs.setViewport(n.x,n.y,n.w,n.h),xs.setScissor(n.x,n.y,n.w,n.h,!0),xs.clearBuffers(r),xs.setScissor(0,0,0,0,!1),xs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),xs.submitSprites(t),xs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):xs.submitSpine(t),xs.flush(),this.executeDrawCallbacks(s,i),xs.end()}executeDrawCallbacks(e,t){const s=Cs;if(s.size>0){Kt.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)}Kt.end();for(const e of n)Es(e)}}}const Rs="__scene_transition_overlay__",Is={r:0,g:0,b:0,a:1};class Fs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ks{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ee,{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),Ts(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=fs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){fs.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,ee)){const s=this.app_.world.get(e,ee);s.persistent=t,this.app_.world.insert(e,ee,s)}}}class Bs{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.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){"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??.3,r=t.color??Is;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ts(Rs,()=>{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;Kt.setLayer(9999),Kt.setDepth(9999),Kt.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)})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Es(Rs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 Fs(t);this.scenes_.set(e,s);const n=new ks(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Rt)?this.app_.getResource(Rt):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(Rt)&&(t.assetServer=this.app_.getResource(Rt));const n=await lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=$s(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}async loadAdditive(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 Fs(t);this.scenes_.set(e,s);const n=new ks(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Rt)?this.app_.getResource(Rt):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(Rt)&&(t.assetServer=this.app_.getResource(Rt));const n=await lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=$s(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}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,ee)){if(this.app_.world.get(e,ee).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Es(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{fs.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,V)){const s=this.app_.world.get(e,V);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,V,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,V)){const s=this.app_.world.get(e,V),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,V,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{fs.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 Us=ce(null,"SceneManager");function $s(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Us).getSceneStatus(t)&&s._fn(...n)}}}const zs=Se([ue(Us),le(fe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ds={name:"SceneManager",build(e){const t=new Bs(e);e.insertResource(Us,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Us),s=t.getInitial();s&&t.load(s)}};e.addSystemToSchedule(ve.Startup,s),e.addSystemToSchedule(ve.Last,zs)}};class Ls{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(ve.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ve.FixedPreUpdate),this.runSchedule(ve.FixedUpdate),this.runSchedule(ve.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(ve.PreUpdate),this.runSchedule(ve.Update),this.runSchedule(ve.PostUpdate),this.runSchedule(ve.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new de;for(const e of Object.values(ve))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ls}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}addSystem(e){return this.addSystemToSchedule(ve.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ve.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_}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}onError(e){return this.error_handler_=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(Us).register(e),this}setInitialScene(e){return this.getResource(Us).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Me(this.world_,this.resources_),this.resources_.insert(fe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ve.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1;const e=[Ss,ws,hs,os,Xe,qt];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){let t=this.systems_.get(e);if(t&&this.runner_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(fe);t.delta=e,t.elapsed+=e,t.frameCount++}}function Os(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 Hs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ws(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case W.FixedWidth:return i;case W.FixedHeight:return o;case W.Expand:return Math.max(i,o);case W.Shrink:return Math.min(i,o);case W.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,ee);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 u,h=0,d=0;if(r.projectionType===O.Orthographic){if(d=r.orthoSize,c){d=Ws(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=Vs(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Ys(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Gs(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(Ks(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Ns=new Float32Array(16);function Vs(e,t,s,n,r,i){const o=Ns;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 Xs=new Float32Array(16);function Ys(e,t,s,n){const r=Xs;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 qs=new Float32Array(16);function Gs(e,t,s){const n=qs;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 Js=new Float32Array(16);function Ks(e,t){const s=Js;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 Qs,Zs,en;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Qs||(Qs={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Zs||(Zs={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(en||(en={}));const tn=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Qs.Left,verticalAlign:Zs.Top,wordWrap:!0,overflow:en.Visible,lineHeight:1.2}),sn=R("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 nn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(m,m),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),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===en.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),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===en.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 Zs.Top:x=u;break;case Zs.Middle:x=(p-w)/2;break;case Zs.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case Qs.Left:n=u;break;case Qs.Center:n=f/2;break;case Qs.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===en.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 Qs.Left:return"left";case Qs.Center:return"center";case Qs.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function rn(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 on(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 an{build(e){z("Text",tn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new nn(t),n=e.world,r=new Map;e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,tn));for(const e of r.keys())n.valid(e)&&n.has(e,tn)||r.delete(e);const e=n.getEntitiesWithComponents([tn]);for(const t of e){const e=n.get(t,tn),i=n.has(t,sn)?n.get(t,sn):null,o=r.get(t);if(o&&!on(o,e,i))continue;n.has(t,V)||n.insert(t,V,{texture:w,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,V);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,V,c),r.set(t,rn(e,i))}}))}}const cn=new an,ln=R("UIMask",{enabled:!0});function un(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 hn(e,t,s,n,r,i,o,a,c,l,u){const h=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)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function dn(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],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;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+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function fn(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],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function pn(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 _n(e,t,s,n,r,i,o){if(!e.has(t,sn)||!e.has(t,N))return null;const a=e.get(t,sn),c=e.get(t,N),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return hn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function gn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([ln]);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,ln).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,G);){const e=t.get(n,G);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=_n(t,s,r,i,o,a,c);e&&(n=un(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=_n(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class mn{build(e){if(z("UIMask",ln),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(gn(e.wasmModule,e.world))}}const yn=new mn,wn=R("Interactable",{enabled:!0}),xn=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var vn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(vn||(vn={}));const bn=R("Button",{state:vn.Normal,transition:null});class Sn{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 Pn=ce(new Sn,"UIEvents"),Cn=I("ScreenSpace");function Tn(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,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+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=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function En(e,t,s,n,r,i){if(!e.has(t,sn))return;const o=e.get(t,sn),a=Tn(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,j);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,j,c),!e.has(t,J))return;const l=e.get(t,J);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&En(e,t,a.rect,a.centerX,a.centerY,!1)}class Mn{build(e){z("UIRect",sn);const t=e.world;e.addSystemToSchedule(ve.PreUpdate,Se([le(De)],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([Cn,sn,j]);for(const e of i)En(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const An=new Mn,Rn=new Float32Array(16),In=new Float32Array(16);let Fn=!0,kn=1;class Bn{build(e){z("Interactable",wn),z("Button",bn);const t=e.world,s=new Sn;e.insertResource(Pn,s);let n=null,r=null;kn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(ve.PreUpdate,Se([le(Re),le(De)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([xn]);for(const e of o){const s=t.get(e,xn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*kn,c=i.screenH-e.mouseY*kn;!function(e){let t=!1;for(let s=0;s<16;s++)if(In[s]!==e[s]){t=!0;break}t&&(In.set(e),Fn=!0)}(i.viewProjection),Fn&&(dn(i.viewProjection,Rn),Fn=!1);const l=fn(a,c,Rn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([wn,sn,N]);let h=null,d=-1/0;for(const e of u){t.has(e,xn)||t.insert(e,xn);if(!t.get(e,wn).enabled)continue;const s=t.get(e,N),n=t.get(e,sn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(pn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,V)&&(s=t.get(e,V).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,xn)){t.get(n,xn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,xn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,xn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,xn)){const e=t.get(r,xn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(ve.Update,Se([],()=>{const e=t.getEntitiesWithComponents([bn]);for(const s of e){if(t.has(s,wn)||t.insert(s,wn,{enabled:!0}),!t.has(s,xn))continue;const e=t.get(s,xn),n=t.get(s,bn),r=t.get(s,wn),i=n.state;if(r.enabled?e.pressed?n.state=vn.Pressed:e.hovered?n.state=vn.Hovered:n.state=vn.Normal:n.state=vn.Disabled,i!==n.state&&n.transition&&t.has(s,V)){const e=t.get(s,V),r=n.transition;switch(n.state){case vn.Normal:e.color={...r.normalColor};break;case vn.Hovered:e.color={...r.hoveredColor};break;case vn.Pressed:e.color={...r.pressedColor};break;case vn.Disabled:e.color={...r.disabledColor}}t.insert(s,V,e)}}},{name:"ButtonSystem"}))}}const Un=new Bn,$n=R("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 zn{build(e){z("TextInput",$n);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(m,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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;function p(){if(null===o||!s.valid(o))return;const t=s.get(o,$n);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(Pn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,y()}function _(e){if(o===e)return;g();const t=s.get(e,$n);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function g(){if(null!==o&&s.valid(o)&&s.has(o,$n)){const e=s.get(o,$n);e.focused=!1,e.dirty=!0}o=null,f.blur()}function y(){c=!0,l=0}function x(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Ln(Math.max(r.width,a)),r.height=Ln(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?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=Dn(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=Dn(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 g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,V);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,V,b)}f.addEventListener("input",()=>{a||null===o||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===o)return;if("Escape"===t.key)return void g();const n=s.get(o,$n);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Pn).emit(o,"submit"),void g()}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,y())}),f.addEventListener("blur",()=>{if(null!==o&&s.valid(o)&&s.has(o,$n)){const e=s.get(o,$n);e.focused=!1,e.dirty=!0}o=null}),e.addSystemToSchedule(ve.PreUpdate,Se([le(Pn)],e=>{const t=s.getEntitiesWithComponents([$n,wn]);for(const e of t){if(!s.has(e,xn))continue;if(s.get(e,xn).justPressed)return void _(e)}if(null!==o){const e=s.getEntitiesWithComponents([wn]);for(const t of e){if(s.has(t,$n))continue;if(!s.has(t,xn))continue;if(s.get(t,xn).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,$n)))){s.get(o,$n).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,$n)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([$n,sn]);for(const e of a){const t=s.get(e,$n);if(!t.dirty)continue;const n=s.get(e,sn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,V)||s.insert(e,V,{texture:w,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}),x(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Dn(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 Ln(e){let t=1;for(;t<e;)t*=2;return t}const On=new zn;async function Hn(e,t,s){const n=e.getResource(Us);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Wn(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=ce({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Nn=ce(null,"PhysicsAPI");function Vn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Xn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Yn{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=Wn(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([Y]);for(const s of t){const t=e.world.get(s,Y);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(ve.PostUpdate,Se([le(fe)],a=>{const c=o.getEntitiesWithComponents([se,j,N]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,se),c=o.get(r,N);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=Vn(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),qn(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===oe.Kinematic){const e=Vn(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 u=e.world.get(o,j);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,G)){const t=e.world.get(o,G);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const s=e.world.get(t.entity,N),n=Vn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=Xn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,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 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=[],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(jn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Nn,Gn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function qn(e,t,s){const n=e.world;if(n.has(s,ne)){const e=n.get(s,ne);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,re)){const e=n.get(s,re);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,ie)){const e=n.get(s,ie);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 Gn{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(Gn.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 Jn(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 Kn(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 Qn(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,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function Zn(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]=Jn(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={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=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),u="binary"===yt(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Kn(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=Jn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new Yn("",{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=yt(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),u=Jn(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,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=qe.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=qe.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n),p=ct(e.world,s);if(c&&e.hasResource(Us))for(const t of p.values())e.world.insert(t,ee,{scene:c,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,V);r&&(r.texture=s[n.data.texture]||0,e.insert(t,V,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const i=e.get(t,K);i&&(i.font=r,e.insert(t,K,i))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,V);s&&(s.material=r,e.insert(t,V,s))}else if("SpineAnimation"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}}}}(e.world,s,f,p),r&&h){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}(h,s,u,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,Q)?l.get(i,Q):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,N)){const e=Qn(l.get(i,N),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),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(Rt);t&&t.setAddressableManifest(a)}}function er(e,t,s){return{name:e,data:t,async setup(){await Zn(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class tr{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"===yt(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=yt(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 nr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Us);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 tr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await Zn(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([X]);for(const n of s){if(e.get(n,X).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([Y]);for(const r of n){const n=e.get(r,Y);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(Us).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,j,o);const a={isActive:!0,projectionType:O.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:H.ColorAndDepth};e.insert(i,X,a)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Us);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 rr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=xs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:xs.getTargetTexture(s),width:e.width,height:e.height}},release(e){xs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(xs.releaseRenderTarget(e._handle),rr.create({width:t,height:s,depth:!0})),begin(e,t){xs.begin(t,e._handle)},end(){xs.end()},getDepthTexture:e=>xs.getTargetDepthTexture(e._handle)};let ir=!1;function or(e){ir=e}function ar(){return ir}function cr(){return!ir}var lr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(lr||(lr={}));class ur{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${lr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case lr.Debug:console.debug(t,s);break;case lr.Info:console.log(t,s);break;case lr.Warn:console.warn(t,s);break;case lr.Error:console.error(t,s)}}}class hr{constructor(){this.handlers_=[],this.minLevel_=lr.Info,this.addHandler(new ur)}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(lr.Debug,e,t,s)}info(e,t,s){this.log(lr.Info,e,t,s)}warn(e,t,s){this.log(lr.Warn,e,t,s)}error(e,t,s){this.log(lr.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 dr=new hr;function fr(){return dr}function pr(e){dr.setMinLevel(e)}function _r(e,t,s){dr.debug(e,t,s)}function gr(e,t,s){dr.info(e,t,s)}function mr(e,t,s){dr.warn(e,t,s)}function yr(e,t,s){dr.error(e,t,s)}const wr=[cn,yn,An,Un,On];function xr(e,t){return function(e,t){const s=Ls.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Yt(e),Ve(e),is(e),us(e),ys(e),bs(e);const r=new As;s.pipeline_=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(De);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(De,{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;xs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(xs.resize(t,c),fs.isInitialized()&&fs.getPassCount()>0&&!fs.isBypassed()&&fs.resize(t,c),s.hasResource(Us)){const e=s.getResource(Us).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=js(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Hs,width:t,height:c,elapsed:u});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:u})}xs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(ve.First,c),s.addSystemToSchedule(ve.Last,l),s.addPlugin(Ft),s.addPlugin(Ht),s.addPlugin(Fe),s.addPlugin(Ds),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:wr,...t})}e=f;export{Ls as App,It as AssetPlugin,kt as AssetRefCounter,At as AssetServer,Rt as Assets,nt as AsyncCache,K as BitmapText,Le as BlendMode,oe as BodyType,ne as BoxCollider,bn as Button,vn as ButtonState,X as Camera,Y as Canvas,ie as CapsuleCollider,J as Children,re as CircleCollider,H as ClearFlags,ye as Commands,xe as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,g as DEFAULT_PIXELS_PER_UNIT,m as DEFAULT_TEXT_CANVAS_SIZE,es as DataType,Kt as Draw,we as EntityCommands,Ps as GLDebug,cs as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Re as Input,Ie as InputPlugin,Ae as InputState,wn as Interactable,j as LocalTransform,lr as LogLevel,hr as Logger,qe as Material,rt as MaterialLoader,pe as Mut,Z as Name,G as Parent,Gn as Physics,jn as PhysicsEvents,Yn as PhysicsPlugin,fs as PostProcess,Dt as PrefabServer,Lt as Prefabs,Ot as PrefabsPlugin,nr as PreviewPlugin,O as ProjectionType,ge as Query,me as QueryInstance,As as RenderPipeline,_s as RenderStage,rr as RenderTexture,xs as Renderer,le as Res,ue as ResMut,se as RigidBody,W as ScaleMode,Us as SceneManager,Bs as SceneManagerState,ee as SceneOwner,ve as Schedule,Cn as ScreenSpace,st as ShaderSources,Q as SpineAnimation,V as Sprite,Me as SystemRunner,tn as Text,Qs as TextAlign,$n as TextInput,zn as TextInputPlugin,en as TextOverflow,an as TextPlugin,nn as TextRenderer,Zs as TextVerticalAlign,fe as Time,De as UICameraInfo,Sn as UIEventQueue,Pn as UIEvents,xn as UIInteraction,Bn as UIInteractionPlugin,Mn as UILayoutPlugin,ln as UIMask,mn as UIMaskPlugin,sn as UIRect,q as Velocity,tr as WebAssetProvider,ze as World,N as WorldTransform,Te as addStartupSystem,Ce as addSystem,Ee as addSystemToSchedule,Ft as assetPlugin,Ms as clearDrawCallbacks,k as clearUserComponents,P as color,Tn as computeUIRectLayout,gn as createMaskProcessor,er as createRuntimeSceneConfig,xr as createWebApp,_r as debug,R as defineComponent,ce as defineResource,Se as defineSystem,I as defineTag,yr as error,dt as findEntityByName,Os as flushPendingSystems,xt as getAddressableType,vt as getAddressableTypeByEditorType,St as getAllAssetExtensions,Et as getAssetMimeType,yt as getAssetTypeEntry,D as getComponent,at as getComponentAssetFields,te as getComponentDefaults,Ct as getCustomExtensions,wt as getEditorType,fr as getLogger,t as getPlatform,n as getPlatformType,F as getUserComponent,Tt as getWeChatPackOptions,gr as info,Yt as initDrawAPI,bs as initGLDebugAPI,is as initGeometryAPI,Ve as initMaterialAPI,us as initPostProcessAPI,ys as initRendererAPI,Fe as inputPlugin,Ut as instantiatePrefab,un as intersectRects,dn as invertMatrix4,U as isBuiltinComponent,Mt as isCustomExtension,ar as isEditor,bt as isKnownAssetExtension,s as isPlatformInitialized,cr as isRuntime,Oe as isTextureRef,r as isWeChat,i as isWeb,ut as loadComponent,Wn as loadPhysicsModule,Zn as loadRuntimeScene,ct as loadSceneData,lt as loadSceneWithAssets,Pt as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,pn as pointInWorldRect,Ht as prefabsPlugin,C as quat,z as registerComponent,ot as registerComponentAssetFields,Ts as registerDrawCallback,Bt as registerEmbeddedAssets,tt as registerMaterialCallback,Ds as sceneManagerPlugin,fn as screenToWorld,or as setEditorMode,pr as setLogLevel,qt as shutdownDrawAPI,Ss as shutdownGLDebugAPI,os as shutdownGeometryAPI,Xe as shutdownMaterialAPI,hs as shutdownPostProcessAPI,ws as shutdownRendererAPI,On as textInputPlugin,cn as textPlugin,Hn as transitionTo,Un as uiInteractionPlugin,An as uiLayoutPlugin,yn as uiMaskPlugin,wr as uiPlugins,Es as unregisterDrawCallback,ht as updateCameraAspectRatio,v as vec2,b as vec3,S as vec4,mr as warn,hn as worldRectToScreen,$s 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 u(e,s){return t().instantiateWasm(e,s)}function h(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)}},u=()=>{e.onPointerUp(0)},h=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",u),s.addEventListener("wheel",h),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",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,g=100,m=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),S=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),P=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),C=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const s in e)t[s]=T(e[s]);return t}let E=0;function M(e,t){const s=++E;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...T(t),...e}:T(t)}}function A(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const s=A(),n=s.get(e);if(n)return n;const r=M(e,t);return s.set(e,r),B(e,t,!1),r}function I(e){const t=A(),s=t.get(e);if(s)return s;const n=M(e,{});return t.set(e,n),B(e,{},!0),n}function F(e){return A().get(e)}function k(){A().clear()}function B(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function U(e){return!0===e._builtin}const $=new Map;function L(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function z(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,s),s}const O={Perspective:0,Orthographic:1},H={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},j=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),N=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=z("Sprite",{texture:w,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}),X=z("Camera",{projectionType:O.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:H.ColorAndDepth}),Y=z("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=z("Parent",{entity:0}),J=z("Children",{entities:[]}),K=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Z={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ee=R("SceneOwner",{scene:"",persistent:!1});function te(e){const t=D(e);return t?T(t._default):null}L("Name",Z);const se=z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ne=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ie=z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe={Static:0,Kinematic:1,Dynamic:2};let ae=0;function ce(e,t){const s=++ae;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function le(e){return{_type:"res",_resource:e}}function ue(e){return{_type:"res_mut",_resource:e}}class he{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class de{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new he(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const fe=ce({delta:0,elapsed:0,frameCount:0},"Time");function pe(e){return{_type:"mut",_component:e}}function _e(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)=>{_e(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class me{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(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 u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)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}}function ye(){return{_type:"commands"}}class we{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=U(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 xe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new we(this,null);return this.spawned_.push(e),e}entity(e){return new we(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 ve;!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"}(ve||(ve={}));let be=0;function Se(e,t,s){const n=++be;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Pe().push({schedule:ve.Update,system:e})}function Te(e){Pe().push({schedule:ve.Startup,system:e})}function Ee(e,t){Pe().push({schedule:e,system:t})}class Me{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 xe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new me(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new xe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ae{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=ce(new Ae,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Ae;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(ve.Last,Se([],()=>{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 ke(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=Be(t[e]),i=Be(r);s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r})}return n}function Be(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")}function $e(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}:$e(e)}}return t}class Le{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return U(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return U(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return U(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(U(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");U(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=ke(t._name,t._default,n);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,$e(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=ke(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 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(!U(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 De=ce({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var ze;function Oe(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"}(ze||(ze={}));let He=null,We=null,je=1;const Ne=new Map;function Ve(e){He=e,We=e.getResourceManager(),tt()}function Xe(){0!==Je&&He&&(He._free(Je),Je=0),Ne.clear(),je=1,Ge=!1,Qe.clear(),Ze=null,We=null,He=null}function Ye(){if(!We)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return We}const qe={createShader:(e,t)=>Ye().createShader(e,t),releaseShader(e){e>0&&Ye().releaseShader(e)},create(e){const t=je++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ze.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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??ze.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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??ze.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ge=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&He&&(Je=He._malloc(Ke)),Je);if(0===t||!He)return{ptr:0,count:0};let s=0,n=0;const r=He.HEAPU8,i=He.HEAPU32,o=He.HEAPF32;for(const[a,c]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=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?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!He||Ge)return;He.materialDataProvider=(e,t,s,n,r)=>{const i=Ne.get(e);if(!i)return He.HEAPU32[t>>2]=0,He.HEAPU32[s>>2]=0,He.HEAPU32[n>>2]=0,void(He.HEAPU32[r>>2]=0);He.HEAPU32[t>>2]=i.shader,He.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=et(i.uniforms);He.HEAPU32[n>>2]=o,He.HEAPU32[r>>2]=a},Ge=!0}const st={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 nt{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 rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.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:qe.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 it=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 ot(e,t){it.set(e,t)}function at(e){const t=it.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 ct(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,Z,{value:n.name}),!1!==n.visible)for(const s of n.components)ut(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 lt(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=it.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,u=new Map,h=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);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.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=it.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]=h.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,Z,{value:s.name}),!1!==s.visible)for(const n of s.components)ut(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 ut(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=D(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 ht(e,t){const s=e.getEntitiesWithComponents([X]);for(const n of s){const s=e.get(n,X);s&&(s.aspectRatio=t,e.insert(n,X,s))}}function dt(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);if(s&&s.value===t)return n}return null}const ft=[{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}],pt={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"},_t=new Map,gt=new Set;for(const e of ft)for(const t of e.extensions)_t.set(t,e),gt.add(t);function mt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function yt(e){return _t.get(mt(e))}function wt(e){return yt(e)?.editorType??"unknown"}function xt(e){return yt(e)?.addressableType??null}function vt(e){for(const t of ft)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function bt(e){return gt.has(e.toLowerCase())}function St(){return gt}function Pt(e){return"string"==typeof e&&(!!e.includes("/")&&bt(mt(e)))}function Ct(){const e=[];for(const t of ft)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Tt(){return Ct().map(e=>({type:"suffix",value:e}))}function Et(e){return pt[e.toLowerCase()]}function Mt(e){const t=yt(e);return t?.wechatPackInclude??!1}class At{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(m,m),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new rt(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(),qe.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),u="binary"===yt(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,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=yt(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 lt(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 qe.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 qe.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 Rt=ce(null,"Assets");class It{build(e){const t=e.wasmModule;t?e.insertResource(Rt,new At(t)):console.warn("AssetPlugin: No WASM module available")}}const Ft=new It;class kt{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 Bt(e,t){const s=e.getResource(Rt);s&&s.registerEmbeddedAssets(t)}async function Ut(e,t,s){const{entities:n,rootId:r}=await Lt(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 lt(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 $t=10;async function Lt(e,t,s,n,r,i=0){if(i>$t)throw new Error(`Prefab nesting depth exceeded ${$t}. 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 Lt(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),u=n.prefabEntityId===e.rootEntityId,h={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};Dt(h,t),c.push(h)}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 Dt(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 zt{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 Ut(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ot=ce(null,"Prefabs");class Ht{constructor(){this.name="PrefabsPlugin",this.dependencies=[Rt]}build(e){const t=e.getResource(Rt);e.insertResource(Ot,new zt(e.world,t))}}const Wt=new Ht;let jt=null,Nt=0,Vt=0,Xt=0;const Yt=new Float32Array(256);function qt(e){jt=e,Nt=jt._malloc(64),Vt=jt._malloc(64),Xt=jt._malloc(1024)}function Gt(){jt&&(Nt&&(jt._free(Nt),Nt=0),Vt&&(jt._free(Vt),Vt=0),Xt&&(jt._free(Xt),Xt=0)),jt=null}function Jt(){if(!jt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return jt}const Kt={r:1,g:1,b:1,a:1},Qt={begin(e){const t=Jt();t.HEAPF32.set(e,Nt/4),t.draw_begin(Nt)},end(){Jt().draw_end()},line(e,t,s,n=1){Jt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Jt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Jt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Jt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Jt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Kt){Jt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Kt){Jt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Jt().draw_setLayer(e)},setDepth(e){Jt().draw_setDepth(e)},getDrawCallCount:()=>jt?jt.draw_getDrawCallCount():0,getPrimitiveCount:()=>jt?jt.draw_getPrimitiveCount():0,setBlendMode(e){Jt().draw_setBlendMode(e)},setDepthTest(e){Jt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Jt();n.HEAPF32.set(s,Vt/4),n.draw_mesh(e,t,Vt)},drawMeshWithMaterial(e,t,s){const n=Jt(),r=qe.get(t);if(!r)return;if(Qt.setBlendMode(r.blendMode),Qt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Qt.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Vt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=es(t);if(!(n<0)){if(Oe(s))Yt[i++]=10,Yt[i++]=n,Yt[i++]=s.slot??e++,Yt[i++]=s.textureId;else if("number"==typeof s)Yt[i++]=1,Yt[i++]=n,Yt[i++]=s;else if(Array.isArray(s)){Yt[i++]=s.length,Yt[i++]=n;for(let e=0;e<s.length;e++)Yt[i++]=s[e]}else"w"in s?(Yt[i++]=4,Yt[i++]=n,Yt[i++]=s.x,Yt[i++]=s.y,Yt[i++]=s.z,Yt[i++]=s.w):"z"in s?(Yt[i++]=3,Yt[i++]=n,Yt[i++]=s.x,Yt[i++]=s.y,Yt[i++]=s.z):(Yt[i++]=2,Yt[i++]=n,Yt[i++]=s.x,Yt[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(Yt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Xt/4),n.draw_meshWithUniforms(e,r.shader,Vt,Xt,i)):n.draw_mesh(e,r.shader,Vt)}},Zt={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};function es(e){return Zt[e]??-1}const ts=new Map;function ss(e,t,s){ts.set(e,{fn:t,scene:s??""})}function ns(e){ts.delete(e)}function rs(){ts.clear()}var is;!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"}(is||(is={}));let os=null,as=0,cs=0,ls=0;function us(e){os=e,as=os._malloc(262144),cs=os._malloc(65536),ls=os._malloc(256)}function hs(){os&&(as&&os._free(as),cs&&os._free(cs),ls&&os._free(ls),as=0,cs=0,ls=0),os=null}function ds(){if(!os)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return os}const fs={create(e){const t=ds(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,as/4);const 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,ls,r).set(i),t.geometry_init(s,as,n,ls,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,cs,n).set(e.indices),t.geometry_setIndices16(s,cs,n)}else{new Uint32Array(t.HEAPU8.buffer,cs,n).set(e.indices),t.geometry_setIndices32(s,cs,n)}}return s},updateVertices(e,t,s=0){const n=ds(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,as/4),n.geometry_updateVertices(e,as,r,s)},release(e){e>0&&ds().geometry_release(e)},isValid:e=>!(!os||e<=0)&&os.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return fs.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:is.Float2},{name:"a_texCoord",type:is.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 fs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:is.Float2},{name:"a_texCoord",type:is.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 fs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:is.Float2},{name:"a_texCoord",type:is.Float2}],indices:new Uint16Array(o)})}};let ps=null;function _s(e){ps=e}function gs(){ps&&ys.isInitialized()&&ys.shutdown(),ps=null}function ms(){if(!ps)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ps}const ys={init:(e,t)=>ms().postprocess_init(e,t),shutdown(){ms().postprocess_shutdown()},resize(e,t){ms().postprocess_resize(e,t)},addPass:(e,t)=>ms().postprocess_addPass(e,t),removePass(e){ms().postprocess_removePass(e)},setEnabled(e,t){ms().postprocess_setPassEnabled(e,t)},isEnabled:e=>ms().postprocess_isPassEnabled(e),setUniform(e,t,s){ms().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){ms().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){ms().postprocess_begin()},end(){ms().postprocess_end()},getPassCount:()=>ms().postprocess_getPassCount(),isInitialized:()=>!!ps&&ps.postprocess_isInitialized(),setBypass(e){ms().postprocess_setBypass(e)},isBypassed:()=>!ps||ps.postprocess_isBypassed(),createBlur:()=>qe.createShader(ws,"#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:()=>qe.createShader(ws,"#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:()=>qe.createShader(ws,"#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:()=>qe.createShader(ws,"#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")},ws="#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 xs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(xs||(xs={}));let vs=null,bs=0;function Ss(e){vs=e,bs=vs._malloc(64)}function Ps(){vs&&bs&&(vs._free(bs),bs=0),vs=null}const Cs={init(e,t){vs?.renderer_init(e,t)},resize(e,t){vs?.renderer_resize(e,t)},begin(e,t){vs&&bs&&(vs.HEAPF32.set(e,bs/4),vs.renderer_begin(bs,t??0))},flush(){vs?.renderer_flush()},end(){vs?.renderer_end()},submitSprites(e){vs&&vs.renderer_submitSprites(e._cpp)},submitBitmapText(e){vs&&vs.renderer_submitBitmapText(e._cpp)},submitSpine(e){vs&&vs.renderer_submitSpine?.(e._cpp)},setStage(e){vs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>vs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){vs?.renderer_releaseTarget(e)},getTargetTexture:e=>vs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>vs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){vs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){vs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){vs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){vs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>vs?vs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>vs?{drawCalls:vs.renderer_getDrawCalls(),triangles:vs.renderer_getTriangles(),sprites:vs.renderer_getSprites(),text:vs.renderer_getText(),spine:vs.renderer_getSpine?.()??0,meshes:vs.renderer_getMeshes(),culled:vs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ts=null;function Es(e){Ts=e}function Ms(){Ts=null}const As={enable(){Ts?.gl_enableErrorCheck(!0)},disable(){Ts?.gl_enableErrorCheck(!1)},check:e=>Ts?.gl_checkErrors(e)??0,diagnose(){Ts?.renderer_diagnose()}};class Rs{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_||(Cs.resize(n,r),ys.isInitialized()&&ys.getPassCount()>0&&ys.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,i):Cs.submitSpine(t),Cs.flush(),this.executeDrawCallbacks(s,i),Cs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=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,i):Cs.submitSpine(t),Cs.flush(),this.executeDrawCallbacks(s,i),Cs.end()}executeDrawCallbacks(e,t){const s=ts;if(s.size>0){Qt.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)}Qt.end();for(const e of n)ns(e)}}}const Is="__scene_transition_overlay__",Fs={r:0,g:0,b:0,a:1};class ks{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Bs{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,ee,{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=ys.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ys.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,ee)){const s=this.app_.world.get(e,ee);s.persistent=t,this.app_.world.insert(e,ee,s)}}}class Us{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??.3,r=t.color??Fs;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ss(Is,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;Qt.setLayer(9999),Qt.setDepth(9999),Qt.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,ns(Is)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ns(Is),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ks(t);this.scenes_.set(e,s);const n=new Bs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Rt)?this.app_.getResource(Rt):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(Rt)&&(t.assetServer=this.app_.getResource(Rt));const n=await lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ls(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 ks(t);this.scenes_.set(e,s);const n=new Bs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Rt)?this.app_.getResource(Rt):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(Rt)&&(t.assetServer=this.app_.getResource(Rt));const n=await lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ls(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,ee)){if(this.app_.world.get(e,ee).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())ns(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ys.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,V)){const s=this.app_.world.get(e,V);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,V,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,V)){const s=this.app_.world.get(e,V),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,V,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ys.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 $s=ce(null,"SceneManager");function Ls(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource($s).getSceneStatus(t)&&s._fn(...n)}}}const Ds=Se([ue($s),le(fe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),zs={name:"SceneManager",build(e){const t=new Us(e);e.insertResource($s,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource($s),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ve.Startup,s),e.addSystemToSchedule(ve.Last,Ds)}};class Os{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,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,.25);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(ve.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ve.FixedPreUpdate),this.runSchedule(ve.FixedUpdate),this.runSchedule(ve.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(ve.PreUpdate),this.runSchedule(ve.Update),this.runSchedule(ve.PostUpdate),this.runSchedule(ve.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Le,this.resources_=new de;for(const e of Object.values(ve))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Os}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}addSystem(e){return this.addSystemToSchedule(ve.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ve.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_}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}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=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($s).register(e),this}setInitialScene(e){return this.getResource($s).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Me(this.world_,this.resources_),this.resources_.insert(fe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ve.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,rs();const e=[Ms,Ps,gs,hs,Xe,Gt];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){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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(fe);t.delta=e,t.elapsed+=e,t.frameCount++}}function Hs(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 Ws=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function js(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case W.FixedWidth:return i;case W.FixedHeight:return o;case W.Expand:return Math.max(i,o);case W.Shrink:return Math.min(i,o);case W.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Ns(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,ee);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 u,h=0,d=0;if(r.projectionType===O.Orthographic){if(d=r.orthoSize,c){d=js(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=Xs(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=qs(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Js(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(Qs(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Vs=new Float32Array(16);function Xs(e,t,s,n,r,i){const o=Vs;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 Ys=new Float32Array(16);function qs(e,t,s,n){const r=Ys;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 Gs=new Float32Array(16);function Js(e,t,s){const n=Gs;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 Ks=new Float32Array(16);function Qs(e,t){const s=Ks;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 Zs,en,tn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Zs||(Zs={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(en||(en={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(tn||(tn={}));const sn=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Zs.Left,verticalAlign:en.Top,wordWrap:!0,overflow:tn.Visible,lineHeight:1.2}),nn=R("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 rn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(m,m),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),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===tn.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),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===tn.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 en.Top:x=u;break;case en.Middle:x=(p-w)/2;break;case en.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case Zs.Left:n=u;break;case Zs.Center:n=f/2;break;case Zs.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===tn.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 Zs.Left:return"left";case Zs.Center:return"center";case Zs.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function on(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 an(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 cn{build(e){L("Text",sn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new rn(t),n=e.world,r=new Map;e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{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,nn)?n.get(t,nn):null,o=r.get(t);if(o&&!an(o,e,i))continue;n.has(t,V)||n.insert(t,V,{texture:w,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,V);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,V,c),r.set(t,on(e,i))}}))}}const ln=new cn,un=R("UIMask",{enabled:!0});function hn(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 dn(e,t,s,n,r,i,o,a,c,l,u){const h=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)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function fn(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],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;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+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function pn(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],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function _n(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 gn(e,t,s,n,r,i,o){if(!e.has(t,nn)||!e.has(t,N))return null;const a=e.get(t,nn),c=e.get(t,N),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return dn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function mn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([un]);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,un).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,G);){const e=t.get(n,G);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=gn(t,s,r,i,o,a,c);e&&(n=hn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=gn(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class yn{build(e){if(L("UIMask",un),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(mn(e.wasmModule,e.world))}}const wn=new yn,xn=R("Interactable",{enabled:!0}),vn=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var bn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(bn||(bn={}));const Sn=R("Button",{state:bn.Normal,transition:null});class Pn{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 Cn=ce(new Pn,"UIEvents"),Tn=I("ScreenSpace");function En(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,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+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=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Mn(e,t,s,n,r,i){if(!e.has(t,nn))return;const o=e.get(t,nn),a=En(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,j);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,j,c),!e.has(t,J))return;const l=e.get(t,J);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Mn(e,t,a.rect,a.centerX,a.centerY,!1)}class An{build(e){L("UIRect",nn);const t=e.world;e.addSystemToSchedule(ve.PreUpdate,Se([le(De)],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([Tn,nn,j]);for(const e of i)Mn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Rn=new An,In=new Float32Array(16),Fn=new Float32Array(16);let kn=!0,Bn=1;class Un{build(e){L("Interactable",xn),L("Button",Sn);const t=e.world,s=new Pn;e.insertResource(Cn,s);let n=null,r=null;Bn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(ve.PreUpdate,Se([le(Re),le(De)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([vn]);for(const e of o){const s=t.get(e,vn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Bn,c=i.screenH-e.mouseY*Bn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Fn[s]!==e[s]){t=!0;break}t&&(Fn.set(e),kn=!0)}(i.viewProjection),kn&&(fn(i.viewProjection,In),kn=!1);const l=pn(a,c,In,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([xn,nn,N]);let h=null,d=-1/0;for(const e of u){t.has(e,vn)||t.insert(e,vn);if(!t.get(e,xn).enabled)continue;const s=t.get(e,N),n=t.get(e,nn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(_n(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,V)&&(s=t.get(e,V).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,vn)){t.get(n,vn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,vn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,vn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,vn)){const e=t.get(r,vn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(ve.Update,Se([],()=>{const e=t.getEntitiesWithComponents([Sn]);for(const s of e){if(t.has(s,xn)||t.insert(s,xn,{enabled:!0}),!t.has(s,vn))continue;const e=t.get(s,vn),n=t.get(s,Sn),r=t.get(s,xn),i=n.state;if(r.enabled?e.pressed?n.state=bn.Pressed:e.hovered?n.state=bn.Hovered:n.state=bn.Normal:n.state=bn.Disabled,i!==n.state&&n.transition&&t.has(s,V)){const e=t.get(s,V),r=n.transition;switch(n.state){case bn.Normal:e.color={...r.normalColor};break;case bn.Hovered:e.color={...r.hoveredColor};break;case bn.Pressed:e.color={...r.pressedColor};break;case bn.Disabled:e.color={...r.disabledColor}}t.insert(s,V,e)}}},{name:"ButtonSystem"}))}}const $n=new Un,Ln=R("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 Dn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",Ln);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(m,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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||v()},_=()=>{a=!0},g=()=>{a=!1,v()},y=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,Ln);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Cn).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())},x=()=>{if(null!==o&&s.valid(o)&&s.has(o,Ln)){const e=s.get(o,Ln);e.focused=!1,e.dirty=!0}o=null};function v(){if(null===o||!s.valid(o))return;const t=s.get(o,Ln);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(Cn).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,Ln);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,Ln)){const e=s.get(o,Ln);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=On(Math.max(r.width,a)),r.height=On(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?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=zn(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=zn(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 g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,V);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,V,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",g),f.addEventListener("keydown",y),f.addEventListener("blur",x),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",g),f.removeEventListener("keydown",y),f.removeEventListener("blur",x),f.remove()},e.addSystemToSchedule(ve.PreUpdate,Se([le(Cn)],e=>{const t=s.getEntitiesWithComponents([Ln,xn]);for(const e of t){if(!s.has(e,vn))continue;if(s.get(e,vn).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([xn]);for(const t of e){if(s.has(t,Ln))continue;if(!s.has(t,vn))continue;if(s.get(t,vn).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,Ln)))){s.get(o,Ln).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ln)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ln,nn]);for(const e of a){const t=s.get(e,Ln);if(!t.dirty)continue;const n=s.get(e,nn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,V)||s.insert(e,V,{texture:w,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 zn(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 On(e){let t=1;for(;t<e;)t*=2;return t}const Hn=new Dn;async function Wn(e,t,s){const n=e.getResource($s);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function jn(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 Nn=ce({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Vn=ce(null,"PhysicsAPI");function Xn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Yn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class qn{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(Nn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=jn(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([Y]);for(const s of t){const t=e.world.get(s,Y);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(ve.PostUpdate,Se([le(fe)],a=>{const c=o.getEntitiesWithComponents([se,j,N]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,se),c=o.get(r,N);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=Xn(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),Gn(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===oe.Kinematic){const e=Xn(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 u=e.world.get(o,j);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,G)){const t=e.world.get(o,G);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const s=e.world.get(t.entity,N),n=Xn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=Yn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,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 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=[],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(Nn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Vn,Jn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Gn(e,t,s){const n=e.world;if(n.has(s,ne)){const e=n.get(s,ne);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,re)){const e=n.get(s,re);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,ie)){const e=n.get(s,ie);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 Jn{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(Jn.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 Kn(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 Qn(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 Zn(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,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function er(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]=Kn(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={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=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),u="binary"===yt(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Qn(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=Kn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new qn("",{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=yt(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),u=Kn(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,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=qe.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=qe.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n),p=ct(e.world,s);if(c&&e.hasResource($s))for(const t of p.values())e.world.insert(t,ee,{scene:c,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,V);r&&(r.texture=s[n.data.texture]||0,e.insert(t,V,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const i=e.get(t,K);i&&(i.font=r,e.insert(t,K,i))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,V);s&&(s.material=r,e.insert(t,V,s))}else if("SpineAnimation"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}}}}(e.world,s,f,p),r&&h){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}(h,s,u,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,Q)?l.get(i,Q):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,N)){const e=Zn(l.get(i,N),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),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(Rt);t&&t.setAddressableManifest(a)}}function tr(e,t,s){return{name:e,data:t,async setup(){await er(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class sr{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"===yt(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=yt(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 nr="__preview__";class rr{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($s);t.register({name:nr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(nr),this.loadPromise_=t.load(nr).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 sr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await er(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,nr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([X]);for(const n of s){if(e.get(n,X).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([Y]);for(const r of n){const n=e.get(r,Y);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($s).getScene(nr),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,j,o);const a={isActive:!0,projectionType:O.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:H.ColorAndDepth};e.insert(i,X,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($s);await e.switchTo(nr),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 ir={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),ir.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 or=!1;function ar(e){or=e}function cr(){return or}function lr(){return!or}var ur;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ur||(ur={}));class hr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ur[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ur.Debug:console.debug(t,s);break;case ur.Info:console.log(t,s);break;case ur.Warn:console.warn(t,s);break;case ur.Error:console.error(t,s)}}}class dr{constructor(){this.handlers_=[],this.minLevel_=ur.Info,this.addHandler(new hr)}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(ur.Debug,e,t,s)}info(e,t,s){this.log(ur.Info,e,t,s)}warn(e,t,s){this.log(ur.Warn,e,t,s)}error(e,t,s){this.log(ur.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 fr=new dr;function pr(){return fr}function _r(e){fr.setMinLevel(e)}function gr(e,t,s){fr.debug(e,t,s)}function mr(e,t,s){fr.info(e,t,s)}function yr(e,t,s){fr.warn(e,t,s)}function wr(e,t,s){fr.error(e,t,s)}const xr=[ln,wn,Rn,$n,Hn];function vr(e,t){return function(e,t){const s=Os.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),qt(e),Ve(e),us(e),_s(e),Ss(e),Es(e);const r=new Rs;s.pipeline_=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=Ns(e,n,t,r));const o=s.getResource(De);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(De,{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;Cs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Cs.resize(t,c),ys.isInitialized()&&ys.getPassCount()>0&&!ys.isBypassed()&&ys.resize(t,c),s.hasResource($s)){const e=s.getResource($s).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Ns(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Ws,width:t,height:c,elapsed:u});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:u})}Cs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(ve.First,c),s.addSystemToSchedule(ve.Last,l),s.addPlugin(Ft),s.addPlugin(Wt),s.addPlugin(Fe),s.addPlugin(zs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:xr,...t})}e=f;export{Os as App,It as AssetPlugin,kt as AssetRefCounter,At as AssetServer,Rt as Assets,nt as AsyncCache,K as BitmapText,ze as BlendMode,oe as BodyType,ne as BoxCollider,Sn as Button,bn as ButtonState,X as Camera,Y as Canvas,ie as CapsuleCollider,J as Children,re as CircleCollider,H as ClearFlags,ye as Commands,xe as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,g as DEFAULT_PIXELS_PER_UNIT,m as DEFAULT_TEXT_CANVAS_SIZE,is as DataType,Qt as Draw,we as EntityCommands,As as GLDebug,fs as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Re as Input,Ie as InputPlugin,Ae as InputState,xn as Interactable,j as LocalTransform,ur as LogLevel,dr as Logger,qe as Material,rt as MaterialLoader,pe as Mut,Z as Name,G as Parent,Jn as Physics,Nn as PhysicsEvents,qn as PhysicsPlugin,ys as PostProcess,zt as PrefabServer,Ot as Prefabs,Ht as PrefabsPlugin,rr as PreviewPlugin,O as ProjectionType,ge as Query,me as QueryInstance,Rs as RenderPipeline,xs as RenderStage,ir as RenderTexture,Cs as Renderer,le as Res,ue as ResMut,se as RigidBody,W as ScaleMode,$s as SceneManager,Us as SceneManagerState,ee as SceneOwner,ve as Schedule,Tn as ScreenSpace,st as ShaderSources,Q as SpineAnimation,V as Sprite,Me as SystemRunner,sn as Text,Zs as TextAlign,Ln as TextInput,Dn as TextInputPlugin,tn as TextOverflow,cn as TextPlugin,rn as TextRenderer,en as TextVerticalAlign,fe as Time,De as UICameraInfo,Pn as UIEventQueue,Cn as UIEvents,vn as UIInteraction,Un as UIInteractionPlugin,An as UILayoutPlugin,un as UIMask,yn as UIMaskPlugin,nn as UIRect,q as Velocity,sr as WebAssetProvider,Le as World,N as WorldTransform,Te as addStartupSystem,Ce as addSystem,Ee as addSystemToSchedule,Ft as assetPlugin,rs as clearDrawCallbacks,k as clearUserComponents,P as color,En as computeUIRectLayout,mn as createMaskProcessor,tr as createRuntimeSceneConfig,vr as createWebApp,gr as debug,R as defineComponent,ce as defineResource,Se as defineSystem,I as defineTag,wr as error,dt as findEntityByName,Hs as flushPendingSystems,xt as getAddressableType,vt as getAddressableTypeByEditorType,St as getAllAssetExtensions,Et as getAssetMimeType,yt as getAssetTypeEntry,D as getComponent,at as getComponentAssetFields,te as getComponentDefaults,Ct as getCustomExtensions,wt as getEditorType,pr as getLogger,t as getPlatform,n as getPlatformType,F as getUserComponent,Tt as getWeChatPackOptions,mr as info,qt as initDrawAPI,Es as initGLDebugAPI,us as initGeometryAPI,Ve as initMaterialAPI,_s as initPostProcessAPI,Ss as initRendererAPI,Fe as inputPlugin,Ut as instantiatePrefab,hn as intersectRects,fn as invertMatrix4,U as isBuiltinComponent,Mt as isCustomExtension,cr as isEditor,bt as isKnownAssetExtension,s as isPlatformInitialized,lr as isRuntime,Oe as isTextureRef,r as isWeChat,i as isWeb,ut as loadComponent,jn as loadPhysicsModule,er as loadRuntimeScene,ct as loadSceneData,lt as loadSceneWithAssets,Pt as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,_n as pointInWorldRect,Wt as prefabsPlugin,C as quat,L as registerComponent,ot as registerComponentAssetFields,ss as registerDrawCallback,Bt as registerEmbeddedAssets,tt as registerMaterialCallback,zs as sceneManagerPlugin,pn as screenToWorld,ar as setEditorMode,_r as setLogLevel,Gt as shutdownDrawAPI,Ms as shutdownGLDebugAPI,hs as shutdownGeometryAPI,Xe as shutdownMaterialAPI,gs as shutdownPostProcessAPI,Ps as shutdownRendererAPI,Hn as textInputPlugin,ln as textPlugin,Wn as transitionTo,$n as uiInteractionPlugin,Rn as uiLayoutPlugin,wn as uiMaskPlugin,xr as uiPlugins,ns as unregisterDrawCallback,ht as updateCameraAspectRatio,v as vec2,b as vec3,S as vec4,yr as warn,dn as worldRectToScreen,Ls as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 9c6f07502..7f3b2b12d 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -472,6 +472,7 @@ declare class World {
getWorldVersion(): number;
beginIteration(): void;
endIteration(): void;
+ resetIterationDepth(): void;
isIterating(): boolean;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
@@ -492,7 +493,7 @@ declare class World {
private removeScript;
private getStorage;
resetQueryPool(): void;
- getEntitiesWithComponents(components: AnyComponentDef[]): Entity[];
+ getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
/**
@@ -692,6 +693,8 @@ declare class App {
private physicsModule_?;
private readonly installed_plugins_;
private error_handler_;
+ private system_error_handler_;
+ private frame_paused_;
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
@@ -714,6 +717,7 @@ declare class App {
get world(): World;
setFixedTimestep(timestep: number): this;
onError(handler: (error: unknown, systemName: string) => void): this;
+ onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
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 d7a01eb0f..025955b30 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -427,6 +427,7 @@ declare class World {
getWorldVersion(): number;
beginIteration(): void;
endIteration(): void;
+ resetIterationDepth(): void;
isIterating(): boolean;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
@@ -447,7 +448,7 @@ declare class World {
private removeScript;
private getStorage;
resetQueryPool(): void;
- getEntitiesWithComponents(components: AnyComponentDef[]): Entity[];
+ getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
/**
@@ -767,6 +768,8 @@ declare class App {
private physicsModule_?;
private readonly installed_plugins_;
private error_handler_;
+ private system_error_handler_;
+ private frame_paused_;
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
@@ -789,6 +792,7 @@ declare class App {
get world(): World;
setFixedTimestep(timestep: number): this;
onError(handler: (error: unknown, systemName: string) => void): this;
+ onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
index 4d374df7e..cad2a5796 100644
--- a/editor/src/builder/BuildService.ts
+++ b/editor/src/builder/BuildService.ts
@@ -125,17 +125,21 @@ export class BuildService {
progress.log('info', `Build completed in ${formatDuration(duration)}`);
if (useCache && artifact.atlasInputHash) {
- const cacheData = await this.cache_.loadCache(config.id || 'default') || {
- version: '1.3',
- configId: config.id || 'default',
- timestamp: Date.now(),
- files: {},
- };
-
- cacheData.atlasPages = this.cache_.serializeAtlasPages(artifact.atlasResult.pages);
- cacheData.atlasInputHash = artifact.atlasInputHash;
-
- await this.cache_.saveCache(cacheData);
+ try {
+ const cacheData = await this.cache_.loadCache(config.id || 'default') || {
+ version: '1.3',
+ configId: config.id || 'default',
+ timestamp: Date.now(),
+ files: {},
+ };
+
+ cacheData.atlasPages = this.cache_.serializeAtlasPages(artifact.atlasResult.pages);
+ cacheData.atlasInputHash = artifact.atlasInputHash;
+
+ await this.cache_.saveCache(cacheData);
+ } catch (err) {
+ console.error('Failed to save build cache:', err);
+ }
}
if (this.history_) {
diff --git a/editor/src/commands/PrefabCommands.ts b/editor/src/commands/PrefabCommands.ts
index 52f018445..8daca1e15 100644
--- a/editor/src/commands/PrefabCommands.ts
+++ b/editor/src/commands/PrefabCommands.ts
@@ -358,7 +358,9 @@ export class ApplyPrefabOverridesCommand extends BaseCommand {
this.updateOtherInstances(instanceEntities);
- this.onSave_(this.prefab_, this.prefabPath_);
+ this.onSave_(this.prefab_, this.prefabPath_).catch(err => {
+ console.error('Failed to save prefab:', err);
+ });
}
undo(): void {
diff --git a/editor/src/ui/Splitter.ts b/editor/src/ui/Splitter.ts
index de11de9c5..d1923458c 100644
--- a/editor/src/ui/Splitter.ts
+++ b/editor/src/ui/Splitter.ts
@@ -27,8 +27,8 @@ export class Splitter {
private startLeftSize_ = 0;
private startRightSize_ = 0;
private onResize_?: (leftSize: number, rightSize: number) => void;
- private boundOnMouseMove_: (e: MouseEvent) => void;
- private boundOnMouseUp_: () => void;
+ private boundOnMouseMove_!: (e: MouseEvent) => void;
+ private boundOnMouseUp_!: () => void;
constructor(options: SplitterOptions) {
this.container_ = options.container;
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.ts
index 5d678b31a..da67d550a 100644
--- a/sdk/src/sceneManager.ts
+++ b/sdk/src/sceneManager.ts
@@ -167,6 +167,7 @@ export class SceneManagerState {
private activeScene_: string | null = null;
private initialScene_: string | null = null;
private transition_: TransitionState | null = null;
+ private loadPromises_ = new Map<string, Promise<SceneContext>>();
constructor(app: App) {
this.app_ = app;
@@ -189,6 +190,11 @@ export class SceneManagerState {
}
async switchTo(name: string, options?: TransitionOptions): Promise<void> {
+ if (this.transition_) {
+ console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${name}")`);
+ return;
+ }
+
const transition = options?.transition ?? 'none';
if (transition === 'fade') {
@@ -273,6 +279,9 @@ export class SceneManagerState {
async load(name: string): Promise<SceneContext> {
if (this.scenes_.has(name)) {
const existing = this.scenes_.get(name)!;
+ if (existing.status === 'loading') {
+ return this.loadPromises_.get(name)!;
+ }
existing.status = 'running';
this.activeScene_ = name;
return this.contexts_.get(name)!;
@@ -289,57 +298,69 @@ export class SceneManagerState {
const ctx = new SceneContextImpl(instance, this.app_);
this.contexts_.set(name, ctx);
- let sceneData = config.data;
- if (!sceneData && config.path) {
- const assetServer = this.app_.hasResource(Assets)
- ? this.app_.getResource(Assets)
- : null;
- if (assetServer) {
- sceneData = await assetServer.loadJson<SceneData>(config.path);
- } else {
- const response = await fetch(config.path);
- sceneData = await response.json() as SceneData;
+ const loadPromise = (async (): Promise<SceneContext> => {
+ let sceneData = config.data;
+ if (!sceneData && config.path) {
+ const assetServer = this.app_.hasResource(Assets)
+ ? this.app_.getResource(Assets)
+ : null;
+ if (assetServer) {
+ sceneData = await assetServer.loadJson<SceneData>(config.path);
+ } else {
+ const response = await fetch(config.path);
+ sceneData = await response.json() as SceneData;
+ }
}
- }
- if (sceneData) {
- const loadOptions: SceneLoadOptions = {};
- if (this.app_.hasResource(Assets)) {
- loadOptions.assetServer = this.app_.getResource(Assets);
+ if (sceneData) {
+ const loadOptions: SceneLoadOptions = {};
+ if (this.app_.hasResource(Assets)) {
+ loadOptions.assetServer = this.app_.getResource(Assets);
+ }
+ const entityMap = await loadSceneWithAssets(
+ this.app_.world, sceneData, loadOptions
+ );
+
+ for (const entity of entityMap.values()) {
+ instance.entities.add(entity);
+ this.app_.world.insert(entity, SceneOwner, {
+ scene: name,
+ persistent: false,
+ });
+ }
}
- const entityMap = await loadSceneWithAssets(
- this.app_.world, sceneData, loadOptions
- );
-
- for (const entity of entityMap.values()) {
- instance.entities.add(entity);
- this.app_.world.insert(entity, SceneOwner, {
- scene: name,
- persistent: false,
- });
+
+ if (config.systems) {
+ for (const { schedule, system } of config.systems) {
+ const wrapped = wrapSceneSystem(this.app_, name, system);
+ this.app_.addSystemToSchedule(schedule, wrapped);
+ }
}
- }
- if (config.systems) {
- for (const { schedule, system } of config.systems) {
- const wrapped = wrapSceneSystem(this.app_, name, system);
- this.app_.addSystemToSchedule(schedule, wrapped);
+ if (config.setup) {
+ await config.setup(ctx);
}
- }
- if (config.setup) {
- await config.setup(ctx);
+ instance.status = 'running';
+ this.activeScene_ = name;
+ this.loadOrder_.push(name);
+ return ctx;
+ })();
+
+ this.loadPromises_.set(name, loadPromise);
+ try {
+ return await loadPromise;
+ } finally {
+ this.loadPromises_.delete(name);
}
-
- instance.status = 'running';
- this.activeScene_ = name;
- this.loadOrder_.push(name);
- return ctx;
}
async loadAdditive(name: string): Promise<SceneContext> {
if (this.scenes_.has(name)) {
const existing = this.scenes_.get(name)!;
+ if (existing.status === 'loading') {
+ return this.loadPromises_.get(name)!;
+ }
existing.status = 'running';
this.additiveScenes_.add(name);
return this.contexts_.get(name)!;
@@ -356,52 +377,61 @@ export class SceneManagerState {
const ctx = new SceneContextImpl(instance, this.app_);
this.contexts_.set(name, ctx);
- let sceneData = config.data;
- if (!sceneData && config.path) {
- const assetServer = this.app_.hasResource(Assets)
- ? this.app_.getResource(Assets)
- : null;
- if (assetServer) {
- sceneData = await assetServer.loadJson<SceneData>(config.path);
- } else {
- const response = await fetch(config.path);
- sceneData = await response.json() as SceneData;
+ const loadPromise = (async (): Promise<SceneContext> => {
+ let sceneData = config.data;
+ if (!sceneData && config.path) {
+ const assetServer = this.app_.hasResource(Assets)
+ ? this.app_.getResource(Assets)
+ : null;
+ if (assetServer) {
+ sceneData = await assetServer.loadJson<SceneData>(config.path);
+ } else {
+ const response = await fetch(config.path);
+ sceneData = await response.json() as SceneData;
+ }
}
- }
- if (sceneData) {
- const loadOptions: SceneLoadOptions = {};
- if (this.app_.hasResource(Assets)) {
- loadOptions.assetServer = this.app_.getResource(Assets);
+ if (sceneData) {
+ const loadOptions: SceneLoadOptions = {};
+ if (this.app_.hasResource(Assets)) {
+ loadOptions.assetServer = this.app_.getResource(Assets);
+ }
+ const entityMap = await loadSceneWithAssets(
+ this.app_.world, sceneData, loadOptions
+ );
+
+ for (const entity of entityMap.values()) {
+ instance.entities.add(entity);
+ this.app_.world.insert(entity, SceneOwner, {
+ scene: name,
+ persistent: false,
+ });
+ }
}
- const entityMap = await loadSceneWithAssets(
- this.app_.world, sceneData, loadOptions
- );
-
- for (const entity of entityMap.values()) {
- instance.entities.add(entity);
- this.app_.world.insert(entity, SceneOwner, {
- scene: name,
- persistent: false,
- });
+
+ if (config.systems) {
+ for (const { schedule, system } of config.systems) {
+ const wrapped = wrapSceneSystem(this.app_, name, system);
+ this.app_.addSystemToSchedule(schedule, wrapped);
+ }
}
- }
- if (config.systems) {
- for (const { schedule, system } of config.systems) {
- const wrapped = wrapSceneSystem(this.app_, name, system);
- this.app_.addSystemToSchedule(schedule, wrapped);
+ if (config.setup) {
+ await config.setup(ctx);
}
- }
- if (config.setup) {
- await config.setup(ctx);
+ instance.status = 'running';
+ this.additiveScenes_.add(name);
+ this.loadOrder_.push(name);
+ return ctx;
+ })();
+
+ this.loadPromises_.set(name, loadPromise);
+ try {
+ return await loadPromise;
+ } finally {
+ this.loadPromises_.delete(name);
}
-
- instance.status = 'running';
- this.additiveScenes_.add(name);
- this.loadOrder_.push(name);
- return ctx;
}
async unload(name: string, options?: TransitionOptions): Promise<void> {
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 646e1d683..cc7e0e484 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -446,6 +446,7 @@ public:
}
entities = std::move(sortedEntities);
components = std::move(sortedComponents);
+ pool->rebuildSparse();
}
// =========================================================================
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index 997dcda9e..ee49735ab 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -309,6 +309,23 @@ public:
components_.clear();
}
+ void rebuildSparse() {
+ pages_.clear();
+ for (usize i = 0; i < dense_.size(); ++i) {
+ const Entity entity = dense_[i];
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+ if (pageIndex >= pages_.size()) {
+ pages_.resize(pageIndex + 1);
+ }
+ if (!pages_[pageIndex]) {
+ pages_[pageIndex] = std::make_unique<Page>();
+ std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_ENTITY);
+ }
+ (*pages_[pageIndex])[offset] = static_cast<Entity>(i);
+ }
+ }
+
// =========================================================================
// Iteration
// =========================================================================
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index c14173f27..c37a2ba3b 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -229,6 +229,9 @@ void RenderFrame::shutdown() {
}
#ifdef ES_ENABLE_SPINE
+ if (spine_shader_handle_.isValid()) {
+ resource_manager_.releaseShader(spine_shader_handle_);
+ }
if (spine_ebo_) { glDeleteBuffers(1, &spine_ebo_); spine_ebo_ = 0; }
if (spine_vbo_) { glDeleteBuffers(1, &spine_vbo_); spine_vbo_ = 0; }
if (spine_vao_) { glDeleteVertexArrays(1, &spine_vao_); spine_vao_ = 0; }