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
refactor: architecture improvements across editor and SDK
esengined33415b369d4
diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex b11718819..db2c55cde 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -40,7 +40,7 @@ export default {},},physics: {- buildDir: 'build-web',+ buildDir: 'build-physics',cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_BOX2D=ON'],targets: ['physics_module'],outputs: {diff --git a/build-tools/cli.js b/build-tools/cli.jsindex ce8f87f42..b81ffae6e 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -7,7 +7,7 @@ import config from './build.config.js';import * as logger from './utils/logger.js';import { checkEnvironment } from './utils/emscripten.js';import { runEht } from './tasks/eht.js';-import { buildWasm, cleanWasm } from './tasks/wasm.js';+import { buildWasm, buildWasmParallel, cleanWasm } from './tasks/wasm.js';import { buildSdk, cleanSdk } from './tasks/sdk.js';import { syncToDesktop } from './tasks/sync.js';import { startWatch } from './tasks/watch.js';@@ -52,10 +52,7 @@ programif (wasmTargets.length > 0) {await runEht({ noCache: !options.cache });-- for (const target of wasmTargets) {- await buildWasm(target, { debug: isDebug, clean: options.clean });- }+ await buildWasmParallel(wasmTargets, { debug: isDebug, clean: options.clean });}if (buildSdkFlag) {diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.jsindex 9bdf56ddd..9ed0d55fc 100644--- a/build-tools/tasks/wasm.js+++ b/build-tools/tasks/wasm.js@@ -91,13 +91,34 @@ async function copyOutputs(buildDir, outputDir, outputs) {}}-export async function buildAllWasm(options = {}) {- const results = [];- for (const target of Object.keys(config.wasm)) {- const result = await buildWasm(target, options);- results.push(result);+export async function buildWasmParallel(targets, options = {}) {+ const groups = new Map();+ for (const target of targets) {+ const targetConfig = config.wasm[target];+ if (!targetConfig) {+ throw new Error(`Unknown target: ${target}. Available: ${Object.keys(config.wasm).join(', ')}`);+ }+ const dir = targetConfig.buildDir;+ if (!groups.has(dir)) {+ groups.set(dir, []);+ }+ groups.get(dir).push(target);}- return results;++ const groupPromises = [];+ for (const groupTargets of groups.values()) {+ groupPromises.push((async () => {+ for (const target of groupTargets) {+ await buildWasm(target, options);+ }+ })());+ }++ await Promise.all(groupPromises);+}++export async function buildAllWasm(options = {}) {+ await buildWasmParallel(Object.keys(config.wasm), options);}export async function cleanWasm(target = null) {diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 1d7b271d2..d2e2d4311 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 B(e,t){I.set(e,t)}function F(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}}),H=U("Parent",{entity:0}),O=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})};B("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,Be=new Map;let Fe=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=Be.get(a);e||(Fe||(Fe=new TextEncoder),e=Fe.encode(a),Be.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(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const s=this.pending_.get(e);if(s)return s;const n=this.loadInternal(e);this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(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}}function De(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)Le(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 ze(e,t,s){const n=new Map,r=s?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(n.set(i.id,t),e.insert(t,V,{value:i.name}),!1!==i.visible)for(const n of i.components){if("Sprite"===n.type&&r){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:s?.assetBaseUrl?`${s.assetBaseUrl}/${t}`:`/${t}`;try{const s=await r.loadTexture(n);e.texture=s.handle,o.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===n.type&&r){const e=n.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,s?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===n.type&&r){const e=n.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,s?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Le(e,t,n)}}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function Le(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=F(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class He{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 Oe{constructor(e){this.textureCache_=new He,this.shaderCache_=new He,this.jsonCache_=new He,this.textCache_=new He,this.binaryCache_=new He,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new He,this.prefabCache_=new He,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 $e(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}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 ze(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 Ne=Q(null,"Assets");class je{build(e){const t=e.wasmModule;t?e.insertResource(Ne,new Oe(t)):console.warn("AssetPlugin: No WASM module available")}}const Ve=new je;async function Xe(e,t,s){const{entities:n,rootId:r}=await Ge(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 ze(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 Ge(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 Ge(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};qe(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 qe(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 Ye{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 Xe(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Je=Q(null,"Prefabs");class Ke{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ne]}build(e){const t=e.getResource(Ne);e.insertResource(Je,new Ye(e.world,t))}}const Qe=new Ke;let Ze=null,et=0,tt=0,st=0;const nt=new Float32Array(256);function rt(e){Ze=e,et=Ze._malloc(64),tt=Ze._malloc(64),st=Ze._malloc(1024)}function ot(){Ze&&(et&&(Ze._free(et),et=0),tt&&(Ze._free(tt),tt=0),st&&(Ze._free(st),st=0)),Ze=null}function it(){if(!Ze)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ze}const at={r:1,g:1,b:1,a:1},lt={begin(e){const t=it();t.HEAPF32.set(e,et/4),t.draw_begin(et)},end(){it().draw_end()},line(e,t,s,n=1){it().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){it().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){it().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){it().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){it().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=at){it().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=at){it().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){it().draw_setLayer(e)},setDepth(e){it().draw_setDepth(e)},getDrawCallCount:()=>Ze?Ze.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ze?Ze.draw_getPrimitiveCount():0,setBlendMode(e){it().draw_setBlendMode(e)},setDepthTest(e){it().draw_setDepthTest(e)},drawMesh(e,t,s){const n=it();n.HEAPF32.set(s,tt/4),n.draw_mesh(e,t,tt)},drawMeshWithMaterial(e,t,s){const n=it(),r=Ee.get(t);if(!r)return;if(lt.setBlendMode(r.blendMode),lt.setDepthTest(r.depthTest),0===r.uniforms.size)return void lt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,tt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ut(t);if(!(n<0)){if(we(s))nt[o++]=10,nt[o++]=n,nt[o++]=s.slot??e++,nt[o++]=s.textureId;else if("number"==typeof s)nt[o++]=1,nt[o++]=n,nt[o++]=s;else if(Array.isArray(s)){nt[o++]=s.length,nt[o++]=n;for(let e=0;e<s.length;e++)nt[o++]=s[e]}else"w"in s?(nt[o++]=4,nt[o++]=n,nt[o++]=s.x,nt[o++]=s.y,nt[o++]=s.z,nt[o++]=s.w):"z"in s?(nt[o++]=3,nt[o++]=n,nt[o++]=s.x,nt[o++]=s.y,nt[o++]=s.z):(nt[o++]=2,nt[o++]=n,nt[o++]=s.x,nt[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(nt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),st/4),n.draw_meshWithUniforms(e,r.shader,tt,st,o)):n.draw_mesh(e,r.shader,tt)}},ct={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 ut(e){return ct[e]??-1}var dt;exports.DataType=void 0,(dt=exports.DataType||(exports.DataType={}))[dt.Float=1]="Float",dt[dt.Float2=2]="Float2",dt[dt.Float3=3]="Float3",dt[dt.Float4=4]="Float4",dt[dt.Int=5]="Int",dt[dt.Int2=6]="Int2",dt[dt.Int3=7]="Int3",dt[dt.Int4=8]="Int4";let ht=null,pt=0,ft=0,mt=0;function gt(e){ht=e,pt=ht._malloc(262144),ft=ht._malloc(65536),mt=ht._malloc(256)}function yt(){ht&&(pt&&ht._free(pt),ft&&ht._free(ft),mt&&ht._free(mt),pt=0,ft=0,mt=0),ht=null}function xt(){if(!ht)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ht}const _t={create(e){const t=xt(),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,pt/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,mt,r).set(o),t.geometry_init(s,pt,n,mt,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,ft,n).set(e.indices),t.geometry_setIndices16(s,ft,n)}else{new Uint32Array(t.HEAPU8.buffer,ft,n).set(e.indices),t.geometry_setIndices32(s,ft,n)}}return s},updateVertices(e,t,s=0){const n=xt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,pt/4),n.geometry_updateVertices(e,pt,r,s)},release(e){e>0&&xt().geometry_release(e)},isValid:e=>!(!ht||e<=0)&&ht.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return _t.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 _t.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 _t.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 wt=null;function vt(e){wt=e}function bt(){wt&&St.isInitialized()&&St.shutdown(),wt=null}function Pt(){if(!wt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return wt}const St={init:(e,t)=>Pt().postprocess_init(e,t),shutdown(){Pt().postprocess_shutdown()},resize(e,t){Pt().postprocess_resize(e,t)},addPass:(e,t)=>Pt().postprocess_addPass(e,t),removePass(e){Pt().postprocess_removePass(e)},setEnabled(e,t){Pt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Pt().postprocess_isPassEnabled(e),setUniform(e,t,s){Pt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Pt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Pt().postprocess_begin()},end(){Pt().postprocess_end()},getPassCount:()=>Pt().postprocess_getPassCount(),isInitialized:()=>!!wt&&wt.postprocess_isInitialized(),setBypass(e){Pt().postprocess_setBypass(e)},isBypassed:()=>!wt||wt.postprocess_isBypassed(),createBlur:()=>Ee.createShader(Ct,"#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(Ct,"#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(Ct,"#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(Ct,"#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")},Ct="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Tt;exports.RenderStage=void 0,(Tt=exports.RenderStage||(exports.RenderStage={}))[Tt.Background=0]="Background",Tt[Tt.Opaque=1]="Opaque",Tt[Tt.Transparent=2]="Transparent",Tt[Tt.Overlay=3]="Overlay";let At=null,Et=0;function Mt(e){At=e,Et=At._malloc(64)}function Rt(){At&&Et&&(At._free(Et),Et=0),At=null}const It={init(e,t){At?.renderer_init(e,t)},resize(e,t){At?.renderer_resize(e,t)},begin(e,t){At&&Et&&(At.HEAPF32.set(e,Et/4),At.renderer_begin(Et,t??0))},flush(){At?.renderer_flush()},end(){At?.renderer_end()},submitSprites(e){At&&At.renderer_submitSprites(e._cpp)},submitBitmapText(e){At&&At.renderer_submitBitmapText(e._cpp)},submitSpine(e){At&&At.renderer_submitSpine?.(e._cpp)},setStage(e){At?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>At?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){At?.renderer_releaseTarget(e)},getTargetTexture:e=>At?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>At?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){At?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){At?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){At?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){At?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>At?At.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>At?{drawCalls:At.renderer_getDrawCalls(),triangles:At.renderer_getTriangles(),sprites:At.renderer_getSprites(),text:At.renderer_getText(),spine:At.renderer_getSpine?.()??0,meshes:At.renderer_getMeshes(),culled:At.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Bt=null;function Ft(e){Bt=e}function Ut(){Bt=null}const kt={enable(){Bt?.gl_enableErrorCheck(!0)},disable(){Bt?.gl_enableErrorCheck(!1)},check:e=>Bt?.gl_checkErrors(e)??0,diagnose(){Bt?.renderer_diagnose()}},Wt=new Map;function $t(e){Wt.delete(e)}class Dt{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_||(It.resize(n,r),St.isInitialized()&&St.getPassCount()>0&&St.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),It.setViewport(0,0,n,r),It.clearBuffers(3),It.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),It.submitSprites(t),It.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):It.submitSpine(t),It.flush(),this.executeDrawCallbacks(s,o),It.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;It.setViewport(n.x,n.y,n.w,n.h),It.setScissor(n.x,n.y,n.w,n.h,!0),It.clearBuffers(r),It.setScissor(0,0,0,0,!1),It.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),It.submitSprites(t),It.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):It.submitSpine(t),It.flush(),this.executeDrawCallbacks(s,o),It.end()}executeDrawCallbacks(e,t){const s=Wt;if(s.size>0){lt.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)}lt.end();for(const e of n)$t(e)}}}class zt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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 zt}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,Ut(),Rt(),bt(),yt(),Te(),ot()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}const Lt=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 Ot(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=jt(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Xt(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=qt(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Yt(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 Nt=new Float32Array(16);function jt(e,t,s,n,r,o){const i=Nt;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 Vt=new Float32Array(16);function Xt(e,t,s,n){const r=Vt;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 Gt=new Float32Array(16);function qt(e,t,s){const n=Gt;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 Yt(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 Jt,Kt,Qt;exports.TextAlign=void 0,(Jt=exports.TextAlign||(exports.TextAlign={}))[Jt.Left=0]="Left",Jt[Jt.Center=1]="Center",Jt[Jt.Right=2]="Right",exports.TextVerticalAlign=void 0,(Kt=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Kt.Top=0]="Top",Kt[Kt.Middle=1]="Middle",Kt[Kt.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Qt=exports.TextOverflow||(exports.TextOverflow={}))[Qt.Visible=0]="Visible",Qt[Qt.Clip=1]="Clip",Qt[Qt.Ellipsis=2]="Ellipsis";const Zt=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}),es=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 ts{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 ss(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 ns(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 rs{build(e){B("Text",Zt);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new ts(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Zt));for(const e of r.keys())n.valid(e)&&n.has(e,Zt)||r.delete(e);const e=n.getEntitiesWithComponents([Zt]);for(const t of e){const e=n.get(t,Zt),o=n.has(t,es)?n.get(t,es):null,i=r.get(t);if(i&&!ns(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,ss(e,o))}}))}}const os=new rs,is=T("UIMask",{enabled:!0});function as(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 ls(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 cs(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 us(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 ds(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 hs(e,t,s,n,r,o,i){if(!e.has(t,es)||!e.has(t,W))return null;const a=e.get(t,es),l=e.get(t,W),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ls(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function ps(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([is]);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,is).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,H);){const e=t.get(n,H);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=hs(t,s,r,o,i,a,l);e&&(n=as(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=hs(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 fs{build(e){if(B("UIMask",is),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ps(e.wasmModule,e.world))}}const ms=new fs,gs=T("Interactable",{enabled:!0}),ys=T("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var xs;exports.ButtonState=void 0,(xs=exports.ButtonState||(exports.ButtonState={}))[xs.Normal=0]="Normal",xs[xs.Hovered=1]="Hovered",xs[xs.Pressed=2]="Pressed",xs[xs.Disabled=3]="Disabled";const _s=T("Button",{state:exports.ButtonState.Normal,transition:null});class ws{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 vs=Q(new ws,"UIEvents"),bs=A("ScreenSpace");function Ps(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 Ss(e,t,s,n,r,o){if(!e.has(t,es))return;const i=e.get(t,es),a=Ps(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,O))return;const c=e.get(t,O);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ss(e,t,a.rect,a.centerX,a.centerY,!1)}class Cs{build(e){B("UIRect",es);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([bs,es,k]);for(const e of o)Ss(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Ts=new Cs,As=new Float32Array(16),Es=new Float32Array(16);let Ms=!0,Rs=1;class Is{build(e){B("Interactable",gs),B("Button",_s);const t=e.world,s=new ws;e.insertResource(vs,s);let n=null,r=null;Rs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([Z(pe),Z(xe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([ys]);for(const e of i){const s=t.get(e,ys);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Rs,l=o.screenH-e.mouseY*Rs;!function(e){let t=!1;for(let s=0;s<16;s++)if(Es[s]!==e[s]){t=!0;break}t&&(Es.set(e),Ms=!0)}(o.viewProjection),Ms&&(cs(o.viewProjection,As),Ms=!1);const c=us(a,l,As,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([gs,es,W]);let d=null,h=-1/0;for(const e of u){t.has(e,ys)||t.insert(e,ys);if(!t.get(e,gs).enabled)continue;const s=t.get(e,W),n=t.get(e,es),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(ds(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,ys)){t.get(n,ys).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,ys).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,ys);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ys)){const e=t.get(r,ys);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,ce([],()=>{const e=t.getEntitiesWithComponents([_s]);for(const s of e){if(t.has(s,gs)||t.insert(s,gs,{enabled:!0}),!t.has(s,ys))continue;const e=t.get(s,ys),n=t.get(s,_s),r=t.get(s,gs),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 Is,Fs=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 Us{build(e){B("TextInput",Fs);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,Fs);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(vs).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,Fs);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,Fs)){const e=s.get(a,Fs);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=Ws(Math.max(r.width,a)),r.height=Ws(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=ks(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=ks(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,Fs);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(vs).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,Fs)){const e=s.get(a,Fs);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,ce([Z(vs)],e=>{const t=s.getEntitiesWithComponents([Fs,gs]);for(const e of t){if(!s.has(e,ys))continue;if(s.get(e,ys).justPressed)return void m(e)}if(null!==a){const e=s.getEntitiesWithComponents([gs]);for(const t of e){if(s.has(t,Fs))continue;if(!s.has(t,ys))continue;if(s.get(t,ys).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,Fs)))){s.get(a,Fs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Fs)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([Fs,es]);for(const e of i){const t=s.get(e,Fs);if(!t.dirty)continue;const n=s.get(e,es),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 ks(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 Ws(e){let t=1;for(;t<e;)t*=2;return t}const $s=new Us;async function Ds(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 zs=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ls=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 Os(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Ns{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(zs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Ds(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),js(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,H)){const t=e.world.get(i,H);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=Os(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(zs,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Ls,Vs._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function js(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 Vs{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(Vs.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 Xs(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 Gs(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 qs(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 Ys(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]=Xs(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=Gs(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=Xs(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 Ns("",{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=Xs(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=De(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=qs(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(Ne);t&&t.setAddressableManifest(a)}}class Js{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(()=>{}));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(()=>{}));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(()=>{}))}}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 Ks={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=It.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:It.getTargetTexture(s),width:e.width,height:e.height}},release(e){It.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(It.releaseRenderTarget(e._handle),Ks.create({width:t,height:s,depth:!0})),begin(e,t){It.begin(t,e._handle)},end(){It.end()},getDepthTexture:e=>It.getTargetDepthTexture(e._handle)};let Qs=!1;const Zs=[os,ms,Ts,Bs,$s];_||(_=!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=zt,exports.AssetPlugin=je,exports.AssetServer=Oe,exports.Assets=Ne,exports.AsyncCache=He,exports.BitmapText=N,exports.BodyType=J,exports.BoxCollider=G,exports.Button=_s,exports.Camera=D,exports.Canvas=z,exports.CapsuleCollider=Y,exports.Children=O,exports.CircleCollider=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=ie,exports.Draw=lt,exports.EntityCommands=oe,exports.GLDebug=kt,exports.Geometry=_t,exports.INVALID_ENTITY=0,exports.INVALID_FONT=b,exports.INVALID_TEXTURE=v,exports.Input=pe,exports.InputPlugin=fe,exports.InputState=he,exports.Interactable=gs,exports.LocalTransform=k,exports.Material=Ee,exports.MaterialLoader=$e,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=V,exports.Parent=H,exports.Physics=Vs,exports.PhysicsEvents=zs,exports.PhysicsPlugin=Ns,exports.PostProcess=St,exports.PrefabServer=Ye,exports.Prefabs=Je,exports.PrefabsPlugin=Ke,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 Js(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 Ys(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=Dt,exports.RenderTexture=Ks,exports.Renderer=It,exports.Res=Z,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=X,exports.ScreenSpace=bs,exports.ShaderSources=We,exports.SpineAnimation=j,exports.Sprite=$,exports.SystemRunner=de,exports.Text=Zt,exports.TextInput=Fs,exports.TextInputPlugin=Us,exports.TextPlugin=rs,exports.TextRenderer=ts,exports.Time=se,exports.UICameraInfo=xe,exports.UIEventQueue=ws,exports.UIEvents=vs,exports.UIInteraction=ys,exports.UIInteractionPlugin=Is,exports.UILayoutPlugin=Cs,exports.UIMask=is,exports.UIMaskPlugin=fs,exports.UIRect=es,exports.Velocity=L,exports.WebAssetProvider=Js,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=Ve,exports.clearDrawCallbacks=function(){Wt.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=Ps,exports.createMaskProcessor=ps,exports.createWebApp=function(e,t){return function(e,t){const s=zt.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),rt(e),Ce(e),gt(e),vt(e),Mt(e),Ft(e);const r=new Dt;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=Ot(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;It.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;It.resize(t,s),St.isInitialized()&&St.getPassCount()>0&&!St.isBypassed()&&St.resize(t,s);const d=Ot(e,n,t,s);if(l(t,s),0===d.length)r.render({registry:{_cpp:n},viewProjection:Lt,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})}It.setViewport(0,0,t,s)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Ve),s.addPlugin(Qe),s.addPlugin(me),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Zs,...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=F,exports.getComponentDefaults=function(e){const t=F(e);return t?{...t._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=E,exports.initDrawAPI=rt,exports.initGLDebugAPI=Ft,exports.initGeometryAPI=gt,exports.initMaterialAPI=Ce,exports.initPostProcessAPI=vt,exports.initRendererAPI=Mt,exports.inputPlugin=me,exports.instantiatePrefab=Xe,exports.intersectRects=as,exports.invertMatrix4=cs,exports.isBuiltinComponent=R,exports.isEditor=function(){return Qs},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Qs},exports.isTextureRef=we,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Le,exports.loadPhysicsModule=Ds,exports.loadRuntimeScene=Ys,exports.loadSceneData=De,exports.loadSceneWithAssets=ze,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=ds,exports.prefabsPlugin=Qe,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=B,exports.registerDrawCallback=function(e,t){Wt.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Ne);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ke,exports.screenToWorld=us,exports.setEditorMode=function(e){Qs=e},exports.shutdownDrawAPI=ot,exports.shutdownGLDebugAPI=Ut,exports.shutdownGeometryAPI=yt,exports.shutdownMaterialAPI=Te,exports.shutdownPostProcessAPI=bt,exports.shutdownRendererAPI=Rt,exports.textInputPlugin=$s,exports.textPlugin=os,exports.uiInteractionPlugin=Bs,exports.uiLayoutPlugin=Ts,exports.uiMaskPlugin=ms,exports.uiPlugins=Zs,exports.unregisterDrawCallback=$t,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=ls,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)})})}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}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex b813395fd..9b364bbc6 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 h(e,n){return t().createCanvas(e,n)}function d(){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 _(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 y(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 _(e)}async readTextFile(e){return y(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const 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}),he=Y("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de={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 _e{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ye{constructor(){this.resources_=new Map}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 _e(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 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 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 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 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(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(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}}function at(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)ct(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 lt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,ie,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}ct(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=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function ct(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 ut(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 ht(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 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 ft{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_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new it(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}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 lt(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 pt=pe(null,"Assets");class mt{build(e){const t=e.wasmModule;t?e.insertResource(pt,new ft(t)):console.warn("AssetPlugin: No WASM module available")}}const gt=new mt;function _t(e,t){const n=e.getResource(pt);n&&n.registerEmbeddedAssets(t)}async function yt(e,t,n){const{entities:s,rootId:r}=await wt(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 lt(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 wt(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 wt(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};xt(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 xt(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 bt{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 yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const vt=pe(null,"Prefabs");class Pt{constructor(){this.name="PrefabsPlugin",this.dependencies=[pt]}build(e){const t=e.getResource(pt);e.insertResource(vt,new bt(e.world,t))}}const St=new Pt;let Ct=null,Et=0,Mt=0,At=0;const Tt=new Float32Array(256);function Rt(e){Ct=e,Et=Ct._malloc(64),Mt=Ct._malloc(64),At=Ct._malloc(1024)}function Ft(){Ct&&(Et&&(Ct._free(Et),Et=0),Mt&&(Ct._free(Mt),Mt=0),At&&(Ct._free(At),At=0)),Ct=null}function It(){if(!Ct)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ct}const Ut={r:1,g:1,b:1,a:1},Bt={begin(e){const t=It();t.HEAPF32.set(e,Et/4),t.draw_begin(Et)},end(){It().draw_end()},line(e,t,n,s=1){It().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){It().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){It().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){It().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){It().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Ut){It().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=Ut){It().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){It().draw_setLayer(e)},setDepth(e){It().draw_setDepth(e)},getDrawCallCount:()=>Ct?Ct.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ct?Ct.draw_getPrimitiveCount():0,setBlendMode(e){It().draw_setBlendMode(e)},setDepthTest(e){It().draw_setDepthTest(e)},drawMesh(e,t,n){const s=It();s.HEAPF32.set(n,Mt/4),s.draw_mesh(e,t,Mt)},drawMeshWithMaterial(e,t,n){const s=It(),r=Ke.get(t);if(!r)return;if(Bt.setBlendMode(r.blendMode),Bt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Bt.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Mt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=$t(t);if(!(s<0)){if(je(n))Tt[o++]=10,Tt[o++]=s,Tt[o++]=n.slot??e++,Tt[o++]=n.textureId;else if("number"==typeof n)Tt[o++]=1,Tt[o++]=s,Tt[o++]=n;else if(Array.isArray(n)){Tt[o++]=n.length,Tt[o++]=s;for(let e=0;e<n.length;e++)Tt[o++]=n[e]}else"w"in n?(Tt[o++]=4,Tt[o++]=s,Tt[o++]=n.x,Tt[o++]=n.y,Tt[o++]=n.z,Tt[o++]=n.w):"z"in n?(Tt[o++]=3,Tt[o++]=s,Tt[o++]=n.x,Tt[o++]=n.y,Tt[o++]=n.z):(Tt[o++]=2,Tt[o++]=s,Tt[o++]=n.x,Tt[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(Tt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),At/4),s.draw_meshWithUniforms(e,r.shader,Mt,At,o)):s.draw_mesh(e,r.shader,Mt)}},kt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function $t(e){return kt[e]??-1}var Wt;!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"}(Wt||(Wt={}));let zt=null,Dt=0,Ht=0,Lt=0;function Ot(e){zt=e,Dt=zt._malloc(262144),Ht=zt._malloc(65536),Lt=zt._malloc(256)}function jt(){zt&&(Dt&&zt._free(Dt),Ht&&zt._free(Ht),Lt&&zt._free(Lt),Dt=0,Ht=0,Lt=0),zt=null}function Nt(){if(!zt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return zt}const Xt={create(e){const t=Nt(),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,Dt/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,Lt,r).set(o),t.geometry_init(n,Dt,s,Lt,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,Ht,s).set(e.indices),t.geometry_setIndices16(n,Ht,s)}else{new Uint32Array(t.HEAPU8.buffer,Ht,s).set(e.indices),t.geometry_setIndices32(n,Ht,s)}}return n},updateVertices(e,t,n=0){const s=Nt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Dt/4),s.geometry_updateVertices(e,Dt,r,n)},release(e){e>0&&Nt().geometry_release(e)},isValid:e=>!(!zt||e<=0)&&zt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Xt.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:Wt.Float2},{name:"a_texCoord",type:Wt.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 Xt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Wt.Float2},{name:"a_texCoord",type:Wt.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 Xt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Wt.Float2},{name:"a_texCoord",type:Wt.Float2}],indices:new Uint16Array(i)})}};let Vt=null;function qt(e){Vt=e}function Gt(){Vt&&Jt.isInitialized()&&Jt.shutdown(),Vt=null}function Yt(){if(!Vt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Vt}const Jt={init:(e,t)=>Yt().postprocess_init(e,t),shutdown(){Yt().postprocess_shutdown()},resize(e,t){Yt().postprocess_resize(e,t)},addPass:(e,t)=>Yt().postprocess_addPass(e,t),removePass(e){Yt().postprocess_removePass(e)},setEnabled(e,t){Yt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Yt().postprocess_isPassEnabled(e),setUniform(e,t,n){Yt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Yt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Yt().postprocess_begin()},end(){Yt().postprocess_end()},getPassCount:()=>Yt().postprocess_getPassCount(),isInitialized:()=>!!Vt&&Vt.postprocess_isInitialized(),setBypass(e){Yt().postprocess_setBypass(e)},isBypassed:()=>!Vt||Vt.postprocess_isBypassed(),createBlur:()=>Ke.createShader(Kt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ke.createShader(Kt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ke.createShader(Kt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(Kt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Kt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Qt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Qt||(Qt={}));let Zt=null,en=0;function tn(e){Zt=e,en=Zt._malloc(64)}function nn(){Zt&&en&&(Zt._free(en),en=0),Zt=null}const sn={init(e,t){Zt?.renderer_init(e,t)},resize(e,t){Zt?.renderer_resize(e,t)},begin(e,t){Zt&&en&&(Zt.HEAPF32.set(e,en/4),Zt.renderer_begin(en,t??0))},flush(){Zt?.renderer_flush()},end(){Zt?.renderer_end()},submitSprites(e){Zt&&Zt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Zt&&Zt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Zt&&Zt.renderer_submitSpine?.(e._cpp)},setStage(e){Zt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Zt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Zt?.renderer_releaseTarget(e)},getTargetTexture:e=>Zt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Zt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Zt?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Zt?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Zt?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Zt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Zt?Zt.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Zt?{drawCalls:Zt.renderer_getDrawCalls(),triangles:Zt.renderer_getTriangles(),sprites:Zt.renderer_getSprites(),text:Zt.renderer_getText(),spine:Zt.renderer_getSpine?.()??0,meshes:Zt.renderer_getMeshes(),culled:Zt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let rn=null;function on(e){rn=e}function an(){rn=null}const ln={enable(){rn?.gl_enableErrorCheck(!0)},disable(){rn?.gl_enableErrorCheck(!1)},check:e=>rn?.gl_checkErrors(e)??0,diagnose(){rn?.renderer_diagnose()}},cn=new Map;function un(e,t){cn.set(e,t)}function hn(e){cn.delete(e)}function dn(){cn.clear()}class fn{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_||(sn.resize(s,r),Jt.isInitialized()&&Jt.getPassCount()>0&&Jt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),sn.setViewport(0,0,s,r),sn.clearBuffers(3),sn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),sn.submitSprites(t),sn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):sn.submitSpine(t),sn.flush(),this.executeDrawCallbacks(n,o),sn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;sn.setViewport(s.x,s.y,s.w,s.h),sn.setScissor(s.x,s.y,s.w,s.h,!0),sn.clearBuffers(r),sn.setScissor(0,0,0,0,!1),sn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),sn.submitSprites(t),sn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):sn.submitSpine(t),sn.flush(),this.executeDrawCallbacks(n,o),sn.end()}executeDrawCallbacks(e,t){const n=cn;if(n.size>0){Bt.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)}Bt.end();for(const e of s)hn(e)}}}class pn{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(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 ye;for(const e of Object.values(Me))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new pn}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_=d(),this.mainLoop())}quit(){this.running_=!1,an(),nn(),Gt(),jt(),Ye(),Ft()}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 mn(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 gn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function _n(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 yn(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(1===r.projectionType){if(d=r.orthoSize,o){d=_n(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=xn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=vn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Sn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Cn(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 wn=new Float32Array(16);function xn(e,t,n,s,r,o){const i=wn;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 bn=new Float32Array(16);function vn(e,t,n,s){const r=bn;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 Pn=new Float32Array(16);function Sn(e,t,n){const s=Pn;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 Cn(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 En,Mn,An;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(En||(En={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Mn||(Mn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(An||(An={}));const Tn=H("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:En.Left,verticalAlign:Mn.Top,wordWrap:!0,overflow:An.Visible,lineHeight:1.2}),Rn=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 Fn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,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===An.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),g=Math.round(255*e.color.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===An.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 Mn.Top:x=u;break;case Mn.Middle:x=(p-w)/2;break;case Mn.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 En.Left:s=u;break;case En.Center:s=f/2;break;case En.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===An.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 En.Left:return"left";case En.Center:return"center";case En.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function In(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 Un(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 Bn{build(e){q("Text",Tn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Fn(t),s=e.world,r=new Map;e.addSystemToSchedule(Me.PreUpdate,Te([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Tn));for(const e of r.keys())s.valid(e)&&s.has(e,Tn)||r.delete(e);const e=s.getEntitiesWithComponents([Tn]);for(const t of e){const e=s.get(t,Tn),o=s.has(t,Rn)?s.get(t,Rn):null,i=r.get(t);if(i&&!Un(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,In(e,o))}}))}}const kn=new Bn,$n=H("UIMask",{enabled:!0});function Wn(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 zn(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(g,y),b=Math.max(g,y),v=Math.min(_,w),P=Math.max(_,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}function Dn(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],g=e[13],_=e[14],y=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=h*g-d*m,E=h*_-f*m,M=h*y-p*m,A=d*_-f*g,T=d*y-p*g,R=f*y-p*_;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-_*P+y*v)*F,n[3]=(f*P-d*S-p*v)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(_*b-m*S-y*x)*F,n[7]=(h*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+y*w)*F,n[11]=(d*b-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]=(g*x-m*v-_*w)*F,n[15]=(h*v-d*x+f*w)*F),n}function Hn(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 Ln(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 On(e,t,n,s,r,o,i){if(!e.has(t,Rn)||!e.has(t,K))return null;const a=e.get(t,Rn),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return zn(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([$n]);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,$n).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 h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=On(t,n,r,o,i,a,l);e&&(s=Wn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=On(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 Nn{build(e){if(q("UIMask",$n),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(jn(e.wasmModule,e.world))}}const Xn=new Nn,Vn=H("Interactable",{enabled:!0}),qn=H("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Gn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Gn||(Gn={}));const Yn=H("Button",{state:Gn.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 Kn=pe(new Jn,"UIEvents"),Qn=L("ScreenSpace");function Zn(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 es(e,t,n,s,r,o){if(!e.has(t,Rn))return;const i=e.get(t,Rn),a=Zn(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)&&es(e,t,a.rect,a.centerX,a.centerY,!1)}class ts{build(e){q("UIRect",Rn);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([Qn,Rn,J]);for(const e of o)es(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const ns=new ts,ss=new Float32Array(16),rs=new Float32Array(16);let os=!0,is=1;class as{build(e){q("Interactable",Vn),q("Button",Yn);const t=e.world,n=new Jn;e.insertResource(Kn,n);let s=null,r=null;is="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Me.PreUpdate,Te([me($e),me(Le)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([qn]);for(const e of i){const n=t.get(e,qn);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*is,l=o.screenH-e.mouseY*is;!function(e){let t=!1;for(let n=0;n<16;n++)if(rs[n]!==e[n]){t=!0;break}t&&(rs.set(e),os=!0)}(o.viewProjection),os&&(Dn(o.viewProjection,ss),os=!1);const c=Hn(a,l,ss,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Vn,Rn,K]);let h=null,d=-1/0;for(const e of u){t.has(e,qn)||t.insert(e,qn);if(!t.get(e,Vn).enabled)continue;const n=t.get(e,K),s=t.get(e,Rn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ln(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>=d&&(d=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,qn)){t.get(s,qn).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,qn).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,qn);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,qn)){const e=t.get(r,qn);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([Yn]);for(const n of e){if(t.has(n,Vn)||t.insert(n,Vn,{enabled:!0}),!t.has(n,qn))continue;const e=t.get(n,qn),s=t.get(n,Yn),r=t.get(n,Vn),o=s.state;if(r.enabled?e.pressed?s.state=Gn.Pressed:e.hovered?s.state=Gn.Hovered:s.state=Gn.Normal:s.state=Gn.Disabled,o!==s.state&&s.transition&&t.has(n,Q)){const e=t.get(n,Q),r=s.transition;switch(s.state){case Gn.Normal:e.color={...r.normalColor};break;case Gn.Hovered:e.color={...r.hoveredColor};break;case Gn.Pressed:e.color={...r.pressedColor};break;case Gn.Disabled:e.color={...r.disabledColor}}t.insert(n,Q,e)}}},{name:"ButtonSystem"}))}}const ls=new as,cs=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 us{build(e){q("TextInput",cs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=h(512,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,cs);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(Kn).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,_()}function m(e){if(i===e)return;g();const t=n.get(e,cs);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),_())}function g(){if(null!==i&&n.valid(i)&&n.has(i,cs)){const e=n.get(i,cs);e.focused=!1,e.dirty=!0}i=null,f.blur()}function _(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ds(Math.max(r.width,a)),r.height=ds(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=hs(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=hs(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),_=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(_.length);t.HEAPU8.set(_,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const b=y.createTexture(a,c,w,_.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,cs);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Kn).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,_())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,cs)){const e=n.get(i,cs);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Me.PreUpdate,Te([me(Kn)],e=>{const t=n.getEntitiesWithComponents([cs,Vn]);for(const e of t){if(!n.has(e,qn))continue;if(n.get(e,qn).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([Vn]);for(const t of e){if(n.has(t,cs))continue;if(!n.has(t,qn))continue;if(n.get(t,qn).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,cs)))){n.get(i,cs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cs)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cs,Rn]);for(const e of a){const t=n.get(e,cs);if(!t.dirty)continue;const s=n.get(e,Rn),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}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function hs(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 ds(e){let t=1;for(;t<e;)t*=2;return t}const fs=new us;async function ps(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 ms=pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),gs=pe(null,"PhysicsAPI");function _s(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ys(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ws{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(ms,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ps(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=_s(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),xs(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===de.Kinematic){const e=_s(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 h=a,d=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=_s(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=ys(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(ms,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(gs,bs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function xs(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,he)){const e=s.get(n,he);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 bs{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(bs.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 vs(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 Ps(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 Ss(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,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,b=u*d,v=u*f;return new Float32Array([(1-(_+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(y+x)*o,0,(g+b)*i,(y-x)*i,(1-(p+_))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Cs(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]=vs(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=Ps(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=vs(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 ws("",{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=vs(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=Ke.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Ke.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=at(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,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,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,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,oe)?c.get(o,oe):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,K)){const e=Ss(c.get(o,K),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],g=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),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(pt);t&&t.setAddressableManifest(a)}}class Es{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(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);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(()=>{}))}}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 Ms{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 Es(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 Cs(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 As={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=sn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:sn.getTargetTexture(n),width:e.width,height:e.height}},release(e){sn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(sn.releaseRenderTarget(e._handle),As.create({width:t,height:n,depth:!0})),begin(e,t){sn.begin(t,e._handle)},end(){sn.end()},getDepthTexture:e=>sn.getTargetDepthTexture(e._handle)};let Ts=!1;function Rs(e){Ts=e}function Fs(){return Ts}function Is(){return!Ts}const Us=[kn,Xn,ns,ls,fs];function Bs(e,t){return function(e,t){const n=pn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),Ge(e),Ot(e),qt(e),tn(e),on(e);const r=new fn;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=yn(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;sn.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;sn.resize(t,n),Jt.isInitialized()&&Jt.getPassCount()>0&&!Jt.isBypassed()&&Jt.resize(t,n);const u=yn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:gn,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})}sn.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(Me.First,l),n.addSystemToSchedule(Me.Last,c),n.addPlugin(gt),n.addPlugin(St),n.addPlugin(ze),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Us,...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{pn as App,mt as AssetPlugin,ft as AssetServer,pt as Assets,dt as AsyncCache,re as BitmapText,Oe as BlendMode,de as BodyType,ce as BoxCollider,Yn as Button,Gn as ButtonState,Z as Camera,ee as Canvas,he as CapsuleCollider,se as Children,ue as CircleCollider,Se as Commands,Ee as CommandsInstance,Wt as DataType,Bt as Draw,Ce as EntityCommands,ln as GLDebug,Xt as Geometry,T as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,$e as Input,We as InputPlugin,ke as InputState,Vn as Interactable,J as LocalTransform,Ke as Material,it as MaterialLoader,xe as Mut,ie as Name,ne as Parent,bs as Physics,ms as PhysicsEvents,ws as PhysicsPlugin,Jt as PostProcess,bt as PrefabServer,vt as Prefabs,Pt as PrefabsPlugin,Ms as PreviewPlugin,ve as Query,Pe as QueryInstance,fn as RenderPipeline,Qt as RenderStage,As as RenderTexture,sn as Renderer,me as Res,ge as ResMut,le as RigidBody,Me as Schedule,Qn as ScreenSpace,ot as ShaderSources,oe as SpineAnimation,Q as Sprite,Be as SystemRunner,Tn as Text,En as TextAlign,cs as TextInput,us as TextInputPlugin,An as TextOverflow,Bn as TextPlugin,Fn as TextRenderer,Mn as TextVerticalAlign,we as Time,Le as UICameraInfo,Jn as UIEventQueue,Kn as UIEvents,qn as UIInteraction,as as UIInteractionPlugin,ts as UILayoutPlugin,$n as UIMask,Nn as UIMaskPlugin,Rn as UIRect,te as Velocity,Es as WebAssetProvider,He as World,K as WorldTransform,Ie as addStartupSystem,Fe as addSystem,Ue as addSystemToSchedule,gt as assetPlugin,dn as clearDrawCallbacks,j as clearUserComponents,k as color,Zn as computeUIRectLayout,jn as createMaskProcessor,Bs as createWebApp,H as defineComponent,pe as defineResource,Te as defineSystem,L as defineTag,ht as findEntityByName,mn as flushPendingSystems,G as getComponent,ae as getComponentDefaults,t as getPlatform,s as getPlatformType,O as getUserComponent,Rt as initDrawAPI,on as initGLDebugAPI,Ot as initGeometryAPI,Ge as initMaterialAPI,qt as initPostProcessAPI,tn as initRendererAPI,ze as inputPlugin,yt as instantiatePrefab,Wn as intersectRects,Dn as invertMatrix4,X as isBuiltinComponent,Fs as isEditor,n as isPlatformInitialized,Is as isRuntime,je as isTextureRef,r as isWeChat,o as isWeb,ct as loadComponent,ps as loadPhysicsModule,Cs as loadRuntimeScene,at as loadSceneData,lt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ln as pointInWorldRect,St as prefabsPlugin,$ as quat,q as registerComponent,un as registerDrawCallback,_t as registerEmbeddedAssets,rt as registerMaterialCallback,Hn as screenToWorld,Rs as setEditorMode,Ft as shutdownDrawAPI,an as shutdownGLDebugAPI,jt as shutdownGeometryAPI,Ye as shutdownMaterialAPI,Gt as shutdownPostProcessAPI,nn as shutdownRendererAPI,fs as textInputPlugin,kn as textPlugin,ls as uiInteractionPlugin,ns as uiLayoutPlugin,Xn as uiMaskPlugin,Us as uiPlugins,hn as unregisterDrawCallback,ut as updateCameraAspectRatio,I as vec2,U as vec3,B as vec4,zn as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,E as wxLoadImagePixels,_ as wxReadFile,y 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}`))}})})}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};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 13009b08d..369a19ce0 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1326,7 +1326,6 @@ interface ShaderLoader {}declare class MaterialLoader {private cache_;- private pending_;private shaderLoader_;private basePath_;constructor(shaderLoader: ShaderLoader, basePath?: string);@@ -1378,6 +1377,20 @@ interface SceneLoadOptions {assetServer?: AssetServer;assetBaseUrl?: string;}+type AssetFieldType = 'texture' | 'material' | 'font';+interface AssetFieldDescriptor {+ field: string;+ type: AssetFieldType;+}+interface SpineFieldDescriptor {+ skeletonField: string;+ atlasField: string;+}+interface ComponentAssetFields {+ fields?: AssetFieldDescriptor[];+ spine?: SpineFieldDescriptor;+}+declare function registerComponentAssetFields(componentType: string, config: ComponentAssetFields): void;declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;@@ -1644,6 +1657,7 @@ declare class AssetServer {private spineSkeletons_;constructor(module: ESEngineModule);registerEmbeddedAssets(assets: Record<string, string>): void;+ setEmbeddedOnly(value: boolean): void;/*** Load texture with vertical flip (for Sprite/UI).* OpenGL UV origin is bottom-left, so standard images need flipping.@@ -2449,5 +2463,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, 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, 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 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 cf4e5d783..cfda02a39 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 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=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),A(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),A(e,{},!0),s}function M(e){return S().get(e)}function T(){S().clear()}function A(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function R(e){return!0===e._builtin}const I=new Map;function F(e,t){I.set(e,t)}function U(e){return I.get(e)??M(e)}function B(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return I.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}}),H=B("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),W=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}F("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 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 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 he{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 de;!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"}(de||(de={}));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:de.Update,system:e})}function ge(e){me().push({schedule:de.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 he&&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 he(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(de.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 Te(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Me||(Me={}));let Ae=null,Re=null,Ie=1;const Fe=new Map;function Ue(e){Ae=e,Re=e.getResourceManager(),Ne()}function Be(){0!==Le&&Ae&&(Ae._free(Le),Le=0),Fe.clear(),Ie=1,ze=!1,Re=null,Ae=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=Ie++,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 Fe.set(t,n),t},get:e=>Fe.get(e),setUniform(e,t,n){const s=Fe.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Fe.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Fe.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Fe.get(e);return t?.blendMode??Me.Normal},setDepthTest(e,t){const n=Fe.get(e);n&&(n.depthTest=t)},getShader(e){const t=Fe.get(e);return t?.shader??0},release(e){Fe.delete(e)},isValid:e=>Fe.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=Fe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ie++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Fe.set(n,s),n},toAssetData(e,t){const n=Fe.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=Fe.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,He=new Map;let We=null;function Oe(e){const t=(0===Le&&Ae&&(Le=Ae._malloc(De)),Le);if(0===t||!Ae)return{ptr:0,count:0};let n=0,s=0;const r=Ae.HEAPU8,o=Ae.HEAPU32,i=Ae.HEAPF32;for(const[a,l]of e){if(n+128>De)break;let e=He.get(a);e||(We||(We=new TextEncoder),e=We.encode(a),He.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 Ne(){if(!Ae||ze)return;Ae.materialDataProvider=(e,t,n,s,r)=>{const o=Fe.get(e);if(!o)return Ae.HEAPU32[t>>2]=0,Ae.HEAPU32[n>>2]=0,Ae.HEAPU32[s>>2]=0,void(Ae.HEAPU32[r>>2]=0);Ae.HEAPU32[t>>2]=o.shader,Ae.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Oe(o.uniforms);Ae.HEAPU32[s>>2]=i,Ae.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(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&($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}}function Xe(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)qe(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 Ye(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,V,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}qe(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=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function qe(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 Ge(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 Je(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 Ke{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 Qe{constructor(e){this.textureCache_=new Ke,this.shaderCache_=new Ke,this.jsonCache_=new Ke,this.textCache_=new Ke,this.binaryCache_=new Ke,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ke,this.prefabCache_=new Ke,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(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 Ve(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}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 Ye(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 Ze=Z(null,"Assets");class et{build(e){const t=e.wasmModule;t?e.insertResource(Ze,new Qe(t)):console.warn("AssetPlugin: No WASM module available")}}const tt=new et;function nt(e,t){const n=e.getResource(Ze);n&&n.registerEmbeddedAssets(t)}async function st(e,t,n){const{entities:s,rootId:r}=await rt(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 Ye(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 rt(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 rt(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};ot(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 ot(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 it{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 st(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const at=Z(null,"Prefabs");class lt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ze]}build(e){const t=e.getResource(Ze);e.insertResource(at,new it(e.world,t))}}const ct=new lt;let ut=null,ht=0,dt=0,ft=0;const pt=new Float32Array(256);function mt(e){ut=e,ht=ut._malloc(64),dt=ut._malloc(64),ft=ut._malloc(1024)}function _t(){ut&&(ht&&(ut._free(ht),ht=0),dt&&(ut._free(dt),dt=0),ft&&(ut._free(ft),ft=0)),ut=null}function gt(){if(!ut)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ut}const yt={r:1,g:1,b:1,a:1},wt={begin(e){const t=gt();t.HEAPF32.set(e,ht/4),t.draw_begin(ht)},end(){gt().draw_end()},line(e,t,n,s=1){gt().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){gt().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){gt().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){gt().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){gt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=yt){gt().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=yt){gt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){gt().draw_setLayer(e)},setDepth(e){gt().draw_setDepth(e)},getDrawCallCount:()=>ut?ut.draw_getDrawCallCount():0,getPrimitiveCount:()=>ut?ut.draw_getPrimitiveCount():0,setBlendMode(e){gt().draw_setBlendMode(e)},setDepthTest(e){gt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=gt();s.HEAPF32.set(n,dt/4),s.draw_mesh(e,t,dt)},drawMeshWithMaterial(e,t,n){const s=gt(),r=$e.get(t);if(!r)return;if(wt.setBlendMode(r.blendMode),wt.setDepthTest(r.depthTest),0===r.uniforms.size)return void wt.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,dt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=vt(t);if(!(s<0)){if(Te(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),ft/4),s.draw_meshWithUniforms(e,r.shader,dt,ft,o)):s.draw_mesh(e,r.shader,dt)}},xt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function vt(e){return xt[e]??-1}var bt;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(bt||(bt={}));let Pt=null,St=0,Ct=0,Et=0;function Mt(e){Pt=e,St=Pt._malloc(262144),Ct=Pt._malloc(65536),Et=Pt._malloc(256)}function Tt(){Pt&&(St&&Pt._free(St),Ct&&Pt._free(Ct),Et&&Pt._free(Et),St=0,Ct=0,Et=0),Pt=null}function At(){if(!Pt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Pt}const Rt={create(e){const t=At(),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,St/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,Et,r).set(o),t.geometry_init(n,St,s,Et,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,Ct,s).set(e.indices),t.geometry_setIndices16(n,Ct,s)}else{new Uint32Array(t.HEAPU8.buffer,Ct,s).set(e.indices),t.geometry_setIndices32(n,Ct,s)}}return n},updateVertices(e,t,n=0){const s=At(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,St/4),s.geometry_updateVertices(e,St,r,n)},release(e){e>0&&At().geometry_release(e)},isValid:e=>!(!Pt||e<=0)&&Pt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Rt.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:bt.Float2},{name:"a_texCoord",type:bt.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 Rt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:bt.Float2},{name:"a_texCoord",type:bt.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 Rt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:bt.Float2},{name:"a_texCoord",type:bt.Float2}],indices:new Uint16Array(i)})}};let It=null;function Ft(e){It=e}function Ut(){It&&kt.isInitialized()&&kt.shutdown(),It=null}function Bt(){if(!It)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return It}const kt={init:(e,t)=>Bt().postprocess_init(e,t),shutdown(){Bt().postprocess_shutdown()},resize(e,t){Bt().postprocess_resize(e,t)},addPass:(e,t)=>Bt().postprocess_addPass(e,t),removePass(e){Bt().postprocess_removePass(e)},setEnabled(e,t){Bt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Bt().postprocess_isPassEnabled(e),setUniform(e,t,n){Bt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Bt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Bt().postprocess_begin()},end(){Bt().postprocess_end()},getPassCount:()=>Bt().postprocess_getPassCount(),isInitialized:()=>!!It&&It.postprocess_isInitialized(),setBypass(e){Bt().postprocess_setBypass(e)},isBypassed:()=>!It||It.postprocess_isBypassed(),createBlur:()=>$e.createShader($t,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>$e.createShader($t,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>$e.createShader($t,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>$e.createShader($t,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},$t="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var zt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(zt||(zt={}));let Lt=null,Dt=0;function Ht(e){Lt=e,Dt=Lt._malloc(64)}function Wt(){Lt&&Dt&&(Lt._free(Dt),Dt=0),Lt=null}const Ot={init(e,t){Lt?.renderer_init(e,t)},resize(e,t){Lt?.renderer_resize(e,t)},begin(e,t){Lt&&Dt&&(Lt.HEAPF32.set(e,Dt/4),Lt.renderer_begin(Dt,t??0))},flush(){Lt?.renderer_flush()},end(){Lt?.renderer_end()},submitSprites(e){Lt&&Lt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Lt&&Lt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Lt&&Lt.renderer_submitSpine?.(e._cpp)},setStage(e){Lt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Lt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Lt?.renderer_releaseTarget(e)},getTargetTexture:e=>Lt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Lt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Lt?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Lt?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Lt?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Lt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Lt?Lt.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Lt?{drawCalls:Lt.renderer_getDrawCalls(),triangles:Lt.renderer_getTriangles(),sprites:Lt.renderer_getSprites(),text:Lt.renderer_getText(),spine:Lt.renderer_getSpine?.()??0,meshes:Lt.renderer_getMeshes(),culled:Lt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Nt=null;function jt(e){Nt=e}function Vt(){Nt=null}const Xt={enable(){Nt?.gl_enableErrorCheck(!0)},disable(){Nt?.gl_enableErrorCheck(!1)},check:e=>Nt?.gl_checkErrors(e)??0,diagnose(){Nt?.renderer_diagnose()}},Yt=new Map;function qt(e,t){Yt.set(e,t)}function Gt(e){Yt.delete(e)}function Jt(){Yt.clear()}class Kt{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_||(Ot.resize(s,r),kt.isInitialized()&&kt.getPassCount()>0&&kt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Ot.setViewport(0,0,s,r),Ot.clearBuffers(3),Ot.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Ot.submitSprites(t),Ot.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ot.submitSpine(t),Ot.flush(),this.executeDrawCallbacks(n,o),Ot.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Ot.setViewport(s.x,s.y,s.w,s.h),Ot.setScissor(s.x,s.y,s.w,s.h,!0),Ot.clearBuffers(r),Ot.setScissor(0,0,0,0,!1),Ot.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Ot.submitSprites(t),Ot.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ot.submitSpine(t),Ot.flush(),this.executeDrawCallbacks(n,o),Ot.end()}executeDrawCallbacks(e,t){const n=Yt;if(n.size>0){wt.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)}wt.end();for(const e of s)Gt(e)}}}class Qt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.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(de.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(de.FixedPreUpdate),this.runSchedule(de.FixedUpdate),this.runSchedule(de.FixedPostUpdate);this.runSchedule(de.PreUpdate),this.runSchedule(de.Update),this.runSchedule(de.PostUpdate),this.runSchedule(de.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Ce,this.resources_=new se;for(const e of Object.values(de))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Qt}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(de.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(de.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(de.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Vt(),Wt(),Ut(),Tt(),Be(),_t()}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 Zt(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 en=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function tn(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 nn(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(1===r.projectionType){if(d=r.orthoSize,o){d=tn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=rn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=an(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=cn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:un(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 sn=new Float32Array(16);function rn(e,t,n,s,r,o){const i=sn;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 on=new Float32Array(16);function an(e,t,n,s){const r=on;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 ln=new Float32Array(16);function cn(e,t,n){const s=ln;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 un(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 hn,dn,fn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(hn||(hn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(dn||(dn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(fn||(fn={}));const pn=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:hn.Left,verticalAlign:dn.Top,wordWrap:!0,overflow:fn.Visible,lineHeight:1.2}),mn=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 _n{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,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===fn.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===fn.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 dn.Top:x=u;break;case dn.Middle:x=(p-w)/2;break;case dn.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 hn.Left:s=u;break;case hn.Center:s=f/2;break;case hn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===fn.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 hn.Left:return"left";case hn.Center:return"center";case hn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function gn(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 yn(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 wn{build(e){F("Text",pn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new _n(t),s=e.world,r=new Map;e.addSystemToSchedule(de.PreUpdate,pe([],()=>{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,mn)?s.get(t,mn):null,i=r.get(t);if(i&&!yn(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,gn(e,o))}}))}}const xn=new wn,vn=C("UIMask",{enabled:!0});function bn(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 Pn(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 Sn(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,T=d*g-f*_,A=d*y-p*_,R=f*y-p*g;let I=w*R-x*A+v*T+b*M-P*E+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*T)*I,n[1]=(o*A-r*R-i*T)*I,n[2]=(_*S-g*P+y*b)*I,n[3]=(f*P-d*S-p*b)*I,n[4]=(c*M-a*R-u*E)*I,n[5]=(s*R-o*M+i*E)*I,n[6]=(g*v-m*S-y*x)*I,n[7]=(h*S-f*v+p*x)*I,n[8]=(a*A-l*M+u*C)*I,n[9]=(r*M-s*A-i*C)*I,n[10]=(m*P-_*v+y*w)*I,n[11]=(d*v-h*P-p*w)*I,n[12]=(l*E-a*T-c*C)*I,n[13]=(s*T-r*E+o*C)*I,n[14]=(_*x-m*b-g*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function Cn(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 En(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 Mn(e,t,n,s,r,o,i){if(!e.has(t,mn)||!e.has(t,$))return null;const a=e.get(t,mn),l=e.get(t,$),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Pn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Tn(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([vn]);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,vn).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,W);){const e=t.get(s,W);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=Mn(t,n,r,o,i,a,l);e&&(s=bn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=Mn(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 An{build(e){if(F("UIMask",vn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Tn(e.wasmModule,e.world))}}const Rn=new An,In=C("Interactable",{enabled:!0}),Fn=C("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Un;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Un||(Un={}));const Bn=C("Button",{state:Un.Normal,transition:null});class kn{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 $n=Z(new kn,"UIEvents"),zn=E("ScreenSpace");function Ln(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 Dn(e,t,n,s,r,o){if(!e.has(t,mn))return;const i=e.get(t,mn),a=Ln(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)&&Dn(e,t,a.rect,a.centerX,a.centerY,!1)}class Hn{build(e){F("UIRect",mn);const t=e.world;e.addSystemToSchedule(de.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([zn,mn,k]);for(const e of o)Dn(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Wn=new Hn,On=new Float32Array(16),Nn=new Float32Array(16);let jn=!0,Vn=1;class Xn{build(e){F("Interactable",In),F("Button",Bn);const t=e.world,n=new kn;e.insertResource($n,n);let s=null,r=null;Vn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(de.PreUpdate,pe([ee(ve),ee(Ee)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Fn]);for(const e of i){const n=t.get(e,Fn);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Vn,l=o.screenH-e.mouseY*Vn;!function(e){let t=!1;for(let n=0;n<16;n++)if(Nn[n]!==e[n]){t=!0;break}t&&(Nn.set(e),jn=!0)}(o.viewProjection),jn&&(Sn(o.viewProjection,On),jn=!1);const c=Cn(a,l,On,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([In,mn,$]);let h=null,d=-1/0;for(const e of u){t.has(e,Fn)||t.insert(e,Fn);if(!t.get(e,In).enabled)continue;const n=t.get(e,$),s=t.get(e,mn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(En(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>=d&&(d=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,Fn)){t.get(s,Fn).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,Fn).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Fn);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,Fn)){const e=t.get(r,Fn);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(de.Update,pe([],()=>{const e=t.getEntitiesWithComponents([Bn]);for(const n of e){if(t.has(n,In)||t.insert(n,In,{enabled:!0}),!t.has(n,Fn))continue;const e=t.get(n,Fn),s=t.get(n,Bn),r=t.get(n,In),o=s.state;if(r.enabled?e.pressed?s.state=Un.Pressed:e.hovered?s.state=Un.Hovered:s.state=Un.Normal:s.state=Un.Disabled,o!==s.state&&s.transition&&t.has(n,z)){const e=t.get(n,z),r=s.transition;switch(s.state){case Un.Normal:e.color={...r.normalColor};break;case Un.Hovered:e.color={...r.hoveredColor};break;case Un.Pressed:e.color={...r.pressedColor};break;case Un.Disabled:e.color={...r.disabledColor}}t.insert(n,z,e)}}},{name:"ButtonSystem"}))}}const Yn=new Xn,qn=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 Gn{build(e){F("TextInput",qn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=h(512,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,qn);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($n).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,qn);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,qn)){const e=n.get(i,qn);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=Kn(Math.max(r.width,a)),r.height=Kn(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=Jn(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=Jn(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,qn);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource($n).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,qn)){const e=n.get(i,qn);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(de.PreUpdate,pe([ee($n)],e=>{const t=n.getEntitiesWithComponents([qn,In]);for(const e of t){if(!n.has(e,Fn))continue;if(n.get(e,Fn).justPressed)return void _(e)}if(null!==i){const e=n.getEntitiesWithComponents([In]);for(const t of e){if(n.has(t,qn))continue;if(!n.has(t,Fn))continue;if(n.get(t,Fn).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(de.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,qn)))){n.get(i,qn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,qn)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([qn,mn]);for(const e of a){const t=n.get(e,qn);if(!t.dirty)continue;const s=n.get(e,mn),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 Jn(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 Kn(e){let t=1;for(;t<e;)t*=2;return t}const Qn=new Gn;async function Zn(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 es=Z({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ts=Z(null,"PhysicsAPI");function ns(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ss(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class rs{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(es,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Zn(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(de.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=ns(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),os(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=ns(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 h=a,d=l,f=c;if(e.world.has(i,W)){const t=e.world.get(i,W);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,$)){const n=e.world.get(t.entity,$),s=ns(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=ss(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(es,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ts,is._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function os(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 is{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(is.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 as(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 ls(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 cs(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 us(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]=as(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=ls(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=as(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 rs("",{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=as(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=$e.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=$e.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Xe(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,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,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,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,j)?c.get(o,j):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,$)){const e=cs(c.get(o,$),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(Ze);t&&t.setAddressableManifest(a)}}class hs{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(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);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(()=>{}))}}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 ds{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 hs(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 us(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 fs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Ot.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Ot.getTargetTexture(n),width:e.width,height:e.height}},release(e){Ot.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Ot.releaseRenderTarget(e._handle),fs.create({width:t,height:n,depth:!0})),begin(e,t){Ot.begin(t,e._handle)},end(){Ot.end()},getDepthTexture:e=>Ot.getTargetDepthTexture(e._handle)};let ps=!1;function ms(e){ps=e}function _s(){return ps}function gs(){return!ps}const ys=[xn,Rn,Wn,Yn,Qn];function ws(e,t){return function(e,t){const n=Qt.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),mt(e),Ue(e),Mt(e),Ft(e),Ht(e),jt(e);const r=new Kt;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=nn(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;Ot.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;Ot.resize(t,n),kt.isInitialized()&&kt.getPassCount()>0&&!kt.isBypassed()&&kt.resize(t,n);const u=nn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:en,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})}Ot.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(de.First,l),n.addSystemToSchedule(de.Last,c),n.addPlugin(tt),n.addPlugin(ct),n.addPlugin(Pe),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ys,...t})}e=f;export{Qt as App,et as AssetPlugin,Qe as AssetServer,Ze as Assets,Ke as AsyncCache,N as BitmapText,Me as BlendMode,K as BodyType,q as BoxCollider,Bn as Button,Un as ButtonState,L as Camera,D as Canvas,J as CapsuleCollider,O as Children,G as CircleCollider,ce as Commands,he as CommandsInstance,bt as DataType,wt as Draw,ue as EntityCommands,Xt as GLDebug,Rt as Geometry,p as INVALID_ENTITY,_ as INVALID_FONT,m as INVALID_TEXTURE,ve as Input,be as InputPlugin,xe as InputState,In as Interactable,k as LocalTransform,$e as Material,Ve as MaterialLoader,oe as Mut,V as Name,W as Parent,is as Physics,es as PhysicsEvents,rs as PhysicsPlugin,kt as PostProcess,it as PrefabServer,at as Prefabs,lt as PrefabsPlugin,ds as PreviewPlugin,ae as Query,le as QueryInstance,Kt as RenderPipeline,zt as RenderStage,fs as RenderTexture,Ot as Renderer,ee as Res,te as ResMut,Y as RigidBody,de as Schedule,zn as ScreenSpace,je as ShaderSources,j as SpineAnimation,z as Sprite,we as SystemRunner,pn as Text,hn as TextAlign,qn as TextInput,Gn as TextInputPlugin,fn as TextOverflow,wn as TextPlugin,_n as TextRenderer,dn as TextVerticalAlign,re as Time,Ee as UICameraInfo,kn as UIEventQueue,$n as UIEvents,Fn as UIInteraction,Xn as UIInteractionPlugin,Hn as UILayoutPlugin,vn as UIMask,An as UIMaskPlugin,mn as UIRect,H as Velocity,hs as WebAssetProvider,Ce as World,$ as WorldTransform,ge as addStartupSystem,_e as addSystem,ye as addSystemToSchedule,tt as assetPlugin,Jt as clearDrawCallbacks,T as clearUserComponents,x as color,Ln as computeUIRectLayout,Tn as createMaskProcessor,ws as createWebApp,C as defineComponent,Z as defineResource,pe as defineSystem,E as defineTag,Je as findEntityByName,Zt as flushPendingSystems,U as getComponent,X as getComponentDefaults,t as getPlatform,s as getPlatformType,M as getUserComponent,mt as initDrawAPI,jt as initGLDebugAPI,Mt as initGeometryAPI,Ue as initMaterialAPI,Ft as initPostProcessAPI,Ht as initRendererAPI,Pe as inputPlugin,st as instantiatePrefab,bn as intersectRects,Sn as invertMatrix4,R as isBuiltinComponent,_s as isEditor,n as isPlatformInitialized,gs as isRuntime,Te as isTextureRef,r as isWeChat,o as isWeb,qe as loadComponent,Zn as loadPhysicsModule,us as loadRuntimeScene,Xe as loadSceneData,Ye as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,En as pointInWorldRect,ct as prefabsPlugin,v as quat,F as registerComponent,qt as registerDrawCallback,nt as registerEmbeddedAssets,Ne as registerMaterialCallback,Cn as screenToWorld,ms as setEditorMode,_t as shutdownDrawAPI,Vt as shutdownGLDebugAPI,Tt as shutdownGeometryAPI,Be as shutdownMaterialAPI,Ut as shutdownPostProcessAPI,Wt as shutdownRendererAPI,Qn as textInputPlugin,xn as textPlugin,Yn as uiInteractionPlugin,Wn as uiLayoutPlugin,Rn as uiMaskPlugin,ys as uiPlugins,Gt as unregisterDrawCallback,Ge as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,Pn 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 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};//# sourceMappingURL=index.js.mapdiff --git a/desktop/src-tauri/src/embedded_assets.rs b/desktop/src-tauri/src/embedded_assets.rsnew file mode 100644index 000000000..2e247328f--- /dev/null+++ b/desktop/src-tauri/src/embedded_assets.rs@@ -0,0 +1,45 @@+//! Centralized embedded assets for the editor binary++// =============================================================================+// WASM Modules+// =============================================================================++pub const ENGINE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.js");+pub const ENGINE_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wasm");+pub const ENGINE_SINGLE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.single.js");+pub const ENGINE_WXGAME_JS: &[u8] = include_bytes!("../../public/wasm/esengine.wxgame.js");+pub const ENGINE_WXGAME_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wxgame.wasm");+pub const SPINE38_JS: &[u8] = include_bytes!("../../public/wasm/spine38.js");+pub const SPINE38_WASM: &[u8] = include_bytes!("../../public/wasm/spine38.wasm");+pub const SPINE41_JS: &[u8] = include_bytes!("../../public/wasm/spine41.js");+pub const SPINE41_WASM: &[u8] = include_bytes!("../../public/wasm/spine41.wasm");+pub const SPINE42_JS: &[u8] = include_bytes!("../../public/wasm/spine42.js");+pub const SPINE42_WASM: &[u8] = include_bytes!("../../public/wasm/spine42.wasm");+pub const PHYSICS_JS: &[u8] = include_bytes!("../../public/wasm/physics.js");+pub const PHYSICS_WASM: &[u8] = include_bytes!("../../public/wasm/physics.wasm");++// =============================================================================+// SDK+// =============================================================================++pub const SDK_ESM_JS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.js");+pub const SDK_ESM_DTS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.d.ts");+pub const SDK_ESM_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/index.js.map");+pub const SDK_WASM_JS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js");+pub const SDK_WASM_DTS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.d.ts");+pub const SDK_WASM_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js.map");+pub const SDK_SPINE_JS: &[u8] = include_bytes!("../../public/sdk/esm/spine/index.js");+pub const SDK_SPINE_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/spine/index.js.map");+pub const SDK_WECHAT_JS: &[u8] = include_bytes!("../../public/sdk/cjs/esengine.wechat.js");++// =============================================================================+// Editor Types+// =============================================================================++pub const EDITOR_DTS: &[u8] = include_bytes!("../../../editor/dist/index.d.ts");++// =============================================================================+// Preview HTML+// =============================================================================++pub const PREVIEW_HTML: &str = include_str!("preview_template.html");diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 74bb2d806..d2d579b73 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -1,5 +1,6 @@//! ESEngine Editor Library+mod embedded_assets;mod preview_server;use preview_server::PreviewServer;@@ -10,26 +11,6 @@ use tauri::{AppHandle, Emitter, Manager, State};use tokio::io::{AsyncBufReadExt, BufReader};use tokio::process::Command;-const ENGINE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.js");-const ENGINE_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wasm");-const ENGINE_SINGLE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.single.js");-const ENGINE_WXGAME_JS: &[u8] = include_bytes!("../../public/wasm/esengine.wxgame.js");-const ENGINE_WXGAME_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wxgame.wasm");-const SDK_WECHAT_JS: &[u8] = include_bytes!("../../public/sdk/cjs/esengine.wechat.js");-const SDK_ESM_JS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.js");-const SDK_ESM_DTS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.d.ts");-const SDK_WASM_JS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js");-const SDK_WASM_DTS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.d.ts");-const EDITOR_DTS: &[u8] = include_bytes!("../../../editor/dist/index.d.ts");-const SPINE38_JS: &[u8] = include_bytes!("../../public/wasm/spine38.js");-const SPINE38_WASM: &[u8] = include_bytes!("../../public/wasm/spine38.wasm");-const SPINE41_JS: &[u8] = include_bytes!("../../public/wasm/spine41.js");-const SPINE41_WASM: &[u8] = include_bytes!("../../public/wasm/spine41.wasm");-const SPINE42_JS: &[u8] = include_bytes!("../../public/wasm/spine42.js");-const SPINE42_WASM: &[u8] = include_bytes!("../../public/wasm/spine42.wasm");-const PHYSICS_JS: &[u8] = include_bytes!("../../public/wasm/physics.js");-const PHYSICS_WASM: &[u8] = include_bytes!("../../public/wasm/physics.wasm");-// =============================================================================// State// =============================================================================@@ -82,6 +63,14 @@ fn stop_preview_server(state: State<AppState>) {*server_lock = None;}+#[tauri::command]+fn notify_preview_reload(state: State<AppState>) {+ let server_lock = state.preview_server.lock().unwrap();+ if let Some(ref server) = *server_lock {+ server.notify_reload();+ }+}+#[tauri::command]fn open_preview_in_browser(port: u16) -> Result<(), String> {let url = format!("http://127.0.0.1:{}", port);@@ -95,97 +84,97 @@ fn open_folder(path: String) -> Result<(), String> {#[tauri::command]fn get_engine_js() -> Vec<u8> {- ENGINE_JS.to_vec()+ embedded_assets::ENGINE_JS.to_vec()}#[tauri::command]fn get_engine_wasm() -> Vec<u8> {- ENGINE_WASM.to_vec()+ embedded_assets::ENGINE_WASM.to_vec()}#[tauri::command]fn get_engine_single_js() -> Vec<u8> {- ENGINE_SINGLE_JS.to_vec()+ embedded_assets::ENGINE_SINGLE_JS.to_vec()}#[tauri::command]fn get_engine_wxgame_js() -> Vec<u8> {- ENGINE_WXGAME_JS.to_vec()+ embedded_assets::ENGINE_WXGAME_JS.to_vec()}#[tauri::command]fn get_engine_wxgame_wasm() -> Vec<u8> {- ENGINE_WXGAME_WASM.to_vec()+ embedded_assets::ENGINE_WXGAME_WASM.to_vec()}#[tauri::command]fn get_sdk_wechat_js() -> Vec<u8> {- SDK_WECHAT_JS.to_vec()+ embedded_assets::SDK_WECHAT_JS.to_vec()}#[tauri::command]fn get_sdk_esm_js() -> Vec<u8> {- SDK_ESM_JS.to_vec()+ embedded_assets::SDK_ESM_JS.to_vec()}#[tauri::command]fn get_sdk_esm_dts() -> Vec<u8> {- SDK_ESM_DTS.to_vec()+ embedded_assets::SDK_ESM_DTS.to_vec()}#[tauri::command]fn get_sdk_wasm_js() -> Vec<u8> {- SDK_WASM_JS.to_vec()+ embedded_assets::SDK_WASM_JS.to_vec()}#[tauri::command]fn get_sdk_wasm_dts() -> Vec<u8> {- SDK_WASM_DTS.to_vec()+ embedded_assets::SDK_WASM_DTS.to_vec()}#[tauri::command]fn get_editor_dts() -> Vec<u8> {- EDITOR_DTS.to_vec()+ embedded_assets::EDITOR_DTS.to_vec()}#[tauri::command]fn get_spine38_js() -> Vec<u8> {- SPINE38_JS.to_vec()+ embedded_assets::SPINE38_JS.to_vec()}#[tauri::command]fn get_spine38_wasm() -> Vec<u8> {- SPINE38_WASM.to_vec()+ embedded_assets::SPINE38_WASM.to_vec()}#[tauri::command]fn get_spine41_js() -> Vec<u8> {- SPINE41_JS.to_vec()+ embedded_assets::SPINE41_JS.to_vec()}#[tauri::command]fn get_spine41_wasm() -> Vec<u8> {- SPINE41_WASM.to_vec()+ embedded_assets::SPINE41_WASM.to_vec()}#[tauri::command]fn get_spine42_js() -> Vec<u8> {- SPINE42_JS.to_vec()+ embedded_assets::SPINE42_JS.to_vec()}#[tauri::command]fn get_spine42_wasm() -> Vec<u8> {- SPINE42_WASM.to_vec()+ embedded_assets::SPINE42_WASM.to_vec()}#[tauri::command]fn get_physics_js() -> Vec<u8> {- PHYSICS_JS.to_vec()+ embedded_assets::PHYSICS_JS.to_vec()}#[tauri::command]fn get_physics_wasm() -> Vec<u8> {- PHYSICS_WASM.to_vec()+ embedded_assets::PHYSICS_WASM.to_vec()}#[derive(Clone, serde::Serialize)]@@ -269,6 +258,7 @@ pub fn run() {toggle_devtools,start_preview_server,stop_preview_server,+ notify_preview_reload,open_preview_in_browser,open_folder,execute_command,diff --git a/desktop/src-tauri/src/preview_server.rs b/desktop/src-tauri/src/preview_server.rsindex ceb961187..db177cbe2 100644--- a/desktop/src-tauri/src/preview_server.rs+++ b/desktop/src-tauri/src/preview_server.rs@@ -1,31 +1,14 @@-//! HTTP server for game preview+//! HTTP server for game preview with SSE live reload+use crate::embedded_assets;+use std::io::Write;use std::path::PathBuf;-use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Condvar, Mutex};use std::thread;use tiny_http::{Header, Response, Server};-// =============================================================================-// Embedded Assets-// =============================================================================--const PREVIEW_HTML: &str = include_str!("preview_template.html");-const ENGINE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.js");-const ENGINE_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wasm");-const SDK_JS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.js");-const SDK_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/index.js.map");-const SDK_WASM_JS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js");-const SDK_WASM_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js.map");-const SDK_SPINE_JS: &[u8] = include_bytes!("../../public/sdk/esm/spine/index.js");-const SDK_SPINE_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/spine/index.js.map");-const SPINE38_JS: &[u8] = include_bytes!("../../public/wasm/spine38.js");-const SPINE38_WASM: &[u8] = include_bytes!("../../public/wasm/spine38.wasm");-const SPINE41_JS: &[u8] = include_bytes!("../../public/wasm/spine41.js");-const SPINE41_WASM: &[u8] = include_bytes!("../../public/wasm/spine41.wasm");-const SPINE42_JS: &[u8] = include_bytes!("../../public/wasm/spine42.js");-const SPINE42_WASM: &[u8] = include_bytes!("../../public/wasm/spine42.wasm");-const PHYSICS_JS: &[u8] = include_bytes!("../../public/wasm/physics.js");-const PHYSICS_WASM: &[u8] = include_bytes!("../../public/wasm/physics.wasm");+const MAX_PORT_ATTEMPTS: u16 = 10;// =============================================================================// Preview Server@@ -33,14 +16,62 @@ const PHYSICS_WASM: &[u8] = include_bytes!("../../public/wasm/physics.wasm");pub struct PreviewServer {server: Option<Arc<Server>>,+ reload_signal: Arc<ReloadSignal>,project_dir: PathBuf,port: u16,}+struct ReloadSignal {+ counter: AtomicU64,+ shutdown: AtomicBool,+ condvar: Condvar,+ mutex: Mutex<()>,+}++impl ReloadSignal {+ fn new() -> Self {+ Self {+ counter: AtomicU64::new(0),+ shutdown: AtomicBool::new(false),+ condvar: Condvar::new(),+ mutex: Mutex::new(()),+ }+ }++ fn notify(&self) {+ self.counter.fetch_add(1, Ordering::SeqCst);+ self.condvar.notify_all();+ }++ fn shutdown(&self) {+ self.shutdown.store(true, Ordering::SeqCst);+ self.condvar.notify_all();+ }++ fn wait(&self, last_seen: u64) -> Option<u64> {+ let mut guard = self.mutex.lock().unwrap();+ loop {+ if self.shutdown.load(Ordering::SeqCst) {+ return None;+ }+ let current = self.counter.load(Ordering::SeqCst);+ if current != last_seen {+ return Some(current);+ }+ guard = self.condvar.wait(guard).unwrap();+ }+ }++ fn current(&self) -> u64 {+ self.counter.load(Ordering::SeqCst)+ }+}+impl PreviewServer {pub fn new(project_dir: PathBuf, port: u16) -> Self {Self {server: None,+ reload_signal: Arc::new(ReloadSignal::new()),project_dir,port,}@@ -51,36 +82,46 @@ impl PreviewServer {return Ok(self.port);}- let addr = format!("127.0.0.1:{}", self.port);- let server = Server::http(&addr).map_err(|e| e.to_string())?;+ let (server, actual_port) = try_bind(self.port)?;+ self.port = actual_port;+let server = Arc::new(server);self.server = Some(Arc::clone(&server));let project_dir = self.project_dir.clone();+ let reload_signal = Arc::clone(&self.reload_signal);thread::spawn(move || {for request in server.incoming_requests() {let url = request.url().to_string();let path = url.trim_start_matches('/');+ if path == "sse-reload" {+ let signal = Arc::clone(&reload_signal);+ thread::spawn(move || {+ handle_sse(request, signal);+ });+ continue;+ }+let response = match path {"" | "index.html" => serve_html(),- "wasm/esengine.js" => serve_embedded(ENGINE_JS, "application/javascript"),- "wasm/esengine.wasm" => serve_embedded(ENGINE_WASM, "application/wasm"),- "sdk/index.js" => serve_embedded(SDK_JS, "application/javascript"),- "sdk/index.js.map" => serve_embedded(SDK_JS_MAP, "application/json"),- "sdk/wasm.js" => serve_embedded(SDK_WASM_JS, "application/javascript"),- "sdk/wasm.js.map" => serve_embedded(SDK_WASM_JS_MAP, "application/json"),- "sdk/spine/index.js" => serve_embedded(SDK_SPINE_JS, "application/javascript"),- "sdk/spine/index.js.map" => serve_embedded(SDK_SPINE_JS_MAP, "application/json"),- "wasm/spine38.js" => serve_embedded(SPINE38_JS, "application/javascript"),- "wasm/spine38.wasm" => serve_embedded(SPINE38_WASM, "application/wasm"),- "wasm/spine41.js" => serve_embedded(SPINE41_JS, "application/javascript"),- "wasm/spine41.wasm" => serve_embedded(SPINE41_WASM, "application/wasm"),- "wasm/spine42.js" => serve_embedded(SPINE42_JS, "application/javascript"),- "wasm/spine42.wasm" => serve_embedded(SPINE42_WASM, "application/wasm"),- "wasm/physics.js" => serve_embedded(PHYSICS_JS, "application/javascript"),- "wasm/physics.wasm" => serve_embedded(PHYSICS_WASM, "application/wasm"),+ "wasm/esengine.js" => serve_embedded(embedded_assets::ENGINE_JS, "application/javascript"),+ "wasm/esengine.wasm" => serve_embedded(embedded_assets::ENGINE_WASM, "application/wasm"),+ "sdk/index.js" => serve_embedded(embedded_assets::SDK_ESM_JS, "application/javascript"),+ "sdk/index.js.map" => serve_embedded(embedded_assets::SDK_ESM_JS_MAP, "application/json"),+ "sdk/wasm.js" => serve_embedded(embedded_assets::SDK_WASM_JS, "application/javascript"),+ "sdk/wasm.js.map" => serve_embedded(embedded_assets::SDK_WASM_JS_MAP, "application/json"),+ "sdk/spine/index.js" => serve_embedded(embedded_assets::SDK_SPINE_JS, "application/javascript"),+ "sdk/spine/index.js.map" => serve_embedded(embedded_assets::SDK_SPINE_JS_MAP, "application/json"),+ "wasm/spine38.js" => serve_embedded(embedded_assets::SPINE38_JS, "application/javascript"),+ "wasm/spine38.wasm" => serve_embedded(embedded_assets::SPINE38_WASM, "application/wasm"),+ "wasm/spine41.js" => serve_embedded(embedded_assets::SPINE41_JS, "application/javascript"),+ "wasm/spine41.wasm" => serve_embedded(embedded_assets::SPINE41_WASM, "application/wasm"),+ "wasm/spine42.js" => serve_embedded(embedded_assets::SPINE42_JS, "application/javascript"),+ "wasm/spine42.wasm" => serve_embedded(embedded_assets::SPINE42_WASM, "application/wasm"),+ "wasm/physics.js" => serve_embedded(embedded_assets::PHYSICS_JS, "application/javascript"),+ "wasm/physics.wasm" => serve_embedded(embedded_assets::PHYSICS_WASM, "application/wasm"),_ => serve_project_file(&project_dir, path),};@@ -92,9 +133,17 @@ impl PreviewServer {}pub fn stop(&mut self) {+ self.reload_signal.shutdown();+ if let Some(ref server) = self.server {+ server.unblock();+ }self.server = None;}+ pub fn notify_reload(&self) {+ self.reload_signal.notify();+ }+pub fn is_running(&self) -> bool {self.server.is_some()}@@ -104,25 +153,86 @@ impl PreviewServer {}}+// =============================================================================+// Port Binding+// =============================================================================++fn try_bind(starting_port: u16) -> Result<(Server, u16), String> {+ for offset in 0..MAX_PORT_ATTEMPTS {+ let port = starting_port + offset;+ let addr = format!("127.0.0.1:{}", port);+ match Server::http(&addr) {+ Ok(server) => return Ok((server, port)),+ Err(_) if offset + 1 < MAX_PORT_ATTEMPTS => continue,+ Err(e) => return Err(format!("Failed to bind ports {}-{}: {}", starting_port, port, e)),+ }+ }+ unreachable!()+}++// =============================================================================+// SSE Live Reload+// =============================================================================++fn handle_sse(request: tiny_http::Request, signal: Arc<ReloadSignal>) {+ let headers = vec![+ Header::from_bytes("Content-Type", "text/event-stream").unwrap(),+ Header::from_bytes("Cache-Control", "no-cache").unwrap(),+ Header::from_bytes("Connection", "keep-alive").unwrap(),+ Header::from_bytes("Access-Control-Allow-Origin", "*").unwrap(),+ ];++ let (reader, mut writer) = std::io::pipe().unwrap();+ let response = Response::new(+ tiny_http::StatusCode(200),+ headers,+ Box::new(reader) as Box<dyn std::io::Read + Send>,+ None,+ None,+ );++ let respond_handle = thread::spawn(move || {+ let _ = request.respond(response);+ });++ let mut last_seen = signal.current();+ loop {+ match signal.wait(last_seen) {+ None => break,+ Some(new_val) => last_seen = new_val,+ }+ if writer.write_all(b"data: reload\n\n").is_err() {+ break;+ }+ if writer.flush().is_err() {+ break;+ }+ }++ drop(writer);+ let _ = respond_handle.join();+}+// =============================================================================// Response Builders// =============================================================================fn serve_html() -> Response<std::io::Cursor<Vec<u8>>> {- let data = PREVIEW_HTML.as_bytes().to_vec();+ let data = embedded_assets::PREVIEW_HTML.as_bytes().to_vec();Response::from_data(data).with_header(content_type("text/html"))+ .with_header(no_cache()).with_header(cors())}fn serve_embedded(data: &[u8], content_type_str: &str) -> Response<std::io::Cursor<Vec<u8>>> {Response::from_data(data.to_vec()).with_header(content_type(content_type_str))+ .with_header(no_cache()).with_header(cors())}fn serve_project_file(project_dir: &PathBuf, path: &str) -> Response<std::io::Cursor<Vec<u8>>> {- // Decode URL-encoded path (e.g., Chinese characters)let decoded_path = urlencoding::decode(path).unwrap_or_else(|_| path.into());let file_path = project_dir.join(decoded_path.as_ref());@@ -134,6 +244,7 @@ fn serve_project_file(project_dir: &PathBuf, path: &str) -> Response<std::io::CuOk(data) => {Response::from_data(data).with_header(content_type(get_mime_type(path)))+ .with_header(no_cache()).with_header(cors())}Err(_) => not_found(),@@ -154,6 +265,10 @@ fn cors() -> Header {Header::from_bytes("Access-Control-Allow-Origin", "*").unwrap()}+fn no_cache() -> Header {+ Header::from_bytes("Cache-Control", "no-cache").unwrap()+}+fn get_mime_type(path: &str) -> &'static str {match path.rsplit('.').next() {Some("html") => "text/html",diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.htmlindex 0a266e586..b5b931a23 100644--- a/desktop/src-tauri/src/preview_template.html+++ b/desktop/src-tauri/src/preview_template.html@@ -195,7 +195,17 @@showError('[unhandled rejection] ' + (err?.message || String(err)), err);});+ function connectLiveReload() {+ const sse = new EventSource('/sse-reload');+ sse.onmessage = () => location.reload();+ sse.onerror = () => {+ sse.close();+ setTimeout(connectLiveReload, 2000);+ };+ }+loadPreview();+ connectLiveReload();</script></body></html>diff --git a/editor/src/asset/AssetDependencyAnalyzer.ts b/editor/src/asset/AssetDependencyAnalyzer.tsindex b6913fe7f..3ea90d758 100644--- a/editor/src/asset/AssetDependencyAnalyzer.ts+++ b/editor/src/asset/AssetDependencyAnalyzer.ts@@ -4,7 +4,7 @@*/import type { AssetDatabase } from './AssetDatabase';-import { isUUID } from './AssetDatabase';+import { isUUID, getComponentRefFields } from './AssetDatabase';import { looksLikeAssetPath } from './AssetTypes';import { joinPath, isAbsolutePath, getDirName } from '../utils/path';import type { NativeFS } from '../types/NativeFS';@@ -26,40 +26,24 @@ export interface DependencyGraph {}// =============================================================================-// Builtin Scanners+// Scanners// =============================================================================-const builtinScanners: AssetRefScanner[] = [- {- componentType: 'Sprite',- extractRefs: (d) => [d.texture as string, d.material as string].filter(Boolean),- },- {- componentType: 'SpineAnimation',- extractRefs: (d) => [- d.skeletonPath as string,- d.atlasPath as string,- d.material as string,- ].filter(Boolean),- },- {- componentType: 'BitmapText',- extractRefs: (d) => [d.font as string].filter(Boolean),- },- {- componentType: 'UIMask',- extractRefs: (d) => [d.texture as string].filter(Boolean),- },-];-const customScanners: AssetRefScanner[] = [];export function registerRefScanner(scanner: AssetRefScanner): void {customScanners.push(scanner);}-function getAllScanners(): AssetRefScanner[] {- return [...builtinScanners, ...customScanners];+function getScanner(componentType: string): AssetRefScanner | undefined {+ const custom = customScanners.find(s => s.componentType === componentType);+ if (custom) return custom;+ const fields = getComponentRefFields(componentType);+ if (!fields) return undefined;+ return {+ componentType,+ extractRefs: (d) => fields.map(f => d[f] as string).filter(Boolean),+ };}// =============================================================================@@ -164,18 +148,12 @@ export class AssetDependencyAnalyzer {if (!entities) return refs;- const scanners = getAllScanners();- const scannerMap = new Map<string, AssetRefScanner>();- for (const s of scanners) {- scannerMap.set(s.componentType, s);- }-for (const entity of entities) {if (entity.prefab?.prefabPath) {refs.push(entity.prefab.prefabPath);}for (const comp of entity.components || []) {- const scanner = scannerMap.get(comp.type);+ const scanner = getScanner(comp.type);if (scanner && comp.data) {refs.push(...scanner.extractRefs(comp.data));}@@ -334,12 +312,6 @@ export class AssetDependencyAnalyzer {if (!entities) return;- const scanners = getAllScanners();- const scannerMap = new Map<string, AssetRefScanner>();- for (const s of scanners) {- scannerMap.set(s.componentType, s);- }-for (const entity of entities) {if (entity.nestedPrefab?.prefabPath) {const nestedRef = this.resolveRef(entity.nestedPrefab.prefabPath);@@ -349,7 +321,7 @@ export class AssetDependencyAnalyzer {}for (const comp of entity.components || []) {- const scanner = scannerMap.get(comp.type);+ const scanner = getScanner(comp.type);if (scanner && comp.data) {const refs = scanner.extractRefs(comp.data);for (const ref of refs) {diff --git a/editor/src/bridge/EditorBridge.ts b/editor/src/bridge/EditorBridge.tsindex 4f4df300c..ec15642c7 100644--- a/editor/src/bridge/EditorBridge.ts+++ b/editor/src/bridge/EditorBridge.ts@@ -74,36 +74,6 @@ export class EditorBridge {this.module_.renderFrame(this.registry_, width, height);}- // =========================================================================- // Preview Mode- // =========================================================================-- private savedScene_: SceneData | null = null;- private isPreviewMode_ = false;-- enterPreviewMode(): void {- if (this.isPreviewMode_) return;-- this.savedScene_ = JSON.parse(JSON.stringify(this.store_.scene));- this.isPreviewMode_ = true;- this.syncToRuntime();- }-- exitPreviewMode(): void {- if (!this.isPreviewMode_) return;-- if (this.savedScene_) {- this.store_.loadScene(this.savedScene_);- this.savedScene_ = null;- }-- this.isPreviewMode_ = false;- }-- get isPreviewMode(): boolean {- return this.isPreviewMode_;- }-// =========================================================================// Private Methods// =========================================================================diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsindex ed4c73998..02cfaecc2 100644--- a/editor/src/builder/ArtifactBuilder.ts+++ b/editor/src/builder/ArtifactBuilder.ts@@ -10,8 +10,10 @@ import type { NativeFS } from '../types/NativeFS';import { BuildProgressReporter } from './BuildProgress';import { AssetExportConfigService, BuildAssetCollector } from './AssetCollector';import { TextureAtlasPacker } from './TextureAtlas';-import { AssetLibrary } from '../asset/AssetLibrary';+import { AssetLibrary, isUUID } from '../asset/AssetLibrary';+import { getAssetType, toAddressableType } from '../asset/AssetTypes';import { compileMaterials } from './MaterialCompiler';+import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';import { normalizePath, joinPath, isAbsolutePath, getParentDir } from '../utils/path';import { getEsbuildWasmURL } from '../context/EditorContext';@@ -98,14 +100,124 @@ export async function buildArtifact(export type SdkModuleLoader = (path: string) => Promise<{ contents: string; loader: esbuild.Loader }>;+let esbuildInitialized = false;+export async function initializeEsbuild(): Promise<void> {- try {- await esbuild.initialize({ wasmURL: getEsbuildWasmURL() });- } catch (err) {- if (!String(err).includes('Cannot call "initialize" more than once')) {- throw err;+ if (esbuildInitialized) return;+ await esbuild.initialize({ wasmURL: getEsbuildWasmURL() });+ esbuildInitialized = true;+}++// =============================================================================+// Shared emitter utilities+// =============================================================================++export function arrayBufferToBase64(buffer: Uint8Array): string {+ let binary = '';+ const bytes = new Uint8Array(buffer);+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ return btoa(binary);+}++export function generateAddressableManifest(+ artifact: BuildArtifact+): { version: string; groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, unknown> }> } {+ const groupService = artifact.assetLibrary.getGroupService();+ const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, unknown> }> = {};++ const spineAtlasPaths = new Map<string, string>();+ for (const relativePath of artifact.assetPaths) {+ if (getAssetType(relativePath) === 'spine-atlas') {+ const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));+ spineAtlasPaths.set(dir, relativePath);}}++ for (const relativePath of artifact.assetPaths) {+ if (relativePath.endsWith('.esshader')) continue;++ const editorType = getAssetType(relativePath);+ const addressableType = toAddressableType(editorType);+ if (!addressableType) continue;++ const uuid = artifact.assetLibrary.getUuid(relativePath);+ if (!uuid) continue;++ const entry = artifact.assetLibrary.getEntry(uuid);+ const groupName = entry?.group ?? 'default';++ if (!groups[groupName]) {+ const groupDef = groupService?.getGroup(groupName);+ groups[groupName] = {+ bundleMode: groupDef?.bundleMode ?? 'together',+ labels: groupDef?.labels ?? [],+ assets: {},+ };+ }++ let path = relativePath;+ const metadata: Record<string, unknown> = {};++ if (artifact.packedPaths.has(relativePath)) {+ const frame = artifact.atlasResult.frameMap.get(relativePath);+ if (frame) {+ path = `atlas_${frame.page}.png`;+ metadata.atlasPage = frame.page;+ metadata.atlasFrame = {+ x: frame.frame.x,+ y: frame.frame.y,+ width: frame.frame.width,+ height: frame.frame.height,+ };+ }+ }++ const compiledMat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);+ if (compiledMat) {+ path = relativePath.replace(/\.esmaterial$/, '.json');+ }++ if (addressableType === 'spine') {+ const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));+ const atlasPath = spineAtlasPaths.get(dir);+ if (atlasPath) {+ metadata.atlas = atlasPath;+ }+ }++ const asset: Record<string, unknown> = {+ path,+ type: addressableType,+ size: entry?.fileSize ?? 0,+ labels: entry ? [...entry.labels] : [],+ };+ if (entry?.address) {+ asset.address = entry.address;+ }+ if (Object.keys(metadata).length > 0) {+ asset.metadata = metadata;+ }++ groups[groupName].assets[uuid] = asset;+ }++ return { version: '2.0', groups };+}++export function convertPrefabWithResolvedRefs(+ prefabContent: string,+ artifact: BuildArtifact+): string {+ const prefab = deserializePrefab(prefabContent);+ const converted = convertPrefabAssetRefs(prefab, (value) => {+ if (isUUID(value)) {+ return artifact.assetLibrary.getPath(value) ?? value;+ }+ return value;+ });+ return JSON.stringify(converted);}export function createBuildVirtualFsPlugin(diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.tsindex 8882ea53d..20b436e48 100644--- a/editor/src/builder/PlayableEmitter.ts+++ b/editor/src/builder/PlayableEmitter.ts@@ -10,10 +10,9 @@ import { BuildProgressReporter } from './BuildProgress';import { getEditorContext } from '../context/EditorContext';import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';import { joinPath, getFileExtension, isAbsolutePath, getParentDir, normalizePath, getProjectDir } from '../utils/path';-import { isUUID } from '../asset/AssetLibrary';-import { getAssetType, toAddressableType } from '../asset/AssetTypes';-import { initializeEsbuild, createBuildVirtualFsPlugin } from './ArtifactBuilder';-import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';+import { isUUID, getComponentRefFields } from '../asset/AssetLibrary';+import { initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, convertPrefabWithResolvedRefs } from './ArtifactBuilder';+import { PLAYABLE_HTML_TEMPLATE } from './templates';import type { NativeFS } from '../types/NativeFS';// =============================================================================@@ -90,7 +89,7 @@ export class PlayableEmitter implements PlatformEmitter {const spineWasm = await fs.getSpineWasm(context.spineVersion);if (spineJs && spineWasm.length > 0) {spineJsSource = spineJs;- spineWasmBase64 = this.arrayBufferToBase64(spineWasm);+ spineWasmBase64 = arrayBufferToBase64(spineWasm);progress.log('info', `Spine ${context.spineVersion} module loaded`);}}@@ -104,7 +103,7 @@ export class PlayableEmitter implements PlatformEmitter {const physicsWasm = await fs.getPhysicsWasm();if (physicsJs && physicsWasm.length > 0) {physicsJsSource = physicsJs;- physicsWasmBase64 = this.arrayBufferToBase64(physicsWasm);+ physicsWasmBase64 = arrayBufferToBase64(physicsWasm);progress.log('info', 'Physics module loaded');}}@@ -114,13 +113,13 @@ export class PlayableEmitter implements PlatformEmitter {progress.setCurrentTask('Collecting assets...', 0);const assets = await this.collectInlineAssets(fs, projectDir, artifact);for (let i = 0; i < artifact.atlasResult.pages.length; i++) {- const base64 = this.arrayBufferToBase64(artifact.atlasResult.pages[i].imageData);+ const base64 = arrayBufferToBase64(artifact.atlasResult.pages[i].imageData);assets.set(`atlas_${i}.png`, `data:image/png;base64,${base64}`);}progress.log('info', `Collected ${assets.size} assets`);// 6.5 Generate addressable manifest- const manifestJson = this.generateAddressableManifest(artifact);+ const manifestJson = JSON.stringify(generateAddressableManifest(artifact));// 7. Assemble HTMLprogress.setCurrentTask('Assembling HTML...', 50);@@ -249,28 +248,13 @@ ${imports}if (path) entity.prefab.prefabPath = path;}for (const comp of entity.components || []) {- if (comp.type === 'Sprite' && comp.data) {- if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture)) {- const path = artifact.assetLibrary.getPath(comp.data.texture);- if (path) comp.data.texture = path;- }- if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {- const path = artifact.assetLibrary.getPath(comp.data.material);- if (path) comp.data.material = path;- }- }- if (comp.type === 'SpineAnimation' && comp.data) {- if (typeof comp.data.skeletonPath === 'string' && isUUID(comp.data.skeletonPath)) {- const path = artifact.assetLibrary.getPath(comp.data.skeletonPath);- if (path) comp.data.skeletonPath = path;- }- if (typeof comp.data.atlasPath === 'string' && isUUID(comp.data.atlasPath)) {- const path = artifact.assetLibrary.getPath(comp.data.atlasPath);- if (path) comp.data.atlasPath = path;- }- if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {- const path = artifact.assetLibrary.getPath(comp.data.material);- if (path) comp.data.material = path;+ const refFields = getComponentRefFields(comp.type);+ if (!refFields || !comp.data) continue;+ for (const field of refFields) {+ const value = comp.data[field];+ if (typeof value === 'string' && isUUID(value)) {+ const path = artifact.assetLibrary.getPath(value);+ if (path) comp.data[field] = path;}}}@@ -322,14 +306,7 @@ ${imports}const fullPath = joinPath(projectDir, relativePath);const content = await fs.readFile(fullPath);if (content) {- const prefab = deserializePrefab(content);- const converted = convertPrefabAssetRefs(prefab, (value) => {- if (isUUID(value)) {- return artifact.assetLibrary.getPath(value) ?? value;- }- return value;- });- const json = JSON.stringify(converted);+ const json = convertPrefabWithResolvedRefs(content, artifact);const base64 = btoa(json);assets.set(relativePath, `data:application/json;base64,${base64}`);}@@ -343,7 +320,7 @@ ${imports}const fullPath = joinPath(projectDir, relativePath);const binary = await fs.readBinaryFile(fullPath);if (binary) {- const base64 = this.arrayBufferToBase64(binary);+ const base64 = arrayBufferToBase64(binary);assets.set(relativePath, `data:${mimeType};base64,${base64}`);}}@@ -397,7 +374,7 @@ ${imports}subStepCount: context.physicsSubStepCount ?? 4,});- return HTML_TEMPLATE+ return PLAYABLE_HTML_TEMPLATE.replace('{{WASM_SDK}}', () => wasmSdk).replace('{{SPINE_SCRIPT}}', () => spineScript).replace('{{PHYSICS_SCRIPT}}', () => physicsScript)@@ -408,214 +385,4 @@ ${imports}.replace('{{MANIFEST}}', () => manifestJson);}- private generateAddressableManifest(artifact: BuildArtifact): string {- const groupService = artifact.assetLibrary.getGroupService();- const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, unknown> }> = {};-- const spineAtlasPaths = new Map<string, string>();- for (const relativePath of artifact.assetPaths) {- if (getAssetType(relativePath) === 'spine-atlas') {- const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));- spineAtlasPaths.set(dir, relativePath);- }- }-- for (const relativePath of artifact.assetPaths) {- if (relativePath.endsWith('.esshader')) continue;-- const editorType = getAssetType(relativePath);- const addressableType = toAddressableType(editorType);- if (!addressableType) continue;-- const uuid = artifact.assetLibrary.getUuid(relativePath);- if (!uuid) continue;-- const entry = artifact.assetLibrary.getEntry(uuid);- const groupName = entry?.group ?? 'default';-- if (!groups[groupName]) {- const groupDef = groupService?.getGroup(groupName);- groups[groupName] = {- bundleMode: groupDef?.bundleMode ?? 'together',- labels: groupDef?.labels ?? [],- assets: {},- };- }-- let path = relativePath;- const metadata: Record<string, unknown> = {};-- if (artifact.packedPaths.has(relativePath)) {- const frame = artifact.atlasResult.frameMap.get(relativePath);- if (frame) {- path = `atlas_${frame.page}.png`;- metadata.atlasPage = frame.page;- metadata.atlasFrame = {- x: frame.frame.x,- y: frame.frame.y,- width: frame.frame.width,- height: frame.frame.height,- };- }- }-- const compiledMat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);- if (compiledMat) {- path = relativePath.replace(/\.esmaterial$/, '.json');- }-- if (addressableType === 'spine') {- const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));- const atlasPath = spineAtlasPaths.get(dir);- if (atlasPath) {- metadata.atlas = atlasPath;- }- }-- const asset: Record<string, unknown> = {- path,- type: addressableType,- size: entry?.fileSize ?? 0,- labels: entry ? [...entry.labels] : [],- };- if (entry?.address) {- asset.address = entry.address;- }- if (Object.keys(metadata).length > 0) {- asset.metadata = metadata;- }-- groups[groupName].assets[uuid] = asset;- }-- return JSON.stringify({ version: '2.0', groups });- }-- private arrayBufferToBase64(buffer: Uint8Array): string {- let binary = '';- const bytes = new Uint8Array(buffer);- for (let i = 0; i < bytes.byteLength; i++) {- binary += String.fromCharCode(bytes[i]);- }- return btoa(binary);- }}--// =============================================================================-// HTML Template-// =============================================================================--const HTML_TEMPLATE = `<!DOCTYPE html>-<html lang="en">-<head>-<meta charset="UTF-8">-<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">-<meta name="ad.size" content="width=320,height=480">-<title>Playable</title>-<style>-*{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}-</style>-</head>-<body>-<canvas id="canvas"></canvas>-<script>-{{WASM_SDK}}-</script>-{{SPINE_SCRIPT}}-{{PHYSICS_SCRIPT}}-<script>-{{GAME_CODE}}-</script>-<script>-var __PA__={{ASSETS_MAP}};-var __SCENE__={{SCENE_DATA}};-var __MANIFEST__={{MANIFEST}};--function loadImagePixels(dataUrl){- return new Promise(function(resolve,reject){- var img=new Image();- img.onload=function(){- var cv=document.createElement('canvas');- cv.width=img.width;cv.height=img.height;- var ctx=cv.getContext('2d');- ctx.drawImage(img,0,0);- var id=ctx.getImageData(0,0,img.width,img.height);- resolve({width:img.width,height:img.height,pixels:new Uint8Array(id.data.buffer)});- };- img.onerror=reject;- img.src=dataUrl;- });-}--function decodeText(dataUrl){return atob(dataUrl.split(',')[1])}--function decodeBinary(dataUrl){- var b=atob(dataUrl.split(',')[1]);- var a=new Uint8Array(b.length);- for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);- return a;-}--(async function(){- 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);- resize();-- var Module=await ESEngineModule({canvas:c,print:function(t){console.log(t)},printErr:function(t){console.error(t)}});- var es=window.esengine;- if(!es||!es.createWebApp){console.error('esengine not found');return}-- var app=es.createWebApp(Module);- if(typeof __PA__!=='undefined')es.registerEmbeddedAssets(app,__PA__);- es.flushPendingSystems(app);-- var spineModule=null;- if(typeof ESSpineModule!=='undefined'){- try{- spineModule=await ESSpineModule({- instantiateWasm:function(imports,cb){- var b=atob(__SPINE_WASM_B64__);- var a=new Uint8Array(b.length);- for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);- WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});- return {};- }- });- }catch(e){console.warn('Spine module not available:',e)}- }-- var physicsModule=null;- if(typeof ESPhysicsModule!=='undefined'){- try{- physicsModule=await ESPhysicsModule({- instantiateWasm:function(imports,cb){- var b=atob(__PHYSICS_WASM_B64__);- var a=new Uint8Array(b.length);- for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);- WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});- return {};- }- });- }catch(e){console.warn('Physics module not available:',e)}- }-- var provider={- loadPixels:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return loadImagePixels(d)},- readText:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeText(d)},- readBinary:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeBinary(d)},- resolvePath:function(ref){return ref}- };-- await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule,{{PHYSICS_CONFIG}},__MANIFEST__);-- var screenAspect=c.width/c.height;- es.updateCameraAspectRatio(app.world,screenAspect);-- app.run();-})();-</script>-</body>-</html>`;diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.tsindex 29150cc40..8e1fba1ee 100644--- a/editor/src/builder/WeChatEmitter.ts+++ b/editor/src/builder/WeChatEmitter.ts@@ -10,11 +10,9 @@ import { BuildProgressReporter } from './BuildProgress';import { getEditorContext } from '../context/EditorContext';import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';import { joinPath, getProjectDir } from '../utils/path';-import { isUUID } from '../asset/AssetLibrary';-import { getAssetType, toAddressableType } from '../asset/AssetTypes';import { resolveShaderPath } from '../utils/shader';-import { initializeEsbuild, createBuildVirtualFsPlugin } from './ArtifactBuilder';-import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';+import { initializeEsbuild, createBuildVirtualFsPlugin, generateAddressableManifest, convertPrefabWithResolvedRefs } from './ArtifactBuilder';+import { generateWeChatGameJs } from './templates';import type { NativeFS } from '../types/NativeFS';// =============================================================================@@ -222,126 +220,19 @@ export class WeChatEmitter implements PlatformEmitter {const firstScene = context.config.scenes[0];const firstSceneName = firstScene ? firstScene.replace(/.*\//, '').replace('.esscene', '') : '';- const gameJs = `-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;-${context.spineVersion ? `-async function initSpineModule() {- try {- var SpineFactory = require('./spine.js');- spineModule = await SpineFactory({- instantiateWasm: function(imports, successCallback) {- WXWebAssembly.instantiate('spine.wasm', imports).then(function(result) {- successCallback(result.instance, result.module);- });- return {};- }- });- } catch(e) { console.warn('Spine module not available:', e); }-}` : ''}--var physicsModule = null;-${context.enablePhysics ? `-async function initPhysicsModule() {- try {- var PhysicsFactory = require('./physics.js');- physicsModule = await PhysicsFactory({- instantiateWasm: function(imports, successCallback) {- WXWebAssembly.instantiate('physics.wasm', imports).then(function(result) {- successCallback(result.instance, result.module);- });- return {};- }- });- } catch(e) { console.warn('Physics module not available:', e); }-}` : ''}--(async function() {- var canvas = wx.createCanvas();- var info = wx.getSystemInfoSync();- canvas.width = info.windowWidth * info.pixelRatio;- canvas.height = info.windowHeight * info.pixelRatio;-- var module = await ESEngineModule({- canvas: canvas,- instantiateWasm: function(imports, successCallback) {- WXWebAssembly.instantiate('esengine.wasm', imports).then(function(result) {- successCallback(result.instance, result.module);- });- return {};- }- });-- var gl = canvas.getContext('webgl2') || canvas.getContext('webgl');- if (!gl) {- console.error('[ESEngine] Failed to create WebGL context');- return;- }- var glHandle = module.GL.registerContext(gl, {- majorVersion: gl.getParameter(gl.VERSION).indexOf('WebGL 2') === 0 ? 2 : 1,- minorVersion: 0,- enableExtensionsByDefault: true- });-- var app = SDK.createWebApp(module, {- glContextHandle: glHandle,- getViewportSize: function() {- return { width: canvas.width, height: canvas.height };- }- });-- ${userCode}-- SDK.flushPendingSystems(app);-- ${context.spineVersion ? 'await initSpineModule();' : ''}- ${context.enablePhysics ? 'await initPhysicsModule();' : ''}-- ${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))); },- resolvePath: resolvePath- };-- var sceneJson = wxfs.readFileSync('scenes/${firstSceneName}.json', 'utf-8');- var sceneData = JSON.parse(sceneJson);-- await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule, physicsModule, ${JSON.stringify({+ const physicsConfig = JSON.stringify({gravity: context.physicsGravity ?? { x: 0, y: -9.81 },fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,subStepCount: context.physicsSubStepCount ?? 4,- })}, manifest);+ });- var screenAspect = canvas.width / canvas.height;- SDK.updateCameraAspectRatio(app.world, screenAspect);- } catch (err) {- console.error('[ESEngine] Failed to load scene:', err);- }- ` : ''}- app.run();-})();-`;+ const gameJs = generateWeChatGameJs({+ userCode,+ firstSceneName,+ hasSpine: !!context.spineVersion,+ hasPhysics: !!context.enablePhysics,+ physicsConfig,+ });await fs.writeFile(joinPath(outputDir, 'game.js'), gameJs);await this.copyWeChatSdk(fs, outputDir, context);@@ -468,14 +359,8 @@ async function initPhysicsModule() {if (relativePath.endsWith('.esprefab')) {const content = await fs.readFile(srcPath);if (content) {- const prefab = deserializePrefab(content);- const converted = convertPrefabAssetRefs(prefab, (value) => {- if (isUUID(value)) {- return artifact.assetLibrary.getPath(value) ?? value;- }- return value;- });- await fs.writeFile(destPath, JSON.stringify(converted, null, 2));+ const json = convertPrefabWithResolvedRefs(content, artifact);+ await fs.writeFile(destPath, JSON.stringify(JSON.parse(json), null, 2));}continue;}@@ -492,86 +377,7 @@ async function initPhysicsModule() {outputDir: string,artifact: BuildArtifact): Promise<void> {- const groupService = artifact.assetLibrary.getGroupService();- const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, unknown> }> = {};-- const spineAtlasPaths = new Map<string, string>();- for (const relativePath of artifact.assetPaths) {- if (getAssetType(relativePath) === 'spine-atlas') {- const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));- spineAtlasPaths.set(dir, relativePath);- }- }-- for (const relativePath of artifact.assetPaths) {- if (relativePath.endsWith('.esshader')) continue;-- const editorType = getAssetType(relativePath);- const addressableType = toAddressableType(editorType);- if (!addressableType) continue;-- const uuid = artifact.assetLibrary.getUuid(relativePath);- if (!uuid) continue;-- const entry = artifact.assetLibrary.getEntry(uuid);- const groupName = entry?.group ?? 'default';-- if (!groups[groupName]) {- const groupDef = groupService?.getGroup(groupName);- groups[groupName] = {- bundleMode: groupDef?.bundleMode ?? 'together',- labels: groupDef?.labels ?? [],- assets: {},- };- }-- let path = relativePath;- const metadata: Record<string, unknown> = {};-- if (artifact.packedPaths.has(relativePath)) {- const frame = artifact.atlasResult.frameMap.get(relativePath);- if (frame) {- path = `atlas_${frame.page}.png`;- metadata.atlasPage = frame.page;- metadata.atlasFrame = {- x: frame.frame.x,- y: frame.frame.y,- width: frame.frame.width,- height: frame.frame.height,- };- }- }-- const compiledMat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);- if (compiledMat) {- path = relativePath.replace(/\.esmaterial$/, '.json');- }-- if (addressableType === 'spine') {- const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));- const atlasPath = spineAtlasPaths.get(dir);- if (atlasPath) {- metadata.atlas = atlasPath;- }- }-- const asset: Record<string, unknown> = {- path,- type: addressableType,- size: entry?.fileSize ?? 0,- labels: entry ? [...entry.labels] : [],- };- if (entry?.address) {- asset.address = entry.address;- }- if (Object.keys(metadata).length > 0) {- asset.metadata = metadata;- }-- groups[groupName].assets[uuid] = asset;- }-- const manifest = { version: '2.0', groups };+ const manifest = generateAddressableManifest(artifact);await fs.writeFile(joinPath(outputDir, 'asset-manifest.json'),JSON.stringify(manifest, null, 2)diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.tsindex e48d78616..41b607f61 100644--- a/editor/src/builder/index.ts+++ b/editor/src/builder/index.ts@@ -5,7 +5,8 @@export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';export { BuildService, type BuildResult, type BuildContext, type BuildOptions } from './BuildService';-export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, type SdkModuleLoader } from './ArtifactBuilder';+export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, convertPrefabWithResolvedRefs, type SdkModuleLoader } from './ArtifactBuilder';+export { PLAYABLE_HTML_TEMPLATE, generateWeChatGameJs, type WeChatGameJsParams } from './templates';export { BuildCache, type BuildCacheData, type FileHash, type FileChangeResult } from './BuildCache';export { BuildProgressReporter, formatDuration, formatSize, type BuildProgress, type BuildLogEntry, type BuildPhase, type LogLevel } from './BuildProgress';diff --git a/editor/src/builder/templates.ts b/editor/src/builder/templates.tsnew file mode 100644index 000000000..2f0373762--- /dev/null+++ b/editor/src/builder/templates.ts@@ -0,0 +1,262 @@+/**+ * @file templates.ts+ * @brief Build output templates for platform emitters+ */++// =============================================================================+// Playable HTML Template+// =============================================================================++export const PLAYABLE_HTML_TEMPLATE = `<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">+<meta name="ad.size" content="width=320,height=480">+<title>Playable</title>+<style>+*{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}+</style>+</head>+<body>+<canvas id="canvas"></canvas>+<script>+{{WASM_SDK}}+</script>+{{SPINE_SCRIPT}}+{{PHYSICS_SCRIPT}}+<script>+{{GAME_CODE}}+</script>+<script>+var __PA__={{ASSETS_MAP}};+var __SCENE__={{SCENE_DATA}};+var __MANIFEST__={{MANIFEST}};++function loadImagePixels(dataUrl){+ return new Promise(function(resolve,reject){+ var img=new Image();+ img.onload=function(){+ var cv=document.createElement('canvas');+ cv.width=img.width;cv.height=img.height;+ var ctx=cv.getContext('2d');+ ctx.drawImage(img,0,0);+ var id=ctx.getImageData(0,0,img.width,img.height);+ resolve({width:img.width,height:img.height,pixels:new Uint8Array(id.data.buffer)});+ };+ img.onerror=reject;+ img.src=dataUrl;+ });+}++function decodeText(dataUrl){return atob(dataUrl.split(',')[1])}++function decodeBinary(dataUrl){+ var b=atob(dataUrl.split(',')[1]);+ var a=new Uint8Array(b.length);+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);+ return a;+}++(async function(){+ 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);+ resize();++ var Module=await ESEngineModule({canvas:c,print:function(t){console.log(t)},printErr:function(t){console.error(t)}});+ var es=window.esengine;+ if(!es||!es.createWebApp){console.error('esengine not found');return}++ var app=es.createWebApp(Module);+ if(typeof __PA__!=='undefined')es.registerEmbeddedAssets(app,__PA__);+ es.flushPendingSystems(app);++ var spineModule=null;+ if(typeof ESSpineModule!=='undefined'){+ try{+ spineModule=await ESSpineModule({+ instantiateWasm:function(imports,cb){+ var b=atob(__SPINE_WASM_B64__);+ var a=new Uint8Array(b.length);+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);+ WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});+ return {};+ }+ });+ }catch(e){console.warn('Spine module not available:',e)}+ }++ var physicsModule=null;+ if(typeof ESPhysicsModule!=='undefined'){+ try{+ physicsModule=await ESPhysicsModule({+ instantiateWasm:function(imports,cb){+ var b=atob(__PHYSICS_WASM_B64__);+ var a=new Uint8Array(b.length);+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);+ WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});+ return {};+ }+ });+ }catch(e){console.warn('Physics module not available:',e)}+ }++ var provider={+ loadPixels:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return loadImagePixels(d)},+ readText:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeText(d)},+ readBinary:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeBinary(d)},+ resolvePath:function(ref){return ref}+ };++ await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule,{{PHYSICS_CONFIG}},__MANIFEST__);++ var screenAspect=c.width/c.height;+ es.updateCameraAspectRatio(app.world,screenAspect);++ app.run();+})();+</script>+</body>+</html>`;++// =============================================================================+// WeChat game.js Template+// =============================================================================++export interface WeChatGameJsParams {+ userCode: string;+ firstSceneName: string;+ hasSpine: boolean;+ hasPhysics: boolean;+ physicsConfig: string;+}++export function generateWeChatGameJs(params: WeChatGameJsParams): string {+ const { userCode, firstSceneName, hasSpine, hasPhysics, physicsConfig } = params;++ const spineInit = hasSpine ? `+async function initSpineModule() {+ try {+ var SpineFactory = require('./spine.js');+ spineModule = await SpineFactory({+ instantiateWasm: function(imports, successCallback) {+ WXWebAssembly.instantiate('spine.wasm', imports).then(function(result) {+ successCallback(result.instance, result.module);+ });+ return {};+ }+ });+ } catch(e) { console.warn('Spine module not available:', e); }+}` : '';++ const physicsInit = hasPhysics ? `+async function initPhysicsModule() {+ try {+ var PhysicsFactory = require('./physics.js');+ physicsModule = await PhysicsFactory({+ instantiateWasm: function(imports, successCallback) {+ WXWebAssembly.instantiate('physics.wasm', imports).then(function(result) {+ successCallback(result.instance, result.module);+ });+ return {};+ }+ });+ } catch(e) { console.warn('Physics module not available:', e); }+}` : '';++ 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))); },+ resolvePath: resolvePath+ };++ var sceneJson = wxfs.readFileSync('scenes/${firstSceneName}.json', 'utf-8');+ var sceneData = JSON.parse(sceneJson);++ await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule, physicsModule, ${physicsConfig}, manifest);++ var screenAspect = canvas.width / canvas.height;+ SDK.updateCameraAspectRatio(app.world, screenAspect);+ } catch (err) {+ console.error('[ESEngine] Failed to load scene:', err);+ }+ ` : '';++ return `+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}++var physicsModule = null;+${physicsInit}++(async function() {+ var canvas = wx.createCanvas();+ var info = wx.getSystemInfoSync();+ canvas.width = info.windowWidth * info.pixelRatio;+ canvas.height = info.windowHeight * info.pixelRatio;++ var module = await ESEngineModule({+ canvas: canvas,+ instantiateWasm: function(imports, successCallback) {+ WXWebAssembly.instantiate('esengine.wasm', imports).then(function(result) {+ successCallback(result.instance, result.module);+ });+ return {};+ }+ });++ var gl = canvas.getContext('webgl2') || canvas.getContext('webgl');+ if (!gl) {+ console.error('[ESEngine] Failed to create WebGL context');+ return;+ }+ var glHandle = module.GL.registerContext(gl, {+ majorVersion: gl.getParameter(gl.VERSION).indexOf('WebGL 2') === 0 ? 2 : 1,+ minorVersion: 0,+ enableExtensionsByDefault: true+ });++ var app = SDK.createWebApp(module, {+ glContextHandle: glHandle,+ getViewportSize: function() {+ return { width: canvas.width, height: canvas.height };+ }+ });++ ${userCode}++ SDK.flushPendingSystems(app);++ ${hasSpine ? 'await initSpineModule();' : ''}+ ${hasPhysics ? 'await initPhysicsModule();' : ''}++ ${sceneLoading}+ app.run();+})();+`;+}diff --git a/editor/src/commands/Command.ts b/editor/src/commands/Command.tsindex 954edbd7e..1842a7b6c 100644--- a/editor/src/commands/Command.ts+++ b/editor/src/commands/Command.ts@@ -3,6 +3,8 @@* @brief Command interface for undo/redo system*/+import type { EntityData } from '../types/SceneTypes';+// =============================================================================// Command Interface// =============================================================================@@ -12,12 +14,15 @@ export interface Command {readonly type: string;readonly timestamp: number;readonly description: string;+ readonly structural: boolean;execute(): void;undo(): void;canMerge(other: Command): boolean;merge(other: Command): Command;++ updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void;}// =============================================================================@@ -31,6 +36,7 @@ export abstract class BaseCommand implements Command {readonly timestamp: number;abstract readonly type: string;abstract readonly description: string;+ readonly structural: boolean = false;constructor() {this.id = `cmd_${++commandIdCounter}_${Date.now()}`;@@ -47,4 +53,6 @@ export abstract class BaseCommand implements Command {merge(_other: Command): Command {return this;}++ updateEntityMap(_map: Map<number, EntityData>, _isUndo: boolean): void {}}diff --git a/editor/src/commands/CommandHistory.ts b/editor/src/commands/CommandHistory.tsindex 51984f46b..47bc0c228 100644--- a/editor/src/commands/CommandHistory.ts+++ b/editor/src/commands/CommandHistory.ts@@ -71,6 +71,16 @@ export class CommandHistory {return this.index_ < this.commands_.length - 1;}+ peekUndo(): Command | null {+ if (!this.canUndo()) return null;+ return this.commands_[this.index_];+ }++ peekRedo(): Command | null {+ if (!this.canRedo()) return null;+ return this.commands_[this.index_ + 1];+ }+clear(): void {this.commands_ = [];this.index_ = -1;diff --git a/editor/src/commands/CompoundCommand.ts b/editor/src/commands/CompoundCommand.tsindex f2182a6f9..4cc1c9594 100644--- a/editor/src/commands/CompoundCommand.ts+++ b/editor/src/commands/CompoundCommand.ts@@ -3,15 +3,18 @@* @brief Compound command for batching multiple commands as one undo unit*/+import type { EntityData } from '../types/SceneTypes';import { BaseCommand, type Command } from './Command';export class CompoundCommand extends BaseCommand {readonly type = 'compound';readonly description: string;+ readonly structural: boolean;constructor(private commands_: Command[], description: string) {super();this.description = description;+ this.structural = commands_.some(c => c.structural);}execute(): void {@@ -25,4 +28,16 @@ export class CompoundCommand extends BaseCommand {this.commands_[i].undo();}}++ updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void {+ if (isUndo) {+ for (let i = this.commands_.length - 1; i >= 0; i--) {+ this.commands_[i].updateEntityMap(map, isUndo);+ }+ } else {+ for (const cmd of this.commands_) {+ cmd.updateEntityMap(map, isUndo);+ }+ }+ }}diff --git a/editor/src/commands/EntityCommands.ts b/editor/src/commands/EntityCommands.tsindex e0ca4196a..16ac042fa 100644--- a/editor/src/commands/EntityCommands.ts+++ b/editor/src/commands/EntityCommands.ts@@ -13,11 +13,13 @@ import { BaseCommand } from './Command';export class CreateEntityCommand extends BaseCommand {readonly type = 'create_entity';+ readonly structural = true;readonly description: string;private entityData_: EntityData;constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entityId_: number,private name_: string,private parent_: number | null = null@@ -31,7 +33,7 @@ export class CreateEntityCommand extends BaseCommand {this.scene_.entities.push(this.entityData_);if (this.parent_ !== null) {- const parentData = this.scene_.entities.find(e => e.id === this.parent_);+ const parentData = this.entityMap_.get(this.parent_);if (parentData && !parentData.children.includes(this.entityId_)) {parentData.children.push(this.entityId_);}@@ -45,7 +47,7 @@ export class CreateEntityCommand extends BaseCommand {}if (this.parent_ !== null) {- const parentData = this.scene_.entities.find(e => e.id === this.parent_);+ const parentData = this.entityMap_.get(this.parent_);if (parentData) {const childIdx = parentData.children.indexOf(this.entityId_);if (childIdx !== -1) {@@ -55,6 +57,14 @@ export class CreateEntityCommand extends BaseCommand {}}+ updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void {+ if (isUndo) {+ map.delete(this.entityId_);+ } else {+ map.set(this.entityId_, this.entityData_);+ }+ }+get entityId(): number {return this.entityId_;}@@ -66,27 +76,29 @@ export class CreateEntityCommand extends BaseCommand {export class DeleteEntityCommand extends BaseCommand {readonly type = 'delete_entity';+ readonly structural = true;readonly description: string;private deletedData_: EntityData | null = null;private deletedChildren_: EntityData[] = [];constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entityId_: number) {super();- const entity = scene_.entities.find(e => e.id === entityId_);+ const entity = entityMap_.get(entityId_);this.description = `Delete entity "${entity?.name ?? entityId_}"`;}execute(): void {- this.deletedData_ = this.scene_.entities.find(e => e.id === this.entityId_) ?? null;+ this.deletedData_ = this.entityMap_.get(this.entityId_) ?? null;if (!this.deletedData_) return;this.deletedChildren_ = this.collectDescendants(this.entityId_);if (this.deletedData_.parent !== null) {- const parentData = this.scene_.entities.find(e => e.id === this.deletedData_!.parent);+ const parentData = this.entityMap_.get(this.deletedData_.parent);if (parentData) {const idx = parentData.children.indexOf(this.entityId_);if (idx !== -1) {@@ -106,20 +118,36 @@ export class DeleteEntityCommand extends BaseCommand {this.scene_.entities.push(...this.deletedChildren_);if (this.deletedData_.parent !== null) {- const parentData = this.scene_.entities.find(e => e.id === this.deletedData_!.parent);+ const parentData = this.entityMap_.get(this.deletedData_.parent);if (parentData && !parentData.children.includes(this.entityId_)) {parentData.children.push(this.entityId_);}}}+ updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void {+ if (isUndo) {+ if (this.deletedData_) {+ map.set(this.entityId_, this.deletedData_);+ }+ for (const child of this.deletedChildren_) {+ map.set(child.id, child);+ }+ } else {+ map.delete(this.entityId_);+ for (const child of this.deletedChildren_) {+ map.delete(child.id);+ }+ }+ }+private collectDescendants(entityId: number): EntityData[] {const result: EntityData[] = [];- const entity = this.scene_.entities.find(e => e.id === entityId);+ const entity = this.entityMap_.get(entityId);if (!entity) return result;for (const childId of entity.children) {- const child = this.scene_.entities.find(e => e.id === childId);+ const child = this.entityMap_.get(childId);if (child) {result.push(child);result.push(...this.collectDescendants(childId));@@ -135,16 +163,18 @@ export class DeleteEntityCommand extends BaseCommand {export class ReparentCommand extends BaseCommand {readonly type = 'reparent';+ readonly structural = true;readonly description: string;private oldParent_: number | null;constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entityId_: number,private newParent_: number | null) {super();- const entity = scene_.entities.find(e => e.id === entityId_);+ const entity = entityMap_.get(entityId_);this.oldParent_ = entity?.parent ?? null;this.description = `Reparent entity "${entity?.name ?? entityId_}"`;}@@ -158,13 +188,13 @@ export class ReparentCommand extends BaseCommand {}private setParent(newParent: number | null): void {- const entity = this.scene_.entities.find(e => e.id === this.entityId_);+ const entity = this.entityMap_.get(this.entityId_);if (!entity) return;const oldParent = entity.parent;if (oldParent !== null) {- const oldParentData = this.scene_.entities.find(e => e.id === oldParent);+ const oldParentData = this.entityMap_.get(oldParent);if (oldParentData) {const idx = oldParentData.children.indexOf(this.entityId_);if (idx !== -1) {@@ -176,7 +206,7 @@ export class ReparentCommand extends BaseCommand {entity.parent = newParent;if (newParent !== null) {- const newParentData = this.scene_.entities.find(e => e.id === newParent);+ const newParentData = this.entityMap_.get(newParent);if (newParentData && !newParentData.children.includes(this.entityId_)) {newParentData.children.push(this.entityId_);}@@ -190,18 +220,20 @@ export class ReparentCommand extends BaseCommand {export class MoveEntityCommand extends BaseCommand {readonly type = 'move_entity';+ readonly structural = true;readonly description: string;private oldParent_: number | null;private oldIndex_: number;constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entityId_: number,private newParent_: number | null,private newIndex_: number) {super();- const entity = scene_.entities.find(e => e.id === entityId_);+ const entity = entityMap_.get(entityId_);this.oldParent_ = entity?.parent ?? null;this.oldIndex_ = this.computeIndex(this.oldParent_);this.description = `Move entity "${entity?.name ?? entityId_}"`;@@ -217,7 +249,7 @@ export class MoveEntityCommand extends BaseCommand {private computeIndex(parent: number | null): number {if (parent !== null) {- const parentData = this.scene_.entities.find(e => e.id === parent);+ const parentData = this.entityMap_.get(parent);return parentData?.children.indexOf(this.entityId_) ?? 0;}const roots = this.scene_.entities.filter(e => e.parent === null);@@ -225,11 +257,11 @@ export class MoveEntityCommand extends BaseCommand {}private applyMove(targetParent: number | null, targetIndex: number): void {- const entity = this.scene_.entities.find(e => e.id === this.entityId_);+ const entity = this.entityMap_.get(this.entityId_);if (!entity) return;if (entity.parent !== null) {- const parent = this.scene_.entities.find(e => e.id === entity.parent);+ const parent = this.entityMap_.get(entity.parent);if (parent) {const idx = parent.children.indexOf(this.entityId_);if (idx !== -1) parent.children.splice(idx, 1);@@ -239,7 +271,7 @@ export class MoveEntityCommand extends BaseCommand {entity.parent = targetParent;if (targetParent !== null) {- const parent = this.scene_.entities.find(e => e.id === targetParent);+ const parent = this.entityMap_.get(targetParent);if (parent) {const i = Math.min(targetIndex, parent.children.length);parent.children.splice(i, 0, this.entityId_);@@ -268,6 +300,7 @@ export class AddComponentCommand extends BaseCommand {constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entityId_: number,private componentType_: string,private componentData_: Record<string, unknown>@@ -277,7 +310,7 @@ export class AddComponentCommand extends BaseCommand {}execute(): void {- const entity = this.scene_.entities.find(e => e.id === this.entityId_);+ const entity = this.entityMap_.get(this.entityId_);if (!entity) return;if (!entity.components.find(c => c.type === this.componentType_)) {@@ -289,7 +322,7 @@ export class AddComponentCommand extends BaseCommand {}undo(): void {- const entity = this.scene_.entities.find(e => e.id === this.entityId_);+ const entity = this.entityMap_.get(this.entityId_);if (!entity) return;const idx = entity.components.findIndex(c => c.type === this.componentType_);@@ -310,6 +343,7 @@ export class RemoveComponentCommand extends BaseCommand {constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entityId_: number,private componentType_: string) {@@ -318,7 +352,7 @@ export class RemoveComponentCommand extends BaseCommand {}execute(): void {- const entity = this.scene_.entities.find(e => e.id === this.entityId_);+ const entity = this.entityMap_.get(this.entityId_);if (!entity) return;const idx = entity.components.findIndex(c => c.type === this.componentType_);@@ -331,7 +365,7 @@ export class RemoveComponentCommand extends BaseCommand {undo(): void {if (!this.removedData_) return;- const entity = this.scene_.entities.find(e => e.id === this.entityId_);+ const entity = this.entityMap_.get(this.entityId_);if (!entity) return;entity.components.push({diff --git a/editor/src/commands/PrefabCommands.ts b/editor/src/commands/PrefabCommands.tsindex d441610f5..52f018445 100644--- a/editor/src/commands/PrefabCommands.ts+++ b/editor/src/commands/PrefabCommands.ts@@ -14,11 +14,14 @@ import { instantiatePrefab, computeNextEntityId } from '../prefab/PrefabInstantiexport class InstantiatePrefabCommand extends BaseCommand {readonly type = 'instantiate_prefab';+ readonly structural = true;readonly description: string;private createdEntityIds_: number[] = [];+ private createdEntities_: EntityData[] = [];constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private prefab_: PrefabData,private prefabPath_: string,private parentEntityId_: number | null,@@ -42,12 +45,13 @@ export class InstantiatePrefabCommand extends BaseCommand {}if (this.parentEntityId_ !== null) {- const parent = this.scene_.entities.find(e => e.id === this.parentEntityId_);+ const parent = this.entityMap_.get(this.parentEntityId_);if (parent && !parent.children.includes(result.rootEntityId)) {parent.children.push(result.rootEntityId);}}+ this.createdEntities_ = result.createdEntities;this.createdEntityIds_ = result.createdEntities.map(e => e.id);}@@ -55,7 +59,7 @@ export class InstantiatePrefabCommand extends BaseCommand {const idsToRemove = new Set(this.createdEntityIds_);if (this.parentEntityId_ !== null) {- const parent = this.scene_.entities.find(e => e.id === this.parentEntityId_);+ const parent = this.entityMap_.get(this.parentEntityId_);if (parent) {parent.children = parent.children.filter(id => !idsToRemove.has(id));}@@ -64,6 +68,18 @@ export class InstantiatePrefabCommand extends BaseCommand {this.scene_.entities = this.scene_.entities.filter(e => !idsToRemove.has(e.id));}+ updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void {+ if (isUndo) {+ for (const id of this.createdEntityIds_) {+ map.delete(id);+ }+ } else {+ for (const entity of this.createdEntities_) {+ map.set(entity.id, entity);+ }+ }+ }+get rootEntityId(): number {return this.createdEntityIds_[0] ?? -1;}@@ -79,6 +95,7 @@ export class InstantiatePrefabCommand extends BaseCommand {export class UnpackPrefabCommand extends BaseCommand {readonly type = 'unpack_prefab';+ readonly structural = true;readonly description: string;private savedPrefabData_: Map<number, EntityData['prefab']> = new Map();@@ -116,6 +133,7 @@ export class UnpackPrefabCommand extends BaseCommand {export class RevertPrefabInstanceCommand extends BaseCommand {readonly type = 'revert_prefab';+ readonly structural = true;readonly description: string;private savedSnapshot_: EntityData[] = [];private savedIndices_: Map<number, number> = new Map();@@ -295,6 +313,7 @@ export class RevertPrefabInstanceCommand extends BaseCommand {export class ApplyPrefabOverridesCommand extends BaseCommand {readonly type = 'apply_prefab';+ readonly structural = true;readonly description: string;private savedPrefab_: PrefabData | null = null;private savedOtherInstances_: Map<number, EntityData>[] = [];@@ -437,10 +456,12 @@ export class ApplyPrefabOverridesCommand extends BaseCommand {export class InstantiateNestedPrefabCommand extends BaseCommand {readonly type = 'instantiate_nested_prefab';+ readonly structural = true;readonly description: string;constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private createdEntities_: EntityData[],private rootEntityId_: number,private parentEntityId_: number | null@@ -455,7 +476,7 @@ export class InstantiateNestedPrefabCommand extends BaseCommand {}if (this.parentEntityId_ !== null) {- const parent = this.scene_.entities.find(e => e.id === this.parentEntityId_);+ const parent = this.entityMap_.get(this.parentEntityId_);if (parent && !parent.children.includes(this.rootEntityId_)) {parent.children.push(this.rootEntityId_);}@@ -466,7 +487,7 @@ export class InstantiateNestedPrefabCommand extends BaseCommand {const idsToRemove = new Set(this.createdEntities_.map(e => e.id));if (this.parentEntityId_ !== null) {- const parent = this.scene_.entities.find(e => e.id === this.parentEntityId_);+ const parent = this.entityMap_.get(this.parentEntityId_);if (parent) {parent.children = parent.children.filter(id => !idsToRemove.has(id));}@@ -475,6 +496,18 @@ export class InstantiateNestedPrefabCommand extends BaseCommand {this.scene_.entities = this.scene_.entities.filter(e => !idsToRemove.has(e.id));}+ updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void {+ if (isUndo) {+ for (const entity of this.createdEntities_) {+ map.delete(entity.id);+ }+ } else {+ for (const entity of this.createdEntities_) {+ map.set(entity.id, entity);+ }+ }+ }+get rootEntityId(): number {return this.rootEntityId_;}diff --git a/editor/src/commands/PropertyCommand.ts b/editor/src/commands/PropertyCommand.tsindex 6147a1da5..4452344b9 100644--- a/editor/src/commands/PropertyCommand.ts+++ b/editor/src/commands/PropertyCommand.ts@@ -23,6 +23,7 @@ export class PropertyCommand extends BaseCommand {constructor(private scene_: SceneData,+ private entityMap_: Map<number, EntityData>,private entity_: Entity,private componentType_: string,private propertyName_: string,@@ -53,6 +54,7 @@ export class PropertyCommand extends BaseCommand {const otherProp = other as PropertyCommand;return new PropertyCommand(this.scene_,+ this.entityMap_,this.entity_,this.componentType_,this.propertyName_,@@ -61,8 +63,12 @@ export class PropertyCommand extends BaseCommand {);}+ get componentType(): string {+ return this.componentType_;+ }+private setPropertyValue(value: unknown): void {- const entityData = this.findEntityData();+ const entityData = this.entityMap_.get(this.entity_ as number);if (!entityData) return;const component = entityData.components.find(c => c.type === this.componentType_);@@ -70,8 +76,4 @@ export class PropertyCommand extends BaseCommand {component.data[this.propertyName_] = value;}}-- private findEntityData(): EntityData | undefined {- return this.scene_.entities.find(e => e.id === this.entity_);- }}diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.tsindex fb793e8ed..a9f8d0277 100644--- a/editor/src/panels/HierarchyPanel.ts+++ b/editor/src/panels/HierarchyPanel.ts@@ -8,7 +8,7 @@ import type { EntityData } from '../types/SceneTypes';import type { EditorStore } from '../store/EditorStore';import { icons } from '../utils/icons';import { getGlobalPathResolver } from '../asset';-import { getDefaultComponentData } from '../schemas/ComponentSchemas';+import { getInitialComponentData } from '../schemas/ComponentSchemas';import { showContextMenu, type ContextMenuItem } from '../ui/ContextMenu';import { getContextMenuItems, type ContextMenuContext } from '../ui/ContextMenuRegistry';import { getEditorContext, getEditorInstance } from '../context/EditorContext';@@ -126,7 +126,7 @@ export class HierarchyPanel {const addBtn = this.container_.querySelector('[data-action="add"]');addBtn?.addEventListener('click', () => {const entity = this.store_.createEntity();- this.store_.addComponent(entity, 'LocalTransform', getDefaultComponentData('LocalTransform'));+ this.store_.addComponent(entity, 'LocalTransform', getInitialComponentData('LocalTransform'));});this.searchInput_?.addEventListener('input', () => {@@ -402,20 +402,20 @@ export class HierarchyPanel {const newEntity = this.store_.createEntity(baseName, parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));this.store_.addComponent(newEntity, 'SpineAnimation', {- ...getDefaultComponentData('SpineAnimation'),+ ...getInitialComponentData('SpineAnimation'),skeletonPath,atlasPath,});} else if (asset.type === 'image') {const newEntity = this.store_.createEntity(baseName, parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));this.store_.addComponent(newEntity, 'Sprite', {- ...getDefaultComponentData('Sprite'),+ ...getInitialComponentData('Sprite'),texture: this.toRelativePath(asset.path),});@@ -697,7 +697,7 @@ export class HierarchyPanel {const createChildren: ContextMenuItem[] = [{ label: 'Empty Entity', icon: icons.plus(14), onClick: () => {const newEntity = this.store_.createEntity(undefined, entity);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));} },{ label: 'Sprite', icon: icons.image(14), onClick: () => this.createEntityWithComponent('Sprite', entity) },{ label: 'Text', icon: icons.type(14), onClick: () => this.createEntityWithComponent('Text', entity) },@@ -785,65 +785,65 @@ export class HierarchyPanel {private createEntityWithComponent(componentType: string, parent: Entity | null): void {const newEntity = this.store_.createEntity(componentType, parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));if (componentType === 'Text') {- this.store_.addComponent(newEntity, 'UIRect', getDefaultComponentData('UIRect'));+ this.store_.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));}- this.store_.addComponent(newEntity, componentType, getDefaultComponentData(componentType));+ this.store_.addComponent(newEntity, componentType, getInitialComponentData(componentType));}private addComponentToEntity(entity: Entity, componentType: string): void {- this.store_.addComponent(entity, componentType, getDefaultComponentData(componentType));+ this.store_.addComponent(entity, componentType, getInitialComponentData(componentType));}private createPhysicsEntity(colliderType: string, parent: Entity | null): void {const newEntity = this.store_.createEntity(colliderType, parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'RigidBody', getDefaultComponentData('RigidBody'));- this.store_.addComponent(newEntity, colliderType, getDefaultComponentData(colliderType));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'RigidBody', getInitialComponentData('RigidBody'));+ this.store_.addComponent(newEntity, colliderType, getInitialComponentData(colliderType));}private createButtonEntity(parent: Entity | null): void {const newEntity = this.store_.createEntity('Button', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'Sprite', getDefaultComponentData('Sprite'));- this.store_.addComponent(newEntity, 'UIRect', getDefaultComponentData('UIRect'));- this.store_.addComponent(newEntity, 'Interactable', getDefaultComponentData('Interactable'));- this.store_.addComponent(newEntity, 'Button', getDefaultComponentData('Button'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));+ this.store_.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));+ this.store_.addComponent(newEntity, 'Interactable', getInitialComponentData('Interactable'));+ this.store_.addComponent(newEntity, 'Button', getInitialComponentData('Button'));}private createTextInputEntity(parent: Entity | null): void {const newEntity = this.store_.createEntity('TextInput', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));- const tiDefaults = getDefaultComponentData('TextInput');+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ const tiDefaults = getInitialComponentData('TextInput');this.store_.addComponent(newEntity, 'Sprite', {- ...getDefaultComponentData('Sprite'),+ ...getInitialComponentData('Sprite'),color: tiDefaults.backgroundColor,size: { x: 200, y: 36 },});this.store_.addComponent(newEntity, 'UIRect', {- ...getDefaultComponentData('UIRect'),+ ...getInitialComponentData('UIRect'),size: { x: 200, y: 36 },});- this.store_.addComponent(newEntity, 'Interactable', getDefaultComponentData('Interactable'));- this.store_.addComponent(newEntity, 'TextInput', getDefaultComponentData('TextInput'));+ this.store_.addComponent(newEntity, 'Interactable', getInitialComponentData('Interactable'));+ this.store_.addComponent(newEntity, 'TextInput', getInitialComponentData('TextInput'));}private createPanelEntity(parent: Entity | null): void {const newEntity = this.store_.createEntity('Panel', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'Sprite', getDefaultComponentData('Sprite'));- this.store_.addComponent(newEntity, 'UIRect', getDefaultComponentData('UIRect'));- this.store_.addComponent(newEntity, 'UIMask', getDefaultComponentData('UIMask'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));+ this.store_.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));+ this.store_.addComponent(newEntity, 'UIMask', getInitialComponentData('UIMask'));}private createScreenSpaceRootEntity(parent: Entity | null): void {const newEntity = this.store_.createEntity('ScreenSpace Root', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));+ this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));this.store_.addComponent(newEntity, 'UIRect', {- ...getDefaultComponentData('UIRect'),+ ...getInitialComponentData('UIRect'),anchorMin: { x: 0, y: 0 },anchorMax: { x: 1, y: 1 },});diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex aa09ead18..9a843239c 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -11,7 +11,7 @@ import type { EditorBridge } from '../bridge/EditorBridge';import type { SliceBorder } from '../types/TextureMetadata';import { getPlatformAdapter } from '../platform/PlatformAdapter';import { hasSlicing, parseTextureMetadata } from '../types/TextureMetadata';-import { getDefaultComponentData } from '../schemas/ComponentSchemas';+import { getDefaultComponentData, getInitialComponentData } from '../schemas/ComponentSchemas';import { getGlobalPathResolver } from '../asset';import { isUUID, getAssetLibrary } from '../asset/AssetDatabase';import { icons } from '../utils/icons';@@ -1400,13 +1400,13 @@ export class SceneViewPanel {const baseName = asset.name.replace(/\.[^.]+$/, '');const newEntity = this.store_.createEntity(baseName);- const transformData = getDefaultComponentData('LocalTransform');+ const transformData = getInitialComponentData('LocalTransform');transformData.position = { x: worldX, y: worldY, z: 0 };this.store_.addComponent(newEntity, 'LocalTransform', transformData);const relativePath = getGlobalPathResolver().toRelativePath(asset.path);this.store_.addComponent(newEntity, 'Sprite', {- ...getDefaultComponentData('Sprite'),+ ...getInitialComponentData('Sprite'),texture: relativePath,});diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.tsindex 94d815e0a..2a8f61a7c 100644--- a/editor/src/panels/inspector/EntityInspector.ts+++ b/editor/src/panels/inspector/EntityInspector.ts@@ -10,6 +10,7 @@ import { createPropertyEditor } from '../../property/PropertyEditor';import {getComponentSchema,getDefaultComponentData,+ getInitialComponentData,isComponentRemovable,} from '../../schemas/ComponentSchemas';import { icons } from '../../utils/icons';@@ -420,7 +421,7 @@ export function renderAddComponentButton(btn.addEventListener('click', () => {const existingTypes = existingComponents.map(c => c.type);showAddComponentPopup(existingTypes, (componentName: string) => {- const defaultData = getDefaultComponentData(componentName);+ const defaultData = getInitialComponentData(componentName);store.addComponent(entity, componentName, defaultData);});});diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.tsindex 894487a8d..3b6d6e9fe 100644--- a/editor/src/preview/PreviewService.ts+++ b/editor/src/preview/PreviewService.ts@@ -77,6 +77,7 @@ export class PreviewService {const fs = this.getNativeFS();if (!fs) return;await this.preparePreviewFiles(fs, scene, compiledScript, spineVersion, enablePhysics, physicsConfig);+ await this.notifyReload();}private async preparePreviewFiles(@@ -126,29 +127,26 @@ export class PreviewService {for (const entity of scene.entities) {for (const component of entity.components) {- if (component.type === 'Sprite') {- const texturePath = component.data.texture as string | undefined;- if (texturePath && !processedPaths.has(texturePath)) {- processedPaths.add(texturePath);-- // Resolve texture path relative to project- const fullPath = `${this.projectDir_}/${texturePath}`;- const metaPath = getMetaFilePath(fullPath);-- try {- if (await fs.exists(metaPath)) {- const content = await fs.readFile(metaPath);- if (content) {- const metadata = parseTextureMetadata(content);- if (metadata) {- result[texturePath] = metadata;- }- }+ if (component.type !== 'Sprite' && component.type !== 'UIMask') continue;+ const texturePath = component.data.texture as string | undefined;+ if (!texturePath || processedPaths.has(texturePath)) continue;+ processedPaths.add(texturePath);++ const fullPath = `${this.projectDir_}/${texturePath}`;+ const metaPath = getMetaFilePath(fullPath);++ try {+ if (await fs.exists(metaPath)) {+ const content = await fs.readFile(metaPath);+ if (content) {+ const metadata = parseTextureMetadata(content);+ if (metadata) {+ result[texturePath] = metadata;}- } catch (err) {- console.warn(`Failed to load texture metadata for ${texturePath}:`, err);}}+ } catch (err) {+ console.warn(`Failed to load texture metadata for ${texturePath}:`, err);}}}@@ -169,4 +167,11 @@ export class PreviewService {private getTauriInvoke(): TauriInvoke | null {return getEditorContext().invoke ?? null;}++ private async notifyReload(): Promise<void> {+ const invoke = this.getTauriInvoke();+ if (invoke) {+ await invoke('notify_preview_reload');+ }+ }}diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex 67448fe98..686f475fd 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -481,120 +481,34 @@ export function registerSpineSchema(): void {// Default Component Data// =============================================================================-const editorOnlyDefaults: Record<string, Record<string, unknown>> = {- RigidBody: {- bodyType: 2,- gravityScale: 1.0,- linearDamping: 0.0,- angularDamping: 0.0,- fixedRotation: false,- bullet: false,- enabled: true,- },- BoxCollider: {- halfExtents: { x: 0.5, y: 0.5 },- offset: { x: 0, y: 0 },- density: 1.0,- friction: 0.3,- restitution: 0.0,- isSensor: false,- },- CircleCollider: {- radius: 0.5,- offset: { x: 0, y: 0 },- density: 1.0,- friction: 0.3,- restitution: 0.0,- isSensor: false,- },- CapsuleCollider: {- radius: 0.25,- halfHeight: 0.5,- offset: { x: 0, y: 0 },- density: 1.0,- friction: 0.3,- restitution: 0.0,- isSensor: false,- },+export function getDefaultComponentData(typeName: string): Record<string, unknown> {+ return getComponentDefaults(typeName) ?? {};+}++const editorInitialOverrides: Record<string, Record<string, unknown>> = {Camera: {- isActive: true,projectionType: 1,- fov: 60,orthoSize: 540,- nearPlane: 0.1,- farPlane: 1000,- priority: 0,- showFrustum: true,- viewportX: 0,- viewportY: 0,- viewportW: 1,- viewportH: 1,- clearFlags: 3,},BitmapText: {text: 'BitmapText',font: '',- color: { r: 1, g: 1, b: 1, a: 1 },- fontSize: 1.0,- align: 0,- spacing: 0,- layer: 0,- },- UIRect: {- anchorMin: { x: 0.5, y: 0.5 },- anchorMax: { x: 0.5, y: 0.5 },- offsetMin: { x: 0, y: 0 },- offsetMax: { x: 0, y: 0 },- size: { x: 100, y: 100 },- pivot: { x: 0.5, y: 0.5 },- },- UIMask: {- enabled: true,- },- Interactable: {- enabled: true,- },- Button: {- state: 0,- transition: null,},Text: {content: 'Text',- fontFamily: 'Arial',- fontSize: 24,- color: { r: 1, g: 1, b: 1, a: 1 },align: 1,verticalAlign: 1,- wordWrap: true,- overflow: 0,- lineHeight: 1.2,},TextInput: {- value: '',placeholder: 'Enter text...',- placeholderColor: { r: 0.6, g: 0.6, b: 0.6, a: 1 },- fontFamily: 'Arial',- fontSize: 16,- color: { r: 1, g: 1, b: 1, a: 1 },- backgroundColor: { r: 0.15, g: 0.15, b: 0.15, a: 1 },- padding: 6,- maxLength: 0,- multiline: false,- password: false,- readOnly: false,},};-export function getDefaultComponentData(typeName: string): Record<string, unknown> {- const editorDefaults = editorOnlyDefaults[typeName];- if (editorDefaults) {- return { ...editorDefaults };+export function getInitialComponentData(typeName: string): Record<string, unknown> {+ const defaults = getDefaultComponentData(typeName);+ const overrides = editorInitialOverrides[typeName];+ if (overrides) {+ return { ...defaults, ...overrides };}-- const sdkDefaults = getComponentDefaults(typeName);- if (sdkDefaults) {- return sdkDefaults;- }-- return {};+ return defaults;}diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex 37231d9ac..87ddb6fe5 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -367,6 +367,7 @@ export class EditorStore {const cmd = new CreateEntityCommand(this.state_.scene,+ this.entityMap_,id,entityName,parent@@ -393,7 +394,7 @@ export class EditorStore {deleteEntity(entity: Entity): void {const descendants = this.collectDescendantIds(entity as number);- const cmd = new DeleteEntityCommand(this.state_.scene, entity);+ const cmd = new DeleteEntityCommand(this.state_.scene, this.entityMap_, entity);this.executeCommand(cmd);if (this.state_.selectedEntity === entity) {@@ -407,7 +408,7 @@ export class EditorStore {}reparentEntity(entity: Entity, newParent: Entity | null): void {- const cmd = new ReparentCommand(this.state_.scene, entity, newParent);+ const cmd = new ReparentCommand(this.state_.scene, this.entityMap_, entity, newParent);this.executeCommand(cmd);this.notifyHierarchyChange({entity: entity as number,@@ -416,7 +417,7 @@ export class EditorStore {}moveEntity(entity: Entity, newParent: Entity | null, index: number): void {- const cmd = new MoveEntityCommand(this.state_.scene, entity, newParent, index);+ const cmd = new MoveEntityCommand(this.state_.scene, this.entityMap_, entity, newParent, index);this.executeCommand(cmd);this.notifyHierarchyChange({entity: entity as number,@@ -441,7 +442,7 @@ export class EditorStore {// =========================================================================addComponent(entity: Entity, type: string, data: Record<string, unknown>): void {- const cmd = new AddComponentCommand(this.state_.scene, entity, type, data);+ const cmd = new AddComponentCommand(this.state_.scene, this.entityMap_, entity, type, data);this.executeCommand(cmd);if (this.isPrefabInstance(entity as number)) {@@ -458,7 +459,7 @@ export class EditorStore {recordComponentRemovedOverride(this.state_.scene, entity as number, type);}- const cmd = new RemoveComponentCommand(this.state_.scene, entity, type);+ const cmd = new RemoveComponentCommand(this.state_.scene, this.entityMap_, entity, type);this.executeCommand(cmd);this.notifyComponentChange({ entity: entity as number, componentType: type, action: 'removed' });}@@ -472,6 +473,7 @@ export class EditorStore {): void {const cmd = new PropertyCommand(this.state_.scene,+ this.entityMap_,entity,componentType,propertyName,@@ -506,6 +508,7 @@ export class EditorStore {): void {const commands = changes.map(c => new PropertyCommand(this.state_.scene,+ this.entityMap_,entity,componentType,c.property,@@ -598,6 +601,7 @@ export class EditorStore {const cmd = new InstantiatePrefabCommand(this.state_.scene,+ this.entityMap_,prefab,prefabPath,parentEntity as number | null,@@ -634,6 +638,7 @@ export class EditorStore {const cmd = new InstantiateNestedPrefabCommand(this.state_.scene,+ this.entityMap_,result.createdEntities,result.rootEntityId,parentEntity as number | null@@ -820,24 +825,20 @@ export class EditorStore {// =========================================================================undo(): void {+ const cmd = this.history_.peekUndo();+ if (!cmd) return;if (this.history_.undo()) {this.state_.isDirty = true;- this.rebuildEntityMap();- this.syncDerivedProperties();- this.worldTransforms_.setScene(this.state_.scene);- this.notifySceneSync();- this.notify();+ this.applyCommandSideEffects(cmd, true);}}redo(): void {+ const cmd = this.history_.peekRedo();+ if (!cmd) return;if (this.history_.redo()) {this.state_.isDirty = true;- this.rebuildEntityMap();- this.syncDerivedProperties();- this.worldTransforms_.setScene(this.state_.scene);- this.notifySceneSync();- this.notify();+ this.applyCommandSideEffects(cmd, false);}}@@ -886,8 +887,20 @@ export class EditorStore {private executeCommand(cmd: import('../commands').Command): void {this.history_.execute(cmd);this.state_.isDirty = true;- this.rebuildEntityMap();- this.worldTransforms_.setScene(this.state_.scene);+ this.applyCommandSideEffects(cmd, false);+ }++ private applyCommandSideEffects(cmd: import('../commands').Command, isUndo: boolean): void {+ cmd.updateEntityMap(this.entityMap_, isUndo);++ if (cmd.structural) {+ this.rebuildEntityMap();+ this.worldTransforms_.setScene(this.state_.scene);+ } else {+ this.worldTransforms_.invalidateAll();+ }++ this.syncDerivedProperties();this.notifySceneSync();this.notify();}diff --git a/editor/src/types/BuildTypes.ts b/editor/src/types/BuildTypes.tsindex d76a72e75..3dcad23f4 100644--- a/editor/src/types/BuildTypes.ts+++ b/editor/src/types/BuildTypes.ts@@ -8,8 +8,6 @@// =============================================================================export type BuildPlatform = 'playable' | 'wechat';-export type BuildStatus = 'success' | 'failed' | 'cancelled';-export type BuildPhase = 'preparing' | 'compiling' | 'processing_assets' | 'assembling' | 'writing' | 'completed' | 'failed';export interface PlatformInfo {id: BuildPlatform;@@ -71,150 +69,6 @@ export interface BuildSettings {configs: BuildConfig[];}-// =============================================================================-// Build Settings File (Project-level)-// =============================================================================--export interface BuildSettingsFile {- version: '1.0';- activePlatform: BuildPlatform;- activeConfigId: string;- configs: BuildConfig[];-}--// =============================================================================-// Build Cache Types-// =============================================================================--export interface FileHash {- path: string;- hash: string;- lastModified: number;- size: number;-}--export interface BuildCacheData {- version: string;- configId: string;- timestamp: number;- files: Record<string, FileHash>;- compiledScripts?: string;- compiledScriptsHash?: string;-}--export interface FileChangeResult {- added: string[];- modified: string[];- removed: string[];- unchanged: string[];-}--// =============================================================================-// Build Progress Types-// =============================================================================--export type LogLevel = 'info' | 'warn' | 'error' | 'debug';--export interface BuildLogEntry {- timestamp: number;- level: LogLevel;- message: string;- phase?: BuildPhase;-}--export interface BuildProgress {- phase: BuildPhase;- overallProgress: number;- currentTask: string;- currentTaskProgress: number;- logs: BuildLogEntry[];- startTime: number;- estimatedTimeRemaining?: number;-}--// =============================================================================-// Build History Types-// =============================================================================--export interface BuildHistoryEntry {- id: string;- configId: string;- configName: string;- platform: string;- timestamp: number;- duration: number;- status: BuildStatus;- outputPath?: string;- outputSize?: number;- error?: string;-}--// =============================================================================-// Build Pipeline Types-// =============================================================================--export interface BuildTask {- id: string;- name: string;- dependencies: string[];- execute: () => Promise<void>;- weight: number;-}--export interface TaskResult {- id: string;- success: boolean;- error?: string;- duration: number;-}--export interface PipelineResult {- success: boolean;- results: TaskResult[];- totalDuration: number;-}--// =============================================================================-// Batch Build Types-// =============================================================================--export interface BatchBuildResult {- success: boolean;- results: ConfigBuildResult[];- totalDuration: number;- successCount: number;- failureCount: number;-}--export interface ConfigBuildResult {- configId: string;- configName: string;- result: BuildResult;- duration: number;-}--export interface BuildResult {- success: boolean;- outputPath?: string;- outputSize?: number;- error?: string;-}--// =============================================================================-// Template Types-// =============================================================================--export interface BuildTemplate {- id: string;- name: string;- description: string;- platform: BuildPlatform;- icon: string;- defines: string[];- playableSettings?: Partial<PlayableSettings>;- wechatSettings?: Partial<WeChatSettings>;-}-// =============================================================================// Default Values// =============================================================================diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex f2856400f..b19866755 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -148,7 +148,13 @@ export class AssetServer {for (const [key, value] of Object.entries(assets)) {this.embedded_.set(key, value);}- this.embeddedOnly_ = typeof location !== 'undefined' && location.protocol === 'file:';+ if (!this.embeddedOnly_) {+ this.embeddedOnly_ = typeof location !== 'undefined' && location.protocol === 'file:';+ }+ }++ setEmbeddedOnly(value: boolean): void {+ this.embeddedOnly_ = value;}// =========================================================================diff --git a/sdk/src/asset/MaterialLoader.ts b/sdk/src/asset/MaterialLoader.tsindex d9813b444..b062b616c 100644--- a/sdk/src/asset/MaterialLoader.ts+++ b/sdk/src/asset/MaterialLoader.ts@@ -6,6 +6,7 @@import type { MaterialAssetData, MaterialHandle, ShaderHandle } from '../material';import { Material } from '../material';import { platformReadTextFile, platformFileExists } from '../platform';+import { AsyncCache } from './AsyncCache';// =============================================================================// Types@@ -27,8 +28,7 @@ export interface ShaderLoader {// =============================================================================export class MaterialLoader {- private cache_ = new Map<string, LoadedMaterial>();- private pending_ = new Map<string, Promise<LoadedMaterial>>();+ private cache_ = new AsyncCache<LoadedMaterial>();private shaderLoader_: ShaderLoader;private basePath_: string;@@ -38,26 +38,7 @@ export class MaterialLoader {}async load(path: string): Promise<LoadedMaterial> {- const cached = this.cache_.get(path);- if (cached) {- return cached;- }-- const pending = this.pending_.get(path);- if (pending) {- return pending;- }-- const promise = this.loadInternal(path);- this.pending_.set(path, promise);-- try {- const result = await promise;- this.cache_.set(path, result);- return result;- } finally {- this.pending_.delete(path);- }+ return this.cache_.getOrLoad(path, () => this.loadInternal(path), 0);}get(path: string): LoadedMaterial | undefined {diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex 2ad0a534b..f9d703065 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -253,6 +253,7 @@ export {loadComponent,updateCameraAspectRatio,findEntityByName,+ registerComponentAssetFields,type SceneData,type SceneEntityData,type SceneComponentData,diff --git a/sdk/src/preview/WebAssetProvider.ts b/sdk/src/preview/WebAssetProvider.tsindex 45774cff6..12a8c0518 100644--- a/sdk/src/preview/WebAssetProvider.ts+++ b/sdk/src/preview/WebAssetProvider.ts@@ -52,7 +52,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {fetch(this.resolveUrl(ref)).then(r => r.text()).then(text => { this.textCache_.set(ref, text); })- .catch(() => {})+ .catch(err => { console.warn(`[WebAssetProvider] Failed to prefetch text "${ref}":`, err); }));}@@ -61,7 +61,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {fetch(this.resolveUrl(ref)).then(r => r.arrayBuffer()).then(buf => { this.binaryCache_.set(ref, new Uint8Array(buf)); })- .catch(() => {})+ .catch(err => { console.warn(`[WebAssetProvider] Failed to prefetch binary "${ref}":`, err); }));}@@ -83,7 +83,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {fetch(this.resolveUrl(fntRef)).then(r => r.text()).then(t => { this.textCache_.set(fntRef, t); })- .catch(() => {})+ .catch(err => { console.warn(`[WebAssetProvider] Failed to prefetch font "${fntRef}":`, err); }));}}diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex b10121d84..9de014900 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -51,6 +51,54 @@ export interface SceneLoadOptions {assetBaseUrl?: string;}+// =============================================================================+// Component Asset Field Registry+// =============================================================================++type AssetFieldType = 'texture' | 'material' | 'font';++interface AssetFieldDescriptor {+ field: string;+ type: AssetFieldType;+}++interface SpineFieldDescriptor {+ skeletonField: string;+ atlasField: string;+}++interface ComponentAssetFields {+ fields?: AssetFieldDescriptor[];+ spine?: SpineFieldDescriptor;+}++const COMPONENT_ASSET_FIELDS = new Map<string, ComponentAssetFields>([+ ['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' },+ ],+ }],+]);++export function registerComponentAssetFields(+ componentType: string,+ config: ComponentAssetFields+): void {+ COMPONENT_ASSET_FIELDS.set(componentType, config);+}+// =============================================================================// Scene Loader// =============================================================================@@ -91,8 +139,13 @@ export async function loadSceneWithAssets(): Promise<Map<number, Entity>> {const entityMap = new Map<number, Entity>();const assetServer = options?.assetServer;+ const baseUrl = options?.assetBaseUrl;const texturePathToUrl = new Map<string, string>();+ if (assetServer) {+ await preloadSceneAssets(sceneData, assetServer, baseUrl, texturePathToUrl);+ }+for (const entityData of sceneData.entities) {const entity = world.spawn();entityMap.set(entityData.id, entity);@@ -101,83 +154,6 @@ export async function loadSceneWithAssets(if (entityData.visible === false) continue;for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data as Record<string, unknown>;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- } catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(- data.material,- options?.assetBaseUrl- );- data.material = loaded.handle;- } catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }-- if (compData.type === 'BitmapText' && assetServer) {- const data = compData.data as Record<string, unknown>;- if (typeof data.font === 'string' && data.font) {- try {- const handle = await assetServer.loadBitmapFont(- data.font,- options?.assetBaseUrl- );- data.font = handle;- } catch (err) {- console.warn(`Failed to load bitmap font: ${data.font}`, err);- data.font = 0;- }- }- }-- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data as Record<string, unknown>;- const skeletonPath = data.skeletonPath as string;- const atlasPath = data.atlasPath as string;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(- skeletonPath,- atlasPath,- options?.assetBaseUrl- );- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(- data.material,- options?.assetBaseUrl- );- data.material = loaded.handle;- } catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }-loadComponent(world, entity, compData);}}@@ -204,6 +180,140 @@ export async function loadSceneWithAssets(return entityMap;}+async function preloadSceneAssets(+ sceneData: SceneData,+ assetServer: AssetServer,+ baseUrl: string | undefined,+ texturePathToUrl: Map<string, string>,+): Promise<void> {+ const textures = new Set<string>();+ const materials = new Set<string>();+ const fonts = new Set<string>();+ const spines: { skeleton: string; atlas: string }[] = [];+ const spineKeys = new Set<string>();++ for (const entityData of sceneData.entities) {+ if (entityData.visible === false) continue;++ for (const compData of entityData.components) {+ const config = COMPONENT_ASSET_FIELDS.get(compData.type);+ if (!config) continue;++ const data = compData.data as Record<string, unknown>;++ if (config.spine) {+ const skelPath = data[config.spine.skeletonField] as string;+ const atlasPath = data[config.spine.atlasField] as string;+ if (skelPath && atlasPath) {+ const key = `${skelPath}:${atlasPath}`;+ if (!spineKeys.has(key)) {+ spineKeys.add(key);+ spines.push({ skeleton: skelPath, atlas: atlasPath });+ }+ }+ }++ if (config.fields) {+ for (const desc of config.fields) {+ const value = data[desc.field];+ if (typeof value !== 'string' || !value) continue;++ switch (desc.type) {+ case 'texture': textures.add(value); break;+ case 'material': materials.add(value); break;+ case 'font': fonts.add(value); break;+ }+ }+ }+ }+ }++ const textureHandles = new Map<string, number>();+ const materialHandles = new Map<string, number>();+ const fontHandles = new Map<string, number>();++ const promises: Promise<void>[] = [];++ for (const texturePath of textures) {+ promises.push((async () => {+ try {+ const isDataUrl = texturePath.startsWith('data:');+ const url = isDataUrl+ ? texturePath+ : baseUrl ? `${baseUrl}/${texturePath}` : `/${texturePath}`;+ const info = await assetServer.loadTexture(url);+ textureHandles.set(texturePath, info.handle);+ texturePathToUrl.set(texturePath, url);+ } catch (err) {+ console.warn(`Failed to load texture: ${texturePath}`, err);+ textureHandles.set(texturePath, 0);+ }+ })());+ }++ for (const materialPath of materials) {+ promises.push((async () => {+ try {+ const loaded = await assetServer.loadMaterial(materialPath, baseUrl);+ materialHandles.set(materialPath, loaded.handle);+ } catch (err) {+ console.warn(`Failed to load material: ${materialPath}`, err);+ materialHandles.set(materialPath, 0);+ }+ })());+ }++ for (const fontPath of fonts) {+ promises.push((async () => {+ try {+ const handle = await assetServer.loadBitmapFont(fontPath, baseUrl);+ fontHandles.set(fontPath, handle);+ } catch (err) {+ console.warn(`Failed to load bitmap font: ${fontPath}`, err);+ fontHandles.set(fontPath, 0);+ }+ })());+ }++ for (const spine of spines) {+ promises.push((async () => {+ const result = await assetServer.loadSpine(spine.skeleton, spine.atlas, baseUrl);+ if (!result.success) {+ console.warn(`Failed to load Spine: ${result.error}`);+ }+ })());+ }++ await Promise.all(promises);++ for (const entityData of sceneData.entities) {+ if (entityData.visible === false) continue;++ for (const compData of entityData.components) {+ const config = COMPONENT_ASSET_FIELDS.get(compData.type);+ if (!config?.fields) continue;++ const data = compData.data as Record<string, unknown>;+ for (const desc of config.fields) {+ const value = data[desc.field];+ if (typeof value !== 'string' || !value) continue;++ switch (desc.type) {+ case 'texture':+ data[desc.field] = textureHandles.get(value) ?? 0;+ break;+ case 'material':+ data[desc.field] = materialHandles.get(value) ?? 0;+ break;+ case 'font':+ data[desc.field] = fontHandles.get(value) ?? 0;+ break;+ }+ }+ }+ }+}+export function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void {if (compData.type === 'UIRect') {const rectData = compData.data as Record<string, unknown>;