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
fix: 2D engine defaults, shared constants, WeChat platform bugs, WASM optimization
esengineacdbcede2dd9
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 8f5e689f8..31ba1eb76 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -16,6 +16,7 @@ set(ES_EMSCRIPTEN_COMPILE_FLAGS-ffunction-sections-fdata-sections-fno-exceptions+ -fno-rtti)# Standard (monolithic) link flagsdiff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex d2e2d4311..d21dc2f80 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,2 +1,2 @@-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}let u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,s)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((s,n)=>{d().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{d().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,g=null;function y(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function x(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,g=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:g}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let _=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return h(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 c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const s=t.touches[0];s&&e.onPointerDown(0,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295,b=4294967295;let P=0;function S(e,t){const s=++P;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function C(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function T(e,t){const s=C(),n=s.get(e);if(n)return n;const r=S(e,t);return s.set(e,r),M(e,t,!1),r}function A(e){const t=C(),s=t.get(e);if(s)return s;const n=S(e,{});return t.set(e,n),M(e,{},!0),n}function E(e){return C().get(e)}function M(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function R(e){return!0===e._builtin}const I=new Map;function F(e,t){I.set(e,t)}function B(e){return I.get(e)??E(e)}function U(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return I.set(e,s),s}const k=U("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),W=U("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=U("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),D=U("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),z=U("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),L=U("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),O=U("Parent",{entity:0}),H=U("Children",{entities:[]}),N=U("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),j=U("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),V={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};F("Name",V);const X=U("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),G=U("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),q=U("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Y=U("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),J={Static:0,Kinematic:1,Dynamic:2};let K=0;function Q(e,t){const s=++K;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}class ee{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 te{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 ee(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function ne(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class re{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ne(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class oe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=R(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ie{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new oe(this,null);return this.spawned_.push(e),e}entity(e){return new oe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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 s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ae;exports.Schedule=void 0,(ae=exports.Schedule||(exports.Schedule={}))[ae.Startup=0]="Startup",ae[ae.First=1]="First",ae[ae.PreUpdate=2]="PreUpdate",ae[ae.Update=3]="Update",ae[ae.PostUpdate=4]="PostUpdate",ae[ae.Last=5]="Last",ae[ae.FixedPreUpdate=10]="FixedPreUpdate",ae[ae.FixedUpdate=11]="FixedUpdate",ae[ae.FixedPostUpdate=12]="FixedPostUpdate";let le=0;function ce(e,t,s){const n=++le;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function ue(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class de{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ie&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new re(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ie(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class he{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const pe=Q(new he,"Input");class fe{constructor(e){this.target_=e??null}build(e){const s=new he;e.insertResource(pe,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const me=new fe;function ge(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:ge(e)}}return t}class ye{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}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),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return R(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return R(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return R(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){return this.has(e,t)?this.get(e,t):null}remove(e,t){R(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s)for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const r={...t._default,...n};if(this.cppRegistry_){const s=`add${t._cppName}`,n=this.cppRegistry_[s];n?.call(this.cppRegistry_,e,ge(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const s=`get${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const s=`has${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const s=`remove${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e)}insertScript(e,t,s){const n=t.create(s);this.getStorage(t).set(e,n),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),n}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!R(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const xe=Q({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var _e;function we(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(_e=exports.BlendMode||(exports.BlendMode={}))[_e.Normal=0]="Normal",_e[_e.Additive=1]="Additive",_e[_e.Multiply=2]="Multiply",_e[_e.Screen=3]="Screen",_e[_e.PremultipliedAlpha=4]="PremultipliedAlpha";let ve=null,be=null,Pe=1;const Se=new Map;function Ce(e){ve=e,be=e.getResourceManager(),ke()}function Te(){0!==Re&&ve&&(ve._free(Re),Re=0),Se.clear(),Pe=1,Me=!1,be=null,ve=null}function Ae(){if(!be)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return be}const Ee={createShader:(e,t)=>Ae().createShader(e,t),releaseShader(e){e>0&&Ae().releaseShader(e)},create(e){const t=Pe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Se.set(t,s),t},get:e=>Se.get(e),setUniform(e,t,s){const n=Se.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Se.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Se.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Se.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Se.get(e);s&&(s.depthTest=t)},getShader(e){const t=Se.get(e);return t?.shader??0},release(e){Se.delete(e)},isValid:e=>Se.has(e),createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Se.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Pe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Se.set(s,n),s},toAssetData(e,t){const s=Se.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Se.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Me=!1,Re=0;const Ie=4096,Fe=new Map;let Be=null;function Ue(e){const t=(0===Re&&ve&&(Re=ve._malloc(Ie)),Re);if(0===t||!ve)return{ptr:0,count:0};let s=0,n=0;const r=ve.HEAPU8,o=ve.HEAPU32,i=ve.HEAPF32;for(const[a,l]of e){if(s+128>Ie)break;let e=Fe.get(a);e||(Be||(Be=new TextEncoder),e=Be.encode(a),Fe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function ke(){if(!ve||Me)return;ve.materialDataProvider=(e,t,s,n,r)=>{const o=Se.get(e);if(!o)return ve.HEAPU32[t>>2]=0,ve.HEAPU32[s>>2]=0,ve.HEAPU32[n>>2]=0,void(ve.HEAPU32[r>>2]=0);ve.HEAPU32[t>>2]=o.shader,ve.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Ue(o.uniforms);ve.HEAPU32[n>>2]=i,ve.HEAPU32[r>>2]=a},Me=!0}const We={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 $e{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const o=t();this.pending_.set(e,o);try{const t=await(s>0?Promise.race([o,new Promise((t,n)=>setTimeout(()=>n(new Error(`AsyncCache timeout: ${e} (${s}ms)`)),s))]):o);return this.cache_.set(e,t),t}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),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 De{constructor(e,t=""){this.cache_=new $e,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ee.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ee.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ee.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ze=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function Le(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,V,{value:n.name}),!1!==n.visible)for(const s of n.components)He(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function Oe(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ze.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ze.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,V,{value:s.name}),!1!==s.visible)for(const n of s.components)He(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function He(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=B(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class Ne{constructor(e){this.textureCache_=new $e,this.shaderCache_=new $e,this.jsonCache_=new $e,this.textCache_=new $e,this.binaryCache_=new $e,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new $e,this.prefabCache_=new $e,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=i(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,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u=e.endsWith(".skel"),d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(s):this.loadFntFile(s))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Oe(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ee.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ee.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const je=Q(null,"Assets");class Ve{build(e){const t=e.wasmModule;t?e.insertResource(je,new Ne(t)):console.warn("AssetPlugin: No WASM module available")}}const Xe=new Ve;async function Ge(e,t,s){const{entities:n,rootId:r}=await qe(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Oe(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}async function qe(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await qe(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Ye(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function Ye(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Je{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ge(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ke=Q(null,"Prefabs");class Qe{constructor(){this.name="PrefabsPlugin",this.dependencies=[je]}build(e){const t=e.getResource(je);e.insertResource(Ke,new Je(e.world,t))}}const Ze=new Qe;let et=null,tt=0,st=0,nt=0;const rt=new Float32Array(256);function ot(e){et=e,tt=et._malloc(64),st=et._malloc(64),nt=et._malloc(1024)}function it(){et&&(tt&&(et._free(tt),tt=0),st&&(et._free(st),st=0),nt&&(et._free(nt),nt=0)),et=null}function at(){if(!et)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return et}const lt={r:1,g:1,b:1,a:1},ct={begin(e){const t=at();t.HEAPF32.set(e,tt/4),t.draw_begin(tt)},end(){at().draw_end()},line(e,t,s,n=1){at().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){at().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){at().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){at().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){at().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=lt){at().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=lt){at().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){at().draw_setLayer(e)},setDepth(e){at().draw_setDepth(e)},getDrawCallCount:()=>et?et.draw_getDrawCallCount():0,getPrimitiveCount:()=>et?et.draw_getPrimitiveCount():0,setBlendMode(e){at().draw_setBlendMode(e)},setDepthTest(e){at().draw_setDepthTest(e)},drawMesh(e,t,s){const n=at();n.HEAPF32.set(s,st/4),n.draw_mesh(e,t,st)},drawMeshWithMaterial(e,t,s){const n=at(),r=Ee.get(t);if(!r)return;if(ct.setBlendMode(r.blendMode),ct.setDepthTest(r.depthTest),0===r.uniforms.size)return void ct.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,st/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=dt(t);if(!(n<0)){if(we(s))rt[o++]=10,rt[o++]=n,rt[o++]=s.slot??e++,rt[o++]=s.textureId;else if("number"==typeof s)rt[o++]=1,rt[o++]=n,rt[o++]=s;else if(Array.isArray(s)){rt[o++]=s.length,rt[o++]=n;for(let e=0;e<s.length;e++)rt[o++]=s[e]}else"w"in s?(rt[o++]=4,rt[o++]=n,rt[o++]=s.x,rt[o++]=s.y,rt[o++]=s.z,rt[o++]=s.w):"z"in s?(rt[o++]=3,rt[o++]=n,rt[o++]=s.x,rt[o++]=s.y,rt[o++]=s.z):(rt[o++]=2,rt[o++]=n,rt[o++]=s.x,rt[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(rt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),nt/4),n.draw_meshWithUniforms(e,r.shader,st,nt,o)):n.draw_mesh(e,r.shader,st)}},ut={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function dt(e){return ut[e]??-1}var ht;exports.DataType=void 0,(ht=exports.DataType||(exports.DataType={}))[ht.Float=1]="Float",ht[ht.Float2=2]="Float2",ht[ht.Float3=3]="Float3",ht[ht.Float4=4]="Float4",ht[ht.Int=5]="Int",ht[ht.Int2=6]="Int2",ht[ht.Int3=7]="Int3",ht[ht.Int4=8]="Int4";let pt=null,ft=0,mt=0,gt=0;function yt(e){pt=e,ft=pt._malloc(262144),mt=pt._malloc(65536),gt=pt._malloc(256)}function xt(){pt&&(ft&&pt._free(ft),mt&&pt._free(mt),gt&&pt._free(gt),ft=0,mt=0,gt=0),pt=null}function _t(){if(!pt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return pt}const wt={create(e){const t=_t(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,ft/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,gt,r).set(o),t.geometry_init(s,ft,n,gt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,mt,n).set(e.indices),t.geometry_setIndices16(s,mt,n)}else{new Uint32Array(t.HEAPU8.buffer,mt,n).set(e.indices),t.geometry_setIndices32(s,mt,n)}}return s},updateVertices(e,t,s=0){const n=_t(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ft/4),n.geometry_updateVertices(e,ft,r,s)},release(e){e>0&&_t().geometry_release(e)},isValid:e=>!(!pt||e<=0)&&pt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return wt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return wt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return wt.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 vt=null;function bt(e){vt=e}function Pt(){vt&&Ct.isInitialized()&&Ct.shutdown(),vt=null}function St(){if(!vt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vt}const Ct={init:(e,t)=>St().postprocess_init(e,t),shutdown(){St().postprocess_shutdown()},resize(e,t){St().postprocess_resize(e,t)},addPass:(e,t)=>St().postprocess_addPass(e,t),removePass(e){St().postprocess_removePass(e)},setEnabled(e,t){St().postprocess_setPassEnabled(e,t)},isEnabled:e=>St().postprocess_isPassEnabled(e),setUniform(e,t,s){St().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){St().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){St().postprocess_begin()},end(){St().postprocess_end()},getPassCount:()=>St().postprocess_getPassCount(),isInitialized:()=>!!vt&&vt.postprocess_isInitialized(),setBypass(e){St().postprocess_setBypass(e)},isBypassed:()=>!vt||vt.postprocess_isBypassed(),createBlur:()=>Ee.createShader(Tt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ee.createShader(Tt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ee.createShader(Tt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ee.createShader(Tt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Tt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var At;exports.RenderStage=void 0,(At=exports.RenderStage||(exports.RenderStage={}))[At.Background=0]="Background",At[At.Opaque=1]="Opaque",At[At.Transparent=2]="Transparent",At[At.Overlay=3]="Overlay";let Et=null,Mt=0;function Rt(e){Et=e,Mt=Et._malloc(64)}function It(){Et&&Mt&&(Et._free(Mt),Mt=0),Et=null}const Ft={init(e,t){Et?.renderer_init(e,t)},resize(e,t){Et?.renderer_resize(e,t)},begin(e,t){Et&&Mt&&(Et.HEAPF32.set(e,Mt/4),Et.renderer_begin(Mt,t??0))},flush(){Et?.renderer_flush()},end(){Et?.renderer_end()},submitSprites(e){Et&&Et.renderer_submitSprites(e._cpp)},submitBitmapText(e){Et&&Et.renderer_submitBitmapText(e._cpp)},submitSpine(e){Et&&Et.renderer_submitSpine?.(e._cpp)},setStage(e){Et?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Et?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Et?.renderer_releaseTarget(e)},getTargetTexture:e=>Et?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Et?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Et?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Et?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Et?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Et?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Et?Et.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Et?{drawCalls:Et.renderer_getDrawCalls(),triangles:Et.renderer_getTriangles(),sprites:Et.renderer_getSprites(),text:Et.renderer_getText(),spine:Et.renderer_getSpine?.()??0,meshes:Et.renderer_getMeshes(),culled:Et.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Bt=null;function Ut(e){Bt=e}function kt(){Bt=null}const Wt={enable(){Bt?.gl_enableErrorCheck(!0)},disable(){Bt?.gl_enableErrorCheck(!1)},check:e=>Bt?.gl_checkErrors(e)??0,diagnose(){Bt?.renderer_diagnose()}},$t=new Map;function Dt(e){$t.delete(e)}class zt{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ft.resize(n,r),Ct.isInitialized()&&Ct.getPassCount()>0&&Ct.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ft.setViewport(0,0,n,r),Ft.clearBuffers(3),Ft.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ft.submitSprites(t),Ft.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ft.submitSpine(t),Ft.flush(),this.executeDrawCallbacks(s,o),Ft.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ft.setViewport(n.x,n.y,n.w,n.h),Ft.setScissor(n.x,n.y,n.w,n.h,!0),Ft.clearBuffers(r),Ft.setScissor(0,0,0,0,!1),Ft.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ft.submitSprites(t),Ft.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ft.submitSpine(t),Ft.flush(),this.executeDrawCallbacks(s,o),Ft.end()}executeDrawCallbacks(e,t){const s=$t;if(s.size>0){ct.begin(e);const n=[];for(const[e,r]of s.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ct.end();for(const e of n)Dt(e)}}}class Lt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=t/1e3;for(this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;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 ye,this.resources_=new te;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Lt}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}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 de(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,kt(),It(),Pt(),xt(),Te(),it()}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(se);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ot=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ht(e,t,s,n,r){const o=e*t/s,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=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Nt(e,t,s,n){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*s/(l.h*n);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=Ht(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Vt(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Gt(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=Yt(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Jt(u,p),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const jt=new Float32Array(16);function Vt(e,t,s,n,r,o){const i=jt;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Xt=new Float32Array(16);function Gt(e,t,s,n){const r=Xt;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const qt=new Float32Array(16);function Yt(e,t,s){const n=qt;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}function Jt(e,t){const s=new Float32Array(16);for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var Kt,Qt,Zt;exports.TextAlign=void 0,(Kt=exports.TextAlign||(exports.TextAlign={}))[Kt.Left=0]="Left",Kt[Kt.Center=1]="Center",Kt[Kt.Right=2]="Right",exports.TextVerticalAlign=void 0,(Qt=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Qt.Top=0]="Top",Qt[Qt.Middle=1]="Middle",Qt[Qt.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Zt=exports.TextOverflow||(exports.TextOverflow={}))[Zt.Visible=0]="Visible",Zt[Zt.Clip=1]="Clip",Zt[Zt.Ellipsis=2]="Ellipsis";const es=T("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),ts=T("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class ss{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 s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),x=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${y}, ${x})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(p,f,C,P.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function ns(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function rs(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class os{build(e){F("Text",es);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new ss(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,es));for(const e of r.keys())n.valid(e)&&n.has(e,es)||r.delete(e);const e=n.getEntitiesWithComponents([es]);for(const t of e){const e=n.get(t,es),o=n.has(t,ts)?n.get(t,ts):null,i=r.get(t);if(i&&!rs(i,e,o))continue;n.has(t,$)||n.insert(t,$,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,$);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,$,l),r.set(t,ns(e,o))}}))}}const is=new os,as=T("UIMask",{enabled:!0});function ls(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function cs(e,t,s,n,r,o,i,a,l,c,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function m(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[g,y]=m(d,p),[x,_]=m(h,f),w=Math.min(g,x),v=Math.max(g,x),b=Math.min(y,_),P=Math.max(y,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(P-b)}}function us(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],x=e[15],_=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,T=d*y-p*m,A=d*x-f*m,E=h*y-p*g,M=h*x-f*g,R=p*x-f*y;let I=_*R-w*M+v*E+b*A-P*T+S*C;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(g*S-y*P+x*b)*I,s[3]=(p*P-h*S-f*b)*I,s[4]=(c*A-a*R-u*T)*I,s[5]=(n*R-o*A+i*T)*I,s[6]=(y*v-m*S-x*w)*I,s[7]=(d*S-p*v+f*w)*I,s[8]=(a*M-l*A+u*C)*I,s[9]=(r*A-n*M-i*C)*I,s[10]=(m*P-g*v+x*_)*I,s[11]=(h*v-d*P-f*_)*I,s[12]=(l*T-a*E-c*C)*I,s[13]=(n*E-r*T+o*C)*I,s[14]=(g*w-m*b-y*_)*I,s[15]=(d*b-h*w+p*_)*I),s}function ds(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function hs(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function ps(e,t,s,n,r,o,i){if(!e.has(t,ts)||!e.has(t,W))return null;const a=e.get(t,ts),l=e.get(t,W),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return cs(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function fs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([as]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,as).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,O);){const e=t.get(n,O);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=ps(t,s,r,o,i,a,l);e&&(n=ls(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ps(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class ms{build(e){if(F("UIMask",as),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(fs(e.wasmModule,e.world))}}const gs=new ms,ys=T("Interactable",{enabled:!0}),xs=T("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var _s;exports.ButtonState=void 0,(_s=exports.ButtonState||(exports.ButtonState={}))[_s.Normal=0]="Normal",_s[_s.Hovered=1]="Hovered",_s[_s.Pressed=2]="Pressed",_s[_s.Disabled=3]="Disabled";const ws=T("Button",{state:exports.ButtonState.Normal,transition:null});class vs{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const bs=Q(new vs,"UIEvents"),Ps=A("ScreenSpace");function Ss(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,m=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,m=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function Cs(e,t,s,n,r,o){if(!e.has(t,ts))return;const i=e.get(t,ts),a=Ss(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,k);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,k,l),!e.has(t,H))return;const c=e.get(t,H);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Cs(e,t,a.rect,a.centerX,a.centerY,!1)}class Ts{build(e){F("UIRect",ts);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([Z(xe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([Ps,ts,k]);for(const e of o)Cs(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const As=new Ts,Es=new Float32Array(16),Ms=new Float32Array(16);let Rs=!0,Is=1;class Fs{build(e){F("Interactable",ys),F("Button",ws);const t=e.world,s=new vs;e.insertResource(bs,s);let n=null,r=null;Is="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([Z(pe),Z(xe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([xs]);for(const e of i){const s=t.get(e,xs);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Is,l=o.screenH-e.mouseY*Is;!function(e){let t=!1;for(let s=0;s<16;s++)if(Ms[s]!==e[s]){t=!0;break}t&&(Ms.set(e),Rs=!0)}(o.viewProjection),Rs&&(us(o.viewProjection,Es),Rs=!1);const c=ds(a,l,Es,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([ys,ts,W]);let d=null,h=-1/0;for(const e of u){t.has(e,xs)||t.insert(e,xs);if(!t.get(e,ys).enabled)continue;const s=t.get(e,W),n=t.get(e,ts),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(hs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,$)&&(s=t.get(e,$).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,xs)){t.get(n,xs).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,xs).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,xs);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,xs)){const e=t.get(r,xs);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,ce([],()=>{const e=t.getEntitiesWithComponents([ws]);for(const s of e){if(t.has(s,ys)||t.insert(s,ys,{enabled:!0}),!t.has(s,xs))continue;const e=t.get(s,xs),n=t.get(s,ws),r=t.get(s,ys),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,$)){const e=t.get(s,$),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,$,e)}}},{name:"ButtonSystem"}))}}const Bs=new Fs,Us=T("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class ks{build(e){F("TextInput",Us);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(512,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const p=h;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,Us);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(bs).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,y()}function m(e){if(a===e)return;g();const t=s.get(e,Us);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),y())}function g(){if(null!==a&&s.valid(a)&&s.has(a,Us)){const e=s.get(a,Us);e.focused=!1,e.dirty=!0}a=null,p.blur()}function y(){c=!0,u=0}function x(e,i,a,l){(r.width<a||r.height<l)&&(r.width=$s(Math.max(r.width,a)),r.height=$s(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ws(o,h,a-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Ws(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,s=m+(e.length-1)*f,n=f}else t=m+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const g=o.getImageData(0,0,a,l),y=new Uint8Array(g.data.buffer),x=t.getResourceManager(),_=t._malloc(y.length);t.HEAPU8.set(y,_);const w=n.get(e);void 0!==w&&x.releaseTexture(w);const v=x.createTexture(a,l,_,y.length,1,!0);n.set(e,v),t._free(_);const b=s.get(e,$);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,$,b)}p.addEventListener("input",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void g();const n=s.get(a,Us);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(bs).emit(a,"submit"),void g()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,y())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,Us)){const e=s.get(a,Us);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([Z(bs)],e=>{const t=s.getEntitiesWithComponents([Us,ys]);for(const e of t){if(!s.has(e,xs))continue;if(s.get(e,xs).justPressed)return void m(e)}if(null!==a){const e=s.getEntitiesWithComponents([ys]);for(const t of e){if(s.has(t,Us))continue;if(!s.has(t,xs))continue;if(s.get(t,xs).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,Us)))){s.get(a,Us).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Us)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([Us,ts]);for(const e of i){const t=s.get(e,Us);if(!t.dirty)continue;const n=s.get(e,ts),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,$)||s.insert(e,$,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ws(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function $s(e){let t=1;for(;t<e;)t*=2;return t}const Ds=new ks;async function zs(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Ls=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Os=Q(null,"PhysicsAPI");function Hs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ns(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class js{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Ls,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=zs(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([z]);for(const s of t){const t=e.world.get(s,z);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,ce([Z(se)],a=>{const l=i.getEntitiesWithComponents([X,k,W]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,X),l=i.get(r,W);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Hs(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Vs(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===J.Kinematic){const e=Hs(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,k);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,O)){const t=e.world.get(i,O);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,W)){const s=e.world.get(t.entity,W),n=Hs(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Ns(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,k,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Ls,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Os,Xs._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Vs(e,t,s){const n=e.world;if(n.has(s,G)){const e=n.get(s,G);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,q)){const e=n.get(s,q);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Y)){const e=n.get(s,Y);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Xs{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Xs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Gs(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function qs(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Ys(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,x=l*p,_=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(y+_))*r,(m+b)*r,(g-v)*r,0,(m-b)*o,(1-(f+_))*o,(x+w)*o,0,(g+v)*i,(x-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Js(e,t,s,n,r,o,i,a){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=Gs(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=qs(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=Gs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new js("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){n[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(a):await s.loadPixels(a),c=Gs(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),h=function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ee.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ee.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),p=Le(e.world,s);if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,$);r&&(r.texture=s[n.data.texture]||0,e.insert(t,$,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,N);o&&(o.font=r,e.insert(t,N,o))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,$);s&&(s.material=r,e.insert(t,$,s))}else if("SpineAnimation"===n.type){const s=e.get(t,j);s&&(s.material=r,e.insert(t,j,s))}}}}(e.world,s,h,p),r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,c,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,j)?c.get(o,j):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,W)){const e=Ys(c.get(o,W),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,u,o),x=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,x>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(y),t.renderer_submitTriangles(x,r,_,o,f,m,h),t._free(x),t._free(_),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(je);t&&t.setAddressableManifest(a)}}class Ks{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&(n.endsWith(".skel")?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const s=JSON.parse(t),n="label-atlas"===s.type?s.generatedFnt:s.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Qs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ft.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ft.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ft.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ft.releaseRenderTarget(e._handle),Qs.create({width:t,height:s,depth:!0})),begin(e,t){Ft.begin(t,e._handle)},end(){Ft.end()},getDepthTexture:e=>Ft.getTargetDepthTexture(e._handle)};let Zs=!1;const en=[is,gs,As,Bs,Ds];_||(_=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=Lt,exports.AssetPlugin=Ve,exports.AssetServer=Ne,exports.Assets=je,exports.AsyncCache=$e,exports.BitmapText=N,exports.BodyType=J,exports.BoxCollider=G,exports.Button=ws,exports.Camera=D,exports.Canvas=z,exports.CapsuleCollider=Y,exports.Children=H,exports.CircleCollider=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=ie,exports.Draw=ct,exports.EntityCommands=oe,exports.GLDebug=Wt,exports.Geometry=wt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=b,exports.INVALID_TEXTURE=v,exports.Input=pe,exports.InputPlugin=fe,exports.InputState=he,exports.Interactable=ys,exports.LocalTransform=k,exports.Material=Ee,exports.MaterialLoader=De,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=V,exports.Parent=O,exports.Physics=Xs,exports.PhysicsEvents=Ls,exports.PhysicsPlugin=js,exports.PostProcess=Ct,exports.PrefabServer=Je,exports.Prefabs=Ke,exports.PrefabsPlugin=Qe,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_)return;let e="fetch scene";try{const t=await s(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const r=new Ks(this.baseUrl_);await r.prefetch(n);let o=null;const i=this.app_.spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await Js(this.app_,this.app_.wasmModule,n,r,o),e="ensureCamera",this.ensureCamera()}catch(t){const s=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${s}\n${n}`),new Error(`[PreviewPlugin:${e}] ${s}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([D]);for(const n of s){if(e.get(n,D).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1920/1080;const n=e.getEntitiesWithComponents([z]);for(const r of n){const n=e.get(r,z);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=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(r,k,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,D,i)}}},exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ne(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=re,exports.RenderPipeline=zt,exports.RenderTexture=Qs,exports.Renderer=Ft,exports.Res=Z,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=X,exports.ScreenSpace=Ps,exports.ShaderSources=We,exports.SpineAnimation=j,exports.Sprite=$,exports.SystemRunner=de,exports.Text=es,exports.TextInput=Us,exports.TextInputPlugin=ks,exports.TextPlugin=os,exports.TextRenderer=ss,exports.Time=se,exports.UICameraInfo=xe,exports.UIEventQueue=vs,exports.UIEvents=bs,exports.UIInteraction=xs,exports.UIInteractionPlugin=Fs,exports.UILayoutPlugin=Ts,exports.UIMask=as,exports.UIMaskPlugin=ms,exports.UIRect=ts,exports.Velocity=L,exports.WebAssetProvider=Ks,exports.World=ye,exports.WorldTransform=W,exports.addStartupSystem=function(e){ue().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ue().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ue().push({schedule:e,system:t})},exports.assetPlugin=Xe,exports.clearDrawCallbacks=function(){$t.clear()},exports.clearUserComponents=function(){C().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=Ss,exports.createMaskProcessor=fs,exports.createWebApp=function(e,t){return function(e,t){const s=Lt.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ot(e),Ce(e),yt(e),bt(e),Rt(e),Ut(e);const r=new zt;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r){const o=Nt(e,n,t,r),i=s.getResource(xe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(xe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=i();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Ft.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;Ft.resize(t,s),Ct.isInitialized()&&Ct.getPassCount()>0&&!Ct.isBypassed()&&Ct.resize(t,s);const d=Nt(e,n,t,s);if(l(t,s),0===d.length)r.render({registry:{_cpp:n},viewProjection:Ot,width:t,height:s,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}Ft.setViewport(0,0,t,s)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Xe),s.addPlugin(Ze),s.addPlugin(me),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:en,...t})},exports.defineComponent=T,exports.defineResource=Q,exports.defineSystem=ce,exports.defineTag=A,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([V]);for(const n of s){const s=e.get(n,V);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getComponent=B,exports.getComponentDefaults=function(e){const t=B(e);return t?{...t._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=E,exports.initDrawAPI=ot,exports.initGLDebugAPI=Ut,exports.initGeometryAPI=yt,exports.initMaterialAPI=Ce,exports.initPostProcessAPI=bt,exports.initRendererAPI=Rt,exports.inputPlugin=me,exports.instantiatePrefab=Ge,exports.intersectRects=ls,exports.invertMatrix4=us,exports.isBuiltinComponent=R,exports.isEditor=function(){return Zs},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Zs},exports.isTextureRef=we,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=He,exports.loadPhysicsModule=zs,exports.loadRuntimeScene=Js,exports.loadSceneData=Le,exports.loadSceneWithAssets=Oe,exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=hs,exports.prefabsPlugin=Ze,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=F,exports.registerComponentAssetFields=function(e,t){ze.set(e,t)},exports.registerDrawCallback=function(e,t){$t.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(je);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ke,exports.screenToWorld=ds,exports.setEditorMode=function(e){Zs=e},exports.shutdownDrawAPI=it,exports.shutdownGLDebugAPI=kt,exports.shutdownGeometryAPI=xt,exports.shutdownMaterialAPI=Te,exports.shutdownPostProcessAPI=Pt,exports.shutdownRendererAPI=It,exports.textInputPlugin=Ds,exports.textPlugin=is,exports.uiInteractionPlugin=Bs,exports.uiLayoutPlugin=As,exports.uiMaskPlugin=gs,exports.uiPlugins=en,exports.unregisterDrawCallback=Dt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([D]);for(const n of s){const s=e.get(n,D);s&&(s.aspectRatio=t,e.insert(n,D,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.worldRectToScreen=cs,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=d();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=x,exports.wxLoadImage=y,exports.wxLoadImagePixels=async function(e){return x(await y(e))},exports.wxReadFile=h,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{d().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}let u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,s)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((s,n)=>{d().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{d().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function m(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function g(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let y=!1;const x=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return h(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 c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},_=1920,w=1080,v=512,b=4294967295,P=4294967295;let S=0;function C(e,t){const s=++S;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function T(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function A(e,t){const s=T(),n=s.get(e);if(n)return n;const r=C(e,t);return s.set(e,r),R(e,t,!1),r}function E(e){const t=T(),s=t.get(e);if(s)return s;const n=C(e,{});return t.set(e,n),R(e,{},!0),n}function M(e){return T().get(e)}function R(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function I(e){return!0===e._builtin}const F=new Map;function B(e,t){F.set(e,t)}function U(e){return F.get(e)??M(e)}function k(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return F.set(e,s),s}const W={Perspective:0,Orthographic:1},D={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},$={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},z=k("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),L=k("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),O=k("Sprite",{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),H=k("Camera",{projectionType:W.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:D.ColorAndDepth}),N=k("Canvas",{designResolution:{x:_,y:w},pixelsPerUnit:100,scaleMode:$.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),j=k("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),V=k("Parent",{entity:0}),X=k("Children",{entities:[]}),G=k("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:P}),q=k("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};B("Name",Y);const J=k("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),K=k("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Q=k("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Z=k("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ee={Static:0,Kinematic:1,Dynamic:2};let te=0;function se(e,t){const s=++te;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ne(e){return{_type:"res",_resource:e}}class re{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 oe{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 re(this.get(e),t=>this.set(e,t))}}const ie=se({delta:0,elapsed:0,frameCount:0},"Time");function ae(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class le{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ae(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class ce{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=I(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ce(this,null);return this.spawned_.push(e),e}entity(e){return new ce(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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 s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var de;exports.Schedule=void 0,(de=exports.Schedule||(exports.Schedule={}))[de.Startup=0]="Startup",de[de.First=1]="First",de[de.PreUpdate=2]="PreUpdate",de[de.Update=3]="Update",de[de.PostUpdate=4]="PostUpdate",de[de.Last=5]="Last",de[de.FixedPreUpdate=10]="FixedPreUpdate",de[de.FixedUpdate=11]="FixedUpdate",de[de.FixedPostUpdate=12]="FixedPostUpdate";let he=0;function pe(e,t,s){const n=++he;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function fe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class me{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new le(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ge{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 ye=se(new ge,"Input");class xe{constructor(e){this.target_=e??null}build(e){const s=new ge;e.insertResource(ye,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,pe([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const _e=new xe;function we(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:we(e)}}return t}class ve{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}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),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return I(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return I(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return I(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){return this.has(e,t)?this.get(e,t):null}remove(e,t){I(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s)for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const r={...t._default,...n};if(this.cppRegistry_){const s=`add${t._cppName}`,n=this.cppRegistry_[s];n?.call(this.cppRegistry_,e,we(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const s=`get${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const s=`has${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const s=`remove${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e)}insertScript(e,t,s){const n=t.create(s);this.getStorage(t).set(e,n),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),n}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!I(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const be=se({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Pe;function Se(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 Ce=null,Te=null,Ae=1;const Ee=new Map;function Me(e){Ce=e,Te=e.getResourceManager(),ze()}function Re(){0!==Ue&&Ce&&(Ce._free(Ue),Ue=0),Ee.clear(),Ae=1,Be=!1,Te=null,Ce=null}function Ie(){if(!Te)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Te}const Fe={createShader:(e,t)=>Ie().createShader(e,t),releaseShader(e){e>0&&Ie().releaseShader(e)},create(e){const t=Ae++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ee.set(t,s),t},get:e=>Ee.get(e),setUniform(e,t,s){const n=Ee.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ee.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ee.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ee.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ee.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ee.get(e);return t?.shader??0},release(e){Ee.delete(e)},isValid:e=>Ee.has(e),createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ee.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ae++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ee.set(s,n),s},toAssetData(e,t){const s=Ee.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ee.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Be=!1,Ue=0;const ke=4096,We=new Map;let De=null;function $e(e){const t=(0===Ue&&Ce&&(Ue=Ce._malloc(ke)),Ue);if(0===t||!Ce)return{ptr:0,count:0};let s=0,n=0;const r=Ce.HEAPU8,o=Ce.HEAPU32,i=Ce.HEAPF32;for(const[a,l]of e){if(s+128>ke)break;let e=We.get(a);e||(De||(De=new TextEncoder),e=De.encode(a),We.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function ze(){if(!Ce||Be)return;Ce.materialDataProvider=(e,t,s,n,r)=>{const o=Ee.get(e);if(!o)return Ce.HEAPU32[t>>2]=0,Ce.HEAPU32[s>>2]=0,Ce.HEAPU32[n>>2]=0,void(Ce.HEAPU32[r>>2]=0);Ce.HEAPU32[t>>2]=o.shader,Ce.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=$e(o.uniforms);Ce.HEAPU32[n>>2]=i,Ce.HEAPU32[r>>2]=a},Be=!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 Oe{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const o=t();this.pending_.set(e,o);try{const t=await(s>0?Promise.race([o,new Promise((t,n)=>setTimeout(()=>n(new Error(`AsyncCache timeout: ${e} (${s}ms)`)),s))]):o);return this.cache_.set(e,t),t}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),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 He{constructor(e,t=""){this.cache_=new Oe,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(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 o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Fe.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const Ne=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function je(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Y,{value:n.name}),!1!==n.visible)for(const s of n.components)Xe(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function Ve(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ne.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ne.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Y,{value:s.name}),!1!==s.visible)for(const n of s.components)Xe(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function Xe(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=U(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class Ge{constructor(e){this.textureCache_=new Oe,this.shaderCache_=new Oe,this.jsonCache_=new Oe,this.textCache_=new Oe,this.binaryCache_=new Oe,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Oe,this.prefabCache_=new Oe,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=i(v,v),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new He(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u=e.endsWith(".skel"),d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(s):this.loadFntFile(s))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ve(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Fe.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Fe.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const qe=se(null,"Assets");class Ye{build(e){const t=e.wasmModule;t?e.insertResource(qe,new Ge(t)):console.warn("AssetPlugin: No WASM module available")}}const Je=new Ye;async function Ke(e,t,s){const{entities:n,rootId:r}=await Qe(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Ve(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}async function Qe(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Qe(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Ze(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function Ze(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class et{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ke(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const tt=se(null,"Prefabs");class st{constructor(){this.name="PrefabsPlugin",this.dependencies=[qe]}build(e){const t=e.getResource(qe);e.insertResource(tt,new et(e.world,t))}}const nt=new st;let rt=null,ot=0,it=0,at=0;const lt=new Float32Array(256);function ct(e){rt=e,ot=rt._malloc(64),it=rt._malloc(64),at=rt._malloc(1024)}function ut(){rt&&(ot&&(rt._free(ot),ot=0),it&&(rt._free(it),it=0),at&&(rt._free(at),at=0)),rt=null}function dt(){if(!rt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return rt}const ht={r:1,g:1,b:1,a:1},pt={begin(e){const t=dt();t.HEAPF32.set(e,ot/4),t.draw_begin(ot)},end(){dt().draw_end()},line(e,t,s,n=1){dt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){dt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){dt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){dt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){dt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=ht){dt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=ht){dt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){dt().draw_setLayer(e)},setDepth(e){dt().draw_setDepth(e)},getDrawCallCount:()=>rt?rt.draw_getDrawCallCount():0,getPrimitiveCount:()=>rt?rt.draw_getPrimitiveCount():0,setBlendMode(e){dt().draw_setBlendMode(e)},setDepthTest(e){dt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=dt();n.HEAPF32.set(s,it/4),n.draw_mesh(e,t,it)},drawMeshWithMaterial(e,t,s){const n=dt(),r=Fe.get(t);if(!r)return;if(pt.setBlendMode(r.blendMode),pt.setDepthTest(r.depthTest),0===r.uniforms.size)return void pt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,it/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=mt(t);if(!(n<0)){if(Se(s))lt[o++]=10,lt[o++]=n,lt[o++]=s.slot??e++,lt[o++]=s.textureId;else if("number"==typeof s)lt[o++]=1,lt[o++]=n,lt[o++]=s;else if(Array.isArray(s)){lt[o++]=s.length,lt[o++]=n;for(let e=0;e<s.length;e++)lt[o++]=s[e]}else"w"in s?(lt[o++]=4,lt[o++]=n,lt[o++]=s.x,lt[o++]=s.y,lt[o++]=s.z,lt[o++]=s.w):"z"in s?(lt[o++]=3,lt[o++]=n,lt[o++]=s.x,lt[o++]=s.y,lt[o++]=s.z):(lt[o++]=2,lt[o++]=n,lt[o++]=s.x,lt[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(lt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),at/4),n.draw_meshWithUniforms(e,r.shader,it,at,o)):n.draw_mesh(e,r.shader,it)}},ft={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 mt(e){return ft[e]??-1}var gt;exports.DataType=void 0,(gt=exports.DataType||(exports.DataType={}))[gt.Float=1]="Float",gt[gt.Float2=2]="Float2",gt[gt.Float3=3]="Float3",gt[gt.Float4=4]="Float4",gt[gt.Int=5]="Int",gt[gt.Int2=6]="Int2",gt[gt.Int3=7]="Int3",gt[gt.Int4=8]="Int4";let yt=null,xt=0,_t=0,wt=0;function vt(e){yt=e,xt=yt._malloc(262144),_t=yt._malloc(65536),wt=yt._malloc(256)}function bt(){yt&&(xt&&yt._free(xt),_t&&yt._free(_t),wt&&yt._free(wt),xt=0,_t=0,wt=0),yt=null}function Pt(){if(!yt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return yt}const St={create(e){const t=Pt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,xt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,wt,r).set(o),t.geometry_init(s,xt,n,wt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_t,n).set(e.indices),t.geometry_setIndices16(s,_t,n)}else{new Uint32Array(t.HEAPU8.buffer,_t,n).set(e.indices),t.geometry_setIndices32(s,_t,n)}}return s},updateVertices(e,t,s=0){const n=Pt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,xt/4),n.geometry_updateVertices(e,xt,r,s)},release(e){e>0&&Pt().geometry_release(e)},isValid:e=>!(!yt||e<=0)&&yt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return St.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return St.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return St.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 Ct=null;function Tt(e){Ct=e}function At(){Ct&&Mt.isInitialized()&&Mt.shutdown(),Ct=null}function Et(){if(!Ct)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ct}const Mt={init:(e,t)=>Et().postprocess_init(e,t),shutdown(){Et().postprocess_shutdown()},resize(e,t){Et().postprocess_resize(e,t)},addPass:(e,t)=>Et().postprocess_addPass(e,t),removePass(e){Et().postprocess_removePass(e)},setEnabled(e,t){Et().postprocess_setPassEnabled(e,t)},isEnabled:e=>Et().postprocess_isPassEnabled(e),setUniform(e,t,s){Et().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Et().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Et().postprocess_begin()},end(){Et().postprocess_end()},getPassCount:()=>Et().postprocess_getPassCount(),isInitialized:()=>!!Ct&&Ct.postprocess_isInitialized(),setBypass(e){Et().postprocess_setBypass(e)},isBypassed:()=>!Ct||Ct.postprocess_isBypassed(),createBlur:()=>Fe.createShader(Rt,"#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(Rt,"#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(Rt,"#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(Rt,"#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")},Rt="#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 It;exports.RenderStage=void 0,(It=exports.RenderStage||(exports.RenderStage={}))[It.Background=0]="Background",It[It.Opaque=1]="Opaque",It[It.Transparent=2]="Transparent",It[It.Overlay=3]="Overlay";let Ft=null,Bt=0;function Ut(e){Ft=e,Bt=Ft._malloc(64)}function kt(){Ft&&Bt&&(Ft._free(Bt),Bt=0),Ft=null}const Wt={init(e,t){Ft?.renderer_init(e,t)},resize(e,t){Ft?.renderer_resize(e,t)},begin(e,t){Ft&&Bt&&(Ft.HEAPF32.set(e,Bt/4),Ft.renderer_begin(Bt,t??0))},flush(){Ft?.renderer_flush()},end(){Ft?.renderer_end()},submitSprites(e){Ft&&Ft.renderer_submitSprites(e._cpp)},submitBitmapText(e){Ft&&Ft.renderer_submitBitmapText(e._cpp)},submitSpine(e){Ft&&Ft.renderer_submitSpine?.(e._cpp)},setStage(e){Ft?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ft?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ft?.renderer_releaseTarget(e)},getTargetTexture:e=>Ft?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ft?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ft?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ft?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ft?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ft?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ft?Ft.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ft?{drawCalls:Ft.renderer_getDrawCalls(),triangles:Ft.renderer_getTriangles(),sprites:Ft.renderer_getSprites(),text:Ft.renderer_getText(),spine:Ft.renderer_getSpine?.()??0,meshes:Ft.renderer_getMeshes(),culled:Ft.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Dt=null;function $t(e){Dt=e}function zt(){Dt=null}const Lt={enable(){Dt?.gl_enableErrorCheck(!0)},disable(){Dt?.gl_enableErrorCheck(!1)},check:e=>Dt?.gl_checkErrors(e)??0,diagnose(){Dt?.renderer_diagnose()}},Ot=new Map;function Ht(e){Ot.delete(e)}class Nt{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Wt.resize(n,r),Mt.isInitialized()&&Mt.getPassCount()>0&&Mt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Wt.setViewport(0,0,n,r),Wt.clearBuffers(3),Wt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Wt.submitSprites(t),Wt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wt.submitSpine(t),Wt.flush(),this.executeDrawCallbacks(s,o),Wt.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Wt.setViewport(n.x,n.y,n.w,n.h),Wt.setScissor(n.x,n.y,n.w,n.h,!0),Wt.clearBuffers(r),Wt.setScissor(0,0,0,0,!1),Wt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Wt.submitSprites(t),Wt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wt.submitSpine(t),Wt.flush(),this.executeDrawCallbacks(s,o),Wt.end()}executeDrawCallbacks(e,t){const s=Ot;if(s.size>0){pt.begin(e);const n=[];for(const[e,r]of s.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}pt.end();for(const e of n)Ht(e)}}}class jt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=t/1e3;for(this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;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 ve,this.resources_=new oe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new jt}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}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 me(this.world_,this.resources_),this.resources_.insert(ie,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,zt(),kt(),At(),bt(),Re(),ut()}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(ie);t.delta=e,t.elapsed+=e,t.frameCount++}}const Vt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Xt(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case $.FixedWidth:return o;case $.FixedHeight:return i;case $.Expand:return Math.max(o,i);case $.Shrink:return Math.min(o,i);case $.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Gt(e,t,s,n){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*s/(l.h*n);let u,d=0,h=0;if(r.projectionType===W.Orthographic){if(h=r.orthoSize,o){h=Xt(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Yt(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Kt(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=Zt(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:es(u,p),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const qt=new Float32Array(16);function Yt(e,t,s,n,r,o){const i=qt;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Jt=new Float32Array(16);function Kt(e,t,s,n){const r=Jt;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Qt=new Float32Array(16);function Zt(e,t,s){const n=Qt;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}function es(e,t){const s=new Float32Array(16);for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var ts,ss,ns;exports.TextAlign=void 0,(ts=exports.TextAlign||(exports.TextAlign={}))[ts.Left=0]="Left",ts[ts.Center=1]="Center",ts[ts.Right=2]="Right",exports.TextVerticalAlign=void 0,(ss=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ss.Top=0]="Top",ss[ss.Middle=1]="Middle",ss[ss.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ns=exports.TextOverflow||(exports.TextOverflow={}))[ns.Visible=0]="Visible",ns[ns.Clip=1]="Clip",ns[ns.Ellipsis=2]="Ellipsis";const rs=A("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),os=A("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class is{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(v,v),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),x=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${y}, ${x})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(p,f,C,P.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function as(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function ls(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class cs{build(e){B("Text",rs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new is(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,pe([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,rs));for(const e of r.keys())n.valid(e)&&n.has(e,rs)||r.delete(e);const e=n.getEntitiesWithComponents([rs]);for(const t of e){const e=n.get(t,rs),o=n.has(t,os)?n.get(t,os):null,i=r.get(t);if(i&&!ls(i,e,o))continue;n.has(t,O)||n.insert(t,O,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,O);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,O,l),r.set(t,as(e,o))}}))}}const us=new cs,ds=A("UIMask",{enabled:!0});function hs(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function ps(e,t,s,n,r,o,i,a,l,c,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function m(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[g,y]=m(d,p),[x,_]=m(h,f),w=Math.min(g,x),v=Math.max(g,x),b=Math.min(y,_),P=Math.max(y,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(P-b)}}function fs(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],x=e[15],_=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,T=d*y-p*m,A=d*x-f*m,E=h*y-p*g,M=h*x-f*g,R=p*x-f*y;let I=_*R-w*M+v*E+b*A-P*T+S*C;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(g*S-y*P+x*b)*I,s[3]=(p*P-h*S-f*b)*I,s[4]=(c*A-a*R-u*T)*I,s[5]=(n*R-o*A+i*T)*I,s[6]=(y*v-m*S-x*w)*I,s[7]=(d*S-p*v+f*w)*I,s[8]=(a*M-l*A+u*C)*I,s[9]=(r*A-n*M-i*C)*I,s[10]=(m*P-g*v+x*_)*I,s[11]=(h*v-d*P-f*_)*I,s[12]=(l*T-a*E-c*C)*I,s[13]=(n*E-r*T+o*C)*I,s[14]=(g*w-m*b-y*_)*I,s[15]=(d*b-h*w+p*_)*I),s}function ms(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function gs(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function ys(e,t,s,n,r,o,i){if(!e.has(t,os)||!e.has(t,L))return null;const a=e.get(t,os),l=e.get(t,L),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ps(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function xs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([ds]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,ds).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,V);){const e=t.get(n,V);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=ys(t,s,r,o,i,a,l);e&&(n=hs(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ys(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class _s{build(e){if(B("UIMask",ds),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(xs(e.wasmModule,e.world))}}const ws=new _s,vs=A("Interactable",{enabled:!0}),bs=A("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Ps;exports.ButtonState=void 0,(Ps=exports.ButtonState||(exports.ButtonState={}))[Ps.Normal=0]="Normal",Ps[Ps.Hovered=1]="Hovered",Ps[Ps.Pressed=2]="Pressed",Ps[Ps.Disabled=3]="Disabled";const Ss=A("Button",{state:exports.ButtonState.Normal,transition:null});class Cs{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Ts=se(new Cs,"UIEvents"),As=E("ScreenSpace");function Es(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,m=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,m=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function Ms(e,t,s,n,r,o){if(!e.has(t,os))return;const i=e.get(t,os),a=Es(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,z,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ms(e,t,a.rect,a.centerX,a.centerY,!1)}class Rs{build(e){B("UIRect",os);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,pe([ne(be)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([As,os,z]);for(const e of o)Ms(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Is=new Rs,Fs=new Float32Array(16),Bs=new Float32Array(16);let Us=!0,ks=1;class Ws{build(e){B("Interactable",vs),B("Button",Ss);const t=e.world,s=new Cs;e.insertResource(Ts,s);let n=null,r=null;ks="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,pe([ne(ye),ne(be)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([bs]);for(const e of i){const s=t.get(e,bs);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*ks,l=o.screenH-e.mouseY*ks;!function(e){let t=!1;for(let s=0;s<16;s++)if(Bs[s]!==e[s]){t=!0;break}t&&(Bs.set(e),Us=!0)}(o.viewProjection),Us&&(fs(o.viewProjection,Fs),Us=!1);const c=ms(a,l,Fs,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([vs,os,L]);let d=null,h=-1/0;for(const e of u){t.has(e,bs)||t.insert(e,bs);if(!t.get(e,vs).enabled)continue;const s=t.get(e,L),n=t.get(e,os),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(gs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,O)&&(s=t.get(e,O).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,bs)){t.get(n,bs).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,bs).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,bs);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,bs)){const e=t.get(r,bs);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,pe([],()=>{const e=t.getEntitiesWithComponents([Ss]);for(const s of e){if(t.has(s,vs)||t.insert(s,vs,{enabled:!0}),!t.has(s,bs))continue;const e=t.get(s,bs),n=t.get(s,Ss),r=t.get(s,vs),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,O)){const e=t.get(s,O),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,O,e)}}},{name:"ButtonSystem"}))}}const Ds=new Ws,$s=A("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class zs{build(e){B("TextInput",$s);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(v,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const p=h;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,$s);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(Ts).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,y()}function m(e){if(a===e)return;g();const t=s.get(e,$s);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),y())}function g(){if(null!==a&&s.valid(a)&&s.has(a,$s)){const e=s.get(a,$s);e.focused=!1,e.dirty=!0}a=null,p.blur()}function y(){c=!0,u=0}function x(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Os(Math.max(r.width,a)),r.height=Os(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ls(o,h,a-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Ls(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,s=m+(e.length-1)*f,n=f}else t=m+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const g=o.getImageData(0,0,a,l),y=new Uint8Array(g.data.buffer),x=t.getResourceManager(),_=t._malloc(y.length);t.HEAPU8.set(y,_);const w=n.get(e);void 0!==w&&x.releaseTexture(w);const v=x.createTexture(a,l,_,y.length,1,!0);n.set(e,v),t._free(_);const b=s.get(e,O);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,O,b)}p.addEventListener("input",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void g();const n=s.get(a,$s);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Ts).emit(a,"submit"),void g()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,y())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,$s)){const e=s.get(a,$s);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,pe([ne(Ts)],e=>{const t=s.getEntitiesWithComponents([$s,vs]);for(const e of t){if(!s.has(e,bs))continue;if(s.get(e,bs).justPressed)return void m(e)}if(null!==a){const e=s.getEntitiesWithComponents([vs]);for(const t of e){if(s.has(t,$s))continue;if(!s.has(t,bs))continue;if(s.get(t,bs).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,pe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,$s)))){s.get(a,$s).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,$s)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([$s,os]);for(const e of i){const t=s.get(e,$s);if(!t.dirty)continue;const n=s.get(e,os),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,O)||s.insert(e,O,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ls(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Os(e){let t=1;for(;t<e;)t*=2;return t}const Hs=new zs;async function Ns(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const js=se({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Vs=se(null,"PhysicsAPI");function Xs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Gs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class qs{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(js,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Ns(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([N]);for(const s of t){const t=e.world.get(s,N);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,pe([ne(ie)],a=>{const l=i.getEntitiesWithComponents([J,z,L]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,J),l=i.get(r,L);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Xs(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ys(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ee.Kinematic){const e=Xs(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,z);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,V)){const t=e.world.get(i,V);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,L)){const s=e.world.get(t.entity,L),n=Xs(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Gs(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,z,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(js,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Vs,Js._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Ys(e,t,s){const n=e.world;if(n.has(s,K)){const e=n.get(s,K);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Q)){const e=n.get(s,Q);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Z)){const e=n.get(s,Z);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Js{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Js.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Ks(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function Qs(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Zs(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,x=l*p,_=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(y+_))*r,(m+b)*r,(g-v)*r,0,(m-b)*o,(1-(f+_))*o,(x+w)*o,0,(g+v)*i,(x-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function en(e,t,s,n,r,o,i,a){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=Ks(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Qs(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=Ks(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new qs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){n[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(a):await s.loadPixels(a),c=Ks(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),h=function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Fe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Fe.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),p=je(e.world,s);if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,O);r&&(r.texture=s[n.data.texture]||0,e.insert(t,O,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,G);o&&(o.font=r,e.insert(t,G,o))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,O);s&&(s.material=r,e.insert(t,O,s))}else if("SpineAnimation"===n.type){const s=e.get(t,q);s&&(s.material=r,e.insert(t,q,s))}}}}(e.world,s,h,p),r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,c,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,q)?c.get(o,q):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,L)){const e=Zs(c.get(o,L),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,u,o),x=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,x>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(y),t.renderer_submitTriangles(x,r,_,o,f,m,h),t._free(x),t._free(_),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(qe);t&&t.setAddressableManifest(a)}}class tn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&(n.endsWith(".skel")?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const s=JSON.parse(t),n="label-atlas"===s.type?s.generatedFnt:s.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const sn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Wt.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Wt.getTargetTexture(s),width:e.width,height:e.height}},release(e){Wt.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Wt.releaseRenderTarget(e._handle),sn.create({width:t,height:s,depth:!0})),begin(e,t){Wt.begin(t,e._handle)},end(){Wt.end()},getDepthTexture:e=>Wt.getTargetDepthTexture(e._handle)};let nn=!1;const rn=[us,ws,Is,Ds,Hs];y||(y=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=x,exports.App=jt,exports.AssetPlugin=Ye,exports.AssetServer=Ge,exports.Assets=qe,exports.AsyncCache=Oe,exports.BitmapText=G,exports.BodyType=ee,exports.BoxCollider=K,exports.Button=Ss,exports.Camera=H,exports.Canvas=N,exports.CapsuleCollider=Z,exports.Children=X,exports.CircleCollider=Q,exports.ClearFlags=D,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=ue,exports.DEFAULT_DESIGN_HEIGHT=w,exports.DEFAULT_DESIGN_WIDTH=_,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=v,exports.Draw=pt,exports.EntityCommands=ce,exports.GLDebug=Lt,exports.Geometry=St,exports.INVALID_ENTITY=0,exports.INVALID_FONT=P,exports.INVALID_TEXTURE=b,exports.Input=ye,exports.InputPlugin=xe,exports.InputState=ge,exports.Interactable=vs,exports.LocalTransform=z,exports.Material=Fe,exports.MaterialLoader=He,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=V,exports.Physics=Js,exports.PhysicsEvents=js,exports.PhysicsPlugin=qs,exports.PostProcess=Mt,exports.PrefabServer=et,exports.Prefabs=tt,exports.PrefabsPlugin=st,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_)return;let e="fetch scene";try{const t=await s(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const r=new tn(this.baseUrl_);await r.prefetch(n);let o=null;const i=this.app_.spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await en(this.app_,this.app_.wasmModule,n,r,o),e="ensureCamera",this.ensureCamera()}catch(t){const s=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${s}\n${n}`),new Error(`[PreviewPlugin:${e}] ${s}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([H]);for(const n of s){if(e.get(n,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([N]);for(const r of n){const n=e.get(r,N);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=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(r,z,o);const i={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:D.ColorAndDepth};e.insert(r,H,i)}}},exports.ProjectionType=W,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ae(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=le,exports.RenderPipeline=Nt,exports.RenderTexture=sn,exports.Renderer=Wt,exports.Res=ne,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=J,exports.ScaleMode=$,exports.ScreenSpace=As,exports.ShaderSources=Le,exports.SpineAnimation=q,exports.Sprite=O,exports.SystemRunner=me,exports.Text=rs,exports.TextInput=$s,exports.TextInputPlugin=zs,exports.TextPlugin=cs,exports.TextRenderer=is,exports.Time=ie,exports.UICameraInfo=be,exports.UIEventQueue=Cs,exports.UIEvents=Ts,exports.UIInteraction=bs,exports.UIInteractionPlugin=Ws,exports.UILayoutPlugin=Rs,exports.UIMask=ds,exports.UIMaskPlugin=_s,exports.UIRect=os,exports.Velocity=j,exports.WebAssetProvider=tn,exports.World=ve,exports.WorldTransform=L,exports.addStartupSystem=function(e){fe().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){fe().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){fe().push({schedule:e,system:t})},exports.assetPlugin=Je,exports.clearDrawCallbacks=function(){Ot.clear()},exports.clearUserComponents=function(){T().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=Es,exports.createMaskProcessor=xs,exports.createWebApp=function(e,t){return function(e,t){const s=jt.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ct(e),Me(e),vt(e),Tt(e),Ut(e),$t(e);const r=new Nt;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r){const o=Gt(e,n,t,r),i=s.getResource(be);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(be,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=i();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Wt.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;Wt.resize(t,s),Mt.isInitialized()&&Mt.getPassCount()>0&&!Mt.isBypassed()&&Mt.resize(t,s);const d=Gt(e,n,t,s);if(l(t,s),0===d.length)r.render({registry:{_cpp:n},viewProjection:Vt,width:t,height:s,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}Wt.setViewport(0,0,t,s)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Je),s.addPlugin(nt),s.addPlugin(_e),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:rn,...t})},exports.defineComponent=A,exports.defineResource=se,exports.defineSystem=pe,exports.defineTag=E,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([Y]);for(const n of s){const s=e.get(n,Y);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getComponent=U,exports.getComponentDefaults=function(e){const t=U(e);return t?{...t._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=M,exports.initDrawAPI=ct,exports.initGLDebugAPI=$t,exports.initGeometryAPI=vt,exports.initMaterialAPI=Me,exports.initPostProcessAPI=Tt,exports.initRendererAPI=Ut,exports.inputPlugin=_e,exports.instantiatePrefab=Ke,exports.intersectRects=hs,exports.invertMatrix4=fs,exports.isBuiltinComponent=I,exports.isEditor=function(){return nn},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!nn},exports.isTextureRef=Se,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Xe,exports.loadPhysicsModule=Ns,exports.loadRuntimeScene=en,exports.loadSceneData=je,exports.loadSceneWithAssets=Ve,exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=gs,exports.prefabsPlugin=nt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=B,exports.registerComponentAssetFields=function(e,t){Ne.set(e,t)},exports.registerDrawCallback=function(e,t){Ot.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(qe);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ze,exports.screenToWorld=ms,exports.setEditorMode=function(e){nn=e},exports.shutdownDrawAPI=ut,exports.shutdownGLDebugAPI=zt,exports.shutdownGeometryAPI=bt,exports.shutdownMaterialAPI=Re,exports.shutdownPostProcessAPI=At,exports.shutdownRendererAPI=kt,exports.textInputPlugin=Hs,exports.textPlugin=us,exports.uiInteractionPlugin=Ds,exports.uiLayoutPlugin=Is,exports.uiMaskPlugin=ws,exports.uiPlugins=rn,exports.unregisterDrawCallback=Ht,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([H]);for(const n of s){const s=e.get(n,H);s&&(s.aspectRatio=t,e.insert(n,H,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.worldRectToScreen=ps,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=d();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=g,exports.wxLoadImage=m,exports.wxLoadImagePixels=async function(e){return g(await m(e))},exports.wxReadFile=h,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{d().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(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 9b364bbc6..797ebab95 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){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 l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let m=null;function g(){return m||(m=wx.getFileSystemManager()),m}function y(e){return new Promise((t,n)=>{g().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function _(e,t="utf-8"){return new Promise((n,s)=>{g().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{g().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=g();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,s)=>{g().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,P=null;function S(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function C(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return v||(v=wx.createCanvas(),v.width=e,v.height=t,P=v.getContext("2d")),(v.width<e||v.height<t)&&(v.width=Math.max(v.width,e),v.height=Math.max(v.height,t)),{canvas:v,ctx:P}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function E(e){return C(await S(e))}let M=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return _(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 n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},T=0,R=4294967295,F=4294967295,I=(e=0,t=0)=>({x:e,y:t}),U=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),B=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),k=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),$=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});let W=0;function z(e,t){const n=++W;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function D(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function H(e,t){const n=D(),s=n.get(e);if(s)return s;const r=z(e,t);return n.set(e,r),N(e,t,!1),r}function L(e){const t=D(),n=t.get(e);if(n)return n;const s=z(e,{});return t.set(e,s),N(e,{},!0),s}function O(e){return D().get(e)}function j(){D().clear()}function N(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function X(e){return!0===e._builtin}const V=new Map;function q(e,t){V.set(e,t)}function G(e){return V.get(e)??O(e)}function Y(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return V.set(e,n),n}const J=Y("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=Y("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=Y("Sprite",{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=Y("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),ee=Y("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=Y("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ne=Y("Parent",{entity:0}),se=Y("Children",{entities:[]}),re=Y("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F}),oe=Y("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function ae(e){const t=G(e);return t?{...t._default}:null}q("Name",ie);const le=Y("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=Y("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=Y("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=Y("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),he={Static:0,Kinematic:1,Dynamic:2};let fe=0;function pe(e,t){const n=++fe;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function me(e){return{_type:"res",_resource:e}}function ge(e){return{_type:"res_mut",_resource:e}}class ye{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 _e{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 ye(this.get(e),t=>this.set(e,t))}}const we=pe({delta:0,elapsed:0,frameCount:0},"Time");function xe(e){return{_type:"mut",_component:e}}function be(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ve(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{be(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Pe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>be(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...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(){const e=[];for(const t of this)e.push([...t]);return e}}function Se(){return{_type:"commands"}}class Ce{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=X(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 Ee{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ce(this,null);return this.spawned_.push(e),e}entity(e){return new Ce(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Me;!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"}(Me||(Me={}));let Ae=0;function Te(e,t,n){const s=++Ae;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Re(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Fe(e){Re().push({schedule:Me.Update,system:e})}function Ie(e){Re().push({schedule:Me.Startup,system:e})}function Ue(e,t){Re().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ee&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new Pe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ee(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ke{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 $e=pe(new ke,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new ke;e.insertResource($e,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Me.Last,Te([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new We;function De(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:De(e)}}return t}class He{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}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),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}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 X(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}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)}tryGet(e,t){return this.has(e,t)?this.get(e,t):null}remove(e,t){X(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,De(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 s=t.create(n);this.getStorage(t).set(e,s),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!X(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const Le=pe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Oe;function je(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"}(Oe||(Oe={}));let Ne=null,Xe=null,Ve=1;const qe=new Map;function Ge(e){Ne=e,Xe=e.getResourceManager(),rt()}function Ye(){0!==Ze&&Ne&&(Ne._free(Ze),Ze=0),qe.clear(),Ve=1,Qe=!1,Xe=null,Ne=null}function Je(){if(!Xe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Xe}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Ve++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Oe.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return qe.set(t,n),t},get:e=>qe.get(e),setUniform(e,t,n){const s=qe.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=qe.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=qe.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=qe.get(e);return t?.blendMode??Oe.Normal},setDepthTest(e,t){const n=qe.get(e);n&&(n.depthTest=t)},getShader(e){const t=qe.get(e);return t?.shader??0},release(e){qe.delete(e)},isValid:e=>qe.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Oe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=qe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ve++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return qe.set(n,s),n},toAssetData(e,t){const n=qe.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=qe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let nt=null;function st(e){const t=(0===Ze&&Ne&&(Ze=Ne._malloc(et)),Ze);if(0===t||!Ne)return{ptr:0,count:0};let n=0,s=0;const r=Ne.HEAPU8,o=Ne.HEAPU32,i=Ne.HEAPF32;for(const[a,l]of e){if(n+128>et)break;let e=tt.get(a);e||(nt||(nt=new TextEncoder),e=nt.encode(a),tt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function rt(){if(!Ne||Qe)return;Ne.materialDataProvider=(e,t,n,s,r)=>{const o=qe.get(e);if(!o)return Ne.HEAPU32[t>>2]=0,Ne.HEAPU32[n>>2]=0,Ne.HEAPU32[s>>2]=0,void(Ne.HEAPU32[r>>2]=0);Ne.HEAPU32[t>>2]=o.shader,Ne.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=st(o.uniforms);Ne.HEAPU32[s>>2]=i,Ne.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;const o=t();this.pending_.set(e,o);try{const t=await(n>0?Promise.race([o,new Promise((t,s)=>setTimeout(()=>s(new Error(`AsyncCache timeout: ${e} (${n}ms)`)),n))]):o);return this.cache_.set(e,t),t}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),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 at{constructor(e,t=""){this.cache_=new it,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Ke.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const lt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function ct(e,t){lt.set(e,t)}function ut(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function dt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function ht(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=G(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function ft(e,t){const n=e.getEntitiesWithComponents([Z]);for(const s of n){const n=e.get(s,Z);n&&(n.aspectRatio=t,e.insert(s,Z,n))}}function pt(e,t){const n=e.getEntitiesWithComponents([ie]);for(const s of n){const n=e.get(s,ie);if(n&&n.value===t)return s}return null}class mt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(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 at(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u=e.endsWith(".skel"),d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}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 dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);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,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??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:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 gt=pe(null,"Assets");class yt{build(e){const t=e.wasmModule;t?e.insertResource(gt,new mt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new yt;function wt(e,t){const n=e.getResource(gt);n&&n.registerEmbeddedAssets(t)}async function xt(e,t,n){const{entities:s,rootId:r}=await bt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await dt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function bt(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await bt(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};vt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function vt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Pt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return xt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const St=pe(null,"Prefabs");class Ct{constructor(){this.name="PrefabsPlugin",this.dependencies=[gt]}build(e){const t=e.getResource(gt);e.insertResource(St,new Pt(e.world,t))}}const Et=new Ct;let Mt=null,At=0,Tt=0,Rt=0;const Ft=new Float32Array(256);function It(e){Mt=e,At=Mt._malloc(64),Tt=Mt._malloc(64),Rt=Mt._malloc(1024)}function Ut(){Mt&&(At&&(Mt._free(At),At=0),Tt&&(Mt._free(Tt),Tt=0),Rt&&(Mt._free(Rt),Rt=0)),Mt=null}function Bt(){if(!Mt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Mt}const kt={r:1,g:1,b:1,a:1},$t={begin(e){const t=Bt();t.HEAPF32.set(e,At/4),t.draw_begin(At)},end(){Bt().draw_end()},line(e,t,n,s=1){Bt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){Bt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){Bt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){Bt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){Bt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=kt){Bt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=kt){Bt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Bt().draw_setLayer(e)},setDepth(e){Bt().draw_setDepth(e)},getDrawCallCount:()=>Mt?Mt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Mt?Mt.draw_getPrimitiveCount():0,setBlendMode(e){Bt().draw_setBlendMode(e)},setDepthTest(e){Bt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Bt();s.HEAPF32.set(n,Tt/4),s.draw_mesh(e,t,Tt)},drawMeshWithMaterial(e,t,n){const s=Bt(),r=Ke.get(t);if(!r)return;if($t.setBlendMode(r.blendMode),$t.setDepthTest(r.depthTest),0===r.uniforms.size)return void $t.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Tt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=zt(t);if(!(s<0)){if(je(n))Ft[o++]=10,Ft[o++]=s,Ft[o++]=n.slot??e++,Ft[o++]=n.textureId;else if("number"==typeof n)Ft[o++]=1,Ft[o++]=s,Ft[o++]=n;else if(Array.isArray(n)){Ft[o++]=n.length,Ft[o++]=s;for(let e=0;e<n.length;e++)Ft[o++]=n[e]}else"w"in n?(Ft[o++]=4,Ft[o++]=s,Ft[o++]=n.x,Ft[o++]=n.y,Ft[o++]=n.z,Ft[o++]=n.w):"z"in n?(Ft[o++]=3,Ft[o++]=s,Ft[o++]=n.x,Ft[o++]=n.y,Ft[o++]=n.z):(Ft[o++]=2,Ft[o++]=s,Ft[o++]=n.x,Ft[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Ft.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Rt/4),s.draw_meshWithUniforms(e,r.shader,Tt,Rt,o)):s.draw_mesh(e,r.shader,Tt)}},Wt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function zt(e){return Wt[e]??-1}var Dt;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Dt||(Dt={}));let Ht=null,Lt=0,Ot=0,jt=0;function Nt(e){Ht=e,Lt=Ht._malloc(262144),Ot=Ht._malloc(65536),jt=Ht._malloc(256)}function Xt(){Ht&&(Lt&&Ht._free(Lt),Ot&&Ht._free(Ot),jt&&Ht._free(jt),Lt=0,Ot=0,jt=0),Ht=null}function Vt(){if(!Ht)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ht}const qt={create(e){const t=Vt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Lt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,jt,r).set(o),t.geometry_init(n,Lt,s,jt,r,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,Ot,s).set(e.indices),t.geometry_setIndices16(n,Ot,s)}else{new Uint32Array(t.HEAPU8.buffer,Ot,s).set(e.indices),t.geometry_setIndices32(n,Ot,s)}}return n},updateVertices(e,t,n=0){const s=Vt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Lt/4),s.geometry_updateVertices(e,Lt,r,n)},release(e){e>0&&Vt().geometry_release(e)},isValid:e=>!(!Ht||e<=0)&&Ht.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return qt.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Dt.Float2},{name:"a_texCoord",type:Dt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return qt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Dt.Float2},{name:"a_texCoord",type:Dt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-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 qt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Dt.Float2},{name:"a_texCoord",type:Dt.Float2}],indices:new Uint16Array(i)})}};let Gt=null;function Yt(e){Gt=e}function Jt(){Gt&&Qt.isInitialized()&&Qt.shutdown(),Gt=null}function Kt(){if(!Gt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Gt}const Qt={init:(e,t)=>Kt().postprocess_init(e,t),shutdown(){Kt().postprocess_shutdown()},resize(e,t){Kt().postprocess_resize(e,t)},addPass:(e,t)=>Kt().postprocess_addPass(e,t),removePass(e){Kt().postprocess_removePass(e)},setEnabled(e,t){Kt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Kt().postprocess_isPassEnabled(e),setUniform(e,t,n){Kt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Kt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Kt().postprocess_begin()},end(){Kt().postprocess_end()},getPassCount:()=>Kt().postprocess_getPassCount(),isInitialized:()=>!!Gt&&Gt.postprocess_isInitialized(),setBypass(e){Kt().postprocess_setBypass(e)},isBypassed:()=>!Gt||Gt.postprocess_isBypassed(),createBlur:()=>Ke.createShader(Zt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ke.createShader(Zt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ke.createShader(Zt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(Zt,"#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")},Zt="#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 en;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(en||(en={}));let tn=null,nn=0;function sn(e){tn=e,nn=tn._malloc(64)}function rn(){tn&&nn&&(tn._free(nn),nn=0),tn=null}const on={init(e,t){tn?.renderer_init(e,t)},resize(e,t){tn?.renderer_resize(e,t)},begin(e,t){tn&&nn&&(tn.HEAPF32.set(e,nn/4),tn.renderer_begin(nn,t??0))},flush(){tn?.renderer_flush()},end(){tn?.renderer_end()},submitSprites(e){tn&&tn.renderer_submitSprites(e._cpp)},submitBitmapText(e){tn&&tn.renderer_submitBitmapText(e._cpp)},submitSpine(e){tn&&tn.renderer_submitSpine?.(e._cpp)},setStage(e){tn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>tn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){tn?.renderer_releaseTarget(e)},getTargetTexture:e=>tn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>tn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){tn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){tn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){tn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){tn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>tn?tn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>tn?{drawCalls:tn.renderer_getDrawCalls(),triangles:tn.renderer_getTriangles(),sprites:tn.renderer_getSprites(),text:tn.renderer_getText(),spine:tn.renderer_getSpine?.()??0,meshes:tn.renderer_getMeshes(),culled:tn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let an=null;function ln(e){an=e}function cn(){an=null}const un={enable(){an?.gl_enableErrorCheck(!0)},disable(){an?.gl_enableErrorCheck(!1)},check:e=>an?.gl_checkErrors(e)??0,diagnose(){an?.renderer_diagnose()}},dn=new Map;function hn(e,t){dn.set(e,t)}function fn(e){dn.delete(e)}function pn(){dn.clear()}class mn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(on.resize(s,r),Qt.isInitialized()&&Qt.getPassCount()>0&&Qt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),on.setViewport(0,0,s,r),on.clearBuffers(3),on.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),on.submitSprites(t),on.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):on.submitSpine(t),on.flush(),this.executeDrawCallbacks(n,o),on.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;on.setViewport(s.x,s.y,s.w,s.h),on.setScissor(s.x,s.y,s.w,s.h,!0),on.clearBuffers(r),on.setScissor(0,0,0,0,!1),on.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),on.submitSprites(t),on.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):on.submitSpine(t),on.flush(),this.executeDrawCallbacks(n,o),on.end()}executeDrawCallbacks(e,t){const n=dn;if(n.size>0){$t.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}$t.end();for(const e of s)fn(e)}}}class gn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(Me.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Me.FixedPreUpdate),this.runSchedule(Me.FixedUpdate),this.runSchedule(Me.FixedPostUpdate);this.runSchedule(Me.PreUpdate),this.runSchedule(Me.Update),this.runSchedule(Me.PostUpdate),this.runSchedule(Me.Last),requestAnimationFrame(this.mainLoop)},this.world_=new He,this.resources_=new _e;for(const e of Object.values(Me))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new gn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Me.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Me.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}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(we,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Me.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,cn(),rn(),Jt(),Xt(),Ye(),Ut()}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(we);t.delta=e,t.elapsed+=e,t.frameCount++}}function yn(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 _n=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function wn(e,t,n,s,r){const o=e*t/n,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=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function xn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=wn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=vn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Sn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=En(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Mn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const bn=new Float32Array(16);function vn(e,t,n,s,r,o){const i=bn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const Pn=new Float32Array(16);function Sn(e,t,n,s){const r=Pn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Cn=new Float32Array(16);function En(e,t,n){const s=Cn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function Mn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var An,Tn,Rn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(An||(An={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Tn||(Tn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Rn||(Rn={}));const Fn=H("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:An.Left,verticalAlign:Tn.Top,wordWrap:!0,overflow:Rn.Visible,lineHeight:1.2}),In=H("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Un{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Rn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===Rn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Tn.Top:x=u;break;case Tn.Middle:x=(p-w)/2;break;case Tn.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case An.Left:s=u;break;case An.Center:s=f/2;break;case An.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===Rn.Clip&&n.restore();const v=n.getImageData(0,0,f,p),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case An.Left:return"left";case An.Center:return"center";case An.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Bn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function kn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class $n{build(e){q("Text",Fn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Un(t),s=e.world,r=new Map;e.addSystemToSchedule(Me.PreUpdate,Te([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Fn));for(const e of r.keys())s.valid(e)&&s.has(e,Fn)||r.delete(e);const e=s.getEntitiesWithComponents([Fn]);for(const t of e){const e=s.get(t,Fn),o=s.has(t,In)?s.get(t,In):null,i=r.get(t);if(i&&!kn(i,e,o))continue;s.has(t,Q)||s.insert(t,Q,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,Q,l),r.set(t,Bn(e,o))}}))}}const Wn=new $n,zn=H("UIMask",{enabled:!0});function Dn(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Hn(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(d,f),[_,w]=m(h,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),P=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}function Ln(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,E=d*y-f*m,M=d*_-p*m,A=h*y-f*g,T=h*_-p*g,R=f*_-p*y;let F=w*R-x*T+b*A+v*M-P*E+S*C;return 0===F||(F=1/F,n[0]=(l*R-c*T+u*A)*F,n[1]=(o*T-r*R-i*A)*F,n[2]=(g*S-y*P+_*v)*F,n[3]=(f*P-h*S-p*v)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(y*b-m*S-_*x)*F,n[7]=(d*S-f*b+p*x)*F,n[8]=(a*T-l*M+u*C)*F,n[9]=(r*M-s*T-i*C)*F,n[10]=(m*P-g*b+_*w)*F,n[11]=(h*b-d*P-p*w)*F,n[12]=(l*E-a*A-c*C)*F,n[13]=(s*A-r*E+o*C)*F,n[14]=(g*x-m*v-y*w)*F,n[15]=(d*v-h*x+f*w)*F),n}function On(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function jn(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Nn(e,t,n,s,r,o,i){if(!e.has(t,In)||!e.has(t,K))return null;const a=e.get(t,In),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Hn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Xn(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([zn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,zn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,ne);){const e=t.get(s,ne);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=Nn(t,n,r,o,i,a,l);e&&(s=Dn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=Nn(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Vn{build(e){if(q("UIMask",zn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Xn(e.wasmModule,e.world))}}const qn=new Vn,Gn=H("Interactable",{enabled:!0}),Yn=H("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Jn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Jn||(Jn={}));const Kn=H("Button",{state:Jn.Normal,transition:null});class Qn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Zn=pe(new Qn,"UIEvents"),es=L("ScreenSpace");function ts(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function ns(e,t,n,s,r,o){if(!e.has(t,In))return;const i=e.get(t,In),a=ts(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,se))return;const c=e.get(t,se);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&ns(e,t,a.rect,a.centerX,a.centerY,!1)}class ss{build(e){q("UIRect",In);const t=e.world;e.addSystemToSchedule(Me.PreUpdate,Te([me(Le)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([es,In,J]);for(const e of o)ns(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const rs=new ss,os=new Float32Array(16),is=new Float32Array(16);let as=!0,ls=1;class cs{build(e){q("Interactable",Gn),q("Button",Kn);const t=e.world,n=new Qn;e.insertResource(Zn,n);let s=null,r=null;ls="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Me.PreUpdate,Te([me($e),me(Le)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Yn]);for(const e of i){const n=t.get(e,Yn);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*ls,l=o.screenH-e.mouseY*ls;!function(e){let t=!1;for(let n=0;n<16;n++)if(is[n]!==e[n]){t=!0;break}t&&(is.set(e),as=!0)}(o.viewProjection),as&&(Ln(o.viewProjection,os),as=!1);const c=On(a,l,os,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Gn,In,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Yn)||t.insert(e,Yn);if(!t.get(e,Gn).enabled)continue;const n=t.get(e,K),s=t.get(e,In),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(jn(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,Q)&&(n=t.get(e,Q).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Yn)){t.get(s,Yn).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Yn).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Yn);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Yn)){const e=t.get(r,Yn);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Me.Update,Te([],()=>{const e=t.getEntitiesWithComponents([Kn]);for(const n of e){if(t.has(n,Gn)||t.insert(n,Gn,{enabled:!0}),!t.has(n,Yn))continue;const e=t.get(n,Yn),s=t.get(n,Kn),r=t.get(n,Gn),o=s.state;if(r.enabled?e.pressed?s.state=Jn.Pressed:e.hovered?s.state=Jn.Hovered:s.state=Jn.Normal:s.state=Jn.Disabled,o!==s.state&&s.transition&&t.has(n,Q)){const e=t.get(n,Q),r=s.transition;switch(s.state){case Jn.Normal:e.color={...r.normalColor};break;case Jn.Hovered:e.color={...r.hoveredColor};break;case Jn.Pressed:e.color={...r.pressedColor};break;case Jn.Disabled:e.color={...r.disabledColor}}t.insert(n,Q,e)}}},{name:"ButtonSystem"}))}}const us=new cs,ds=H("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class hs{build(e){q("TextInput",ds);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,ds);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Zn).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;g();const t=n.get(e,ds);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function g(){if(null!==i&&n.valid(i)&&n.has(i,ds)){const e=n.get(i,ds);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function _(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ps(Math.max(r.width,a)),r.height=ps(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=fs(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=fs(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,Q);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,Q,v)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,ds);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Zn).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,ds)){const e=n.get(i,ds);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Me.PreUpdate,Te([me(Zn)],e=>{const t=n.getEntitiesWithComponents([ds,Gn]);for(const e of t){if(!n.has(e,Yn))continue;if(n.get(e,Yn).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([Gn]);for(const t of e){if(n.has(t,ds))continue;if(!n.has(t,Yn))continue;if(n.get(t,Yn).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Me.PreUpdate,Te([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,ds)))){n.get(i,ds).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,ds)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([ds,In]);for(const e of a){const t=n.get(e,ds);if(!t.dirty)continue;const s=n.get(e,In),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,Q)||n.insert(e,Q,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),_(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function fs(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ps(e){let t=1;for(;t<e;)t*=2;return t}const ms=new hs;async function gs(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const ys=pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),_s=pe(null,"PhysicsAPI");function ws(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function xs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class bs{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ys,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=gs(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const n of t){const t=e.world.get(n,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Me.PostUpdate,Te([me(we)],a=>{const l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=i.get(r,K);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=ws(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),vs(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=ws(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,ne)){const t=e.world.get(i,ne);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const n=e.world.get(t.entity,K),s=ws(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=xs(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,J,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(ys,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(_s,Ps._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function vs(e,t,n){const s=e.world;if(s.has(n,ce)){const e=s.get(n,ce);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ue)){const e=s.get(n,ue);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,de)){const e=s.get(n,de);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Ps{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Ps.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Ss(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Cs(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Es(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ms(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Ss(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=Cs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Ss(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new bs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=Ss(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Ke.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=ut(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,Q);r&&(r.texture=n[s.data.texture]||0,e.insert(t,Q,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,Q);n&&(n.material=r,e.insert(t,Q,n))}else if("SpineAnimation"===s.type){const n=e.get(t,oe);n&&(n.material=r,e.insert(t,oe,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,K)){const e=Es(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(gt);t&&t.setAddressableManifest(a)}}class As{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Ts{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_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new As(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await Ms(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Z]);for(const s of n){if(e.get(s,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([ee]);for(const r of s){const s=e.get(r,ee);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=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(r,J,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,Z,i)}}}const Rs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=on.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:on.getTargetTexture(n),width:e.width,height:e.height}},release(e){on.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(on.releaseRenderTarget(e._handle),Rs.create({width:t,height:n,depth:!0})),begin(e,t){on.begin(t,e._handle)},end(){on.end()},getDepthTexture:e=>on.getTargetDepthTexture(e._handle)};let Fs=!1;function Is(e){Fs=e}function Us(){return Fs}function Bs(){return!Fs}const ks=[Wn,qn,rs,us,ms];function $s(e,t){return function(e,t){const n=gn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),It(e),Ge(e),Nt(e),Yt(e),sn(e),ln(e);const r=new mn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=xn(e,s,t,r),i=n.getResource(Le);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Le,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;on.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;on.resize(t,n),Qt.isInitialized()&&Qt.getPassCount()>0&&!Qt.isBypassed()&&Qt.resize(t,n);const u=xn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:_n,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}on.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(Me.First,l),n.addSystemToSchedule(Me.Last,c),n.addPlugin(_t),n.addPlugin(Et),n.addPlugin(ze),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ks,...t})}M||(M=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return 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),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=A;export{gn as App,yt as AssetPlugin,mt as AssetServer,gt as Assets,it as AsyncCache,re as BitmapText,Oe as BlendMode,he as BodyType,ce as BoxCollider,Kn as Button,Jn as ButtonState,Z as Camera,ee as Canvas,de as CapsuleCollider,se as Children,ue as CircleCollider,Se as Commands,Ee as CommandsInstance,Dt as DataType,$t as Draw,Ce as EntityCommands,un as GLDebug,qt as Geometry,T as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,$e as Input,We as InputPlugin,ke as InputState,Gn as Interactable,J as LocalTransform,Ke as Material,at as MaterialLoader,xe as Mut,ie as Name,ne as Parent,Ps as Physics,ys as PhysicsEvents,bs as PhysicsPlugin,Qt as PostProcess,Pt as PrefabServer,St as Prefabs,Ct as PrefabsPlugin,Ts as PreviewPlugin,ve as Query,Pe as QueryInstance,mn as RenderPipeline,en as RenderStage,Rs as RenderTexture,on as Renderer,me as Res,ge as ResMut,le as RigidBody,Me as Schedule,es as ScreenSpace,ot as ShaderSources,oe as SpineAnimation,Q as Sprite,Be as SystemRunner,Fn as Text,An as TextAlign,ds as TextInput,hs as TextInputPlugin,Rn as TextOverflow,$n as TextPlugin,Un as TextRenderer,Tn as TextVerticalAlign,we as Time,Le as UICameraInfo,Qn as UIEventQueue,Zn as UIEvents,Yn as UIInteraction,cs as UIInteractionPlugin,ss as UILayoutPlugin,zn as UIMask,Vn as UIMaskPlugin,In as UIRect,te as Velocity,As as WebAssetProvider,He as World,K as WorldTransform,Ie as addStartupSystem,Fe as addSystem,Ue as addSystemToSchedule,_t as assetPlugin,pn as clearDrawCallbacks,j as clearUserComponents,k as color,ts as computeUIRectLayout,Xn as createMaskProcessor,$s as createWebApp,H as defineComponent,pe as defineResource,Te as defineSystem,L as defineTag,pt as findEntityByName,yn as flushPendingSystems,G as getComponent,ae as getComponentDefaults,t as getPlatform,s as getPlatformType,O as getUserComponent,It as initDrawAPI,ln as initGLDebugAPI,Nt as initGeometryAPI,Ge as initMaterialAPI,Yt as initPostProcessAPI,sn as initRendererAPI,ze as inputPlugin,xt as instantiatePrefab,Dn as intersectRects,Ln as invertMatrix4,X as isBuiltinComponent,Us as isEditor,n as isPlatformInitialized,Bs as isRuntime,je as isTextureRef,r as isWeChat,o as isWeb,ht as loadComponent,gs as loadPhysicsModule,Ms as loadRuntimeScene,ut as loadSceneData,dt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,jn as pointInWorldRect,Et as prefabsPlugin,$ as quat,q as registerComponent,ct as registerComponentAssetFields,hn as registerDrawCallback,wt as registerEmbeddedAssets,rt as registerMaterialCallback,On as screenToWorld,Is as setEditorMode,Ut as shutdownDrawAPI,cn as shutdownGLDebugAPI,Xt as shutdownGeometryAPI,Ye as shutdownMaterialAPI,Jt as shutdownPostProcessAPI,rn as shutdownRendererAPI,ms as textInputPlugin,Wn as textPlugin,us as uiInteractionPlugin,rs as uiLayoutPlugin,qn as uiMaskPlugin,ks as uiPlugins,fn as unregisterDrawCallback,ft as updateCameraAspectRatio,I as vec2,U as vec3,B as vec4,Hn as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,E as wxLoadImagePixels,y as wxReadFile,_ as wxReadTextFile,b as wxWriteFile};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){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 l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let m=null;function g(){return m||(m=wx.getFileSystemManager()),m}function y(e){return new Promise((t,n)=>{g().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function _(e,t="utf-8"){return new Promise((n,s)=>{g().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{g().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=g();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,s)=>{g().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function v(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function P(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function S(e){return P(await v(e))}let C=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return _(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 n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},M=1920,A=1080,T=100,R=512,F=0,I=4294967295,U=4294967295,B=(e=0,t=0)=>({x:e,y:t}),k=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),$=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),W=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),z=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});let D=0;function H(e,t){const n=++D;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function O(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const n=O(),s=n.get(e);if(s)return s;const r=H(e,t);return n.set(e,r),V(e,t,!1),r}function N(e){const t=O(),n=t.get(e);if(n)return n;const s=H(e,{});return t.set(e,s),V(e,{},!0),s}function j(e){return O().get(e)}function X(){O().clear()}function V(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function q(e){return!0===e._builtin}const G=new Map;function Y(e,t){G.set(e,t)}function J(e){return G.get(e)??j(e)}function K(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return G.set(e,n),n}const Q={Perspective:0,Orthographic:1},Z={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ee={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},te=K("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ne=K("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),se=K("Sprite",{texture:I,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),re=K("Camera",{projectionType:Q.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.ColorAndDepth}),oe=K("Canvas",{designResolution:{x:M,y:A},pixelsPerUnit:100,scaleMode:ee.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ie=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ae=K("Parent",{entity:0}),le=K("Children",{entities:[]}),ce=K("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:U}),ue=K("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),de={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function he(e){const t=J(e);return t?{...t._default}:null}Y("Name",de);const fe=K("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),pe=K("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),me=K("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ge=K("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ye={Static:0,Kinematic:1,Dynamic:2};let _e=0;function we(e,t){const n=++_e;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function xe(e){return{_type:"res",_resource:e}}function be(e){return{_type:"res_mut",_resource:e}}class ve{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 Pe{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 ve(this.get(e),t=>this.set(e,t))}}const Se=we({delta:0,elapsed:0,frameCount:0},"Time");function Ce(e){return{_type:"mut",_component:e}}function Ee(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Me(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{Ee(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Ee(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...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(){const e=[];for(const t of this)e.push([...t]);return e}}function Te(){return{_type:"commands"}}class Re{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=q(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 Fe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Re(this,null);return this.spawned_.push(e),e}entity(e){return new Re(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ie;!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"}(Ie||(Ie={}));let Ue=0;function Be(e,t,n){const s=++Ue;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function ke(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function $e(e){ke().push({schedule:Ie.Update,system:e})}function We(e){ke().push({schedule:Ie.Startup,system:e})}function ze(e,t){ke().push({schedule:e,system:t})}class De{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Fe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new Ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Fe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class He{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 Oe=we(new He,"Input");class Le{constructor(e){this.target_=e??null}build(e){const n=new He;e.insertResource(Oe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ie.Last,Be([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ne=new Le;function je(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:je(e)}}return t}class Xe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}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),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}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 q(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){return this.has(e,t)?this.get(e,t):null}remove(e,t){q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,je(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 s=t.create(n);this.getStorage(t).set(e,s),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!q(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const Ve=we({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var qe;function Ge(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"}(qe||(qe={}));let Ye=null,Je=null,Ke=1;const Qe=new Map;function Ze(e){Ye=e,Je=e.getResourceManager(),ct()}function et(){0!==rt&&Ye&&(Ye._free(rt),rt=0),Qe.clear(),Ke=1,st=!1,Je=null,Ye=null}function tt(){if(!Je)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Je}const nt={createShader:(e,t)=>tt().createShader(e,t),releaseShader(e){e>0&&tt().releaseShader(e)},create(e){const t=Ke++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??qe.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Qe.set(t,n),t},get:e=>Qe.get(e),setUniform(e,t,n){const s=Qe.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Qe.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Qe.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Qe.get(e);return t?.blendMode??qe.Normal},setDepthTest(e,t){const n=Qe.get(e);n&&(n.depthTest=t)},getShader(e){const t=Qe.get(e);return t?.shader??0},release(e){Qe.delete(e)},isValid:e=>Qe.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??qe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Qe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ke++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Qe.set(n,s),n},toAssetData(e,t){const n=Qe.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Qe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let st=!1,rt=0;const ot=4096,it=new Map;let at=null;function lt(e){const t=(0===rt&&Ye&&(rt=Ye._malloc(ot)),rt);if(0===t||!Ye)return{ptr:0,count:0};let n=0,s=0;const r=Ye.HEAPU8,o=Ye.HEAPU32,i=Ye.HEAPF32;for(const[a,l]of e){if(n+128>ot)break;let e=it.get(a);e||(at||(at=new TextEncoder),e=at.encode(a),it.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function ct(){if(!Ye||st)return;Ye.materialDataProvider=(e,t,n,s,r)=>{const o=Qe.get(e);if(!o)return Ye.HEAPU32[t>>2]=0,Ye.HEAPU32[n>>2]=0,Ye.HEAPU32[s>>2]=0,void(Ye.HEAPU32[r>>2]=0);Ye.HEAPU32[t>>2]=o.shader,Ye.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=lt(o.uniforms);Ye.HEAPU32[s>>2]=i,Ye.HEAPU32[r>>2]=a},st=!0}const ut={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 dt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;const o=t();this.pending_.set(e,o);try{const t=await(n>0?Promise.race([o,new Promise((t,s)=>setTimeout(()=>s(new Error(`AsyncCache timeout: ${e} (${n}ms)`)),n))]):o);return this.cache_.set(e,t),t}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),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 ht{constructor(e,t=""){this.cache_=new dt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(nt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())nt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:nt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const ft=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function pt(e,t){ft.set(e,t)}function mt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,de,{value:s.name}),!1!==s.visible)for(const n of s.components)yt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function gt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ft.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ft.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,de,{value:n.name}),!1!==n.visible)for(const s of n.components)yt(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function yt(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=J(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function _t(e,t){const n=e.getEntitiesWithComponents([re]);for(const s of n){const n=e.get(s,re);n&&(n.aspectRatio=t,e.insert(s,re,n))}}function wt(e,t){const n=e.getEntitiesWithComponents([de]);for(const s of n){const n=e.get(s,de);if(n&&n.value===t)return s}return null}class xt{constructor(e){this.textureCache_=new dt,this.shaderCache_=new dt,this.jsonCache_=new dt,this.textCache_=new dt,this.binaryCache_=new dt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new dt,this.prefabCache_=new dt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(R,R),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ht(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u=e.endsWith(".skel"),d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}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 gt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);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,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??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:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return nt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return nt.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 bt=we(null,"Assets");class vt{build(e){const t=e.wasmModule;t?e.insertResource(bt,new xt(t)):console.warn("AssetPlugin: No WASM module available")}}const Pt=new vt;function St(e,t){const n=e.getResource(bt);n&&n.registerEmbeddedAssets(t)}async function Ct(e,t,n){const{entities:s,rootId:r}=await Et(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await gt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Et(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Et(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Mt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function Mt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class At{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ct(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Tt=we(null,"Prefabs");class Rt{constructor(){this.name="PrefabsPlugin",this.dependencies=[bt]}build(e){const t=e.getResource(bt);e.insertResource(Tt,new At(e.world,t))}}const Ft=new Rt;let It=null,Ut=0,Bt=0,kt=0;const $t=new Float32Array(256);function Wt(e){It=e,Ut=It._malloc(64),Bt=It._malloc(64),kt=It._malloc(1024)}function zt(){It&&(Ut&&(It._free(Ut),Ut=0),Bt&&(It._free(Bt),Bt=0),kt&&(It._free(kt),kt=0)),It=null}function Dt(){if(!It)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return It}const Ht={r:1,g:1,b:1,a:1},Ot={begin(e){const t=Dt();t.HEAPF32.set(e,Ut/4),t.draw_begin(Ut)},end(){Dt().draw_end()},line(e,t,n,s=1){Dt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){Dt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){Dt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){Dt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){Dt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Ht){Dt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Ht){Dt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Dt().draw_setLayer(e)},setDepth(e){Dt().draw_setDepth(e)},getDrawCallCount:()=>It?It.draw_getDrawCallCount():0,getPrimitiveCount:()=>It?It.draw_getPrimitiveCount():0,setBlendMode(e){Dt().draw_setBlendMode(e)},setDepthTest(e){Dt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Dt();s.HEAPF32.set(n,Bt/4),s.draw_mesh(e,t,Bt)},drawMeshWithMaterial(e,t,n){const s=Dt(),r=nt.get(t);if(!r)return;if(Ot.setBlendMode(r.blendMode),Ot.setDepthTest(r.depthTest),0===r.uniforms.size)return void Ot.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Bt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Nt(t);if(!(s<0)){if(Ge(n))$t[o++]=10,$t[o++]=s,$t[o++]=n.slot??e++,$t[o++]=n.textureId;else if("number"==typeof n)$t[o++]=1,$t[o++]=s,$t[o++]=n;else if(Array.isArray(n)){$t[o++]=n.length,$t[o++]=s;for(let e=0;e<n.length;e++)$t[o++]=n[e]}else"w"in n?($t[o++]=4,$t[o++]=s,$t[o++]=n.x,$t[o++]=n.y,$t[o++]=n.z,$t[o++]=n.w):"z"in n?($t[o++]=3,$t[o++]=s,$t[o++]=n.x,$t[o++]=n.y,$t[o++]=n.z):($t[o++]=2,$t[o++]=s,$t[o++]=n.x,$t[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set($t.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),kt/4),s.draw_meshWithUniforms(e,r.shader,Bt,kt,o)):s.draw_mesh(e,r.shader,Bt)}},Lt={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 Nt(e){return Lt[e]??-1}var jt;!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"}(jt||(jt={}));let Xt=null,Vt=0,qt=0,Gt=0;function Yt(e){Xt=e,Vt=Xt._malloc(262144),qt=Xt._malloc(65536),Gt=Xt._malloc(256)}function Jt(){Xt&&(Vt&&Xt._free(Vt),qt&&Xt._free(qt),Gt&&Xt._free(Gt),Vt=0,qt=0,Gt=0),Xt=null}function Kt(){if(!Xt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Xt}const Qt={create(e){const t=Kt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Vt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Gt,r).set(o),t.geometry_init(n,Vt,s,Gt,r,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,qt,s).set(e.indices),t.geometry_setIndices16(n,qt,s)}else{new Uint32Array(t.HEAPU8.buffer,qt,s).set(e.indices),t.geometry_setIndices32(n,qt,s)}}return n},updateVertices(e,t,n=0){const s=Kt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Vt/4),s.geometry_updateVertices(e,Vt,r,n)},release(e){e>0&&Kt().geometry_release(e)},isValid:e=>!(!Xt||e<=0)&&Xt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Qt.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:jt.Float2},{name:"a_texCoord",type:jt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Qt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:jt.Float2},{name:"a_texCoord",type:jt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-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 Qt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:jt.Float2},{name:"a_texCoord",type:jt.Float2}],indices:new Uint16Array(i)})}};let Zt=null;function en(e){Zt=e}function tn(){Zt&&sn.isInitialized()&&sn.shutdown(),Zt=null}function nn(){if(!Zt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Zt}const sn={init:(e,t)=>nn().postprocess_init(e,t),shutdown(){nn().postprocess_shutdown()},resize(e,t){nn().postprocess_resize(e,t)},addPass:(e,t)=>nn().postprocess_addPass(e,t),removePass(e){nn().postprocess_removePass(e)},setEnabled(e,t){nn().postprocess_setPassEnabled(e,t)},isEnabled:e=>nn().postprocess_isPassEnabled(e),setUniform(e,t,n){nn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){nn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){nn().postprocess_begin()},end(){nn().postprocess_end()},getPassCount:()=>nn().postprocess_getPassCount(),isInitialized:()=>!!Zt&&Zt.postprocess_isInitialized(),setBypass(e){nn().postprocess_setBypass(e)},isBypassed:()=>!Zt||Zt.postprocess_isBypassed(),createBlur:()=>nt.createShader(rn,"#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:()=>nt.createShader(rn,"#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:()=>nt.createShader(rn,"#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:()=>nt.createShader(rn,"#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")},rn="#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 on;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(on||(on={}));let an=null,ln=0;function cn(e){an=e,ln=an._malloc(64)}function un(){an&&ln&&(an._free(ln),ln=0),an=null}const dn={init(e,t){an?.renderer_init(e,t)},resize(e,t){an?.renderer_resize(e,t)},begin(e,t){an&&ln&&(an.HEAPF32.set(e,ln/4),an.renderer_begin(ln,t??0))},flush(){an?.renderer_flush()},end(){an?.renderer_end()},submitSprites(e){an&&an.renderer_submitSprites(e._cpp)},submitBitmapText(e){an&&an.renderer_submitBitmapText(e._cpp)},submitSpine(e){an&&an.renderer_submitSpine?.(e._cpp)},setStage(e){an?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>an?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){an?.renderer_releaseTarget(e)},getTargetTexture:e=>an?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>an?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){an?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){an?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){an?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){an?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>an?an.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>an?{drawCalls:an.renderer_getDrawCalls(),triangles:an.renderer_getTriangles(),sprites:an.renderer_getSprites(),text:an.renderer_getText(),spine:an.renderer_getSpine?.()??0,meshes:an.renderer_getMeshes(),culled:an.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let hn=null;function fn(e){hn=e}function pn(){hn=null}const mn={enable(){hn?.gl_enableErrorCheck(!0)},disable(){hn?.gl_enableErrorCheck(!1)},check:e=>hn?.gl_checkErrors(e)??0,diagnose(){hn?.renderer_diagnose()}},gn=new Map;function yn(e,t){gn.set(e,t)}function _n(e){gn.delete(e)}function wn(){gn.clear()}class xn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(dn.resize(s,r),sn.isInitialized()&&sn.getPassCount()>0&&sn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),dn.setViewport(0,0,s,r),dn.clearBuffers(3),dn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),dn.submitSprites(t),dn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):dn.submitSpine(t),dn.flush(),this.executeDrawCallbacks(n,o),dn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;dn.setViewport(s.x,s.y,s.w,s.h),dn.setScissor(s.x,s.y,s.w,s.h,!0),dn.clearBuffers(r),dn.setScissor(0,0,0,0,!1),dn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),dn.submitSprites(t),dn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):dn.submitSpine(t),dn.flush(),this.executeDrawCallbacks(n,o),dn.end()}executeDrawCallbacks(e,t){const n=gn;if(n.size>0){Ot.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Ot.end();for(const e of s)_n(e)}}}class bn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(Ie.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ie.FixedPreUpdate),this.runSchedule(Ie.FixedUpdate),this.runSchedule(Ie.FixedPostUpdate);this.runSchedule(Ie.PreUpdate),this.runSchedule(Ie.Update),this.runSchedule(Ie.PostUpdate),this.runSchedule(Ie.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Xe,this.resources_=new Pe;for(const e of Object.values(Ie))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Ie.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ie.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}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 De(this.world_,this.resources_),this.resources_.insert(Se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ie.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,pn(),un(),tn(),Jt(),et(),zt()}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(Se);t.delta=e,t.elapsed+=e,t.frameCount++}}function vn(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 Pn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Sn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ee.FixedWidth:return o;case ee.FixedHeight:return i;case ee.Expand:return Math.max(o,i);case ee.Shrink:return Math.min(o,i);case ee.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Cn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===Q.Orthographic){if(h=r.orthoSize,o){h=Sn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Mn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Tn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Fn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:In(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const En=new Float32Array(16);function Mn(e,t,n,s,r,o){const i=En;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const An=new Float32Array(16);function Tn(e,t,n,s){const r=An;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Rn=new Float32Array(16);function Fn(e,t,n){const s=Rn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function In(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var Un,Bn,kn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Un||(Un={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Bn||(Bn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(kn||(kn={}));const $n=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Un.Left,verticalAlign:Bn.Top,wordWrap:!0,overflow:kn.Visible,lineHeight:1.2}),Wn=L("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class zn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(R,R),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===kn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===kn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Bn.Top:x=u;break;case Bn.Middle:x=(p-w)/2;break;case Bn.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case Un.Left:s=u;break;case Un.Center:s=f/2;break;case Un.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===kn.Clip&&n.restore();const v=n.getImageData(0,0,f,p),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Un.Left:return"left";case Un.Center:return"center";case Un.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Dn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Hn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class On{build(e){Y("Text",$n);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new zn(t),s=e.world,r=new Map;e.addSystemToSchedule(Ie.PreUpdate,Be([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,$n));for(const e of r.keys())s.valid(e)&&s.has(e,$n)||r.delete(e);const e=s.getEntitiesWithComponents([$n]);for(const t of e){const e=s.get(t,$n),o=s.has(t,Wn)?s.get(t,Wn):null,i=r.get(t);if(i&&!Hn(i,e,o))continue;s.has(t,se)||s.insert(t,se,{texture:I,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,se);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,se,l),r.set(t,Dn(e,o))}}))}}const Ln=new On,Nn=L("UIMask",{enabled:!0});function jn(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Xn(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(d,f),[_,w]=m(h,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),P=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}function Vn(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,E=d*y-f*m,M=d*_-p*m,A=h*y-f*g,T=h*_-p*g,R=f*_-p*y;let F=w*R-x*T+b*A+v*M-P*E+S*C;return 0===F||(F=1/F,n[0]=(l*R-c*T+u*A)*F,n[1]=(o*T-r*R-i*A)*F,n[2]=(g*S-y*P+_*v)*F,n[3]=(f*P-h*S-p*v)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(y*b-m*S-_*x)*F,n[7]=(d*S-f*b+p*x)*F,n[8]=(a*T-l*M+u*C)*F,n[9]=(r*M-s*T-i*C)*F,n[10]=(m*P-g*b+_*w)*F,n[11]=(h*b-d*P-p*w)*F,n[12]=(l*E-a*A-c*C)*F,n[13]=(s*A-r*E+o*C)*F,n[14]=(g*x-m*v-y*w)*F,n[15]=(d*v-h*x+f*w)*F),n}function qn(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Gn(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Yn(e,t,n,s,r,o,i){if(!e.has(t,Wn)||!e.has(t,ne))return null;const a=e.get(t,Wn),l=e.get(t,ne),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Xn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Jn(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Nn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Nn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,ae);){const e=t.get(s,ae);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=Yn(t,n,r,o,i,a,l);e&&(s=jn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=Yn(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Kn{build(e){if(Y("UIMask",Nn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Jn(e.wasmModule,e.world))}}const Qn=new Kn,Zn=L("Interactable",{enabled:!0}),es=L("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ts;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(ts||(ts={}));const ns=L("Button",{state:ts.Normal,transition:null});class ss{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const rs=we(new ss,"UIEvents"),os=N("ScreenSpace");function is(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function as(e,t,n,s,r,o){if(!e.has(t,Wn))return;const i=e.get(t,Wn),a=is(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,te);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,te,l),!e.has(t,le))return;const c=e.get(t,le);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&as(e,t,a.rect,a.centerX,a.centerY,!1)}class ls{build(e){Y("UIRect",Wn);const t=e.world;e.addSystemToSchedule(Ie.PreUpdate,Be([xe(Ve)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([os,Wn,te]);for(const e of o)as(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const cs=new ls,us=new Float32Array(16),ds=new Float32Array(16);let hs=!0,fs=1;class ps{build(e){Y("Interactable",Zn),Y("Button",ns);const t=e.world,n=new ss;e.insertResource(rs,n);let s=null,r=null;fs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ie.PreUpdate,Be([xe(Oe),xe(Ve)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([es]);for(const e of i){const n=t.get(e,es);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*fs,l=o.screenH-e.mouseY*fs;!function(e){let t=!1;for(let n=0;n<16;n++)if(ds[n]!==e[n]){t=!0;break}t&&(ds.set(e),hs=!0)}(o.viewProjection),hs&&(Vn(o.viewProjection,us),hs=!1);const c=qn(a,l,us,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Zn,Wn,ne]);let d=null,h=-1/0;for(const e of u){t.has(e,es)||t.insert(e,es);if(!t.get(e,Zn).enabled)continue;const n=t.get(e,ne),s=t.get(e,Wn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Gn(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,se)&&(n=t.get(e,se).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,es)){t.get(s,es).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,es).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,es);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,es)){const e=t.get(r,es);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ie.Update,Be([],()=>{const e=t.getEntitiesWithComponents([ns]);for(const n of e){if(t.has(n,Zn)||t.insert(n,Zn,{enabled:!0}),!t.has(n,es))continue;const e=t.get(n,es),s=t.get(n,ns),r=t.get(n,Zn),o=s.state;if(r.enabled?e.pressed?s.state=ts.Pressed:e.hovered?s.state=ts.Hovered:s.state=ts.Normal:s.state=ts.Disabled,o!==s.state&&s.transition&&t.has(n,se)){const e=t.get(n,se),r=s.transition;switch(s.state){case ts.Normal:e.color={...r.normalColor};break;case ts.Hovered:e.color={...r.hoveredColor};break;case ts.Pressed:e.color={...r.pressedColor};break;case ts.Disabled:e.color={...r.disabledColor}}t.insert(n,se,e)}}},{name:"ButtonSystem"}))}}const ms=new ps,gs=L("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class ys{build(e){Y("TextInput",gs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(R,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,gs);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(rs).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;g();const t=n.get(e,gs);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function g(){if(null!==i&&n.valid(i)&&n.has(i,gs)){const e=n.get(i,gs);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function _(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ws(Math.max(r.width,a)),r.height=ws(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=_s(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=_s(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,se);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,se,v)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,gs);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(rs).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,gs)){const e=n.get(i,gs);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Ie.PreUpdate,Be([xe(rs)],e=>{const t=n.getEntitiesWithComponents([gs,Zn]);for(const e of t){if(!n.has(e,es))continue;if(n.get(e,es).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([Zn]);for(const t of e){if(n.has(t,gs))continue;if(!n.has(t,es))continue;if(n.get(t,es).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ie.PreUpdate,Be([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,gs)))){n.get(i,gs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,gs)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([gs,Wn]);for(const e of a){const t=n.get(e,gs);if(!t.dirty)continue;const s=n.get(e,Wn),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,se)||n.insert(e,se,{texture:I,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),_(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function _s(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ws(e){let t=1;for(;t<e;)t*=2;return t}const xs=new ys;async function bs(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const vs=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ps=we(null,"PhysicsAPI");function Ss(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Cs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Es{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(vs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=bs(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([oe]);for(const n of t){const t=e.world.get(n,oe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Ie.PostUpdate,Be([xe(Se)],a=>{const l=i.getEntitiesWithComponents([fe,te,ne]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,fe),l=i.get(r,ne);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Ss(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ms(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ye.Kinematic){const e=Ss(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,te);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,ae)){const t=e.world.get(i,ae);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ne)){const n=e.world.get(t.entity,ne),s=Ss(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Cs(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,te,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(vs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ps,As._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Ms(e,t,n){const s=e.world;if(s.has(n,pe)){const e=s.get(n,pe);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,me)){const e=s.get(n,me);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ge)){const e=s.get(n,ge);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class As{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(As.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Ts(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Rs(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Fs(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Is(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Ts(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=Rs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Ts(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Es("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=Ts(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=nt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=nt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=mt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,se);r&&(r.texture=n[s.data.texture]||0,e.insert(t,se,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,ce);o&&(o.font=r,e.insert(t,ce,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,se);n&&(n.material=r,e.insert(t,se,n))}else if("SpineAnimation"===s.type){const n=e.get(t,ue);n&&(n.material=r,e.insert(t,ue,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,ue)?c.get(o,ue):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,ne)){const e=Fs(c.get(o,ne),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(bt);t&&t.setAddressableManifest(a)}}class Us{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Bs{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_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new Us(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await Is(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([re]);for(const s of n){if(e.get(s,re).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([oe]);for(const r of s){const s=e.get(r,oe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=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(r,te,o);const i={isActive:!0,projectionType:Q.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.ColorAndDepth};e.insert(r,re,i)}}}const ks={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=dn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:dn.getTargetTexture(n),width:e.width,height:e.height}},release(e){dn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(dn.releaseRenderTarget(e._handle),ks.create({width:t,height:n,depth:!0})),begin(e,t){dn.begin(t,e._handle)},end(){dn.end()},getDepthTexture:e=>dn.getTargetDepthTexture(e._handle)};let $s=!1;function Ws(e){$s=e}function zs(){return $s}function Ds(){return!$s}const Hs=[Ln,Qn,cs,ms,xs];function Os(e,t){return function(e,t){const n=bn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Wt(e),Ze(e),Yt(e),en(e),cn(e),fn(e);const r=new xn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Cn(e,s,t,r),i=n.getResource(Ve);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Ve,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;dn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;dn.resize(t,n),sn.isInitialized()&&sn.getPassCount()>0&&!sn.isBypassed()&&sn.resize(t,n);const u=Cn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Pn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}dn.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(Ie.First,l),n.addSystemToSchedule(Ie.Last,c),n.addPlugin(Pt),n.addPlugin(Ft),n.addPlugin(Ne),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Hs,...t})}C||(C=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return 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),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E;export{bn as App,vt as AssetPlugin,xt as AssetServer,bt as Assets,dt as AsyncCache,ce as BitmapText,qe as BlendMode,ye as BodyType,pe as BoxCollider,ns as Button,ts as ButtonState,re as Camera,oe as Canvas,ge as CapsuleCollider,le as Children,me as CircleCollider,Z as ClearFlags,Te as Commands,Fe as CommandsInstance,A as DEFAULT_DESIGN_HEIGHT,M as DEFAULT_DESIGN_WIDTH,T as DEFAULT_PIXELS_PER_UNIT,R as DEFAULT_TEXT_CANVAS_SIZE,jt as DataType,Ot as Draw,Re as EntityCommands,mn as GLDebug,Qt as Geometry,F as INVALID_ENTITY,U as INVALID_FONT,I as INVALID_TEXTURE,Oe as Input,Le as InputPlugin,He as InputState,Zn as Interactable,te as LocalTransform,nt as Material,ht as MaterialLoader,Ce as Mut,de as Name,ae as Parent,As as Physics,vs as PhysicsEvents,Es as PhysicsPlugin,sn as PostProcess,At as PrefabServer,Tt as Prefabs,Rt as PrefabsPlugin,Bs as PreviewPlugin,Q as ProjectionType,Me as Query,Ae as QueryInstance,xn as RenderPipeline,on as RenderStage,ks as RenderTexture,dn as Renderer,xe as Res,be as ResMut,fe as RigidBody,ee as ScaleMode,Ie as Schedule,os as ScreenSpace,ut as ShaderSources,ue as SpineAnimation,se as Sprite,De as SystemRunner,$n as Text,Un as TextAlign,gs as TextInput,ys as TextInputPlugin,kn as TextOverflow,On as TextPlugin,zn as TextRenderer,Bn as TextVerticalAlign,Se as Time,Ve as UICameraInfo,ss as UIEventQueue,rs as UIEvents,es as UIInteraction,ps as UIInteractionPlugin,ls as UILayoutPlugin,Nn as UIMask,Kn as UIMaskPlugin,Wn as UIRect,ie as Velocity,Us as WebAssetProvider,Xe as World,ne as WorldTransform,We as addStartupSystem,$e as addSystem,ze as addSystemToSchedule,Pt as assetPlugin,wn as clearDrawCallbacks,X as clearUserComponents,W as color,is as computeUIRectLayout,Jn as createMaskProcessor,Os as createWebApp,L as defineComponent,we as defineResource,Be as defineSystem,N as defineTag,wt as findEntityByName,vn as flushPendingSystems,J as getComponent,he as getComponentDefaults,t as getPlatform,s as getPlatformType,j as getUserComponent,Wt as initDrawAPI,fn as initGLDebugAPI,Yt as initGeometryAPI,Ze as initMaterialAPI,en as initPostProcessAPI,cn as initRendererAPI,Ne as inputPlugin,Ct as instantiatePrefab,jn as intersectRects,Vn as invertMatrix4,q as isBuiltinComponent,zs as isEditor,n as isPlatformInitialized,Ds as isRuntime,Ge as isTextureRef,r as isWeChat,o as isWeb,yt as loadComponent,bs as loadPhysicsModule,Is as loadRuntimeScene,mt as loadSceneData,gt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Gn as pointInWorldRect,Ft as prefabsPlugin,z as quat,Y as registerComponent,pt as registerComponentAssetFields,yn as registerDrawCallback,St as registerEmbeddedAssets,ct as registerMaterialCallback,qn as screenToWorld,Ws as setEditorMode,zt as shutdownDrawAPI,pn as shutdownGLDebugAPI,Jt as shutdownGeometryAPI,et as shutdownMaterialAPI,tn as shutdownPostProcessAPI,un as shutdownRendererAPI,xs as textInputPlugin,Ln as textPlugin,ms as uiInteractionPlugin,cs as uiLayoutPlugin,Qn as uiMaskPlugin,Hs as uiPlugins,_n as unregisterDrawCallback,_t as updateCameraAspectRatio,B as vec2,k as vec3,$ as vec4,Xn as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,P as wxGetImagePixels,v as wxLoadImage,S as wxLoadImagePixels,y as wxReadFile,_ as wxReadTextFile,b as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 369a19ce0..a8a406935 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1,3 +1,8 @@+declare const DEFAULT_DESIGN_WIDTH = 1920;+declare const DEFAULT_DESIGN_HEIGHT = 1080;+declare const DEFAULT_PIXELS_PER_UNIT = 100;+declare const DEFAULT_TEXT_CANVAS_SIZE = 512;+/*** @file types.ts* @brief Core type definitions for ESEngine SDK@@ -113,6 +118,26 @@ type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;declare function isBuiltinComponent(comp: AnyComponentDef): comp is BuiltinComponentDef<any>;declare function registerComponent(name: string, def: AnyComponentDef): void;declare function getComponent(name: string): AnyComponentDef | undefined;+declare const ProjectionType: {+ readonly Perspective: 0;+ readonly Orthographic: 1;+};+type ProjectionType = (typeof ProjectionType)[keyof typeof ProjectionType];+declare const ClearFlags: {+ readonly None: 0;+ readonly ColorOnly: 1;+ readonly DepthOnly: 2;+ readonly ColorAndDepth: 3;+};+type ClearFlags = (typeof ClearFlags)[keyof typeof ClearFlags];+declare const ScaleMode: {+ readonly FixedWidth: 0;+ readonly FixedHeight: 1;+ readonly Expand: 2;+ readonly Shrink: 3;+ readonly Match: 4;+};+type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];interface LocalTransformData {position: Vec3;rotation: Quat;@@ -2463,5 +2488,5 @@ declare const uiPlugins: Plugin[];declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponent, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, ScaleMode, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponent, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };export type { AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, 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 cfda02a39..ebbb967d6 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 s(){return e?.name??null}function r(){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 l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,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 s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,_=4294967295,g=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});let b=0;function P(e,t){const n=++b;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function S(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const n=S(),s=n.get(e);if(s)return s;const r=P(e,t);return n.set(e,r),T(e,t,!1),r}function E(e){const t=S(),n=t.get(e);if(n)return n;const s=P(e,{});return t.set(e,s),T(e,{},!0),s}function M(e){return S().get(e)}function A(){S().clear()}function T(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function R(e){return!0===e._builtin}const F=new Map;function I(e,t){F.set(e,t)}function U(e){return F.get(e)??M(e)}function B(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return F.set(e,n),n}const k=B("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=B("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=B("Sprite",{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),L=B("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),D=B("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),W=B("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),H=B("Parent",{entity:0}),O=B("Children",{entities:[]}),N=B("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_}),j=B("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),V={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function X(e){const t=U(e);return t?{...t._default}:null}I("Name",V);const Y=B("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),q=B("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),G=B("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),J=B("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),K={Static:0,Kinematic:1,Dynamic:2};let Q=0;function Z(e,t){const n=++Q;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function ee(e){return{_type:"res",_resource:e}}function te(e){return{_type:"res_mut",_resource:e}}class ne{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 se{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 ne(this.get(e),t=>this.set(e,t))}}const re=Z({delta:0,elapsed:0,frameCount:0},"Time");function oe(e){return{_type:"mut",_component:e}}function ie(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ae(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ie(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class le{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ie(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...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(){const e=[];for(const t of this)e.push([...t]);return e}}function ce(){return{_type:"commands"}}class ue{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=R(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 de{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ue(this,null);return this.spawned_.push(e),e}entity(e){return new ue(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var he;!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"}(he||(he={}));let fe=0;function pe(e,t,n){const s=++fe;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function me(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function _e(e){me().push({schedule:he.Update,system:e})}function ge(e){me().push({schedule:he.Startup,system:e})}function ye(e,t){me().push({schedule:e,system:t})}class we{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof de&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new le(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new de(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class xe{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 ve=Z(new xe,"Input");class be{constructor(e){this.target_=e??null}build(e){const n=new xe;e.insertResource(ve,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(he.Last,pe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Pe=new be;function Se(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Se(e)}}return t}class Ce{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}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),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}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 R(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return R(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return R(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){return this.has(e,t)?this.get(e,t):null}remove(e,t){R(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,Se(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 s=t.create(n);this.getStorage(t).set(e,s),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!R(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const Ee=Z({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Me;function Ae(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"}(Me||(Me={}));let Te=null,Re=null,Fe=1;const Ie=new Map;function Ue(e){Te=e,Re=e.getResourceManager(),Ne()}function Be(){0!==Le&&Te&&(Te._free(Le),Le=0),Ie.clear(),Fe=1,ze=!1,Re=null,Te=null}function ke(){if(!Re)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Re}const $e={createShader:(e,t)=>ke().createShader(e,t),releaseShader(e){e>0&&ke().releaseShader(e)},create(e){const t=Fe++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Me.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Ie.set(t,n),t},get:e=>Ie.get(e),setUniform(e,t,n){const s=Ie.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Ie.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ie.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ie.get(e);return t?.blendMode??Me.Normal},setDepthTest(e,t){const n=Ie.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ie.get(e);return t?.shader??0},release(e){Ie.delete(e)},isValid:e=>Ie.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Me.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ie.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Fe++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ie.set(n,s),n},toAssetData(e,t){const n=Ie.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Ie.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ze=!1,Le=0;const De=4096,We=new Map;let He=null;function Oe(e){const t=(0===Le&&Te&&(Le=Te._malloc(De)),Le);if(0===t||!Te)return{ptr:0,count:0};let n=0,s=0;const r=Te.HEAPU8,o=Te.HEAPU32,i=Te.HEAPF32;for(const[a,l]of e){if(n+128>De)break;let e=We.get(a);e||(He||(He=new TextEncoder),e=He.encode(a),We.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Ne(){if(!Te||ze)return;Te.materialDataProvider=(e,t,n,s,r)=>{const o=Ie.get(e);if(!o)return Te.HEAPU32[t>>2]=0,Te.HEAPU32[n>>2]=0,Te.HEAPU32[s>>2]=0,void(Te.HEAPU32[r>>2]=0);Te.HEAPU32[t>>2]=o.shader,Te.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Oe(o.uniforms);Te.HEAPU32[s>>2]=i,Te.HEAPU32[r>>2]=a},ze=!0}const je={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 Ve{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;const o=t();this.pending_.set(e,o);try{const t=await(n>0?Promise.race([o,new Promise((t,s)=>setTimeout(()=>s(new Error(`AsyncCache timeout: ${e} (${n}ms)`)),n))]):o);return this.cache_.set(e,t),t}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),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,t=""){this.cache_=new Ve,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&($e.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())$e.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:$e.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ye=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function qe(e,t){Ye.set(e,t)}function Ge(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,V,{value:s.name}),!1!==s.visible)for(const n of s.components)Ke(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Je(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ye.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ye.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,V,{value:n.name}),!1!==n.visible)for(const s of n.components)Ke(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Ke(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=U(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function Qe(e,t){const n=e.getEntitiesWithComponents([L]);for(const s of n){const n=e.get(s,L);n&&(n.aspectRatio=t,e.insert(s,L,n))}}function Ze(e,t){const n=e.getEntitiesWithComponents([V]);for(const s of n){const n=e.get(s,V);if(n&&n.value===t)return s}return null}class et{constructor(e){this.textureCache_=new Ve,this.shaderCache_=new Ve,this.jsonCache_=new Ve,this.textCache_=new Ve,this.binaryCache_=new Ve,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ve,this.prefabCache_=new Ve,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(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 Xe(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u=e.endsWith(".skel"),d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}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 Je(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);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,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??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:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return $e.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return $e.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 tt=Z(null,"Assets");class nt{build(e){const t=e.wasmModule;t?e.insertResource(tt,new et(t)):console.warn("AssetPlugin: No WASM module available")}}const st=new nt;function rt(e,t){const n=e.getResource(tt);n&&n.registerEmbeddedAssets(t)}async function ot(e,t,n){const{entities:s,rootId:r}=await it(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Je(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function it(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await it(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};at(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function at(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class lt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return ot(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ct=Z(null,"Prefabs");class ut{constructor(){this.name="PrefabsPlugin",this.dependencies=[tt]}build(e){const t=e.getResource(tt);e.insertResource(ct,new lt(e.world,t))}}const dt=new ut;let ht=null,ft=0,pt=0,mt=0;const _t=new Float32Array(256);function gt(e){ht=e,ft=ht._malloc(64),pt=ht._malloc(64),mt=ht._malloc(1024)}function yt(){ht&&(ft&&(ht._free(ft),ft=0),pt&&(ht._free(pt),pt=0),mt&&(ht._free(mt),mt=0)),ht=null}function wt(){if(!ht)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ht}const xt={r:1,g:1,b:1,a:1},vt={begin(e){const t=wt();t.HEAPF32.set(e,ft/4),t.draw_begin(ft)},end(){wt().draw_end()},line(e,t,n,s=1){wt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){wt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){wt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){wt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){wt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=xt){wt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=xt){wt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){wt().draw_setLayer(e)},setDepth(e){wt().draw_setDepth(e)},getDrawCallCount:()=>ht?ht.draw_getDrawCallCount():0,getPrimitiveCount:()=>ht?ht.draw_getPrimitiveCount():0,setBlendMode(e){wt().draw_setBlendMode(e)},setDepthTest(e){wt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=wt();s.HEAPF32.set(n,pt/4),s.draw_mesh(e,t,pt)},drawMeshWithMaterial(e,t,n){const s=wt(),r=$e.get(t);if(!r)return;if(vt.setBlendMode(r.blendMode),vt.setDepthTest(r.depthTest),0===r.uniforms.size)return void vt.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,pt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Pt(t);if(!(s<0)){if(Ae(n))_t[o++]=10,_t[o++]=s,_t[o++]=n.slot??e++,_t[o++]=n.textureId;else if("number"==typeof n)_t[o++]=1,_t[o++]=s,_t[o++]=n;else if(Array.isArray(n)){_t[o++]=n.length,_t[o++]=s;for(let e=0;e<n.length;e++)_t[o++]=n[e]}else"w"in n?(_t[o++]=4,_t[o++]=s,_t[o++]=n.x,_t[o++]=n.y,_t[o++]=n.z,_t[o++]=n.w):"z"in n?(_t[o++]=3,_t[o++]=s,_t[o++]=n.x,_t[o++]=n.y,_t[o++]=n.z):(_t[o++]=2,_t[o++]=s,_t[o++]=n.x,_t[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(_t.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),mt/4),s.draw_meshWithUniforms(e,r.shader,pt,mt,o)):s.draw_mesh(e,r.shader,pt)}},bt={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 Pt(e){return bt[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,Et=0,Mt=0,At=0;function Tt(e){Ct=e,Et=Ct._malloc(262144),Mt=Ct._malloc(65536),At=Ct._malloc(256)}function Rt(){Ct&&(Et&&Ct._free(Et),Mt&&Ct._free(Mt),At&&Ct._free(At),Et=0,Mt=0,At=0),Ct=null}function Ft(){if(!Ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ct}const It={create(e){const t=Ft(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Et/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,At,r).set(o),t.geometry_init(n,Et,s,At,r,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,Mt,s).set(e.indices),t.geometry_setIndices16(n,Mt,s)}else{new Uint32Array(t.HEAPU8.buffer,Mt,s).set(e.indices),t.geometry_setIndices32(n,Mt,s)}}return n},updateVertices(e,t,n=0){const s=Ft(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Et/4),s.geometry_updateVertices(e,Et,r,n)},release(e){e>0&&Ft().geometry_release(e)},isValid:e=>!(!Ct||e<=0)&&Ct.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return It.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:St.Float2},{name:"a_texCoord",type:St.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return It.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:St.Float2},{name:"a_texCoord",type:St.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-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 It.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 Bt(e){Ut=e}function kt(){Ut&&zt.isInitialized()&&zt.shutdown(),Ut=null}function $t(){if(!Ut)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ut}const zt={init:(e,t)=>$t().postprocess_init(e,t),shutdown(){$t().postprocess_shutdown()},resize(e,t){$t().postprocess_resize(e,t)},addPass:(e,t)=>$t().postprocess_addPass(e,t),removePass(e){$t().postprocess_removePass(e)},setEnabled(e,t){$t().postprocess_setPassEnabled(e,t)},isEnabled:e=>$t().postprocess_isPassEnabled(e),setUniform(e,t,n){$t().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){$t().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){$t().postprocess_begin()},end(){$t().postprocess_end()},getPassCount:()=>$t().postprocess_getPassCount(),isInitialized:()=>!!Ut&&Ut.postprocess_isInitialized(),setBypass(e){$t().postprocess_setBypass(e)},isBypassed:()=>!Ut||Ut.postprocess_isBypassed(),createBlur:()=>$e.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:()=>$e.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:()=>$e.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:()=>$e.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 Dt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Dt||(Dt={}));let Wt=null,Ht=0;function Ot(e){Wt=e,Ht=Wt._malloc(64)}function Nt(){Wt&&Ht&&(Wt._free(Ht),Ht=0),Wt=null}const jt={init(e,t){Wt?.renderer_init(e,t)},resize(e,t){Wt?.renderer_resize(e,t)},begin(e,t){Wt&&Ht&&(Wt.HEAPF32.set(e,Ht/4),Wt.renderer_begin(Ht,t??0))},flush(){Wt?.renderer_flush()},end(){Wt?.renderer_end()},submitSprites(e){Wt&&Wt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Wt&&Wt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Wt&&Wt.renderer_submitSpine?.(e._cpp)},setStage(e){Wt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Wt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Wt?.renderer_releaseTarget(e)},getTargetTexture:e=>Wt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Wt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Wt?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Wt?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Wt?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Wt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Wt?Wt.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Wt?{drawCalls:Wt.renderer_getDrawCalls(),triangles:Wt.renderer_getTriangles(),sprites:Wt.renderer_getSprites(),text:Wt.renderer_getText(),spine:Wt.renderer_getSpine?.()??0,meshes:Wt.renderer_getMeshes(),culled:Wt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Vt=null;function Xt(e){Vt=e}function Yt(){Vt=null}const qt={enable(){Vt?.gl_enableErrorCheck(!0)},disable(){Vt?.gl_enableErrorCheck(!1)},check:e=>Vt?.gl_checkErrors(e)??0,diagnose(){Vt?.renderer_diagnose()}},Gt=new Map;function Jt(e,t){Gt.set(e,t)}function Kt(e){Gt.delete(e)}function Qt(){Gt.clear()}class Zt{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(jt.resize(s,r),zt.isInitialized()&&zt.getPassCount()>0&&zt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),jt.setViewport(0,0,s,r),jt.clearBuffers(3),jt.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),jt.submitSprites(t),jt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):jt.submitSpine(t),jt.flush(),this.executeDrawCallbacks(n,o),jt.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;jt.setViewport(s.x,s.y,s.w,s.h),jt.setScissor(s.x,s.y,s.w,s.h,!0),jt.clearBuffers(r),jt.setScissor(0,0,0,0,!1),jt.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),jt.submitSprites(t),jt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):jt.submitSpine(t),jt.flush(),this.executeDrawCallbacks(n,o),jt.end()}executeDrawCallbacks(e,t){const n=Gt;if(n.size>0){vt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}vt.end();for(const e of s)Kt(e)}}}class en{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(he.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(he.FixedPreUpdate),this.runSchedule(he.FixedUpdate),this.runSchedule(he.FixedPostUpdate);this.runSchedule(he.PreUpdate),this.runSchedule(he.Update),this.runSchedule(he.PostUpdate),this.runSchedule(he.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Ce,this.resources_=new se;for(const e of Object.values(he))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new en}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(he.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(he.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}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 we(this.world_,this.resources_),this.resources_.insert(re,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(he.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Yt(),Nt(),kt(),Rt(),Be(),yt()}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(re);t.delta=e,t.elapsed+=e,t.frameCount++}}function tn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const nn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function sn(e,t,n,s,r){const o=e*t/n,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=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function rn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=sn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=an(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=cn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=dn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:hn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const on=new Float32Array(16);function an(e,t,n,s,r,o){const i=on;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const ln=new Float32Array(16);function cn(e,t,n,s){const r=ln;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const un=new Float32Array(16);function dn(e,t,n){const s=un;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function hn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var fn,pn,mn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(fn||(fn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(pn||(pn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(mn||(mn={}));const _n=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:fn.Left,verticalAlign:pn.Top,wordWrap:!0,overflow:mn.Visible,lineHeight:1.2}),gn=C("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class yn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===mn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===mn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case pn.Top:x=u;break;case pn.Middle:x=(p-w)/2;break;case pn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case fn.Left:s=u;break;case fn.Center:s=f/2;break;case fn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===mn.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case fn.Left:return"left";case fn.Center:return"center";case fn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function wn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function xn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class vn{build(e){I("Text",_n);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new yn(t),s=e.world,r=new Map;e.addSystemToSchedule(he.PreUpdate,pe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,_n));for(const e of r.keys())s.valid(e)&&s.has(e,_n)||r.delete(e);const e=s.getEntitiesWithComponents([_n]);for(const t of e){const e=s.get(t,_n),o=s.has(t,gn)?s.get(t,gn):null,i=r.get(t);if(i&&!xn(i,e,o))continue;s.has(t,z)||s.insert(t,z,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,z);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,z,l),r.set(t,wn(e,o))}}))}}const bn=new vn,Pn=C("UIMask",{enabled:!0});function Sn(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Cn(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(d,f),[y,w]=m(h,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function En(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*_-h*m,E=d*g-f*m,M=d*y-p*m,A=h*g-f*_,T=h*y-p*_,R=f*y-p*g;let F=w*R-x*T+v*A+b*M-P*E+S*C;return 0===F||(F=1/F,n[0]=(l*R-c*T+u*A)*F,n[1]=(o*T-r*R-i*A)*F,n[2]=(_*S-g*P+y*b)*F,n[3]=(f*P-h*S-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(g*v-m*S-y*x)*F,n[7]=(d*S-f*v+p*x)*F,n[8]=(a*T-l*M+u*C)*F,n[9]=(r*M-s*T-i*C)*F,n[10]=(m*P-_*v+y*w)*F,n[11]=(h*v-d*P-p*w)*F,n[12]=(l*E-a*A-c*C)*F,n[13]=(s*A-r*E+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(d*b-h*x+f*w)*F),n}function Mn(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function An(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Tn(e,t,n,s,r,o,i){if(!e.has(t,gn)||!e.has(t,$))return null;const a=e.get(t,gn),l=e.get(t,$),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Cn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Rn(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Pn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Pn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,H);){const e=t.get(s,H);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=Tn(t,n,r,o,i,a,l);e&&(s=Sn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=Tn(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Fn{build(e){if(I("UIMask",Pn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Rn(e.wasmModule,e.world))}}const In=new Fn,Un=C("Interactable",{enabled:!0}),Bn=C("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var kn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(kn||(kn={}));const $n=C("Button",{state:kn.Normal,transition:null});class zn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ln=Z(new zn,"UIEvents"),Dn=E("ScreenSpace");function Wn(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function Hn(e,t,n,s,r,o){if(!e.has(t,gn))return;const i=e.get(t,gn),a=Wn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,k);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,k,l),!e.has(t,O))return;const c=e.get(t,O);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Hn(e,t,a.rect,a.centerX,a.centerY,!1)}class On{build(e){I("UIRect",gn);const t=e.world;e.addSystemToSchedule(he.PreUpdate,pe([ee(Ee)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Dn,gn,k]);for(const e of o)Hn(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Nn=new On,jn=new Float32Array(16),Vn=new Float32Array(16);let Xn=!0,Yn=1;class qn{build(e){I("Interactable",Un),I("Button",$n);const t=e.world,n=new zn;e.insertResource(Ln,n);let s=null,r=null;Yn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(he.PreUpdate,pe([ee(ve),ee(Ee)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Bn]);for(const e of i){const n=t.get(e,Bn);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Yn,l=o.screenH-e.mouseY*Yn;!function(e){let t=!1;for(let n=0;n<16;n++)if(Vn[n]!==e[n]){t=!0;break}t&&(Vn.set(e),Xn=!0)}(o.viewProjection),Xn&&(En(o.viewProjection,jn),Xn=!1);const c=Mn(a,l,jn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Un,gn,$]);let d=null,h=-1/0;for(const e of u){t.has(e,Bn)||t.insert(e,Bn);if(!t.get(e,Un).enabled)continue;const n=t.get(e,$),s=t.get(e,gn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(An(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,z)&&(n=t.get(e,z).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Bn)){t.get(s,Bn).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Bn).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Bn);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Bn)){const e=t.get(r,Bn);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(he.Update,pe([],()=>{const e=t.getEntitiesWithComponents([$n]);for(const n of e){if(t.has(n,Un)||t.insert(n,Un,{enabled:!0}),!t.has(n,Bn))continue;const e=t.get(n,Bn),s=t.get(n,$n),r=t.get(n,Un),o=s.state;if(r.enabled?e.pressed?s.state=kn.Pressed:e.hovered?s.state=kn.Hovered:s.state=kn.Normal:s.state=kn.Disabled,o!==s.state&&s.transition&&t.has(n,z)){const e=t.get(n,z),r=s.transition;switch(s.state){case kn.Normal:e.color={...r.normalColor};break;case kn.Hovered:e.color={...r.hoveredColor};break;case kn.Pressed:e.color={...r.pressedColor};break;case kn.Disabled:e.color={...r.disabledColor}}t.insert(n,z,e)}}},{name:"ButtonSystem"}))}}const Gn=new qn,Jn=C("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Kn{build(e){I("TextInput",Jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,Jn);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Ln).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function _(e){if(i===e)return;g();const t=n.get(e,Jn);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function g(){if(null!==i&&n.valid(i)&&n.has(i,Jn)){const e=n.get(i,Jn);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function w(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Zn(Math.max(r.width,a)),r.height=Zn(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Qn(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Qn(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,z);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,z,b)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,Jn);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ln).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,Jn)){const e=n.get(i,Jn);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(he.PreUpdate,pe([ee(Ln)],e=>{const t=n.getEntitiesWithComponents([Jn,Un]);for(const e of t){if(!n.has(e,Bn))continue;if(n.get(e,Bn).justPressed)return void _(e)}if(null!==i){const e=n.getEntitiesWithComponents([Un]);for(const t of e){if(n.has(t,Jn))continue;if(!n.has(t,Bn))continue;if(n.get(t,Bn).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(he.PreUpdate,pe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Jn)))){n.get(i,Jn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Jn)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Jn,gn]);for(const e of a){const t=n.get(e,Jn);if(!t.dirty)continue;const s=n.get(e,gn),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,z)||n.insert(e,z,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),w(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Qn(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Zn(e){let t=1;for(;t<e;)t*=2;return t}const es=new Kn;async function ts(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const ns=Z({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ss=Z(null,"PhysicsAPI");function rs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function os(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class is{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ns,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ts(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([D]);for(const n of t){const t=e.world.get(n,D);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(he.PostUpdate,pe([ee(re)],a=>{const l=i.getEntitiesWithComponents([Y,k,$]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,Y),l=i.get(r,$);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=rs(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),as(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===K.Kinematic){const e=rs(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,k);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,H)){const t=e.world.get(i,H);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,$)){const n=e.world.get(t.entity,$),s=rs(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=os(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,k,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(ns,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ss,ls._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function as(e,t,n){const s=e.world;if(s.has(n,q)){const e=s.get(n,q);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,G)){const e=s.get(n,G);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,J)){const e=s.get(n,J);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ls{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(ls.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function cs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function us(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ds(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function hs(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=cs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=us(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=cs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new is("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=cs(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=$e.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=$e.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Ge(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,z);r&&(r.texture=n[s.data.texture]||0,e.insert(t,z,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,N);o&&(o.font=r,e.insert(t,N,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,z);n&&(n.material=r,e.insert(t,z,n))}else if("SpineAnimation"===s.type){const n=e.get(t,j);n&&(n.material=r,e.insert(t,j,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,j)?c.get(o,j):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,$)){const e=ds(c.get(o,$),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(tt);t&&t.setAddressableManifest(a)}}class fs{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class ps{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_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new fs(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await hs(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([L]);for(const s of n){if(e.get(s,L).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([D]);for(const r of s){const s=e.get(r,D);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=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(r,k,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,L,i)}}}const ms={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=jt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:jt.getTargetTexture(n),width:e.width,height:e.height}},release(e){jt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(jt.releaseRenderTarget(e._handle),ms.create({width:t,height:n,depth:!0})),begin(e,t){jt.begin(t,e._handle)},end(){jt.end()},getDepthTexture:e=>jt.getTargetDepthTexture(e._handle)};let _s=!1;function gs(e){_s=e}function ys(){return _s}function ws(){return!_s}const xs=[bn,In,Nn,Gn,es];function vs(e,t){return function(e,t){const n=en.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),gt(e),Ue(e),Tt(e),Bt(e),Ot(e),Xt(e);const r=new Zt;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=rn(e,s,t,r),i=n.getResource(Ee);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Ee,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;jt.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;jt.resize(t,n),zt.isInitialized()&&zt.getPassCount()>0&&!zt.isBypassed()&&zt.resize(t,n);const u=rn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:nn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}jt.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(he.First,l),n.addSystemToSchedule(he.Last,c),n.addPlugin(st),n.addPlugin(dt),n.addPlugin(Pe),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:xs,...t})}e=f;export{en as App,nt as AssetPlugin,et as AssetServer,tt as Assets,Ve as AsyncCache,N as BitmapText,Me as BlendMode,K as BodyType,q as BoxCollider,$n as Button,kn as ButtonState,L as Camera,D as Canvas,J as CapsuleCollider,O as Children,G as CircleCollider,ce as Commands,de as CommandsInstance,St as DataType,vt as Draw,ue as EntityCommands,qt as GLDebug,It as Geometry,p as INVALID_ENTITY,_ as INVALID_FONT,m as INVALID_TEXTURE,ve as Input,be as InputPlugin,xe as InputState,Un as Interactable,k as LocalTransform,$e as Material,Xe as MaterialLoader,oe as Mut,V as Name,H as Parent,ls as Physics,ns as PhysicsEvents,is as PhysicsPlugin,zt as PostProcess,lt as PrefabServer,ct as Prefabs,ut as PrefabsPlugin,ps as PreviewPlugin,ae as Query,le as QueryInstance,Zt as RenderPipeline,Dt as RenderStage,ms as RenderTexture,jt as Renderer,ee as Res,te as ResMut,Y as RigidBody,he as Schedule,Dn as ScreenSpace,je as ShaderSources,j as SpineAnimation,z as Sprite,we as SystemRunner,_n as Text,fn as TextAlign,Jn as TextInput,Kn as TextInputPlugin,mn as TextOverflow,vn as TextPlugin,yn as TextRenderer,pn as TextVerticalAlign,re as Time,Ee as UICameraInfo,zn as UIEventQueue,Ln as UIEvents,Bn as UIInteraction,qn as UIInteractionPlugin,On as UILayoutPlugin,Pn as UIMask,Fn as UIMaskPlugin,gn as UIRect,W as Velocity,fs as WebAssetProvider,Ce as World,$ as WorldTransform,ge as addStartupSystem,_e as addSystem,ye as addSystemToSchedule,st as assetPlugin,Qt as clearDrawCallbacks,A as clearUserComponents,x as color,Wn as computeUIRectLayout,Rn as createMaskProcessor,vs as createWebApp,C as defineComponent,Z as defineResource,pe as defineSystem,E as defineTag,Ze as findEntityByName,tn as flushPendingSystems,U as getComponent,X as getComponentDefaults,t as getPlatform,s as getPlatformType,M as getUserComponent,gt as initDrawAPI,Xt as initGLDebugAPI,Tt as initGeometryAPI,Ue as initMaterialAPI,Bt as initPostProcessAPI,Ot as initRendererAPI,Pe as inputPlugin,ot as instantiatePrefab,Sn as intersectRects,En as invertMatrix4,R as isBuiltinComponent,ys as isEditor,n as isPlatformInitialized,ws as isRuntime,Ae as isTextureRef,r as isWeChat,o as isWeb,Ke as loadComponent,ts as loadPhysicsModule,hs as loadRuntimeScene,Ge as loadSceneData,Je as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,An as pointInWorldRect,dt as prefabsPlugin,v as quat,I as registerComponent,qe as registerComponentAssetFields,Jt as registerDrawCallback,rt as registerEmbeddedAssets,Ne as registerMaterialCallback,Mn as screenToWorld,gs as setEditorMode,yt as shutdownDrawAPI,Yt as shutdownGLDebugAPI,Rt as shutdownGeometryAPI,Be as shutdownMaterialAPI,kt as shutdownPostProcessAPI,Nt as shutdownRendererAPI,es as textInputPlugin,bn as textPlugin,Gn as uiInteractionPlugin,Nn as uiLayoutPlugin,In as uiMaskPlugin,xs as uiPlugins,Kt as unregisterDrawCallback,Qe as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,Cn as worldRectToScreen};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){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 l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,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 s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,m=1080,_=100,g=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),P=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),S=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),C=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});let E=0;function M(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function A(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function T(e,t){const n=A(),s=n.get(e);if(s)return s;const r=M(e,t);return n.set(e,r),U(e,t,!1),r}function R(e){const t=A(),n=t.get(e);if(n)return n;const s=M(e,{});return t.set(e,s),U(e,{},!0),s}function F(e){return A().get(e)}function I(){A().clear()}function U(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function B(e){return!0===e._builtin}const k=new Map;function $(e,t){k.set(e,t)}function z(e){return k.get(e)??F(e)}function L(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return k.set(e,n),n}const D={Perspective:0,Orthographic:1},W={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},H={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},O=L("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),N=L("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),j=L("Sprite",{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),V=L("Camera",{projectionType:D.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:W.ColorAndDepth}),X=L("Canvas",{designResolution:{x:p,y:m},pixelsPerUnit:100,scaleMode:H.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Y=L("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),q=L("Parent",{entity:0}),G=L("Children",{entities:[]}),J=L("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),K=L("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Q={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function Z(e){const t=z(e);return t?{...t._default}:null}$("Name",Q);const ee=L("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),te=L("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ne=L("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),se=L("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re={Static:0,Kinematic:1,Dynamic:2};let oe=0;function ie(e,t){const n=++oe;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function ae(e){return{_type:"res",_resource:e}}function le(e){return{_type:"res_mut",_resource:e}}class ce{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 ue{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 ce(this.get(e),t=>this.set(e,t))}}const he=ie({delta:0,elapsed:0,frameCount:0},"Time");function de(e){return{_type:"mut",_component:e}}function fe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function pe(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{fe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class me{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>fe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const h of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(h,t[n])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=h}yield a}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...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(){const e=[];for(const t of this)e.push([...t]);return e}}function _e(){return{_type:"commands"}}class ge{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=B(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 ye{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ge(this,null);return this.spawned_.push(e),e}entity(e){return new ge(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var we;!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"}(we||(we={}));let xe=0;function ve(e,t,n){const s=++xe;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function be(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Pe(e){be().push({schedule:we.Update,system:e})}function Se(e){be().push({schedule:we.Startup,system:e})}function Ce(e,t){be().push({schedule:e,system:t})}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ye&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new me(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ye(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Ae=ie(new Me,"Input");class Te{constructor(e){this.target_=e??null}build(e){const n=new Me;e.insertResource(Ae,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(we.Last,ve([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Re=new Te;function Fe(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Fe(e)}}return t}class Ie{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}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),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}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 B(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return B(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return B(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){return this.has(e,t)?this.get(e,t):null}remove(e,t){B(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,Fe(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 s=t.create(n);this.getStorage(t).set(e,s),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!B(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const Ue=ie({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Be;function ke(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"}(Be||(Be={}));let $e=null,ze=null,Le=1;const De=new Map;function We(e){$e=e,ze=e.getResourceManager(),Je()}function He(){0!==Ve&&$e&&($e._free(Ve),Ve=0),De.clear(),Le=1,je=!1,ze=null,$e=null}function Oe(){if(!ze)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ze}const Ne={createShader:(e,t)=>Oe().createShader(e,t),releaseShader(e){e>0&&Oe().releaseShader(e)},create(e){const t=Le++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Be.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return De.set(t,n),t},get:e=>De.get(e),setUniform(e,t,n){const s=De.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=De.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=De.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=De.get(e);return t?.blendMode??Be.Normal},setDepthTest(e,t){const n=De.get(e);n&&(n.depthTest=t)},getShader(e){const t=De.get(e);return t?.shader??0},release(e){De.delete(e)},isValid:e=>De.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Be.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=De.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Le++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return De.set(n,s),n},toAssetData(e,t){const n=De.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=De.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let je=!1,Ve=0;const Xe=4096,Ye=new Map;let qe=null;function Ge(e){const t=(0===Ve&&$e&&(Ve=$e._malloc(Xe)),Ve);if(0===t||!$e)return{ptr:0,count:0};let n=0,s=0;const r=$e.HEAPU8,o=$e.HEAPU32,i=$e.HEAPF32;for(const[a,l]of e){if(n+128>Xe)break;let e=Ye.get(a);e||(qe||(qe=new TextEncoder),e=qe.encode(a),Ye.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Je(){if(!$e||je)return;$e.materialDataProvider=(e,t,n,s,r)=>{const o=De.get(e);if(!o)return $e.HEAPU32[t>>2]=0,$e.HEAPU32[n>>2]=0,$e.HEAPU32[s>>2]=0,void($e.HEAPU32[r>>2]=0);$e.HEAPU32[t>>2]=o.shader,$e.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Ge(o.uniforms);$e.HEAPU32[s>>2]=i,$e.HEAPU32[r>>2]=a},je=!0}const Ke={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Qe{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;const o=t();this.pending_.set(e,o);try{const t=await(n>0?Promise.race([o,new Promise((t,s)=>setTimeout(()=>s(new Error(`AsyncCache timeout: ${e} (${n}ms)`)),n))]):o);return this.cache_.set(e,t),t}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),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 Ze{constructor(e,t=""){this.cache_=new Qe,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ne.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ne.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Ne.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const et=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function tt(e,t){et.set(e,t)}function nt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Q,{value:s.name}),!1!==s.visible)for(const n of s.components)rt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function st(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=et.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)d.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)d.push((async()=>{try{const s=await t.loadBitmapFont(e,n);h.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=et.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=h.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Q,{value:n.name}),!1!==n.visible)for(const s of n.components)rt(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function rt(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=z(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function ot(e,t){const n=e.getEntitiesWithComponents([V]);for(const s of n){const n=e.get(s,V);n&&(n.aspectRatio=t,e.insert(s,V,n))}}function it(e,t){const n=e.getEntitiesWithComponents([Q]);for(const s of n){const n=e.get(s,Q);if(n&&n.value===t)return s}return null}class at{constructor(e){this.textureCache_=new Qe,this.shaderCache_=new Qe,this.jsonCache_=new Qe,this.textCache_=new Qe,this.binaryCache_=new Qe,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Qe,this.prefabCache_=new Qe,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=h(g,g),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Ze(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u=e.endsWith(".skel"),h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}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 st(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);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,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??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:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Ne.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Ne.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await 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 s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 lt=ie(null,"Assets");class ct{build(e){const t=e.wasmModule;t?e.insertResource(lt,new at(t)):console.warn("AssetPlugin: No WASM module available")}}const ut=new ct;function ht(e,t){const n=e.getResource(lt);n&&n.registerEmbeddedAssets(t)}async function dt(e,t,n){const{entities:s,rootId:r}=await ft(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await st(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function ft(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await ft(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};pt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function pt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class mt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return dt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const _t=ie(null,"Prefabs");class gt{constructor(){this.name="PrefabsPlugin",this.dependencies=[lt]}build(e){const t=e.getResource(lt);e.insertResource(_t,new mt(e.world,t))}}const yt=new gt;let wt=null,xt=0,vt=0,bt=0;const Pt=new Float32Array(256);function St(e){wt=e,xt=wt._malloc(64),vt=wt._malloc(64),bt=wt._malloc(1024)}function Ct(){wt&&(xt&&(wt._free(xt),xt=0),vt&&(wt._free(vt),vt=0),bt&&(wt._free(bt),bt=0)),wt=null}function Et(){if(!wt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return wt}const Mt={r:1,g:1,b:1,a:1},At={begin(e){const t=Et();t.HEAPF32.set(e,xt/4),t.draw_begin(xt)},end(){Et().draw_end()},line(e,t,n,s=1){Et().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){Et().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){Et().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){Et().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){Et().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Mt){Et().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Mt){Et().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Et().draw_setLayer(e)},setDepth(e){Et().draw_setDepth(e)},getDrawCallCount:()=>wt?wt.draw_getDrawCallCount():0,getPrimitiveCount:()=>wt?wt.draw_getPrimitiveCount():0,setBlendMode(e){Et().draw_setBlendMode(e)},setDepthTest(e){Et().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Et();s.HEAPF32.set(n,vt/4),s.draw_mesh(e,t,vt)},drawMeshWithMaterial(e,t,n){const s=Et(),r=Ne.get(t);if(!r)return;if(At.setBlendMode(r.blendMode),At.setDepthTest(r.depthTest),0===r.uniforms.size)return void At.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,vt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Rt(t);if(!(s<0)){if(ke(n))Pt[o++]=10,Pt[o++]=s,Pt[o++]=n.slot??e++,Pt[o++]=n.textureId;else if("number"==typeof n)Pt[o++]=1,Pt[o++]=s,Pt[o++]=n;else if(Array.isArray(n)){Pt[o++]=n.length,Pt[o++]=s;for(let e=0;e<n.length;e++)Pt[o++]=n[e]}else"w"in n?(Pt[o++]=4,Pt[o++]=s,Pt[o++]=n.x,Pt[o++]=n.y,Pt[o++]=n.z,Pt[o++]=n.w):"z"in n?(Pt[o++]=3,Pt[o++]=s,Pt[o++]=n.x,Pt[o++]=n.y,Pt[o++]=n.z):(Pt[o++]=2,Pt[o++]=s,Pt[o++]=n.x,Pt[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Pt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),bt/4),s.draw_meshWithUniforms(e,r.shader,vt,bt,o)):s.draw_mesh(e,r.shader,vt)}},Tt={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 Rt(e){return Tt[e]??-1}var Ft;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Ft||(Ft={}));let It=null,Ut=0,Bt=0,kt=0;function $t(e){It=e,Ut=It._malloc(262144),Bt=It._malloc(65536),kt=It._malloc(256)}function zt(){It&&(Ut&&It._free(Ut),Bt&&It._free(Bt),kt&&It._free(kt),Ut=0,Bt=0,kt=0),It=null}function Lt(){if(!It)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return It}const Dt={create(e){const t=Lt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ut/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,kt,r).set(o),t.geometry_init(n,Ut,s,kt,r,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,Bt,s).set(e.indices),t.geometry_setIndices16(n,Bt,s)}else{new Uint32Array(t.HEAPU8.buffer,Bt,s).set(e.indices),t.geometry_setIndices32(n,Bt,s)}}return n},updateVertices(e,t,n=0){const s=Lt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Ut/4),s.geometry_updateVertices(e,Ut,r,n)},release(e){e>0&&Lt().geometry_release(e)},isValid:e=>!(!It||e<=0)&&It.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Dt.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Ft.Float2},{name:"a_texCoord",type:Ft.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Dt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Ft.Float2},{name:"a_texCoord",type:Ft.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-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 Dt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Ft.Float2},{name:"a_texCoord",type:Ft.Float2}],indices:new Uint16Array(i)})}};let Wt=null;function Ht(e){Wt=e}function Ot(){Wt&&jt.isInitialized()&&jt.shutdown(),Wt=null}function Nt(){if(!Wt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Wt}const jt={init:(e,t)=>Nt().postprocess_init(e,t),shutdown(){Nt().postprocess_shutdown()},resize(e,t){Nt().postprocess_resize(e,t)},addPass:(e,t)=>Nt().postprocess_addPass(e,t),removePass(e){Nt().postprocess_removePass(e)},setEnabled(e,t){Nt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Nt().postprocess_isPassEnabled(e),setUniform(e,t,n){Nt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Nt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Nt().postprocess_begin()},end(){Nt().postprocess_end()},getPassCount:()=>Nt().postprocess_getPassCount(),isInitialized:()=>!!Wt&&Wt.postprocess_isInitialized(),setBypass(e){Nt().postprocess_setBypass(e)},isBypassed:()=>!Wt||Wt.postprocess_isBypassed(),createBlur:()=>Ne.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:()=>Ne.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:()=>Ne.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:()=>Ne.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 Xt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Xt||(Xt={}));let Yt=null,qt=0;function Gt(e){Yt=e,qt=Yt._malloc(64)}function Jt(){Yt&&qt&&(Yt._free(qt),qt=0),Yt=null}const Kt={init(e,t){Yt?.renderer_init(e,t)},resize(e,t){Yt?.renderer_resize(e,t)},begin(e,t){Yt&&qt&&(Yt.HEAPF32.set(e,qt/4),Yt.renderer_begin(qt,t??0))},flush(){Yt?.renderer_flush()},end(){Yt?.renderer_end()},submitSprites(e){Yt&&Yt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Yt&&Yt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Yt&&Yt.renderer_submitSpine?.(e._cpp)},setStage(e){Yt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Yt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Yt?.renderer_releaseTarget(e)},getTargetTexture:e=>Yt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Yt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Yt?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Yt?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Yt?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Yt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Yt?Yt.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Yt?{drawCalls:Yt.renderer_getDrawCalls(),triangles:Yt.renderer_getTriangles(),sprites:Yt.renderer_getSprites(),text:Yt.renderer_getText(),spine:Yt.renderer_getSpine?.()??0,meshes:Yt.renderer_getMeshes(),culled:Yt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Qt=null;function Zt(e){Qt=e}function en(){Qt=null}const tn={enable(){Qt?.gl_enableErrorCheck(!0)},disable(){Qt?.gl_enableErrorCheck(!1)},check:e=>Qt?.gl_checkErrors(e)??0,diagnose(){Qt?.renderer_diagnose()}},nn=new Map;function sn(e,t){nn.set(e,t)}function rn(e){nn.delete(e)}function on(){nn.clear()}class an{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Kt.resize(s,r),jt.isInitialized()&&jt.getPassCount()>0&&jt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Kt.setViewport(0,0,s,r),Kt.clearBuffers(3),Kt.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Kt.submitSprites(t),Kt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Kt.submitSpine(t),Kt.flush(),this.executeDrawCallbacks(n,o),Kt.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Kt.setViewport(s.x,s.y,s.w,s.h),Kt.setScissor(s.x,s.y,s.w,s.h,!0),Kt.clearBuffers(r),Kt.setScissor(0,0,0,0,!1),Kt.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Kt.submitSprites(t),Kt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Kt.submitSpine(t),Kt.flush(),this.executeDrawCallbacks(n,o),Kt.end()}executeDrawCallbacks(e,t){const n=nn;if(n.size>0){At.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}At.end();for(const e of s)rn(e)}}}class ln{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(we.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(we.FixedPreUpdate),this.runSchedule(we.FixedUpdate),this.runSchedule(we.FixedPostUpdate);this.runSchedule(we.PreUpdate),this.runSchedule(we.Update),this.runSchedule(we.PostUpdate),this.runSchedule(we.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Ie,this.resources_=new ue;for(const e of Object.values(we))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ln}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(we.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(we.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}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 Ee(this.world_,this.resources_),this.resources_.insert(he,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(we.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,en(),Jt(),Ot(),zt(),He(),Ct()}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(he);t.delta=e,t.elapsed+=e,t.frameCount++}}function cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const un=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function hn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case H.FixedWidth:return o;case H.FixedHeight:return i;case H.Expand:return Math.max(o,i);case H.Shrink:return Math.min(o,i);case H.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function dn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,h=0,d=0;if(r.projectionType===D.Orthographic){if(d=r.orthoSize,o){d=hn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=pn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=_n(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=yn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:wn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const fn=new Float32Array(16);function pn(e,t,n,s,r,o){const i=fn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const mn=new Float32Array(16);function _n(e,t,n,s){const r=mn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const gn=new Float32Array(16);function yn(e,t,n){const s=gn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function wn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var xn,vn,bn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(xn||(xn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(vn||(vn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(bn||(bn={}));const Pn=T("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:xn.Left,verticalAlign:vn.Top,wordWrap:!0,overflow:bn.Visible,lineHeight:1.2}),Sn=T("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Cn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(g,g),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===bn.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===bn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case vn.Top:x=u;break;case vn.Middle:x=(p-w)/2;break;case vn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case xn.Left:s=u;break;case xn.Center:s=f/2;break;case xn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===bn.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case xn.Left:return"left";case xn.Center:return"center";case xn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function En(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Mn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class An{build(e){$("Text",Pn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Cn(t),s=e.world,r=new Map;e.addSystemToSchedule(we.PreUpdate,ve([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Pn));for(const e of r.keys())s.valid(e)&&s.has(e,Pn)||r.delete(e);const e=s.getEntitiesWithComponents([Pn]);for(const t of e){const e=s.get(t,Pn),o=s.has(t,Sn)?s.get(t,Sn):null,i=r.get(t);if(i&&!Mn(i,e,o))continue;s.has(t,j)||s.insert(t,j,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,j);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,j,l),r.set(t,En(e,o))}}))}}const Tn=new An,Rn=T("UIMask",{enabled:!0});function Fn(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function In(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(h,f),[y,w]=m(d,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function Un(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=h*_-d*m,E=h*g-f*m,M=h*y-p*m,A=d*g-f*_,T=d*y-p*_,R=f*y-p*g;let F=w*R-x*T+v*A+b*M-P*E+S*C;return 0===F||(F=1/F,n[0]=(l*R-c*T+u*A)*F,n[1]=(o*T-r*R-i*A)*F,n[2]=(_*S-g*P+y*b)*F,n[3]=(f*P-d*S-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(g*v-m*S-y*x)*F,n[7]=(h*S-f*v+p*x)*F,n[8]=(a*T-l*M+u*C)*F,n[9]=(r*M-s*T-i*C)*F,n[10]=(m*P-_*v+y*w)*F,n[11]=(d*v-h*P-p*w)*F,n[12]=(l*E-a*A-c*C)*F,n[13]=(s*A-r*E+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Bn(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function kn(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function $n(e,t,n,s,r,o,i){if(!e.has(t,Sn)||!e.has(t,N))return null;const a=e.get(t,Sn),l=e.get(t,N),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return In(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function zn(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Rn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Rn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,q);){const e=t.get(s,q);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=$n(t,n,r,o,i,a,l);e&&(s=Fn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=$n(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Ln{build(e){if($("UIMask",Rn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(zn(e.wasmModule,e.world))}}const Dn=new Ln,Wn=T("Interactable",{enabled:!0}),Hn=T("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var On;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(On||(On={}));const Nn=T("Button",{state:On.Normal,transition:null});class jn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Vn=ie(new jn,"UIEvents"),Xn=R("ScreenSpace");function Yn(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function qn(e,t,n,s,r,o){if(!e.has(t,Sn))return;const i=e.get(t,Sn),a=Yn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,O);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,O,l),!e.has(t,G))return;const c=e.get(t,G);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&qn(e,t,a.rect,a.centerX,a.centerY,!1)}class Gn{build(e){$("UIRect",Sn);const t=e.world;e.addSystemToSchedule(we.PreUpdate,ve([ae(Ue)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Xn,Sn,O]);for(const e of o)qn(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Jn=new Gn,Kn=new Float32Array(16),Qn=new Float32Array(16);let Zn=!0,es=1;class ts{build(e){$("Interactable",Wn),$("Button",Nn);const t=e.world,n=new jn;e.insertResource(Vn,n);let s=null,r=null;es="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(we.PreUpdate,ve([ae(Ae),ae(Ue)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Hn]);for(const e of i){const n=t.get(e,Hn);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*es,l=o.screenH-e.mouseY*es;!function(e){let t=!1;for(let n=0;n<16;n++)if(Qn[n]!==e[n]){t=!0;break}t&&(Qn.set(e),Zn=!0)}(o.viewProjection),Zn&&(Un(o.viewProjection,Kn),Zn=!1);const c=Bn(a,l,Kn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Wn,Sn,N]);let h=null,d=-1/0;for(const e of u){t.has(e,Hn)||t.insert(e,Hn);if(!t.get(e,Wn).enabled)continue;const n=t.get(e,N),s=t.get(e,Sn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(kn(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,j)&&(n=t.get(e,j).layer),n>=d&&(d=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,Hn)){t.get(s,Hn).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,Hn).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Hn);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Hn)){const e=t.get(r,Hn);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(we.Update,ve([],()=>{const e=t.getEntitiesWithComponents([Nn]);for(const n of e){if(t.has(n,Wn)||t.insert(n,Wn,{enabled:!0}),!t.has(n,Hn))continue;const e=t.get(n,Hn),s=t.get(n,Nn),r=t.get(n,Wn),o=s.state;if(r.enabled?e.pressed?s.state=On.Pressed:e.hovered?s.state=On.Hovered:s.state=On.Normal:s.state=On.Disabled,o!==s.state&&s.transition&&t.has(n,j)){const e=t.get(n,j),r=s.transition;switch(s.state){case On.Normal:e.color={...r.normalColor};break;case On.Hovered:e.color={...r.hoveredColor};break;case On.Pressed:e.color={...r.pressedColor};break;case On.Disabled:e.color={...r.disabledColor}}t.insert(n,j,e)}}},{name:"ButtonSystem"}))}}const ns=new ts,ss=T("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class rs{build(e){$("TextInput",ss);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=h(g,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!d)return;const f=d;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,ss);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Vn).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;_();const t=n.get(e,ss);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function _(){if(null!==i&&n.valid(i)&&n.has(i,ss)){const e=n.get(i,ss);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function x(e,i,a,c){(r.width<a||r.height<c)&&(r.width=is(Math.max(r.width,a)),r.height=is(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=os(o,d,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(d,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=os(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,j);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,j,b)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,ss);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Vn).emit(i,"submit"),void _()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,ss)){const e=n.get(i,ss);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(we.PreUpdate,ve([ae(Vn)],e=>{const t=n.getEntitiesWithComponents([ss,Wn]);for(const e of t){if(!n.has(e,Hn))continue;if(n.get(e,Hn).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([Wn]);for(const t of e){if(n.has(t,ss))continue;if(!n.has(t,Hn))continue;if(n.get(t,Hn).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(we.PreUpdate,ve([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,ss)))){n.get(i,ss).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,ss)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([ss,Sn]);for(const e of a){const t=n.get(e,ss);if(!t.dirty)continue;const s=n.get(e,Sn),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,j)||n.insert(e,j,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function os(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function is(e){let t=1;for(;t<e;)t*=2;return t}const as=new rs;async function ls(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const cs=ie({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),us=ie(null,"PhysicsAPI");function hs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ds(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class fs{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(cs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ls(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([X]);for(const n of t){const t=e.world.get(n,X);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(we.PostUpdate,ve([ae(he)],a=>{const l=i.getEntitiesWithComponents([ee,O,N]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,ee),l=i.get(r,N);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=hs(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ps(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===re.Kinematic){const e=hs(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,O);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(i,q)){const t=e.world.get(i,q);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const n=e.world.get(t.entity,N),s=hs(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=ds(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,O,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(cs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(us,ms._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function ps(e,t,n){const s=e.world;if(s.has(n,te)){const e=s.get(n,te);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ne)){const e=s.get(n,ne);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,se)){const e=s.get(n,se);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ms{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(ms.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function _s(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function gs(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ys(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,_=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function ws(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=_s(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=gs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=_s(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new fs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=_s(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),d=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Ne.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Ne.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=nt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,j);r&&(r.texture=n[s.data.texture]||0,e.insert(t,j,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,J);o&&(o.font=r,e.insert(t,J,o))}}}(e.world,n,h,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,j);n&&(n.material=r,e.insert(t,j,n))}else if("SpineAnimation"===s.type){const n=e.get(t,K);n&&(n.material=r,e.insert(t,K,n))}}}}(e.world,n,d,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,K)?c.get(o,K):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,N)){const e=ys(c.get(o,N),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,u,s)}if(a){const t=e.getResource(lt);t&&t.setAddressableManifest(a)}}class xs{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class vs{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_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new xs(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await ws(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([V]);for(const s of n){if(e.get(s,V).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([X]);for(const r of s){const s=e.get(r,X);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=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(r,O,o);const i={isActive:!0,projectionType:D.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:W.ColorAndDepth};e.insert(r,V,i)}}}const bs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Kt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Kt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Kt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Kt.releaseRenderTarget(e._handle),bs.create({width:t,height:n,depth:!0})),begin(e,t){Kt.begin(t,e._handle)},end(){Kt.end()},getDepthTexture:e=>Kt.getTargetDepthTexture(e._handle)};let Ps=!1;function Ss(e){Ps=e}function Cs(){return Ps}function Es(){return!Ps}const Ms=[Tn,Dn,Jn,ns,as];function As(e,t){return function(e,t){const n=ln.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),St(e),We(e),$t(e),Ht(e),Gt(e),Zt(e);const r=new an;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=dn(e,s,t,r),i=n.getResource(Ue);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Ue,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Kt.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;Kt.resize(t,n),jt.isInitialized()&&jt.getPassCount()>0&&!jt.isBypassed()&&jt.resize(t,n);const u=dn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:un,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Kt.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(we.First,l),n.addSystemToSchedule(we.Last,c),n.addPlugin(ut),n.addPlugin(yt),n.addPlugin(Re),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ms,...t})}e=f;export{ln as App,ct as AssetPlugin,at as AssetServer,lt as Assets,Qe as AsyncCache,J as BitmapText,Be as BlendMode,re as BodyType,te as BoxCollider,Nn as Button,On as ButtonState,V as Camera,X as Canvas,se as CapsuleCollider,G as Children,ne as CircleCollider,W as ClearFlags,_e as Commands,ye as CommandsInstance,m as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,_ as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,Ft as DataType,At as Draw,ge as EntityCommands,tn as GLDebug,Dt as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Ae as Input,Te as InputPlugin,Me as InputState,Wn as Interactable,O as LocalTransform,Ne as Material,Ze as MaterialLoader,de as Mut,Q as Name,q as Parent,ms as Physics,cs as PhysicsEvents,fs as PhysicsPlugin,jt as PostProcess,mt as PrefabServer,_t as Prefabs,gt as PrefabsPlugin,vs as PreviewPlugin,D as ProjectionType,pe as Query,me as QueryInstance,an as RenderPipeline,Xt as RenderStage,bs as RenderTexture,Kt as Renderer,ae as Res,le as ResMut,ee as RigidBody,H as ScaleMode,we as Schedule,Xn as ScreenSpace,Ke as ShaderSources,K as SpineAnimation,j as Sprite,Ee as SystemRunner,Pn as Text,xn as TextAlign,ss as TextInput,rs as TextInputPlugin,bn as TextOverflow,An as TextPlugin,Cn as TextRenderer,vn as TextVerticalAlign,he as Time,Ue as UICameraInfo,jn as UIEventQueue,Vn as UIEvents,Hn as UIInteraction,ts as UIInteractionPlugin,Gn as UILayoutPlugin,Rn as UIMask,Ln as UIMaskPlugin,Sn as UIRect,Y as Velocity,xs as WebAssetProvider,Ie as World,N as WorldTransform,Se as addStartupSystem,Pe as addSystem,Ce as addSystemToSchedule,ut as assetPlugin,on as clearDrawCallbacks,I as clearUserComponents,S as color,Yn as computeUIRectLayout,zn as createMaskProcessor,As as createWebApp,T as defineComponent,ie as defineResource,ve as defineSystem,R as defineTag,it as findEntityByName,cn as flushPendingSystems,z as getComponent,Z as getComponentDefaults,t as getPlatform,s as getPlatformType,F as getUserComponent,St as initDrawAPI,Zt as initGLDebugAPI,$t as initGeometryAPI,We as initMaterialAPI,Ht as initPostProcessAPI,Gt as initRendererAPI,Re as inputPlugin,dt as instantiatePrefab,Fn as intersectRects,Un as invertMatrix4,B as isBuiltinComponent,Cs as isEditor,n as isPlatformInitialized,Es as isRuntime,ke as isTextureRef,r as isWeChat,o as isWeb,rt as loadComponent,ls as loadPhysicsModule,ws as loadRuntimeScene,nt as loadSceneData,st as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,kn as pointInWorldRect,yt as prefabsPlugin,C as quat,$ as registerComponent,tt as registerComponentAssetFields,sn as registerDrawCallback,ht as registerEmbeddedAssets,Je as registerMaterialCallback,Bn as screenToWorld,Ss as setEditorMode,Ct as shutdownDrawAPI,en as shutdownGLDebugAPI,zt as shutdownGeometryAPI,He as shutdownMaterialAPI,Ot as shutdownPostProcessAPI,Jt as shutdownRendererAPI,as as textInputPlugin,Tn as textPlugin,ns as uiInteractionPlugin,Jn as uiLayoutPlugin,Dn as uiMaskPlugin,Ms as uiPlugins,rn as unregisterDrawCallback,ot as updateCameraAspectRatio,v as vec2,b as vec3,P as vec4,In as worldRectToScreen};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/physics/index.js b/desktop/public/sdk/esm/physics/index.jsindex 6fc63d2ed..c080d4387 100644--- a/desktop/public/sdk/esm/physics/index.js+++ b/desktop/public/sdk/esm/physics/index.js@@ -1,2 +1,2 @@-const e=new Map;function t(t,s){const i={_id:Symbol(`Builtin_${t}`),_name:t,_cppName:t,_builtin:!0,_default:s};return e.set(t,i),i}const s=t("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),i=t("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});t("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),t("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3});const n=t("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});t("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const o=t("Parent",{entity:0});t("Children",{entities:[]}),t("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295}),t("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0});const r={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var a,l;a="Name",l=r,e.set(a,l);let c=0;function u(e,t){const s=++c;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}const y=u({delta:0,elapsed:0,frameCount:0},"Time");var p;!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"}(p||(p={}));let _=0;async function m(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function d(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const s=t.cwrap.bind(t);return{_physics_init:s("physics_init",null,["number","number","number","number"]),_physics_shutdown:s("physics_shutdown",null,[]),_physics_createBody:s("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:s("physics_destroyBody",null,["number"]),_physics_hasBody:s("physics_hasBody","number",["number"]),_physics_addBoxShape:s("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:s("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:s("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:s("physics_step",null,["number"]),_physics_setBodyTransform:s("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:s("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:s("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:s("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:s("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:s("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:s("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:s("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:s("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:s("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:s("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:s("physics_getSensorExitBuffer","number",[]),_physics_applyForce:s("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:s("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:s("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:s("physics_getLinearVelocity","number",["number"]),_physics_setGravity:s("physics_setGravity",null,["number","number"]),_physics_getGravity:s("physics_getGravity","number",[]),_physics_setAngularVelocity:s("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:s("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:s("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:s("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:s("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const h=t("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),f=t("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),g=t("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),b=t("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),x={Static:0,Kinematic:1,Dynamic:2},E=u({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),S=u(null,"PhysicsAPI");function P(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function C(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class v{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(E,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,a=m(this.wasmUrl_,this.factory_).then(a=>{a._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const l=function(e){const t=e.world.getEntitiesWithComponents([n]);for(const s of t){const t=e.world.get(s,n);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),c=1/l,u=e.world;var m;e.addSystemToSchedule(p.PostUpdate,function(e,t,s){const i=++_;return{_id:Symbol(`System_${i}_${s?.name}`),_params:e,_fn:t,_name:s?.name??`System_${i}`}}([(m=y,{_type:"res",_resource:m})],n=>{const y=u.getEntitiesWithComponents([h,s,i]),p=new Set;for(const s of y){p.add(s);const n=u.get(s,h),o=u.get(s,i);if(t.has(s)){const e=r.get(s);!e||e.bodyType===n.bodyType&&e.gravityScale===n.gravityScale&&e.linearDamping===n.linearDamping&&e.angularDamping===n.angularDamping&&e.fixedRotation===n.fixedRotation&&e.bullet===n.bullet||(a._physics_updateBodyProperties(s,n.bodyType,n.gravityScale,n.linearDamping,n.angularDamping,n.fixedRotation?1:0,n.bullet?1:0),e.bodyType=n.bodyType,e.gravityScale=n.gravityScale,e.linearDamping=n.linearDamping,e.angularDamping=n.angularDamping,e.fixedRotation=n.fixedRotation,e.bullet=n.bullet)}else{if(!n.enabled)continue;const i=P(o.rotation);a._physics_createBody(s,n.bodyType,o.position.x*c,o.position.y*c,i,n.gravityScale,n.linearDamping,n.angularDamping,n.fixedRotation?1:0,n.bullet?1:0),A(e,a,s),t.add(s),r.set(s,{bodyType:n.bodyType,gravityScale:n.gravityScale,linearDamping:n.linearDamping,angularDamping:n.angularDamping,fixedRotation:n.fixedRotation,bullet:n.bullet})}if(n.bodyType===x.Kinematic){const e=P(o.rotation);a._physics_setBodyTransform(s,o.position.x*c,o.position.y*c,e)}}for(const e of t)p.has(e)||(a._physics_destroyBody(e),t.delete(e),r.delete(e));a._physics_step(n.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const a=t._physics_getDynamicBodyTransforms(),l=a>>2;for(let a=0;a<r;a++){const r=l+4*a,c=t.HEAPU32[r],u=t.HEAPF32[r+1]*n,y=t.HEAPF32[r+2]*n,p=t.HEAPF32[r+3];if(!e.world.valid(c))continue;const _=e.world.get(c,s);if(!_)continue;let m=u,d=y,h=p;if(e.world.has(c,o)){const t=e.world.get(c,o);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,i)){const s=e.world.get(t.entity,i),n=P(s.rotation),o=u-s.position.x,r=y-s.position.y,a=Math.cos(-n),l=Math.sin(-n);m=(o*a-r*l)/(0!==s.scale.x?s.scale.x:1),d=(o*l+r*a)/(0!==s.scale.y?s.scale.y:1),h=p-n}}_.position.x=m,_.position.y=d;const f=C(h);_.rotation.w=f.w,_.rotation.x=f.x,_.rotation.y=f.y,_.rotation.z=f.z,e.world.insert(c,s,_)}}(e,a,l),function(e,t,s){t._physics_collectEvents();const i=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*s,contactY:t.HEAPF32[n+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const i=e+2*s;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const i=e+2*s;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const i=e+2*s;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(E,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,a,l)},{name:"PhysicsSystem"})),e.physicsModule=a,e.insertResource(S,B._fromModule(a)),e.setFixedTimestep(this.config_.fixedTimestep)});a.catch(()=>{}),e.physicsInitPromise=a}}function A(e,t,s){const i=e.world;if(i.has(s,f)){const e=i.get(s,f);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(s,g)){const e=i.get(s,g);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(s,b)){const e=i.get(s,b);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class B{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(B.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}export{x as BodyType,f as BoxCollider,b as CapsuleCollider,g as CircleCollider,B as Physics,S as PhysicsAPI,E as PhysicsEvents,v as PhysicsPlugin,h as RigidBody,m as loadPhysicsModule,d as loadPhysicsSideModule};+const e=new Map;function t(t,s){const i={_id:Symbol(`Builtin_${t}`),_name:t,_cppName:t,_builtin:!0,_default:s};return e.set(t,i),i}const s=t("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),i=t("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});t("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),t("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3});const n=t("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});t("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const o=t("Parent",{entity:0});t("Children",{entities:[]}),t("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295}),t("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0});const r={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var a,l;a="Name",l=r,e.set(a,l);let c=0;function u(e,t){const s=++c;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}const y=u({delta:0,elapsed:0,frameCount:0},"Time");var p;!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"}(p||(p={}));let _=0;async function m(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function d(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const s=t.cwrap.bind(t);return{_physics_init:s("physics_init",null,["number","number","number","number"]),_physics_shutdown:s("physics_shutdown",null,[]),_physics_createBody:s("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:s("physics_destroyBody",null,["number"]),_physics_hasBody:s("physics_hasBody","number",["number"]),_physics_addBoxShape:s("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:s("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:s("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:s("physics_step",null,["number"]),_physics_setBodyTransform:s("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:s("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:s("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:s("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:s("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:s("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:s("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:s("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:s("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:s("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:s("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:s("physics_getSensorExitBuffer","number",[]),_physics_applyForce:s("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:s("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:s("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:s("physics_getLinearVelocity","number",["number"]),_physics_setGravity:s("physics_setGravity",null,["number","number"]),_physics_getGravity:s("physics_getGravity","number",[]),_physics_setAngularVelocity:s("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:s("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:s("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:s("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:s("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const h=t("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),f=t("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),g=t("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),b=t("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),x={Static:0,Kinematic:1,Dynamic:2},E=u({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),S=u(null,"PhysicsAPI");function P(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function C(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class v{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(E,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,a=m(this.wasmUrl_,this.factory_).then(a=>{a._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const l=function(e){const t=e.world.getEntitiesWithComponents([n]);for(const s of t){const t=e.world.get(s,n);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),c=1/l,u=e.world;var m;e.addSystemToSchedule(p.PostUpdate,function(e,t,s){const i=++_;return{_id:Symbol(`System_${i}_${s?.name}`),_params:e,_fn:t,_name:s?.name??`System_${i}`}}([(m=y,{_type:"res",_resource:m})],n=>{const y=u.getEntitiesWithComponents([h,s,i]),p=new Set;for(const s of y){p.add(s);const n=u.get(s,h),o=u.get(s,i);if(t.has(s)){const e=r.get(s);!e||e.bodyType===n.bodyType&&e.gravityScale===n.gravityScale&&e.linearDamping===n.linearDamping&&e.angularDamping===n.angularDamping&&e.fixedRotation===n.fixedRotation&&e.bullet===n.bullet||(a._physics_updateBodyProperties(s,n.bodyType,n.gravityScale,n.linearDamping,n.angularDamping,n.fixedRotation?1:0,n.bullet?1:0),e.bodyType=n.bodyType,e.gravityScale=n.gravityScale,e.linearDamping=n.linearDamping,e.angularDamping=n.angularDamping,e.fixedRotation=n.fixedRotation,e.bullet=n.bullet)}else{if(!n.enabled)continue;const i=P(o.rotation);a._physics_createBody(s,n.bodyType,o.position.x*c,o.position.y*c,i,n.gravityScale,n.linearDamping,n.angularDamping,n.fixedRotation?1:0,n.bullet?1:0),A(e,a,s),t.add(s),r.set(s,{bodyType:n.bodyType,gravityScale:n.gravityScale,linearDamping:n.linearDamping,angularDamping:n.angularDamping,fixedRotation:n.fixedRotation,bullet:n.bullet})}if(n.bodyType===x.Kinematic){const e=P(o.rotation);a._physics_setBodyTransform(s,o.position.x*c,o.position.y*c,e)}}for(const e of t)p.has(e)||(a._physics_destroyBody(e),t.delete(e),r.delete(e));a._physics_step(n.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const a=t._physics_getDynamicBodyTransforms(),l=a>>2;for(let a=0;a<r;a++){const r=l+4*a,c=t.HEAPU32[r],u=t.HEAPF32[r+1]*n,y=t.HEAPF32[r+2]*n,p=t.HEAPF32[r+3];if(!e.world.valid(c))continue;const _=e.world.get(c,s);if(!_)continue;let m=u,d=y,h=p;if(e.world.has(c,o)){const t=e.world.get(c,o);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,i)){const s=e.world.get(t.entity,i),n=P(s.rotation),o=u-s.position.x,r=y-s.position.y,a=Math.cos(-n),l=Math.sin(-n);m=(o*a-r*l)/(0!==s.scale.x?s.scale.x:1),d=(o*l+r*a)/(0!==s.scale.y?s.scale.y:1),h=p-n}}_.position.x=m,_.position.y=d;const f=C(h);_.rotation.w=f.w,_.rotation.x=f.x,_.rotation.y=f.y,_.rotation.z=f.z,e.world.insert(c,s,_)}}(e,a,l),function(e,t,s){t._physics_collectEvents();const i=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*s,contactY:t.HEAPF32[n+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const i=e+2*s;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const i=e+2*s;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const i=e+2*s;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(E,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,a,l)},{name:"PhysicsSystem"})),e.physicsModule=a,e.insertResource(S,B._fromModule(a)),e.setFixedTimestep(this.config_.fixedTimestep)});a.catch(()=>{}),e.physicsInitPromise=a}}function A(e,t,s){const i=e.world;if(i.has(s,f)){const e=i.get(s,f);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(s,g)){const e=i.get(s,g);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(s,b)){const e=i.get(s,b);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class B{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(B.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}export{x as BodyType,f as BoxCollider,b as CapsuleCollider,g as CircleCollider,B as Physics,S as PhysicsAPI,E as PhysicsEvents,v as PhysicsPlugin,h as RigidBody,m as loadPhysicsModule,d as loadPhysicsSideModule};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.jsindex d8a912e1f..496a662ef 100644--- a/desktop/public/sdk/esm/spine/index.js+++ b/desktop/public/sdk/esm/spine/index.js@@ -1,2 +1,2 @@-let e=0;function t(t,n){const a=++e;return{_id:Symbol(`Resource_${a}_${n??""}`),_name:n??`Resource_${a}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");const n=new Map;function a(e,t){const a={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return n.set(e,a),a}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}});const r=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}});a("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),a("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),a("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),a("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),a("Parent",{entity:0}),a("Children",{entities:[]}),a("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295});const s=a("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),i={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var o,l,u;o="Name",l=i,n.set(o,l),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"}(u||(u={}));const c=t(null,"Assets");function p(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function h(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:p(n)}}class m{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let a,r;if("string"==typeof e){const t=(new TextEncoder).encode(e);r=t.length,a=this.raw_._malloc(r+1),this.raw_.HEAPU8.set(t,a),this.raw_.HEAPU8[a+r]=0}else r=e.length,a=this.raw_._malloc(r),this.raw_.HEAPU8.set(e,a);const s=this.api_.loadSkeleton(a,r,t,t.length,n);return this.raw_._free(a),s}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,a,r){this.api_.setAtlasPageTexture(e,t,n,a,r)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,a=0){return!!this.api_.playAnimation(e,t,n,a)}addAnimation(e,t,n=!0,a=0,r=0){return!!this.api_.addAnimation(e,t,n,a,r)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),a=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,a))return this.raw_._free(n),this.raw_._free(a),null;const r=this.raw_.HEAPF32[n>>2],s=this.raw_.HEAPF32[a>>2];return this.raw_._free(n),this.raw_._free(a),{x:r,y:s}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,a=t>>2,r={x:n[a],y:n[a+1],width:n[a+2],height:n[a+3]};return this.raw_._free(t),r}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],a=this.raw_._malloc(8),r=a,s=a+4;for(let a=0;a<t;a++){const t=this.api_.getMeshBatchVertexCount(e,a),i=this.api_.getMeshBatchIndexCount(e,a);if(t<=0||i<=0)continue;const o=8*t*4,l=2*i,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,a,u,c,r,s);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),h=new Uint16Array(this.raw_.HEAPU8.buffer,c,i);n.push({vertices:new Float32Array(p),indices:new Uint16Array(h),textureId:this.raw_.HEAPU32[r>>2],blendMode:this.raw_.HEAPU32[s>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(a),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const a=this.listeners_.get(e);a.has(t)||a.set(t,new Set),a.get(t).add(n)}off(e,t,n){const a=this.listeners_.get(e);if(!a)return;const r=a.get(t);r&&r.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const _=t(null,"SpineController"),d=new Float32Array(16);function g(e,t,n,a){const r=e.scale.x*t*(n?-1:1),s=e.scale.y*t*(a?-1:1),i=e.scale.z,o=e.rotation.x,l=e.rotation.y,u=e.rotation.z,c=e.rotation.w,p=o+o,h=l+l,m=u+u,_=o*p,g=o*h,b=o*m,f=l*h,w=l*m,y=u*m,S=c*p,A=c*h,P=c*m;return d[0]=(1-(f+y))*r,d[1]=(g+P)*r,d[2]=(b-A)*r,d[3]=0,d[4]=(g-P)*s,d[5]=(1-(_+y))*s,d[6]=(w+S)*s,d[7]=0,d[8]=(b+A)*i,d[9]=(w-S)*i,d[10]=(1-(_+f))*i,d[11]=0,d[12]=e.position.x,d[13]=e.position.y,d[14]=e.position.z,d[15]=1,d}class b{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=h(this.wasmUrl_,this.factory_).then(({raw:n,api:a})=>{const i=new m(n,a);e.insertResource(_,i),e.hasResource(c)&&e.getResource(c).setSpineController(i);const o=new Map,l=new Map,p=new Map,h={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(c)?e.getResource(c):null;if(!n)return;const a=t.getEntitiesWithComponents([s]),r=new Set;for(const e of a){r.add(e);const a=t.get(e,s),u=`${a.skeletonPath}:${a.atlasPath}`;if(!o.has(e)||l.get(e)!==u){o.has(e)&&(i.destroyInstance(o.get(e)),o.delete(e),l.delete(e),p.delete(e));const t=n.getSpineSkeletonHandle(a.skeletonPath,a.atlasPath);if(void 0===t)continue;const r=i.createInstance(t);if(r<0)continue;o.set(e,r),l.set(e,u),a.skin&&i.setSkin(r,a.skin),a.animation&&i.play(r,a.animation,a.loop),p.set(e,{animation:a.animation,skin:a.skin,loop:a.loop});continue}const c=p.get(e);if(!c)continue;const h=o.get(e);c.skin!==a.skin&&(i.setSkin(h,a.skin),c.skin=a.skin),c.animation===a.animation&&c.loop===a.loop||(a.animation&&i.play(h,a.animation,a.loop),c.animation=a.animation,c.loop=a.loop)}for(const[e,t]of o)r.has(e)||(i.destroyInstance(t),o.delete(e),l.delete(e),p.delete(e))}};if(e.addSystemToSchedule(u.PreUpdate,h),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((a,l)=>{let u=l-n;n=l,(u<=0||u>.5)&&(u=1/60);const c=e.world;for(const[e,n]of o){const a=c.has(e,s)?c.get(e,s):null,o=!1!==a?.playing,l=a?.timeScale??1;let p;if(o&&i.update(n,u*l),c.has(e,r)){p=g(c.get(e,r),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1)}const h=a?.color;M(t,i,n,p,h)}})}return{controller:i,coreModule:t}});e.insertResource(_,null),n.catch(()=>{}),e.spineInitPromise=n}}let f=new Float32Array(0),w=0,y=0,S=0,A=0,P=0,x=null;function k(e,t,n,a){if(t&&n>=a)return[t,n];t&&e._free(t);const r=2*a;return[e._malloc(r),r]}function M(e,t,n,a,r){x&&x!==e&&x&&(w&&(x._free(w),w=0,y=0),S&&(x._free(S),S=0,A=0),P&&(x._free(P),P=0),x=null),x=e;const s=t.extractMeshBatches(n);a&&(P||(P=e._malloc(64)),e.HEAPF32.set(a,P>>2));const i=r&&(1!==r.r||1!==r.g||1!==r.b||1!==r.a);for(const t of s){let n=t.vertices;if(i){const e=t.blendMode>=4;f.length<n.length&&(f=new Float32Array(2*n.length)),f.set(n);const a=f.subarray(0,n.length);for(let t=0;t<a.length;t+=8)e?(a[t+4]*=r.r*r.a,a[t+5]*=r.g*r.a,a[t+6]*=r.b*r.a):(a[t+4]*=r.r,a[t+5]*=r.g,a[t+6]*=r.b),a[t+7]*=r.a;n=a}const s=n.byteLength,o=t.indices.byteLength;[w,y]=k(e,w,y,s),[S,A]=k(e,S,A,o),e.HEAPF32.set(n,w>>2),new Uint16Array(e.HEAPU8.buffer,S,t.indices.length).set(t.indices),e.renderer_submitTriangles(w,n.length/8,S,t.indices.length,t.textureId,t.blendMode,a?P:0)}}export{m as SpineModuleController,b as SpinePlugin,_ as SpineResource,h as loadSpineModule,M as submitSpineMeshesToCore,p as wrapSpineModule};+let e=0;function t(t,n){const a=++e;return{_id:Symbol(`Resource_${a}_${n??""}`),_name:n??`Resource_${a}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");const n=new Map;function a(e,t){const a={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return n.set(e,a),a}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}});const r=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}});a("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),a("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),a("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),a("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),a("Parent",{entity:0}),a("Children",{entities:[]}),a("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295});const s=a("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),i={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var o,l,u;o="Name",l=i,n.set(o,l),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"}(u||(u={}));const c=t(null,"Assets");function p(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function h(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:p(n)}}class m{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let a,r;if("string"==typeof e){const t=(new TextEncoder).encode(e);r=t.length,a=this.raw_._malloc(r+1),this.raw_.HEAPU8.set(t,a),this.raw_.HEAPU8[a+r]=0}else r=e.length,a=this.raw_._malloc(r),this.raw_.HEAPU8.set(e,a);const s=this.api_.loadSkeleton(a,r,t,t.length,n);return this.raw_._free(a),s}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,a,r){this.api_.setAtlasPageTexture(e,t,n,a,r)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,a=0){return!!this.api_.playAnimation(e,t,n,a)}addAnimation(e,t,n=!0,a=0,r=0){return!!this.api_.addAnimation(e,t,n,a,r)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),a=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,a))return this.raw_._free(n),this.raw_._free(a),null;const r=this.raw_.HEAPF32[n>>2],s=this.raw_.HEAPF32[a>>2];return this.raw_._free(n),this.raw_._free(a),{x:r,y:s}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,a=t>>2,r={x:n[a],y:n[a+1],width:n[a+2],height:n[a+3]};return this.raw_._free(t),r}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],a=this.raw_._malloc(8),r=a,s=a+4;for(let a=0;a<t;a++){const t=this.api_.getMeshBatchVertexCount(e,a),i=this.api_.getMeshBatchIndexCount(e,a);if(t<=0||i<=0)continue;const o=8*t*4,l=2*i,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,a,u,c,r,s);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),h=new Uint16Array(this.raw_.HEAPU8.buffer,c,i);n.push({vertices:new Float32Array(p),indices:new Uint16Array(h),textureId:this.raw_.HEAPU32[r>>2],blendMode:this.raw_.HEAPU32[s>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(a),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const a=this.listeners_.get(e);a.has(t)||a.set(t,new Set),a.get(t).add(n)}off(e,t,n){const a=this.listeners_.get(e);if(!a)return;const r=a.get(t);r&&r.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const _=t(null,"SpineController"),d=new Float32Array(16);function g(e,t,n,a){const r=e.scale.x*t*(n?-1:1),s=e.scale.y*t*(a?-1:1),i=e.scale.z,o=e.rotation.x,l=e.rotation.y,u=e.rotation.z,c=e.rotation.w,p=o+o,h=l+l,m=u+u,_=o*p,g=o*h,b=o*m,f=l*h,w=l*m,y=u*m,S=c*p,A=c*h,P=c*m;return d[0]=(1-(f+y))*r,d[1]=(g+P)*r,d[2]=(b-A)*r,d[3]=0,d[4]=(g-P)*s,d[5]=(1-(_+y))*s,d[6]=(w+S)*s,d[7]=0,d[8]=(b+A)*i,d[9]=(w-S)*i,d[10]=(1-(_+f))*i,d[11]=0,d[12]=e.position.x,d[13]=e.position.y,d[14]=e.position.z,d[15]=1,d}class b{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=h(this.wasmUrl_,this.factory_).then(({raw:n,api:a})=>{const i=new m(n,a);e.insertResource(_,i),e.hasResource(c)&&e.getResource(c).setSpineController(i);const o=new Map,l=new Map,p=new Map,h={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(c)?e.getResource(c):null;if(!n)return;const a=t.getEntitiesWithComponents([s]),r=new Set;for(const e of a){r.add(e);const a=t.get(e,s),u=`${a.skeletonPath}:${a.atlasPath}`;if(!o.has(e)||l.get(e)!==u){o.has(e)&&(i.destroyInstance(o.get(e)),o.delete(e),l.delete(e),p.delete(e));const t=n.getSpineSkeletonHandle(a.skeletonPath,a.atlasPath);if(void 0===t)continue;const r=i.createInstance(t);if(r<0)continue;o.set(e,r),l.set(e,u),a.skin&&i.setSkin(r,a.skin),a.animation&&i.play(r,a.animation,a.loop),p.set(e,{animation:a.animation,skin:a.skin,loop:a.loop});continue}const c=p.get(e);if(!c)continue;const h=o.get(e);c.skin!==a.skin&&(i.setSkin(h,a.skin),c.skin=a.skin),c.animation===a.animation&&c.loop===a.loop||(a.animation&&i.play(h,a.animation,a.loop),c.animation=a.animation,c.loop=a.loop)}for(const[e,t]of o)r.has(e)||(i.destroyInstance(t),o.delete(e),l.delete(e),p.delete(e))}};if(e.addSystemToSchedule(u.PreUpdate,h),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((a,l)=>{let u=l-n;n=l,(u<=0||u>.5)&&(u=1/60);const c=e.world;for(const[e,n]of o){const a=c.has(e,s)?c.get(e,s):null,o=!1!==a?.playing,l=a?.timeScale??1;let p;if(o&&i.update(n,u*l),c.has(e,r)){p=g(c.get(e,r),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1)}const h=a?.color;M(t,i,n,p,h)}})}return{controller:i,coreModule:t}});e.insertResource(_,null),n.catch(()=>{}),e.spineInitPromise=n}}let f=new Float32Array(0),w=0,y=0,S=0,A=0,P=0,x=null;function k(e,t,n,a){if(t&&n>=a)return[t,n];t&&e._free(t);const r=2*a;return[e._malloc(r),r]}function M(e,t,n,a,r){x&&x!==e&&x&&(w&&(x._free(w),w=0,y=0),S&&(x._free(S),S=0,A=0),P&&(x._free(P),P=0),x=null),x=e;const s=t.extractMeshBatches(n);a&&(P||(P=e._malloc(64)),e.HEAPF32.set(a,P>>2));const i=r&&(1!==r.r||1!==r.g||1!==r.b||1!==r.a);for(const t of s){let n=t.vertices;if(i){const e=t.blendMode>=4;f.length<n.length&&(f=new Float32Array(2*n.length)),f.set(n);const a=f.subarray(0,n.length);for(let t=0;t<a.length;t+=8)e?(a[t+4]*=r.r*r.a,a[t+5]*=r.g*r.a,a[t+6]*=r.b*r.a):(a[t+4]*=r.r,a[t+5]*=r.g,a[t+6]*=r.b),a[t+7]*=r.a;n=a}const s=n.byteLength,o=t.indices.byteLength;[w,y]=k(e,w,y,s),[S,A]=k(e,S,A,o),e.HEAPF32.set(n,w>>2),new Uint16Array(e.HEAPU8.buffer,S,t.indices.length).set(t.indices),e.renderer_submitTriangles(w,n.length/8,S,t.indices.length,t.textureId,t.blendMode,a?P:0)}}export{m as SpineModuleController,b as SpinePlugin,_ as SpineResource,h as loadSpineModule,M as submitSpineMeshesToCore,p as wrapSpineModule};//# sourceMappingURL=index.js.mapdiff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex 00f3b4dc4..4d3aeaf34 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -10,6 +10,7 @@ import {Draw, Geometry, Material, BlendMode, DataType, ShaderSources,PostProcess, Renderer, RenderStage,registerDrawCallback, unregisterDrawCallback, clearDrawCallbacks,+ DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT,} from 'esengine';import { EditorStore } from './store/EditorStore';import { EditorBridge } from './bridge/EditorBridge';@@ -562,7 +563,7 @@ export class Editor {setSettingsValue('physics.gravityY', config.physicsGravityY ?? -9.81);setSettingsValue('physics.fixedTimestep', config.physicsFixedTimestep ?? 1 / 60);setSettingsValue('physics.subStepCount', config.physicsSubStepCount ?? 4);- const resolution = config.designResolution ?? { width: 1920, height: 1080 };+ const resolution = config.designResolution ?? { width: DEFAULT_DESIGN_WIDTH, height: DEFAULT_DESIGN_HEIGHT };setSettingsValue('project.designWidth', resolution.width);setSettingsValue('project.designHeight', resolution.height);}@@ -605,8 +606,8 @@ export class Editor {config.physicsFixedTimestep = getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60;config.physicsSubStepCount = getSettingsValue<number>('physics.subStepCount') ?? 4;config.designResolution = {- width: getSettingsValue<number>('project.designWidth') || 1920,- height: getSettingsValue<number>('project.designHeight') || 1080,+ width: getSettingsValue<number>('project.designWidth') || DEFAULT_DESIGN_WIDTH,+ height: getSettingsValue<number>('project.designHeight') || DEFAULT_DESIGN_HEIGHT,};config.modified = new Date().toISOString();const fs = getEditorContext().fs;diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsindex 02cfaecc2..de349eaac 100644--- a/editor/src/builder/ArtifactBuilder.ts+++ b/editor/src/builder/ArtifactBuilder.ts@@ -113,12 +113,14 @@ export async function initializeEsbuild(): Promise<void> {// =============================================================================export function arrayBufferToBase64(buffer: Uint8Array): string {- let binary = '';+ const CHUNK_SIZE = 0x2000;const bytes = new Uint8Array(buffer);- for (let i = 0; i < bytes.byteLength; i++) {- binary += String.fromCharCode(bytes[i]);+ const chunks: string[] = [];+ for (let i = 0; i < bytes.byteLength; i += CHUNK_SIZE) {+ const slice = bytes.subarray(i, Math.min(i + CHUNK_SIZE, bytes.byteLength));+ chunks.push(String.fromCharCode.apply(null, slice as unknown as number[]));}- return btoa(binary);+ return btoa(chunks.join(''));}export function generateAddressableManifest(diff --git a/editor/src/builder/BuildTemplates.ts b/editor/src/builder/BuildTemplates.tsindex 022be6986..4626f16b9 100644--- a/editor/src/builder/BuildTemplates.ts+++ b/editor/src/builder/BuildTemplates.ts@@ -160,6 +160,7 @@ export function createConfigFromTemplate(minifyCode: template.playableSettings?.minifyCode ?? false,embedFonts: template.playableSettings?.embedFonts ?? true,outputPath: template.playableSettings?.outputPath ?? 'build/playable.html',+ ctaUrl: template.playableSettings?.ctaUrl ?? '',};} else {config.wechatSettings = {diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.tsindex 20b436e48..85adaed07 100644--- a/editor/src/builder/PlayableEmitter.ts+++ b/editor/src/builder/PlayableEmitter.ts@@ -289,6 +289,8 @@ ${imports}await this.walkDirectory(fs, assetsDir, 'assets', allFiles);}+ const pending: Array<Promise<void>> = [];+for (const relativePath of allFiles) {if (artifact.packedPaths.has(relativePath)) continue;if (relativePath.endsWith('.esshader')) continue;@@ -303,13 +305,14 @@ ${imports}}if (relativePath.endsWith('.esprefab')) {- const fullPath = joinPath(projectDir, relativePath);- const content = await fs.readFile(fullPath);- if (content) {- const json = convertPrefabWithResolvedRefs(content, artifact);- const base64 = btoa(json);- assets.set(relativePath, `data:application/json;base64,${base64}`);- }+ pending.push(+ fs.readFile(joinPath(projectDir, relativePath)).then(content => {+ if (content) {+ const json = convertPrefabWithResolvedRefs(content, artifact);+ assets.set(relativePath, `data:application/json;base64,${btoa(json)}`);+ }+ })+ );continue;}@@ -317,14 +320,17 @@ ${imports}const mimeType = MIME_TYPES[ext];if (!mimeType) continue;- const fullPath = joinPath(projectDir, relativePath);- const binary = await fs.readBinaryFile(fullPath);- if (binary) {- const base64 = arrayBufferToBase64(binary);- assets.set(relativePath, `data:${mimeType};base64,${base64}`);- }+ pending.push(+ fs.readBinaryFile(joinPath(projectDir, relativePath)).then(binary => {+ if (binary) {+ const base64 = arrayBufferToBase64(binary);+ assets.set(relativePath, `data:${mimeType};base64,${base64}`);+ }+ })+ );}+ await Promise.all(pending);return assets;}@@ -374,6 +380,8 @@ ${imports}subStepCount: context.physicsSubStepCount ?? 4,});+ const ctaUrl = JSON.stringify(context.config.playableSettings?.ctaUrl || '');+return PLAYABLE_HTML_TEMPLATE.replace('{{WASM_SDK}}', () => wasmSdk).replace('{{SPINE_SCRIPT}}', () => spineScript)@@ -382,7 +390,8 @@ ${imports}.replace('{{ASSETS_MAP}}', () => `{${entries.join(',')}}`).replace('{{SCENE_DATA}}', () => sceneData).replace('{{PHYSICS_CONFIG}}', () => physicsConfig)- .replace('{{MANIFEST}}', () => manifestJson);+ .replace('{{MANIFEST}}', () => manifestJson)+ .replace(/\{\{CTA_URL\}\}/g, () => ctaUrl);}}diff --git a/editor/src/builder/templates.ts b/editor/src/builder/templates.tsindex 2f0373762..d42cadbe2 100644--- a/editor/src/builder/templates.ts+++ b/editor/src/builder/templates.ts@@ -18,10 +18,13 @@ export const PLAYABLE_HTML_TEMPLATE = `<!DOCTYPE html>*{margin:0;padding:0;box-sizing:border-box}html,body{width:100%;height:100%;overflow:hidden;background:#000}#canvas{display:block;width:100%;height:100%;touch-action:none}+#cta{position:fixed;bottom:5%;left:50%;transform:translateX(-50%);padding:12px 32px;font-size:18px;font-weight:bold;color:#fff;background:#ff4444;border:none;border-radius:8px;cursor:pointer;z-index:999;text-transform:uppercase;box-shadow:0 2px 8px rgba(0,0,0,0.3)}+#cta:active{transform:translateX(-50%) scale(0.95)}</style></head><body><canvas id="canvas"></canvas>+<button id="cta" style="display:none">Install Now</button><script>{{WASM_SDK}}</script>@@ -60,7 +63,14 @@ function decodeBinary(dataUrl){return a;}+function installCTA(){+ if(typeof mraid!=='undefined'&&mraid.open){mraid.open({{CTA_URL}})}+ else{window.open({{CTA_URL}},'_blank')}+}+document.getElementById('cta').addEventListener('click',installCTA);+(async function(){+ try{var c=document.getElementById('canvas');function resize(){var dpr=window.devicePixelRatio||1;c.width=window.innerWidth*dpr;c.height=window.innerHeight*dpr}window.addEventListener('resize',resize);@@ -116,7 +126,9 @@ function decodeBinary(dataUrl){var screenAspect=c.width/c.height;es.updateCameraAspectRatio(app.world,screenAspect);+ document.getElementById('cta').style.display='block';app.run();+ }catch(e){console.error('Playable init error:',e)}})();</script></body>@@ -169,17 +181,34 @@ async function initPhysicsModule() {const sceneLoading = firstSceneName ? `try {- var wxfs = wx.getFileSystemManager();var provider = {loadPixels: function(ref) { return SDK.wxLoadImagePixels(resolvePath(ref)); },loadPixelsRaw: function(ref) { return SDK.wxLoadImagePixels(resolvePath(ref)); },- readText: function(ref) { return wxfs.readFileSync(resolvePath(ref), 'utf-8'); },- readBinary: function(ref) { return new Uint8Array(wxfs.readFileSync(resolvePath(ref))); },+ readText: function(ref) {+ return new Promise(function(resolve, reject) {+ wxfs.readFile({ filePath: resolvePath(ref), encoding: 'utf-8',+ success: function(res) { resolve(res.data); },+ fail: function(err) { reject(new Error(err.errMsg)); }+ });+ });+ },+ readBinary: function(ref) {+ return new Promise(function(resolve, reject) {+ wxfs.readFile({ filePath: resolvePath(ref),+ success: function(res) { resolve(new Uint8Array(res.data)); },+ fail: function(err) { reject(new Error(err.errMsg)); }+ });+ });+ },resolvePath: resolvePath};- var sceneJson = wxfs.readFileSync('scenes/${firstSceneName}.json', 'utf-8');- var sceneData = JSON.parse(sceneJson);+ var sceneData = await new Promise(function(resolve, reject) {+ wxfs.readFile({ filePath: 'scenes/${firstSceneName}.json', encoding: 'utf-8',+ success: function(res) { resolve(JSON.parse(res.data)); },+ fail: function(err) { reject(new Error(err.errMsg)); }+ });+ });await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule, physicsModule, ${physicsConfig}, manifest);@@ -195,19 +224,6 @@ var ESEngineModule = require('./esengine.js');var SDK = require('./sdk.js');globalThis.__esengine_sdk = SDK;-var manifest = JSON.parse(wx.getFileSystemManager().readFileSync('asset-manifest.json', 'utf-8'));-var assetIndex = {};-for (var gn in manifest.groups) {- var g = manifest.groups[gn];- for (var uuid in g.assets) {- assetIndex[uuid] = g.assets[uuid];- }-}-function resolvePath(ref) {- var entry = assetIndex[ref];- return entry ? entry.path : ref;-}-var spineModule = null;${spineInit}@@ -215,6 +231,25 @@ var physicsModule = null;${physicsInit}(async function() {+ var wxfs = wx.getFileSystemManager();+ var manifest = await new Promise(function(resolve, reject) {+ wxfs.readFile({ filePath: 'asset-manifest.json', encoding: 'utf-8',+ success: function(res) { resolve(JSON.parse(res.data)); },+ fail: function(err) { reject(new Error(err.errMsg)); }+ });+ });+ var assetIndex = {};+ for (var gn in manifest.groups) {+ var g = manifest.groups[gn];+ for (var uuid in g.assets) {+ assetIndex[uuid] = g.assets[uuid];+ }+ }+ function resolvePath(ref) {+ var entry = assetIndex[ref];+ return entry ? entry.path : ref;+ }+var canvas = wx.createCanvas();var info = wx.getSystemInfoSync();canvas.width = info.windowWidth * info.pixelRatio;diff --git a/editor/src/gizmos/ColliderOverlay.ts b/editor/src/gizmos/ColliderOverlay.tsindex 5b7ac4bf6..5f3adf309 100644--- a/editor/src/gizmos/ColliderOverlay.ts+++ b/editor/src/gizmos/ColliderOverlay.ts@@ -4,6 +4,7 @@*/import type { Entity } from 'esengine';+import { DEFAULT_PIXELS_PER_UNIT } from 'esengine';import type { EditorStore } from '../store/EditorStore';import type { EntityData, ComponentData } from '../types/SceneTypes';import { quatToEuler } from '../math/Transform';@@ -419,11 +420,11 @@ export class ColliderOverlay {for (const entity of store.scene.entities) {for (const comp of entity.components) {if (comp.type === 'Canvas') {- return (comp.data.pixelsPerUnit as number) || 100;+ return (comp.data.pixelsPerUnit as number) || DEFAULT_PIXELS_PER_UNIT;}}}- return 100;+ return DEFAULT_PIXELS_PER_UNIT;}private cloneColliderData(comp: ComponentData): Record<string, unknown> {diff --git a/editor/src/launcher/ProjectService.ts b/editor/src/launcher/ProjectService.tsindex 16265b873..497b51caa 100644--- a/editor/src/launcher/ProjectService.ts+++ b/editor/src/launcher/ProjectService.ts@@ -9,6 +9,7 @@ import type {ProjectTemplate,} from '../types/ProjectTypes';import { ENGINE_VERSION } from '../types/ProjectTypes';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from 'esengine';import { SdkExportService } from '../sdk';import { EditorExportService } from '../extension';import { getEditorContext } from '../context/EditorContext';@@ -128,7 +129,7 @@ export async function createProject(created: now,modified: now,spineVersion: 'none',- designResolution: { width: 1920, height: 1080 },+ designResolution: { width: DEFAULT_DESIGN_WIDTH, height: DEFAULT_DESIGN_HEIGHT },};const projectFilePath = joinPath(projectDir, 'project.esproject');@@ -343,7 +344,7 @@ function createDefaultScene(_template: ProjectTemplate,designResolution: { width: number; height: number },) {- const pixelsPerUnit = 100;+ const pixelsPerUnit = DEFAULT_PIXELS_PER_UNIT;const orthoSize = designResolution.height / 2;return {diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.tsindex 43c552490..eee9ca889 100644--- a/editor/src/panels/ContentBrowserPanel.ts+++ b/editor/src/panels/ContentBrowserPanel.ts@@ -17,6 +17,7 @@ import { getGlobalPathResolver } from '../asset';import { showErrorToast } from '../ui/Toast';import { createEmptyScene } from '../types/SceneTypes';import { getSettingsValue } from '../settings';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT } from 'esengine';// =============================================================================// Types@@ -816,8 +817,8 @@ export const ${className} = defineComponent('${className}', {const platform = getPlatformAdapter();const filePath = `${parentPath}/${name}`;- const w = getSettingsValue<number>('project.designWidth') || 1920;- const h = getSettingsValue<number>('project.designHeight') || 1080;+ const w = getSettingsValue<number>('project.designWidth') || DEFAULT_DESIGN_WIDTH;+ const h = getSettingsValue<number>('project.designHeight') || DEFAULT_DESIGN_HEIGHT;const scene = createEmptyScene(name.replace('.esscene', ''), { width: w, height: h });const content = JSON.stringify(scene, null, 2);diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex 686f475fd..046107f1a 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -89,8 +89,8 @@ export const CameraSchema: ComponentSchema = {name: 'projectionType',type: 'enum',options: [- { label: 'Orthographic', value: 0 },- { label: 'Perspective', value: 1 },+ { label: 'Perspective', value: 0 },+ { label: 'Orthographic', value: 1 },],},{ name: 'fov', type: 'number', min: 1, max: 179 },@@ -486,10 +486,6 @@ export function getDefaultComponentData(typeName: string): Record<string, unknow}const editorInitialOverrides: Record<string, Record<string, unknown>> = {- Camera: {- projectionType: 1,- orthoSize: 540,- },BitmapText: {text: 'BitmapText',font: '',diff --git a/editor/src/settings/builtinSettings.ts b/editor/src/settings/builtinSettings.tsindex 05e879dc8..3df050a67 100644--- a/editor/src/settings/builtinSettings.ts+++ b/editor/src/settings/builtinSettings.ts@@ -1,4 +1,5 @@import { registerSettingsSection, registerSettingsItem } from './SettingsRegistry';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT } from 'esengine';export function registerBuiltinSettings(): void {registerSettingsSection({@@ -124,7 +125,7 @@ export function registerBuiltinSettings(): void {section: 'project',label: 'Design Width',type: 'number',- defaultValue: 1920,+ defaultValue: DEFAULT_DESIGN_WIDTH,min: 1,step: 1,order: 4,@@ -135,7 +136,7 @@ export function registerBuiltinSettings(): void {section: 'project',label: 'Design Height',type: 'number',- defaultValue: 1080,+ defaultValue: DEFAULT_DESIGN_HEIGHT,min: 1,step: 1,order: 5,diff --git a/editor/src/types/BuildTypes.ts b/editor/src/types/BuildTypes.tsindex 3dcad23f4..50647e4d2 100644--- a/editor/src/types/BuildTypes.ts+++ b/editor/src/types/BuildTypes.ts@@ -30,6 +30,7 @@ export interface PlayableSettings {minifyCode: boolean;embedFonts: boolean;outputPath: string;+ ctaUrl: string;}export interface WeChatSubpackage {@@ -80,6 +81,7 @@ export function createDefaultPlayableSettings(): PlayableSettings {minifyCode: false,embedFonts: true,outputPath: 'build/playable.html',+ ctaUrl: '',};}@@ -132,6 +134,7 @@ export function createDefaultBuildSettings(): BuildSettings {minifyCode: false,embedFonts: true,outputPath: 'build/playable-dev.html',+ ctaUrl: '',},},{@@ -146,6 +149,7 @@ export function createDefaultBuildSettings(): BuildSettings {minifyCode: true,embedFonts: true,outputPath: 'build/playable.html',+ ctaUrl: '',},},{diff --git a/editor/src/types/SceneTypes.ts b/editor/src/types/SceneTypes.tsindex b4b6002c2..b938d452e 100644--- a/editor/src/types/SceneTypes.ts+++ b/editor/src/types/SceneTypes.ts@@ -4,6 +4,7 @@*/import type { Entity } from 'esengine';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from 'esengine';import type { TextureMetadata } from './TextureMetadata';import type { PrefabInstanceData } from './PrefabTypes';@@ -58,8 +59,8 @@ export function createEmptyScene(name: string = 'Untitled',designResolution?: { width: number; height: number },): SceneData {- const res = designResolution ?? { width: 1920, height: 1080 };- const pixelsPerUnit = 100;+ const res = designResolution ?? { width: DEFAULT_DESIGN_WIDTH, height: DEFAULT_DESIGN_HEIGHT };+ const pixelsPerUnit = DEFAULT_PIXELS_PER_UNIT;const orthoSize = res.height / 2;return {diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex f16bf1acb..8141c3712 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -18,6 +18,7 @@ import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';import { initRendererAPI, shutdownRendererAPI } from './renderer';import { initGLDebugAPI, shutdownGLDebugAPI } from './glDebug';import { platformNow } from './platform';+import { ProjectionType, ScaleMode } from './component';import { RenderPipeline, type SpineRendererFn } from './renderPipeline';import { Renderer } from './renderer';import { PostProcess } from './postprocess';@@ -466,11 +467,11 @@ function computeEffectiveOrthoSize(const orthoForHeight = baseOrthoSize;switch (scaleMode) {- case 0: return orthoForWidth;- case 1: return orthoForHeight;- case 2: return Math.max(orthoForWidth, orthoForHeight);- case 3: return Math.min(orthoForWidth, orthoForHeight);- case 4: {+ case ScaleMode.FixedWidth: return orthoForWidth;+ case ScaleMode.FixedHeight: return orthoForHeight;+ case ScaleMode.Expand: return Math.max(orthoForWidth, orthoForHeight);+ case ScaleMode.Shrink: return Math.min(orthoForWidth, orthoForHeight);+ case ScaleMode.Match: {const t = matchWidthOrHeight;return Math.pow(orthoForWidth, 1 - t) * Math.pow(orthoForHeight, t);}@@ -513,7 +514,7 @@ function collectCameras(module: ESEngineModule, registry: CppRegistry, width: nulet camHalfW = 0;let camHalfH = 0;- if (camera.projectionType === 1) {+ if (camera.projectionType === ProjectionType.Orthographic) {camHalfH = camera.orthoSize;if (canvas) {@@ -566,7 +567,7 @@ function computeViewProjection(module: ESEngineModule, registry: CppRegistry, wiconst aspect = width / height;let projection: Float32Array;- if (camera.projectionType === 1) {+ if (camera.projectionType === ProjectionType.Orthographic) {let halfH = camera.orthoSize;const canvas = findCanvasData(module, registry);diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex b19866755..c97523f86 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -4,6 +4,7 @@*/import type { Entity, TextureHandle, FontHandle } from '../types';+import { DEFAULT_TEXT_CANVAS_SIZE } from '../defaults';import type { ESEngineModule } from '../wasm';import type { ShaderHandle } from '../material';import { Material } from '../material';@@ -130,7 +131,7 @@ export class AssetServer {constructor(module: ESEngineModule) {this.module_ = module;- this.canvas_ = platformCreateCanvas(512, 512) as HTMLCanvasElement;+ this.canvas_ = platformCreateCanvas(DEFAULT_TEXT_CANVAS_SIZE, DEFAULT_TEXT_CANVAS_SIZE) as HTMLCanvasElement;this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true })!;const shaderLoader: ShaderLoader = {diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex 833e75605..82dbbee35 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -4,6 +4,7 @@*/import { Entity, Vec2, Vec3, Color, Quat, INVALID_TEXTURE, INVALID_FONT } from './types';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from './defaults';import type {RigidBodyData, BoxColliderData, CircleColliderData, CapsuleColliderData,} from './physics/PhysicsComponents';@@ -130,6 +131,36 @@ export function defineBuiltin<T>(name: string, defaults: T): BuiltinComponentDefreturn def;}+// =============================================================================+// Camera / Canvas Enums+// =============================================================================++export const ProjectionType = {+ Perspective: 0,+ Orthographic: 1,+} as const;++export type ProjectionType = (typeof ProjectionType)[keyof typeof ProjectionType];++export const ClearFlags = {+ None: 0,+ ColorOnly: 1,+ DepthOnly: 2,+ ColorAndDepth: 3,+} as const;++export type ClearFlags = (typeof ClearFlags)[keyof typeof ClearFlags];++export const ScaleMode = {+ FixedWidth: 0,+ FixedHeight: 1,+ Expand: 2,+ Shrink: 3,+ Match: 4,+} as const;++export type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];+// =============================================================================// Builtin Component Types// =============================================================================@@ -255,26 +286,26 @@ export const Sprite = defineBuiltin<SpriteData>('Sprite', {});export const Camera = defineBuiltin<CameraData>('Camera', {- projectionType: 0,+ projectionType: ProjectionType.Orthographic,fov: 60,- orthoSize: 5,+ orthoSize: 540,nearPlane: 0.1,farPlane: 1000,aspectRatio: 1.77,isActive: true,priority: 0,- showFrustum: true,+ showFrustum: false,viewportX: 0,viewportY: 0,viewportW: 1,viewportH: 1,- clearFlags: 3,+ clearFlags: ClearFlags.ColorAndDepth,});export const Canvas = defineBuiltin<CanvasData>('Canvas', {- designResolution: { x: 1920, y: 1080 },- pixelsPerUnit: 100,- scaleMode: 1,+ designResolution: { x: DEFAULT_DESIGN_WIDTH, y: DEFAULT_DESIGN_HEIGHT },+ pixelsPerUnit: DEFAULT_PIXELS_PER_UNIT,+ scaleMode: ScaleMode.FixedHeight,matchWidthOrHeight: 0.5,backgroundColor: { r: 0, g: 0, b: 0, a: 1 }});diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex f9d703065..48a775ed4 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -3,6 +3,17 @@* @brief ESEngine SDK - Core exports (no platform initialization)*/+// =============================================================================+// Defaults+// =============================================================================++export {+ DEFAULT_DESIGN_WIDTH,+ DEFAULT_DESIGN_HEIGHT,+ DEFAULT_PIXELS_PER_UNIT,+ DEFAULT_TEXT_CANVAS_SIZE,+} from './defaults';+// =============================================================================// Types// =============================================================================@@ -54,6 +65,9 @@ export {BitmapText,SpineAnimation,Name,+ ProjectionType,+ ClearFlags,+ ScaleMode,type LocalTransformData,type WorldTransformData,type SpriteData,diff --git a/sdk/src/defaults.ts b/sdk/src/defaults.tsnew file mode 100644index 000000000..57364133e--- /dev/null+++ b/sdk/src/defaults.ts@@ -0,0 +1,4 @@+export const DEFAULT_DESIGN_WIDTH = 1920;+export const DEFAULT_DESIGN_HEIGHT = 1080;+export const DEFAULT_PIXELS_PER_UNIT = 100;+export const DEFAULT_TEXT_CANVAS_SIZE = 512;diff --git a/sdk/src/platform/wechat/image.ts b/sdk/src/platform/wechat/image.tsindex 24a16fa1d..53d9b4c4a 100644--- a/sdk/src/platform/wechat/image.ts+++ b/sdk/src/platform/wechat/image.ts@@ -19,26 +19,15 @@ export interface ImageLoadResult {// Canvas Management// =============================================================================-let offscreenCanvas: WechatMinigame.Canvas | null = null;-let offscreenCtx: CanvasRenderingContext2D | null = null;-function getOffscreenCanvas(width: number, height: number): {canvas: WechatMinigame.Canvas;ctx: CanvasRenderingContext2D;} {- if (!offscreenCanvas) {- offscreenCanvas = wx.createCanvas();- offscreenCanvas.width = width;- offscreenCanvas.height = height;- offscreenCtx = offscreenCanvas.getContext('2d') as CanvasRenderingContext2D;- }-- if (offscreenCanvas.width < width || offscreenCanvas.height < height) {- offscreenCanvas.width = Math.max(offscreenCanvas.width, width);- offscreenCanvas.height = Math.max(offscreenCanvas.height, height);- }-- return { canvas: offscreenCanvas, ctx: offscreenCtx! };+ const canvas = wx.createCanvas();+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;+ return { canvas, ctx };}// =============================================================================diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.tsindex 6f0e2de22..3017217da 100644--- a/sdk/src/platform/wechat/index.ts+++ b/sdk/src/platform/wechat/index.ts@@ -67,20 +67,30 @@ class WeChatPlatformAdapter implements PlatformAdapter {}bindInputEvents(callbacks: InputEventCallbacks, _target?: unknown): void {+ const { pixelRatio } = wx.getSystemInfoSync();+wx.onTouchStart((e: any) => {- const touch = e.touches[0];- if (touch) {- callbacks.onPointerDown(0, touch.clientX, touch.clientY);+ for (const touch of e.touches) {+ callbacks.onPointerDown(+ touch.identifier,+ touch.clientX * pixelRatio,+ touch.clientY * pixelRatio+ );}});wx.onTouchMove((e: any) => {const touch = e.touches[0];if (touch) {- callbacks.onPointerMove(touch.clientX, touch.clientY);+ callbacks.onPointerMove(+ touch.clientX * pixelRatio,+ touch.clientY * pixelRatio+ );}});- wx.onTouchEnd(() => {- callbacks.onPointerUp(0);+ wx.onTouchEnd((e: any) => {+ for (const touch of e.changedTouches) {+ callbacks.onPointerUp(touch.identifier);+ }});}}diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 17064587c..4ce331259 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -6,7 +6,8 @@import type { App, Plugin } from '../app';import type { SceneData } from '../scene';import { loadRuntimeScene } from '../runtimeLoader';-import { LocalTransform, Camera, Canvas, type LocalTransformData, type CameraData, type CanvasData } from '../component';+import { LocalTransform, Camera, Canvas, ProjectionType, ClearFlags, type LocalTransformData, type CameraData, type CanvasData } from '../component';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from '../defaults';import { platformFetch } from '../platform';import { WebAssetProvider } from './WebAssetProvider';@@ -96,13 +97,13 @@ export class PreviewPlugin implements Plugin {console.warn('[PreviewPlugin] No active camera found, creating default camera');let orthoSize = 540;- let aspectRatio = 1920 / 1080;+ let aspectRatio = DEFAULT_DESIGN_WIDTH / DEFAULT_DESIGN_HEIGHT;const canvasEntities = world.getEntitiesWithComponents([Canvas]);for (const entity of canvasEntities) {const canvas = world.get(entity, Canvas) as CanvasData;if (canvas.designResolution) {- const ppu = canvas.pixelsPerUnit || 100;+ const ppu = canvas.pixelsPerUnit || DEFAULT_PIXELS_PER_UNIT;orthoSize = (canvas.designResolution.y / 2) / ppu;aspectRatio = canvas.designResolution.x / canvas.designResolution.y;break;@@ -120,19 +121,19 @@ export class PreviewPlugin implements Plugin {const cameraData: CameraData = {isActive: true,- projectionType: 1,+ projectionType: ProjectionType.Orthographic,fov: 60,orthoSize,nearPlane: 0.1,farPlane: 1000,aspectRatio,priority: 0,- showFrustum: true,+ showFrustum: false,viewportX: 0,viewportY: 0,viewportW: 1,viewportH: 1,- clearFlags: 3,+ clearFlags: ClearFlags.ColorAndDepth,};world.insert(cameraEntity, Camera, cameraData);}diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.tsindex 248433334..3cb5a19e1 100644--- a/sdk/src/ui/TextInputPlugin.ts+++ b/sdk/src/ui/TextInputPlugin.ts@@ -1,6 +1,7 @@import type { App, Plugin } from '../app';import type { Entity } from '../types';import { INVALID_TEXTURE } from '../types';+import { DEFAULT_TEXT_CANVAS_SIZE } from '../defaults';import { defineSystem, Schedule } from '../system';import { registerComponent, Sprite, type SpriteData } from '../component';import { TextInput, type TextInputData } from './TextInput';@@ -23,7 +24,7 @@ export class TextInputPlugin implements Plugin {const world = app.world;const textureCache = new Map<Entity, number>();- const canvas = platformCreateCanvas(512, 64);+ const canvas = platformCreateCanvas(DEFAULT_TEXT_CANVAS_SIZE, 64);const ctx = canvas.getContext('2d', { willReadFrequently: true })! asCanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.tsindex 67bc3b239..ac66f23da 100644--- a/sdk/src/ui/TextRenderer.ts+++ b/sdk/src/ui/TextRenderer.ts@@ -4,6 +4,7 @@*/import type { Entity, Vec2 } from '../types';+import { DEFAULT_TEXT_CANVAS_SIZE } from '../defaults';import type { ESEngineModule, CppResourceManager } from '../wasm';import { TextAlign, TextVerticalAlign, TextOverflow, type TextData } from './text';import type { UIRectData } from './UIRect';@@ -31,7 +32,7 @@ export class TextRenderer {constructor(module: ESEngineModule) {this.module = module;- this.canvas = platformCreateCanvas(512, 512);+ this.canvas = platformCreateCanvas(DEFAULT_TEXT_CANVAS_SIZE, DEFAULT_TEXT_CANVAS_SIZE);this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })! as CanvasRenderingContext2D;}