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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
chore: sync SDK build outputs to desktop/public
esengined99f45cde65c
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 98aa810a1..24e083d51 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 n(e){return t().readTextFile(e)}async function s(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,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 c(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 l=null;function u(){return l||(l=wx.getFileSystemManager()),l}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,n)=>{u().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(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,x=null;function _(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 m(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return f||(f=wx.createCanvas(),f.width=e,f.height=t,x=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:x}}(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 o=s.getImageData(0,0,r,n);return{width:r,height:n,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 c(e,t)}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},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 P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function T(e,t){const r=P(),n=r.get(e);if(n)return n;const s=S(e,t);return r.set(e,s),b(e,t,!1),s}function C(e){return P().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 M(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}}),E=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}),U=A("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),I=A("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),W=A("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),B=A("Parent",{entity:0}),z=A("Children",{entities:[]}),$=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}),k={LocalTransform:R,WorldTransform:E,Sprite:F,Camera:U,Canvas:I,Velocity:W,Parent:B,Children:z,SpineAnimation:$};let D=0;function L(e,t){const r=++D;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class O{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 H{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 O(this.get(e),t=>this.set(e,t))}}const N=L({delta:0,elapsed:0,frameCount:0},"Time");function G(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class V{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return G(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)),o=[...s,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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]}}class j{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=M(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 X{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new j(this,null)}entity(e){return new j(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 q;exports.Schedule=void 0,(q=exports.Schedule||(exports.Schedule={}))[q.Startup=0]="Startup",q[q.First=1]="First",q[q.PreUpdate=2]="PreUpdate",q[q.Update=3]="Update",q[q.PostUpdate=4]="PostUpdate",q[q.Last=5]="Last",q[q.FixedPreUpdate=10]="FixedPreUpdate",q[q.FixedUpdate=11]="FixedUpdate",q[q.FixedPostUpdate=12]="FixedPostUpdate";let Y=0;function K(e,t,r){const n=++Y;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}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 X&&e.flush()}resolveParam(e){switch(e._type){case"query":return new V(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new X(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 r=new Z;e.insertResource(ee,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,n){r.mouseX=t,r.mouseY=n,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,K([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const re=new te;class ne{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 M(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}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,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 se,oe,ie;exports.TextAlign=void 0,(se=exports.TextAlign||(exports.TextAlign={}))[se.Left=0]="Left",se[se.Center=1]="Center",se[se.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=T("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 ce{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,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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),p=s?Math.ceil(o):h+2*u,f=s?Math.ceil(i):d+2*u;if(s&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const x=Math.round(255*e.color.x),_=Math.round(255*e.color.y),m=Math.round(255*e.color.z),g=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(${x}, ${_}, ${m}, ${g})`,s&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=c.length*l;let w;if(s)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 c){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}r.fillText(t,n,v),v+=l}s&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),P=new Uint8Array(S.data.buffer),T=this.flipVertically(P,p,f),C=this.module.getResourceManager(),b=this.module._malloc(T.length);this.module.HEAPU8.set(T,b);const A=C.createTexture(p,f,b,T.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 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 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 n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const le=T("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 ce(t),n=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,K([],()=>{const e=n.getEntitiesWithComponents([ae]);for(const t of e){const e=n.get(t,ae);if(!e.dirty)continue;n.has(t,F)||n.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 s=n.has(t,le)?n.get(t,le):null,o=r.renderForEntity(t,e,s),i=n.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},n.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,xe=null,_e=1;const me=new Map;function ge(e){fe=e,xe=e.getResourceManager(),be()}function ye(){0!==Pe&&fe&&(fe._free(Pe),Pe=0),me.clear(),_e=1,Se=!1,xe=null,fe=null}function we(){if(!xe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return xe}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,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return me.set(t,r),t},get:e=>me.get(e),setUniform(e,t,r){const n=me.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=me.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=me.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=me.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=me.get(e);r&&(r.depthTest=t)},getShader(e){const t=me.get(e);return t?.shader??0},release(e){me.delete(e)},isValid:e=>me.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??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=me.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=_e++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return me.set(r,n),r},toAssetData(e,t){const r=me.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=me.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Se=!1,Pe=0;const Te=4096;function Ce(e){const t=(0===Pe&&fe&&(Pe=fe._malloc(Te)),Pe);if(0===t||!fe)return{ptr:0,count:0};let r=0,n=0;const s=fe.HEAPU8,o=fe.HEAPU32,i=fe.HEAPF32;for(const[a,c]of e){if(r+128>Te)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[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]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function be(){if(!fe||Se)return;fe.materialDataProvider=(e,t,r,n,s)=>{const o=me.get(e);if(!o)return fe.HEAPU32[t>>2]=0,fe.HEAPU32[r>>2]=0,fe.HEAPU32[n>>2]=0,void(fe.HEAPU32[s>>2]=0);fe.HEAPU32[t>>2]=o.shader,fe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Ce(o.uniforms);fe.HEAPU32[n>>2]=i,fe.HEAPU32[s>>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"};class Me{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 s(t))throw new Error(`Material file not found: ${t}`);const r=await n(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}}function Re(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)Fe(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 Ee(e,t,r){const n=new Map,s=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();n.set(i.id,t);for(const n of i.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,o.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,o=e.atlasPath;if(t&&o){const e=await s.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 s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Fe(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=o.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function Fe(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,R,n);break;case"Sprite":e.insert(t,F,n);break;case"Camera":e.insert(t,U,n);break;case"Canvas":e.insert(t,I,n);break;case"Text":e.insert(t,ae,n);break;case"SpineAnimation":e.insert(t,$,n);break;case"UIRect":e.insert(t,le,n);break;default:{const s=C(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}class Ue{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 Ie{constructor(e){this.textureCache_=new Ue,this.shaderCache_=new Ue,this.jsonCache_=new Ue,this.textCache_=new Ue,this.binaryCache_=new Ue,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 Me(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),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};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("/")),c=this.parseAtlasTextures(i);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 Ee(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 o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;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),o=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,r,a,o.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 s(e))throw new Error(`Shader file not found: ${e}`);const t=await n(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 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 We=L(null,"Assets");class Be{build(e){const t=e.wasmModule;t?e.insertResource(We,new Ie(t)):console.warn("AssetPlugin: No WASM module available")}}const ze=new Be;let $e=null,ke=0,De=0,Le=0;const Oe=new Float32Array(256);function He(e){$e=e,ke=$e._malloc(64),De=$e._malloc(64),Le=$e._malloc(1024)}function Ne(){$e&&(ke&&($e._free(ke),ke=0),De&&($e._free(De),De=0),Le&&($e._free(Le),Le=0)),$e=null}function Ge(){if(!$e)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return $e}const Ve={x:1,y:1,z:1,w:1},je={begin(e){const t=Ge();t.HEAPF32.set(e,ke/4),t.draw_begin(ke)},end(){Ge().draw_end()},line(e,t,r,n=1){Ge().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){Ge().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){Ge().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){Ge().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){Ge().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=Ve){Ge().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=Ve){Ge().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){Ge().draw_setLayer(e)},setDepth(e){Ge().draw_setDepth(e)},getDrawCallCount:()=>$e?$e.draw_getDrawCallCount():0,getPrimitiveCount:()=>$e?$e.draw_getPrimitiveCount():0,setBlendMode(e){Ge().draw_setBlendMode(e)},setDepthTest(e){Ge().draw_setDepthTest(e)},drawMesh(e,t,r){const n=Ge();n.HEAPF32.set(r,De/4),n.draw_mesh(e,t,De)},drawMeshWithMaterial(e,t,r){const n=Ge(),s=ve.get(t);if(!s)return;if(je.setBlendMode(s.blendMode),je.setDepthTest(s.depthTest),0===s.uniforms.size)return void je.drawMesh(e,s.shader,r);n.HEAPF32.set(r,De/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=qe(e);if(!(r<0)){if(pe(t))Oe[o++]=10,Oe[o++]=r,Oe[o++]=t.slot??i++,Oe[o++]=t.textureId;else if("number"==typeof t)Oe[o++]=1,Oe[o++]=r,Oe[o++]=t;else if(Array.isArray(t)){Oe[o++]=t.length,Oe[o++]=r;for(let e=0;e<t.length;e++)Oe[o++]=t[e]}else"w"in t?(Oe[o++]=4,Oe[o++]=r,Oe[o++]=t.x,Oe[o++]=t.y,Oe[o++]=t.z,Oe[o++]=t.w):"z"in t?(Oe[o++]=3,Oe[o++]=r,Oe[o++]=t.x,Oe[o++]=t.y,Oe[o++]=t.z):(Oe[o++]=2,Oe[o++]=r,Oe[o++]=t.x,Oe[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(Oe.subarray(0,o),Le/4),n.draw_meshWithUniforms(e,s.shader,De,Le,o)):n.draw_mesh(e,s.shader,De)}},Xe={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 qe(e){return Xe[e]??-1}var Ye;exports.DataType=void 0,(Ye=exports.DataType||(exports.DataType={}))[Ye.Float=1]="Float",Ye[Ye.Float2=2]="Float2",Ye[Ye.Float3=3]="Float3",Ye[Ye.Float4=4]="Float4",Ye[Ye.Int=5]="Int",Ye[Ye.Int2=6]="Int2",Ye[Ye.Int3=7]="Int3",Ye[Ye.Int4=8]="Int4";let Ke=null,Je=0,Qe=0,Ze=0;function et(e){Ke=e,Je=Ke._malloc(262144),Qe=Ke._malloc(65536),Ze=Ke._malloc(256)}function tt(){Ke&&(Je&&Ke._free(Je),Qe&&Ke._free(Qe),Ze&&Ke._free(Ze),Je=0,Qe=0,Ze=0),Ke=null}function rt(){if(!Ke)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ke}const nt={create(e){const t=rt(),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,Je/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ze,s).set(o),t.geometry_init(r,Je,n,Ze,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,Qe,n).set(e.indices),t.geometry_setIndices16(r,Qe,n)}else{new Uint32Array(t.HEAPU8.buffer,Qe,n).set(e.indices),t.geometry_setIndices32(r,Qe,n)}}return r},updateVertices(e,t,r=0){const n=rt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,Je/4),n.geometry_updateVertices(e,Je,s,r)},release(e){e>0&&rt().geometry_release(e)},isValid:e=>!(!Ke||e<=0)&&Ke.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return nt.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: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=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return nt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,n=-1/0,s=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-r)/(s-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 nt.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 st=null;function ot(e){st=e}function it(){st&&ct.isInitialized()&&ct.shutdown(),st=null}function at(){if(!st)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return st}const ct={init:(e,t)=>at().postprocess_init(e,t),shutdown(){at().postprocess_shutdown()},resize(e,t){at().postprocess_resize(e,t)},addPass:(e,t)=>at().postprocess_addPass(e,t),removePass(e){at().postprocess_removePass(e)},setEnabled(e,t){at().postprocess_setPassEnabled(e,t)},isEnabled:e=>at().postprocess_isPassEnabled(e),setUniform(e,t,r){at().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){at().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){at().postprocess_begin()},end(){at().postprocess_end()},getPassCount:()=>at().postprocess_getPassCount(),isInitialized:()=>!!st&&st.postprocess_isInitialized(),setBypass(e){at().postprocess_setBypass(e)},isBypassed:()=>!st||st.postprocess_isBypassed(),createBlur:()=>ve.createShader(lt,"#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(lt,"#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(lt,"#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(lt,"#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")},lt="#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 ut;exports.RenderStage=void 0,(ut=exports.RenderStage||(exports.RenderStage={}))[ut.Background=0]="Background",ut[ut.Opaque=1]="Opaque",ut[ut.Transparent=2]="Transparent",ut[ut.Overlay=3]="Overlay";let ht=null,dt=0;function pt(e){ht=e,dt=ht._malloc(64)}function ft(){ht&&dt&&(ht._free(dt),dt=0),ht=null}const xt={init(e,t){ht?.renderer_init(e,t)},resize(e,t){ht?.renderer_resize(e,t)},begin(e,t){ht&&dt&&(ht.HEAPF32.set(e,dt/4),ht.renderer_begin(dt,t??0))},flush(){ht?.renderer_flush()},end(){ht?.renderer_end()},submitSprites(e){ht&&ht.renderer_submitSprites(e._cpp)},submitSpine(e){ht&&ht.renderer_submitSpine?.(e._cpp)},setStage(e){ht?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>ht?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){ht?.renderer_releaseTarget(e)},getTargetTexture:e=>ht?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ht?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){ht?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>ht?{drawCalls:ht.renderer_getDrawCalls(),triangles:ht.renderer_getTriangles(),sprites:ht.renderer_getSprites(),spine:ht.renderer_getSpine?.()??0,meshes:ht.renderer_getMeshes(),culled:ht.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let _t=null;function mt(e){_t=e}function gt(){_t=null}const yt={enable(){_t?.gl_enableErrorCheck(!0)},disable(){_t?.gl_enableErrorCheck(!1)},check:e=>_t?.gl_checkErrors(e)??0,diagnose(){_t?.renderer_diagnose()}},wt=new Map;function vt(e){wt.delete(e)}class St{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;xt.resize(n,s),ct.isInitialized()&&ct.getPassCount()>0&&!ct.isBypassed()&&ct.resize(n,s),xt.begin(r),xt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):xt.submitSpine(t),xt.flush();const i=wt;if(i.size>0){je.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)}je.end();for(const t of e)vt(t)}xt.end()}}class Pt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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 ne,this.resources_=new H;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Pt}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_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}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,gt(),ft(),it(),tt(),ye(),Ne()}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 Tt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ct(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function bt(e,t,r,n,s){const o=e*t/r,i=e;switch(n){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function At(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,c=n-r,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+r)/c,i[14]=-(o+s)/l,i[15]=1,i}function Mt(e,t,r,n){const s=new Float32Array(16),o=1/Math.tan(e/2),i=r-n;return s[0]=o/t,s[5]=o,s[10]=(n+r)/i,s[11]=-1,s[14]=2*n*r/i,s}function Rt(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 Et(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}function Ft(e,t){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const s=r.createTexture(t.width,t.height,n,t.pixels.length,1);return e._free(n),s}function Ut(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function It(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function Wt(e,t,r,n,s){const o=await async function(e,t,r){const n={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==n[s])continue;try{n[s]=Ft(e,await r.loadPixels(s))}catch{n[s]=0}}return n}(t,r,n);!function(e,t,r){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const s=r[e];if(s&&s>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;n.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={};s&&(i=await async function(e,t,r,n){const s={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=n.resolvePath(o),c=n.resolvePath(i);try{const r=n.readText(i),l=a.endsWith(".skel");Ut(t,a),l?t.FS.writeFile(a,n.readBinary(o)):t.FS.writeFile(a,n.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;s[o]=u;const h=It(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const s=d+"/"+h[r];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=Ft(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,r,n));const a=function(e,t){const r={},n={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===r[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){r[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=ve.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=ve.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),c=Re(e.world,r);if(function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const s=e.get(t,F);s&&(s.texture=r[n.data.texture]||0,e.insert(t,F,s))}}}(e.world,r,o,c),function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const s=r[n.data.material]||0;if(s)if("Sprite"===n.type){const r=e.get(t,F);r&&(r.material=s,e.insert(t,F,r))}else if("SpineAnimation"===n.type){const r=e.get(t,$);r&&(r.material=s,e.insert(t,$,r))}}}}(e.world,r,a,c),s){const n=function(e,t,r,n){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,r,i,c);!function(e,t,r,n){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in n){const s=n[e];r.spine_update(s,i);const o=r.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const n=r.spine_getMeshBatchVertexCount(s,e),o=r.spine_getMeshBatchIndexCount(s,e);if(!n||!o)continue;const i=8*n*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(s,e,c,l,u,h);const d=r.HEAPU32[u>>2],p=r.HEAPU32[h>>2],f=new Float32Array(r.HEAPF32.buffer,c,8*n),x=new Uint16Array(r.HEAPU8.buffer,l,o),_=t._malloc(i),m=t._malloc(a);t.HEAPF32.set(f,_>>2),new Uint16Array(t.HEAPU8.buffer,m,o).set(x),t.renderer_submitTriangles(_,n,m,o,d,p,0),t._free(_),t._free(m),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,s,n)}}class Bt{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,s=e.data.atlasPath;n&&(n.endsWith(".skel")?r.add(n):t.add(n)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),n=await r.blob(),s=await createImageBitmap(n),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const zt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=xt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:xt.getTargetTexture(r),width:e.width,height:e.height}},release(e){xt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(xt.releaseRenderTarget(e._handle),zt.create({width:t,height:r,depth:!0})),begin(e,t){xt.begin(t,e._handle)},end(){xt.end()},getDepthTexture:e=>xt.getTargetDepthTexture(e._handle)};let $t=!1;var kt;g||(g=!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 a(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 c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),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=kt=y,console.log(`[ESEngine] Platform: ${kt.name}`),exports.App=Pt,exports.AssetPlugin=Be,exports.AssetServer=Ie,exports.Assets=We,exports.AsyncCache=Ue,exports.Camera=U,exports.Canvas=I,exports.Children=z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=X,exports.Draw=je,exports.EntityCommands=j,exports.GLDebug=yt,exports.Geometry=nt,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=Me,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=B,exports.PostProcess=ct,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,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(),n=new Bt(this.baseUrl_);await n.prefetch(t);let s=null;const o=this.app_.__spineInitPromise;if(o){s=(await o).controller.module}await Wt(this.app_,this.app_.wasmModule,t,n,s),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([U]);for(const n of r){if(e.get(n,U).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const n=e.getEntitiesWithComponents([I]);for(const s of n){const n=e.get(s,I);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,r=n.designResolution.x/n.designResolution.y;break}}const s=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,R,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,U,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{G(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)},exports.QueryInstance=V,exports.RenderPipeline=St,exports.RenderTexture=zt,exports.Renderer=xt,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=Ae,exports.SpineAnimation=$,exports.Sprite=F,exports.SystemRunner=Q,exports.Text=ae,exports.TextPlugin=ue,exports.TextRenderer=ce,exports.Time=N,exports.UIRect=le,exports.Velocity=W,exports.WebAssetProvider=Bt,exports.World=ne,exports.WorldTransform=E,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=ze,exports.clearDrawCallbacks=function(){wt.clear()},exports.clearUserComponents=function(){P().clear()},exports.color=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),exports.createWebApp=function(e,t){const r=Pt.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),He(e),ge(e),et(e),ot(e),pt(e),mt(e);const s=new St;r.pipeline_=s;let o=i();const a=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=a(),r=n.entityCount(),c=Ct(n,r+1e3);if(c){const e=c.backgroundColor;xt.setClearColor(e.x,e.y,e.z,e.w)}const l=function(e,t,r){const n=e.entityCount(),s=n+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const o=e.getCamera(n);if(!o.isActive)continue;const i=e.getLocalTransform(n),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=Ct(e,s);if(r){t=bt(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const n=t*a;c=At(-n,n,-t,t,-o.farPlane,o.farPlane)}else c=Mt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Et(c,Rt(i.position.x,i.position.y,i.position.z))}return Tt}(n,e,t),u=(i()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:l,width:e,height:t,elapsed:u})}};return r.addSystemToSchedule(exports.Schedule.Last,c),r.addPlugin(ze),r.addPlugin(re),r.addPlugin(he),r},exports.defineComponent=T,exports.defineResource=L,exports.defineSystem=K,exports.defineTag=function(e){const t=P(),r=t.get(e);if(r)return r;const n=S(e,{});return t.set(e,n),b(e,{},!0),n},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=k[e];if(t)return{...t._default};const r=C(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=C,exports.initDrawAPI=He,exports.initGLDebugAPI=mt,exports.initGeometryAPI=et,exports.initMaterialAPI=ge,exports.initPostProcessAPI=ot,exports.initRendererAPI=pt,exports.inputPlugin=re,exports.isBuiltinComponent=M,exports.isEditor=function(){return $t},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!$t},exports.isTextureRef=pe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Fe,exports.loadRuntimeScene=Wt,exports.loadSceneData=Re,exports.loadSceneWithAssets=Ee,exports.platformFetch=r,exports.platformFileExists=s,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=async function(e){return t().readFile(e)},exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n}),exports.registerDrawCallback=function(e,t){wt.set(e,t)},exports.registerMaterialCallback=be,exports.setEditorMode=function(e){$t=e},exports.shutdownDrawAPI=Ne,exports.shutdownGLDebugAPI=gt,exports.shutdownGeometryAPI=tt,exports.shutdownMaterialAPI=ye,exports.shutdownPostProcessAPI=it,exports.shutdownRendererAPI=ft,exports.textPlugin=he,exports.unregisterDrawCallback=vt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([U]);for(const n of r){const r=e.get(n,U);r&&(r.aspectRatio=t,e.insert(n,U,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,n=1)=>({x:e,y:t,z:r,w:n}),exports.wxFileExists=p,exports.wxFileExistsSync=function(e){const t=u();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=m,exports.wxLoadImage=_,exports.wxLoadImagePixels=async function(e,t=!0){return m(await _(e),t)},exports.wxReadFile=h,exports.wxReadTextFile=d,exports.wxWriteFile=function(e,t){return new Promise((r,n)=>{u().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function c(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 u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,r)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let x=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 g(e,t=!0){const{width:r,height:s}=e,{ctx:n}=function(e,t){return x||(x=wx.createCanvas(),x.width=e,x.height=t,m=x.getContext("2d")),(x.width<e||x.height<t)&&(x.width=Math.max(x.width,e),x.height=Math.max(x.height,t)),{canvas:x,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 y=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return d(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;let S=0;function P(e,t){const r=++S;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 b(e,t){const r=T(),s=r.get(e);if(s)return s;const n=P(e,t);return r.set(e,n),A(e,t,!1),n}function C(e){return T().get(e)}function A(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function M(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function E(e){return!0===e._builtin}const R=M("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=M("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=M("Sprite",{texture:v,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=M("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),W=M("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),B=M("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),z=M("Parent",{entity:0}),D=M("Children",{entities:[]}),$=M("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}),k={LocalTransform:R,WorldTransform:U,Sprite:F,Camera:I,Canvas:W,Velocity:B,Parent:z,Children:D,SpineAnimation:$};let L=0;function O(e,t){const r=++L;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class H{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 N{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 H(this.get(e),t=>this.set(e,t))}}const G=O({delta:0,elapsed:0,frameCount:0},"Time");function V(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class j{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,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];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)c.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}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]}}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 q{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 K=0;function J(e,t,r){const s=++K;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function Q(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Z{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 q&&e.flush()}resolveParam(e){switch(e._type){case"query":return new j(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new q(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ee{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=O(new ee,"Input");class re{constructor(e){this.target_=e??null}build(e){const r=new ee;e.insertResource(te,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,J([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const se=new re;class ne{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 oe,ie,ae;exports.TextAlign=void 0,(oe=exports.TextAlign||(exports.TextAlign={}))[oe.Left=0]="Left",oe[oe.Center=1]="Center",oe[oe.Right=2]="Right",exports.TextVerticalAlign=void 0,(ie=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ie.Top=0]="Top",ie[ie.Middle=1]="Middle",ie[ie.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ae=exports.TextOverflow||(exports.TextOverflow={}))[ae.Visible=0]="Visible",ae[ae.Clip=1]="Clip",ae[ae.Ellipsis=2]="Ellipsis";const ce=b("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=i(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 c=this.wrapText(e.content,a?o: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),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/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(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 x=Math.round(255*e.color.x),m=Math.round(255*e.color.y),_=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(${x}, ${m}, ${_}, ${g})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=c.length*l;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 c){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+=l}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),P=new Uint8Array(S.data.buffer),T=this.flipVertically(P,p,f),b=this.module.getResourceManager(),C=this.module._malloc(T.length);this.module.HEAPU8.set(T,C);const A=b.createTexture(p,f,C,T.length,1);return this.module._free(C),{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 ue=b("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class he{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,J([],()=>{const e=s.getEntitiesWithComponents([ce]);for(const t of e){const e=s.get(t,ce);if(!e.dirty)continue;s.has(t,F)||s.insert(t,F,{texture:v,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,ue)?s.get(t,ue):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 de=new he;var pe;function fe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(pe=exports.BlendMode||(exports.BlendMode={}))[pe.Normal=0]="Normal",pe[pe.Additive=1]="Additive",pe[pe.Multiply=2]="Multiply",pe[pe.Screen=3]="Screen",pe[pe.PremultipliedAlpha=4]="PremultipliedAlpha";let xe=null,me=null,_e=1;const ge=new Map;function ye(e){xe=e,me=e.getResourceManager(),Ae()}function we(){0!==Te&&xe&&(xe._free(Te),Te=0),ge.clear(),_e=1,Pe=!1,me=null,xe=null}function ve(){if(!me)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return me}const Se={createShader:(e,t)=>ve().createShader(e,t),releaseShader(e){e>0&&ve().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 ge.set(t,r),t},get:e=>ge.get(e),setUniform(e,t,r){const s=ge.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=ge.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=ge.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=ge.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=ge.get(e);r&&(r.depthTest=t)},getShader(e){const t=ge.get(e);return t?.shader??0},release(e){ge.delete(e)},isValid:e=>ge.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=ge.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 ge.set(r,s),r},toAssetData(e,t){const r=ge.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=ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Pe=!1,Te=0;const be=4096;function Ce(e){const t=(0===Te&&xe&&(Te=xe._malloc(be)),Te);if(0===t||!xe)return{ptr:0,count:0};let r=0,s=0;const n=xe.HEAPU8,o=xe.HEAPU32,i=xe.HEAPF32;for(const[a,c]of e){if(r+128>be)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,n.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]);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(!xe||Pe)return;xe.materialDataProvider=(e,t,r,s,n)=>{const o=ge.get(e);if(!o)return xe.HEAPU32[t>>2]=0,xe.HEAPU32[r>>2]=0,xe.HEAPU32[s>>2]=0,void(xe.HEAPU32[n>>2]=0);xe.HEAPU32[t>>2]=o.shader,xe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Ce(o.uniforms);xe.HEAPU32[s>>2]=i,xe.HEAPU32[n>>2]=a},Pe=!0}const Me={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ee{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&&(Se.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Se.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:Se.createFromAsset(s,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}}function Re(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)Fe(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}async function Ue(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}}Fe(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 Fe(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,W,s);break;case"Text":e.insert(t,ce,s);break;case"SpineAnimation":e.insert(t,$,s);break;case"UIRect":e.insert(t,ue,s);break;default:{const n=C(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Ie{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 We{constructor(e){this.textureCache_=new Ie,this.shaderCache_=new Ie,this.jsonCache_=new Ie,this.textCache_=new Ie,this.binaryCache_=new Ie,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,this.module_=e,this.canvas_=i(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 Ee(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}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 this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${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),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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 Ue(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){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r)??r;return new Promise((r,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=s})}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 c=i.createTexture(t,r,a,o.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 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){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(r);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Se.createShader(s,i)}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}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await n(t);return JSON.parse(r)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const 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 Be=O(null,"Assets");class ze{build(e){const t=e.wasmModule;t?e.insertResource(Be,new We(t)):console.warn("AssetPlugin: No WASM module available")}}const De=new ze;let $e=null,ke=0,Le=0,Oe=0;const He=new Float32Array(256);function Ne(e){$e=e,ke=$e._malloc(64),Le=$e._malloc(64),Oe=$e._malloc(1024)}function Ge(){$e&&(ke&&($e._free(ke),ke=0),Le&&($e._free(Le),Le=0),Oe&&($e._free(Oe),Oe=0)),$e=null}function Ve(){if(!$e)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return $e}const je={x:1,y:1,z:1,w:1},Xe={begin(e){const t=Ve();t.HEAPF32.set(e,ke/4),t.draw_begin(ke)},end(){Ve().draw_end()},line(e,t,r,s=1){Ve().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){Ve().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){Ve().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){Ve().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){Ve().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},texture(e,t,r,s=je){Ve().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=je){Ve().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.x,n.y,n.z,n.w)},setLayer(e){Ve().draw_setLayer(e)},setDepth(e){Ve().draw_setDepth(e)},getDrawCallCount:()=>$e?$e.draw_getDrawCallCount():0,getPrimitiveCount:()=>$e?$e.draw_getPrimitiveCount():0,setBlendMode(e){Ve().draw_setBlendMode(e)},setDepthTest(e){Ve().draw_setDepthTest(e)},drawMesh(e,t,r){const s=Ve();s.HEAPF32.set(r,Le/4),s.draw_mesh(e,t,Le)},drawMeshWithMaterial(e,t,r){const s=Ve(),n=Se.get(t);if(!n)return;if(Xe.setBlendMode(n.blendMode),Xe.setDepthTest(n.depthTest),0===n.uniforms.size)return void Xe.drawMesh(e,n.shader,r);s.HEAPF32.set(r,Le/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=Ye(e);if(!(r<0)){if(fe(t))He[o++]=10,He[o++]=r,He[o++]=t.slot??i++,He[o++]=t.textureId;else if("number"==typeof t)He[o++]=1,He[o++]=r,He[o++]=t;else if(Array.isArray(t)){He[o++]=t.length,He[o++]=r;for(let e=0;e<t.length;e++)He[o++]=t[e]}else"w"in t?(He[o++]=4,He[o++]=r,He[o++]=t.x,He[o++]=t.y,He[o++]=t.z,He[o++]=t.w):"z"in t?(He[o++]=3,He[o++]=r,He[o++]=t.x,He[o++]=t.y,He[o++]=t.z):(He[o++]=2,He[o++]=r,He[o++]=t.x,He[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(He.subarray(0,o),Oe/4),s.draw_meshWithUniforms(e,n.shader,Le,Oe,o)):s.draw_mesh(e,n.shader,Le)}},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 Ye(e){return qe[e]??-1}var Ke;exports.DataType=void 0,(Ke=exports.DataType||(exports.DataType={}))[Ke.Float=1]="Float",Ke[Ke.Float2=2]="Float2",Ke[Ke.Float3=3]="Float3",Ke[Ke.Float4=4]="Float4",Ke[Ke.Int=5]="Int",Ke[Ke.Int2=6]="Int2",Ke[Ke.Int3=7]="Int3",Ke[Ke.Int4=8]="Int4";let Je=null,Qe=0,Ze=0,et=0;function tt(e){Je=e,Qe=Je._malloc(262144),Ze=Je._malloc(65536),et=Je._malloc(256)}function rt(){Je&&(Qe&&Je._free(Qe),Ze&&Je._free(Ze),et&&Je._free(et),Qe=0,Ze=0,et=0),Je=null}function st(){if(!Je)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Je}const nt={create(e){const t=st(),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,Qe/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,et,n).set(o),t.geometry_init(r,Qe,s,et,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,Ze,s).set(e.indices),t.geometry_setIndices16(r,Ze,s)}else{new Uint32Array(t.HEAPU8.buffer,Ze,s).set(e.indices),t.geometry_setIndices32(r,Ze,s)}}return r},updateVertices(e,t,r=0){const s=st(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,Qe/4),s.geometry_updateVertices(e,Qe,n,r)},release(e){e>0&&st().geometry_release(e)},isValid:e=>!(!Je||e<=0)&&Je.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return nt.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,c=(Math.sin(n)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return nt.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 nt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let ot=null;function it(e){ot=e}function at(){ot&<.isInitialized()&<.shutdown(),ot=null}function ct(){if(!ot)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ot}const lt={init:(e,t)=>ct().postprocess_init(e,t),shutdown(){ct().postprocess_shutdown()},resize(e,t){ct().postprocess_resize(e,t)},addPass:(e,t)=>ct().postprocess_addPass(e,t),removePass(e){ct().postprocess_removePass(e)},setEnabled(e,t){ct().postprocess_setPassEnabled(e,t)},isEnabled:e=>ct().postprocess_isPassEnabled(e),setUniform(e,t,r){ct().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){ct().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){ct().postprocess_begin()},end(){ct().postprocess_end()},getPassCount:()=>ct().postprocess_getPassCount(),isInitialized:()=>!!ot&&ot.postprocess_isInitialized(),setBypass(e){ct().postprocess_setBypass(e)},isBypassed:()=>!ot||ot.postprocess_isBypassed(),createBlur:()=>Se.createShader(ut,"#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:()=>Se.createShader(ut,"#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:()=>Se.createShader(ut,"#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:()=>Se.createShader(ut,"#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")},ut="#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 ht;exports.RenderStage=void 0,(ht=exports.RenderStage||(exports.RenderStage={}))[ht.Background=0]="Background",ht[ht.Opaque=1]="Opaque",ht[ht.Transparent=2]="Transparent",ht[ht.Overlay=3]="Overlay";let dt=null,pt=0;function ft(e){dt=e,pt=dt._malloc(64)}function xt(){dt&&pt&&(dt._free(pt),pt=0),dt=null}const mt={init(e,t){dt?.renderer_init(e,t)},resize(e,t){dt?.renderer_resize(e,t)},begin(e,t){dt&&pt&&(dt.HEAPF32.set(e,pt/4),dt.renderer_begin(pt,t??0))},flush(){dt?.renderer_flush()},end(){dt?.renderer_end()},submitSprites(e){dt&&dt.renderer_submitSprites(e._cpp)},submitSpine(e){dt&&dt.renderer_submitSpine?.(e._cpp)},setStage(e){dt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>dt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){dt?.renderer_releaseTarget(e)},getTargetTexture:e=>dt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>dt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){dt?.renderer_setClearColor?.(e,t,r,s)},getStats:()=>dt?{drawCalls:dt.renderer_getDrawCalls(),triangles:dt.renderer_getTriangles(),sprites:dt.renderer_getSprites(),spine:dt.renderer_getSpine?.()??0,meshes:dt.renderer_getMeshes(),culled:dt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let _t=null;function gt(e){_t=e}function yt(){_t=null}const wt={enable(){_t?.gl_enableErrorCheck(!0)},disable(){_t?.gl_enableErrorCheck(!1)},check:e=>_t?.gl_checkErrors(e)??0,diagnose(){_t?.renderer_diagnose()}},vt=new Map;function St(e){vt.delete(e)}class Pt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;mt.resize(s,n),lt.isInitialized()&<.getPassCount()>0&&!lt.isBypassed()&<.resize(s,n),mt.begin(r),mt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):mt.submitSpine(t),mt.flush();const i=vt;if(i.size>0){Xe.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)}Xe.end();for(const t of e)St(t)}mt.end()}}class Tt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),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 ne,this.resources_=new N;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Tt}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_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}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 Z(this.world_,this.resources_),this.resources_.insert(G,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,yt(),xt(),at(),rt(),we(),Ge()}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(G),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(G,r)}}const bt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ct(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function At(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Mt(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,c=s-r,l=o-n;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(s+r)/c,i[14]=-(o+n)/l,i[15]=1,i}function Et(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 Rt(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 Ut(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}function Ft(e,t){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const n=r.createTexture(t.width,t.height,s,t.pixels.length,1);return e._free(s),n}function It(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function Wt(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function Bt(e,t,r,s,n){const o=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Ft(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={};n&&(i=await async function(e,t,r,s){const n={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=s.resolvePath(o),c=s.resolvePath(i);try{const r=s.readText(i),l=a.endsWith(".skel");It(t,a),l?t.FS.writeFile(a,s.readBinary(o)):t.FS.writeFile(a,s.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;n[o]=u;const h=Wt(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const n=d+"/"+h[r];try{const o=s.loadPixelsRaw?await s.loadPixelsRaw(n):await s.loadPixels(n),i=Ft(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return n}(t,n,r,s));const a=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Se.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=Se.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),c=Re(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,F);n&&(n.texture=r[s.data.texture]||0,e.insert(t,F,n))}}}(e.world,r,o,c),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,F);r&&(r.material=n,e.insert(t,F,r))}else if("SpineAnimation"===s.type){const r=e.get(t,$);r&&(r.material=n,e.insert(t,$,r))}}}}(e.world,r,a,c),n){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=s.get(o.id);void 0!==c&&(n[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return n}(n,r,i,c);!function(e,t,r,s){let n=0;e.setSpineRenderer((e,o)=>{let i=o-n;n=o,(i<=0||i>.5)&&(i=1/60);for(const e in s){const n=s[e];r.spine_update(n,i);const o=r.spine_getMeshBatchCount(n);for(let e=0;e<o;e++){const s=r.spine_getMeshBatchVertexCount(n,e),o=r.spine_getMeshBatchIndexCount(n,e);if(!s||!o)continue;const i=8*s*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(n,e,c,l,u,h);const d=r.HEAPU32[u>>2],p=r.HEAPU32[h>>2],f=new Float32Array(r.HEAPF32.buffer,c,8*s),x=new Uint16Array(r.HEAPU8.buffer,l,o),m=t._malloc(i),_=t._malloc(a);t.HEAPF32.set(f,m>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(x),t.renderer_submitTriangles(m,s,_,o,d,p,0),t._free(m),t._free(_),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,n,s)}}class zt{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Dt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=mt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:mt.getTargetTexture(r),width:e.width,height:e.height}},release(e){mt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(mt.releaseRenderTarget(e._handle),Dt.create({width:t,height:r,depth:!0})),begin(e,t){mt.begin(t,e._handle)},end(){mt.end()},getDepthTexture:e=>mt.getTargetDepthTexture(e._handle)};let $t=!1;var kt;y||(y=!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 c(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=kt=w,console.log(`[ESEngine] Platform: ${kt.name}`),exports.App=Tt,exports.AssetPlugin=ze,exports.AssetServer=We,exports.Assets=Be,exports.AsyncCache=Ie,exports.Camera=I,exports.Canvas=W,exports.Children=D,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=q,exports.Draw=Xe,exports.EntityCommands=X,exports.GLDebug=wt,exports.Geometry=nt,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=v,exports.Input=te,exports.InputPlugin=re,exports.InputState=ee,exports.LocalTransform=R,exports.Material=Se,exports.MaterialLoader=Ee,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=z,exports.PostProcess=lt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,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=new zt(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.module}await Bt(this.app_,this.app_.wasmModule,t,s,n),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");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([W]);for(const n of s){const s=e.get(n,W);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,R,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(n,I,i)}}},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=j,exports.RenderPipeline=Pt,exports.RenderTexture=Dt,exports.Renderer=mt,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=Me,exports.SpineAnimation=$,exports.Sprite=F,exports.SystemRunner=Z,exports.Text=ce,exports.TextPlugin=he,exports.TextRenderer=le,exports.Time=G,exports.UIRect=ue,exports.Velocity=B,exports.WebAssetProvider=zt,exports.World=ne,exports.WorldTransform=U,exports.addStartupSystem=function(e){Q().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Q().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Q().push({schedule:e,system:t})},exports.assetPlugin=De,exports.clearDrawCallbacks=function(){vt.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.createWebApp=function(e,t){const r=Tt.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ne(e),ye(e),tt(e),it(e),ft(e),gt(e);const n=new Pt;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=i(),r=s.entityCount(),c=Ct(s,r+1e3);if(c){const e=c.backgroundColor;mt.setClearColor(e.x,e.y,e.z,e.w)}const l=function(e,t,r){const s=e.entityCount(),n=s+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=Ct(e,n);if(r){t=At(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const s=t*a;c=Mt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=Et(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Ut(c,Rt(i.position.x,i.position.y,i.position.z))}return bt}(s,e,t),u=(a()-o)/1e3;n.render({registry:{_cpp:s},viewProjection:l,width:e,height:t,elapsed:u})}};return r.addSystemToSchedule(exports.Schedule.Last,c),r.addPlugin(De),r.addPlugin(se),r.addPlugin(de),r},exports.defineComponent=b,exports.defineResource=O,exports.defineSystem=J,exports.defineTag=function(e){const t=T(),r=t.get(e);if(r)return r;const s=P(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=k[e];if(t)return{...t._default};const r=C(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=C,exports.initDrawAPI=Ne,exports.initGLDebugAPI=gt,exports.initGeometryAPI=tt,exports.initMaterialAPI=ye,exports.initPostProcessAPI=it,exports.initRendererAPI=ft,exports.inputPlugin=se,exports.isBuiltinComponent=E,exports.isEditor=function(){return $t},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!$t},exports.isTextureRef=fe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Fe,exports.loadRuntimeScene=Bt,exports.loadSceneData=Re,exports.loadSceneWithAssets=Ue,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){vt.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Be);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Ae,exports.setEditorMode=function(e){$t=e},exports.shutdownDrawAPI=Ge,exports.shutdownGLDebugAPI=yt,exports.shutdownGeometryAPI=rt,exports.shutdownMaterialAPI=we,exports.shutdownPostProcessAPI=at,exports.shutdownRendererAPI=xt,exports.textPlugin=de,exports.unregisterDrawCallback=St,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=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=g,exports.wxLoadImage=_,exports.wxLoadImagePixels=async function(e,t=!0){return g(await _(e),t)},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex c61f77dc6..04c0738fa 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 o(){return"web"===e?.name}async function i(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 o=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(o.data.buffer)}}async function T(e,t=!0){return P(await b(e),t)}let M=!1;const E=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()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,U=(e=0,t=0)=>({x:e,y:t}),F=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),z=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),I=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),W=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let B=0;function $(e,t){const r=++B;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function k(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function D(e,t){const r=k(),n=r.get(e);if(n)return n;const s=$(e,t);return r.set(e,s),N(e,t,!1),s}function L(e){const t=k(),r=t.get(e);if(r)return r;const n=$(e,{});return t.set(e,n),N(e,{},!0),n}function O(e){return k().get(e)}function H(){k().clear()}function N(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function j(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function X(e){return!0===e._builtin}const G=j("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=j("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),q=j("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}),Y=j("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),K=j("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=j("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=j("Parent",{entity:0}),Z=j("Children",{entities:[]}),ee=j("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:G,WorldTransform:V,Sprite:q,Camera:Y,Canvas:K,Velocity:J,Parent:Q,Children:Z,SpineAnimation:ee};function re(e){const t=te[e];if(t)return{...t._default};const r=O(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 oe(e){return{_type:"res",_resource:e}}function ie(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)),o=[...s,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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 Me{constructor(e){this.target_=e??null}build(e){const r=new Pe;e.insertResource(Te,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,n){r.mouseX=t,r.mouseY=n,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(ge.First,we([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ee=new Me;class Ae{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,Ue,Fe;!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"}(Ue||(Ue={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Fe||(Fe={}));const ze=D("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Re.Left,verticalAlign:Ue.Top,wordWrap:!0,overflow:Fe.Visible,lineHeight:1.2,dirty:!0});class Ie{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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===Fe.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<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===Fe.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 Ue.Top:x=u;break;case Ue.Middle:x=(p-w)/2;break;case Ue.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===Fe.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 M=P.createTexture(f,p,T,b.length,1);return this.module._free(T),{textureHandle:M,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 o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const We=D("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Be{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new Ie(t),n=e.world;e.addSystemToSchedule(ge.PreUpdate,we([],()=>{const e=n.getEntitiesWithComponents([ze]);for(const t of e){const e=n.get(t,ze);if(!e.dirty)continue;n.has(t,q)||n.insert(t,q,{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,We)?n.get(t,We):null,o=r.renderForEntity(t,e,s),i=n.get(t,q);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},n.insert(t,q,i),e.dirty=!1}}))}}const $e=new Be;var ke;function De(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"}(ke||(ke={}));let Le=null,Oe=null,He=1;const Ne=new Map;function je(e){Le=e,Oe=e.getResourceManager(),Qe()}function Xe(){0!==Ye&&Le&&(Le._free(Ye),Ye=0),Ne.clear(),He=1,qe=!1,Oe=null,Le=null}function Ge(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ve={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=He++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ke.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??ke.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??ke.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=He++,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 qe=!1,Ye=0;const Ke=4096;function Je(e){const t=(0===Ye&&Le&&(Ye=Le._malloc(Ke)),Ye);if(0===t||!Le)return{ptr:0,count:0};let r=0,n=0;const s=Le.HEAPU8,o=Le.HEAPU32,i=Le.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);o[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]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function Qe(){if(!Le||qe)return;Le.materialDataProvider=(e,t,r,n,s)=>{const o=Ne.get(e);if(!o)return Le.HEAPU32[t>>2]=0,Le.HEAPU32[r>>2]=0,Le.HEAPU32[n>>2]=0,void(Le.HEAPU32[s>>2]=0);Le.HEAPU32[t>>2]=o.shader,Le.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Je(o.uniforms);Le.HEAPU32[n>>2]=i,Le.HEAPU32[s>>2]=a},qe=!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"};class et{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),o=await this.shaderLoader_.load(s);return{handle:Ve.createFromAsset(n,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function tt(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)nt(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 rt(e,t,r){const n=new Map,s=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();n.set(i.id,t);for(const n of i.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,o.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,o=e.atlasPath;if(t&&o){const e=await s.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 s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}nt(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=o.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function nt(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,G,n);break;case"Sprite":e.insert(t,q,n);break;case"Camera":e.insert(t,Y,n);break;case"Canvas":e.insert(t,K,n);break;case"Text":e.insert(t,ze,n);break;case"SpineAnimation":e.insert(t,ee,n);break;case"UIRect":e.insert(t,We,n);break;default:{const s=O(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function st(e,t){const r=e.getEntitiesWithComponents([Y]);for(const n of r){const r=e.get(n,Y);r&&(r.aspectRatio=t,e.insert(n,Y,r))}}class ot{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 it{constructor(e){this.textureCache_=new ot,this.shaderCache_=new ot,this.jsonCache_=new ot,this.textCache_=new ot,this.binaryCache_=new ot,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.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 et(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),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};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("/")),c=this.parseAtlasTextures(i);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 rt(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 o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;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),o=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,r,a,o.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 i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(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 at=se(null,"Assets");class ct{build(e){const t=e.wasmModule;t?e.insertResource(at,new it(t)):console.warn("AssetPlugin: No WASM module available")}}const lt=new ct;let ut=null,ht=0,dt=0,ft=0;const pt=new Float32Array(256);function _t(e){ut=e,ht=ut._malloc(64),dt=ut._malloc(64),ft=ut._malloc(1024)}function mt(){ut&&(ht&&(ut._free(ht),ht=0),dt&&(ut._free(dt),dt=0),ft&&(ut._free(ft),ft=0)),ut=null}function gt(){if(!ut)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ut}const yt={x:1,y:1,z:1,w:1},wt={begin(e){const t=gt();t.HEAPF32.set(e,ht/4),t.draw_begin(ht)},end(){gt().draw_end()},line(e,t,r,n=1){gt().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){gt().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){gt().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){gt().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){gt().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=yt){gt().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=yt){gt().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){gt().draw_setLayer(e)},setDepth(e){gt().draw_setDepth(e)},getDrawCallCount:()=>ut?ut.draw_getDrawCallCount():0,getPrimitiveCount:()=>ut?ut.draw_getPrimitiveCount():0,setBlendMode(e){gt().draw_setBlendMode(e)},setDepthTest(e){gt().draw_setDepthTest(e)},drawMesh(e,t,r){const n=gt();n.HEAPF32.set(r,dt/4),n.draw_mesh(e,t,dt)},drawMeshWithMaterial(e,t,r){const n=gt(),s=Ve.get(t);if(!s)return;if(wt.setBlendMode(s.blendMode),wt.setDepthTest(s.depthTest),0===s.uniforms.size)return void wt.drawMesh(e,s.shader,r);n.HEAPF32.set(r,dt/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=vt(e);if(!(r<0)){if(De(t))pt[o++]=10,pt[o++]=r,pt[o++]=t.slot??i++,pt[o++]=t.textureId;else if("number"==typeof t)pt[o++]=1,pt[o++]=r,pt[o++]=t;else if(Array.isArray(t)){pt[o++]=t.length,pt[o++]=r;for(let e=0;e<t.length;e++)pt[o++]=t[e]}else"w"in t?(pt[o++]=4,pt[o++]=r,pt[o++]=t.x,pt[o++]=t.y,pt[o++]=t.z,pt[o++]=t.w):"z"in t?(pt[o++]=3,pt[o++]=r,pt[o++]=t.x,pt[o++]=t.y,pt[o++]=t.z):(pt[o++]=2,pt[o++]=r,pt[o++]=t.x,pt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(pt.subarray(0,o),ft/4),n.draw_meshWithUniforms(e,s.shader,dt,ft,o)):n.draw_mesh(e,s.shader,dt)}},xt={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 vt(e){return xt[e]??-1}var St;!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"}(St||(St={}));let Ct=null,bt=0,Pt=0,Tt=0;function Mt(e){Ct=e,bt=Ct._malloc(262144),Pt=Ct._malloc(65536),Tt=Ct._malloc(256)}function Et(){Ct&&(bt&&Ct._free(bt),Pt&&Ct._free(Pt),Tt&&Ct._free(Tt),bt=0,Pt=0,Tt=0),Ct=null}function At(){if(!Ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ct}const Rt={create(e){const t=At(),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,bt/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Tt,s).set(o),t.geometry_init(r,bt,n,Tt,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,Pt,n).set(e.indices),t.geometry_setIndices16(r,Pt,n)}else{new Uint32Array(t.HEAPU8.buffer,Pt,n).set(e.indices),t.geometry_setIndices32(r,Pt,n)}}return r},updateVertices(e,t,r=0){const n=At(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,bt/4),n.geometry_updateVertices(e,bt,s,r)},release(e){e>0&&At().geometry_release(e)},isValid:e=>!(!Ct||e<=0)&&Ct.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return Rt.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:St.Float2},{name:"a_texCoord",type:St.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Rt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:St.Float2},{name:"a_texCoord",type:St.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 o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-r)/(s-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 Rt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:St.Float2},{name:"a_texCoord",type:St.Float2}],indices:new Uint16Array(i)})}};let Ut=null;function Ft(e){Ut=e}function zt(){Ut&&Wt.isInitialized()&&Wt.shutdown(),Ut=null}function It(){if(!Ut)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ut}const Wt={init:(e,t)=>It().postprocess_init(e,t),shutdown(){It().postprocess_shutdown()},resize(e,t){It().postprocess_resize(e,t)},addPass:(e,t)=>It().postprocess_addPass(e,t),removePass(e){It().postprocess_removePass(e)},setEnabled(e,t){It().postprocess_setPassEnabled(e,t)},isEnabled:e=>It().postprocess_isPassEnabled(e),setUniform(e,t,r){It().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){It().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){It().postprocess_begin()},end(){It().postprocess_end()},getPassCount:()=>It().postprocess_getPassCount(),isInitialized:()=>!!Ut&&Ut.postprocess_isInitialized(),setBypass(e){It().postprocess_setBypass(e)},isBypassed:()=>!Ut||Ut.postprocess_isBypassed(),createBlur:()=>Ve.createShader(Bt,"#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(Bt,"#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(Bt,"#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(Bt,"#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")},Bt="#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 $t;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}($t||($t={}));let kt=null,Dt=0;function Lt(e){kt=e,Dt=kt._malloc(64)}function Ot(){kt&&Dt&&(kt._free(Dt),Dt=0),kt=null}const Ht={init(e,t){kt?.renderer_init(e,t)},resize(e,t){kt?.renderer_resize(e,t)},begin(e,t){kt&&Dt&&(kt.HEAPF32.set(e,Dt/4),kt.renderer_begin(Dt,t??0))},flush(){kt?.renderer_flush()},end(){kt?.renderer_end()},submitSprites(e){kt&&kt.renderer_submitSprites(e._cpp)},submitSpine(e){kt&&kt.renderer_submitSpine?.(e._cpp)},setStage(e){kt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>kt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){kt?.renderer_releaseTarget(e)},getTargetTexture:e=>kt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>kt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){kt?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>kt?{drawCalls:kt.renderer_getDrawCalls(),triangles:kt.renderer_getTriangles(),sprites:kt.renderer_getSprites(),spine:kt.renderer_getSpine?.()??0,meshes:kt.renderer_getMeshes(),culled:kt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Nt=null;function jt(e){Nt=e}function Xt(){Nt=null}const Gt={enable(){Nt?.gl_enableErrorCheck(!0)},disable(){Nt?.gl_enableErrorCheck(!1)},check:e=>Nt?.gl_checkErrors(e)??0,diagnose(){Nt?.renderer_diagnose()}},Vt=new Map;function qt(e,t){Vt.set(e,t)}function Yt(e){Vt.delete(e)}function Kt(){Vt.clear()}class Jt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;Ht.resize(n,s),Wt.isInitialized()&&Wt.getPassCount()>0&&!Wt.isBypassed()&&Wt.resize(n,s),Ht.begin(r),Ht.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Ht.submitSpine(t),Ht.flush();const i=Vt;if(i.size>0){wt.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)}wt.end();for(const t of e)Yt(t)}Ht.end()}}class Qt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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 Ae,this.resources_=new ce;for(const e of Object.values(ge))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Qt}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_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}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,Xt(),Ot(),zt(),Et(),Xe(),mt()}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 Zt(e,t){const r=Qt.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),_t(e),je(e),Mt(e),Ft(e),Lt(e),jt(e);const s=new Jt;r.pipeline_=s;let o=d();const i=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}=i(),r=n.entityCount(),a=rr(n,r+1e3);if(a){const e=a.backgroundColor;Ht.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,r){const n=e.entityCount(),s=n+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const o=e.getCamera(n);if(!o.isActive)continue;const i=e.getLocalTransform(n),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=rr(e,s);if(r){t=nr(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const n=t*a;c=sr(-n,n,-t,t,-o.farPlane,o.farPlane)}else c=or(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return ar(c,ir(i.position.x,i.position.y,i.position.z))}return tr}(n,e,t),l=(d()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:c,width:e,height:t,elapsed:l})}};return r.addSystemToSchedule(ge.Last,a),r.addPlugin(lt),r.addPlugin(Ee),r.addPlugin($e),r}function er(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 tr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function rr(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function nr(e,t,r,n,s){const o=e*t/r,i=e;switch(n){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function sr(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,c=n-r,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+r)/c,i[14]=-(o+s)/l,i[15]=1,i}function or(e,t,r,n){const s=new Float32Array(16),o=1/Math.tan(e/2),i=r-n;return s[0]=o/t,s[5]=o,s[10]=(n+r)/i,s[11]=-1,s[14]=2*n*r/i,s}function ir(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 ar(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}function cr(e,t){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const s=r.createTexture(t.width,t.height,n,t.pixels.length,1);return e._free(n),s}function lr(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function ur(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function hr(e,t,r,n,s){const o=await async function(e,t,r){const n={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==n[s])continue;try{n[s]=cr(e,await r.loadPixels(s))}catch{n[s]=0}}return n}(t,r,n);!function(e,t,r){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const s=r[e];if(s&&s>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;n.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={};s&&(i=await async function(e,t,r,n){const s={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=n.resolvePath(o),c=n.resolvePath(i);try{const r=n.readText(i),l=a.endsWith(".skel");lr(t,a),l?t.FS.writeFile(a,n.readBinary(o)):t.FS.writeFile(a,n.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;s[o]=u;const h=ur(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const s=d+"/"+h[r];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=cr(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,r,n));const a=function(e,t){const r={},n={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===r[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){r[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ve.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=Ve.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),c=tt(e.world,r);if(function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const s=e.get(t,q);s&&(s.texture=r[n.data.texture]||0,e.insert(t,q,s))}}}(e.world,r,o,c),function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const s=r[n.data.material]||0;if(s)if("Sprite"===n.type){const r=e.get(t,q);r&&(r.material=s,e.insert(t,q,r))}else if("SpineAnimation"===n.type){const r=e.get(t,ee);r&&(r.material=s,e.insert(t,ee,r))}}}}(e.world,r,a,c),s){const n=function(e,t,r,n){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,r,i,c);!function(e,t,r,n){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in n){const s=n[e];r.spine_update(s,i);const o=r.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const n=r.spine_getMeshBatchVertexCount(s,e),o=r.spine_getMeshBatchIndexCount(s,e);if(!n||!o)continue;const i=8*n*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(s,e,c,l,u,h);const d=r.HEAPU32[u>>2],f=r.HEAPU32[h>>2],p=new Float32Array(r.HEAPF32.buffer,c,8*n),_=new Uint16Array(r.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,n,g,o,d,f,0),t._free(m),t._free(g),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,s,n)}}class dr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,s=e.data.atlasPath;n&&(n.endsWith(".skel")?r.add(n):t.add(n)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),n=await r.blob(),s=await createImageBitmap(n),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class fr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=new dr(this.baseUrl_);await r.prefetch(t);let n=null;const s=this.app_.__spineInitPromise;if(s){n=(await s).controller.module}await hr(this.app_,this.app_.wasmModule,t,r,n),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([Y]);for(const n of r){if(e.get(n,Y).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const n=e.getEntitiesWithComponents([K]);for(const s of n){const n=e.get(s,K);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,r=n.designResolution.x/n.designResolution.y;break}}const s=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,G,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,Y,i)}}}const pr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Ht.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Ht.getTargetTexture(r),width:e.width,height:e.height}},release(e){Ht.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Ht.releaseRenderTarget(e._handle),pr.create({width:t,height:r,depth:!0})),begin(e,t){Ht.begin(t,e._handle)},end(){Ht.end()},getDepthTexture:e=>Ht.getTargetDepthTexture(e._handle)};let _r=!1;function mr(e){_r=e}function gr(){return _r}function yr(){return!_r}var wr;M||(M=!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=wr=E,console.log(`[ESEngine] Platform: ${wr.name}`);export{Qt as App,ct as AssetPlugin,it as AssetServer,at as Assets,ot as AsyncCache,ke as BlendMode,Y as Camera,K as Canvas,Z as Children,pe as Commands,me as CommandsInstance,St as DataType,wt as Draw,_e as EntityCommands,Gt as GLDebug,Rt as Geometry,A as INVALID_ENTITY,R as INVALID_TEXTURE,Te as Input,Me as InputPlugin,Pe as InputState,G as LocalTransform,Ve as Material,et as MaterialLoader,ue as Mut,Q as Parent,Wt as PostProcess,fr as PreviewPlugin,de as Query,fe as QueryInstance,Jt as RenderPipeline,$t as RenderStage,pr as RenderTexture,Ht as Renderer,oe as Res,ie as ResMut,ge as Schedule,Ze as ShaderSources,ee as SpineAnimation,q as Sprite,be as SystemRunner,ze as Text,Re as TextAlign,Fe as TextOverflow,Be as TextPlugin,Ie as TextRenderer,Ue as TextVerticalAlign,le as Time,We as UIRect,J as Velocity,dr as WebAssetProvider,Ae as World,V as WorldTransform,Se as addStartupSystem,ve as addSystem,Ce as addSystemToSchedule,lt as assetPlugin,Kt as clearDrawCallbacks,H as clearUserComponents,I as color,Zt as createWebApp,D as defineComponent,se as defineResource,we as defineSystem,L as defineTag,er as flushPendingSystems,re as getComponentDefaults,t as getPlatform,n as getPlatformType,O as getUserComponent,_t as initDrawAPI,jt as initGLDebugAPI,Mt as initGeometryAPI,je as initMaterialAPI,Ft as initPostProcessAPI,Lt as initRendererAPI,Ee as inputPlugin,X as isBuiltinComponent,gr as isEditor,r as isPlatformInitialized,yr as isRuntime,De as isTextureRef,s as isWeChat,o as isWeb,nt as loadComponent,hr as loadRuntimeScene,tt as loadSceneData,rt as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,W as quat,qt as registerDrawCallback,Qe as registerMaterialCallback,mr as setEditorMode,mt as shutdownDrawAPI,Xt as shutdownGLDebugAPI,Et as shutdownGeometryAPI,Xe as shutdownMaterialAPI,zt as shutdownPostProcessAPI,Ot as shutdownRendererAPI,$e as textPlugin,Yt as unregisterDrawCallback,st as updateCameraAspectRatio,U as vec2,F as vec3,z 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 o(){return"web"===e?.name}async function i(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,b=null;function P(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 C(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,b=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:b}}(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 o=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(o.data.buffer)}}async function T(e,t=!0){return C(await P(e),t)}let E=!1;const M=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)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,U=(e=0,t=0)=>({x:e,y:t}),F=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),I=(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}),W=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let B=0;function $(e,t){const r=++B;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function k(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const r=k(),n=r.get(e);if(n)return n;const s=$(e,t);return r.set(e,s),N(e,t,!1),s}function D(e){const t=k(),r=t.get(e);if(r)return r;const n=$(e,{});return t.set(e,n),N(e,{},!0),n}function O(e){return k().get(e)}function H(){k().clear()}function N(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function j(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function X(e){return!0===e._builtin}const G=j("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=j("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),q=j("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}),Y=j("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),K=j("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=j("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=j("Parent",{entity:0}),Z=j("Children",{entities:[]}),ee=j("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:G,WorldTransform:V,Sprite:q,Camera:Y,Canvas:K,Velocity:J,Parent:Q,Children:Z,SpineAnimation:ee};function re(e){const t=te[e];if(t)return{...t._default};const r=O(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 oe(e){return{_type:"res",_resource:e}}function ie(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)),o=[...s,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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 be(e,t){xe().push({schedule:e,system:t})}class Pe{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 Ce{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 Ce,"Input");class Ee{constructor(e){this.target_=e??null}build(e){const r=new Ce;e.insertResource(Te,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,n){r.mouseX=t,r.mouseY=n,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(ge.First,we([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Me=new Ee;class Ae{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,Ue,Fe;!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"}(Ue||(Ue={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Fe||(Fe={}));const Ie=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Re.Left,verticalAlign:Ue.Top,wordWrap:!0,overflow:Fe.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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===Fe.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<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===Fe.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 Ue.Top:x=u;break;case Ue.Middle:x=(p-w)/2;break;case Ue.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===Fe.Clip&&r.restore();const S=r.getImageData(0,0,f,p),b=new Uint8Array(S.data.buffer),P=this.flipVertically(b,f,p),C=this.module.getResourceManager(),T=this.module._malloc(P.length);this.module.HEAPU8.set(P,T);const E=C.createTexture(f,p,T,P.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 o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const We=L("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Be{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([Ie]);for(const t of e){const e=n.get(t,Ie);if(!e.dirty)continue;n.has(t,q)||n.insert(t,q,{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,We)?n.get(t,We):null,o=r.renderForEntity(t,e,s),i=n.get(t,q);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},n.insert(t,q,i),e.dirty=!1}}))}}const $e=new Be;var ke;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"}(ke||(ke={}));let De=null,Oe=null,He=1;const Ne=new Map;function je(e){De=e,Oe=e.getResourceManager(),Qe()}function Xe(){0!==Ye&&De&&(De._free(Ye),Ye=0),Ne.clear(),He=1,qe=!1,Oe=null,De=null}function Ge(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ve={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=He++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ke.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??ke.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??ke.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=He++,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 qe=!1,Ye=0;const Ke=4096;function Je(e){const t=(0===Ye&&De&&(Ye=De._malloc(Ke)),Ye);if(0===t||!De)return{ptr:0,count:0};let r=0,n=0;const s=De.HEAPU8,o=De.HEAPU32,i=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);o[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]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function Qe(){if(!De||qe)return;De.materialDataProvider=(e,t,r,n,s)=>{const o=Ne.get(e);if(!o)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]=o.shader,De.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Je(o.uniforms);De.HEAPU32[n>>2]=i,De.HEAPU32[s>>2]=a},qe=!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"};class et{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),o=await this.shaderLoader_.load(s);return{handle:Ve.createFromAsset(n,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function tt(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)nt(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 rt(e,t,r){const n=new Map,s=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();n.set(i.id,t);for(const n of i.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,o.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,o=e.atlasPath;if(t&&o){const e=await s.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 s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}nt(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=o.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function nt(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,G,n);break;case"Sprite":e.insert(t,q,n);break;case"Camera":e.insert(t,Y,n);break;case"Canvas":e.insert(t,K,n);break;case"Text":e.insert(t,Ie,n);break;case"SpineAnimation":e.insert(t,ee,n);break;case"UIRect":e.insert(t,We,n);break;default:{const s=O(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function st(e,t){const r=e.getEntitiesWithComponents([Y]);for(const n of r){const r=e.get(n,Y);r&&(r.aspectRatio=t,e.insert(n,Y,r))}}class ot{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 it{constructor(e){this.textureCache_=new ot,this.shaderCache_=new ot,this.jsonCache_=new ot,this.textCache_=new ot,this.binaryCache_=new ot,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,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 et(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}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),o=await this.fetchText(s);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${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 c=this.resolveUrl(e,r),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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 rt(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){const r=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(r)??r;return new Promise((r,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=n})}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 o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;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),o=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,r,a,o.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){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const r=await c(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:s}=this.parseEsShader(r);if(!n||!s)throw new Error(`Invalid shader format: ${e}`);return Ve.createShader(n,s)}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}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await c(t);return JSON.parse(r)}const r=await i(e);if(!r.ok)throw new Error(`Failed to fetch JSON: ${e} (${r.status})`);return r.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const r=await i(e);if(!r.ok)throw new Error(`Failed to fetch text: ${e} (${r.status})`);return r.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const r=await i(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const 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 at=se(null,"Assets");class ct{build(e){const t=e.wasmModule;t?e.insertResource(at,new it(t)):console.warn("AssetPlugin: No WASM module available")}}const lt=new ct;function ut(e,t){const r=e.getResource(at);r&&r.registerEmbeddedAssets(t)}let ht=null,dt=0,ft=0,pt=0;const _t=new Float32Array(256);function mt(e){ht=e,dt=ht._malloc(64),ft=ht._malloc(64),pt=ht._malloc(1024)}function gt(){ht&&(dt&&(ht._free(dt),dt=0),ft&&(ht._free(ft),ft=0),pt&&(ht._free(pt),pt=0)),ht=null}function yt(){if(!ht)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ht}const wt={x:1,y:1,z:1,w:1},xt={begin(e){const t=yt();t.HEAPF32.set(e,dt/4),t.draw_begin(dt)},end(){yt().draw_end()},line(e,t,r,n=1){yt().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){yt().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){yt().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){yt().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){yt().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=wt){yt().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=wt){yt().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){yt().draw_setLayer(e)},setDepth(e){yt().draw_setDepth(e)},getDrawCallCount:()=>ht?ht.draw_getDrawCallCount():0,getPrimitiveCount:()=>ht?ht.draw_getPrimitiveCount():0,setBlendMode(e){yt().draw_setBlendMode(e)},setDepthTest(e){yt().draw_setDepthTest(e)},drawMesh(e,t,r){const n=yt();n.HEAPF32.set(r,ft/4),n.draw_mesh(e,t,ft)},drawMeshWithMaterial(e,t,r){const n=yt(),s=Ve.get(t);if(!s)return;if(xt.setBlendMode(s.blendMode),xt.setDepthTest(s.depthTest),0===s.uniforms.size)return void xt.drawMesh(e,s.shader,r);n.HEAPF32.set(r,ft/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=St(e);if(!(r<0)){if(Le(t))_t[o++]=10,_t[o++]=r,_t[o++]=t.slot??i++,_t[o++]=t.textureId;else if("number"==typeof t)_t[o++]=1,_t[o++]=r,_t[o++]=t;else if(Array.isArray(t)){_t[o++]=t.length,_t[o++]=r;for(let e=0;e<t.length;e++)_t[o++]=t[e]}else"w"in t?(_t[o++]=4,_t[o++]=r,_t[o++]=t.x,_t[o++]=t.y,_t[o++]=t.z,_t[o++]=t.w):"z"in t?(_t[o++]=3,_t[o++]=r,_t[o++]=t.x,_t[o++]=t.y,_t[o++]=t.z):(_t[o++]=2,_t[o++]=r,_t[o++]=t.x,_t[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(_t.subarray(0,o),pt/4),n.draw_meshWithUniforms(e,s.shader,ft,pt,o)):n.draw_mesh(e,s.shader,ft)}},vt={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 St(e){return vt[e]??-1}var bt;!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"}(bt||(bt={}));let Pt=null,Ct=0,Tt=0,Et=0;function Mt(e){Pt=e,Ct=Pt._malloc(262144),Tt=Pt._malloc(65536),Et=Pt._malloc(256)}function At(){Pt&&(Ct&&Pt._free(Ct),Tt&&Pt._free(Tt),Et&&Pt._free(Et),Ct=0,Tt=0,Et=0),Pt=null}function Rt(){if(!Pt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Pt}const Ut={create(e){const t=Rt(),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,Ct/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Et,s).set(o),t.geometry_init(r,Ct,n,Et,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,Tt,n).set(e.indices),t.geometry_setIndices16(r,Tt,n)}else{new Uint32Array(t.HEAPU8.buffer,Tt,n).set(e.indices),t.geometry_setIndices32(r,Tt,n)}}return r},updateVertices(e,t,r=0){const n=Rt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,Ct/4),n.geometry_updateVertices(e,Ct,s,r)},release(e){e>0&&Rt().geometry_release(e)},isValid:e=>!(!Pt||e<=0)&&Pt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return Ut.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:bt.Float2},{name:"a_texCoord",type:bt.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ut.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:bt.Float2},{name:"a_texCoord",type:bt.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 o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-r)/(s-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 Ut.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:bt.Float2},{name:"a_texCoord",type:bt.Float2}],indices:new Uint16Array(i)})}};let Ft=null;function It(e){Ft=e}function zt(){Ft&&Bt.isInitialized()&&Bt.shutdown(),Ft=null}function Wt(){if(!Ft)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ft}const Bt={init:(e,t)=>Wt().postprocess_init(e,t),shutdown(){Wt().postprocess_shutdown()},resize(e,t){Wt().postprocess_resize(e,t)},addPass:(e,t)=>Wt().postprocess_addPass(e,t),removePass(e){Wt().postprocess_removePass(e)},setEnabled(e,t){Wt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Wt().postprocess_isPassEnabled(e),setUniform(e,t,r){Wt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Wt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Wt().postprocess_begin()},end(){Wt().postprocess_end()},getPassCount:()=>Wt().postprocess_getPassCount(),isInitialized:()=>!!Ft&&Ft.postprocess_isInitialized(),setBypass(e){Wt().postprocess_setBypass(e)},isBypassed:()=>!Ft||Ft.postprocess_isBypassed(),createBlur:()=>Ve.createShader($t,"#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($t,"#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($t,"#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($t,"#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")},$t="#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 kt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(kt||(kt={}));let Lt=null,Dt=0;function Ot(e){Lt=e,Dt=Lt._malloc(64)}function Ht(){Lt&&Dt&&(Lt._free(Dt),Dt=0),Lt=null}const Nt={init(e,t){Lt?.renderer_init(e,t)},resize(e,t){Lt?.renderer_resize(e,t)},begin(e,t){Lt&&Dt&&(Lt.HEAPF32.set(e,Dt/4),Lt.renderer_begin(Dt,t??0))},flush(){Lt?.renderer_flush()},end(){Lt?.renderer_end()},submitSprites(e){Lt&&Lt.renderer_submitSprites(e._cpp)},submitSpine(e){Lt&&Lt.renderer_submitSpine?.(e._cpp)},setStage(e){Lt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>Lt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){Lt?.renderer_releaseTarget(e)},getTargetTexture:e=>Lt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Lt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){Lt?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>Lt?{drawCalls:Lt.renderer_getDrawCalls(),triangles:Lt.renderer_getTriangles(),sprites:Lt.renderer_getSprites(),spine:Lt.renderer_getSpine?.()??0,meshes:Lt.renderer_getMeshes(),culled:Lt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let jt=null;function Xt(e){jt=e}function Gt(){jt=null}const Vt={enable(){jt?.gl_enableErrorCheck(!0)},disable(){jt?.gl_enableErrorCheck(!1)},check:e=>jt?.gl_checkErrors(e)??0,diagnose(){jt?.renderer_diagnose()}},qt=new Map;function Yt(e,t){qt.set(e,t)}function Kt(e){qt.delete(e)}function Jt(){qt.clear()}class Qt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;Nt.resize(n,s),Bt.isInitialized()&&Bt.getPassCount()>0&&!Bt.isBypassed()&&Bt.resize(n,s),Nt.begin(r),Nt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Nt.submitSpine(t),Nt.flush();const i=qt;if(i.size>0){xt.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)}xt.end();for(const t of e)Kt(t)}Nt.end()}}class Zt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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 Ae,this.resources_=new ce;for(const e of Object.values(ge))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zt}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_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}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 Pe(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,Gt(),Ht(),zt(),At(),Xe(),gt()}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 er(e,t){const r=Zt.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),mt(e),je(e),Mt(e),It(e),Ot(e),Xt(e);const s=new Qt;r.pipeline_=s;let o=d();const i=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}=i(),r=n.entityCount(),a=nr(n,r+1e3);if(a){const e=a.backgroundColor;Nt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,r){const n=e.entityCount(),s=n+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const o=e.getCamera(n);if(!o.isActive)continue;const i=e.getLocalTransform(n),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=nr(e,s);if(r){t=sr(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const n=t*a;c=or(-n,n,-t,t,-o.farPlane,o.farPlane)}else c=ir(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return cr(c,ar(i.position.x,i.position.y,i.position.z))}return rr}(n,e,t),l=(d()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:c,width:e,height:t,elapsed:l})}};return r.addSystemToSchedule(ge.Last,a),r.addPlugin(lt),r.addPlugin(Me),r.addPlugin($e),r}function tr(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 rr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function nr(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function sr(e,t,r,n,s){const o=e*t/r,i=e;switch(n){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function or(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,c=n-r,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+r)/c,i[14]=-(o+s)/l,i[15]=1,i}function ir(e,t,r,n){const s=new Float32Array(16),o=1/Math.tan(e/2),i=r-n;return s[0]=o/t,s[5]=o,s[10]=(n+r)/i,s[11]=-1,s[14]=2*n*r/i,s}function ar(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 cr(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}function lr(e,t){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const s=r.createTexture(t.width,t.height,n,t.pixels.length,1);return e._free(n),s}function ur(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function hr(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function dr(e,t,r,n,s){const o=await async function(e,t,r){const n={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==n[s])continue;try{n[s]=lr(e,await r.loadPixels(s))}catch{n[s]=0}}return n}(t,r,n);!function(e,t,r){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const s=r[e];if(s&&s>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;n.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={};s&&(i=await async function(e,t,r,n){const s={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=n.resolvePath(o),c=n.resolvePath(i);try{const r=n.readText(i),l=a.endsWith(".skel");ur(t,a),l?t.FS.writeFile(a,n.readBinary(o)):t.FS.writeFile(a,n.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;s[o]=u;const h=hr(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const s=d+"/"+h[r];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=lr(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,r,n));const a=function(e,t){const r={},n={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===r[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){r[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ve.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=Ve.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),c=tt(e.world,r);if(function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const s=e.get(t,q);s&&(s.texture=r[n.data.texture]||0,e.insert(t,q,s))}}}(e.world,r,o,c),function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const s=r[n.data.material]||0;if(s)if("Sprite"===n.type){const r=e.get(t,q);r&&(r.material=s,e.insert(t,q,r))}else if("SpineAnimation"===n.type){const r=e.get(t,ee);r&&(r.material=s,e.insert(t,ee,r))}}}}(e.world,r,a,c),s){const n=function(e,t,r,n){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,r,i,c);!function(e,t,r,n){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in n){const s=n[e];r.spine_update(s,i);const o=r.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const n=r.spine_getMeshBatchVertexCount(s,e),o=r.spine_getMeshBatchIndexCount(s,e);if(!n||!o)continue;const i=8*n*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(s,e,c,l,u,h);const d=r.HEAPU32[u>>2],f=r.HEAPU32[h>>2],p=new Float32Array(r.HEAPF32.buffer,c,8*n),_=new Uint16Array(r.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,n,g,o,d,f,0),t._free(m),t._free(g),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,s,n)}}class fr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,s=e.data.atlasPath;n&&(n.endsWith(".skel")?r.add(n):t.add(n)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),n=await r.blob(),s=await createImageBitmap(n),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class pr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=new fr(this.baseUrl_);await r.prefetch(t);let n=null;const s=this.app_.__spineInitPromise;if(s){n=(await s).controller.module}await dr(this.app_,this.app_.wasmModule,t,r,n),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([Y]);for(const n of r){if(e.get(n,Y).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const n=e.getEntitiesWithComponents([K]);for(const s of n){const n=e.get(s,K);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,r=n.designResolution.x/n.designResolution.y;break}}const s=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,G,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,Y,i)}}}const _r={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Nt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Nt.getTargetTexture(r),width:e.width,height:e.height}},release(e){Nt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Nt.releaseRenderTarget(e._handle),_r.create({width:t,height:r,depth:!0})),begin(e,t){Nt.begin(t,e._handle)},end(){Nt.end()},getDepthTexture:e=>Nt.getTargetDepthTexture(e._handle)};let mr=!1;function gr(e){mr=e}function yr(){return mr}function wr(){return!mr}var xr;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=xr=M,console.log(`[ESEngine] Platform: ${xr.name}`);export{Zt as App,ct as AssetPlugin,it as AssetServer,at as Assets,ot as AsyncCache,ke as BlendMode,Y as Camera,K as Canvas,Z as Children,pe as Commands,me as CommandsInstance,bt as DataType,xt as Draw,_e as EntityCommands,Vt as GLDebug,Ut as Geometry,A as INVALID_ENTITY,R as INVALID_TEXTURE,Te as Input,Ee as InputPlugin,Ce as InputState,G as LocalTransform,Ve as Material,et as MaterialLoader,ue as Mut,Q as Parent,Bt as PostProcess,pr as PreviewPlugin,de as Query,fe as QueryInstance,Qt as RenderPipeline,kt as RenderStage,_r as RenderTexture,Nt as Renderer,oe as Res,ie as ResMut,ge as Schedule,Ze as ShaderSources,ee as SpineAnimation,q as Sprite,Pe as SystemRunner,Ie as Text,Re as TextAlign,Fe as TextOverflow,Be as TextPlugin,ze as TextRenderer,Ue as TextVerticalAlign,le as Time,We as UIRect,J as Velocity,fr as WebAssetProvider,Ae as World,V as WorldTransform,Se as addStartupSystem,ve as addSystem,be as addSystemToSchedule,lt as assetPlugin,Jt as clearDrawCallbacks,H as clearUserComponents,z as color,er as createWebApp,L as defineComponent,se as defineResource,we as defineSystem,D as defineTag,tr as flushPendingSystems,re as getComponentDefaults,t as getPlatform,n as getPlatformType,O as getUserComponent,mt as initDrawAPI,Xt as initGLDebugAPI,Mt as initGeometryAPI,je as initMaterialAPI,It as initPostProcessAPI,Ot as initRendererAPI,Me as inputPlugin,X as isBuiltinComponent,yr as isEditor,r as isPlatformInitialized,wr as isRuntime,Le as isTextureRef,s as isWeChat,o as isWeb,nt as loadComponent,dr as loadRuntimeScene,tt as loadSceneData,rt as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,W as quat,Yt as registerDrawCallback,ut as registerEmbeddedAssets,Qe as registerMaterialCallback,gr as setEditorMode,gt as shutdownDrawAPI,Gt as shutdownGLDebugAPI,At as shutdownGeometryAPI,Xe as shutdownMaterialAPI,zt as shutdownPostProcessAPI,Ht as shutdownRendererAPI,$e as textPlugin,Kt as unregisterDrawCallback,st as updateCameraAspectRatio,U as vec2,F as vec3,I as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,T as wxLoadImagePixels,g as wxReadFile,y as wxReadTextFile,v as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 13270506e..4a4013c2c 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -996,7 +996,9 @@ declare class AssetServer {private materialLoader_;private canvas_;private ctx_;+ private embedded_;constructor(module: ESEngineModule);+ registerEmbeddedAssets(assets: Record<string, string>): void;/*** Load texture with vertical flip (for Sprite/UI).* OpenGL UV origin is bottom-left, so standard images need flipping.@@ -1035,6 +1037,10 @@ declare class AssetServer {private unpremultiplyAlpha;private loadShaderInternal;private parseEsShader;+ private decodeDataUrlText;+ private decodeDataUrlBinary;+ private isLocalPath;+ private toLocalPath;private fetchJson;private fetchText;private fetchBinary;@@ -1063,6 +1069,13 @@ declare class AssetPlugin implements Plugin {}declare const assetPlugin: AssetPlugin;+/**+ * @file index.ts+ * @brief Asset module exports+ */++declare function registerEmbeddedAssets(app: App, assets: Record<string, string>): void;+/*** @file SpineModuleLoader.ts* @brief Loads and initializes the standalone Spine WASM module@@ -1236,6 +1249,10 @@ interface PlatformAdapter {* High-resolution timestamp in milliseconds*/now(): number;+ /**+ * Create an Image element for loading textures+ */+ createImage(): HTMLImageElement;/*** Bind input events (keyboard, pointer, wheel)* @param callbacks - Event callbacks@@ -1676,5 +1693,5 @@ declare const GLDebug: {diagnose(): void;};-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 1aca6bfaa..f0b89ed59 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 o(){return"web"===e?.name}async function i(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()}bindInputEvents(e,t){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerDown(0,r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerMove(r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=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 P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const n=P(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),R(e,t,!1),s}function T(e){const t=P(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),R(e,{},!0),r}function b(e){return P().get(e)}function M(){P().clear()}function R(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function E(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const U=E("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=E("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=E("Sprite",{texture:_,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=E("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),B=E("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),k=E("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),$=E("Parent",{entity:0}),L=E("Children",{entities:[]}),D=E("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:U,WorldTransform:F,Sprite:z,Camera:I,Canvas:B,Velocity:k,Parent:$,Children:L,SpineAnimation:D};function H(e){const t=W[e];if(t)return{...t._default};const n=b(e);return n?{...n._default}:null}let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function j(e){return{_type:"res",_resource:e}}function X(e){return{_type:"res_mut",_resource:e}}class V{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 G{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 V(this.get(e),t=>this.set(e,t))}}const Y=N({delta:0,elapsed:0,frameCount:0},"Time");function K(e){return{_type:"mut",_component:e}}function q(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)=>{q(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 q(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)),o=[...s,...n],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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=A(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 oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ie(e){oe().push({schedule:ne.Update,system:e})}function ae(e){oe().push({schedule:ne.Startup,system:e})}function ce(e,t){oe().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=N(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const n=new ue;e.insertResource(he,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,r){n.mouseX=t,n.mouseY=r,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(ne.First,se([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class pe{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 A(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(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 _e,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(_e||(_e={})),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=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:_e.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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===ge.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.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;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(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===ge.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case me.Top:x=u;break;case me.Middle:x=(p-w)/2;break;case me.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case _e.Left:r=u;break;case _e.Center:r=f/2;break;case _e.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,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),T=this.module.getResourceManager(),b=this.module._malloc(C.length);this.module.HEAPU8.set(C,b);const M=T.createTexture(f,p,b,C.length,1);return this.module._free(b),{textureHandle:M,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const 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 _e.Left:return"left";case _e.Center:return"center";case _e.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 o=t*r,i=(n-1-t)*r;s.set(e.subarray(o,o+r),i)}return s}}const xe=C("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:_,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,o=n.renderForEntity(t,e,s),i=r.get(t,z);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},r.insert(t,z,i),e.dirty=!1}}))}}const Se=new ve;var Pe;function Ce(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"}(Pe||(Pe={}));let Te=null,be=null,Me=1;const Re=new Map;function Ee(e){Te=e,be=e.getResourceManager(),$e()}function Ae(){0!==Ie&&Te&&(Te._free(Ie),Ie=0),Re.clear(),Me=1,ze=!1,be=null,Te=null}function Ue(){if(!be)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return be}const Fe={createShader:(e,t)=>Ue().createShader(e,t),releaseShader(e){e>0&&Ue().releaseShader(e)},create(e){const t=Me++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pe.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??Pe.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??Pe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Re.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Me++,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,Ie=0;const Be=4096;function ke(e){const t=(0===Ie&&Te&&(Ie=Te._malloc(Be)),Ie);if(0===t||!Te)return{ptr:0,count:0};let n=0,r=0;const s=Te.HEAPU8,o=Te.HEAPU32,i=Te.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);o[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]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function $e(){if(!Te||ze)return;Te.materialDataProvider=(e,t,n,r,s)=>{const o=Re.get(e);if(!o)return Te.HEAPU32[t>>2]=0,Te.HEAPU32[n>>2]=0,Te.HEAPU32[r>>2]=0,void(Te.HEAPU32[s>>2]=0);Te.HEAPU32[t>>2]=o.shader,Te.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=ke(o.uniforms);Te.HEAPU32[r>>2]=i,Te.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"};class De{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&&(Fe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Fe.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),o=await this.shaderLoader_.load(s);return{handle:Fe.createFromAsset(r,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function We(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)Oe(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 He(e,t,n){const r=new Map,s=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t);for(const r of i.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,o.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,o=e.atlasPath;if(t&&o){const e=await s.loadSpine(t,o,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}}Oe(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=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Oe(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,U,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,I,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=b(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Ne(e,t){const n=e.getEntitiesWithComponents([I]);for(const r of n){const n=e.get(r,I);n&&(n.aspectRatio=t,e.insert(r,I,n))}}class je{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 Xe{constructor(e){this.textureCache_=new je,this.shaderCache_=new je,this.jsonCache_=new je,this.textCache_=new je,this.binaryCache_=new je,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 De(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),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};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("/")),c=this.parseAtlasTextures(i);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 He(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 o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;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),o=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,n,a,o.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 Fe.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 i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(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 Ve=N(null,"Assets");class Ge{build(e){const t=e.wasmModule;t?e.insertResource(Ve,new Xe(t)):console.warn("AssetPlugin: No WASM module available")}}const Ye=new Ge;let Ke=null,qe=0,Je=0,Qe=0;const Ze=new Float32Array(256);function et(e){Ke=e,qe=Ke._malloc(64),Je=Ke._malloc(64),Qe=Ke._malloc(1024)}function tt(){Ke&&(qe&&(Ke._free(qe),qe=0),Je&&(Ke._free(Je),Je=0),Qe&&(Ke._free(Qe),Qe=0)),Ke=null}function nt(){if(!Ke)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ke}const rt={x:1,y:1,z:1,w:1},st={begin(e){const t=nt();t.HEAPF32.set(e,qe/4),t.draw_begin(qe)},end(){nt().draw_end()},line(e,t,n,r=1){nt().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){nt().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){nt().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){nt().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){nt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=rt){nt().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=rt){nt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){nt().draw_setLayer(e)},setDepth(e){nt().draw_setDepth(e)},getDrawCallCount:()=>Ke?Ke.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ke?Ke.draw_getPrimitiveCount():0,setBlendMode(e){nt().draw_setBlendMode(e)},setDepthTest(e){nt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=nt();r.HEAPF32.set(n,Je/4),r.draw_mesh(e,t,Je)},drawMeshWithMaterial(e,t,n){const r=nt(),s=Fe.get(t);if(!s)return;if(st.setBlendMode(s.blendMode),st.setDepthTest(s.depthTest),0===s.uniforms.size)return void st.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Je/4);let o=0,i=0;for(const[e,t]of s.uniforms){const n=it(e);if(!(n<0)){if(Ce(t))Ze[o++]=10,Ze[o++]=n,Ze[o++]=t.slot??i++,Ze[o++]=t.textureId;else if("number"==typeof t)Ze[o++]=1,Ze[o++]=n,Ze[o++]=t;else if(Array.isArray(t)){Ze[o++]=t.length,Ze[o++]=n;for(let e=0;e<t.length;e++)Ze[o++]=t[e]}else"w"in t?(Ze[o++]=4,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z,Ze[o++]=t.w):"z"in t?(Ze[o++]=3,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z):(Ze[o++]=2,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(Ze.subarray(0,o),Qe/4),r.draw_meshWithUniforms(e,s.shader,Je,Qe,o)):r.draw_mesh(e,s.shader,Je)}},ot={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function it(e){return ot[e]??-1}var at;!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"}(at||(at={}));let ct=null,lt=0,ut=0,ht=0;function dt(e){ct=e,lt=ct._malloc(262144),ut=ct._malloc(65536),ht=ct._malloc(256)}function ft(){ct&&(lt&&ct._free(lt),ut&&ct._free(ut),ht&&ct._free(ht),lt=0,ut=0,ht=0),ct=null}function pt(){if(!ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ct}const _t={create(e){const t=pt(),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,lt/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ht,s).set(o),t.geometry_init(n,lt,r,ht,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,ut,r).set(e.indices),t.geometry_setIndices16(n,ut,r)}else{new Uint32Array(t.HEAPU8.buffer,ut,r).set(e.indices),t.geometry_setIndices32(n,ut,r)}}return n},updateVertices(e,t,n=0){const r=pt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,lt/4),r.geometry_updateVertices(e,lt,s,n)},release(e){e>0&&pt().geometry_release(e)},isValid:e=>!(!ct||e<=0)&&ct.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return _t.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:at.Float2},{name:"a_texCoord",type:at.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return _t.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.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 o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-n)/(s-n);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 _t.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.Float2}],indices:new Uint16Array(i)})}};let mt=null;function gt(e){mt=e}function yt(){mt&&xt.isInitialized()&&xt.shutdown(),mt=null}function wt(){if(!mt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return mt}const xt={init:(e,t)=>wt().postprocess_init(e,t),shutdown(){wt().postprocess_shutdown()},resize(e,t){wt().postprocess_resize(e,t)},addPass:(e,t)=>wt().postprocess_addPass(e,t),removePass(e){wt().postprocess_removePass(e)},setEnabled(e,t){wt().postprocess_setPassEnabled(e,t)},isEnabled:e=>wt().postprocess_isPassEnabled(e),setUniform(e,t,n){wt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){wt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){wt().postprocess_begin()},end(){wt().postprocess_end()},getPassCount:()=>wt().postprocess_getPassCount(),isInitialized:()=>!!mt&&mt.postprocess_isInitialized(),setBypass(e){wt().postprocess_setBypass(e)},isBypassed:()=>!mt||mt.postprocess_isBypassed(),createBlur:()=>Fe.createShader(vt,"#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:()=>Fe.createShader(vt,"#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:()=>Fe.createShader(vt,"#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:()=>Fe.createShader(vt,"#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")},vt="#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 St;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(St||(St={}));let Pt=null,Ct=0;function Tt(e){Pt=e,Ct=Pt._malloc(64)}function bt(){Pt&&Ct&&(Pt._free(Ct),Ct=0),Pt=null}const Mt={init(e,t){Pt?.renderer_init(e,t)},resize(e,t){Pt?.renderer_resize(e,t)},begin(e,t){Pt&&Ct&&(Pt.HEAPF32.set(e,Ct/4),Pt.renderer_begin(Ct,t??0))},flush(){Pt?.renderer_flush()},end(){Pt?.renderer_end()},submitSprites(e){Pt&&Pt.renderer_submitSprites(e._cpp)},submitSpine(e){Pt&&Pt.renderer_submitSpine?.(e._cpp)},setStage(e){Pt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Pt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Pt?.renderer_releaseTarget(e)},getTargetTexture:e=>Pt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Pt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Pt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>Pt?{drawCalls:Pt.renderer_getDrawCalls(),triangles:Pt.renderer_getTriangles(),sprites:Pt.renderer_getSprites(),spine:Pt.renderer_getSpine?.()??0,meshes:Pt.renderer_getMeshes(),culled:Pt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Rt=null;function Et(e){Rt=e}function At(){Rt=null}const Ut={enable(){Rt?.gl_enableErrorCheck(!0)},disable(){Rt?.gl_enableErrorCheck(!1)},check:e=>Rt?.gl_checkErrors(e)??0,diagnose(){Rt?.renderer_diagnose()}},Ft=new Map;function zt(e,t){Ft.set(e,t)}function It(e){Ft.delete(e)}function Bt(){Ft.clear()}class kt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:o}=e;Mt.resize(r,s),xt.isInitialized()&&xt.getPassCount()>0&&!xt.isBypassed()&&xt.resize(r,s),Mt.begin(n),Mt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Mt.submitSpine(t),Mt.flush();const i=Ft;if(i.size>0){st.begin(n);const e=[];for(const[t,n]of i.entries())try{n(o)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}st.end();for(const t of e)It(t)}Mt.end()}}class $t{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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 pe,this.resources_=new G;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new $t}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_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}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,At(),bt(),yt(),ft(),Ae(),tt()}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 Lt(e,t){const n=$t.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),et(e),Ee(e),dt(e),gt(e),Tt(e),Et(e);const s=new kt;n.pipeline_=s;let o=d();const i=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}=i(),n=r.entityCount(),a=Ht(r,n+1e3);if(a){const e=a.backgroundColor;Mt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const r=e.entityCount(),s=r+1e3;for(let r=0;r<s;r++){if(!e.valid(r)||!e.hasCamera(r)||!e.hasLocalTransform(r))continue;const o=e.getCamera(r);if(!o.isActive)continue;const i=e.getLocalTransform(r),a=t/n;let c;if(1===o.projectionType){let t=o.orthoSize;const n=Ht(e,s);if(n){t=Ot(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const r=t*a;c=Nt(-r,r,-t,t,-o.farPlane,o.farPlane)}else c=jt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Vt(c,Xt(i.position.x,i.position.y,i.position.z))}return Wt}(r,e,t),l=(d()-o)/1e3;s.render({registry:{_cpp:r},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(Ye),n.addPlugin(fe),n.addPlugin(Se),n}function Dt(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 Wt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ht(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Ot(e,t,n,r,s){const o=e*t/n,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Nt(e,t,n,r,s,o){const i=new Float32Array(16),a=t-e,c=r-n,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(r+n)/c,i[14]=-(o+s)/l,i[15]=1,i}function jt(e,t,n,r){const s=new Float32Array(16),o=1/Math.tan(e/2),i=n-r;return s[0]=o/t,s[5]=o,s[10]=(r+n)/i,s[11]=-1,s[14]=2*r*n/i,s}function Xt(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 Vt(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}function Gt(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function Yt(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function Kt(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function qt(e,t,n,r,s){const o=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=Gt(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,o);let i={};s&&(i=await async function(e,t,n,r){const s={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,i=n.data.atlasPath;if(!o||!i)continue;const a=r.resolvePath(o),c=r.resolvePath(i);try{const n=r.readText(i),l=a.endsWith(".skel");Yt(t,a),l?t.FS.writeFile(a,r.readBinary(o)):t.FS.writeFile(a,r.readText(o));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;s[o]=u;const h=Kt(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const s=d+"/"+h[n];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Gt(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,n,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,n,r));const a=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=Fe.createShader(e.vertexSource,e.fragmentSource),r[o]=i),n[s]=Fe.createFromAsset(e,i)}catch{n[s]=0}}return n}(n,r),c=We(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,z);s&&(s.texture=n[r.data.texture]||0,e.insert(t,z,s))}}}(e.world,n,o,c),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,z);n&&(n.material=s,e.insert(t,z,n))}else if("SpineAnimation"===r.type){const n=e.get(t,D);n&&(n.material=s,e.insert(t,D,n))}}}}(e.world,n,a,c),s){const r=function(e,t,n,r){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=r.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,n,i,c);!function(e,t,n,r){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in r){const s=r[e];n.spine_update(s,i);const o=n.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const r=n.spine_getMeshBatchVertexCount(s,e),o=n.spine_getMeshBatchIndexCount(s,e);if(!r||!o)continue;const i=8*r*4,a=2*o,c=n._malloc(i),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(s,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,r,g,o,d,f,0),t._free(m),t._free(g),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,s,r)}}class Jt{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),r=await n.blob(),s=await createImageBitmap(r),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Qt{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Jt(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.module}await qt(this.app_,this.app_.wasmModule,t,n,r),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([I]);for(const r of n){if(e.get(r,I).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([B]);for(const s of r){const r=e.get(s,B);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,U,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,I,i)}}}const Zt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Mt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Mt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Mt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Mt.releaseRenderTarget(e._handle),Zt.create({width:t,height:n,depth:!0})),begin(e,t){Mt.begin(t,e._handle)},end(){Mt.end()},getDepthTexture:e=>Mt.getTargetDepthTexture(e._handle)};let en=!1;function tn(e){en=e}function nn(){return en}function rn(){return!en}var sn;e=sn=f,console.log(`[ESEngine] Platform: ${sn.name}`);export{$t as App,Ge as AssetPlugin,Xe as AssetServer,Ve as Assets,je as AsyncCache,Pe as BlendMode,I as Camera,B as Canvas,L as Children,Z as Commands,te as CommandsInstance,at as DataType,st as Draw,ee as EntityCommands,Ut as GLDebug,_t as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,U as LocalTransform,Fe as Material,De as MaterialLoader,K as Mut,$ as Parent,xt as PostProcess,Qt as PreviewPlugin,J as Query,Q as QueryInstance,kt as RenderPipeline,St as RenderStage,Zt as RenderTexture,Mt as Renderer,j as Res,X as ResMut,ne as Schedule,Le as ShaderSources,D as SpineAnimation,z as Sprite,le as SystemRunner,ye as Text,_e as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,k as Velocity,Jt as WebAssetProvider,pe as World,F as WorldTransform,ae as addStartupSystem,ie as addSystem,ce as addSystemToSchedule,Ye as assetPlugin,Bt as clearDrawCallbacks,M as clearUserComponents,w as color,Lt as createWebApp,C as defineComponent,N as defineResource,se as defineSystem,T as defineTag,Dt as flushPendingSystems,H as getComponentDefaults,t as getPlatform,r as getPlatformType,b as getUserComponent,et as initDrawAPI,Et as initGLDebugAPI,dt as initGeometryAPI,Ee as initMaterialAPI,gt as initPostProcessAPI,Tt as initRendererAPI,fe as inputPlugin,A as isBuiltinComponent,nn as isEditor,n as isPlatformInitialized,rn as isRuntime,Ce as isTextureRef,s as isWeChat,o as isWeb,Oe as loadComponent,qt as loadRuntimeScene,We as loadSceneData,He as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,zt as registerDrawCallback,$e as registerMaterialCallback,tn as setEditorMode,tt as shutdownDrawAPI,At as shutdownGLDebugAPI,ft as shutdownGeometryAPI,Ae as shutdownMaterialAPI,yt as shutdownPostProcessAPI,bt as shutdownRendererAPI,Se as textPlugin,It as unregisterDrawCallback,Ne 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 o(){return"web"===e?.name}async function i(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}}createImage(){return new Image}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()}bindInputEvents(e,t){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerDown(0,r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerMove(r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=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 P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const n=P(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),R(e,t,!1),s}function b(e){const t=P(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),R(e,{},!0),r}function T(e){return P().get(e)}function M(){P().clear()}function R(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function E(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const U=E("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=E("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=E("Sprite",{texture:_,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=E("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),B=E("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),k=E("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),L=E("Parent",{entity:0}),$=E("Children",{entities:[]}),D=E("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:U,WorldTransform:F,Sprite:z,Camera:I,Canvas:B,Velocity:k,Parent:L,Children:$,SpineAnimation:D};function O(e){const t=W[e];if(t)return{...t._default};const n=T(e);return n?{...n._default}:null}let H=0;function N(e,t){const n=++H;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function j(e){return{_type:"res",_resource:e}}function X(e){return{_type:"res_mut",_resource:e}}class V{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 G{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 V(this.get(e),t=>this.set(e,t))}}const Y=N({delta:0,elapsed:0,frameCount:0},"Time");function K(e){return{_type:"mut",_component:e}}function q(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)=>{q(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 q(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)),o=[...s,...n],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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=A(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 oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ie(e){oe().push({schedule:ne.Update,system:e})}function ae(e){oe().push({schedule:ne.Startup,system:e})}function ce(e,t){oe().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=N(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const n=new ue;e.insertResource(he,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,r){n.mouseX=t,n.mouseY=r,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(ne.First,se([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class pe{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 A(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(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 _e,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(_e||(_e={})),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=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:_e.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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===ge.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.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;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(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===ge.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case me.Top:x=u;break;case me.Middle:x=(p-w)/2;break;case me.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case _e.Left:r=u;break;case _e.Center:r=f/2;break;case _e.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,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),b=this.module.getResourceManager(),T=this.module._malloc(C.length);this.module.HEAPU8.set(C,T);const M=b.createTexture(f,p,T,C.length,1);return this.module._free(T),{textureHandle:M,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const 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 _e.Left:return"left";case _e.Center:return"center";case _e.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 o=t*r,i=(n-1-t)*r;s.set(e.subarray(o,o+r),i)}return s}}const xe=C("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:_,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,o=n.renderForEntity(t,e,s),i=r.get(t,z);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},r.insert(t,z,i),e.dirty=!1}}))}}const Se=new ve;var Pe;function Ce(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"}(Pe||(Pe={}));let be=null,Te=null,Me=1;const Re=new Map;function Ee(e){be=e,Te=e.getResourceManager(),Le()}function Ae(){0!==Ie&&be&&(be._free(Ie),Ie=0),Re.clear(),Me=1,ze=!1,Te=null,be=null}function Ue(){if(!Te)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Te}const Fe={createShader:(e,t)=>Ue().createShader(e,t),releaseShader(e){e>0&&Ue().releaseShader(e)},create(e){const t=Me++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pe.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??Pe.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??Pe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Re.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Me++,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,Ie=0;const Be=4096;function ke(e){const t=(0===Ie&&be&&(Ie=be._malloc(Be)),Ie);if(0===t||!be)return{ptr:0,count:0};let n=0,r=0;const s=be.HEAPU8,o=be.HEAPU32,i=be.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);o[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]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function Le(){if(!be||ze)return;be.materialDataProvider=(e,t,n,r,s)=>{const o=Re.get(e);if(!o)return be.HEAPU32[t>>2]=0,be.HEAPU32[n>>2]=0,be.HEAPU32[r>>2]=0,void(be.HEAPU32[s>>2]=0);be.HEAPU32[t>>2]=o.shader,be.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=ke(o.uniforms);be.HEAPU32[r>>2]=i,be.HEAPU32[s>>2]=a},ze=!0}const $e={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class De{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&&(Fe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Fe.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),o=await this.shaderLoader_.load(s);return{handle:Fe.createFromAsset(r,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function We(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)He(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 Oe(e,t,n){const r=new Map,s=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t);for(const r of i.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,o.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,o=e.atlasPath;if(t&&o){const e=await s.loadSpine(t,o,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}}He(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=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function He(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,U,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,I,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=T(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Ne(e,t){const n=e.getEntitiesWithComponents([I]);for(const r of n){const n=e.get(r,I);n&&(n.aspectRatio=t,e.insert(r,I,n))}}class je{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 Xe{constructor(e){this.textureCache_=new je,this.shaderCache_=new je,this.jsonCache_=new je,this.textCache_=new je,this.binaryCache_=new je,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,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 De(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}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),o=await this.fetchText(s);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${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 c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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 Oe(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){const n=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}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 o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;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),o=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,n,a,o.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){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return Fe.createShader(r,s)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const 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 Ve=N(null,"Assets");class Ge{build(e){const t=e.wasmModule;t?e.insertResource(Ve,new Xe(t)):console.warn("AssetPlugin: No WASM module available")}}const Ye=new Ge;function Ke(e,t){const n=e.getResource(Ve);n&&n.registerEmbeddedAssets(t)}let qe=null,Je=0,Qe=0,Ze=0;const et=new Float32Array(256);function tt(e){qe=e,Je=qe._malloc(64),Qe=qe._malloc(64),Ze=qe._malloc(1024)}function nt(){qe&&(Je&&(qe._free(Je),Je=0),Qe&&(qe._free(Qe),Qe=0),Ze&&(qe._free(Ze),Ze=0)),qe=null}function rt(){if(!qe)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return qe}const st={x:1,y:1,z:1,w:1},ot={begin(e){const t=rt();t.HEAPF32.set(e,Je/4),t.draw_begin(Je)},end(){rt().draw_end()},line(e,t,n,r=1){rt().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){rt().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){rt().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){rt().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){rt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=st){rt().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=st){rt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){rt().draw_setLayer(e)},setDepth(e){rt().draw_setDepth(e)},getDrawCallCount:()=>qe?qe.draw_getDrawCallCount():0,getPrimitiveCount:()=>qe?qe.draw_getPrimitiveCount():0,setBlendMode(e){rt().draw_setBlendMode(e)},setDepthTest(e){rt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=rt();r.HEAPF32.set(n,Qe/4),r.draw_mesh(e,t,Qe)},drawMeshWithMaterial(e,t,n){const r=rt(),s=Fe.get(t);if(!s)return;if(ot.setBlendMode(s.blendMode),ot.setDepthTest(s.depthTest),0===s.uniforms.size)return void ot.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Qe/4);let o=0,i=0;for(const[e,t]of s.uniforms){const n=at(e);if(!(n<0)){if(Ce(t))et[o++]=10,et[o++]=n,et[o++]=t.slot??i++,et[o++]=t.textureId;else if("number"==typeof t)et[o++]=1,et[o++]=n,et[o++]=t;else if(Array.isArray(t)){et[o++]=t.length,et[o++]=n;for(let e=0;e<t.length;e++)et[o++]=t[e]}else"w"in t?(et[o++]=4,et[o++]=n,et[o++]=t.x,et[o++]=t.y,et[o++]=t.z,et[o++]=t.w):"z"in t?(et[o++]=3,et[o++]=n,et[o++]=t.x,et[o++]=t.y,et[o++]=t.z):(et[o++]=2,et[o++]=n,et[o++]=t.x,et[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(et.subarray(0,o),Ze/4),r.draw_meshWithUniforms(e,s.shader,Qe,Ze,o)):r.draw_mesh(e,s.shader,Qe)}},it={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function at(e){return it[e]??-1}var ct;!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"}(ct||(ct={}));let lt=null,ut=0,ht=0,dt=0;function ft(e){lt=e,ut=lt._malloc(262144),ht=lt._malloc(65536),dt=lt._malloc(256)}function pt(){lt&&(ut&<._free(ut),ht&<._free(ht),dt&<._free(dt),ut=0,ht=0,dt=0),lt=null}function _t(){if(!lt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return lt}const mt={create(e){const t=_t(),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,ut/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,dt,s).set(o),t.geometry_init(n,ut,r,dt,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,ht,r).set(e.indices),t.geometry_setIndices16(n,ht,r)}else{new Uint32Array(t.HEAPU8.buffer,ht,r).set(e.indices),t.geometry_setIndices32(n,ht,r)}}return n},updateVertices(e,t,n=0){const r=_t(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,ut/4),r.geometry_updateVertices(e,ut,s,n)},release(e){e>0&&_t().geometry_release(e)},isValid:e=>!(!lt||e<=0)&<.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return mt.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:ct.Float2},{name:"a_texCoord",type:ct.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return mt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ct.Float2},{name:"a_texCoord",type:ct.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 o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-n)/(s-n);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 mt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:ct.Float2},{name:"a_texCoord",type:ct.Float2}],indices:new Uint16Array(i)})}};let gt=null;function yt(e){gt=e}function wt(){gt&&vt.isInitialized()&&vt.shutdown(),gt=null}function xt(){if(!gt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gt}const vt={init:(e,t)=>xt().postprocess_init(e,t),shutdown(){xt().postprocess_shutdown()},resize(e,t){xt().postprocess_resize(e,t)},addPass:(e,t)=>xt().postprocess_addPass(e,t),removePass(e){xt().postprocess_removePass(e)},setEnabled(e,t){xt().postprocess_setPassEnabled(e,t)},isEnabled:e=>xt().postprocess_isPassEnabled(e),setUniform(e,t,n){xt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){xt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){xt().postprocess_begin()},end(){xt().postprocess_end()},getPassCount:()=>xt().postprocess_getPassCount(),isInitialized:()=>!!gt&>.postprocess_isInitialized(),setBypass(e){xt().postprocess_setBypass(e)},isBypassed:()=>!gt||gt.postprocess_isBypassed(),createBlur:()=>Fe.createShader(St,"#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:()=>Fe.createShader(St,"#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:()=>Fe.createShader(St,"#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:()=>Fe.createShader(St,"#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")},St="#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 Pt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Pt||(Pt={}));let Ct=null,bt=0;function Tt(e){Ct=e,bt=Ct._malloc(64)}function Mt(){Ct&&bt&&(Ct._free(bt),bt=0),Ct=null}const Rt={init(e,t){Ct?.renderer_init(e,t)},resize(e,t){Ct?.renderer_resize(e,t)},begin(e,t){Ct&&bt&&(Ct.HEAPF32.set(e,bt/4),Ct.renderer_begin(bt,t??0))},flush(){Ct?.renderer_flush()},end(){Ct?.renderer_end()},submitSprites(e){Ct&&Ct.renderer_submitSprites(e._cpp)},submitSpine(e){Ct&&Ct.renderer_submitSpine?.(e._cpp)},setStage(e){Ct?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Ct?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Ct?.renderer_releaseTarget(e)},getTargetTexture:e=>Ct?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ct?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Ct?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>Ct?{drawCalls:Ct.renderer_getDrawCalls(),triangles:Ct.renderer_getTriangles(),sprites:Ct.renderer_getSprites(),spine:Ct.renderer_getSpine?.()??0,meshes:Ct.renderer_getMeshes(),culled:Ct.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Et=null;function At(e){Et=e}function Ut(){Et=null}const Ft={enable(){Et?.gl_enableErrorCheck(!0)},disable(){Et?.gl_enableErrorCheck(!1)},check:e=>Et?.gl_checkErrors(e)??0,diagnose(){Et?.renderer_diagnose()}},zt=new Map;function It(e,t){zt.set(e,t)}function Bt(e){zt.delete(e)}function kt(){zt.clear()}class Lt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:o}=e;Rt.resize(r,s),vt.isInitialized()&&vt.getPassCount()>0&&!vt.isBypassed()&&vt.resize(r,s),Rt.begin(n),Rt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Rt.submitSpine(t),Rt.flush();const i=zt;if(i.size>0){ot.begin(n);const e=[];for(const[t,n]of i.entries())try{n(o)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}ot.end();for(const t of e)Bt(t)}Rt.end()}}class $t{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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 pe,this.resources_=new G;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new $t}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_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}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,Ut(),Mt(),wt(),pt(),Ae(),nt()}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 Dt(e,t){const n=$t.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tt(e),Ee(e),ft(e),yt(e),Tt(e),At(e);const s=new Lt;n.pipeline_=s;let o=d();const i=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}=i(),n=r.entityCount(),a=Ht(r,n+1e3);if(a){const e=a.backgroundColor;Rt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const r=e.entityCount(),s=r+1e3;for(let r=0;r<s;r++){if(!e.valid(r)||!e.hasCamera(r)||!e.hasLocalTransform(r))continue;const o=e.getCamera(r);if(!o.isActive)continue;const i=e.getLocalTransform(r),a=t/n;let c;if(1===o.projectionType){let t=o.orthoSize;const n=Ht(e,s);if(n){t=Nt(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const r=t*a;c=jt(-r,r,-t,t,-o.farPlane,o.farPlane)}else c=Xt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Gt(c,Vt(i.position.x,i.position.y,i.position.z))}return Ot}(r,e,t),l=(d()-o)/1e3;s.render({registry:{_cpp:r},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(Ye),n.addPlugin(fe),n.addPlugin(Se),n}function Wt(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 Ot=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ht(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Nt(e,t,n,r,s){const o=e*t/n,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function jt(e,t,n,r,s,o){const i=new Float32Array(16),a=t-e,c=r-n,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(r+n)/c,i[14]=-(o+s)/l,i[15]=1,i}function Xt(e,t,n,r){const s=new Float32Array(16),o=1/Math.tan(e/2),i=n-r;return s[0]=o/t,s[5]=o,s[10]=(r+n)/i,s[11]=-1,s[14]=2*r*n/i,s}function Vt(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 Gt(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}function Yt(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function Kt(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function qt(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function Jt(e,t,n,r,s){const o=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=Yt(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,o);let i={};s&&(i=await async function(e,t,n,r){const s={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,i=n.data.atlasPath;if(!o||!i)continue;const a=r.resolvePath(o),c=r.resolvePath(i);try{const n=r.readText(i),l=a.endsWith(".skel");Kt(t,a),l?t.FS.writeFile(a,r.readBinary(o)):t.FS.writeFile(a,r.readText(o));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;s[o]=u;const h=qt(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const s=d+"/"+h[n];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Yt(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,n,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,n,r));const a=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=Fe.createShader(e.vertexSource,e.fragmentSource),r[o]=i),n[s]=Fe.createFromAsset(e,i)}catch{n[s]=0}}return n}(n,r),c=We(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,z);s&&(s.texture=n[r.data.texture]||0,e.insert(t,z,s))}}}(e.world,n,o,c),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,z);n&&(n.material=s,e.insert(t,z,n))}else if("SpineAnimation"===r.type){const n=e.get(t,D);n&&(n.material=s,e.insert(t,D,n))}}}}(e.world,n,a,c),s){const r=function(e,t,n,r){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=r.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,n,i,c);!function(e,t,n,r){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in r){const s=r[e];n.spine_update(s,i);const o=n.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const r=n.spine_getMeshBatchVertexCount(s,e),o=n.spine_getMeshBatchIndexCount(s,e);if(!r||!o)continue;const i=8*r*4,a=2*o,c=n._malloc(i),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(s,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,r,g,o,d,f,0),t._free(m),t._free(g),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,s,r)}}class Qt{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),r=await n.blob(),s=await createImageBitmap(r),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Zt{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Qt(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.module}await Jt(this.app_,this.app_.wasmModule,t,n,r),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([I]);for(const r of n){if(e.get(r,I).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([B]);for(const s of r){const r=e.get(s,B);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,U,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,I,i)}}}const en={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Rt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Rt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Rt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Rt.releaseRenderTarget(e._handle),en.create({width:t,height:n,depth:!0})),begin(e,t){Rt.begin(t,e._handle)},end(){Rt.end()},getDepthTexture:e=>Rt.getTargetDepthTexture(e._handle)};let tn=!1;function nn(e){tn=e}function rn(){return tn}function sn(){return!tn}var on;e=on=f,console.log(`[ESEngine] Platform: ${on.name}`);export{$t as App,Ge as AssetPlugin,Xe as AssetServer,Ve as Assets,je as AsyncCache,Pe as BlendMode,I as Camera,B as Canvas,$ as Children,Z as Commands,te as CommandsInstance,ct as DataType,ot as Draw,ee as EntityCommands,Ft as GLDebug,mt as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,U as LocalTransform,Fe as Material,De as MaterialLoader,K as Mut,L as Parent,vt as PostProcess,Zt as PreviewPlugin,J as Query,Q as QueryInstance,Lt as RenderPipeline,Pt as RenderStage,en as RenderTexture,Rt as Renderer,j as Res,X as ResMut,ne as Schedule,$e as ShaderSources,D as SpineAnimation,z as Sprite,le as SystemRunner,ye as Text,_e as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,k as Velocity,Qt as WebAssetProvider,pe as World,F as WorldTransform,ae as addStartupSystem,ie as addSystem,ce as addSystemToSchedule,Ye as assetPlugin,kt as clearDrawCallbacks,M as clearUserComponents,w as color,Dt as createWebApp,C as defineComponent,N as defineResource,se as defineSystem,b as defineTag,Wt as flushPendingSystems,O as getComponentDefaults,t as getPlatform,r as getPlatformType,T as getUserComponent,tt as initDrawAPI,At as initGLDebugAPI,ft as initGeometryAPI,Ee as initMaterialAPI,yt as initPostProcessAPI,Tt as initRendererAPI,fe as inputPlugin,A as isBuiltinComponent,rn as isEditor,n as isPlatformInitialized,sn as isRuntime,Ce as isTextureRef,s as isWeChat,o as isWeb,He as loadComponent,Jt as loadRuntimeScene,We as loadSceneData,Oe as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,It as registerDrawCallback,Ke as registerEmbeddedAssets,Le as registerMaterialCallback,nn as setEditorMode,nt as shutdownDrawAPI,Ut as shutdownGLDebugAPI,pt as shutdownGeometryAPI,Ae as shutdownMaterialAPI,wt as shutdownPostProcessAPI,Mt as shutdownRendererAPI,Se as textPlugin,Bt as unregisterDrawCallback,Ne as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};//# sourceMappingURL=index.js.map