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: run FixedUpdate schedules in main loop

esengine1cef9e9e0e74
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index d9bbfe92e..23140101e 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 r(e,r){return t().fetch(e,r)}async function s(e){return t().readTextFile(e)}async function n(e){return t().fileExists(e)}function o(e,r){return t().createCanvas(e,r)}function i(){return t().now()}function a(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,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 "${r}": ${t}`)}}let c=null;function u(){return c||(c=wx.getFileSystemManager()),c}function h(e){return new Promise((t,r)=>{u().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function d(e,t="utf-8"){return new Promise((r,s)=>{u().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e){return new Promise(t=>{u().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let f=null,m=null;function _(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function x(e,t=!0){const{width:r,height:s}=e,{ctx:n}=function(e,t){return f||(f=wx.createCanvas(),f.width=e,f.height=t,m=f.getContext("2d")),(f.width<e||f.height<t)&&(f.width=Math.max(f.width,e),f.height=Math.max(f.height,t)),{canvas:f,ctx:m}}(r,s);n.clearRect(0,0,r,s),n.save(),t&&(n.translate(0,s),n.scale(1,-1)),n.drawImage(e,0,0),n.restore();const o=n.getImageData(0,0,r,s);return{width:r,height:s,pixels:new Uint8Array(o.data.buffer)}}let g=!1;const y=new class{constructor(){this.name="wechat"}async fetch(e,t){return a(e,t)}async readFile(e){return h(e)}async readTextFile(e){return d(e)}async fileExists(e){return p(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(e,t)}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}},w=4294967295;let v=0;function S(e,t){const r=++v;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function T(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const r=T(),s=r.get(e);if(s)return s;const n=S(e,t);return r.set(e,n),b(e,t,!1),n}function P(e){return T().get(e)}function b(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function A(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function E(e){return!0===e._builtin}const R=A("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),M=A("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=A("Sprite",{texture:w,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),I=A("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),U=A("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),B=A("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),k=A("Parent",{entity:0}),z=A("Children",{entities:[]}),W=A("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),$={LocalTransform:R,WorldTransform:M,Sprite:F,Camera:I,Canvas:U,Velocity:B,Parent:k,Children:z,SpineAnimation:W};let D=0;function L(e,t){const r=++D;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class G{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 O{constructor(){this.resources_=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)}getResMut(e){return new G(this.get(e),t=>this.set(e,t))}}const N=L({delta:0,elapsed:0,frameCount:0},"Time");function V(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class H{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return V(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:s}=this.descriptor_,n=e.map(e=>this.getActualComponent(e)),o=[...n,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,l=[];try{for(const e of i){if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data);l=[];let r=!1;for(const t of s)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=n.map(t=>this.world_.get(e,t));for(const e of t)l.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}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(){return[...this]}}class X{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 r;return r=E(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),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 j{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new X(this,null)}entity(e){return new X(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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Y;exports.Schedule=void 0,(Y=exports.Schedule||(exports.Schedule={}))[Y.Startup=0]="Startup",Y[Y.First=1]="First",Y[Y.PreUpdate=2]="PreUpdate",Y[Y.Update=3]="Update",Y[Y.PostUpdate=4]="PostUpdate",Y[Y.Last=5]="Last",Y[Y.FixedPreUpdate=10]="FixedPreUpdate",Y[Y.FixedUpdate=11]="FixedUpdate",Y[Y.FixedPostUpdate=12]="FixedPostUpdate";let q=0;function K(e,t,r){const s=++q;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function J(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Q{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof j&&e.flush()}resolveParam(e){switch(e._type){case"query":return new H(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new j(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Z{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 ee=L(new Z,"Input");class te{constructor(e){this.target_=e??null}build(e){const t=new Z;e.insertResource(ee,t);const r=this.target_??document.querySelector("canvas")??document.body;document.addEventListener("keydown",e=>{t.keysDown.has(e.code)||t.keysPressed.add(e.code),t.keysDown.add(e.code)}),document.addEventListener("keyup",e=>{t.keysDown.delete(e.code),t.keysReleased.add(e.code)}),r.addEventListener("mousemove",e=>{t.mouseX=e.offsetX,t.mouseY=e.offsetY}),r.addEventListener("mousedown",e=>{const r=e.button;t.mouseButtons.add(r),t.mouseButtonsPressed.add(r)}),r.addEventListener("mouseup",e=>{const r=e.button;t.mouseButtons.delete(r),t.mouseButtonsReleased.add(r)}),r.addEventListener("touchstart",e=>{const s=e.touches[0];if(s){const e=r.getBoundingClientRect();t.mouseX=s.clientX-e.left,t.mouseY=s.clientY-e.top,t.mouseButtons.add(0),t.mouseButtonsPressed.add(0)}}),r.addEventListener("touchmove",e=>{const s=e.touches[0];if(s){const e=r.getBoundingClientRect();t.mouseX=s.clientX-e.left,t.mouseY=s.clientY-e.top}}),r.addEventListener("touchend",()=>{t.mouseButtons.delete(0),t.mouseButtonsReleased.add(0)}),r.addEventListener("wheel",e=>{t.scrollDeltaX+=e.deltaX,t.scrollDeltaY+=e.deltaY}),e.addSystemToSchedule(exports.Schedule.First,K([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const re=new te;class se{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}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,r){return E(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return E(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return E(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){E(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,s)}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let s=!0;for(const t of e)if(!this.has(r,t)){s=!1;break}s&&t.push(r)}return t}}var ne,oe,ie;exports.TextAlign=void 0,(ne=exports.TextAlign||(exports.TextAlign={}))[ne.Left=0]="Left",ne[ne.Center=1]="Center",ne[ne.Right=2]="Right",exports.TextVerticalAlign=void 0,(oe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[oe.Top=0]="Top",oe[oe.Middle=1]="Middle",oe[oe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ie=exports.TextOverflow||(exports.TextOverflow={}))[ie.Visible=0]="Visible",ie[ie.Clip=1]="Clip",ie[ie.Ellipsis=2]="Ellipsis";const ae=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class le{constructor(e){this.cache=new Map,this.module=e,this.canvas=o(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>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(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.x),_=Math.round(255*e.color.y),x=Math.round(255*e.color.z),g=e.color.w;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${x}, ${g})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of l){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),T=new Uint8Array(S.data.buffer),C=this.flipVertically(T,p,f),P=this.module.getResourceManager(),b=this.module._malloc(C.length);this.module.HEAPU8.set(C,b);const A=P.createTexture(p,f,b,C.length,1);return this.module._free(b),{textureHandle:A,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}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)}}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 r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}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}flipVertically(e,t,r){const s=4*t,n=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*s,i=(r-1-t)*s;n.set(e.subarray(o,o+s),i)}return n}}const ce=C("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ue{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new le(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,K([],()=>{const e=s.getEntitiesWithComponents([ae]);for(const t of e){const e=s.get(t,ae);if(!e.dirty)continue;s.has(t,F)||s.insert(t,F,{texture:w,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,ce)?s.get(t,ce):null,o=r.renderForEntity(t,e,n),i=s.get(t,F);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},s.insert(t,F,i),e.dirty=!1}}))}}const he=new ue;var de;function pe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(de=exports.BlendMode||(exports.BlendMode={}))[de.Normal=0]="Normal",de[de.Additive=1]="Additive",de[de.Multiply=2]="Multiply",de[de.Screen=3]="Screen",de[de.PremultipliedAlpha=4]="PremultipliedAlpha";let fe=null,me=null,_e=1;const xe=new Map;function ge(e){fe=e,me=e.getResourceManager(),be()}function ye(){0!==Te&&fe&&(fe._free(Te),Te=0),xe.clear(),_e=1,Se=!1,me=null,fe=null}function we(){if(!me)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return me}const ve={createShader:(e,t)=>we().createShader(e,t),releaseShader(e){e>0&&we().releaseShader(e)},create(e){const t=_e++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return xe.set(t,r),t},get:e=>xe.get(e),setUniform(e,t,r){const s=xe.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=xe.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=xe.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=xe.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=xe.get(e);r&&(r.depthTest=t)},getShader(e){const t=xe.get(e);return t?.shader??0},release(e){xe.delete(e)},isValid:e=>xe.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=xe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=_e++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return xe.set(r,s),r},toAssetData(e,t){const r=xe.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=xe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Se=!1,Te=0;const Ce=4096;function Pe(e){const t=(0===Te&&fe&&(Te=fe._malloc(Ce)),Te);if(0===t||!fe)return{ptr:0,count:0};let r=0,s=0;const n=fe.HEAPU8,o=fe.HEAPU32,i=fe.HEAPF32;for(const[a,l]of e){if(r+128>Ce)break;const e=(new TextEncoder).encode(a),c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function be(){if(!fe||Se)return;fe.materialDataProvider=(e,t,r,s,n)=>{const o=xe.get(e);if(!o)return fe.HEAPU32[t>>2]=0,fe.HEAPU32[r>>2]=0,fe.HEAPU32[s>>2]=0,void(fe.HEAPU32[n>>2]=0);fe.HEAPU32[t>>2]=o.shader,fe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Pe(o.uniforms);fe.HEAPU32[s>>2]=i,fe.HEAPU32[n>>2]=a},Se=!0}const Ae={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"};let Ee=null,Re=0,Me=0,Fe=0;const Ie=new Float32Array(256);function Ue(e){Ee=e,Re=Ee._malloc(64),Me=Ee._malloc(64),Fe=Ee._malloc(1024)}function Be(){Ee&&(Re&&(Ee._free(Re),Re=0),Me&&(Ee._free(Me),Me=0),Fe&&(Ee._free(Fe),Fe=0)),Ee=null}function ke(){if(!Ee)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ee}const ze={x:1,y:1,z:1,w:1},We={begin(e){const t=ke();t.HEAPF32.set(e,Re/4),t.draw_begin(Re)},end(){ke().draw_end()},line(e,t,r,s=1){ke().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rect(e,t,r,s=!0){ke().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rectOutline(e,t,r,s=1){ke().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},circle(e,t,r,s=!0,n=32){ke().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},circleOutline(e,t,r,s=1,n=32){ke().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},texture(e,t,r,s=ze){ke().draw_texture(e.x,e.y,t.x,t.y,r,s.x,s.y,s.z,s.w)},textureRotated(e,t,r,s,n=ze){ke().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.x,n.y,n.z,n.w)},setLayer(e){ke().draw_setLayer(e)},setDepth(e){ke().draw_setDepth(e)},getDrawCallCount:()=>Ee?Ee.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ee?Ee.draw_getPrimitiveCount():0,setBlendMode(e){ke().draw_setBlendMode(e)},setDepthTest(e){ke().draw_setDepthTest(e)},drawMesh(e,t,r){const s=ke();s.HEAPF32.set(r,Me/4),s.draw_mesh(e,t,Me)},drawMeshWithMaterial(e,t,r){const s=ke(),n=ve.get(t);if(!n)return;if(We.setBlendMode(n.blendMode),We.setDepthTest(n.depthTest),0===n.uniforms.size)return void We.drawMesh(e,n.shader,r);s.HEAPF32.set(r,Me/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=De(e);if(!(r<0)){if(pe(t))Ie[o++]=10,Ie[o++]=r,Ie[o++]=t.slot??i++,Ie[o++]=t.textureId;else if("number"==typeof t)Ie[o++]=1,Ie[o++]=r,Ie[o++]=t;else if(Array.isArray(t)){Ie[o++]=t.length,Ie[o++]=r;for(let e=0;e<t.length;e++)Ie[o++]=t[e]}else"w"in t?(Ie[o++]=4,Ie[o++]=r,Ie[o++]=t.x,Ie[o++]=t.y,Ie[o++]=t.z,Ie[o++]=t.w):"z"in t?(Ie[o++]=3,Ie[o++]=r,Ie[o++]=t.x,Ie[o++]=t.y,Ie[o++]=t.z):(Ie[o++]=2,Ie[o++]=r,Ie[o++]=t.x,Ie[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Ie.subarray(0,o),Fe/4),s.draw_meshWithUniforms(e,n.shader,Me,Fe,o)):s.draw_mesh(e,n.shader,Me)}},$e={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 De(e){return $e[e]??-1}var Le;exports.DataType=void 0,(Le=exports.DataType||(exports.DataType={}))[Le.Float=1]="Float",Le[Le.Float2=2]="Float2",Le[Le.Float3=3]="Float3",Le[Le.Float4=4]="Float4",Le[Le.Int=5]="Int",Le[Le.Int2=6]="Int2",Le[Le.Int3=7]="Int3",Le[Le.Int4=8]="Int4";let Ge=null,Oe=0,Ne=0,Ve=0;function He(e){Ge=e,Oe=Ge._malloc(262144),Ne=Ge._malloc(65536),Ve=Ge._malloc(256)}function Xe(){Ge&&(Oe&&Ge._free(Oe),Ne&&Ge._free(Ne),Ve&&Ge._free(Ve),Oe=0,Ne=0,Ve=0),Ge=null}function je(){if(!Ge)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ge}const Ye={create(e){const t=je(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Oe/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ve,n).set(o),t.geometry_init(r,Oe,s,Ve,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ne,s).set(e.indices),t.geometry_setIndices16(r,Ne,s)}else{new Uint32Array(t.HEAPU8.buffer,Ne,s).set(e.indices),t.geometry_setIndices32(r,Ne,s)}}return r},updateVertices(e,t,r=0){const s=je(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,Oe/4),s.geometry_updateVertices(e,Oe,n,r)},release(e){e>0&&je().geometry_release(e)},isValid:e=>!(!Ge||e<=0)&&Ge.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return Ye.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,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 r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ye.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);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 Ye.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 qe=null;function Ke(e){qe=e}function Je(){qe&&Ze.isInitialized()&&Ze.shutdown(),qe=null}function Qe(){if(!qe)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return qe}const Ze={init:(e,t)=>Qe().postprocess_init(e,t),shutdown(){Qe().postprocess_shutdown()},resize(e,t){Qe().postprocess_resize(e,t)},addPass:(e,t)=>Qe().postprocess_addPass(e,t),removePass(e){Qe().postprocess_removePass(e)},setEnabled(e,t){Qe().postprocess_setPassEnabled(e,t)},isEnabled:e=>Qe().postprocess_isPassEnabled(e),setUniform(e,t,r){Qe().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Qe().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Qe().postprocess_begin()},end(){Qe().postprocess_end()},getPassCount:()=>Qe().postprocess_getPassCount(),isInitialized:()=>!!qe&&qe.postprocess_isInitialized(),setBypass(e){Qe().postprocess_setBypass(e)},isBypassed:()=>!qe||qe.postprocess_isBypassed(),createBlur:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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")},et="#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 tt;exports.RenderStage=void 0,(tt=exports.RenderStage||(exports.RenderStage={}))[tt.Background=0]="Background",tt[tt.Opaque=1]="Opaque",tt[tt.Transparent=2]="Transparent",tt[tt.Overlay=3]="Overlay";let rt=null,st=0;function nt(e){rt=e,st=rt._malloc(64)}function ot(){rt&&st&&(rt._free(st),st=0),rt=null}const it={init(e,t){rt?.renderer_init(e,t)},resize(e,t){rt?.renderer_resize(e,t)},begin(e,t){rt&&st&&(rt.HEAPF32.set(e,st/4),rt.renderer_begin(st,t??0))},flush(){rt?.renderer_flush()},end(){rt?.renderer_end()},submitSprites(e){rt&&rt.renderer_submitSprites(e._cpp)},submitSpine(e){rt&&rt.renderer_submitSpine(e._cpp)},setStage(e){rt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>rt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){rt?.renderer_releaseTarget(e)},getTargetTexture:e=>rt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){rt?.renderer_setClearColor?.(e,t,r,s)},getStats:()=>rt?{drawCalls:rt.renderer_getDrawCalls(),triangles:rt.renderer_getTriangles(),sprites:rt.renderer_getSprites(),spine:rt.renderer_getSpine(),meshes:rt.renderer_getMeshes(),culled:rt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let at=null;function lt(e){at=e}function ct(){at=null}const ut={enable(){at?.gl_enableErrorCheck(!0)},disable(){at?.gl_enableErrorCheck(!1)},check:e=>at?.gl_checkErrors(e)??0,diagnose(){at?.renderer_diagnose()}},ht=new Map;function dt(e){ht.delete(e)}class pt{render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;it.resize(s,n),Ze.isInitialized()&&Ze.getPassCount()>0&&!Ze.isBypassed()&&Ze.resize(s,n),it.begin(r),it.submitSprites(t),it.submitSpine(t),it.flush();const i=ht;if(i.size>0){We.begin(r);const e=[];for(const[t,r]of i.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}We.end();for(const t of e)dt(t)}it.end()}}class ft{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.module_=null,this.mainLoop=()=>{if(!this.running_)return;const e=i(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;this.updateTime(r),this.runSchedule(exports.Schedule.First),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new se,this.resources_=new O;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ft}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),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 world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Q(this.world_,this.resources_),this.resources_.insert(N,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=i(),this.mainLoop())}quit(){this.running_=!1,ct(),ot(),Je(),Xe(),ye(),Be()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(N),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(N,r)}}const mt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function _t(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}function xt(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function gt(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function yt(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}class wt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ve.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await n(t))throw new Error(`Material file not found: ${t}`);const r=await s(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const o=JSON.parse(r);if("material"!==o.type)throw new Error(`Invalid material file type: ${o.type}`);const i=this.resolveShaderPath(e,o.shader),a=await this.shaderLoader_.load(i);return{handle:ve.createFromAsset(o,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 r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}async function vt(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t);for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}St(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function St(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,R,s);break;case"Sprite":e.insert(t,F,s);break;case"Camera":e.insert(t,I,s);break;case"Canvas":e.insert(t,U,s);break;case"Text":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,W,s);break;case"UIRect":e.insert(t,ce,s);break;default:{const n=P(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Ct{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=o(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new wt(t)}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 r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await fetch(n);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${n}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),l=this.parseAtlasTextures(i);for(const e of l){const t=a?`${a}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,r),u=await fetch(c);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${c}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}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 r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return vt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(s,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(s)},s.onerror=()=>r(new Error(`Failed to load image: ${e}`)),s.src=e})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),s&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.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,r,a,o.length,1);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){if(!await n(e))throw new Error(`Shader file not found: ${e}`);const t=await s(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(t);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return ve.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}async fetchJson(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.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 r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Pt=L(null,"Assets");class bt{build(e){const t=e.wasmModule;t?e.insertResource(Pt,new Ct(t)):console.warn("AssetPlugin: No WASM module available")}}const At=new bt;class Et{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,r=!0,s=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,r,s)}addAnimation(e,t,r=!0,s=0,n=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,r,s,n)}setEmptyAnimation(e,t=.2,r=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,r)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const r=this.module_.spineGetBonePosition(e,t);return r?{x:r.x,y:r.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,r){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,r||"")}on(e,t,r){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(r)}off(e,t,r){const s=this.listeners_.get(e);if(!s)return;const n=s.get(t);n&&n.delete(r)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const r=this.listeners_.get(e);if(!r)return;const s={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},n=r.get(s.type);n&&n.forEach(e=>{try{e(s)}catch(e){console.error("Error in Spine event callback:",e)}})}}const Rt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=it.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:it.getTargetTexture(r),width:e.width,height:e.height}},release(e){it.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(it.releaseRenderTarget(e._handle),Rt.create({width:t,height:r,depth:!0})),begin(e,t){it.begin(t,e._handle)},end(){it.end()},getDepthTexture:e=>it.getTargetDepthTexture(e._handle)};let Mt=!1;var Ft;g||(g=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await a(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.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:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Ft=y,console.log(`[ESEngine] Platform: ${Ft.name}`),exports.App=ft,exports.AssetPlugin=bt,exports.AssetServer=Ct,exports.Assets=Pt,exports.AsyncCache=Tt,exports.Camera=I,exports.Canvas=U,exports.Children=z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=j,exports.Draw=We,exports.EntityCommands=X,exports.GLDebug=ut,exports.Geometry=Ye,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=w,exports.Input=ee,exports.InputPlugin=te,exports.InputState=Z,exports.LocalTransform=R,exports.Material=ve,exports.MaterialLoader=wt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=k,exports.PostProcess=Ze,exports.PreviewPlugin=class{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(Pt)||e.addPlugin(At),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=this.app_.getResource(Pt);await s.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([I]);for(const s of r){if(e.get(s,I).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(t,R,r);const s={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,I,s)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{V(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=H,exports.RenderPipeline=pt,exports.RenderTexture=Rt,exports.Renderer=it,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=Ae,exports.SpineAnimation=W,exports.SpineController=Et,exports.Sprite=F,exports.SystemRunner=Q,exports.Text=ae,exports.TextPlugin=ue,exports.TextRenderer=le,exports.Time=N,exports.UIRect=ce,exports.Velocity=B,exports.World=se,exports.WorldTransform=M,exports.addStartupSystem=function(e){J().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){J().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){J().push({schedule:e,system:t})},exports.assetPlugin=At,exports.clearDrawCallbacks=function(){ht.clear()},exports.clearUserComponents=function(){T().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({x:e,y:t,z:r,w:s}),exports.createSpineController=function(e){return new Et(e)},exports.createWebApp=function(e,t){const r=ft.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ue(e),ge(e),He(e),Ke(e),nt(e),lt(e);const n=new pt;let o=i();const a=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=a(),r=function(e,t,r){const s=e.entityCount()+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const s=e.getCamera(n);if(!s.isActive)continue;const o=e.getLocalTransform(n),i=t/r;let a;if(1===s.projectionType){const e=s.orthoSize,t=e*i;a=_t(-t,t,-e,e,-s.farPlane,s.farPlane)}else a=xt(s.fov*Math.PI/180,i,s.nearPlane,s.farPlane);return yt(a,gt(o.position.x,o.position.y,o.position.z))}return mt}(s,e,t),l=(i()-o)/1e3;n.render({registry:{_cpp:s},viewProjection:r,width:e,height:t,elapsed:l})}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(re),r.addPlugin(he),r},exports.defineComponent=C,exports.defineResource=L,exports.defineSystem=K,exports.defineTag=function(e){const t=T(),r=t.get(e);if(r)return r;const s=S(e,{});return t.set(e,s),b(e,{},!0),s},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=$[e];if(t)return{...t._default};const r=P(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=P,exports.initDrawAPI=Ue,exports.initGLDebugAPI=lt,exports.initGeometryAPI=He,exports.initMaterialAPI=ge,exports.initPostProcessAPI=Ke,exports.initRendererAPI=nt,exports.inputPlugin=re,exports.isBuiltinComponent=E,exports.isEditor=function(){return Mt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Mt},exports.isTextureRef=pe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=St,exports.loadSceneData=function(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t);for(const r of s.components)St(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r},exports.loadSceneWithAssets=vt,exports.platformFetch=r,exports.platformFileExists=n,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=async function(e){return t().readFile(e)},exports.platformReadTextFile=s,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){ht.set(e,t)},exports.registerMaterialCallback=be,exports.setEditorMode=function(e){Mt=e},exports.shutdownDrawAPI=Be,exports.shutdownGLDebugAPI=ct,exports.shutdownGeometryAPI=Xe,exports.shutdownMaterialAPI=ye,exports.shutdownPostProcessAPI=Je,exports.shutdownRendererAPI=ot,exports.textPlugin=he,exports.unregisterDrawCallback=dt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([I]);for(const s of r){const r=e.get(s,I);r&&(r.aspectRatio=t,e.insert(s,I,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=p,exports.wxFileExistsSync=function(e){const t=u();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=x,exports.wxLoadImage=_,exports.wxLoadImagePixels=async function(e,t=!0){return x(await _(e),t)},exports.wxReadFile=h,exports.wxReadTextFile=d,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{u().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(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 r(e,r){return t().fetch(e,r)}async function s(e){return t().readTextFile(e)}async function n(e){return t().fileExists(e)}function o(e,r){return t().createCanvas(e,r)}function i(){return t().now()}function a(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,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 "${r}": ${t}`)}}let c=null;function u(){return c||(c=wx.getFileSystemManager()),c}function h(e){return new Promise((t,r)=>{u().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function d(e,t="utf-8"){return new Promise((r,s)=>{u().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e){return new Promise(t=>{u().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let f=null,m=null;function _(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function x(e,t=!0){const{width:r,height:s}=e,{ctx:n}=function(e,t){return f||(f=wx.createCanvas(),f.width=e,f.height=t,m=f.getContext("2d")),(f.width<e||f.height<t)&&(f.width=Math.max(f.width,e),f.height=Math.max(f.height,t)),{canvas:f,ctx:m}}(r,s);n.clearRect(0,0,r,s),n.save(),t&&(n.translate(0,s),n.scale(1,-1)),n.drawImage(e,0,0),n.restore();const o=n.getImageData(0,0,r,s);return{width:r,height:s,pixels:new Uint8Array(o.data.buffer)}}let g=!1;const y=new class{constructor(){this.name="wechat"}async fetch(e,t){return a(e,t)}async readFile(e){return h(e)}async readTextFile(e){return d(e)}async fileExists(e){return p(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(e,t)}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}},w=4294967295;let v=0;function S(e,t){const r=++v;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function T(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const r=T(),s=r.get(e);if(s)return s;const n=S(e,t);return r.set(e,n),A(e,t,!1),n}function P(e){return T().get(e)}function A(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function E(e){return!0===e._builtin}const R=b("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),M=b("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=b("Sprite",{texture:w,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),I=b("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),U=b("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),B=b("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),k=b("Parent",{entity:0}),z=b("Children",{entities:[]}),W=b("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),$={LocalTransform:R,WorldTransform:M,Sprite:F,Camera:I,Canvas:U,Velocity:B,Parent:k,Children:z,SpineAnimation:W};let D=0;function L(e,t){const r=++D;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class G{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 O{constructor(){this.resources_=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)}getResMut(e){return new G(this.get(e),t=>this.set(e,t))}}const N=L({delta:0,elapsed:0,frameCount:0},"Time");function V(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class H{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return V(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:s}=this.descriptor_,n=e.map(e=>this.getActualComponent(e)),o=[...n,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,l=[];try{for(const e of i){if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data);l=[];let r=!1;for(const t of s)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=n.map(t=>this.world_.get(e,t));for(const e of t)l.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}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(){return[...this]}}class X{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 r;return r=E(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),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 j{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new X(this,null)}entity(e){return new X(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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Y;exports.Schedule=void 0,(Y=exports.Schedule||(exports.Schedule={}))[Y.Startup=0]="Startup",Y[Y.First=1]="First",Y[Y.PreUpdate=2]="PreUpdate",Y[Y.Update=3]="Update",Y[Y.PostUpdate=4]="PostUpdate",Y[Y.Last=5]="Last",Y[Y.FixedPreUpdate=10]="FixedPreUpdate",Y[Y.FixedUpdate=11]="FixedUpdate",Y[Y.FixedPostUpdate=12]="FixedPostUpdate";let q=0;function K(e,t,r){const s=++q;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function J(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Q{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof j&&e.flush()}resolveParam(e){switch(e._type){case"query":return new H(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new j(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Z{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 ee=L(new Z,"Input");class te{constructor(e){this.target_=e??null}build(e){const t=new Z;e.insertResource(ee,t);const r=this.target_??document.querySelector("canvas")??document.body;document.addEventListener("keydown",e=>{t.keysDown.has(e.code)||t.keysPressed.add(e.code),t.keysDown.add(e.code)}),document.addEventListener("keyup",e=>{t.keysDown.delete(e.code),t.keysReleased.add(e.code)}),r.addEventListener("mousemove",e=>{t.mouseX=e.offsetX,t.mouseY=e.offsetY}),r.addEventListener("mousedown",e=>{const r=e.button;t.mouseButtons.add(r),t.mouseButtonsPressed.add(r)}),r.addEventListener("mouseup",e=>{const r=e.button;t.mouseButtons.delete(r),t.mouseButtonsReleased.add(r)}),r.addEventListener("touchstart",e=>{const s=e.touches[0];if(s){const e=r.getBoundingClientRect();t.mouseX=s.clientX-e.left,t.mouseY=s.clientY-e.top,t.mouseButtons.add(0),t.mouseButtonsPressed.add(0)}}),r.addEventListener("touchmove",e=>{const s=e.touches[0];if(s){const e=r.getBoundingClientRect();t.mouseX=s.clientX-e.left,t.mouseY=s.clientY-e.top}}),r.addEventListener("touchend",()=>{t.mouseButtons.delete(0),t.mouseButtonsReleased.add(0)}),r.addEventListener("wheel",e=>{t.scrollDeltaX+=e.deltaX,t.scrollDeltaY+=e.deltaY}),e.addSystemToSchedule(exports.Schedule.First,K([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const re=new te;class se{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}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,r){return E(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return E(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return E(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){E(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,s)}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let s=!0;for(const t of e)if(!this.has(r,t)){s=!1;break}s&&t.push(r)}return t}}var ne,oe,ie;exports.TextAlign=void 0,(ne=exports.TextAlign||(exports.TextAlign={}))[ne.Left=0]="Left",ne[ne.Center=1]="Center",ne[ne.Right=2]="Right",exports.TextVerticalAlign=void 0,(oe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[oe.Top=0]="Top",oe[oe.Middle=1]="Middle",oe[oe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ie=exports.TextOverflow||(exports.TextOverflow={}))[ie.Visible=0]="Visible",ie[ie.Clip=1]="Clip",ie[ie.Ellipsis=2]="Ellipsis";const ae=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class le{constructor(e){this.cache=new Map,this.module=e,this.canvas=o(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>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(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.x),_=Math.round(255*e.color.y),x=Math.round(255*e.color.z),g=e.color.w;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${x}, ${g})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of l){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),T=new Uint8Array(S.data.buffer),C=this.flipVertically(T,p,f),P=this.module.getResourceManager(),A=this.module._malloc(C.length);this.module.HEAPU8.set(C,A);const b=P.createTexture(p,f,A,C.length,1);return this.module._free(A),{textureHandle:b,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}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)}}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 r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}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}flipVertically(e,t,r){const s=4*t,n=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*s,i=(r-1-t)*s;n.set(e.subarray(o,o+s),i)}return n}}const ce=C("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ue{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new le(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,K([],()=>{const e=s.getEntitiesWithComponents([ae]);for(const t of e){const e=s.get(t,ae);if(!e.dirty)continue;s.has(t,F)||s.insert(t,F,{texture:w,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,ce)?s.get(t,ce):null,o=r.renderForEntity(t,e,n),i=s.get(t,F);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},s.insert(t,F,i),e.dirty=!1}}))}}const he=new ue;var de;function pe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(de=exports.BlendMode||(exports.BlendMode={}))[de.Normal=0]="Normal",de[de.Additive=1]="Additive",de[de.Multiply=2]="Multiply",de[de.Screen=3]="Screen",de[de.PremultipliedAlpha=4]="PremultipliedAlpha";let fe=null,me=null,_e=1;const xe=new Map;function ge(e){fe=e,me=e.getResourceManager(),Ae()}function ye(){0!==Te&&fe&&(fe._free(Te),Te=0),xe.clear(),_e=1,Se=!1,me=null,fe=null}function we(){if(!me)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return me}const ve={createShader:(e,t)=>we().createShader(e,t),releaseShader(e){e>0&&we().releaseShader(e)},create(e){const t=_e++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return xe.set(t,r),t},get:e=>xe.get(e),setUniform(e,t,r){const s=xe.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=xe.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=xe.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=xe.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=xe.get(e);r&&(r.depthTest=t)},getShader(e){const t=xe.get(e);return t?.shader??0},release(e){xe.delete(e)},isValid:e=>xe.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=xe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=_e++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return xe.set(r,s),r},toAssetData(e,t){const r=xe.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=xe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Se=!1,Te=0;const Ce=4096;function Pe(e){const t=(0===Te&&fe&&(Te=fe._malloc(Ce)),Te);if(0===t||!fe)return{ptr:0,count:0};let r=0,s=0;const n=fe.HEAPU8,o=fe.HEAPU32,i=fe.HEAPF32;for(const[a,l]of e){if(r+128>Ce)break;const e=(new TextEncoder).encode(a),c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function Ae(){if(!fe||Se)return;fe.materialDataProvider=(e,t,r,s,n)=>{const o=xe.get(e);if(!o)return fe.HEAPU32[t>>2]=0,fe.HEAPU32[r>>2]=0,fe.HEAPU32[s>>2]=0,void(fe.HEAPU32[n>>2]=0);fe.HEAPU32[t>>2]=o.shader,fe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Pe(o.uniforms);fe.HEAPU32[s>>2]=i,fe.HEAPU32[n>>2]=a},Se=!0}const be={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"};let Ee=null,Re=0,Me=0,Fe=0;const Ie=new Float32Array(256);function Ue(e){Ee=e,Re=Ee._malloc(64),Me=Ee._malloc(64),Fe=Ee._malloc(1024)}function Be(){Ee&&(Re&&(Ee._free(Re),Re=0),Me&&(Ee._free(Me),Me=0),Fe&&(Ee._free(Fe),Fe=0)),Ee=null}function ke(){if(!Ee)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ee}const ze={x:1,y:1,z:1,w:1},We={begin(e){const t=ke();t.HEAPF32.set(e,Re/4),t.draw_begin(Re)},end(){ke().draw_end()},line(e,t,r,s=1){ke().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rect(e,t,r,s=!0){ke().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rectOutline(e,t,r,s=1){ke().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},circle(e,t,r,s=!0,n=32){ke().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},circleOutline(e,t,r,s=1,n=32){ke().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},texture(e,t,r,s=ze){ke().draw_texture(e.x,e.y,t.x,t.y,r,s.x,s.y,s.z,s.w)},textureRotated(e,t,r,s,n=ze){ke().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.x,n.y,n.z,n.w)},setLayer(e){ke().draw_setLayer(e)},setDepth(e){ke().draw_setDepth(e)},getDrawCallCount:()=>Ee?Ee.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ee?Ee.draw_getPrimitiveCount():0,setBlendMode(e){ke().draw_setBlendMode(e)},setDepthTest(e){ke().draw_setDepthTest(e)},drawMesh(e,t,r){const s=ke();s.HEAPF32.set(r,Me/4),s.draw_mesh(e,t,Me)},drawMeshWithMaterial(e,t,r){const s=ke(),n=ve.get(t);if(!n)return;if(We.setBlendMode(n.blendMode),We.setDepthTest(n.depthTest),0===n.uniforms.size)return void We.drawMesh(e,n.shader,r);s.HEAPF32.set(r,Me/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=De(e);if(!(r<0)){if(pe(t))Ie[o++]=10,Ie[o++]=r,Ie[o++]=t.slot??i++,Ie[o++]=t.textureId;else if("number"==typeof t)Ie[o++]=1,Ie[o++]=r,Ie[o++]=t;else if(Array.isArray(t)){Ie[o++]=t.length,Ie[o++]=r;for(let e=0;e<t.length;e++)Ie[o++]=t[e]}else"w"in t?(Ie[o++]=4,Ie[o++]=r,Ie[o++]=t.x,Ie[o++]=t.y,Ie[o++]=t.z,Ie[o++]=t.w):"z"in t?(Ie[o++]=3,Ie[o++]=r,Ie[o++]=t.x,Ie[o++]=t.y,Ie[o++]=t.z):(Ie[o++]=2,Ie[o++]=r,Ie[o++]=t.x,Ie[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Ie.subarray(0,o),Fe/4),s.draw_meshWithUniforms(e,n.shader,Me,Fe,o)):s.draw_mesh(e,n.shader,Me)}},$e={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 De(e){return $e[e]??-1}var Le;exports.DataType=void 0,(Le=exports.DataType||(exports.DataType={}))[Le.Float=1]="Float",Le[Le.Float2=2]="Float2",Le[Le.Float3=3]="Float3",Le[Le.Float4=4]="Float4",Le[Le.Int=5]="Int",Le[Le.Int2=6]="Int2",Le[Le.Int3=7]="Int3",Le[Le.Int4=8]="Int4";let Ge=null,Oe=0,Ne=0,Ve=0;function He(e){Ge=e,Oe=Ge._malloc(262144),Ne=Ge._malloc(65536),Ve=Ge._malloc(256)}function Xe(){Ge&&(Oe&&Ge._free(Oe),Ne&&Ge._free(Ne),Ve&&Ge._free(Ve),Oe=0,Ne=0,Ve=0),Ge=null}function je(){if(!Ge)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ge}const Ye={create(e){const t=je(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Oe/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ve,n).set(o),t.geometry_init(r,Oe,s,Ve,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ne,s).set(e.indices),t.geometry_setIndices16(r,Ne,s)}else{new Uint32Array(t.HEAPU8.buffer,Ne,s).set(e.indices),t.geometry_setIndices32(r,Ne,s)}}return r},updateVertices(e,t,r=0){const s=je(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,Oe/4),s.geometry_updateVertices(e,Oe,n,r)},release(e){e>0&&je().geometry_release(e)},isValid:e=>!(!Ge||e<=0)&&Ge.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return Ye.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,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 r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ye.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);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 Ye.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 qe=null;function Ke(e){qe=e}function Je(){qe&&Ze.isInitialized()&&Ze.shutdown(),qe=null}function Qe(){if(!qe)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return qe}const Ze={init:(e,t)=>Qe().postprocess_init(e,t),shutdown(){Qe().postprocess_shutdown()},resize(e,t){Qe().postprocess_resize(e,t)},addPass:(e,t)=>Qe().postprocess_addPass(e,t),removePass(e){Qe().postprocess_removePass(e)},setEnabled(e,t){Qe().postprocess_setPassEnabled(e,t)},isEnabled:e=>Qe().postprocess_isPassEnabled(e),setUniform(e,t,r){Qe().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Qe().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Qe().postprocess_begin()},end(){Qe().postprocess_end()},getPassCount:()=>Qe().postprocess_getPassCount(),isInitialized:()=>!!qe&&qe.postprocess_isInitialized(),setBypass(e){Qe().postprocess_setBypass(e)},isBypassed:()=>!qe||qe.postprocess_isBypassed(),createBlur:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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")},et="#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 tt;exports.RenderStage=void 0,(tt=exports.RenderStage||(exports.RenderStage={}))[tt.Background=0]="Background",tt[tt.Opaque=1]="Opaque",tt[tt.Transparent=2]="Transparent",tt[tt.Overlay=3]="Overlay";let rt=null,st=0;function nt(e){rt=e,st=rt._malloc(64)}function ot(){rt&&st&&(rt._free(st),st=0),rt=null}const it={init(e,t){rt?.renderer_init(e,t)},resize(e,t){rt?.renderer_resize(e,t)},begin(e,t){rt&&st&&(rt.HEAPF32.set(e,st/4),rt.renderer_begin(st,t??0))},flush(){rt?.renderer_flush()},end(){rt?.renderer_end()},submitSprites(e){rt&&rt.renderer_submitSprites(e._cpp)},submitSpine(e){rt&&rt.renderer_submitSpine(e._cpp)},setStage(e){rt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>rt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){rt?.renderer_releaseTarget(e)},getTargetTexture:e=>rt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){rt?.renderer_setClearColor?.(e,t,r,s)},getStats:()=>rt?{drawCalls:rt.renderer_getDrawCalls(),triangles:rt.renderer_getTriangles(),sprites:rt.renderer_getSprites(),spine:rt.renderer_getSpine(),meshes:rt.renderer_getMeshes(),culled:rt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let at=null;function lt(e){at=e}function ct(){at=null}const ut={enable(){at?.gl_enableErrorCheck(!0)},disable(){at?.gl_enableErrorCheck(!1)},check:e=>at?.gl_checkErrors(e)??0,diagnose(){at?.renderer_diagnose()}},ht=new Map;function dt(e){ht.delete(e)}class pt{render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;it.resize(s,n),Ze.isInitialized()&&Ze.getPassCount()>0&&!Ze.isBypassed()&&Ze.resize(s,n),it.begin(r),it.submitSprites(t),it.submitSpine(t),it.flush();const i=ht;if(i.size>0){We.begin(r);const e=[];for(const[t,r]of i.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}We.end();for(const t of e)dt(t)}it.end()}}class ft{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.mainLoop=()=>{if(!this.running_)return;const e=i(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);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 se,this.resources_=new O;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ft}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),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 world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Q(this.world_,this.resources_),this.resources_.insert(N,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=i(),this.mainLoop())}quit(){this.running_=!1,ct(),ot(),Je(),Xe(),ye(),Be()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(N),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(N,r)}}const mt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function _t(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}function xt(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function gt(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function yt(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}class wt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ve.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await n(t))throw new Error(`Material file not found: ${t}`);const r=await s(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const o=JSON.parse(r);if("material"!==o.type)throw new Error(`Invalid material file type: ${o.type}`);const i=this.resolveShaderPath(e,o.shader),a=await this.shaderLoader_.load(i);return{handle:ve.createFromAsset(o,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 r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}async function vt(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t);for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}St(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function St(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,R,s);break;case"Sprite":e.insert(t,F,s);break;case"Camera":e.insert(t,I,s);break;case"Canvas":e.insert(t,U,s);break;case"Text":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,W,s);break;case"UIRect":e.insert(t,ce,s);break;default:{const n=P(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Ct{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=o(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new wt(t)}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 r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await fetch(n);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${n}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),l=this.parseAtlasTextures(i);for(const e of l){const t=a?`${a}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,r),u=await fetch(c);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${c}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}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 r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return vt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(s,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(s)},s.onerror=()=>r(new Error(`Failed to load image: ${e}`)),s.src=e})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),s&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.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,r,a,o.length,1);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){if(!await n(e))throw new Error(`Shader file not found: ${e}`);const t=await s(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(t);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return ve.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}async fetchJson(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.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 r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Pt=L(null,"Assets");class At{build(e){const t=e.wasmModule;t?e.insertResource(Pt,new Ct(t)):console.warn("AssetPlugin: No WASM module available")}}const bt=new At;class Et{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,r=!0,s=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,r,s)}addAnimation(e,t,r=!0,s=0,n=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,r,s,n)}setEmptyAnimation(e,t=.2,r=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,r)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const r=this.module_.spineGetBonePosition(e,t);return r?{x:r.x,y:r.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,r){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,r||"")}on(e,t,r){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(r)}off(e,t,r){const s=this.listeners_.get(e);if(!s)return;const n=s.get(t);n&&n.delete(r)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const r=this.listeners_.get(e);if(!r)return;const s={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},n=r.get(s.type);n&&n.forEach(e=>{try{e(s)}catch(e){console.error("Error in Spine event callback:",e)}})}}const Rt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=it.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:it.getTargetTexture(r),width:e.width,height:e.height}},release(e){it.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(it.releaseRenderTarget(e._handle),Rt.create({width:t,height:r,depth:!0})),begin(e,t){it.begin(t,e._handle)},end(){it.end()},getDepthTexture:e=>it.getTargetDepthTexture(e._handle)};let Mt=!1;var Ft;g||(g=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await a(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.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:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Ft=y,console.log(`[ESEngine] Platform: ${Ft.name}`),exports.App=ft,exports.AssetPlugin=At,exports.AssetServer=Ct,exports.Assets=Pt,exports.AsyncCache=Tt,exports.Camera=I,exports.Canvas=U,exports.Children=z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=j,exports.Draw=We,exports.EntityCommands=X,exports.GLDebug=ut,exports.Geometry=Ye,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=w,exports.Input=ee,exports.InputPlugin=te,exports.InputState=Z,exports.LocalTransform=R,exports.Material=ve,exports.MaterialLoader=wt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=k,exports.PostProcess=Ze,exports.PreviewPlugin=class{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(Pt)||e.addPlugin(bt),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=this.app_.getResource(Pt);await s.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([I]);for(const s of r){if(e.get(s,I).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(t,R,r);const s={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,I,s)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{V(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=H,exports.RenderPipeline=pt,exports.RenderTexture=Rt,exports.Renderer=it,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=be,exports.SpineAnimation=W,exports.SpineController=Et,exports.Sprite=F,exports.SystemRunner=Q,exports.Text=ae,exports.TextPlugin=ue,exports.TextRenderer=le,exports.Time=N,exports.UIRect=ce,exports.Velocity=B,exports.World=se,exports.WorldTransform=M,exports.addStartupSystem=function(e){J().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){J().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){J().push({schedule:e,system:t})},exports.assetPlugin=bt,exports.clearDrawCallbacks=function(){ht.clear()},exports.clearUserComponents=function(){T().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({x:e,y:t,z:r,w:s}),exports.createSpineController=function(e){return new Et(e)},exports.createWebApp=function(e,t){const r=ft.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ue(e),ge(e),He(e),Ke(e),nt(e),lt(e);const n=new pt;let o=i();const a=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=a(),r=function(e,t,r){const s=e.entityCount()+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const s=e.getCamera(n);if(!s.isActive)continue;const o=e.getLocalTransform(n),i=t/r;let a;if(1===s.projectionType){const e=s.orthoSize,t=e*i;a=_t(-t,t,-e,e,-s.farPlane,s.farPlane)}else a=xt(s.fov*Math.PI/180,i,s.nearPlane,s.farPlane);return yt(a,gt(o.position.x,o.position.y,o.position.z))}return mt}(s,e,t),l=(i()-o)/1e3;n.render({registry:{_cpp:s},viewProjection:r,width:e,height:t,elapsed:l})}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(re),r.addPlugin(he),r},exports.defineComponent=C,exports.defineResource=L,exports.defineSystem=K,exports.defineTag=function(e){const t=T(),r=t.get(e);if(r)return r;const s=S(e,{});return t.set(e,s),A(e,{},!0),s},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=$[e];if(t)return{...t._default};const r=P(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=P,exports.initDrawAPI=Ue,exports.initGLDebugAPI=lt,exports.initGeometryAPI=He,exports.initMaterialAPI=ge,exports.initPostProcessAPI=Ke,exports.initRendererAPI=nt,exports.inputPlugin=re,exports.isBuiltinComponent=E,exports.isEditor=function(){return Mt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Mt},exports.isTextureRef=pe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=St,exports.loadSceneData=function(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t);for(const r of s.components)St(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r},exports.loadSceneWithAssets=vt,exports.platformFetch=r,exports.platformFileExists=n,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=async function(e){return t().readFile(e)},exports.platformReadTextFile=s,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){ht.set(e,t)},exports.registerMaterialCallback=Ae,exports.setEditorMode=function(e){Mt=e},exports.shutdownDrawAPI=Be,exports.shutdownGLDebugAPI=ct,exports.shutdownGeometryAPI=Xe,exports.shutdownMaterialAPI=ye,exports.shutdownPostProcessAPI=Je,exports.shutdownRendererAPI=ot,exports.textPlugin=he,exports.unregisterDrawCallback=dt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([I]);for(const s of r){const r=e.get(s,I);r&&(r.aspectRatio=t,e.insert(s,I,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=p,exports.wxFileExistsSync=function(e){const t=u();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=x,exports.wxLoadImage=_,exports.wxLoadImagePixels=async function(e,t=!0){return x(await _(e),t)},exports.wxReadFile=h,exports.wxReadTextFile=d,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{u().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(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 dff89f94c..12745047e 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 r(){return null!==e}function n(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,r){return t().fetch(e,r)}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,r){return t().instantiateWasm(e,r)}function h(e,r){return t().createCanvas(e,r)}function d(){return t().now()}function f(e,t){return new Promise((r,n)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"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];r({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,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).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 r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,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 "${r}": ${t}`)}}let _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,r)=>{m().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function y(e,t="utf-8"){return new Promise((r,n)=>{m().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function v(e,t){return new Promise((r,n)=>{m().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let S=null,C=null;function b(e){return new Promise((t,r)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function P(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return S||(S=wx.createCanvas(),S.width=e,S.height=t,C=S.getContext("2d")),(S.width<e||S.height<t)&&(S.width=Math.max(S.width,e),S.height=Math.max(S.height,t)),{canvas:S,ctx:C}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const i=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(i.data.buffer)}}async function T(e,t=!0){return P(await b(e),t)}let E=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return g(e)}async readTextFile(e){return y(e)}async fileExists(e){return w(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)}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}},M=0,R=4294967295,F=(e=0,t=0)=>({x:e,y:t}),U=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),B=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),z=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),k=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let $=0;function I(e,t){const r=++$;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function W(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const r=W(),n=r.get(e);if(n)return n;const s=I(e,t);return r.set(e,s),N(e,t,!1),s}function D(e){const t=W(),r=t.get(e);if(r)return r;const n=I(e,{});return t.set(e,n),N(e,{},!0),n}function G(e){return W().get(e)}function O(){W().clear()}function N(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function H(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function X(e){return!0===e._builtin}const j=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:R,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),K=H("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=H("Parent",{entity:0}),Z=H("Children",{entities:[]}),ee=H("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),te={LocalTransform:j,WorldTransform:V,Sprite:Y,Camera:q,Canvas:K,Velocity:J,Parent:Q,Children:Z,SpineAnimation:ee};function re(e){const t=te[e];if(t)return{...t._default};const r=G(e);return r?{...r._default}:null}let ne=0;function se(e,t){const r=++ne;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function ie(e){return{_type:"res",_resource:e}}function oe(e){return{_type:"res_mut",_resource:e}}class ae{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 ce{constructor(){this.resources_=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)}getResMut(e){return new ae(this.get(e),t=>this.set(e,t))}}const le=se({delta:0,elapsed:0,frameCount:0},"Time");function ue(e){return{_type:"mut",_component:e}}function he(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function de(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{he(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)}class fe{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return he(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:n}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...r],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let r=!1;for(const t of n)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}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(){return[...this]}}function pe(){return{_type:"commands"}}class _e{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 r;return r=X(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),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 me{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new _e(this,null)}entity(e){return new _e(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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ge;!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"}(ge||(ge={}));let ye=0;function we(e,t,r){const n=++ye;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function xe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ve(e){xe().push({schedule:ge.Update,system:e})}function Se(e){xe().push({schedule:ge.Startup,system:e})}function Ce(e,t){xe().push({schedule:e,system:t})}class be{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof me&&e.flush()}resolveParam(e){switch(e._type){case"query":return new fe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new me(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Pe{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 Te=se(new Pe,"Input");class Ee{constructor(e){this.target_=e??null}build(e){const t=new Pe;e.insertResource(Te,t);const r=this.target_??document.querySelector("canvas")??document.body;document.addEventListener("keydown",e=>{t.keysDown.has(e.code)||t.keysPressed.add(e.code),t.keysDown.add(e.code)}),document.addEventListener("keyup",e=>{t.keysDown.delete(e.code),t.keysReleased.add(e.code)}),r.addEventListener("mousemove",e=>{t.mouseX=e.offsetX,t.mouseY=e.offsetY}),r.addEventListener("mousedown",e=>{const r=e.button;t.mouseButtons.add(r),t.mouseButtonsPressed.add(r)}),r.addEventListener("mouseup",e=>{const r=e.button;t.mouseButtons.delete(r),t.mouseButtonsReleased.add(r)}),r.addEventListener("touchstart",e=>{const n=e.touches[0];if(n){const e=r.getBoundingClientRect();t.mouseX=n.clientX-e.left,t.mouseY=n.clientY-e.top,t.mouseButtons.add(0),t.mouseButtonsPressed.add(0)}}),r.addEventListener("touchmove",e=>{const n=e.touches[0];if(n){const e=r.getBoundingClientRect();t.mouseX=n.clientX-e.left,t.mouseY=n.clientY-e.top}}),r.addEventListener("touchend",()=>{t.mouseButtons.delete(0),t.mouseButtonsReleased.add(0)}),r.addEventListener("wheel",e=>{t.scrollDeltaX+=e.deltaX,t.scrollDeltaY+=e.deltaY}),e.addSystemToSchedule(ge.First,we([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ae=new Ee;class Me{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}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,r){return X(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return X(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return X(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){X(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const n={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,n)}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const n=t.create(r);return this.getStorage(t).set(e,n),n}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let n=!0;for(const t of e)if(!this.has(r,t)){n=!1;break}n&&t.push(r)}return t}}var Re,Fe,Ue;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Re||(Re={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Fe||(Fe={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ue||(Ue={}));const Be=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Re.Left,verticalAlign:Fe.Top,wordWrap:!0,overflow:Ue.Visible,lineHeight:1.2,dirty:!0});class ze{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;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=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Ue.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.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;r.clearRect(0,0,n.width,n.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Ue.Clip&&(r.save(),r.beginPath(),r.rect(0,0,f,p),r.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Fe.Top:x=u;break;case Fe.Middle:x=(p-w)/2;break;case Fe.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 Re.Left:n=u;break;case Re.Center:n=f/2;break;case Re.Right:n=f-u;break;default:n=u}r.fillText(t,n,v),v+=l}s&&e.overflow===Ue.Clip&&r.restore();const S=r.getImageData(0,0,f,p),C=new Uint8Array(S.data.buffer),b=this.flipVertically(C,f,p),P=this.module.getResourceManager(),T=this.module._malloc(b.length);this.module.HEAPU8.set(b,T);const E=P.createTexture(f,p,T,b.length,1);return this.module._free(T),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const s=this.renderText(t,r);return this.cache.set(e,s),s}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)}}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 r=e.split("\n"),n=[];for(const e of r){if(!e){n.push("");continue}let r="";for(const s of e){const e=r+s;this.ctx.measureText(e).width>t&&r?(n.push(r),r=s):r=e}r&&n.push(r)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case Re.Left:return"left";case Re.Center:return"center";case Re.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const i=t*n,o=(r-1-t)*n;s.set(e.subarray(i,i+n),o)}return s}}const ke=L("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class $e{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new ze(t),n=e.world;e.addSystemToSchedule(ge.PreUpdate,we([],()=>{const e=n.getEntitiesWithComponents([Be]);for(const t of e){const e=n.get(t,Be);if(!e.dirty)continue;n.has(t,Y)||n.insert(t,Y,{texture:R,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=n.has(t,ke)?n.get(t,ke):null,i=r.renderForEntity(t,e,s),o=n.get(t,Y);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},n.insert(t,Y,o),e.dirty=!1}}))}}const Ie=new $e;var We;function Le(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"}(We||(We={}));let De=null,Ge=null,Oe=1;const Ne=new Map;function He(e){De=e,Ge=e.getResourceManager(),Qe()}function Xe(){0!==qe&&De&&(De._free(qe),qe=0),Ne.clear(),Oe=1,Ye=!1,Ge=null,De=null}function je(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const Ve={createShader:(e,t)=>je().createShader(e,t),releaseShader(e){e>0&&je().releaseShader(e)},create(e){const t=Oe++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??We.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Ne.set(t,r),t},get:e=>Ne.get(e),setUniform(e,t,r){const n=Ne.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Ne.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ne.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??We.Normal},setDepthTest(e,t){const r=Ne.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),createFromAsset(e,t){const r={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)r[t]=n;else if("object"==typeof n&&null!==n){const e=n;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??We.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Oe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ne.set(r,n),r},toAssetData(e,t){const r=Ne.get(e);if(!r)return null;const n={};for(const[e,t]of r.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.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,qe=0;const Ke=4096;function Je(e){const t=(0===qe&&De&&(qe=De._malloc(Ke)),qe);if(0===t||!De)return{ptr:0,count:0};let r=0,n=0;const s=De.HEAPU8,i=De.HEAPU32,o=De.HEAPF32;for(const[a,c]of e){if(r+128>Ke)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+r>>2]=l,r+=4,s.set(e,t+r),r+=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+r>>2]=h,r+=4;for(let e=0;e<4;e++)o[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function Qe(){if(!De||Ye)return;De.materialDataProvider=(e,t,r,n,s)=>{const i=Ne.get(e);if(!i)return De.HEAPU32[t>>2]=0,De.HEAPU32[r>>2]=0,De.HEAPU32[n>>2]=0,void(De.HEAPU32[s>>2]=0);De.HEAPU32[t>>2]=i.shader,De.HEAPU32[r>>2]=i.blendMode;const{ptr:o,count:a}=Je(i.uniforms);De.HEAPU32[n>>2]=o,De.HEAPU32[s>>2]=a},Ye=!0}const Ze={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"};let et=null,tt=0,rt=0,nt=0;const st=new Float32Array(256);function it(e){et=e,tt=et._malloc(64),rt=et._malloc(64),nt=et._malloc(1024)}function ot(){et&&(tt&&(et._free(tt),tt=0),rt&&(et._free(rt),rt=0),nt&&(et._free(nt),nt=0)),et=null}function at(){if(!et)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return et}const ct={x:1,y:1,z:1,w:1},lt={begin(e){const t=at();t.HEAPF32.set(e,tt/4),t.draw_begin(tt)},end(){at().draw_end()},line(e,t,r,n=1){at().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rect(e,t,r,n=!0){at().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rectOutline(e,t,r,n=1){at().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},circle(e,t,r,n=!0,s=32){at().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},circleOutline(e,t,r,n=1,s=32){at().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=ct){at().draw_texture(e.x,e.y,t.x,t.y,r,n.x,n.y,n.z,n.w)},textureRotated(e,t,r,n,s=ct){at().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){at().draw_setLayer(e)},setDepth(e){at().draw_setDepth(e)},getDrawCallCount:()=>et?et.draw_getDrawCallCount():0,getPrimitiveCount:()=>et?et.draw_getPrimitiveCount():0,setBlendMode(e){at().draw_setBlendMode(e)},setDepthTest(e){at().draw_setDepthTest(e)},drawMesh(e,t,r){const n=at();n.HEAPF32.set(r,rt/4),n.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,r){const n=at(),s=Ve.get(t);if(!s)return;if(lt.setBlendMode(s.blendMode),lt.setDepthTest(s.depthTest),0===s.uniforms.size)return void lt.drawMesh(e,s.shader,r);n.HEAPF32.set(r,rt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const r=ht(e);if(!(r<0)){if(Le(t))st[i++]=10,st[i++]=r,st[i++]=t.slot??o++,st[i++]=t.textureId;else if("number"==typeof t)st[i++]=1,st[i++]=r,st[i++]=t;else if(Array.isArray(t)){st[i++]=t.length,st[i++]=r;for(let e=0;e<t.length;e++)st[i++]=t[e]}else"w"in t?(st[i++]=4,st[i++]=r,st[i++]=t.x,st[i++]=t.y,st[i++]=t.z,st[i++]=t.w):"z"in t?(st[i++]=3,st[i++]=r,st[i++]=t.x,st[i++]=t.y,st[i++]=t.z):(st[i++]=2,st[i++]=r,st[i++]=t.x,st[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(n.HEAPF32.set(st.subarray(0,i),nt/4),n.draw_meshWithUniforms(e,s.shader,rt,nt,i)):n.draw_mesh(e,s.shader,rt)}},ut={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ht(e){return ut[e]??-1}var dt;!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"}(dt||(dt={}));let ft=null,pt=0,_t=0,mt=0;function gt(e){ft=e,pt=ft._malloc(262144),_t=ft._malloc(65536),mt=ft._malloc(256)}function yt(){ft&&(pt&&ft._free(pt),_t&&ft._free(_t),mt&&ft._free(mt),pt=0,_t=0,mt=0),ft=null}function wt(){if(!ft)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ft}const xt={create(e){const t=wt(),r=t.geometry_create();if(0===r)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,pt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,mt,s).set(i),t.geometry_init(r,pt,n,mt,s,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,_t,n).set(e.indices),t.geometry_setIndices16(r,_t,n)}else{new Uint32Array(t.HEAPU8.buffer,_t,n).set(e.indices),t.geometry_setIndices32(r,_t,n)}}return r},updateVertices(e,t,r=0){const n=wt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,pt/4),n.geometry_updateVertices(e,pt,s,r)},release(e){e>0&&wt().geometry_release(e)},isValid:e=>!(!ft||e<=0)&&ft.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return xt.create({vertices:new Float32Array([-r,-n,0,0,r,-n,1,0,r,n,1,1,-r,n,0,1]),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;r.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.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,r=1/0,n=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-r)/(s-r);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 xt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.Float2}],indices:new Uint16Array(o)})}};let vt=null;function St(e){vt=e}function Ct(){vt&&Pt.isInitialized()&&Pt.shutdown(),vt=null}function bt(){if(!vt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vt}const Pt={init:(e,t)=>bt().postprocess_init(e,t),shutdown(){bt().postprocess_shutdown()},resize(e,t){bt().postprocess_resize(e,t)},addPass:(e,t)=>bt().postprocess_addPass(e,t),removePass(e){bt().postprocess_removePass(e)},setEnabled(e,t){bt().postprocess_setPassEnabled(e,t)},isEnabled:e=>bt().postprocess_isPassEnabled(e),setUniform(e,t,r){bt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){bt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){bt().postprocess_begin()},end(){bt().postprocess_end()},getPassCount:()=>bt().postprocess_getPassCount(),isInitialized:()=>!!vt&&vt.postprocess_isInitialized(),setBypass(e){bt().postprocess_setBypass(e)},isBypassed:()=>!vt||vt.postprocess_isBypassed(),createBlur:()=>Ve.createShader(Tt,"#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:()=>Ve.createShader(Tt,"#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:()=>Ve.createShader(Tt,"#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:()=>Ve.createShader(Tt,"#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")},Tt="#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 Et;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Et||(Et={}));let At=null,Mt=0;function Rt(e){At=e,Mt=At._malloc(64)}function Ft(){At&&Mt&&(At._free(Mt),Mt=0),At=null}const Ut={init(e,t){At?.renderer_init(e,t)},resize(e,t){At?.renderer_resize(e,t)},begin(e,t){At&&Mt&&(At.HEAPF32.set(e,Mt/4),At.renderer_begin(Mt,t??0))},flush(){At?.renderer_flush()},end(){At?.renderer_end()},submitSprites(e){At&&At.renderer_submitSprites(e._cpp)},submitSpine(e){At&&At.renderer_submitSpine(e._cpp)},setStage(e){At?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>At?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){At?.renderer_releaseTarget(e)},getTargetTexture:e=>At?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>At?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){At?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>At?{drawCalls:At.renderer_getDrawCalls(),triangles:At.renderer_getTriangles(),sprites:At.renderer_getSprites(),spine:At.renderer_getSpine(),meshes:At.renderer_getMeshes(),culled:At.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Bt=null;function zt(e){Bt=e}function kt(){Bt=null}const $t={enable(){Bt?.gl_enableErrorCheck(!0)},disable(){Bt?.gl_enableErrorCheck(!1)},check:e=>Bt?.gl_checkErrors(e)??0,diagnose(){Bt?.renderer_diagnose()}},It=new Map;function Wt(e,t){It.set(e,t)}function Lt(e){It.delete(e)}function Dt(){It.clear()}class Gt{render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:i}=e;Ut.resize(n,s),Pt.isInitialized()&&Pt.getPassCount()>0&&!Pt.isBypassed()&&Pt.resize(n,s),Ut.begin(r),Ut.submitSprites(t),Ut.submitSpine(t),Ut.flush();const o=It;if(o.size>0){lt.begin(r);const e=[];for(const[t,r]of o.entries())try{r(i)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}lt.end();for(const t of e)Lt(t)}Ut.end()}}class Ot{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.module_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;this.updateTime(r),this.runSchedule(ge.First),this.runSchedule(ge.PreUpdate),this.runSchedule(ge.Update),this.runSchedule(ge.PostUpdate),this.runSchedule(ge.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Me,this.resources_=new ce;for(const e of Object.values(ge))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ot}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ge.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ge.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new be(this.world_,this.resources_),this.resources_.insert(le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ge.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,kt(),Ft(),Ct(),yt(),Xe(),ot()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(le),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(le,r)}}function Nt(e,t){const r=Ot.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),it(e),He(e),gt(e),St(e),Rt(e),zt(e);const s=new Gt;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const n=e.getCamera(s);if(!n.isActive)continue;const i=e.getLocalTransform(s),o=t/r;let a;if(1===n.projectionType){const e=n.orthoSize,t=e*o;a=jt(-t,t,-e,e,-n.farPlane,n.farPlane)}else a=Vt(n.fov*Math.PI/180,o,n.nearPlane,n.farPlane);return qt(a,Yt(i.position.x,i.position.y,i.position.z))}return Xt}(n,e,t),a=(d()-i)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:a})}};return r.addSystemToSchedule(ge.Last,a),r.addPlugin(Ae),r.addPlugin(Ie),r}function Ht(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}}const Xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function jt(e,t,r,n,s,i){const o=new Float32Array(16),a=t-e,c=n-r,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+r)/c,o[14]=-(i+s)/l,o[15]=1,o}function Vt(e,t,r,n){const s=new Float32Array(16),i=1/Math.tan(e/2),o=r-n;return s[0]=i/t,s[5]=i,s[10]=(n+r)/o,s[11]=-1,s[14]=2*n*r/o,s}function Yt(e,t,r){const n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n[12]=-e,n[13]=-t,n[14]=-r,n}function qt(e,t){const r=new Float32Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)r[4*s+n]=e[0+n]*t[4*s+0]+e[4+n]*t[4*s+1]+e[8+n]*t[4*s+2]+e[12+n]*t[4*s+3];return r}class Kt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const n=this.loadInternal(e);this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ve.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 r=await c(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(r);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const s=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(s);return{handle:Ve.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 r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function Jt(e,t){const r=new Map;for(const n of t.entities){const t=e.spawn();r.set(n.id,t);for(const r of n.components)Zt(e,t,r)}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return r}async function Qt(e,t,r){const n=new Map,s=r?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();n.set(o.id,t);for(const n of o.components){if("Sprite"===n.type&&s){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await s.loadTexture(n);e.texture=r.handle,i.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===n.type&&s){const e=n.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Zt(e,t,n)}}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function Zt(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,j,n);break;case"Sprite":e.insert(t,Y,n);break;case"Camera":e.insert(t,q,n);break;case"Canvas":e.insert(t,K,n);break;case"Text":e.insert(t,Be,n);break;case"SpineAnimation":e.insert(t,ee,n);break;case"UIRect":e.insert(t,ke,n);break;default:{const s=G(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function er(e,t){const r=e.getEntitiesWithComponents([q]);for(const n of r){const r=e.get(n,q);r&&(r.aspectRatio=t,e.insert(n,q,r))}}class tr{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const n=this.pending_.get(e);if(n)return n;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class rr{constructor(e){this.textureCache_=new tr,this.shaderCache_=new tr,this.jsonCache_=new tr,this.textCache_=new tr,this.binaryCache_=new tr,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}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 r of[!0,!1]){const n=this.textureCacheKey(e,r),s=this.textureCache_.get(n);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const s=this.resolveUrl(t,r),i=await fetch(s);if(!i.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const o=await i.text();if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(o);for(const e of c){const t=a?`${a}/${e}`:e,n=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(n),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}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 r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return Qt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const n of e.textures)r.push(this.loadTexture(n).then(e=>{t.textures.set(n,e)}));if(e.materials)for(const n of e.materials)r.push(this.loadMaterial(n).then(e=>{t.materials.set(n,e)}));if(e.spine)for(const n of e.spine){const e=`${n.skeleton}:${n.atlas}`;r.push(this.loadSpine(n.skeleton,n.atlas,n.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const n of e.json)r.push(this.loadJson(n).then(e=>{t.json.set(n,e)}));if(e.text)for(const n of e.text)r.push(this.loadText(n).then(e=>{t.text.set(n,e)}));if(e.binary)for(const n of e.binary)r.push(this.loadBinary(n).then(e=>{t.binary.set(n,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}createTextureFromImage(e,t){const{width:r,height:n}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,r,n,t):this.createTextureFallback(e,r,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,r,n,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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,r,n),width:r,height:n}}createTextureFallback(e,t,r,n){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,r),i=new Uint8Array(s.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,r,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const n=255/r;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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:n}=this.parseEsShader(t);if(!r||!n)throw new Error(`Invalid shader format: ${e}`);return Ve.createShader(r,n)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}async fetchJson(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.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 r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const n=r.split("/").filter(e=>e);let s="";for(const e of n){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const nr=se(null,"Assets");class sr{build(e){const t=e.wasmModule;t?e.insertResource(nr,new rr(t)):console.warn("AssetPlugin: No WASM module available")}}const ir=new sr;class or{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(nr)||e.addPlugin(ir),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=this.app_.getResource(nr);await r.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([q]);for(const n of r){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(t,j,r);const n={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,q,n)}}}class ar{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,r=!0,n=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,r,n)}addAnimation(e,t,r=!0,n=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,r,n,s)}setEmptyAnimation(e,t=.2,r=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,r)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const r=this.module_.spineGetBonePosition(e,t);return r?{x:r.x,y:r.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,r){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,r||"")}on(e,t,r){this.listeners_.has(e)||this.listeners_.set(e,new Map);const n=this.listeners_.get(e);n.has(t)||n.set(t,new Set),n.get(t).add(r)}off(e,t,r){const n=this.listeners_.get(e);if(!n)return;const s=n.get(t);s&&s.delete(r)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const r=this.listeners_.get(e);if(!r)return;const n={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=r.get(n.type);s&&s.forEach(e=>{try{e(n)}catch(e){console.error("Error in Spine event callback:",e)}})}}function cr(e){return new ar(e)}const lr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Ut.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Ut.getTargetTexture(r),width:e.width,height:e.height}},release(e){Ut.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Ut.releaseRenderTarget(e._handle),lr.create({width:t,height:r,depth:!0})),begin(e,t){Ut.begin(t,e._handle)},end(){Ut.end()},getDepthTexture:e=>Ut.getTargetDepthTexture(e._handle)};let ur=!1;function hr(e){ur=e}function dr(){return ur}function fr(){return!ur}var pr;E||(E=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(r,n);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.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:r}}),"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),r=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?r[n++]=s:s<2048?(r[n++]=192|s>>6,r[n++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,r[n++]=240|s>>18,r[n++]=128|s>>12&63,r[n++]=128|s>>6&63,r[n++]=128|63&s):(r[n++]=224|s>>12,r[n++]=128|s>>6&63,r[n++]=128|63&s)}return r.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const n=t[e];if(n<128)r+=String.fromCharCode(n),e++;else if(192==(224&n))r+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))r+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=pr=A,console.log(`[ESEngine] Platform: ${pr.name}`);export{Ot as App,sr as AssetPlugin,rr as AssetServer,nr as Assets,tr as AsyncCache,We as BlendMode,q as Camera,K as Canvas,Z as Children,pe as Commands,me as CommandsInstance,dt as DataType,lt as Draw,_e as EntityCommands,$t as GLDebug,xt as Geometry,M as INVALID_ENTITY,R as INVALID_TEXTURE,Te as Input,Ee as InputPlugin,Pe as InputState,j as LocalTransform,Ve as Material,Kt as MaterialLoader,ue as Mut,Q as Parent,Pt as PostProcess,or as PreviewPlugin,de as Query,fe as QueryInstance,Gt as RenderPipeline,Et as RenderStage,lr as RenderTexture,Ut as Renderer,ie as Res,oe as ResMut,ge as Schedule,Ze as ShaderSources,ee as SpineAnimation,ar as SpineController,Y as Sprite,be as SystemRunner,Be as Text,Re as TextAlign,Ue as TextOverflow,$e as TextPlugin,ze as TextRenderer,Fe as TextVerticalAlign,le as Time,ke as UIRect,J as Velocity,Me as World,V as WorldTransform,Se as addStartupSystem,ve as addSystem,Ce as addSystemToSchedule,ir as assetPlugin,Dt as clearDrawCallbacks,O as clearUserComponents,z as color,cr as createSpineController,Nt as createWebApp,L as defineComponent,se as defineResource,we as defineSystem,D as defineTag,Ht as flushPendingSystems,re as getComponentDefaults,t as getPlatform,n as getPlatformType,G as getUserComponent,it as initDrawAPI,zt as initGLDebugAPI,gt as initGeometryAPI,He as initMaterialAPI,St as initPostProcessAPI,Rt as initRendererAPI,Ae as inputPlugin,X as isBuiltinComponent,dr as isEditor,r as isPlatformInitialized,fr as isRuntime,Le as isTextureRef,s as isWeChat,i as isWeb,Zt as loadComponent,Jt as loadSceneData,Qt as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,k as quat,Wt as registerDrawCallback,Qe as registerMaterialCallback,hr as setEditorMode,ot as shutdownDrawAPI,kt as shutdownGLDebugAPI,yt as shutdownGeometryAPI,Xe as shutdownMaterialAPI,Ct as shutdownPostProcessAPI,Ft as shutdownRendererAPI,Ie as textPlugin,Lt as unregisterDrawCallback,er as updateCameraAspectRatio,F as vec2,U as vec3,B as vec4,w as wxFileExists,x as wxFileExistsSync,P as wxGetImagePixels,b as wxLoadImage,T as wxLoadImagePixels,g as wxReadFile,y as wxReadTextFile,v 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 r(){return null!==e}function n(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,r){return t().fetch(e,r)}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,r){return t().instantiateWasm(e,r)}function h(e,r){return t().createCanvas(e,r)}function d(){return t().now()}function f(e,t){return new Promise((r,n)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"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];r({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,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).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 r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,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 "${r}": ${t}`)}}let _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,r)=>{m().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function y(e,t="utf-8"){return new Promise((r,n)=>{m().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function v(e,t){return new Promise((r,n)=>{m().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let S=null,C=null;function b(e){return new Promise((t,r)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function T(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return S||(S=wx.createCanvas(),S.width=e,S.height=t,C=S.getContext("2d")),(S.width<e||S.height<t)&&(S.width=Math.max(S.width,e),S.height=Math.max(S.height,t)),{canvas:S,ctx:C}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const i=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(i.data.buffer)}}async function P(e,t=!0){return T(await b(e),t)}let E=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return g(e)}async readTextFile(e){return y(e)}async fileExists(e){return w(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)}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}},M=0,R=4294967295,F=(e=0,t=0)=>({x:e,y:t}),U=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),B=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),z=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),k=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let $=0;function I(e,t){const r=++$;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function W(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const r=W(),n=r.get(e);if(n)return n;const s=I(e,t);return r.set(e,s),N(e,t,!1),s}function D(e){const t=W(),r=t.get(e);if(r)return r;const n=I(e,{});return t.set(e,n),N(e,{},!0),n}function G(e){return W().get(e)}function O(){W().clear()}function N(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function H(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function X(e){return!0===e._builtin}const j=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:R,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),K=H("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=H("Parent",{entity:0}),Z=H("Children",{entities:[]}),ee=H("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),te={LocalTransform:j,WorldTransform:V,Sprite:Y,Camera:q,Canvas:K,Velocity:J,Parent:Q,Children:Z,SpineAnimation:ee};function re(e){const t=te[e];if(t)return{...t._default};const r=G(e);return r?{...r._default}:null}let ne=0;function se(e,t){const r=++ne;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function ie(e){return{_type:"res",_resource:e}}function oe(e){return{_type:"res_mut",_resource:e}}class ae{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 ce{constructor(){this.resources_=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)}getResMut(e){return new ae(this.get(e),t=>this.set(e,t))}}const le=se({delta:0,elapsed:0,frameCount:0},"Time");function ue(e){return{_type:"mut",_component:e}}function he(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function de(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{he(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)}class fe{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return he(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:n}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...r],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let r=!1;for(const t of n)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}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(){return[...this]}}function pe(){return{_type:"commands"}}class _e{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 r;return r=X(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),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 me{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new _e(this,null)}entity(e){return new _e(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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ge;!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"}(ge||(ge={}));let ye=0;function we(e,t,r){const n=++ye;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function xe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ve(e){xe().push({schedule:ge.Update,system:e})}function Se(e){xe().push({schedule:ge.Startup,system:e})}function Ce(e,t){xe().push({schedule:e,system:t})}class be{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof me&&e.flush()}resolveParam(e){switch(e._type){case"query":return new fe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new me(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Te{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 Pe=se(new Te,"Input");class Ee{constructor(e){this.target_=e??null}build(e){const t=new Te;e.insertResource(Pe,t);const r=this.target_??document.querySelector("canvas")??document.body;document.addEventListener("keydown",e=>{t.keysDown.has(e.code)||t.keysPressed.add(e.code),t.keysDown.add(e.code)}),document.addEventListener("keyup",e=>{t.keysDown.delete(e.code),t.keysReleased.add(e.code)}),r.addEventListener("mousemove",e=>{t.mouseX=e.offsetX,t.mouseY=e.offsetY}),r.addEventListener("mousedown",e=>{const r=e.button;t.mouseButtons.add(r),t.mouseButtonsPressed.add(r)}),r.addEventListener("mouseup",e=>{const r=e.button;t.mouseButtons.delete(r),t.mouseButtonsReleased.add(r)}),r.addEventListener("touchstart",e=>{const n=e.touches[0];if(n){const e=r.getBoundingClientRect();t.mouseX=n.clientX-e.left,t.mouseY=n.clientY-e.top,t.mouseButtons.add(0),t.mouseButtonsPressed.add(0)}}),r.addEventListener("touchmove",e=>{const n=e.touches[0];if(n){const e=r.getBoundingClientRect();t.mouseX=n.clientX-e.left,t.mouseY=n.clientY-e.top}}),r.addEventListener("touchend",()=>{t.mouseButtons.delete(0),t.mouseButtonsReleased.add(0)}),r.addEventListener("wheel",e=>{t.scrollDeltaX+=e.deltaX,t.scrollDeltaY+=e.deltaY}),e.addSystemToSchedule(ge.First,we([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ae=new Ee;class Me{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}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,r){return X(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return X(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return X(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){X(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const n={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,n)}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const n=t.create(r);return this.getStorage(t).set(e,n),n}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let n=!0;for(const t of e)if(!this.has(r,t)){n=!1;break}n&&t.push(r)}return t}}var Re,Fe,Ue;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Re||(Re={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Fe||(Fe={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ue||(Ue={}));const Be=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Re.Left,verticalAlign:Fe.Top,wordWrap:!0,overflow:Ue.Visible,lineHeight:1.2,dirty:!0});class ze{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;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=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Ue.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.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;r.clearRect(0,0,n.width,n.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Ue.Clip&&(r.save(),r.beginPath(),r.rect(0,0,f,p),r.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Fe.Top:x=u;break;case Fe.Middle:x=(p-w)/2;break;case Fe.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 Re.Left:n=u;break;case Re.Center:n=f/2;break;case Re.Right:n=f-u;break;default:n=u}r.fillText(t,n,v),v+=l}s&&e.overflow===Ue.Clip&&r.restore();const S=r.getImageData(0,0,f,p),C=new Uint8Array(S.data.buffer),b=this.flipVertically(C,f,p),T=this.module.getResourceManager(),P=this.module._malloc(b.length);this.module.HEAPU8.set(b,P);const E=T.createTexture(f,p,P,b.length,1);return this.module._free(P),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const s=this.renderText(t,r);return this.cache.set(e,s),s}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)}}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 r=e.split("\n"),n=[];for(const e of r){if(!e){n.push("");continue}let r="";for(const s of e){const e=r+s;this.ctx.measureText(e).width>t&&r?(n.push(r),r=s):r=e}r&&n.push(r)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case Re.Left:return"left";case Re.Center:return"center";case Re.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const i=t*n,o=(r-1-t)*n;s.set(e.subarray(i,i+n),o)}return s}}const ke=L("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class $e{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new ze(t),n=e.world;e.addSystemToSchedule(ge.PreUpdate,we([],()=>{const e=n.getEntitiesWithComponents([Be]);for(const t of e){const e=n.get(t,Be);if(!e.dirty)continue;n.has(t,Y)||n.insert(t,Y,{texture:R,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=n.has(t,ke)?n.get(t,ke):null,i=r.renderForEntity(t,e,s),o=n.get(t,Y);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},n.insert(t,Y,o),e.dirty=!1}}))}}const Ie=new $e;var We;function Le(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"}(We||(We={}));let De=null,Ge=null,Oe=1;const Ne=new Map;function He(e){De=e,Ge=e.getResourceManager(),Qe()}function Xe(){0!==qe&&De&&(De._free(qe),qe=0),Ne.clear(),Oe=1,Ye=!1,Ge=null,De=null}function je(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const Ve={createShader:(e,t)=>je().createShader(e,t),releaseShader(e){e>0&&je().releaseShader(e)},create(e){const t=Oe++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??We.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Ne.set(t,r),t},get:e=>Ne.get(e),setUniform(e,t,r){const n=Ne.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Ne.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ne.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??We.Normal},setDepthTest(e,t){const r=Ne.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),createFromAsset(e,t){const r={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)r[t]=n;else if("object"==typeof n&&null!==n){const e=n;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??We.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Oe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ne.set(r,n),r},toAssetData(e,t){const r=Ne.get(e);if(!r)return null;const n={};for(const[e,t]of r.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.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,qe=0;const Ke=4096;function Je(e){const t=(0===qe&&De&&(qe=De._malloc(Ke)),qe);if(0===t||!De)return{ptr:0,count:0};let r=0,n=0;const s=De.HEAPU8,i=De.HEAPU32,o=De.HEAPF32;for(const[a,c]of e){if(r+128>Ke)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+r>>2]=l,r+=4,s.set(e,t+r),r+=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+r>>2]=h,r+=4;for(let e=0;e<4;e++)o[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function Qe(){if(!De||Ye)return;De.materialDataProvider=(e,t,r,n,s)=>{const i=Ne.get(e);if(!i)return De.HEAPU32[t>>2]=0,De.HEAPU32[r>>2]=0,De.HEAPU32[n>>2]=0,void(De.HEAPU32[s>>2]=0);De.HEAPU32[t>>2]=i.shader,De.HEAPU32[r>>2]=i.blendMode;const{ptr:o,count:a}=Je(i.uniforms);De.HEAPU32[n>>2]=o,De.HEAPU32[s>>2]=a},Ye=!0}const Ze={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"};let et=null,tt=0,rt=0,nt=0;const st=new Float32Array(256);function it(e){et=e,tt=et._malloc(64),rt=et._malloc(64),nt=et._malloc(1024)}function ot(){et&&(tt&&(et._free(tt),tt=0),rt&&(et._free(rt),rt=0),nt&&(et._free(nt),nt=0)),et=null}function at(){if(!et)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return et}const ct={x:1,y:1,z:1,w:1},lt={begin(e){const t=at();t.HEAPF32.set(e,tt/4),t.draw_begin(tt)},end(){at().draw_end()},line(e,t,r,n=1){at().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rect(e,t,r,n=!0){at().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rectOutline(e,t,r,n=1){at().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},circle(e,t,r,n=!0,s=32){at().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},circleOutline(e,t,r,n=1,s=32){at().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=ct){at().draw_texture(e.x,e.y,t.x,t.y,r,n.x,n.y,n.z,n.w)},textureRotated(e,t,r,n,s=ct){at().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){at().draw_setLayer(e)},setDepth(e){at().draw_setDepth(e)},getDrawCallCount:()=>et?et.draw_getDrawCallCount():0,getPrimitiveCount:()=>et?et.draw_getPrimitiveCount():0,setBlendMode(e){at().draw_setBlendMode(e)},setDepthTest(e){at().draw_setDepthTest(e)},drawMesh(e,t,r){const n=at();n.HEAPF32.set(r,rt/4),n.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,r){const n=at(),s=Ve.get(t);if(!s)return;if(lt.setBlendMode(s.blendMode),lt.setDepthTest(s.depthTest),0===s.uniforms.size)return void lt.drawMesh(e,s.shader,r);n.HEAPF32.set(r,rt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const r=ht(e);if(!(r<0)){if(Le(t))st[i++]=10,st[i++]=r,st[i++]=t.slot??o++,st[i++]=t.textureId;else if("number"==typeof t)st[i++]=1,st[i++]=r,st[i++]=t;else if(Array.isArray(t)){st[i++]=t.length,st[i++]=r;for(let e=0;e<t.length;e++)st[i++]=t[e]}else"w"in t?(st[i++]=4,st[i++]=r,st[i++]=t.x,st[i++]=t.y,st[i++]=t.z,st[i++]=t.w):"z"in t?(st[i++]=3,st[i++]=r,st[i++]=t.x,st[i++]=t.y,st[i++]=t.z):(st[i++]=2,st[i++]=r,st[i++]=t.x,st[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(n.HEAPF32.set(st.subarray(0,i),nt/4),n.draw_meshWithUniforms(e,s.shader,rt,nt,i)):n.draw_mesh(e,s.shader,rt)}},ut={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ht(e){return ut[e]??-1}var dt;!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"}(dt||(dt={}));let ft=null,pt=0,_t=0,mt=0;function gt(e){ft=e,pt=ft._malloc(262144),_t=ft._malloc(65536),mt=ft._malloc(256)}function yt(){ft&&(pt&&ft._free(pt),_t&&ft._free(_t),mt&&ft._free(mt),pt=0,_t=0,mt=0),ft=null}function wt(){if(!ft)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ft}const xt={create(e){const t=wt(),r=t.geometry_create();if(0===r)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,pt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,mt,s).set(i),t.geometry_init(r,pt,n,mt,s,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,_t,n).set(e.indices),t.geometry_setIndices16(r,_t,n)}else{new Uint32Array(t.HEAPU8.buffer,_t,n).set(e.indices),t.geometry_setIndices32(r,_t,n)}}return r},updateVertices(e,t,r=0){const n=wt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,pt/4),n.geometry_updateVertices(e,pt,s,r)},release(e){e>0&&wt().geometry_release(e)},isValid:e=>!(!ft||e<=0)&&ft.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return xt.create({vertices:new Float32Array([-r,-n,0,0,r,-n,1,0,r,n,1,1,-r,n,0,1]),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;r.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.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,r=1/0,n=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-r)/(s-r);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 xt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.Float2}],indices:new Uint16Array(o)})}};let vt=null;function St(e){vt=e}function Ct(){vt&&Tt.isInitialized()&&Tt.shutdown(),vt=null}function bt(){if(!vt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vt}const Tt={init:(e,t)=>bt().postprocess_init(e,t),shutdown(){bt().postprocess_shutdown()},resize(e,t){bt().postprocess_resize(e,t)},addPass:(e,t)=>bt().postprocess_addPass(e,t),removePass(e){bt().postprocess_removePass(e)},setEnabled(e,t){bt().postprocess_setPassEnabled(e,t)},isEnabled:e=>bt().postprocess_isPassEnabled(e),setUniform(e,t,r){bt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){bt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){bt().postprocess_begin()},end(){bt().postprocess_end()},getPassCount:()=>bt().postprocess_getPassCount(),isInitialized:()=>!!vt&&vt.postprocess_isInitialized(),setBypass(e){bt().postprocess_setBypass(e)},isBypassed:()=>!vt||vt.postprocess_isBypassed(),createBlur:()=>Ve.createShader(Pt,"#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:()=>Ve.createShader(Pt,"#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:()=>Ve.createShader(Pt,"#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:()=>Ve.createShader(Pt,"#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")},Pt="#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 Et;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Et||(Et={}));let At=null,Mt=0;function Rt(e){At=e,Mt=At._malloc(64)}function Ft(){At&&Mt&&(At._free(Mt),Mt=0),At=null}const Ut={init(e,t){At?.renderer_init(e,t)},resize(e,t){At?.renderer_resize(e,t)},begin(e,t){At&&Mt&&(At.HEAPF32.set(e,Mt/4),At.renderer_begin(Mt,t??0))},flush(){At?.renderer_flush()},end(){At?.renderer_end()},submitSprites(e){At&&At.renderer_submitSprites(e._cpp)},submitSpine(e){At&&At.renderer_submitSpine(e._cpp)},setStage(e){At?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>At?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){At?.renderer_releaseTarget(e)},getTargetTexture:e=>At?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>At?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){At?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>At?{drawCalls:At.renderer_getDrawCalls(),triangles:At.renderer_getTriangles(),sprites:At.renderer_getSprites(),spine:At.renderer_getSpine(),meshes:At.renderer_getMeshes(),culled:At.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Bt=null;function zt(e){Bt=e}function kt(){Bt=null}const $t={enable(){Bt?.gl_enableErrorCheck(!0)},disable(){Bt?.gl_enableErrorCheck(!1)},check:e=>Bt?.gl_checkErrors(e)??0,diagnose(){Bt?.renderer_diagnose()}},It=new Map;function Wt(e,t){It.set(e,t)}function Lt(e){It.delete(e)}function Dt(){It.clear()}class Gt{render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:i}=e;Ut.resize(n,s),Tt.isInitialized()&&Tt.getPassCount()>0&&!Tt.isBypassed()&&Tt.resize(n,s),Ut.begin(r),Ut.submitSprites(t),Ut.submitSpine(t),Ut.flush();const o=It;if(o.size>0){lt.begin(r);const e=[];for(const[t,r]of o.entries())try{r(i)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}lt.end();for(const t of e)Lt(t)}Ut.end()}}class Ot{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.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(ge.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ge.FixedPreUpdate),this.runSchedule(ge.FixedUpdate),this.runSchedule(ge.FixedPostUpdate);this.runSchedule(ge.PreUpdate),this.runSchedule(ge.Update),this.runSchedule(ge.PostUpdate),this.runSchedule(ge.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Me,this.resources_=new ce;for(const e of Object.values(ge))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ot}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ge.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ge.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new be(this.world_,this.resources_),this.resources_.insert(le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ge.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,kt(),Ft(),Ct(),yt(),Xe(),ot()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(le),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(le,r)}}function Nt(e,t){const r=Ot.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),it(e),He(e),gt(e),St(e),Rt(e),zt(e);const s=new Gt;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const n=e.getCamera(s);if(!n.isActive)continue;const i=e.getLocalTransform(s),o=t/r;let a;if(1===n.projectionType){const e=n.orthoSize,t=e*o;a=jt(-t,t,-e,e,-n.farPlane,n.farPlane)}else a=Vt(n.fov*Math.PI/180,o,n.nearPlane,n.farPlane);return qt(a,Yt(i.position.x,i.position.y,i.position.z))}return Xt}(n,e,t),a=(d()-i)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:a})}};return r.addSystemToSchedule(ge.Last,a),r.addPlugin(Ae),r.addPlugin(Ie),r}function Ht(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}}const Xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function jt(e,t,r,n,s,i){const o=new Float32Array(16),a=t-e,c=n-r,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+r)/c,o[14]=-(i+s)/l,o[15]=1,o}function Vt(e,t,r,n){const s=new Float32Array(16),i=1/Math.tan(e/2),o=r-n;return s[0]=i/t,s[5]=i,s[10]=(n+r)/o,s[11]=-1,s[14]=2*n*r/o,s}function Yt(e,t,r){const n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n[12]=-e,n[13]=-t,n[14]=-r,n}function qt(e,t){const r=new Float32Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)r[4*s+n]=e[0+n]*t[4*s+0]+e[4+n]*t[4*s+1]+e[8+n]*t[4*s+2]+e[12+n]*t[4*s+3];return r}class Kt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const n=this.loadInternal(e);this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ve.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 r=await c(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(r);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const s=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(s);return{handle:Ve.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 r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function Jt(e,t){const r=new Map;for(const n of t.entities){const t=e.spawn();r.set(n.id,t);for(const r of n.components)Zt(e,t,r)}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return r}async function Qt(e,t,r){const n=new Map,s=r?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();n.set(o.id,t);for(const n of o.components){if("Sprite"===n.type&&s){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await s.loadTexture(n);e.texture=r.handle,i.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===n.type&&s){const e=n.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Zt(e,t,n)}}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function Zt(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,j,n);break;case"Sprite":e.insert(t,Y,n);break;case"Camera":e.insert(t,q,n);break;case"Canvas":e.insert(t,K,n);break;case"Text":e.insert(t,Be,n);break;case"SpineAnimation":e.insert(t,ee,n);break;case"UIRect":e.insert(t,ke,n);break;default:{const s=G(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function er(e,t){const r=e.getEntitiesWithComponents([q]);for(const n of r){const r=e.get(n,q);r&&(r.aspectRatio=t,e.insert(n,q,r))}}class tr{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const n=this.pending_.get(e);if(n)return n;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class rr{constructor(e){this.textureCache_=new tr,this.shaderCache_=new tr,this.jsonCache_=new tr,this.textCache_=new tr,this.binaryCache_=new tr,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}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 r of[!0,!1]){const n=this.textureCacheKey(e,r),s=this.textureCache_.get(n);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const s=this.resolveUrl(t,r),i=await fetch(s);if(!i.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const o=await i.text();if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(o);for(const e of c){const t=a?`${a}/${e}`:e,n=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(n),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}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 r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return Qt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const n of e.textures)r.push(this.loadTexture(n).then(e=>{t.textures.set(n,e)}));if(e.materials)for(const n of e.materials)r.push(this.loadMaterial(n).then(e=>{t.materials.set(n,e)}));if(e.spine)for(const n of e.spine){const e=`${n.skeleton}:${n.atlas}`;r.push(this.loadSpine(n.skeleton,n.atlas,n.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const n of e.json)r.push(this.loadJson(n).then(e=>{t.json.set(n,e)}));if(e.text)for(const n of e.text)r.push(this.loadText(n).then(e=>{t.text.set(n,e)}));if(e.binary)for(const n of e.binary)r.push(this.loadBinary(n).then(e=>{t.binary.set(n,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}createTextureFromImage(e,t){const{width:r,height:n}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,r,n,t):this.createTextureFallback(e,r,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,r,n,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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,r,n),width:r,height:n}}createTextureFallback(e,t,r,n){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,r),i=new Uint8Array(s.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,r,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const n=255/r;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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:n}=this.parseEsShader(t);if(!r||!n)throw new Error(`Invalid shader format: ${e}`);return Ve.createShader(r,n)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}async fetchJson(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.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 r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const n=r.split("/").filter(e=>e);let s="";for(const e of n){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const nr=se(null,"Assets");class sr{build(e){const t=e.wasmModule;t?e.insertResource(nr,new rr(t)):console.warn("AssetPlugin: No WASM module available")}}const ir=new sr;class or{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(nr)||e.addPlugin(ir),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=this.app_.getResource(nr);await r.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([q]);for(const n of r){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(t,j,r);const n={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,q,n)}}}class ar{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,r=!0,n=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,r,n)}addAnimation(e,t,r=!0,n=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,r,n,s)}setEmptyAnimation(e,t=.2,r=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,r)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const r=this.module_.spineGetBonePosition(e,t);return r?{x:r.x,y:r.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,r){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,r||"")}on(e,t,r){this.listeners_.has(e)||this.listeners_.set(e,new Map);const n=this.listeners_.get(e);n.has(t)||n.set(t,new Set),n.get(t).add(r)}off(e,t,r){const n=this.listeners_.get(e);if(!n)return;const s=n.get(t);s&&s.delete(r)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const r=this.listeners_.get(e);if(!r)return;const n={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=r.get(n.type);s&&s.forEach(e=>{try{e(n)}catch(e){console.error("Error in Spine event callback:",e)}})}}function cr(e){return new ar(e)}const lr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Ut.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Ut.getTargetTexture(r),width:e.width,height:e.height}},release(e){Ut.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Ut.releaseRenderTarget(e._handle),lr.create({width:t,height:r,depth:!0})),begin(e,t){Ut.begin(t,e._handle)},end(){Ut.end()},getDepthTexture:e=>Ut.getTargetDepthTexture(e._handle)};let ur=!1;function hr(e){ur=e}function dr(){return ur}function fr(){return!ur}var pr;E||(E=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(r,n);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.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:r}}),"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),r=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?r[n++]=s:s<2048?(r[n++]=192|s>>6,r[n++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,r[n++]=240|s>>18,r[n++]=128|s>>12&63,r[n++]=128|s>>6&63,r[n++]=128|63&s):(r[n++]=224|s>>12,r[n++]=128|s>>6&63,r[n++]=128|63&s)}return r.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const n=t[e];if(n<128)r+=String.fromCharCode(n),e++;else if(192==(224&n))r+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))r+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=pr=A,console.log(`[ESEngine] Platform: ${pr.name}`);export{Ot as App,sr as AssetPlugin,rr as AssetServer,nr as Assets,tr as AsyncCache,We as BlendMode,q as Camera,K as Canvas,Z as Children,pe as Commands,me as CommandsInstance,dt as DataType,lt as Draw,_e as EntityCommands,$t as GLDebug,xt as Geometry,M as INVALID_ENTITY,R as INVALID_TEXTURE,Pe as Input,Ee as InputPlugin,Te as InputState,j as LocalTransform,Ve as Material,Kt as MaterialLoader,ue as Mut,Q as Parent,Tt as PostProcess,or as PreviewPlugin,de as Query,fe as QueryInstance,Gt as RenderPipeline,Et as RenderStage,lr as RenderTexture,Ut as Renderer,ie as Res,oe as ResMut,ge as Schedule,Ze as ShaderSources,ee as SpineAnimation,ar as SpineController,Y as Sprite,be as SystemRunner,Be as Text,Re as TextAlign,Ue as TextOverflow,$e as TextPlugin,ze as TextRenderer,Fe as TextVerticalAlign,le as Time,ke as UIRect,J as Velocity,Me as World,V as WorldTransform,Se as addStartupSystem,ve as addSystem,Ce as addSystemToSchedule,ir as assetPlugin,Dt as clearDrawCallbacks,O as clearUserComponents,z as color,cr as createSpineController,Nt as createWebApp,L as defineComponent,se as defineResource,we as defineSystem,D as defineTag,Ht as flushPendingSystems,re as getComponentDefaults,t as getPlatform,n as getPlatformType,G as getUserComponent,it as initDrawAPI,zt as initGLDebugAPI,gt as initGeometryAPI,He as initMaterialAPI,St as initPostProcessAPI,Rt as initRendererAPI,Ae as inputPlugin,X as isBuiltinComponent,dr as isEditor,r as isPlatformInitialized,fr as isRuntime,Le as isTextureRef,s as isWeChat,i as isWeb,Zt as loadComponent,Jt as loadSceneData,Qt as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,k as quat,Wt as registerDrawCallback,Qe as registerMaterialCallback,hr as setEditorMode,ot as shutdownDrawAPI,kt as shutdownGLDebugAPI,yt as shutdownGeometryAPI,Xe as shutdownMaterialAPI,Ct as shutdownPostProcessAPI,Ft as shutdownRendererAPI,Ie as textPlugin,Lt as unregisterDrawCallback,er as updateCameraAspectRatio,F as vec2,U as vec3,B as vec4,w as wxFileExists,x as wxFileExistsSync,T as wxGetImagePixels,b as wxLoadImage,P as wxLoadImagePixels,g as wxReadFile,y as wxReadTextFile,v 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 a32b390c6..bf179fc1a 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -524,6 +524,8 @@ declare class App {
private runner_;
private running_;
private lastTime_;
+ private fixedTimestep_;
+ private fixedAccumulator_;
private module_;
private constructor();
static new(): App;
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index c4aa2c0f0..9a9aa381e 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}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,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.module}}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}},_=0,p=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),w=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),x=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});let v=0;function S(e,t){const n=++v;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function C(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function T(e,t){const n=C(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),R(e,t,!1),s}function P(e){const t=C(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),R(e,{},!0),r}function E(e){return C().get(e)}function b(){C().clear()}function R(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function A(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function M(e){return!0===e._builtin}const F=A("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),U=A("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=A("Sprite",{texture:p,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),k=A("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),B=A("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),$=A("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),I=A("Parent",{entity:0}),L=A("Children",{entities:[]}),D=A("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),W={LocalTransform:F,WorldTransform:U,Sprite:z,Camera:k,Canvas:B,Velocity:$,Parent:I,Children:L,SpineAnimation:D};function O(e){const t=W[e];if(t)return{...t._default};const n=E(e);return n?{...n._default}:null}let H=0;function G(e,t){const n=++H;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function N(e){return{_type:"res",_resource:e}}function V(e){return{_type:"res_mut",_resource:e}}class j{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 X{constructor(){this.resources_=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)}getResMut(e){return new j(this.get(e),t=>this.set(e,t))}}const Y=G({delta:0,elapsed:0,frameCount:0},"Time");function q(e){return{_type:"mut",_component:e}}function K(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function J(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{K(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class Q{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return K(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function Z(){return{_type:"commands"}}class ee{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=M(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}entity(e){return new ee(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ne;!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"}(ne||(ne={}));let re=0;function se(e,t,n){const r=++re;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function ie(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function oe(e){ie().push({schedule:ne.Update,system:e})}function ae(e){ie().push({schedule:ne.Startup,system:e})}function ce(e,t){ie().push({schedule:e,system:t})}class le{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof te&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Q(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new te(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ue{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 he=G(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const t=new ue;e.insertResource(he,t);const n=this.target_??document.querySelector("canvas")??document.body;document.addEventListener("keydown",e=>{t.keysDown.has(e.code)||t.keysPressed.add(e.code),t.keysDown.add(e.code)}),document.addEventListener("keyup",e=>{t.keysDown.delete(e.code),t.keysReleased.add(e.code)}),n.addEventListener("mousemove",e=>{t.mouseX=e.offsetX,t.mouseY=e.offsetY}),n.addEventListener("mousedown",e=>{const n=e.button;t.mouseButtons.add(n),t.mouseButtonsPressed.add(n)}),n.addEventListener("mouseup",e=>{const n=e.button;t.mouseButtons.delete(n),t.mouseButtonsReleased.add(n)}),n.addEventListener("touchstart",e=>{const r=e.touches[0];if(r){const e=n.getBoundingClientRect();t.mouseX=r.clientX-e.left,t.mouseY=r.clientY-e.top,t.mouseButtons.add(0),t.mouseButtonsPressed.add(0)}}),n.addEventListener("touchmove",e=>{const r=e.touches[0];if(r){const e=n.getBoundingClientRect();t.mouseX=r.clientX-e.left,t.mouseY=r.clientY-e.top}}),n.addEventListener("touchend",()=>{t.mouseButtons.delete(0),t.mouseButtonsReleased.add(0)}),n.addEventListener("wheel",e=>{t.scrollDeltaX+=e.deltaX,t.scrollDeltaY+=e.deltaY}),e.addSystemToSchedule(ne.First,se([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class _e{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}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,n){return M(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return M(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return M(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){M(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,r)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var pe,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(pe||(pe={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(me||(me={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ge||(ge={}));const ye=T("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:pe.Left,verticalAlign:me.Top,wordWrap:!0,overflow:ge.Visible,lineHeight:1.2,dirty:!0});class we{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;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=s?Math.ceil(i):h+2*u,_=s?Math.ceil(o):d+2*u;if(s&&e.overflow===ge.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(r.width<f||r.height<_){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(_));r.width=e,r.height=t}const p=Math.round(255*e.color.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${p}, ${m}, ${g}, ${y})`,s&&e.overflow===ge.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,_),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case me.Top:x=u;break;case me.Middle:x=(_-w)/2;break;case me.Bottom:x=_-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case pe.Left:r=u;break;case pe.Center:r=f/2;break;case pe.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ge.Clip&&n.restore();const S=n.getImageData(0,0,f,_),C=new Uint8Array(S.data.buffer),T=this.flipVertically(C,f,_),P=this.module.getResourceManager(),E=this.module._malloc(T.length);this.module.HEAPU8.set(T,E);const b=P.createTexture(f,_,E,T.length,1);return this.module._free(E),{textureHandle:b,width:f,height:_}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}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)}}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 n=e.split("\n"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case pe.Left:return"left";case pe.Center:return"center";case pe.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*r,o=(n-1-t)*r;s.set(e.subarray(i,i+r),o)}return s}}const xe=T("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new we(t),r=e.world;e.addSystemToSchedule(ne.PreUpdate,se([],()=>{const e=r.getEntitiesWithComponents([ye]);for(const t of e){const e=r.get(t,ye);if(!e.dirty)continue;r.has(t,z)||r.insert(t,z,{texture:p,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,xe)?r.get(t,xe):null,i=n.renderForEntity(t,e,s),o=r.get(t,z);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,z,o),e.dirty=!1}}))}}const Se=new ve;var Ce;function Te(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"}(Ce||(Ce={}));let Pe=null,Ee=null,be=1;const Re=new Map;function Ae(e){Pe=e,Ee=e.getResourceManager(),Ie()}function Me(){0!==ke&&Pe&&(Pe._free(ke),ke=0),Re.clear(),be=1,ze=!1,Ee=null,Pe=null}function Fe(){if(!Ee)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ee}const Ue={createShader:(e,t)=>Fe().createShader(e,t),releaseShader(e){e>0&&Fe().releaseShader(e)},create(e){const t=be++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ce.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Re.set(t,n),t},get:e=>Re.get(e),setUniform(e,t,n){const r=Re.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Re.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Re.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Re.get(e);return t?.blendMode??Ce.Normal},setDepthTest(e,t){const n=Re.get(e);n&&(n.depthTest=t)},getShader(e){const t=Re.get(e);return t?.shader??0},release(e){Re.delete(e)},isValid:e=>Re.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ce.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Re.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=be++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Re.set(n,r),n},toAssetData(e,t){const n=Re.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=Re.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ze=!1,ke=0;const Be=4096;function $e(e){const t=(0===ke&&Pe&&(ke=Pe._malloc(Be)),ke);if(0===t||!Pe)return{ptr:0,count:0};let n=0,r=0;const s=Pe.HEAPU8,i=Pe.HEAPU32,o=Pe.HEAPF32;for(const[a,c]of e){if(n+128>Be)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=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+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function Ie(){if(!Pe||ze)return;Pe.materialDataProvider=(e,t,n,r,s)=>{const i=Re.get(e);if(!i)return Pe.HEAPU32[t>>2]=0,Pe.HEAPU32[n>>2]=0,Pe.HEAPU32[r>>2]=0,void(Pe.HEAPU32[s>>2]=0);Pe.HEAPU32[t>>2]=i.shader,Pe.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=$e(i.uniforms);Pe.HEAPU32[r>>2]=o,Pe.HEAPU32[s>>2]=a},ze=!0}const Le={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"};let De=null,We=0,Oe=0,He=0;const Ge=new Float32Array(256);function Ne(e){De=e,We=De._malloc(64),Oe=De._malloc(64),He=De._malloc(1024)}function Ve(){De&&(We&&(De._free(We),We=0),Oe&&(De._free(Oe),Oe=0),He&&(De._free(He),He=0)),De=null}function je(){if(!De)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return De}const Xe={x:1,y:1,z:1,w:1},Ye={begin(e){const t=je();t.HEAPF32.set(e,We/4),t.draw_begin(We)},end(){je().draw_end()},line(e,t,n,r=1){je().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rect(e,t,n,r=!0){je().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rectOutline(e,t,n,r=1){je().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},circle(e,t,n,r=!0,s=32){je().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},circleOutline(e,t,n,r=1,s=32){je().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=Xe){je().draw_texture(e.x,e.y,t.x,t.y,n,r.x,r.y,r.z,r.w)},textureRotated(e,t,n,r,s=Xe){je().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){je().draw_setLayer(e)},setDepth(e){je().draw_setDepth(e)},getDrawCallCount:()=>De?De.draw_getDrawCallCount():0,getPrimitiveCount:()=>De?De.draw_getPrimitiveCount():0,setBlendMode(e){je().draw_setBlendMode(e)},setDepthTest(e){je().draw_setDepthTest(e)},drawMesh(e,t,n){const r=je();r.HEAPF32.set(n,Oe/4),r.draw_mesh(e,t,Oe)},drawMeshWithMaterial(e,t,n){const r=je(),s=Ue.get(t);if(!s)return;if(Ye.setBlendMode(s.blendMode),Ye.setDepthTest(s.depthTest),0===s.uniforms.size)return void Ye.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Oe/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Ke(e);if(!(n<0)){if(Te(t))Ge[i++]=10,Ge[i++]=n,Ge[i++]=t.slot??o++,Ge[i++]=t.textureId;else if("number"==typeof t)Ge[i++]=1,Ge[i++]=n,Ge[i++]=t;else if(Array.isArray(t)){Ge[i++]=t.length,Ge[i++]=n;for(let e=0;e<t.length;e++)Ge[i++]=t[e]}else"w"in t?(Ge[i++]=4,Ge[i++]=n,Ge[i++]=t.x,Ge[i++]=t.y,Ge[i++]=t.z,Ge[i++]=t.w):"z"in t?(Ge[i++]=3,Ge[i++]=n,Ge[i++]=t.x,Ge[i++]=t.y,Ge[i++]=t.z):(Ge[i++]=2,Ge[i++]=n,Ge[i++]=t.x,Ge[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(Ge.subarray(0,i),He/4),r.draw_meshWithUniforms(e,s.shader,Oe,He,i)):r.draw_mesh(e,s.shader,Oe)}},qe={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 Ke(e){return qe[e]??-1}var Je;!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"}(Je||(Je={}));let Qe=null,Ze=0,et=0,tt=0;function nt(e){Qe=e,Ze=Qe._malloc(262144),et=Qe._malloc(65536),tt=Qe._malloc(256)}function rt(){Qe&&(Ze&&Qe._free(Ze),et&&Qe._free(et),tt&&Qe._free(tt),Ze=0,et=0,tt=0),Qe=null}function st(){if(!Qe)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qe}const it={create(e){const t=st(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ze/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,tt,s).set(i),t.geometry_init(n,Ze,r,tt,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,et,r).set(e.indices),t.geometry_setIndices16(n,et,r)}else{new Uint32Array(t.HEAPU8.buffer,et,r).set(e.indices),t.geometry_setIndices32(n,et,r)}}return n},updateVertices(e,t,n=0){const r=st(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ze/4),r.geometry_updateVertices(e,Ze,s,n)},release(e){e>0&&st().geometry_release(e)},isValid:e=>!(!Qe||e<=0)&&Qe.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return it.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return it.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);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 it.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array(o)})}};let ot=null;function at(e){ot=e}function ct(){ot&&ut.isInitialized()&&ut.shutdown(),ot=null}function lt(){if(!ot)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ot}const ut={init:(e,t)=>lt().postprocess_init(e,t),shutdown(){lt().postprocess_shutdown()},resize(e,t){lt().postprocess_resize(e,t)},addPass:(e,t)=>lt().postprocess_addPass(e,t),removePass(e){lt().postprocess_removePass(e)},setEnabled(e,t){lt().postprocess_setPassEnabled(e,t)},isEnabled:e=>lt().postprocess_isPassEnabled(e),setUniform(e,t,n){lt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){lt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){lt().postprocess_begin()},end(){lt().postprocess_end()},getPassCount:()=>lt().postprocess_getPassCount(),isInitialized:()=>!!ot&&ot.postprocess_isInitialized(),setBypass(e){lt().postprocess_setBypass(e)},isBypassed:()=>!ot||ot.postprocess_isBypassed(),createBlur:()=>Ue.createShader(ht,"#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:()=>Ue.createShader(ht,"#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:()=>Ue.createShader(ht,"#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:()=>Ue.createShader(ht,"#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")},ht="#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 dt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(dt||(dt={}));let ft=null,_t=0;function pt(e){ft=e,_t=ft._malloc(64)}function mt(){ft&&_t&&(ft._free(_t),_t=0),ft=null}const gt={init(e,t){ft?.renderer_init(e,t)},resize(e,t){ft?.renderer_resize(e,t)},begin(e,t){ft&&_t&&(ft.HEAPF32.set(e,_t/4),ft.renderer_begin(_t,t??0))},flush(){ft?.renderer_flush()},end(){ft?.renderer_end()},submitSprites(e){ft&&ft.renderer_submitSprites(e._cpp)},submitSpine(e){ft&&ft.renderer_submitSpine(e._cpp)},setStage(e){ft?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ft?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ft?.renderer_releaseTarget(e)},getTargetTexture:e=>ft?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ft?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){ft?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>ft?{drawCalls:ft.renderer_getDrawCalls(),triangles:ft.renderer_getTriangles(),sprites:ft.renderer_getSprites(),spine:ft.renderer_getSpine(),meshes:ft.renderer_getMeshes(),culled:ft.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let yt=null;function wt(e){yt=e}function xt(){yt=null}const vt={enable(){yt?.gl_enableErrorCheck(!0)},disable(){yt?.gl_enableErrorCheck(!1)},check:e=>yt?.gl_checkErrors(e)??0,diagnose(){yt?.renderer_diagnose()}},St=new Map;function Ct(e,t){St.set(e,t)}function Tt(e){St.delete(e)}function Pt(){St.clear()}class Et{render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;gt.resize(r,s),ut.isInitialized()&&ut.getPassCount()>0&&!ut.isBypassed()&&ut.resize(r,s),gt.begin(n),gt.submitSprites(t),gt.submitSpine(t),gt.flush();const o=St;if(o.size>0){Ye.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Ye.end();for(const t of e)Tt(t)}gt.end()}}class bt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.module_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;this.updateTime(n),this.runSchedule(ne.First),this.runSchedule(ne.PreUpdate),this.runSchedule(ne.Update),this.runSchedule(ne.PostUpdate),this.runSchedule(ne.Last),requestAnimationFrame(this.mainLoop)},this.world_=new _e,this.resources_=new X;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ne.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ne.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new le(this.world_,this.resources_),this.resources_.insert(Y,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ne.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,xt(),mt(),ct(),rt(),Me(),Ve()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(Y),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(Y,n)}}function Rt(e,t){const n=bt.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ne(e),Ae(e),nt(e),at(e),pt(e),wt(e);const s=new Et;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=function(e,t,n){const r=e.entityCount()+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const r=e.getCamera(s);if(!r.isActive)continue;const i=e.getLocalTransform(s),o=t/n;let a;if(1===r.projectionType){const e=r.orthoSize,t=e*o;a=Ft(-t,t,-e,e,-r.farPlane,r.farPlane)}else a=Ut(r.fov*Math.PI/180,o,r.nearPlane,r.farPlane);return kt(a,zt(i.position.x,i.position.y,i.position.z))}return Mt}(r,e,t),a=(d()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:n,width:e,height:t,elapsed:a})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(fe),n.addPlugin(Se),n}function At(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Mt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ft(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function Ut(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function zt(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function kt(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}class Bt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ue.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ue.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 n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:Ue.createFromAsset(r,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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function $t(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)Lt(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function It(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t);for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Lt(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Lt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,F,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,k,r);break;case"Canvas":e.insert(t,B,r);break;case"Text":e.insert(t,ye,r);break;case"SpineAnimation":e.insert(t,D,r);break;case"UIRect":e.insert(t,xe,r);break;default:{const s=E(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Dt(e,t){const n=e.getEntitiesWithComponents([k]);for(const r of n){const n=e.get(r,k);n&&(n.aspectRatio=t,e.insert(r,k,n))}}class Wt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Ot{constructor(e){this.textureCache_=new Wt,this.shaderCache_=new Wt,this.jsonCache_=new Wt,this.textCache_=new Wt,this.binaryCache_=new Wt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=h(512,512),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)}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 n of[!0,!1]){const r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await fetch(s);if(!i.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const o=await i.text();if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(o);for(const e of c){const t=a?`${a}/${e}`:e,r=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return It(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.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,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const r=255/n;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ue.createShader(n,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}async fetchJson(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ht=G(null,"Assets");class Gt{build(e){const t=e.wasmModule;t?e.insertResource(Ht,new Ot(t)):console.warn("AssetPlugin: No WASM module available")}}const Nt=new Gt;class Vt{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(Ht)||e.addPlugin(Nt),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=this.app_.getResource(Ht);await n.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([k]);for(const r of n){if(e.get(r,k).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),n={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(t,F,n);const r={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,k,r)}}}class jt{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,n=!0,r=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,n,r,s)}setEmptyAnimation(e,t=.2,n=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,n)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const n=this.module_.spineGetBonePosition(e,t);return n?{x:n.x,y:n.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,n){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,n||"")}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const s=r.get(t);s&&s.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const n=this.listeners_.get(e);if(!n)return;const r={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=n.get(r.type);s&&s.forEach(e=>{try{e(r)}catch(e){console.error("Error in Spine event callback:",e)}})}}function Xt(e){return new jt(e)}const Yt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=gt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:gt.getTargetTexture(n),width:e.width,height:e.height}},release(e){gt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(gt.releaseRenderTarget(e._handle),Yt.create({width:t,height:n,depth:!0})),begin(e,t){gt.begin(t,e._handle)},end(){gt.end()},getDepthTexture:e=>gt.getTargetDepthTexture(e._handle)};let qt=!1;function Kt(e){qt=e}function Jt(){return qt}function Qt(){return!qt}var Zt;e=Zt=f,console.log(`[ESEngine] Platform: ${Zt.name}`);export{bt as App,Gt as AssetPlugin,Ot as AssetServer,Ht as Assets,Wt as AsyncCache,Ce as BlendMode,k as Camera,B as Canvas,L as Children,Z as Commands,te as CommandsInstance,Je as DataType,Ye as Draw,ee as EntityCommands,vt as GLDebug,it as Geometry,_ as INVALID_ENTITY,p as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,F as LocalTransform,Ue as Material,Bt as MaterialLoader,q as Mut,I as Parent,ut as PostProcess,Vt as PreviewPlugin,J as Query,Q as QueryInstance,Et as RenderPipeline,dt as RenderStage,Yt as RenderTexture,gt as Renderer,N as Res,V as ResMut,ne as Schedule,Le as ShaderSources,D as SpineAnimation,jt as SpineController,z as Sprite,le as SystemRunner,ye as Text,pe as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,$ as Velocity,_e as World,U as WorldTransform,ae as addStartupSystem,oe as addSystem,ce as addSystemToSchedule,Nt as assetPlugin,Pt as clearDrawCallbacks,b as clearUserComponents,w as color,Xt as createSpineController,Rt as createWebApp,T as defineComponent,G as defineResource,se as defineSystem,P as defineTag,At as flushPendingSystems,O as getComponentDefaults,t as getPlatform,r as getPlatformType,E as getUserComponent,Ne as initDrawAPI,wt as initGLDebugAPI,nt as initGeometryAPI,Ae as initMaterialAPI,at as initPostProcessAPI,pt as initRendererAPI,fe as inputPlugin,M as isBuiltinComponent,Jt as isEditor,n as isPlatformInitialized,Qt as isRuntime,Te as isTextureRef,s as isWeChat,i as isWeb,Lt as loadComponent,$t as loadSceneData,It as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Ct as registerDrawCallback,Ie as registerMaterialCallback,Kt as setEditorMode,Ve as shutdownDrawAPI,xt as shutdownGLDebugAPI,rt as shutdownGeometryAPI,Me as shutdownMaterialAPI,ct as shutdownPostProcessAPI,mt as shutdownRendererAPI,Se as textPlugin,Tt as unregisterDrawCallback,Dt as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}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,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.module}}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}},_=0,p=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),w=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),x=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});let v=0;function S(e,t){const n=++v;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function C(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function T(e,t){const n=C(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),A(e,t,!1),s}function P(e){const t=C(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),A(e,{},!0),r}function E(e){return C().get(e)}function b(){C().clear()}function A(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function R(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function M(e){return!0===e._builtin}const F=R("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),U=R("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=R("Sprite",{texture:p,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),k=R("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),B=R("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),$=R("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),I=R("Parent",{entity:0}),L=R("Children",{entities:[]}),D=R("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),W={LocalTransform:F,WorldTransform:U,Sprite:z,Camera:k,Canvas:B,Velocity:$,Parent:I,Children:L,SpineAnimation:D};function O(e){const t=W[e];if(t)return{...t._default};const n=E(e);return n?{...n._default}:null}let H=0;function G(e,t){const n=++H;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function N(e){return{_type:"res",_resource:e}}function V(e){return{_type:"res_mut",_resource:e}}class j{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 X{constructor(){this.resources_=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)}getResMut(e){return new j(this.get(e),t=>this.set(e,t))}}const Y=G({delta:0,elapsed:0,frameCount:0},"Time");function q(e){return{_type:"mut",_component:e}}function K(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function J(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{K(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class Q{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return K(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function Z(){return{_type:"commands"}}class ee{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=M(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}entity(e){return new ee(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ne;!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"}(ne||(ne={}));let re=0;function se(e,t,n){const r=++re;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function ie(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function oe(e){ie().push({schedule:ne.Update,system:e})}function ae(e){ie().push({schedule:ne.Startup,system:e})}function ce(e,t){ie().push({schedule:e,system:t})}class le{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof te&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Q(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new te(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ue{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 he=G(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const t=new ue;e.insertResource(he,t);const n=this.target_??document.querySelector("canvas")??document.body;document.addEventListener("keydown",e=>{t.keysDown.has(e.code)||t.keysPressed.add(e.code),t.keysDown.add(e.code)}),document.addEventListener("keyup",e=>{t.keysDown.delete(e.code),t.keysReleased.add(e.code)}),n.addEventListener("mousemove",e=>{t.mouseX=e.offsetX,t.mouseY=e.offsetY}),n.addEventListener("mousedown",e=>{const n=e.button;t.mouseButtons.add(n),t.mouseButtonsPressed.add(n)}),n.addEventListener("mouseup",e=>{const n=e.button;t.mouseButtons.delete(n),t.mouseButtonsReleased.add(n)}),n.addEventListener("touchstart",e=>{const r=e.touches[0];if(r){const e=n.getBoundingClientRect();t.mouseX=r.clientX-e.left,t.mouseY=r.clientY-e.top,t.mouseButtons.add(0),t.mouseButtonsPressed.add(0)}}),n.addEventListener("touchmove",e=>{const r=e.touches[0];if(r){const e=n.getBoundingClientRect();t.mouseX=r.clientX-e.left,t.mouseY=r.clientY-e.top}}),n.addEventListener("touchend",()=>{t.mouseButtons.delete(0),t.mouseButtonsReleased.add(0)}),n.addEventListener("wheel",e=>{t.scrollDeltaX+=e.deltaX,t.scrollDeltaY+=e.deltaY}),e.addSystemToSchedule(ne.First,se([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class _e{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}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,n){return M(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return M(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return M(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){M(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,r)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var pe,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(pe||(pe={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(me||(me={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ge||(ge={}));const ye=T("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:pe.Left,verticalAlign:me.Top,wordWrap:!0,overflow:ge.Visible,lineHeight:1.2,dirty:!0});class we{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;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=s?Math.ceil(i):h+2*u,_=s?Math.ceil(o):d+2*u;if(s&&e.overflow===ge.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(r.width<f||r.height<_){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(_));r.width=e,r.height=t}const p=Math.round(255*e.color.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${p}, ${m}, ${g}, ${y})`,s&&e.overflow===ge.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,_),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case me.Top:x=u;break;case me.Middle:x=(_-w)/2;break;case me.Bottom:x=_-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case pe.Left:r=u;break;case pe.Center:r=f/2;break;case pe.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ge.Clip&&n.restore();const S=n.getImageData(0,0,f,_),C=new Uint8Array(S.data.buffer),T=this.flipVertically(C,f,_),P=this.module.getResourceManager(),E=this.module._malloc(T.length);this.module.HEAPU8.set(T,E);const b=P.createTexture(f,_,E,T.length,1);return this.module._free(E),{textureHandle:b,width:f,height:_}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}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)}}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 n=e.split("\n"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case pe.Left:return"left";case pe.Center:return"center";case pe.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*r,o=(n-1-t)*r;s.set(e.subarray(i,i+r),o)}return s}}const xe=T("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new we(t),r=e.world;e.addSystemToSchedule(ne.PreUpdate,se([],()=>{const e=r.getEntitiesWithComponents([ye]);for(const t of e){const e=r.get(t,ye);if(!e.dirty)continue;r.has(t,z)||r.insert(t,z,{texture:p,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,xe)?r.get(t,xe):null,i=n.renderForEntity(t,e,s),o=r.get(t,z);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,z,o),e.dirty=!1}}))}}const Se=new ve;var Ce;function Te(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"}(Ce||(Ce={}));let Pe=null,Ee=null,be=1;const Ae=new Map;function Re(e){Pe=e,Ee=e.getResourceManager(),Ie()}function Me(){0!==ke&&Pe&&(Pe._free(ke),ke=0),Ae.clear(),be=1,ze=!1,Ee=null,Pe=null}function Fe(){if(!Ee)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ee}const Ue={createShader:(e,t)=>Fe().createShader(e,t),releaseShader(e){e>0&&Fe().releaseShader(e)},create(e){const t=be++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ce.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Ae.set(t,n),t},get:e=>Ae.get(e),setUniform(e,t,n){const r=Ae.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Ae.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ae.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ae.get(e);return t?.blendMode??Ce.Normal},setDepthTest(e,t){const n=Ae.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ae.get(e);return t?.shader??0},release(e){Ae.delete(e)},isValid:e=>Ae.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ce.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ae.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=be++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ae.set(n,r),n},toAssetData(e,t){const n=Ae.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=Ae.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ze=!1,ke=0;const Be=4096;function $e(e){const t=(0===ke&&Pe&&(ke=Pe._malloc(Be)),ke);if(0===t||!Pe)return{ptr:0,count:0};let n=0,r=0;const s=Pe.HEAPU8,i=Pe.HEAPU32,o=Pe.HEAPF32;for(const[a,c]of e){if(n+128>Be)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=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+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function Ie(){if(!Pe||ze)return;Pe.materialDataProvider=(e,t,n,r,s)=>{const i=Ae.get(e);if(!i)return Pe.HEAPU32[t>>2]=0,Pe.HEAPU32[n>>2]=0,Pe.HEAPU32[r>>2]=0,void(Pe.HEAPU32[s>>2]=0);Pe.HEAPU32[t>>2]=i.shader,Pe.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=$e(i.uniforms);Pe.HEAPU32[r>>2]=o,Pe.HEAPU32[s>>2]=a},ze=!0}const Le={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"};let De=null,We=0,Oe=0,He=0;const Ge=new Float32Array(256);function Ne(e){De=e,We=De._malloc(64),Oe=De._malloc(64),He=De._malloc(1024)}function Ve(){De&&(We&&(De._free(We),We=0),Oe&&(De._free(Oe),Oe=0),He&&(De._free(He),He=0)),De=null}function je(){if(!De)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return De}const Xe={x:1,y:1,z:1,w:1},Ye={begin(e){const t=je();t.HEAPF32.set(e,We/4),t.draw_begin(We)},end(){je().draw_end()},line(e,t,n,r=1){je().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rect(e,t,n,r=!0){je().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rectOutline(e,t,n,r=1){je().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},circle(e,t,n,r=!0,s=32){je().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},circleOutline(e,t,n,r=1,s=32){je().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=Xe){je().draw_texture(e.x,e.y,t.x,t.y,n,r.x,r.y,r.z,r.w)},textureRotated(e,t,n,r,s=Xe){je().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){je().draw_setLayer(e)},setDepth(e){je().draw_setDepth(e)},getDrawCallCount:()=>De?De.draw_getDrawCallCount():0,getPrimitiveCount:()=>De?De.draw_getPrimitiveCount():0,setBlendMode(e){je().draw_setBlendMode(e)},setDepthTest(e){je().draw_setDepthTest(e)},drawMesh(e,t,n){const r=je();r.HEAPF32.set(n,Oe/4),r.draw_mesh(e,t,Oe)},drawMeshWithMaterial(e,t,n){const r=je(),s=Ue.get(t);if(!s)return;if(Ye.setBlendMode(s.blendMode),Ye.setDepthTest(s.depthTest),0===s.uniforms.size)return void Ye.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Oe/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Ke(e);if(!(n<0)){if(Te(t))Ge[i++]=10,Ge[i++]=n,Ge[i++]=t.slot??o++,Ge[i++]=t.textureId;else if("number"==typeof t)Ge[i++]=1,Ge[i++]=n,Ge[i++]=t;else if(Array.isArray(t)){Ge[i++]=t.length,Ge[i++]=n;for(let e=0;e<t.length;e++)Ge[i++]=t[e]}else"w"in t?(Ge[i++]=4,Ge[i++]=n,Ge[i++]=t.x,Ge[i++]=t.y,Ge[i++]=t.z,Ge[i++]=t.w):"z"in t?(Ge[i++]=3,Ge[i++]=n,Ge[i++]=t.x,Ge[i++]=t.y,Ge[i++]=t.z):(Ge[i++]=2,Ge[i++]=n,Ge[i++]=t.x,Ge[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(Ge.subarray(0,i),He/4),r.draw_meshWithUniforms(e,s.shader,Oe,He,i)):r.draw_mesh(e,s.shader,Oe)}},qe={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 Ke(e){return qe[e]??-1}var Je;!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"}(Je||(Je={}));let Qe=null,Ze=0,et=0,tt=0;function nt(e){Qe=e,Ze=Qe._malloc(262144),et=Qe._malloc(65536),tt=Qe._malloc(256)}function rt(){Qe&&(Ze&&Qe._free(Ze),et&&Qe._free(et),tt&&Qe._free(tt),Ze=0,et=0,tt=0),Qe=null}function st(){if(!Qe)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qe}const it={create(e){const t=st(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ze/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,tt,s).set(i),t.geometry_init(n,Ze,r,tt,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,et,r).set(e.indices),t.geometry_setIndices16(n,et,r)}else{new Uint32Array(t.HEAPU8.buffer,et,r).set(e.indices),t.geometry_setIndices32(n,et,r)}}return n},updateVertices(e,t,n=0){const r=st(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ze/4),r.geometry_updateVertices(e,Ze,s,n)},release(e){e>0&&st().geometry_release(e)},isValid:e=>!(!Qe||e<=0)&&Qe.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return it.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return it.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);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 it.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array(o)})}};let ot=null;function at(e){ot=e}function ct(){ot&&ut.isInitialized()&&ut.shutdown(),ot=null}function lt(){if(!ot)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ot}const ut={init:(e,t)=>lt().postprocess_init(e,t),shutdown(){lt().postprocess_shutdown()},resize(e,t){lt().postprocess_resize(e,t)},addPass:(e,t)=>lt().postprocess_addPass(e,t),removePass(e){lt().postprocess_removePass(e)},setEnabled(e,t){lt().postprocess_setPassEnabled(e,t)},isEnabled:e=>lt().postprocess_isPassEnabled(e),setUniform(e,t,n){lt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){lt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){lt().postprocess_begin()},end(){lt().postprocess_end()},getPassCount:()=>lt().postprocess_getPassCount(),isInitialized:()=>!!ot&&ot.postprocess_isInitialized(),setBypass(e){lt().postprocess_setBypass(e)},isBypassed:()=>!ot||ot.postprocess_isBypassed(),createBlur:()=>Ue.createShader(ht,"#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:()=>Ue.createShader(ht,"#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:()=>Ue.createShader(ht,"#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:()=>Ue.createShader(ht,"#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")},ht="#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 dt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(dt||(dt={}));let ft=null,_t=0;function pt(e){ft=e,_t=ft._malloc(64)}function mt(){ft&&_t&&(ft._free(_t),_t=0),ft=null}const gt={init(e,t){ft?.renderer_init(e,t)},resize(e,t){ft?.renderer_resize(e,t)},begin(e,t){ft&&_t&&(ft.HEAPF32.set(e,_t/4),ft.renderer_begin(_t,t??0))},flush(){ft?.renderer_flush()},end(){ft?.renderer_end()},submitSprites(e){ft&&ft.renderer_submitSprites(e._cpp)},submitSpine(e){ft&&ft.renderer_submitSpine(e._cpp)},setStage(e){ft?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ft?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ft?.renderer_releaseTarget(e)},getTargetTexture:e=>ft?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ft?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){ft?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>ft?{drawCalls:ft.renderer_getDrawCalls(),triangles:ft.renderer_getTriangles(),sprites:ft.renderer_getSprites(),spine:ft.renderer_getSpine(),meshes:ft.renderer_getMeshes(),culled:ft.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let yt=null;function wt(e){yt=e}function xt(){yt=null}const vt={enable(){yt?.gl_enableErrorCheck(!0)},disable(){yt?.gl_enableErrorCheck(!1)},check:e=>yt?.gl_checkErrors(e)??0,diagnose(){yt?.renderer_diagnose()}},St=new Map;function Ct(e,t){St.set(e,t)}function Tt(e){St.delete(e)}function Pt(){St.clear()}class Et{render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;gt.resize(r,s),ut.isInitialized()&&ut.getPassCount()>0&&!ut.isBypassed()&&ut.resize(r,s),gt.begin(n),gt.submitSprites(t),gt.submitSpine(t),gt.flush();const o=St;if(o.size>0){Ye.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Ye.end();for(const t of e)Tt(t)}gt.end()}}class bt{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.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(ne.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ne.FixedPreUpdate),this.runSchedule(ne.FixedUpdate),this.runSchedule(ne.FixedPostUpdate);this.runSchedule(ne.PreUpdate),this.runSchedule(ne.Update),this.runSchedule(ne.PostUpdate),this.runSchedule(ne.Last),requestAnimationFrame(this.mainLoop)},this.world_=new _e,this.resources_=new X;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ne.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ne.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new le(this.world_,this.resources_),this.resources_.insert(Y,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ne.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,xt(),mt(),ct(),rt(),Me(),Ve()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(Y),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(Y,n)}}function At(e,t){const n=bt.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ne(e),Re(e),nt(e),at(e),pt(e),wt(e);const s=new Et;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=function(e,t,n){const r=e.entityCount()+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const r=e.getCamera(s);if(!r.isActive)continue;const i=e.getLocalTransform(s),o=t/n;let a;if(1===r.projectionType){const e=r.orthoSize,t=e*o;a=Ft(-t,t,-e,e,-r.farPlane,r.farPlane)}else a=Ut(r.fov*Math.PI/180,o,r.nearPlane,r.farPlane);return kt(a,zt(i.position.x,i.position.y,i.position.z))}return Mt}(r,e,t),a=(d()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:n,width:e,height:t,elapsed:a})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(fe),n.addPlugin(Se),n}function Rt(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Mt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ft(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function Ut(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function zt(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function kt(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}class Bt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ue.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ue.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 n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:Ue.createFromAsset(r,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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function $t(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)Lt(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function It(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t);for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Lt(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Lt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,F,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,k,r);break;case"Canvas":e.insert(t,B,r);break;case"Text":e.insert(t,ye,r);break;case"SpineAnimation":e.insert(t,D,r);break;case"UIRect":e.insert(t,xe,r);break;default:{const s=E(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Dt(e,t){const n=e.getEntitiesWithComponents([k]);for(const r of n){const n=e.get(r,k);n&&(n.aspectRatio=t,e.insert(r,k,n))}}class Wt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Ot{constructor(e){this.textureCache_=new Wt,this.shaderCache_=new Wt,this.jsonCache_=new Wt,this.textCache_=new Wt,this.binaryCache_=new Wt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=h(512,512),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)}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 n of[!0,!1]){const r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await fetch(s);if(!i.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const o=await i.text();if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(o);for(const e of c){const t=a?`${a}/${e}`:e,r=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return It(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.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,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const r=255/n;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ue.createShader(n,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}async fetchJson(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ht=G(null,"Assets");class Gt{build(e){const t=e.wasmModule;t?e.insertResource(Ht,new Ot(t)):console.warn("AssetPlugin: No WASM module available")}}const Nt=new Gt;class Vt{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(Ht)||e.addPlugin(Nt),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=this.app_.getResource(Ht);await n.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([k]);for(const r of n){if(e.get(r,k).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),n={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(t,F,n);const r={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,k,r)}}}class jt{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,n=!0,r=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,n,r,s)}setEmptyAnimation(e,t=.2,n=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,n)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const n=this.module_.spineGetBonePosition(e,t);return n?{x:n.x,y:n.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,n){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,n||"")}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const s=r.get(t);s&&s.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const n=this.listeners_.get(e);if(!n)return;const r={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=n.get(r.type);s&&s.forEach(e=>{try{e(r)}catch(e){console.error("Error in Spine event callback:",e)}})}}function Xt(e){return new jt(e)}const Yt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=gt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:gt.getTargetTexture(n),width:e.width,height:e.height}},release(e){gt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(gt.releaseRenderTarget(e._handle),Yt.create({width:t,height:n,depth:!0})),begin(e,t){gt.begin(t,e._handle)},end(){gt.end()},getDepthTexture:e=>gt.getTargetDepthTexture(e._handle)};let qt=!1;function Kt(e){qt=e}function Jt(){return qt}function Qt(){return!qt}var Zt;e=Zt=f,console.log(`[ESEngine] Platform: ${Zt.name}`);export{bt as App,Gt as AssetPlugin,Ot as AssetServer,Ht as Assets,Wt as AsyncCache,Ce as BlendMode,k as Camera,B as Canvas,L as Children,Z as Commands,te as CommandsInstance,Je as DataType,Ye as Draw,ee as EntityCommands,vt as GLDebug,it as Geometry,_ as INVALID_ENTITY,p as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,F as LocalTransform,Ue as Material,Bt as MaterialLoader,q as Mut,I as Parent,ut as PostProcess,Vt as PreviewPlugin,J as Query,Q as QueryInstance,Et as RenderPipeline,dt as RenderStage,Yt as RenderTexture,gt as Renderer,N as Res,V as ResMut,ne as Schedule,Le as ShaderSources,D as SpineAnimation,jt as SpineController,z as Sprite,le as SystemRunner,ye as Text,pe as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,$ as Velocity,_e as World,U as WorldTransform,ae as addStartupSystem,oe as addSystem,ce as addSystemToSchedule,Nt as assetPlugin,Pt as clearDrawCallbacks,b as clearUserComponents,w as color,Xt as createSpineController,At as createWebApp,T as defineComponent,G as defineResource,se as defineSystem,P as defineTag,Rt as flushPendingSystems,O as getComponentDefaults,t as getPlatform,r as getPlatformType,E as getUserComponent,Ne as initDrawAPI,wt as initGLDebugAPI,nt as initGeometryAPI,Re as initMaterialAPI,at as initPostProcessAPI,pt as initRendererAPI,fe as inputPlugin,M as isBuiltinComponent,Jt as isEditor,n as isPlatformInitialized,Qt as isRuntime,Te as isTextureRef,s as isWeChat,i as isWeb,Lt as loadComponent,$t as loadSceneData,It as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Ct as registerDrawCallback,Ie as registerMaterialCallback,Kt as setEditorMode,Ve as shutdownDrawAPI,xt as shutdownGLDebugAPI,rt as shutdownGeometryAPI,Me as shutdownMaterialAPI,ct as shutdownPostProcessAPI,mt as shutdownRendererAPI,Se as textPlugin,Tt as unregisterDrawCallback,Dt as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};
//# sourceMappingURL=index.js.map
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 6e6dc2d97..c075b3c44 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -46,6 +46,8 @@ export class App {
private running_ = false;
private lastTime_ = 0;
+ private fixedTimestep_ = 1 / 60;
+ private fixedAccumulator_ = 0;
private module_: ESEngineModule | null = null;
@@ -167,6 +169,15 @@ export class App {
this.updateTime(delta);
this.runSchedule(Schedule.First);
+
+ this.fixedAccumulator_ += delta;
+ while (this.fixedAccumulator_ >= this.fixedTimestep_) {
+ this.fixedAccumulator_ -= this.fixedTimestep_;
+ this.runSchedule(Schedule.FixedPreUpdate);
+ this.runSchedule(Schedule.FixedUpdate);
+ this.runSchedule(Schedule.FixedPostUpdate);
+ }
+
this.runSchedule(Schedule.PreUpdate);
this.runSchedule(Schedule.Update);
this.runSchedule(Schedule.PostUpdate);