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
perf: replace embind with extern C and switch spine to spine-c runtime
esengine075f3ca60267
diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.jsonindex f3a44a92f..d7db83193 100644--- a/.vscode/c_cpp_properties.json+++ b/.vscode/c_cpp_properties.json@@ -9,7 +9,7 @@"${workspaceFolder}/third_party/glfw/include","${workspaceFolder}/third_party/glad/include","${workspaceFolder}/third_party/stb",- "${workspaceFolder}/third_party/spine-runtimes/spine-cpp/spine-cpp/include",+ "${workspaceFolder}/third_party/spine-runtimes/spine-c/spine-c/include","${workspaceFolder}/third_party/nlohmann","${workspaceFolder}/third_party/box2d/include","${workspaceFolder}/build/quickjs_headers"@@ -33,7 +33,7 @@"${workspaceFolder}/third_party/glfw/include","${workspaceFolder}/third_party/glad/include","${workspaceFolder}/third_party/stb",- "${workspaceFolder}/third_party/spine-runtimes/spine-cpp/spine-cpp/include",+ "${workspaceFolder}/third_party/spine-runtimes/spine-c/spine-c/include","${workspaceFolder}/third_party/nlohmann","${workspaceFolder}/third_party/box2d/include","${workspaceFolder}/build/quickjs_headers"@@ -56,7 +56,7 @@"${workspaceFolder}/include","${workspaceFolder}/third_party/glm","${workspaceFolder}/third_party/stb",- "${workspaceFolder}/third_party/spine-runtimes/spine-cpp/spine-cpp/include",+ "${workspaceFolder}/third_party/spine-runtimes/spine-c/spine-c/include","${workspaceFolder}/third_party/nlohmann","${workspaceFolder}/third_party/box2d/include"],diff --git a/CMakeLists.txt b/CMakeLists.txtindex a17e3230a..b646e1bfa 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -11,6 +11,8 @@ option(ES_BUILD_TESTS "Build tests" ON)option(ES_BUILD_SINGLE_FILE "Build single-file SDK (WASM inlined)" OFF)option(ES_ENABLE_SPINE "Enable Spine animation support" ON)option(ES_ENABLE_BOX2D "Enable Box2D physics support" OFF)+option(ES_BUILD_MAIN_MODULE "Build as MAIN_MODULE for dynamic linking" OFF)+option(ES_BUILD_SIDE_MODULE "Build side modules for dynamic linking" OFF)list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")include(ESEngineConfig)@@ -330,19 +332,18 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a})endif()- # Spine standalone WASM module+ # Spine standalone WASM module (spine-c)if(ES_ENABLE_SPINE)file(GLOB_RECURSE SPINE_MODULE_SPINE_SOURCES- "${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes/spine-cpp/spine-cpp/src/spine/*.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes/spine-c/spine-c/src/spine/*.c")add_executable(spine_modulesrc/esengine/bindings/SpineModuleEntry.cpp${SPINE_MODULE_SPINE_SOURCES})target_include_directories(spine_module PRIVATE- ${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes/spine-cpp/spine-cpp/include+ ${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes/spine-c/spine-c/include)- target_compile_definitions(spine_module PRIVATE SPINE_SHORT_NAMES)es_apply_spine_module_settings(spine_module)set_target_properties(spine_module PROPERTIES@@ -351,19 +352,19 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a})endif()- # Spine 3.8 standalone module+ # Spine 3.8 standalone module (spine-c)if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes-3.8")file(GLOB_RECURSE SPINE38_MODULE_SOURCES- "${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes-3.8/spine-cpp/spine-cpp/src/spine/*.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes-3.8/spine-c/spine-c/src/spine/*.c")add_executable(spine_module_38src/esengine/bindings/SpineModuleEntry.cpp${SPINE38_MODULE_SOURCES})target_include_directories(spine_module_38 PRIVATE- ${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes-3.8/spine-cpp/spine-cpp/include+ ${CMAKE_CURRENT_SOURCE_DIR}/third_party/spine-runtimes-3.8/spine-c/spine-c/include)- target_compile_definitions(spine_module_38 PRIVATE SPINE_SHORT_NAMES ES_SPINE_38)+ target_compile_definitions(spine_module_38 PRIVATE ES_SPINE_38)es_apply_spine_module_settings(spine_module_38)set_target_properties(spine_module_38 PROPERTIESOUTPUT_NAME "spine38"@@ -387,6 +388,43 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sdk")endif()++ # Main module SDK (MAIN_MODULE=2, supports loading side modules)+ if(ES_BUILD_MAIN_MODULE)+ add_executable(esengine_sdk_main src/esengine/bindings/WebSDKEntry.cpp)+ target_link_libraries(esengine_sdk_main PRIVATE -Wl,--whole-archive esengine -Wl,--no-whole-archive)+ es_apply_main_module_settings(esengine_sdk_main)+ set_target_properties(esengine_sdk_main PROPERTIES+ OUTPUT_NAME "esengine"+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sdk"+ )++ if(ES_BUILD_WXGAME)+ add_executable(esengine_wxgame_main src/esengine/bindings/WebSDKEntry.cpp)+ target_link_libraries(esengine_wxgame_main PRIVATE -Wl,--whole-archive esengine -Wl,--no-whole-archive)+ es_apply_wxgame_main_module_settings(esengine_wxgame_main)+ set_target_properties(esengine_wxgame_main PROPERTIES+ OUTPUT_NAME "esengine.wxgame"+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sdk"+ )+ endif()+ endif()++ # Physics side module (SIDE_MODULE=2, pure .wasm, no JS glue)+ if(ES_ENABLE_BOX2D AND ES_BUILD_SIDE_MODULE)+ add_executable(physics_side_module+ src/esengine/bindings/PhysicsModuleEntry.cpp+ )+ target_link_libraries(physics_side_module PRIVATE box2d)+ target_include_directories(physics_side_module PRIVATE+ ${CMAKE_CURRENT_SOURCE_DIR}/third_party/box2d/include+ )+ es_apply_physics_side_module_settings(physics_side_module)+ set_target_properties(physics_side_module PROPERTIES+ OUTPUT_NAME "physics"+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sdk"+ )+ endif()endif()if(ES_BUILD_TESTS)diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex 209c23ca2..473006a40 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -48,6 +48,32 @@ export default {'sdk/physics.wasm': 'wasm/web/physics.wasm',},},+ 'web-main': {+ buildDir: 'build-web-main',+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_BUILD_MAIN_MODULE=ON'],+ targets: ['esengine_sdk_main'],+ outputs: {+ 'sdk/esengine.js': 'wasm/web/esengine.js',+ 'sdk/esengine.wasm': 'wasm/web/esengine.wasm',+ },+ },+ 'wechat-main': {+ buildDir: 'build-wxgame-main',+ cmakeFlags: ['-DES_BUILD_WXGAME=ON', '-DES_BUILD_TESTS=OFF', '-DES_BUILD_MAIN_MODULE=ON'],+ targets: ['esengine_wxgame_main'],+ outputs: {+ 'sdk/esengine.wxgame.js': 'wasm/wechat/esengine.wxgame.js',+ 'sdk/esengine.wxgame.wasm': 'wasm/wechat/esengine.wxgame.wasm',+ },+ },+ 'physics-side': {+ buildDir: 'build-web-main',+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_BOX2D=ON', '-DES_BUILD_SIDE_MODULE=ON'],+ targets: ['physics_side_module'],+ outputs: {+ 'sdk/physics.wasm': 'wasm/web/physics.wasm',+ },+ },spine: {buildDir: 'build-web',cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF'],diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 7ca3397a9..f4859dbe8 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -20,7 +20,7 @@ programprogram.command('build').description('Build ESEngine')- .option('-t, --target <target>', 'Build target (web, wechat, playable, spine, spine38, physics, sdk, all)', 'web')+ .option('-t, --target <target>', 'Build target (web, wechat, playable, spine, spine38, physics, web-main, wechat-main, physics-side, sdk, all)', 'web').option('-d, --debug', 'Debug build', false).option('-r, --release', 'Release build (default)', true).option('-c, --clean', 'Clean before build', false)diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 5e0a39f5b..13b6c7957 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -40,35 +40,56 @@ set(ES_EMSCRIPTEN_LINK_FLAGS# Modular Build (Dynamic Linking) Configuration# =============================================================================-# Main module link flags (for dynamic linking)+# Main module link flags (MAIN_MODULE=2, supports loading side modules)set(ES_EMSCRIPTEN_MAIN_MODULE_FLAGS- -sMAIN_MODULE=2 # Main module with minimal stdlib exports+ --bind+ -sMAIN_MODULE=2-sWASM=1-sUSE_WEBGL2=1-sFULL_ES3=1-sALLOW_MEMORY_GROWTH=1+ -sALLOW_TABLE_GROWTH=1-sNO_EXIT_RUNTIME=1- -sASSERTIONS=1+ -sASSERTIONS=0-sEXPORT_ES6=1-sMODULARIZE=1- "-sEXPORT_NAME='ESEngineCore'"- "-sEXPORTED_FUNCTIONS=['_malloc','_free','_es_app_init','_dlopen','_dlsym','_dlclose']"- "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','loadDynamicLibrary']"- # Embed minimal assets for core- "--embed-file=${CMAKE_SOURCE_DIR}/assets/shaders@/assets/shaders"+ -sFORCE_FILESYSTEM=1+ "-sEXPORT_NAME='ESEngineModule'"+ "-sEXPORTED_FUNCTIONS=['_malloc','_free']"+ "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','FS','addFunction','loadDynamicLibrary']"+ -O3+ -flto)-# Side module compile flags (position independent code)-set(ES_EMSCRIPTEN_SIDE_MODULE_COMPILE_FLAGS- -fPIC- -sRELOCATABLE=1+# WeChat MAIN_MODULE variant+set(ES_EMSCRIPTEN_WXGAME_MAIN_MODULE_FLAGS+ --bind+ -sMAIN_MODULE=2+ -sWASM=1+ -sUSE_WEBGL2=1+ -sFULL_ES3=1+ -sALLOW_MEMORY_GROWTH=1+ -sALLOW_TABLE_GROWTH=1+ -sNO_EXIT_RUNTIME=1+ -sENVIRONMENT=web,node+ -sEXPORT_ES6=0+ -sMODULARIZE=1+ -sFORCE_FILESYSTEM=1+ -sDYNAMIC_EXECUTION=0+ "-sEXPORT_NAME='ESEngineModule'"+ "-sEXPORTED_FUNCTIONS=['_malloc','_free']"+ "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','GL','FS','loadDynamicLibrary']"+ -O3+ --closure=0)-# Side module link flags-set(ES_EMSCRIPTEN_SIDE_MODULE_FLAGS- -sSIDE_MODULE=2 # Side module (dynamic library)+# Physics side module flags (SIDE_MODULE=2, pure .wasm, no JS glue)+set(ES_EMSCRIPTEN_PHYSICS_SIDE_MODULE_FLAGS+ -sSIDE_MODULE=2-sWASM=1-sRELOCATABLE=1+ -O3+ -flto)# Debug-specific flags@@ -126,36 +147,41 @@ function(es_apply_emscripten_settings TARGET_NAME)endif()endfunction()-# Helper function to apply MAIN_MODULE settings (modular build)+# Helper function to apply MAIN_MODULE settingsfunction(es_apply_main_module_settings TARGET_NAME)- if(ES_BUILD_WEB AND ES_BUILD_MODULAR)- target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS})+ target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS} -flto)- string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_MAIN_MODULE_FLAGS}")- set_target_properties(${TARGET_NAME} PROPERTIES- SUFFIX ".js"- LINK_FLAGS "${LINK_FLAGS_STR}"- )- message(STATUS "Configured ${TARGET_NAME} as MAIN_MODULE")- endif()+ string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_MAIN_MODULE_FLAGS}")+ set_target_properties(${TARGET_NAME} PROPERTIES+ SUFFIX ".js"+ LINK_FLAGS "${LINK_FLAGS_STR}"+ )+ message(STATUS "Configured ${TARGET_NAME} as MAIN_MODULE")endfunction()-# Helper function to apply SIDE_MODULE settings (modular build)-function(es_apply_side_module_settings TARGET_NAME)- if(ES_BUILD_WEB AND ES_BUILD_MODULAR)- target_compile_options(${TARGET_NAME} PRIVATE- ${ES_EMSCRIPTEN_COMPILE_FLAGS}- ${ES_EMSCRIPTEN_SIDE_MODULE_COMPILE_FLAGS}- )+# Helper function to apply WeChat MAIN_MODULE settings+function(es_apply_wxgame_main_module_settings TARGET_NAME)+ target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS})- string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_SIDE_MODULE_FLAGS}")- set_target_properties(${TARGET_NAME} PROPERTIES- PREFIX ""- SUFFIX ".wasm"- LINK_FLAGS "${LINK_FLAGS_STR}"- )- message(STATUS "Configured ${TARGET_NAME} as SIDE_MODULE")- endif()+ string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_WXGAME_MAIN_MODULE_FLAGS}")+ set_target_properties(${TARGET_NAME} PROPERTIES+ SUFFIX ".js"+ LINK_FLAGS "${LINK_FLAGS_STR}"+ )+ message(STATUS "Configured ${TARGET_NAME} as WXGAME MAIN_MODULE")+endfunction()++# Helper function to apply physics SIDE_MODULE settings+function(es_apply_physics_side_module_settings TARGET_NAME)+ target_compile_options(${TARGET_NAME} PRIVATE -fPIC -sRELOCATABLE=1 -flto)++ string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_PHYSICS_SIDE_MODULE_FLAGS}")+ set_target_properties(${TARGET_NAME} PROPERTIES+ PREFIX ""+ SUFFIX ".wasm"+ LINK_FLAGS "${LINK_FLAGS_STR}"+ )+ message(STATUS "Configured ${TARGET_NAME} as SIDE_MODULE")endfunction()# SDK-specific link flags (library only, no app entry)@@ -241,24 +267,25 @@ endfunction()# =============================================================================set(ES_EMSCRIPTEN_SPINE_MODULE_FLAGS- --bind-sWASM=1-sALLOW_MEMORY_GROWTH=1-sNO_EXIT_RUNTIME=1-sEXPORT_ES6=0-sMODULARIZE=1-sDYNAMIC_EXECUTION=0- -sFORCE_FILESYSTEM=1+ -sFILESYSTEM=0"-sEXPORT_NAME='ESSpineModule'""-sEXPORTED_FUNCTIONS=['_malloc','_free']"- "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','FS']"+ "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','UTF8ToString','stringToNewUTF8','HEAPF32','HEAPU8','HEAPU32']"-O3-flto+ -fno-exceptions+ -fno-rtti)function(es_apply_spine_module_settings TARGET_NAME)if(ES_BUILD_WEB OR ES_BUILD_WXGAME)- target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS} -flto)+ target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS} -flto -fno-exceptions -fno-rtti)string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_SPINE_MODULE_FLAGS}")set_target_properties(${TARGET_NAME} PROPERTIES@@ -273,7 +300,6 @@ endfunction()# =============================================================================set(ES_EMSCRIPTEN_PHYSICS_MODULE_FLAGS- --bind-sWASM=1-sALLOW_MEMORY_GROWTH=1-sNO_EXIT_RUNTIME=1@@ -300,6 +326,6 @@ function(es_apply_physics_module_settings TARGET_NAME)endfunction()message(STATUS "Emscripten configuration loaded")-if(ES_BUILD_MODULAR)- message(STATUS "Modular build enabled: MAIN_MODULE + SIDE_MODULE architecture")+if(ES_BUILD_MAIN_MODULE)+ message(STATUS "MAIN_MODULE build enabled: supports loading SIDE_MODULE")endif()diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex b989069ba..f86187a43 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,2 +1,2 @@-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function c(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,r)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let x=null,_=null;function m(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function y(e,t=!0){const{width:r,height:s}=e,{ctx:n}=function(e,t){return x||(x=wx.createCanvas(),x.width=e,x.height=t,_=x.getContext("2d")),(x.width<e||x.height<t)&&(x.width=Math.max(x.width,e),x.height=Math.max(x.height,t)),{canvas:x,ctx:_}}(r,s);n.clearRect(0,0,r,s),n.save(),t&&(n.translate(0,s),n.scale(1,-1)),n.drawImage(e,0,0),n.restore();const o=n.getImageData(0,0,r,s);return{width:r,height:s,pixels:new Uint8Array(o.data.buffer)}}let g=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return d(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;function S(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=S("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),C=S("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=S("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),b=S("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A={Static:0,Kinematic:1,Dynamic:2};let E=0;function M(e,t){const r=++E;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function U(e,t){const r=R(),s=r.get(e);if(s)return s;const n=M(e,t);return r.set(e,n),I(e,t,!1),n}function F(e){return R().get(e)}function I(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function B(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function z(e){return!0===e._builtin}const W=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}}),D=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}}),$=B("Sprite",{texture:v,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),L=B("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),k=B("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),O=B("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),H=B("Parent",{entity:0}),N=B("Children",{entities:[]}),V=B("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),G={LocalTransform:W,WorldTransform:D,Sprite:$,Camera:L,Canvas:k,Velocity:O,Parent:H,Children:N,SpineAnimation:V,RigidBody:P,BoxCollider:C,CircleCollider:T,CapsuleCollider:b};let j=0;function X(e,t){const r=++j;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function q(e){return{_type:"res",_resource:e}}class K{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 Y{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 K(this.get(e),t=>this.set(e,t))}}const J=X({delta:0,elapsed:0,frameCount:0},"Time");function Q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class Z{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return Q(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:s}=this.descriptor_,n=e.map(e=>this.getActualComponent(e)),o=[...n,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let r=!1;for(const t of s)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=n.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}class ee{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let r;return r=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}entity(e){return new ee(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var re;exports.Schedule=void 0,(re=exports.Schedule||(exports.Schedule={}))[re.Startup=0]="Startup",re[re.First=1]="First",re[re.PreUpdate=2]="PreUpdate",re[re.Update=3]="Update",re[re.PostUpdate=4]="PostUpdate",re[re.Last=5]="Last",re[re.FixedPreUpdate=10]="FixedPreUpdate",re[re.FixedUpdate=11]="FixedUpdate",re[re.FixedPostUpdate=12]="FixedPostUpdate";let se=0;function ne(e,t,r){const s=++se;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ie{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof te&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Z(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new te(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ae{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ce=X(new ae,"Input");class le{constructor(e){this.target_=e??null}build(e){const r=new ae;e.insertResource(ce,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,ne([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ue=new le;class he{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return z(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,s)}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let s=!0;for(const t of e)if(!this.has(r,t)){s=!1;break}s&&t.push(r)}return t}}var de,pe,fe;exports.TextAlign=void 0,(de=exports.TextAlign||(exports.TextAlign={}))[de.Left=0]="Left",de[de.Center=1]="Center",de[de.Right=2]="Right",exports.TextVerticalAlign=void 0,(pe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[pe.Top=0]="Top",pe[pe.Middle=1]="Middle",pe[pe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(fe=exports.TextOverflow||(exports.TextOverflow={}))[fe.Visible=0]="Visible",fe[fe.Clip=1]="Clip",fe[fe.Ellipsis=2]="Ellipsis";const xe=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class _e{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let c=this.wrapText(e.content,a?o:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const x=Math.round(255*e.color.x),_=Math.round(255*e.color.y),m=Math.round(255*e.color.z),y=e.color.w;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${x}, ${_}, ${m}, ${y})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const g=c.length*l;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-g)/2;break;case exports.TextVerticalAlign.Bottom:w=f-g-u;break;default:w=u}else w=u;let v=w;for(const t of c){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,v),v+=l}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,p,f),T=this.module.getResourceManager(),b=this.module._malloc(C.length);this.module.HEAPU8.set(C,b);const A=T.createTexture(p,f,b,C.length,1);return this.module._free(b),{textureHandle:A,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const s=4*t,n=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*s,i=(r-1-t)*s;n.set(e.subarray(o,o+s),i)}return n}}const me=U("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ye{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new _e(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ne([],()=>{const e=s.getEntitiesWithComponents([xe]);for(const t of e){const e=s.get(t,xe);if(!e.dirty)continue;s.has(t,$)||s.insert(t,$,{texture:v,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,me)?s.get(t,me):null,o=r.renderForEntity(t,e,n),i=s.get(t,$);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},s.insert(t,$,i),e.dirty=!1}}))}}const ge=new ye;var we;function ve(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(we=exports.BlendMode||(exports.BlendMode={}))[we.Normal=0]="Normal",we[we.Additive=1]="Additive",we[we.Multiply=2]="Multiply",we[we.Screen=3]="Screen",we[we.PremultipliedAlpha=4]="PremultipliedAlpha";let Se=null,Pe=null,Ce=1;const Te=new Map;function be(e){Se=e,Pe=e.getResourceManager(),Be()}function Ae(){0!==Ue&&Se&&(Se._free(Ue),Ue=0),Te.clear(),Ce=1,Re=!1,Pe=null,Se=null}function Ee(){if(!Pe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Pe}const Me={createShader:(e,t)=>Ee().createShader(e,t),releaseShader(e){e>0&&Ee().releaseShader(e)},create(e){const t=Ce++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return Te.set(t,r),t},get:e=>Te.get(e),setUniform(e,t,r){const s=Te.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=Te.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Te.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Te.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Te.get(e);r&&(r.depthTest=t)},getShader(e){const t=Te.get(e);return t?.shader??0},release(e){Te.delete(e)},isValid:e=>Te.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Te.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Ce++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Te.set(r,s),r},toAssetData(e,t){const r=Te.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=Te.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Re=!1,Ue=0;const Fe=4096;function Ie(e){const t=(0===Ue&&Se&&(Ue=Se._malloc(Fe)),Ue);if(0===t||!Se)return{ptr:0,count:0};let r=0,s=0;const n=Se.HEAPU8,o=Se.HEAPU32,i=Se.HEAPF32;for(const[a,c]of e){if(r+128>Fe)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,n.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function Be(){if(!Se||Re)return;Se.materialDataProvider=(e,t,r,s,n)=>{const o=Te.get(e);if(!o)return Se.HEAPU32[t>>2]=0,Se.HEAPU32[r>>2]=0,Se.HEAPU32[s>>2]=0,void(Se.HEAPU32[n>>2]=0);Se.HEAPU32[t>>2]=o.shader,Se.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Ie(o.uniforms);Se.HEAPU32[s>>2]=i,Se.HEAPU32[n>>2]=a},Re=!0}const ze={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class We{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Me.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Me.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:Me.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function De(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t);for(const r of s.components)Le(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function $e(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t);for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Le(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function Le(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,W,s);break;case"Sprite":e.insert(t,$,s);break;case"Camera":e.insert(t,L,s);break;case"Canvas":e.insert(t,k,s);break;case"Text":e.insert(t,xe,s);break;case"SpineAnimation":e.insert(t,V,s);break;case"UIRect":e.insert(t,me,s);break;default:{const n=F(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class ke{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Oe{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.embedded_=new Map,this.module_=e,this.canvas_=i(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new We(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,r),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return $e(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r)??r;return new Promise((r,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),s&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:c,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(r);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Me.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await n(t);return JSON.parse(r)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const He=X(null,"Assets");class Ne{build(e){const t=e.wasmModule;t?e.insertResource(He,new Oe(t)):console.warn("AssetPlugin: No WASM module available")}}const Ve=new Ne;let Ge=null,je=0,Xe=0,qe=0;const Ke=new Float32Array(256);function Ye(e){Ge=e,je=Ge._malloc(64),Xe=Ge._malloc(64),qe=Ge._malloc(1024)}function Je(){Ge&&(je&&(Ge._free(je),je=0),Xe&&(Ge._free(Xe),Xe=0),qe&&(Ge._free(qe),qe=0)),Ge=null}function Qe(){if(!Ge)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ge}const Ze={x:1,y:1,z:1,w:1},et={begin(e){const t=Qe();t.HEAPF32.set(e,je/4),t.draw_begin(je)},end(){Qe().draw_end()},line(e,t,r,s=1){Qe().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rect(e,t,r,s=!0){Qe().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rectOutline(e,t,r,s=1){Qe().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},circle(e,t,r,s=!0,n=32){Qe().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},circleOutline(e,t,r,s=1,n=32){Qe().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},texture(e,t,r,s=Ze){Qe().draw_texture(e.x,e.y,t.x,t.y,r,s.x,s.y,s.z,s.w)},textureRotated(e,t,r,s,n=Ze){Qe().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.x,n.y,n.z,n.w)},setLayer(e){Qe().draw_setLayer(e)},setDepth(e){Qe().draw_setDepth(e)},getDrawCallCount:()=>Ge?Ge.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ge?Ge.draw_getPrimitiveCount():0,setBlendMode(e){Qe().draw_setBlendMode(e)},setDepthTest(e){Qe().draw_setDepthTest(e)},drawMesh(e,t,r){const s=Qe();s.HEAPF32.set(r,Xe/4),s.draw_mesh(e,t,Xe)},drawMeshWithMaterial(e,t,r){const s=Qe(),n=Me.get(t);if(!n)return;if(et.setBlendMode(n.blendMode),et.setDepthTest(n.depthTest),0===n.uniforms.size)return void et.drawMesh(e,n.shader,r);s.HEAPF32.set(r,Xe/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=rt(e);if(!(r<0)){if(ve(t))Ke[o++]=10,Ke[o++]=r,Ke[o++]=t.slot??i++,Ke[o++]=t.textureId;else if("number"==typeof t)Ke[o++]=1,Ke[o++]=r,Ke[o++]=t;else if(Array.isArray(t)){Ke[o++]=t.length,Ke[o++]=r;for(let e=0;e<t.length;e++)Ke[o++]=t[e]}else"w"in t?(Ke[o++]=4,Ke[o++]=r,Ke[o++]=t.x,Ke[o++]=t.y,Ke[o++]=t.z,Ke[o++]=t.w):"z"in t?(Ke[o++]=3,Ke[o++]=r,Ke[o++]=t.x,Ke[o++]=t.y,Ke[o++]=t.z):(Ke[o++]=2,Ke[o++]=r,Ke[o++]=t.x,Ke[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Ke.subarray(0,o),qe/4),s.draw_meshWithUniforms(e,n.shader,Xe,qe,o)):s.draw_mesh(e,n.shader,Xe)}},tt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function rt(e){return tt[e]??-1}var st;exports.DataType=void 0,(st=exports.DataType||(exports.DataType={}))[st.Float=1]="Float",st[st.Float2=2]="Float2",st[st.Float3=3]="Float3",st[st.Float4=4]="Float4",st[st.Int=5]="Int",st[st.Int2=6]="Int2",st[st.Int3=7]="Int3",st[st.Int4=8]="Int4";let nt=null,ot=0,it=0,at=0;function ct(e){nt=e,ot=nt._malloc(262144),it=nt._malloc(65536),at=nt._malloc(256)}function lt(){nt&&(ot&&nt._free(ot),it&&nt._free(it),at&&nt._free(at),ot=0,it=0,at=0),nt=null}function ut(){if(!nt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return nt}const ht={create(e){const t=ut(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,ot/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,at,n).set(o),t.geometry_init(r,ot,s,at,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,it,s).set(e.indices),t.geometry_setIndices16(r,it,s)}else{new Uint32Array(t.HEAPU8.buffer,it,s).set(e.indices),t.geometry_setIndices32(r,it,s)}}return r},updateVertices(e,t,r=0){const s=ut(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,ot/4),s.geometry_updateVertices(e,ot,n,r)},release(e){e>0&&ut().geometry_release(e)},isValid:e=>!(!nt||e<=0)&&nt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return ht.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,c=(Math.sin(n)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return ht.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return ht.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 dt=null;function pt(e){dt=e}function ft(){dt&&_t.isInitialized()&&_t.shutdown(),dt=null}function xt(){if(!dt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return dt}const _t={init:(e,t)=>xt().postprocess_init(e,t),shutdown(){xt().postprocess_shutdown()},resize(e,t){xt().postprocess_resize(e,t)},addPass:(e,t)=>xt().postprocess_addPass(e,t),removePass(e){xt().postprocess_removePass(e)},setEnabled(e,t){xt().postprocess_setPassEnabled(e,t)},isEnabled:e=>xt().postprocess_isPassEnabled(e),setUniform(e,t,r){xt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){xt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){xt().postprocess_begin()},end(){xt().postprocess_end()},getPassCount:()=>xt().postprocess_getPassCount(),isInitialized:()=>!!dt&&dt.postprocess_isInitialized(),setBypass(e){xt().postprocess_setBypass(e)},isBypassed:()=>!dt||dt.postprocess_isBypassed(),createBlur:()=>Me.createShader(mt,"#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:()=>Me.createShader(mt,"#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:()=>Me.createShader(mt,"#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:()=>Me.createShader(mt,"#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")},mt="#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 yt;exports.RenderStage=void 0,(yt=exports.RenderStage||(exports.RenderStage={}))[yt.Background=0]="Background",yt[yt.Opaque=1]="Opaque",yt[yt.Transparent=2]="Transparent",yt[yt.Overlay=3]="Overlay";let gt=null,wt=0;function vt(e){gt=e,wt=gt._malloc(64)}function St(){gt&&wt&&(gt._free(wt),wt=0),gt=null}const Pt={init(e,t){gt?.renderer_init(e,t)},resize(e,t){gt?.renderer_resize(e,t)},begin(e,t){gt&&wt&&(gt.HEAPF32.set(e,wt/4),gt.renderer_begin(wt,t??0))},flush(){gt?.renderer_flush()},end(){gt?.renderer_end()},submitSprites(e){gt&>.renderer_submitSprites(e._cpp)},submitSpine(e){gt&>.renderer_submitSpine?.(e._cpp)},setStage(e){gt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>gt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){gt?.renderer_releaseTarget(e)},getTargetTexture:e=>gt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>gt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){gt?.renderer_setClearColor?.(e,t,r,s)},getStats:()=>gt?{drawCalls:gt.renderer_getDrawCalls(),triangles:gt.renderer_getTriangles(),sprites:gt.renderer_getSprites(),spine:gt.renderer_getSpine?.()??0,meshes:gt.renderer_getMeshes(),culled:gt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Ct=null;function Tt(e){Ct=e}function bt(){Ct=null}const At={enable(){Ct?.gl_enableErrorCheck(!0)},disable(){Ct?.gl_enableErrorCheck(!1)},check:e=>Ct?.gl_checkErrors(e)??0,diagnose(){Ct?.renderer_diagnose()}},Et=new Map;function Mt(e){Et.delete(e)}class Rt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;Pt.resize(s,n),_t.isInitialized()&&_t.getPassCount()>0&&!_t.isBypassed()&&_t.resize(s,n),Pt.begin(r),Pt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Pt.submitSpine(t),Pt.flush();const i=Et;if(i.size>0){et.begin(r);const e=[];for(const[t,r]of i.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}et.end();for(const t of e)Mt(t)}Pt.end()}}class Ut{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new he,this.resources_=new Y;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ut}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ie(this.world_,this.resources_),this.resources_.insert(J,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,bt(),St(),ft(),lt(),Ae(),Je()}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(J),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(J,r)}}const Ft=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function It(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function Bt(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function zt(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,c=s-r,l=o-n;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(s+r)/c,i[14]=-(o+n)/l,i[15]=1,i}function Wt(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function Dt(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function $t(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}function Lt(e,t){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const n=r.createTexture(t.width,t.height,s,t.pixels.length,1);return e._free(s),n}function kt(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function Ot(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function Ht(e,t,r,s,n){const o=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Lt(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={};n&&(i=await async function(e,t,r,s){const n={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=s.resolvePath(o),c=s.resolvePath(i);try{const r=s.readText(i),l=a.endsWith(".skel");kt(t,a),l?t.FS.writeFile(a,s.readBinary(o)):t.FS.writeFile(a,s.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;n[o]=u;const h=Ot(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const n=d+"/"+h[r];try{const o=s.loadPixelsRaw?await s.loadPixelsRaw(n):await s.loadPixels(n),i=Lt(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return n}(t,n,r,s));const a=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Me.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=Me.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),c=De(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,$);n&&(n.texture=r[s.data.texture]||0,e.insert(t,$,n))}}}(e.world,r,o,c),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,$);r&&(r.material=n,e.insert(t,$,r))}else if("SpineAnimation"===s.type){const r=e.get(t,V);r&&(r.material=n,e.insert(t,V,r))}}}}(e.world,r,a,c),n){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=s.get(o.id);void 0!==c&&(n[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return n}(n,r,i,c);!function(e,t,r,s){let n=0;e.setSpineRenderer((e,o)=>{let i=o-n;n=o,(i<=0||i>.5)&&(i=1/60);for(const e in s){const n=s[e];r.spine_update(n,i);const o=r.spine_getMeshBatchCount(n);for(let e=0;e<o;e++){const s=r.spine_getMeshBatchVertexCount(n,e),o=r.spine_getMeshBatchIndexCount(n,e);if(!s||!o)continue;const i=8*s*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(n,e,c,l,u,h);const d=r.HEAPU32[u>>2],p=r.HEAPU32[h>>2],f=new Float32Array(r.HEAPF32.buffer,c,8*s),x=new Uint16Array(r.HEAPU8.buffer,l,o),_=t._malloc(i),m=t._malloc(a);t.HEAPF32.set(f,_>>2),new Uint16Array(t.HEAPU8.buffer,m,o).set(x),t.renderer_submitTriangles(_,s,m,o,d,p,0),t._free(_),t._free(m),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,n,s)}}class Nt{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Vt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Pt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Pt.getTargetTexture(r),width:e.width,height:e.height}},release(e){Pt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Pt.releaseRenderTarget(e._handle),Vt.create({width:t,height:r,depth:!0})),begin(e,t){Pt.begin(t,e._handle)},end(){Pt.end()},getDepthTexture:e=>Pt.getTargetDepthTexture(e._handle)};let Gt=!1;async function jt(e,t){if(t)return t();return(0,(await import(e)).default)()}const Xt=X({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function qt(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Kt(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}function Yt(e,t,r){const s=e.world;if(s.has(r,C)){const e=s.get(r,C);return void t.physics_addBoxShape(r,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}if(s.has(r,T)){const e=s.get(r,T);return void t.physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}if(s.has(r,b)){const e=s.get(r,b);t.physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}}var Jt;g||(g=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await c(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Jt=w,console.log(`[ESEngine] Platform: ${Jt.name}`),exports.App=Ut,exports.AssetPlugin=Ne,exports.AssetServer=Oe,exports.Assets=He,exports.AsyncCache=ke,exports.BodyType=A,exports.BoxCollider=C,exports.Camera=L,exports.Canvas=k,exports.CapsuleCollider=b,exports.Children=N,exports.CircleCollider=T,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=te,exports.Draw=et,exports.EntityCommands=ee,exports.GLDebug=At,exports.Geometry=ht,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=v,exports.Input=ce,exports.InputPlugin=le,exports.InputState=ae,exports.LocalTransform=W,exports.Material=Me,exports.MaterialLoader=We,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=H,exports.Physics=class{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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){return this.module_.physics_getLinearVelocity(e)}},exports.PhysicsEvents=Xt,exports.PhysicsPlugin=class{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Xt,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=jt(this.wasmUrl_,this.factory_).then(r=>{r.physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,ne([q(J)],n=>{const o=s.getEntitiesWithComponents([P,W]),i=new Set;for(const n of o){i.add(n);const o=s.get(n,P),a=s.get(n,W);if(!t.has(n)){if(!o.enabled)continue;const s=qt(a.rotation);r.physics_createBody(n,o.bodyType,a.position.x,a.position.y,s,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation,o.bullet),Yt(e,r,n),t.add(n)}if(o.bodyType===A.Kinematic){const e=qt(a.rotation);r.physics_setBodyTransform(n,a.position.x,a.position.y,e)}}for(const e of t)i.has(e)||(r.physics_destroyBody(e),t.delete(e));r.physics_step(n.delta),function(e,t){const r=t.physics_getDynamicBodyCount();if(0===r)return;const s=t.physics_getDynamicBodyTransforms(),n=s>>2;for(let s=0;s<r;s++){const r=n+4*s,o=t.HEAPU32[r],i=t.HEAPF32[r+1],a=t.HEAPF32[r+2],c=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const l=e.world.get(o,W);if(!l)continue;l.position.x=i,l.position.y=a;const u=Kt(c);l.rotation.w=u.w,l.rotation.x=u.x,l.rotation.y=u.y,l.rotation.z=u.z}}(e,r),function(e,t){const r=t.physics_getCollisionEvents(),s=[];for(let e=0;e<r.enters.size();e++){const t=r.enters.get(e);s.push(t)}const n=[];for(let e=0;e<r.exits.size();e++){const t=r.exits.get(e);n.push({entityA:t.entityA,entityB:t.entityB})}const o=[];for(let e=0;e<r.sensorEnters.size();e++)o.push(r.sensorEnters.get(e));const i=[];for(let e=0;e<r.sensorExits.size();e++)i.push(r.sensorExits.get(e));e.insertResource(Xt,{collisionEnters:s,collisionExits:n,sensorEnters:o,sensorExits:i}),r.enters.delete(),r.exits.delete(),r.sensorEnters.delete(),r.sensorExits.delete()}(e,r)},{name:"PhysicsSystem"})),e.__physicsModule=r});e.__physicsInitPromise=r}},exports.PostProcess=_t,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Nt(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.module}await Ht(this.app_,this.app_.wasmModule,t,s,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([L]);for(const s of r){if(e.get(s,L).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([k]);for(const n of s){const s=e.get(n,k);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,W,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(n,L,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{Q(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=Z,exports.RenderPipeline=Rt,exports.RenderTexture=Vt,exports.Renderer=Pt,exports.Res=q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ShaderSources=ze,exports.SpineAnimation=V,exports.Sprite=$,exports.SystemRunner=ie,exports.Text=xe,exports.TextPlugin=ye,exports.TextRenderer=_e,exports.Time=J,exports.UIRect=me,exports.Velocity=O,exports.WebAssetProvider=Nt,exports.World=he,exports.WorldTransform=D,exports.addStartupSystem=function(e){oe().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){oe().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){oe().push({schedule:e,system:t})},exports.assetPlugin=Ve,exports.clearDrawCallbacks=function(){Et.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({x:e,y:t,z:r,w:s}),exports.createWebApp=function(e,t){const r=Ut.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ye(e),be(e),ct(e),pt(e),vt(e),Tt(e);const n=new Rt;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=i(),r=s.entityCount(),c=It(s,r+1e3);if(c){const e=c.backgroundColor;Pt.setClearColor(e.x,e.y,e.z,e.w)}const l=function(e,t,r){const s=e.entityCount(),n=s+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=It(e,n);if(r){t=Bt(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const s=t*a;c=zt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=Wt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return $t(c,Dt(i.position.x,i.position.y,i.position.z))}return Ft}(s,e,t),u=(a()-o)/1e3;n.render({registry:{_cpp:s},viewProjection:l,width:e,height:t,elapsed:u})}};return r.addSystemToSchedule(exports.Schedule.Last,c),r.addPlugin(Ve),r.addPlugin(ue),r.addPlugin(ge),r},exports.defineComponent=U,exports.defineResource=X,exports.defineSystem=ne,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const s=M(e,{});return t.set(e,s),I(e,{},!0),s},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=G[e];if(t)return{...t._default};const r=F(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=F,exports.initDrawAPI=Ye,exports.initGLDebugAPI=Tt,exports.initGeometryAPI=ct,exports.initMaterialAPI=be,exports.initPostProcessAPI=pt,exports.initRendererAPI=vt,exports.inputPlugin=ue,exports.isBuiltinComponent=z,exports.isEditor=function(){return Gt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Gt},exports.isTextureRef=ve,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Le,exports.loadPhysicsModule=jt,exports.loadRuntimeScene=Ht,exports.loadSceneData=De,exports.loadSceneWithAssets=$e,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){Et.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(He);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Be,exports.setEditorMode=function(e){Gt=e},exports.shutdownDrawAPI=Je,exports.shutdownGLDebugAPI=bt,exports.shutdownGeometryAPI=lt,exports.shutdownMaterialAPI=Ae,exports.shutdownPostProcessAPI=ft,exports.shutdownRendererAPI=St,exports.textPlugin=ge,exports.unregisterDrawCallback=Mt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([L]);for(const s of r){const r=e.get(s,L);r&&(r.aspectRatio=t,e.insert(s,L,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=y,exports.wxLoadImage=m,exports.wxLoadImagePixels=async function(e,t=!0){return y(await m(e),t)},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function c(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,r)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,_=null;function x(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function g(e,t=!0){const{width:r,height:s}=e,{ctx:n}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,_=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:_}}(r,s);n.clearRect(0,0,r,s),n.save(),t&&(n.translate(0,s),n.scale(1,-1)),n.drawImage(e,0,0),n.restore();const o=n.getImageData(0,0,r,s);return{width:r,height:s,pixels:new Uint8Array(o.data.buffer)}}let y=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return d(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),S=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A={Static:0,Kinematic:1,Dynamic:2};let E=0;function M(e,t){const r=++E;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function U(e,t){const r=R(),s=r.get(e);if(s)return s;const n=M(e,t);return r.set(e,n),B(e,t,!1),n}function F(e){return R().get(e)}function B(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function W(e){return!0===e._builtin}const z=I("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),k=I("Sprite",{texture:v,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),$=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),L=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),H=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),O=I("Parent",{entity:0}),N=I("Children",{entities:[]}),V=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),G={LocalTransform:z,WorldTransform:D,Sprite:k,Camera:$,Canvas:L,Velocity:H,Parent:O,Children:N,SpineAnimation:V,RigidBody:P,BoxCollider:S,CircleCollider:C,CapsuleCollider:T};let X=0;function j(e,t){const r=++X;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function Y(e){return{_type:"res",_resource:e}}class q{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 K{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 q(this.get(e),t=>this.set(e,t))}}const J=j({delta:0,elapsed:0,frameCount:0},"Time");function Q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class Z{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return Q(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:s}=this.descriptor_,n=e.map(e=>this.getActualComponent(e)),o=[...n,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let r=!1;for(const t of s)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=n.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}class ee{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let r;return r=W(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}entity(e){return new ee(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var re;exports.Schedule=void 0,(re=exports.Schedule||(exports.Schedule={}))[re.Startup=0]="Startup",re[re.First=1]="First",re[re.PreUpdate=2]="PreUpdate",re[re.Update=3]="Update",re[re.PostUpdate=4]="PostUpdate",re[re.Last=5]="Last",re[re.FixedPreUpdate=10]="FixedPreUpdate",re[re.FixedUpdate=11]="FixedUpdate",re[re.FixedPostUpdate=12]="FixedPostUpdate";let se=0;function ne(e,t,r){const s=++se;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ie{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof te&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Z(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new te(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ae{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ce=j(new ae,"Input");class le{constructor(e){this.target_=e??null}build(e){const r=new ae;e.insertResource(ce,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,ne([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ue=new le;class he{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return W(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return W(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return W(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){W(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,s)}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let s=!0;for(const t of e)if(!this.has(r,t)){s=!1;break}s&&t.push(r)}return t}}var de,pe,fe;exports.TextAlign=void 0,(de=exports.TextAlign||(exports.TextAlign={}))[de.Left=0]="Left",de[de.Center=1]="Center",de[de.Right=2]="Right",exports.TextVerticalAlign=void 0,(pe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[pe.Top=0]="Top",pe[pe.Middle=1]="Middle",pe[pe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(fe=exports.TextOverflow||(exports.TextOverflow={}))[fe.Visible=0]="Visible",fe[fe.Clip=1]="Clip",fe[fe.Ellipsis=2]="Ellipsis";const me=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class _e{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let c=this.wrapText(e.content,a?o:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.x),_=Math.round(255*e.color.y),x=Math.round(255*e.color.z),g=e.color.w;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${x}, ${g})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=c.length*l;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of c){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,v),v+=l}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const b=r.getImageData(0,0,p,f),P=new Uint8Array(b.data.buffer),S=this.flipVertically(P,p,f),C=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const A=C.createTexture(p,f,T,S.length,1);return this.module._free(T),{textureHandle:A,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const s=4*t,n=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*s,i=(r-1-t)*s;n.set(e.subarray(o,o+s),i)}return n}}const xe=U("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ge{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new _e(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ne([],()=>{const e=s.getEntitiesWithComponents([me]);for(const t of e){const e=s.get(t,me);if(!e.dirty)continue;s.has(t,k)||s.insert(t,k,{texture:v,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,xe)?s.get(t,xe):null,o=r.renderForEntity(t,e,n),i=s.get(t,k);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},s.insert(t,k,i),e.dirty=!1}}))}}const ye=new ge;var we;function ve(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(we=exports.BlendMode||(exports.BlendMode={}))[we.Normal=0]="Normal",we[we.Additive=1]="Additive",we[we.Multiply=2]="Multiply",we[we.Screen=3]="Screen",we[we.PremultipliedAlpha=4]="PremultipliedAlpha";let be=null,Pe=null,Se=1;const Ce=new Map;function Te(e){be=e,Pe=e.getResourceManager(),Ie()}function Ae(){0!==Ue&&be&&(be._free(Ue),Ue=0),Ce.clear(),Se=1,Re=!1,Pe=null,be=null}function Ee(){if(!Pe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Pe}const Me={createShader:(e,t)=>Ee().createShader(e,t),releaseShader(e){e>0&&Ee().releaseShader(e)},create(e){const t=Se++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return Ce.set(t,r),t},get:e=>Ce.get(e),setUniform(e,t,r){const s=Ce.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=Ce.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ce.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ce.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Ce.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ce.get(e);return t?.shader??0},release(e){Ce.delete(e)},isValid:e=>Ce.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ce.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Se++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ce.set(r,s),r},toAssetData(e,t){const r=Ce.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=Ce.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Re=!1,Ue=0;const Fe=4096;function Be(e){const t=(0===Ue&&be&&(Ue=be._malloc(Fe)),Ue);if(0===t||!be)return{ptr:0,count:0};let r=0,s=0;const n=be.HEAPU8,o=be.HEAPU32,i=be.HEAPF32;for(const[a,c]of e){if(r+128>Fe)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,n.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function Ie(){if(!be||Re)return;be.materialDataProvider=(e,t,r,s,n)=>{const o=Ce.get(e);if(!o)return be.HEAPU32[t>>2]=0,be.HEAPU32[r>>2]=0,be.HEAPU32[s>>2]=0,void(be.HEAPU32[n>>2]=0);be.HEAPU32[t>>2]=o.shader,be.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Be(o.uniforms);be.HEAPU32[s>>2]=i,be.HEAPU32[n>>2]=a},Re=!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 ze{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Me.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Me.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:Me.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function De(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t);for(const r of s.components)$e(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function ke(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t);for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}$e(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function $e(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,z,s);break;case"Sprite":e.insert(t,k,s);break;case"Camera":e.insert(t,$,s);break;case"Canvas":e.insert(t,L,s);break;case"Text":e.insert(t,me,s);break;case"SpineAnimation":e.insert(t,V,s);break;case"UIRect":e.insert(t,xe,s);break;default:{const n=F(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Le{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class He{constructor(e){this.textureCache_=new Le,this.shaderCache_=new Le,this.jsonCache_=new Le,this.textCache_=new Le,this.binaryCache_=new Le,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,this.module_=e,this.canvas_=i(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ze(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,r),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return ke(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r)??r;return new Promise((r,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),s&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:c,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(r);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Me.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await n(t);return JSON.parse(r)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Oe=j(null,"Assets");class Ne{build(e){const t=e.wasmModule;t?e.insertResource(Oe,new He(t)):console.warn("AssetPlugin: No WASM module available")}}const Ve=new Ne;let Ge=null,Xe=0,je=0,Ye=0;const qe=new Float32Array(256);function Ke(e){Ge=e,Xe=Ge._malloc(64),je=Ge._malloc(64),Ye=Ge._malloc(1024)}function Je(){Ge&&(Xe&&(Ge._free(Xe),Xe=0),je&&(Ge._free(je),je=0),Ye&&(Ge._free(Ye),Ye=0)),Ge=null}function Qe(){if(!Ge)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ge}const Ze={x:1,y:1,z:1,w:1},et={begin(e){const t=Qe();t.HEAPF32.set(e,Xe/4),t.draw_begin(Xe)},end(){Qe().draw_end()},line(e,t,r,s=1){Qe().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rect(e,t,r,s=!0){Qe().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rectOutline(e,t,r,s=1){Qe().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},circle(e,t,r,s=!0,n=32){Qe().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},circleOutline(e,t,r,s=1,n=32){Qe().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},texture(e,t,r,s=Ze){Qe().draw_texture(e.x,e.y,t.x,t.y,r,s.x,s.y,s.z,s.w)},textureRotated(e,t,r,s,n=Ze){Qe().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.x,n.y,n.z,n.w)},setLayer(e){Qe().draw_setLayer(e)},setDepth(e){Qe().draw_setDepth(e)},getDrawCallCount:()=>Ge?Ge.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ge?Ge.draw_getPrimitiveCount():0,setBlendMode(e){Qe().draw_setBlendMode(e)},setDepthTest(e){Qe().draw_setDepthTest(e)},drawMesh(e,t,r){const s=Qe();s.HEAPF32.set(r,je/4),s.draw_mesh(e,t,je)},drawMeshWithMaterial(e,t,r){const s=Qe(),n=Me.get(t);if(!n)return;if(et.setBlendMode(n.blendMode),et.setDepthTest(n.depthTest),0===n.uniforms.size)return void et.drawMesh(e,n.shader,r);s.HEAPF32.set(r,je/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=rt(e);if(!(r<0)){if(ve(t))qe[o++]=10,qe[o++]=r,qe[o++]=t.slot??i++,qe[o++]=t.textureId;else if("number"==typeof t)qe[o++]=1,qe[o++]=r,qe[o++]=t;else if(Array.isArray(t)){qe[o++]=t.length,qe[o++]=r;for(let e=0;e<t.length;e++)qe[o++]=t[e]}else"w"in t?(qe[o++]=4,qe[o++]=r,qe[o++]=t.x,qe[o++]=t.y,qe[o++]=t.z,qe[o++]=t.w):"z"in t?(qe[o++]=3,qe[o++]=r,qe[o++]=t.x,qe[o++]=t.y,qe[o++]=t.z):(qe[o++]=2,qe[o++]=r,qe[o++]=t.x,qe[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(qe.subarray(0,o),Ye/4),s.draw_meshWithUniforms(e,n.shader,je,Ye,o)):s.draw_mesh(e,n.shader,je)}},tt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function rt(e){return tt[e]??-1}var st;exports.DataType=void 0,(st=exports.DataType||(exports.DataType={}))[st.Float=1]="Float",st[st.Float2=2]="Float2",st[st.Float3=3]="Float3",st[st.Float4=4]="Float4",st[st.Int=5]="Int",st[st.Int2=6]="Int2",st[st.Int3=7]="Int3",st[st.Int4=8]="Int4";let nt=null,ot=0,it=0,at=0;function ct(e){nt=e,ot=nt._malloc(262144),it=nt._malloc(65536),at=nt._malloc(256)}function lt(){nt&&(ot&&nt._free(ot),it&&nt._free(it),at&&nt._free(at),ot=0,it=0,at=0),nt=null}function ut(){if(!nt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return nt}const ht={create(e){const t=ut(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,ot/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,at,n).set(o),t.geometry_init(r,ot,s,at,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,it,s).set(e.indices),t.geometry_setIndices16(r,it,s)}else{new Uint32Array(t.HEAPU8.buffer,it,s).set(e.indices),t.geometry_setIndices32(r,it,s)}}return r},updateVertices(e,t,r=0){const s=ut(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,ot/4),s.geometry_updateVertices(e,ot,n,r)},release(e){e>0&&ut().geometry_release(e)},isValid:e=>!(!nt||e<=0)&&nt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return ht.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,c=(Math.sin(n)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return ht.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return ht.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 dt=null;function pt(e){dt=e}function ft(){dt&&_t.isInitialized()&&_t.shutdown(),dt=null}function mt(){if(!dt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return dt}const _t={init:(e,t)=>mt().postprocess_init(e,t),shutdown(){mt().postprocess_shutdown()},resize(e,t){mt().postprocess_resize(e,t)},addPass:(e,t)=>mt().postprocess_addPass(e,t),removePass(e){mt().postprocess_removePass(e)},setEnabled(e,t){mt().postprocess_setPassEnabled(e,t)},isEnabled:e=>mt().postprocess_isPassEnabled(e),setUniform(e,t,r){mt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){mt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){mt().postprocess_begin()},end(){mt().postprocess_end()},getPassCount:()=>mt().postprocess_getPassCount(),isInitialized:()=>!!dt&&dt.postprocess_isInitialized(),setBypass(e){mt().postprocess_setBypass(e)},isBypassed:()=>!dt||dt.postprocess_isBypassed(),createBlur:()=>Me.createShader(xt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Me.createShader(xt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Me.createShader(xt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Me.createShader(xt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},xt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var gt;exports.RenderStage=void 0,(gt=exports.RenderStage||(exports.RenderStage={}))[gt.Background=0]="Background",gt[gt.Opaque=1]="Opaque",gt[gt.Transparent=2]="Transparent",gt[gt.Overlay=3]="Overlay";let yt=null,wt=0;function vt(e){yt=e,wt=yt._malloc(64)}function bt(){yt&&wt&&(yt._free(wt),wt=0),yt=null}const Pt={init(e,t){yt?.renderer_init(e,t)},resize(e,t){yt?.renderer_resize(e,t)},begin(e,t){yt&&wt&&(yt.HEAPF32.set(e,wt/4),yt.renderer_begin(wt,t??0))},flush(){yt?.renderer_flush()},end(){yt?.renderer_end()},submitSprites(e){yt&&yt.renderer_submitSprites(e._cpp)},submitSpine(e){yt&&yt.renderer_submitSpine?.(e._cpp)},setStage(e){yt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>yt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){yt?.renderer_releaseTarget(e)},getTargetTexture:e=>yt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>yt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){yt?.renderer_setClearColor?.(e,t,r,s)},getStats:()=>yt?{drawCalls:yt.renderer_getDrawCalls(),triangles:yt.renderer_getTriangles(),sprites:yt.renderer_getSprites(),spine:yt.renderer_getSpine?.()??0,meshes:yt.renderer_getMeshes(),culled:yt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let St=null;function Ct(e){St=e}function Tt(){St=null}const At={enable(){St?.gl_enableErrorCheck(!0)},disable(){St?.gl_enableErrorCheck(!1)},check:e=>St?.gl_checkErrors(e)??0,diagnose(){St?.renderer_diagnose()}},Et=new Map;function Mt(e){Et.delete(e)}class Rt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;Pt.resize(s,n),_t.isInitialized()&&_t.getPassCount()>0&&!_t.isBypassed()&&_t.resize(s,n),Pt.begin(r),Pt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Pt.submitSpine(t),Pt.flush();const i=Et;if(i.size>0){et.begin(r);const e=[];for(const[t,r]of i.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}et.end();for(const t of e)Mt(t)}Pt.end()}}class Ut{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new he,this.resources_=new K;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ut}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ie(this.world_,this.resources_),this.resources_.insert(J,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Tt(),bt(),ft(),lt(),Ae(),Je()}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(J),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(J,r)}}const Ft=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Bt(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function It(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Wt(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,c=s-r,l=o-n;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(s+r)/c,i[14]=-(o+n)/l,i[15]=1,i}function zt(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function Dt(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function kt(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}function $t(e,t){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const n=r.createTexture(t.width,t.height,s,t.pixels.length,1);return e._free(s),n}function Lt(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function Ht(e,t,r,s,n){const o=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=$t(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={},a=null;n&&(a=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),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"])}}(n),i=await async function(e,t,r,s,n){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 c=n.resolvePath(i),l=n.resolvePath(a);try{const s=n.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=n.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=n.readText(i),r=(new TextEncoder).encode(e);d=r.length,h=t._malloc(d+1),t.HEAPU8.set(r,h),t.HEAPU8[h+d]=0}const p=r.loadSkeleton(h,d,s,s.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=Lt(s),m=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=$t(e,o),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,a,r,s));const c=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Me.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=Me.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),l=De(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,k);n&&(n.texture=r[s.data.texture]||0,e.insert(t,k,n))}}}(e.world,r,o,l),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,k);r&&(r.material=n,e.insert(t,k,r))}else if("SpineAnimation"===s.type){const r=e.get(t,V);r&&(r.material=n,e.insert(t,V,r))}}}}(e.world,r,c,l),n&&a){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const c=s.get(o.id);void 0!==c&&(n[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(a,r,i,l);!function(e,t,r,s,n){let o=0;e.setSpineRenderer((e,i)=>{let a=i-o;o=i,(a<=0||a>.5)&&(a=1/60);for(const e in n){const o=n[e];s.update(o,a);const i=s.getMeshBatchCount(o);for(let e=0;e<i;e++){const n=s.getMeshBatchVertexCount(o,e),i=s.getMeshBatchIndexCount(o,e);if(!n||!i)continue;const a=8*n*4,c=2*i,l=r._malloc(a),u=r._malloc(c),h=r._malloc(4),d=r._malloc(4);s.getMeshBatchData(o,e,l,u,h,d);const p=r.HEAPU32[h>>2],f=r.HEAPU32[d>>2],m=new Float32Array(r.HEAPF32.buffer,l,8*n),_=new Uint16Array(r.HEAPU8.buffer,u,i),x=t._malloc(a),g=t._malloc(c);t.HEAPF32.set(m,x>>2),new Uint16Array(t.HEAPU8.buffer,g,i).set(_),t.renderer_submitTriangles(x,n,g,i,p,f,0),t._free(x),t._free(g),r._free(l),r._free(u),r._free(h),r._free(d)}}})}(e,t,n,a,s)}}class Ot{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Nt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Pt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Pt.getTargetTexture(r),width:e.width,height:e.height}},release(e){Pt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Pt.releaseRenderTarget(e._handle),Nt.create({width:t,height:r,depth:!0})),begin(e,t){Pt.begin(t,e._handle)},end(){Pt.end()},getDepthTexture:e=>Pt.getTargetDepthTexture(e._handle)};let Vt=!1;async function Gt(e,t){if(t)return t();return(0,(await import(e)).default)()}const Xt=j({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function jt(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Yt(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}function qt(e,t,r){const s=e.world;if(s.has(r,S)){const e=s.get(r,S);return void t._physics_addBoxShape(r,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(r,C)){const e=s.get(r,C);return void t._physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,T)){const e=s.get(r,T);t._physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}var Kt;y||(y=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await c(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Kt=w,console.log(`[ESEngine] Platform: ${Kt.name}`),exports.App=Ut,exports.AssetPlugin=Ne,exports.AssetServer=He,exports.Assets=Oe,exports.AsyncCache=Le,exports.BodyType=A,exports.BoxCollider=S,exports.Camera=$,exports.Canvas=L,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=te,exports.Draw=et,exports.EntityCommands=ee,exports.GLDebug=At,exports.Geometry=ht,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=v,exports.Input=ce,exports.InputPlugin=le,exports.InputState=ae,exports.LocalTransform=z,exports.Material=Me,exports.MaterialLoader=ze,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=O,exports.Physics=class{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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]}}},exports.PhysicsEvents=Xt,exports.PhysicsPlugin=class{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Xt,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=Gt(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,ne([Y(J)],n=>{const o=s.getEntitiesWithComponents([P,z]),i=new Set;for(const n of o){i.add(n);const o=s.get(n,P),a=s.get(n,z);if(!t.has(n)){if(!o.enabled)continue;const s=jt(a.rotation);r._physics_createBody(n,o.bodyType,a.position.x,a.position.y,s,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),qt(e,r,n),t.add(n)}if(o.bodyType===A.Kinematic){const e=jt(a.rotation);r._physics_setBodyTransform(n,a.position.x,a.position.y,e)}}for(const e of t)i.has(e)||(r._physics_destroyBody(e),t.delete(e));r._physics_step(n.delta),function(e,t){const r=t._physics_getDynamicBodyCount();if(0===r)return;const s=t._physics_getDynamicBodyTransforms(),n=s>>2;for(let s=0;s<r;s++){const r=n+4*s,o=t.HEAPU32[r],i=t.HEAPF32[r+1],a=t.HEAPF32[r+2],c=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const l=e.world.get(o,z);if(!l)continue;l.position.x=i,l.position.y=a;const u=Yt(c);l.rotation.w=u.w,l.rotation.x=u.x,l.rotation.y=u.y,l.rotation.z=u.z}}(e,r),function(e,t){t._physics_collectEvents();const r=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let n=0;n<s;n++){const s=e+6*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4],contactY:t.HEAPF32[s+5]})}}const n=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<o;r++){const s=e+2*r;n.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const i=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let r=0;r<a;r++){const s=e+2*r;i.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let r=0;r<l;r++){const s=e+2*r;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Xt,{collisionEnters:r,collisionExits:n,sensorEnters:i,sensorExits:c})}(e,r)},{name:"PhysicsSystem"})),e.__physicsModule=r});e.__physicsInitPromise=r}},exports.PostProcess=_t,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Ot(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await Ht(this.app_,this.app_.wasmModule,t,s,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([$]);for(const s of r){if(e.get(s,$).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([L]);for(const n of s){const s=e.get(n,L);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,z,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(n,$,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{Q(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=Z,exports.RenderPipeline=Rt,exports.RenderTexture=Nt,exports.Renderer=Pt,exports.Res=Y,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ShaderSources=We,exports.SpineAnimation=V,exports.Sprite=k,exports.SystemRunner=ie,exports.Text=me,exports.TextPlugin=ge,exports.TextRenderer=_e,exports.Time=J,exports.UIRect=xe,exports.Velocity=H,exports.WebAssetProvider=Ot,exports.World=he,exports.WorldTransform=D,exports.addStartupSystem=function(e){oe().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){oe().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){oe().push({schedule:e,system:t})},exports.assetPlugin=Ve,exports.clearDrawCallbacks=function(){Et.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({x:e,y:t,z:r,w:s}),exports.createWebApp=function(e,t){const r=Ut.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ke(e),Te(e),ct(e),pt(e),vt(e),Ct(e);const n=new Rt;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=i(),r=s.entityCount(),c=Bt(s,r+1e3);if(c){const e=c.backgroundColor;Pt.setClearColor(e.x,e.y,e.z,e.w)}const l=function(e,t,r){const s=e.entityCount(),n=s+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=Bt(e,n);if(r){t=It(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const s=t*a;c=Wt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=zt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return kt(c,Dt(i.position.x,i.position.y,i.position.z))}return Ft}(s,e,t),u=(a()-o)/1e3;n.render({registry:{_cpp:s},viewProjection:l,width:e,height:t,elapsed:u})}};return r.addSystemToSchedule(exports.Schedule.Last,c),r.addPlugin(Ve),r.addPlugin(ue),r.addPlugin(ye),r},exports.defineComponent=U,exports.defineResource=j,exports.defineSystem=ne,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const s=M(e,{});return t.set(e,s),B(e,{},!0),s},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=G[e];if(t)return{...t._default};const r=F(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=F,exports.initDrawAPI=Ke,exports.initGLDebugAPI=Ct,exports.initGeometryAPI=ct,exports.initMaterialAPI=Te,exports.initPostProcessAPI=pt,exports.initRendererAPI=vt,exports.inputPlugin=ue,exports.isBuiltinComponent=W,exports.isEditor=function(){return Vt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Vt},exports.isTextureRef=ve,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=$e,exports.loadPhysicsModule=Gt,exports.loadRuntimeScene=Ht,exports.loadSceneData=De,exports.loadSceneWithAssets=ke,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){Et.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Oe);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Ie,exports.setEditorMode=function(e){Vt=e},exports.shutdownDrawAPI=Je,exports.shutdownGLDebugAPI=Tt,exports.shutdownGeometryAPI=lt,exports.shutdownMaterialAPI=Ae,exports.shutdownPostProcessAPI=ft,exports.shutdownRendererAPI=bt,exports.textPlugin=ye,exports.unregisterDrawCallback=Mt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([$]);for(const s of r){const r=e.get(s,$);r&&(r.aspectRatio=t,e.insert(s,$,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=g,exports.wxLoadImage=x,exports.wxLoadImagePixels=async function(e,t=!0){return g(await x(e),t)},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex f33872d68..68866a31f 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 r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(e,t){return new Promise((n,r)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,r={};if(e.header)for(const t of Object.keys(e.header))r[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:r,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=>{r(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 _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function y(e){return new Promise((t,n)=>{m().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function g(e,t="utf-8"){return new Promise((n,r)=>{m().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function v(e,t){return new Promise((n,r)=>{m().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let S=null,b=null;function P(e){return new Promise((t,n)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function C(e,t=!0){const{width:n,height:r}=e,{ctx:s}=function(e,t){return S||(S=wx.createCanvas(),S.width=e,S.height=t,b=S.getContext("2d")),(S.width<e||S.height<t)&&(S.width=Math.max(S.width,e),S.height=Math.max(S.height,t)),{canvas:S,ctx:b}}(n,r);s.clearRect(0,0,n,r),s.save(),t&&(s.translate(0,r),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const i=s.getImageData(0,0,n,r);return{width:n,height:r,pixels:new Uint8Array(i.data.buffer)}}async function T(e,t=!0){return C(await P(e),t)}let E=!1;const M=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return g(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)})}},A=0,R=4294967295,U=(e=0,t=0)=>({x:e,y:t}),F=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),B=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),z=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),I=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const $=W("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),k=W("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=W("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),D=W("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H={Static:0,Kinematic:1,Dynamic:2};let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function j(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function X(e,t){const n=j(),r=n.get(e);if(r)return r;const s=N(e,t);return n.set(e,s),K(e,t,!1),s}function V(e){const t=j(),n=t.get(e);if(n)return n;const r=N(e,{});return t.set(e,r),K(e,{},!0),r}function G(e){return j().get(e)}function q(){j().clear()}function K(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Y(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function J(e){return!0===e._builtin}const Q=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}}),Z=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}}),ee=Y("Sprite",{texture:R,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),te=Y("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),ne=Y("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),re=Y("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=Y("Parent",{entity:0}),ie=Y("Children",{entities:[]}),oe=Y("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),ae={LocalTransform:Q,WorldTransform:Z,Sprite:ee,Camera:te,Canvas:ne,Velocity:re,Parent:se,Children:ie,SpineAnimation:oe,RigidBody:$,BoxCollider:k,CircleCollider:L,CapsuleCollider:D};function ce(e){const t=ae[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let le=0;function ue(e,t){const n=++le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function he(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class pe{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new fe(this.get(e),t=>this.set(e,t))}}const _e=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ye(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function ge(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{ye(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class we{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ye(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function xe(){return{_type:"commands"}}class ve{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=J(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 Se{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ve(this,null)}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var be;!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"}(be||(be={}));let Pe=0;function Ce(e,t,n){const r=++Pe;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:be.Update,system:e})}function Me(e){Te().push({schedule:be.Startup,system:e})}function Ae(e,t){Te().push({schedule:e,system:t})}class Re{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof Se&&e.flush()}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ue{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Fe=ue(new Ue,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ue;e.insertResource(Fe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,r){n.mouseX=t,n.mouseY=r,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(be.First,Ce([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new Be;class Ie{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return J(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return J(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return J(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){J(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,r)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var We,$e,ke;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(We||(We={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}($e||($e={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ke||(ke={}));const Le=X("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:We.Left,verticalAlign:$e.Top,wordWrap:!0,overflow:ke.Visible,lineHeight:1.2,dirty:!0});class De{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===ke.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.height=t}const _=Math.round(255*e.color.x),m=Math.round(255*e.color.y),y=Math.round(255*e.color.z),g=e.color.w;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${y}, ${g})`,s&&e.overflow===ke.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case $e.Top:x=u;break;case $e.Middle:x=(p-w)/2;break;case $e.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case We.Left:r=u;break;case We.Center:r=f/2;break;case We.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ke.Clip&&n.restore();const S=n.getImageData(0,0,f,p),b=new Uint8Array(S.data.buffer),P=this.flipVertically(b,f,p),C=this.module.getResourceManager(),T=this.module._malloc(P.length);this.module.HEAPU8.set(P,T);const E=C.createTexture(f,p,T,P.length,1);return this.module._free(T),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case We.Left:return"left";case We.Center:return"center";case We.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*r,o=(n-1-t)*r;s.set(e.subarray(i,i+r),o)}return s}}const He=X("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Oe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new De(t),r=e.world;e.addSystemToSchedule(be.PreUpdate,Ce([],()=>{const e=r.getEntitiesWithComponents([Le]);for(const t of e){const e=r.get(t,Le);if(!e.dirty)continue;r.has(t,ee)||r.insert(t,ee,{texture:R,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,He)?r.get(t,He):null,i=n.renderForEntity(t,e,s),o=r.get(t,ee);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,ee,o),e.dirty=!1}}))}}const Ne=new Oe;var je;function Xe(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"}(je||(je={}));let Ve=null,Ge=null,qe=1;const Ke=new Map;function Ye(e){Ve=e,Ge=e.getResourceManager(),st()}function Je(){0!==tt&&Ve&&(Ve._free(tt),tt=0),Ke.clear(),qe=1,et=!1,Ge=null,Ve=null}function Qe(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??je.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Ke.set(t,n),t},get:e=>Ke.get(e),setUniform(e,t,n){const r=Ke.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Ke.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ke.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ke.get(e);return t?.blendMode??je.Normal},setDepthTest(e,t){const n=Ke.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ke.get(e);return t?.shader??0},release(e){Ke.delete(e)},isValid:e=>Ke.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??je.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ke.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=qe++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ke.set(n,r),n},toAssetData(e,t){const n=Ke.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=Ke.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const nt=4096;function rt(e){const t=(0===tt&&Ve&&(tt=Ve._malloc(nt)),tt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,r=0;const s=Ve.HEAPU8,i=Ve.HEAPU32,o=Ve.HEAPF32;for(const[a,c]of e){if(n+128>nt)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function st(){if(!Ve||et)return;Ve.materialDataProvider=(e,t,n,r,s)=>{const i=Ke.get(e);if(!i)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[r>>2]=0,void(Ve.HEAPU32[s>>2]=0);Ve.HEAPU32[t>>2]=i.shader,Ve.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=rt(i.uniforms);Ve.HEAPU32[r>>2]=o,Ve.HEAPU32[s>>2]=a},et=!0}const it={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 ot{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:Ze.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function at(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)lt(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function ct(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t);for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}lt(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function lt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,Q,r);break;case"Sprite":e.insert(t,ee,r);break;case"Camera":e.insert(t,te,r);break;case"Canvas":e.insert(t,ne,r);break;case"Text":e.insert(t,Le,r);break;case"SpineAnimation":e.insert(t,oe,r);break;case"UIRect":e.insert(t,He,r);break;default:{const s=G(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function ut(e,t){const n=e.getEntitiesWithComponents([te]);for(const r of n){const n=e.get(r,te);n&&(n.aspectRatio=t,e.insert(r,te,n))}}class ht{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class dt{constructor(e){this.textureCache_=new ht,this.shaderCache_=new ht,this.jsonCache_=new ht,this.textCache_=new ht,this.binaryCache_=new ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await this.fetchText(s);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,r=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return ct(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const r=255/n;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,s)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=ue(null,"Assets");class pt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new dt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new pt;function mt(e,t){const n=e.getResource(ft);n&&n.registerEmbeddedAssets(t)}let yt=null,gt=0,wt=0,xt=0;const vt=new Float32Array(256);function St(e){yt=e,gt=yt._malloc(64),wt=yt._malloc(64),xt=yt._malloc(1024)}function bt(){yt&&(gt&&(yt._free(gt),gt=0),wt&&(yt._free(wt),wt=0),xt&&(yt._free(xt),xt=0)),yt=null}function Pt(){if(!yt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return yt}const Ct={x:1,y:1,z:1,w:1},Tt={begin(e){const t=Pt();t.HEAPF32.set(e,gt/4),t.draw_begin(gt)},end(){Pt().draw_end()},line(e,t,n,r=1){Pt().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rect(e,t,n,r=!0){Pt().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rectOutline(e,t,n,r=1){Pt().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},circle(e,t,n,r=!0,s=32){Pt().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},circleOutline(e,t,n,r=1,s=32){Pt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=Ct){Pt().draw_texture(e.x,e.y,t.x,t.y,n,r.x,r.y,r.z,r.w)},textureRotated(e,t,n,r,s=Ct){Pt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){Pt().draw_setLayer(e)},setDepth(e){Pt().draw_setDepth(e)},getDrawCallCount:()=>yt?yt.draw_getDrawCallCount():0,getPrimitiveCount:()=>yt?yt.draw_getPrimitiveCount():0,setBlendMode(e){Pt().draw_setBlendMode(e)},setDepthTest(e){Pt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=Pt();r.HEAPF32.set(n,wt/4),r.draw_mesh(e,t,wt)},drawMeshWithMaterial(e,t,n){const r=Pt(),s=Ze.get(t);if(!s)return;if(Tt.setBlendMode(s.blendMode),Tt.setDepthTest(s.depthTest),0===s.uniforms.size)return void Tt.drawMesh(e,s.shader,n);r.HEAPF32.set(n,wt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Mt(e);if(!(n<0)){if(Xe(t))vt[i++]=10,vt[i++]=n,vt[i++]=t.slot??o++,vt[i++]=t.textureId;else if("number"==typeof t)vt[i++]=1,vt[i++]=n,vt[i++]=t;else if(Array.isArray(t)){vt[i++]=t.length,vt[i++]=n;for(let e=0;e<t.length;e++)vt[i++]=t[e]}else"w"in t?(vt[i++]=4,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y,vt[i++]=t.z,vt[i++]=t.w):"z"in t?(vt[i++]=3,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y,vt[i++]=t.z):(vt[i++]=2,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(vt.subarray(0,i),xt/4),r.draw_meshWithUniforms(e,s.shader,wt,xt,i)):r.draw_mesh(e,s.shader,wt)}},Et={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Mt(e){return Et[e]??-1}var At;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(At||(At={}));let Rt=null,Ut=0,Ft=0,Bt=0;function zt(e){Rt=e,Ut=Rt._malloc(262144),Ft=Rt._malloc(65536),Bt=Rt._malloc(256)}function It(){Rt&&(Ut&&Rt._free(Ut),Ft&&Rt._free(Ft),Bt&&Rt._free(Bt),Ut=0,Ft=0,Bt=0),Rt=null}function Wt(){if(!Rt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rt}const $t={create(e){const t=Wt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ut/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Bt,s).set(i),t.geometry_init(n,Ut,r,Bt,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ft,r).set(e.indices),t.geometry_setIndices16(n,Ft,r)}else{new Uint32Array(t.HEAPU8.buffer,Ft,r).set(e.indices),t.geometry_setIndices32(n,Ft,r)}}return n},updateVertices(e,t,n=0){const r=Wt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ut/4),r.geometry_updateVertices(e,Ut,s,n)},release(e){e>0&&Wt().geometry_release(e)},isValid:e=>!(!Rt||e<=0)&&Rt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return $t.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:At.Float2},{name:"a_texCoord",type:At.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return $t.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:At.Float2},{name:"a_texCoord",type:At.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return $t.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:At.Float2},{name:"a_texCoord",type:At.Float2}],indices:new Uint16Array(o)})}};let kt=null;function Lt(e){kt=e}function Dt(){kt&&Ot.isInitialized()&&Ot.shutdown(),kt=null}function Ht(){if(!kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return kt}const Ot={init:(e,t)=>Ht().postprocess_init(e,t),shutdown(){Ht().postprocess_shutdown()},resize(e,t){Ht().postprocess_resize(e,t)},addPass:(e,t)=>Ht().postprocess_addPass(e,t),removePass(e){Ht().postprocess_removePass(e)},setEnabled(e,t){Ht().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ht().postprocess_isPassEnabled(e),setUniform(e,t,n){Ht().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Ht().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Ht().postprocess_begin()},end(){Ht().postprocess_end()},getPassCount:()=>Ht().postprocess_getPassCount(),isInitialized:()=>!!kt&&kt.postprocess_isInitialized(),setBypass(e){Ht().postprocess_setBypass(e)},isBypassed:()=>!kt||kt.postprocess_isBypassed(),createBlur:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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")},Nt="#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 jt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(jt||(jt={}));let Xt=null,Vt=0;function Gt(e){Xt=e,Vt=Xt._malloc(64)}function qt(){Xt&&Vt&&(Xt._free(Vt),Vt=0),Xt=null}const Kt={init(e,t){Xt?.renderer_init(e,t)},resize(e,t){Xt?.renderer_resize(e,t)},begin(e,t){Xt&&Vt&&(Xt.HEAPF32.set(e,Vt/4),Xt.renderer_begin(Vt,t??0))},flush(){Xt?.renderer_flush()},end(){Xt?.renderer_end()},submitSprites(e){Xt&&Xt.renderer_submitSprites(e._cpp)},submitSpine(e){Xt&&Xt.renderer_submitSpine?.(e._cpp)},setStage(e){Xt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xt?.renderer_releaseTarget(e)},getTargetTexture:e=>Xt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Xt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>Xt?{drawCalls:Xt.renderer_getDrawCalls(),triangles:Xt.renderer_getTriangles(),sprites:Xt.renderer_getSprites(),spine:Xt.renderer_getSpine?.()??0,meshes:Xt.renderer_getMeshes(),culled:Xt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Yt=null;function Jt(e){Yt=e}function Qt(){Yt=null}const Zt={enable(){Yt?.gl_enableErrorCheck(!0)},disable(){Yt?.gl_enableErrorCheck(!1)},check:e=>Yt?.gl_checkErrors(e)??0,diagnose(){Yt?.renderer_diagnose()}},en=new Map;function tn(e,t){en.set(e,t)}function nn(e){en.delete(e)}function rn(){en.clear()}class sn{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;Kt.resize(r,s),Ot.isInitialized()&&Ot.getPassCount()>0&&!Ot.isBypassed()&&Ot.resize(r,s),Kt.begin(n),Kt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):Kt.submitSpine(t),Kt.flush();const o=en;if(o.size>0){Tt.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Tt.end();for(const t of e)nn(t)}Kt.end()}}class on{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(be.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(be.FixedPreUpdate),this.runSchedule(be.FixedUpdate),this.runSchedule(be.FixedPostUpdate);this.runSchedule(be.PreUpdate),this.runSchedule(be.Update),this.runSchedule(be.PostUpdate),this.runSchedule(be.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Ie,this.resources_=new pe;for(const e of Object.values(be))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new on}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(be.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(be.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Re(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(be.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Qt(),qt(),Dt(),It(),Je(),bt()}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(_e),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(_e,n)}}function an(e,t){const n=on.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),St(e),Ye(e),zt(e),Lt(e),Gt(e),Jt(e);const s=new sn;n.pipeline_=s;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=r.entityCount(),a=un(r,n+1e3);if(a){const e=a.backgroundColor;Kt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const r=e.entityCount(),s=r+1e3;for(let r=0;r<s;r++){if(!e.valid(r)||!e.hasCamera(r)||!e.hasLocalTransform(r))continue;const i=e.getCamera(r);if(!i.isActive)continue;const o=e.getLocalTransform(r),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=un(e,s);if(n){t=hn(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const r=t*a;c=dn(-r,r,-t,t,-i.farPlane,i.farPlane)}else c=fn(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return _n(c,pn(o.position.x,o.position.y,o.position.z))}return ln}(r,e,t),l=(d()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(be.Last,a),n.addPlugin(_t),n.addPlugin(ze),n.addPlugin(Ne),n}function cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function un(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function hn(e,t,n,r,s){const i=e*t/n,o=e;switch(r){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=s;return Math.pow(i,1-e)*Math.pow(o,e)}}}function dn(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function fn(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function pn(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function _n(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}function mn(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function yn(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function gn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function wn(e,t,n,r,s){const i=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=mn(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,i);let o={};s&&(o=await async function(e,t,n,r){const s={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,o=n.data.atlasPath;if(!i||!o)continue;const a=r.resolvePath(i),c=r.resolvePath(o);try{const n=r.readText(o),l=a.endsWith(".skel");yn(t,a),l?t.FS.writeFile(a,r.readBinary(i)):t.FS.writeFile(a,r.readText(i));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;s[i]=u;const h=gn(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const s=d+"/"+h[n];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),o=mn(e,i),a=e.getResourceManager().getTextureGLId(o);t.spine_setAtlasPageTexture(u,n,a,i.width,i.height)}catch{}}}catch{}}return s}(t,s,n,r));const a=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=r[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=Ze.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),c=at(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,ee);s&&(s.texture=n[r.data.texture]||0,e.insert(t,ee,s))}}}(e.world,n,i,c),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,ee);n&&(n.material=s,e.insert(t,ee,n))}else if("SpineAnimation"===r.type){const n=e.get(t,oe);n&&(n.material=s,e.insert(t,oe,n))}}}}(e.world,n,a,c),s){const r=function(e,t,n,r){const s={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.spine_createInstance(o);if(a<0)continue;const c=r.get(i.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,n,o,c);!function(e,t,n,r){let s=0;e.setSpineRenderer((e,i)=>{let o=i-s;s=i,(o<=0||o>.5)&&(o=1/60);for(const e in r){const s=r[e];n.spine_update(s,o);const i=n.spine_getMeshBatchCount(s);for(let e=0;e<i;e++){const r=n.spine_getMeshBatchVertexCount(s,e),i=n.spine_getMeshBatchIndexCount(s,e);if(!r||!i)continue;const o=8*r*4,a=2*i,c=n._malloc(o),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(s,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,l,i),m=t._malloc(o),y=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,y,i).set(_),t.renderer_submitTriangles(m,r,y,i,d,f,0),t._free(m),t._free(y),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,s,r)}}class xn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),r=await n.blob(),s=await createImageBitmap(r),i=new OffscreenCanvas(s.width,s.height).getContext("2d");i.drawImage(s,0,0);const o=i.getImageData(0,0,s.width,s.height);return s.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class vn{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new xn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.module}await wn(this.app_,this.app_.wasmModule,t,n,r),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([te]);for(const r of n){if(e.get(r,te).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([ne]);for(const s of r){const r=e.get(s,ne);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,Q,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,te,o)}}}const Sn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Kt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Kt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Kt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Kt.releaseRenderTarget(e._handle),Sn.create({width:t,height:n,depth:!0})),begin(e,t){Kt.begin(t,e._handle)},end(){Kt.end()},getDepthTexture:e=>Kt.getTargetDepthTexture(e._handle)};let bn=!1;function Pn(e){bn=e}function Cn(){return bn}function Tn(){return!bn}async function En(e,t){if(t)return t();return(0,(await import(e)).default)()}const Mn=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function An(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Rn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Un{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(Mn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=En(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=e.world;e.addSystemToSchedule(be.PostUpdate,Ce([he(_e)],s=>{const i=r.getEntitiesWithComponents([$,Q]),o=new Set;for(const s of i){o.add(s);const i=r.get(s,$),a=r.get(s,Q);if(!t.has(s)){if(!i.enabled)continue;const r=An(a.rotation);n.physics_createBody(s,i.bodyType,a.position.x,a.position.y,r,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation,i.bullet),Fn(e,n,s),t.add(s)}if(i.bodyType===H.Kinematic){const e=An(a.rotation);n.physics_setBodyTransform(s,a.position.x,a.position.y,e)}}for(const e of t)o.has(e)||(n.physics_destroyBody(e),t.delete(e));n.physics_step(s.delta),function(e,t){const n=t.physics_getDynamicBodyCount();if(0===n)return;const r=t.physics_getDynamicBodyTransforms(),s=r>>2;for(let r=0;r<n;r++){const n=s+4*r,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,Q);if(!l)continue;l.position.x=o,l.position.y=a;const u=Rn(c);l.rotation.w=u.w,l.rotation.x=u.x,l.rotation.y=u.y,l.rotation.z=u.z}}(e,n),function(e,t){const n=t.physics_getCollisionEvents(),r=[];for(let e=0;e<n.enters.size();e++){const t=n.enters.get(e);r.push(t)}const s=[];for(let e=0;e<n.exits.size();e++){const t=n.exits.get(e);s.push({entityA:t.entityA,entityB:t.entityB})}const i=[];for(let e=0;e<n.sensorEnters.size();e++)i.push(n.sensorEnters.get(e));const o=[];for(let e=0;e<n.sensorExits.size();e++)o.push(n.sensorExits.get(e));e.insertResource(Mn,{collisionEnters:r,collisionExits:s,sensorEnters:i,sensorExits:o}),n.enters.delete(),n.exits.delete(),n.sensorEnters.delete(),n.sensorExits.delete()}(e,n)},{name:"PhysicsSystem"})),e.__physicsModule=n});e.__physicsInitPromise=n}}function Fn(e,t,n){const r=e.world;if(r.has(n,k)){const e=r.get(n,k);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)}if(r.has(n,L)){const e=r.get(n,L);return void t.physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}if(r.has(n,D)){const e=r.get(n,D);t.physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}}class Bn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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){return this.module_.physics_getLinearVelocity(e)}}var zn;E||(E=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(n,r);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url: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 r=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?n[r++]=s:s<2048?(n[r++]=192|s>>6,n[r++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,n[r++]=240|s>>18,n[r++]=128|s>>12&63,n[r++]=128|s>>6&63,n[r++]=128|63&s):(n[r++]=224|s>>12,n[r++]=128|s>>6&63,n[r++]=128|63&s)}return n.subarray(0,r)}}),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 r=t[e];if(r<128)n+=String.fromCharCode(r),e++;else if(192==(224&r))n+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))n+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=zn=M,console.log(`[ESEngine] Platform: ${zn.name}`);export{on as App,pt as AssetPlugin,dt as AssetServer,ft as Assets,ht as AsyncCache,je as BlendMode,H as BodyType,k as BoxCollider,te as Camera,ne as Canvas,D as CapsuleCollider,ie as Children,L as CircleCollider,xe as Commands,Se as CommandsInstance,At as DataType,Tt as Draw,ve as EntityCommands,Zt as GLDebug,$t as Geometry,A as INVALID_ENTITY,R as INVALID_TEXTURE,Fe as Input,Be as InputPlugin,Ue as InputState,Q as LocalTransform,Ze as Material,ot as MaterialLoader,me as Mut,se as Parent,Bn as Physics,Mn as PhysicsEvents,Un as PhysicsPlugin,Ot as PostProcess,vn as PreviewPlugin,ge as Query,we as QueryInstance,sn as RenderPipeline,jt as RenderStage,Sn as RenderTexture,Kt as Renderer,he as Res,de as ResMut,$ as RigidBody,be as Schedule,it as ShaderSources,oe as SpineAnimation,ee as Sprite,Re as SystemRunner,Le as Text,We as TextAlign,ke as TextOverflow,Oe as TextPlugin,De as TextRenderer,$e as TextVerticalAlign,_e as Time,He as UIRect,re as Velocity,xn as WebAssetProvider,Ie as World,Z as WorldTransform,Me as addStartupSystem,Ee as addSystem,Ae as addSystemToSchedule,_t as assetPlugin,rn as clearDrawCallbacks,q as clearUserComponents,z as color,an as createWebApp,X as defineComponent,ue as defineResource,Ce as defineSystem,V as defineTag,cn as flushPendingSystems,ce as getComponentDefaults,t as getPlatform,r as getPlatformType,G as getUserComponent,St as initDrawAPI,Jt as initGLDebugAPI,zt as initGeometryAPI,Ye as initMaterialAPI,Lt as initPostProcessAPI,Gt as initRendererAPI,ze as inputPlugin,J as isBuiltinComponent,Cn as isEditor,n as isPlatformInitialized,Tn as isRuntime,Xe as isTextureRef,s as isWeChat,i as isWeb,lt as loadComponent,En as loadPhysicsModule,wn as loadRuntimeScene,at as loadSceneData,ct as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,I as quat,tn as registerDrawCallback,mt as registerEmbeddedAssets,st as registerMaterialCallback,Pn as setEditorMode,bt as shutdownDrawAPI,Qt as shutdownGLDebugAPI,It as shutdownGeometryAPI,Je as shutdownMaterialAPI,Dt as shutdownPostProcessAPI,qt as shutdownRendererAPI,Ne as textPlugin,nn as unregisterDrawCallback,ut as updateCameraAspectRatio,U as vec2,F as vec3,B as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,T as wxLoadImagePixels,y as wxReadFile,g as wxReadTextFile,v as wxWriteFile};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(e,t){return new Promise((n,r)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,r={};if(e.header)for(const t of Object.keys(e.header))r[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:r,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=>{r(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 _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,n)=>{m().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,r)=>{m().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function v(e,t){return new Promise((n,r)=>{m().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let b=null,P=null;function S(e){return new Promise((t,n)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function C(e,t=!0){const{width:n,height:r}=e,{ctx:s}=function(e,t){return b||(b=wx.createCanvas(),b.width=e,b.height=t,P=b.getContext("2d")),(b.width<e||b.height<t)&&(b.width=Math.max(b.width,e),b.height=Math.max(b.height,t)),{canvas:b,ctx:P}}(n,r);s.clearRect(0,0,n,r),s.save(),t&&(s.translate(0,r),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const i=s.getImageData(0,0,n,r);return{width:n,height:r,pixels:new Uint8Array(i.data.buffer)}}async function E(e,t=!0){return C(await S(e),t)}let T=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return g(e)}async readTextFile(e){return y(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}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)})}},M=0,R=4294967295,U=(e=0,t=0)=>({x:e,y:t}),F=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),B=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),I=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),z=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const $=W("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),k=W("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),D=W("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=W("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H={Static:0,Kinematic:1,Dynamic:2};let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function j(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function X(e,t){const n=j(),r=n.get(e);if(r)return r;const s=N(e,t);return n.set(e,s),q(e,t,!1),s}function V(e){const t=j(),n=t.get(e);if(n)return n;const r=N(e,{});return t.set(e,r),q(e,{},!0),r}function G(e){return j().get(e)}function Y(){j().clear()}function q(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function J(e){return!0===e._builtin}const Q=K("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Z=K("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ee=K("Sprite",{texture:R,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),te=K("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),ne=K("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),re=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=K("Parent",{entity:0}),ie=K("Children",{entities:[]}),oe=K("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),ae={LocalTransform:Q,WorldTransform:Z,Sprite:ee,Camera:te,Canvas:ne,Velocity:re,Parent:se,Children:ie,SpineAnimation:oe,RigidBody:$,BoxCollider:k,CircleCollider:D,CapsuleCollider:L};function ce(e){const t=ae[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let le=0;function ue(e,t){const n=++le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function he(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class pe{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new fe(this.get(e),t=>this.set(e,t))}}const _e=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function ye(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{ge(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class we{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ge(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function xe(){return{_type:"commands"}}class ve{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=J(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 be{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ve(this,null)}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;!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"}(Pe||(Pe={}));let Se=0;function Ce(e,t,n){const r=++Se;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Te(e){Ee().push({schedule:Pe.Update,system:e})}function Ae(e){Ee().push({schedule:Pe.Startup,system:e})}function Me(e,t){Ee().push({schedule:e,system:t})}class Re{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof be&&e.flush()}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ue{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Fe=ue(new Ue,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ue;e.insertResource(Fe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,r){n.mouseX=t,n.mouseY=r,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Pe.First,Ce([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Be;class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return J(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return J(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return J(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){J(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,r)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var We,$e,ke;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(We||(We={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}($e||($e={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ke||(ke={}));const De=X("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:We.Left,verticalAlign:$e.Top,wordWrap:!0,overflow:ke.Visible,lineHeight:1.2,dirty:!0});class Le{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===ke.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.height=t}const _=Math.round(255*e.color.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===ke.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case $e.Top:x=u;break;case $e.Middle:x=(p-w)/2;break;case $e.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case We.Left:r=u;break;case We.Center:r=f/2;break;case We.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ke.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.flipVertically(P,f,p),C=this.module.getResourceManager(),E=this.module._malloc(S.length);this.module.HEAPU8.set(S,E);const T=C.createTexture(f,p,E,S.length,1);return this.module._free(E),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case We.Left:return"left";case We.Center:return"center";case We.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*r,o=(n-1-t)*r;s.set(e.subarray(i,i+r),o)}return s}}const He=X("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Oe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Le(t),r=e.world;e.addSystemToSchedule(Pe.PreUpdate,Ce([],()=>{const e=r.getEntitiesWithComponents([De]);for(const t of e){const e=r.get(t,De);if(!e.dirty)continue;r.has(t,ee)||r.insert(t,ee,{texture:R,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,He)?r.get(t,He):null,i=n.renderForEntity(t,e,s),o=r.get(t,ee);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,ee,o),e.dirty=!1}}))}}const Ne=new Oe;var je;function Xe(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"}(je||(je={}));let Ve=null,Ge=null,Ye=1;const qe=new Map;function Ke(e){Ve=e,Ge=e.getResourceManager(),st()}function Je(){0!==tt&&Ve&&(Ve._free(tt),tt=0),qe.clear(),Ye=1,et=!1,Ge=null,Ve=null}function Qe(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=Ye++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??je.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return qe.set(t,n),t},get:e=>qe.get(e),setUniform(e,t,n){const r=qe.get(e);r&&r.uniforms.set(t,n)},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??je.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,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??je.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=qe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ye++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return qe.set(n,r),n},toAssetData(e,t){const n=qe.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=qe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const nt=4096;function rt(e){const t=(0===tt&&Ve&&(tt=Ve._malloc(nt)),tt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,r=0;const s=Ve.HEAPU8,i=Ve.HEAPU32,o=Ve.HEAPF32;for(const[a,c]of e){if(n+128>nt)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function st(){if(!Ve||et)return;Ve.materialDataProvider=(e,t,n,r,s)=>{const i=qe.get(e);if(!i)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[r>>2]=0,void(Ve.HEAPU32[s>>2]=0);Ve.HEAPU32[t>>2]=i.shader,Ve.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=rt(i.uniforms);Ve.HEAPU32[r>>2]=o,Ve.HEAPU32[s>>2]=a},et=!0}const it={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 ot{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:Ze.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function at(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)lt(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function ct(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t);for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}lt(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function lt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,Q,r);break;case"Sprite":e.insert(t,ee,r);break;case"Camera":e.insert(t,te,r);break;case"Canvas":e.insert(t,ne,r);break;case"Text":e.insert(t,De,r);break;case"SpineAnimation":e.insert(t,oe,r);break;case"UIRect":e.insert(t,He,r);break;default:{const s=G(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function ut(e,t){const n=e.getEntitiesWithComponents([te]);for(const r of n){const n=e.get(r,te);n&&(n.aspectRatio=t,e.insert(r,te,n))}}class ht{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class dt{constructor(e){this.textureCache_=new ht,this.shaderCache_=new ht,this.jsonCache_=new ht,this.textCache_=new ht,this.binaryCache_=new ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await this.fetchText(s);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,r=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return ct(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const r=255/n;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,s)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=ue(null,"Assets");class pt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new dt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new pt;function mt(e,t){const n=e.getResource(ft);n&&n.registerEmbeddedAssets(t)}let gt=null,yt=0,wt=0,xt=0;const vt=new Float32Array(256);function bt(e){gt=e,yt=gt._malloc(64),wt=gt._malloc(64),xt=gt._malloc(1024)}function Pt(){gt&&(yt&&(gt._free(yt),yt=0),wt&&(gt._free(wt),wt=0),xt&&(gt._free(xt),xt=0)),gt=null}function St(){if(!gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return gt}const Ct={x:1,y:1,z:1,w:1},Et={begin(e){const t=St();t.HEAPF32.set(e,yt/4),t.draw_begin(yt)},end(){St().draw_end()},line(e,t,n,r=1){St().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rect(e,t,n,r=!0){St().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rectOutline(e,t,n,r=1){St().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},circle(e,t,n,r=!0,s=32){St().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},circleOutline(e,t,n,r=1,s=32){St().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=Ct){St().draw_texture(e.x,e.y,t.x,t.y,n,r.x,r.y,r.z,r.w)},textureRotated(e,t,n,r,s=Ct){St().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){St().draw_setLayer(e)},setDepth(e){St().draw_setDepth(e)},getDrawCallCount:()=>gt?gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>gt?gt.draw_getPrimitiveCount():0,setBlendMode(e){St().draw_setBlendMode(e)},setDepthTest(e){St().draw_setDepthTest(e)},drawMesh(e,t,n){const r=St();r.HEAPF32.set(n,wt/4),r.draw_mesh(e,t,wt)},drawMeshWithMaterial(e,t,n){const r=St(),s=Ze.get(t);if(!s)return;if(Et.setBlendMode(s.blendMode),Et.setDepthTest(s.depthTest),0===s.uniforms.size)return void Et.drawMesh(e,s.shader,n);r.HEAPF32.set(n,wt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=At(e);if(!(n<0)){if(Xe(t))vt[i++]=10,vt[i++]=n,vt[i++]=t.slot??o++,vt[i++]=t.textureId;else if("number"==typeof t)vt[i++]=1,vt[i++]=n,vt[i++]=t;else if(Array.isArray(t)){vt[i++]=t.length,vt[i++]=n;for(let e=0;e<t.length;e++)vt[i++]=t[e]}else"w"in t?(vt[i++]=4,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y,vt[i++]=t.z,vt[i++]=t.w):"z"in t?(vt[i++]=3,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y,vt[i++]=t.z):(vt[i++]=2,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(vt.subarray(0,i),xt/4),r.draw_meshWithUniforms(e,s.shader,wt,xt,i)):r.draw_mesh(e,s.shader,wt)}},Tt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function At(e){return Tt[e]??-1}var Mt;!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"}(Mt||(Mt={}));let Rt=null,Ut=0,Ft=0,Bt=0;function It(e){Rt=e,Ut=Rt._malloc(262144),Ft=Rt._malloc(65536),Bt=Rt._malloc(256)}function zt(){Rt&&(Ut&&Rt._free(Ut),Ft&&Rt._free(Ft),Bt&&Rt._free(Bt),Ut=0,Ft=0,Bt=0),Rt=null}function Wt(){if(!Rt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rt}const $t={create(e){const t=Wt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ut/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Bt,s).set(i),t.geometry_init(n,Ut,r,Bt,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ft,r).set(e.indices),t.geometry_setIndices16(n,Ft,r)}else{new Uint32Array(t.HEAPU8.buffer,Ft,r).set(e.indices),t.geometry_setIndices32(n,Ft,r)}}return n},updateVertices(e,t,n=0){const r=Wt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ut/4),r.geometry_updateVertices(e,Ut,s,n)},release(e){e>0&&Wt().geometry_release(e)},isValid:e=>!(!Rt||e<=0)&&Rt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return $t.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return $t.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return $t.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.Float2}],indices:new Uint16Array(o)})}};let kt=null;function Dt(e){kt=e}function Lt(){kt&&Ot.isInitialized()&&Ot.shutdown(),kt=null}function Ht(){if(!kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return kt}const Ot={init:(e,t)=>Ht().postprocess_init(e,t),shutdown(){Ht().postprocess_shutdown()},resize(e,t){Ht().postprocess_resize(e,t)},addPass:(e,t)=>Ht().postprocess_addPass(e,t),removePass(e){Ht().postprocess_removePass(e)},setEnabled(e,t){Ht().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ht().postprocess_isPassEnabled(e),setUniform(e,t,n){Ht().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Ht().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Ht().postprocess_begin()},end(){Ht().postprocess_end()},getPassCount:()=>Ht().postprocess_getPassCount(),isInitialized:()=>!!kt&&kt.postprocess_isInitialized(),setBypass(e){Ht().postprocess_setBypass(e)},isBypassed:()=>!kt||kt.postprocess_isBypassed(),createBlur:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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")},Nt="#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 jt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(jt||(jt={}));let Xt=null,Vt=0;function Gt(e){Xt=e,Vt=Xt._malloc(64)}function Yt(){Xt&&Vt&&(Xt._free(Vt),Vt=0),Xt=null}const qt={init(e,t){Xt?.renderer_init(e,t)},resize(e,t){Xt?.renderer_resize(e,t)},begin(e,t){Xt&&Vt&&(Xt.HEAPF32.set(e,Vt/4),Xt.renderer_begin(Vt,t??0))},flush(){Xt?.renderer_flush()},end(){Xt?.renderer_end()},submitSprites(e){Xt&&Xt.renderer_submitSprites(e._cpp)},submitSpine(e){Xt&&Xt.renderer_submitSpine?.(e._cpp)},setStage(e){Xt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xt?.renderer_releaseTarget(e)},getTargetTexture:e=>Xt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Xt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>Xt?{drawCalls:Xt.renderer_getDrawCalls(),triangles:Xt.renderer_getTriangles(),sprites:Xt.renderer_getSprites(),spine:Xt.renderer_getSpine?.()??0,meshes:Xt.renderer_getMeshes(),culled:Xt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Kt=null;function Jt(e){Kt=e}function Qt(){Kt=null}const Zt={enable(){Kt?.gl_enableErrorCheck(!0)},disable(){Kt?.gl_enableErrorCheck(!1)},check:e=>Kt?.gl_checkErrors(e)??0,diagnose(){Kt?.renderer_diagnose()}},en=new Map;function tn(e,t){en.set(e,t)}function nn(e){en.delete(e)}function rn(){en.clear()}class sn{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;qt.resize(r,s),Ot.isInitialized()&&Ot.getPassCount()>0&&!Ot.isBypassed()&&Ot.resize(r,s),qt.begin(n),qt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):qt.submitSpine(t),qt.flush();const o=en;if(o.size>0){Et.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Et.end();for(const t of e)nn(t)}qt.end()}}class on{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Pe.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Pe.FixedPreUpdate),this.runSchedule(Pe.FixedUpdate),this.runSchedule(Pe.FixedPostUpdate);this.runSchedule(Pe.PreUpdate),this.runSchedule(Pe.Update),this.runSchedule(Pe.PostUpdate),this.runSchedule(Pe.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new pe;for(const e of Object.values(Pe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new on}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Pe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Pe.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Re(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Pe.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Qt(),Yt(),Lt(),zt(),Je(),Pt()}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(_e),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(_e,n)}}function an(e,t){const n=on.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),bt(e),Ke(e),It(e),Dt(e),Gt(e),Jt(e);const s=new sn;n.pipeline_=s;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=r.entityCount(),a=un(r,n+1e3);if(a){const e=a.backgroundColor;qt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const r=e.entityCount(),s=r+1e3;for(let r=0;r<s;r++){if(!e.valid(r)||!e.hasCamera(r)||!e.hasLocalTransform(r))continue;const i=e.getCamera(r);if(!i.isActive)continue;const o=e.getLocalTransform(r),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=un(e,s);if(n){t=hn(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const r=t*a;c=dn(-r,r,-t,t,-i.farPlane,i.farPlane)}else c=fn(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return _n(c,pn(o.position.x,o.position.y,o.position.z))}return ln}(r,e,t),l=(d()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(Pe.Last,a),n.addPlugin(_t),n.addPlugin(Ie),n.addPlugin(Ne),n}function cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function un(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function hn(e,t,n,r,s){const i=e*t/n,o=e;switch(r){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=s;return Math.pow(i,1-e)*Math.pow(o,e)}}}function dn(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function fn(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function pn(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function _n(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}function mn(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function gn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function yn(e,t,n,r,s){const i=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=mn(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,i);let o={},a=null;s&&(a=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),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"])}}(s),o=await async function(e,t,n,r,s){const i={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,a=r.data.atlasPath;if(!o||!a)continue;const c=s.resolvePath(o),l=s.resolvePath(a);try{const r=s.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=s.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.readText(o),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,r,r.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=gn(r),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const r=_+"/"+p[t];try{const i=s.loadPixelsRaw?await s.loadPixelsRaw(r):await s.loadPixels(r),o=mn(e,i),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,s,a,n,r));const c=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=r[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=Ze.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),l=at(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,ee);s&&(s.texture=n[r.data.texture]||0,e.insert(t,ee,s))}}}(e.world,n,i,l),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,ee);n&&(n.material=s,e.insert(t,ee,n))}else if("SpineAnimation"===r.type){const n=e.get(t,oe);n&&(n.material=s,e.insert(t,oe,n))}}}}(e.world,n,c,l),s&&a){const r=function(e,t,n,r){const s={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=r.get(i.id);void 0!==c&&(s[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return s}(a,n,o,l);!function(e,t,n,r,s){let i=0;e.setSpineRenderer((e,o)=>{let a=o-i;i=o,(a<=0||a>.5)&&(a=1/60);for(const e in s){const i=s[e];r.update(i,a);const o=r.getMeshBatchCount(i);for(let e=0;e<o;e++){const s=r.getMeshBatchVertexCount(i,e),o=r.getMeshBatchIndexCount(i,e);if(!s||!o)continue;const a=8*s*4,c=2*o,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),d=n._malloc(4);r.getMeshBatchData(i,e,l,u,h,d);const f=n.HEAPU32[h>>2],p=n.HEAPU32[d>>2],_=new Float32Array(n.HEAPF32.buffer,l,8*s),m=new Uint16Array(n.HEAPU8.buffer,u,o),g=t._malloc(a),y=t._malloc(c);t.HEAPF32.set(_,g>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(m),t.renderer_submitTriangles(g,s,y,o,f,p,0),t._free(g),t._free(y),n._free(l),n._free(u),n._free(h),n._free(d)}}})}(e,t,s,a,r)}}class wn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),r=await n.blob(),s=await createImageBitmap(r),i=new OffscreenCanvas(s.width,s.height).getContext("2d");i.drawImage(s,0,0);const o=i.getImageData(0,0,s.width,s.height);return s.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class xn{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new wn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await yn(this.app_,this.app_.wasmModule,t,n,r),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([te]);for(const r of n){if(e.get(r,te).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([ne]);for(const s of r){const r=e.get(s,ne);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,Q,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,te,o)}}}const vn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=qt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:qt.getTargetTexture(n),width:e.width,height:e.height}},release(e){qt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(qt.releaseRenderTarget(e._handle),vn.create({width:t,height:n,depth:!0})),begin(e,t){qt.begin(t,e._handle)},end(){qt.end()},getDepthTexture:e=>qt.getTargetDepthTexture(e._handle)};let bn=!1;function Pn(e){bn=e}function Sn(){return bn}function Cn(){return!bn}async function En(e,t){if(t)return t();return(0,(await import(e)).default)()}const Tn=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function An(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Mn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Rn{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(Tn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=En(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=e.world;e.addSystemToSchedule(Pe.PostUpdate,Ce([he(_e)],s=>{const i=r.getEntitiesWithComponents([$,Q]),o=new Set;for(const s of i){o.add(s);const i=r.get(s,$),a=r.get(s,Q);if(!t.has(s)){if(!i.enabled)continue;const r=An(a.rotation);n._physics_createBody(s,i.bodyType,a.position.x,a.position.y,r,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),Un(e,n,s),t.add(s)}if(i.bodyType===H.Kinematic){const e=An(a.rotation);n._physics_setBodyTransform(s,a.position.x,a.position.y,e)}}for(const e of t)o.has(e)||(n._physics_destroyBody(e),t.delete(e));n._physics_step(s.delta),function(e,t){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),s=r>>2;for(let r=0;r<n;r++){const n=s+4*r,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,Q);if(!l)continue;l.position.x=o,l.position.y=a;const u=Mn(c);l.rotation.w=u.w,l.rotation.x=u.x,l.rotation.y=u.y,l.rotation.z=u.z}}(e,n),function(e,t){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let s=0;s<r;s++){const r=e+6*s;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],contactY:t.HEAPF32[r+5]})}}const s=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const r=e+2*n;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const o=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<a;n++){const r=e+2*n;o.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<l;n++){const r=e+2*n;c.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(Tn,{collisionEnters:n,collisionExits:s,sensorEnters:o,sensorExits:c})}(e,n)},{name:"PhysicsSystem"})),e.__physicsModule=n});e.__physicsInitPromise=n}}function Un(e,t,n){const r=e.world;if(r.has(n,k)){const e=r.get(n,k);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(r.has(n,D)){const e=r.get(n,D);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(r.has(n,L)){const e=r.get(n,L);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 Fn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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]}}}var Bn;T||(T=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(n,r);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url: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 r=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?n[r++]=s:s<2048?(n[r++]=192|s>>6,n[r++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,n[r++]=240|s>>18,n[r++]=128|s>>12&63,n[r++]=128|s>>6&63,n[r++]=128|63&s):(n[r++]=224|s>>12,n[r++]=128|s>>6&63,n[r++]=128|63&s)}return n.subarray(0,r)}}),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 r=t[e];if(r<128)n+=String.fromCharCode(r),e++;else if(192==(224&r))n+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))n+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Bn=A,console.log(`[ESEngine] Platform: ${Bn.name}`);export{on as App,pt as AssetPlugin,dt as AssetServer,ft as Assets,ht as AsyncCache,je as BlendMode,H as BodyType,k as BoxCollider,te as Camera,ne as Canvas,L as CapsuleCollider,ie as Children,D as CircleCollider,xe as Commands,be as CommandsInstance,Mt as DataType,Et as Draw,ve as EntityCommands,Zt as GLDebug,$t as Geometry,M as INVALID_ENTITY,R as INVALID_TEXTURE,Fe as Input,Be as InputPlugin,Ue as InputState,Q as LocalTransform,Ze as Material,ot as MaterialLoader,me as Mut,se as Parent,Fn as Physics,Tn as PhysicsEvents,Rn as PhysicsPlugin,Ot as PostProcess,xn as PreviewPlugin,ye as Query,we as QueryInstance,sn as RenderPipeline,jt as RenderStage,vn as RenderTexture,qt as Renderer,he as Res,de as ResMut,$ as RigidBody,Pe as Schedule,it as ShaderSources,oe as SpineAnimation,ee as Sprite,Re as SystemRunner,De as Text,We as TextAlign,ke as TextOverflow,Oe as TextPlugin,Le as TextRenderer,$e as TextVerticalAlign,_e as Time,He as UIRect,re as Velocity,wn as WebAssetProvider,ze as World,Z as WorldTransform,Ae as addStartupSystem,Te as addSystem,Me as addSystemToSchedule,_t as assetPlugin,rn as clearDrawCallbacks,Y as clearUserComponents,I as color,an as createWebApp,X as defineComponent,ue as defineResource,Ce as defineSystem,V as defineTag,cn as flushPendingSystems,ce as getComponentDefaults,t as getPlatform,r as getPlatformType,G as getUserComponent,bt as initDrawAPI,Jt as initGLDebugAPI,It as initGeometryAPI,Ke as initMaterialAPI,Dt as initPostProcessAPI,Gt as initRendererAPI,Ie as inputPlugin,J as isBuiltinComponent,Sn as isEditor,n as isPlatformInitialized,Cn as isRuntime,Xe as isTextureRef,s as isWeChat,i as isWeb,lt as loadComponent,En as loadPhysicsModule,yn as loadRuntimeScene,at as loadSceneData,ct as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,z as quat,tn as registerDrawCallback,mt as registerEmbeddedAssets,st as registerMaterialCallback,Pn as setEditorMode,Pt as shutdownDrawAPI,Qt as shutdownGLDebugAPI,zt as shutdownGeometryAPI,Je as shutdownMaterialAPI,Lt as shutdownPostProcessAPI,Yt as shutdownRendererAPI,Ne as textPlugin,nn as unregisterDrawCallback,ut as updateCameraAspectRatio,U as vec2,F as vec3,B as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,E as wxLoadImagePixels,g as wxReadFile,y as wxReadTextFile,v as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 0c0cae907..d010620ba 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1148,38 +1148,34 @@ declare function registerEmbeddedAssets(app: App, assets: Record<string, string>* @brief Loads and initializes the standalone Spine WASM module*/interface SpineWasmModule {- spine_loadSkeleton(skelPath: string, atlasText: string, atlasLen: number, isBinary: boolean): number;- spine_unloadSkeleton(handle: number): void;- spine_getAtlasPageCount(handle: number): number;- spine_getAtlasPageTextureName(handle: number, pageIndex: number): string;- spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;- spine_createInstance(skeletonHandle: number): number;- spine_destroyInstance(instanceId: number): void;- spine_playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;- spine_addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;- spine_setSkin(instanceId: number, name: string): void;- spine_update(instanceId: number, dt: number): void;- spine_getAnimations(instanceId: number): string;- spine_getSkins(instanceId: number): string;- spine_getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;- spine_getBoneRotation(instanceId: number, bone: string): number;- spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;- spine_getMeshBatchCount(instanceId: number): number;- spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;- spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;- spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;+ _spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;+ _spine_unloadSkeleton(handle: number): void;+ _spine_getAtlasPageCount(handle: number): number;+ _spine_getAtlasPageTextureName(handle: number, pageIndex: number): number;+ _spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;+ _spine_createInstance(skeletonHandle: number): number;+ _spine_destroyInstance(instanceId: number): void;+ _spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;+ _spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;+ _spine_setSkin(instanceId: number, name: number): void;+ _spine_update(instanceId: number, dt: number): void;+ _spine_getAnimations(instanceId: number): number;+ _spine_getSkins(instanceId: number): number;+ _spine_getBonePosition(instanceId: number, bone: number, outXPtr: number, outYPtr: number): number;+ _spine_getBoneRotation(instanceId: number, bone: number): number;+ _spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;+ _spine_getMeshBatchCount(instanceId: number): number;+ _spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;+ _spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;+ _spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;+ cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;+ UTF8ToString(ptr: number): string;+ stringToNewUTF8(str: string): number;HEAPF32: Float32Array;HEAPU8: Uint8Array;HEAPU32: Uint32Array;_malloc(size: number): number;_free(ptr: number): void;- FS: {- writeFile(path: string, data: string | Uint8Array): void;- mkdirTree(path: string): void;- analyzePath(path: string): {- exists: boolean;- };- };}/**@@ -1748,58 +1744,40 @@ declare function isRuntime(): boolean;/*** @file PhysicsModuleLoader.ts- * @brief Loads and initializes the standalone Physics WASM module+ * @brief Loads and initializes the Physics WASM module (standalone or side module)*/interface PhysicsWasmModule {- physics_init(gx: number, gy: number, timestep: number, substeps: number): void;- physics_shutdown(): void;- physics_createBody(entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: boolean, bullet: boolean): void;- physics_destroyBody(entityId: number): void;- physics_hasBody(entityId: number): boolean;- physics_addBoxShape(entityId: number, halfW: number, halfH: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: boolean): void;- physics_addCircleShape(entityId: number, radius: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: boolean): void;- physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: boolean): void;- physics_step(dt: number): void;- physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;- physics_getDynamicBodyCount(): number;- physics_getDynamicBodyTransforms(): number;- physics_getCollisionEvents(): CollisionEventsRaw;- physics_applyForce(entityId: number, forceX: number, forceY: number): void;- physics_applyImpulse(entityId: number, impulseX: number, impulseY: number): void;- physics_setLinearVelocity(entityId: number, vx: number, vy: number): void;- physics_getLinearVelocity(entityId: number): {- x: number;- y: number;- };+ _physics_init(gx: number, gy: number, timestep: number, substeps: number): void;+ _physics_shutdown(): void;+ _physics_createBody(entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number): void;+ _physics_destroyBody(entityId: number): void;+ _physics_hasBody(entityId: number): number;+ _physics_addBoxShape(entityId: number, halfW: number, halfH: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;+ _physics_addCircleShape(entityId: number, radius: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;+ _physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;+ _physics_step(dt: number): void;+ _physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;+ _physics_getDynamicBodyCount(): number;+ _physics_getDynamicBodyTransforms(): number;+ _physics_collectEvents(): void;+ _physics_getCollisionEnterCount(): number;+ _physics_getCollisionEnterBuffer(): number;+ _physics_getCollisionExitCount(): number;+ _physics_getCollisionExitBuffer(): number;+ _physics_getSensorEnterCount(): number;+ _physics_getSensorEnterBuffer(): number;+ _physics_getSensorExitCount(): number;+ _physics_getSensorExitBuffer(): number;+ _physics_applyForce(entityId: number, forceX: number, forceY: number): void;+ _physics_applyImpulse(entityId: number, impulseX: number, impulseY: number): void;+ _physics_setLinearVelocity(entityId: number, vx: number, vy: number): void;+ _physics_getLinearVelocity(entityId: number): number;HEAPF32: Float32Array;HEAPU8: Uint8Array;HEAPU32: Uint32Array;_malloc(size: number): number;_free(ptr: number): void;}-interface EmscriptenVector<T> {- size(): number;- get(index: number): T;- delete(): void;-}-interface CollisionEventRaw {- entityA: number;- entityB: number;- normalX: number;- normalY: number;- contactX: number;- contactY: number;-}-interface SensorEventRaw {- sensorEntity: number;- visitorEntity: number;-}-interface CollisionEventsRaw {- enters: EmscriptenVector<CollisionEventRaw>;- exits: EmscriptenVector<CollisionEventRaw>;- sensorEnters: EmscriptenVector<SensorEventRaw>;- sensorExits: EmscriptenVector<SensorEventRaw>;-}type PhysicsModuleFactory = (config?: Record<string, unknown>) => Promise<PhysicsWasmModule>;declare function loadPhysicsModule(wasmUrl: string, factory?: PhysicsModuleFactory): Promise<PhysicsWasmModule>;diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex f22210a34..9ac36075b 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 i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),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){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=4294967295,m=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),g=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),w=(e=1,t=1,n=1,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function v(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const S=v("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=v("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=v("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),b=v("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T={Static:0,Kinematic:1,Dynamic:2};let E=0;function M(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function A(e,t){const n=R(),s=n.get(e);if(s)return s;const r=M(e,t);return n.set(e,r),B(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=M(e,{});return t.set(e,s),B(e,{},!0),s}function F(e){return R().get(e)}function z(){R().clear()}function B(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function L(e){return!0===e._builtin}const k=I("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=I("Sprite",{texture:_,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),W=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),H=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),O=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=I("Parent",{entity:0}),j=I("Children",{entities:[]}),V=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),X={LocalTransform:k,WorldTransform:$,Sprite:D,Camera:W,Canvas:H,Velocity:O,Parent:N,Children:j,SpineAnimation:V,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:b};function G(e){const t=X[e];if(t)return{...t._default};const n=F(e);return n?{...n._default}:null}let Y=0;function K(e,t){const n=++Y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function q(e){return{_type:"res",_resource:e}}function J(e){return{_type:"res_mut",_resource:e}}class Q{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 Z{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 Q(this.get(e),t=>this.set(e,t))}}const ee=K({delta:0,elapsed:0,frameCount:0},"Time");function te(e){return{_type:"mut",_component:e}}function ne(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function se(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class re{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ne(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:s}=this.descriptor_,r=e.map(e=>this.getActualComponent(e)),i=[...r,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of s)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=r.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:r[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function ie(){return{_type:"commands"}}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 n;return n=L(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 ae{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new oe(this,null)}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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ce;!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"}(ce||(ce={}));let le=0;function ue(e,t,n){const s=++le;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function he(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function de(e){he().push({schedule:ce.Update,system:e})}function fe(e){he().push({schedule:ce.Startup,system:e})}function pe(e,t){he().push({schedule:e,system:t})}class _e{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof ae&&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 ae(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ye=K(new me,"Input");class ge{constructor(e){this.target_=e??null}build(e){const n=new me;e.insertResource(ye,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(ce.First,ue([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const we=new ge;class xe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return L(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return L(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return L(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){L(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,s)}return s}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);return this.getStorage(t).set(e,s),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)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let s=!0;for(const t of e)if(!this.has(n,t)){s=!1;break}s&&t.push(n)}return t}}var ve,Se,Pe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ve||(ve={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Se||(Se={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Pe||(Pe={}));const Ce=A("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:ve.Left,verticalAlign:Se.Top,wordWrap:!0,overflow:Pe.Visible,lineHeight:1.2,dirty:!0});class be{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,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===Pe.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(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 _=Math.round(255*e.color.x),m=Math.round(255*e.color.y),y=Math.round(255*e.color.z),g=e.color.w;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}, ${y}, ${g})`,r&&e.overflow===Pe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case Se.Top:x=u;break;case Se.Middle:x=(p-w)/2;break;case Se.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let s;switch(e.align){case ve.Left:s=u;break;case ve.Center:s=f/2;break;case ve.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Pe.Clip&&n.restore();const S=n.getImageData(0,0,f,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),b=this.module.getResourceManager(),T=this.module._malloc(C.length);this.module.HEAPU8.set(C,T);const E=b.createTexture(f,p,T,C.length,1);return this.module._free(T),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let 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)}}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 ve.Left:return"left";case ve.Center:return"center";case ve.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const s=4*t,r=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*s,o=(n-1-t)*s;r.set(e.subarray(i,i+s),o)}return r}}const Te=A("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Ee{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new be(t),s=e.world;e.addSystemToSchedule(ce.PreUpdate,ue([],()=>{const e=s.getEntitiesWithComponents([Ce]);for(const t of e){const e=s.get(t,Ce);if(!e.dirty)continue;s.has(t,D)||s.insert(t,D,{texture:_,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const r=s.has(t,Te)?s.get(t,Te):null,i=n.renderForEntity(t,e,r),o=s.get(t,D);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},s.insert(t,D,o),e.dirty=!1}}))}}const Me=new Ee;var Re;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"}(Re||(Re={}));let Ue=null,Fe=null,ze=1;const Be=new Map;function Ie(e){Ue=e,Fe=e.getResourceManager(),Ne()}function Le(){0!==We&&Ue&&(Ue._free(We),We=0),Be.clear(),ze=1,De=!1,Fe=null,Ue=null}function ke(){if(!Fe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Fe}const $e={createShader:(e,t)=>ke().createShader(e,t),releaseShader(e){e>0&&ke().releaseShader(e)},create(e){const t=ze++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Re.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Be.set(t,n),t},get:e=>Be.get(e),setUniform(e,t,n){const s=Be.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=Be.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Be.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Be.get(e);return t?.blendMode??Re.Normal},setDepthTest(e,t){const n=Be.get(e);n&&(n.depthTest=t)},getShader(e){const t=Be.get(e);return t?.shader??0},release(e){Be.delete(e)},isValid:e=>Be.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;"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??Re.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Be.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ze++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Be.set(n,s),n},toAssetData(e,t){const n=Be.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=Be.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let De=!1,We=0;const He=4096;function Oe(e){const t=(0===We&&Ue&&(We=Ue._malloc(He)),We);if(0===t||!Ue)return{ptr:0,count:0};let n=0,s=0;const r=Ue.HEAPU8,i=Ue.HEAPU32,o=Ue.HEAPF32;for(const[a,c]of e){if(n+128>He)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ne(){if(!Ue||De)return;Ue.materialDataProvider=(e,t,n,s,r)=>{const i=Be.get(e);if(!i)return Ue.HEAPU32[t>>2]=0,Ue.HEAPU32[n>>2]=0,Ue.HEAPU32[s>>2]=0,void(Ue.HEAPU32[r>>2]=0);Ue.HEAPU32[t>>2]=i.shader,Ue.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Oe(i.uniforms);Ue.HEAPU32[s>>2]=o,Ue.HEAPU32[r>>2]=a},De=!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 l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),i=await this.shaderLoader_.load(r);return{handle:$e.createFromAsset(s,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Xe(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t);for(const n of s.components)Ye(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 Ge(e,t,n){const s=new Map,r=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();s.set(o.id,t);for(const s of o.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,i.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("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await r.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ye(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 Ye(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,k,s);break;case"Sprite":e.insert(t,D,s);break;case"Camera":e.insert(t,W,s);break;case"Canvas":e.insert(t,H,s);break;case"Text":e.insert(t,Ce,s);break;case"SpineAnimation":e.insert(t,V,s);break;case"UIRect":e.insert(t,Te,s);break;default:{const r=F(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ke(e,t){const n=e.getEntitiesWithComponents([W]);for(const s of n){const n=e.get(s,W);n&&(n.aspectRatio=t,e.insert(s,W,n))}}class qe{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Je{constructor(e){this.textureCache_=new qe,this.shaderCache_=new qe,this.jsonCache_=new qe,this.textCache_=new qe,this.binaryCache_=new qe,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Ve(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const 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);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 Ge(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>r(new Error(`Failed to load image: ${e}`)),i.src=s})}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 i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,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_.save(),s&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const r=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const 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;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return $e.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await o(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 Qe=K(null,"Assets");class Ze{build(e){const t=e.wasmModule;t?e.insertResource(Qe,new Je(t)):console.warn("AssetPlugin: No WASM module available")}}const et=new Ze;function tt(e,t){const n=e.getResource(Qe);n&&n.registerEmbeddedAssets(t)}let nt=null,st=0,rt=0,it=0;const ot=new Float32Array(256);function at(e){nt=e,st=nt._malloc(64),rt=nt._malloc(64),it=nt._malloc(1024)}function ct(){nt&&(st&&(nt._free(st),st=0),rt&&(nt._free(rt),rt=0),it&&(nt._free(it),it=0)),nt=null}function lt(){if(!nt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return nt}const ut={x:1,y:1,z:1,w:1},ht={begin(e){const t=lt();t.HEAPF32.set(e,st/4),t.draw_begin(st)},end(){lt().draw_end()},line(e,t,n,s=1){lt().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},rect(e,t,n,s=!0){lt().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},rectOutline(e,t,n,s=1){lt().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},circle(e,t,n,s=!0,r=32){lt().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,s,r)},circleOutline(e,t,n,s=1,r=32){lt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,s,r)},texture(e,t,n,s=ut){lt().draw_texture(e.x,e.y,t.x,t.y,n,s.x,s.y,s.z,s.w)},textureRotated(e,t,n,s,r=ut){lt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.x,r.y,r.z,r.w)},setLayer(e){lt().draw_setLayer(e)},setDepth(e){lt().draw_setDepth(e)},getDrawCallCount:()=>nt?nt.draw_getDrawCallCount():0,getPrimitiveCount:()=>nt?nt.draw_getPrimitiveCount():0,setBlendMode(e){lt().draw_setBlendMode(e)},setDepthTest(e){lt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=lt();s.HEAPF32.set(n,rt/4),s.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,n){const s=lt(),r=$e.get(t);if(!r)return;if(ht.setBlendMode(r.blendMode),ht.setDepthTest(r.depthTest),0===r.uniforms.size)return void ht.drawMesh(e,r.shader,n);s.HEAPF32.set(n,rt/4);let i=0,o=0;for(const[e,t]of r.uniforms){const n=ft(e);if(!(n<0)){if(Ae(t))ot[i++]=10,ot[i++]=n,ot[i++]=t.slot??o++,ot[i++]=t.textureId;else if("number"==typeof t)ot[i++]=1,ot[i++]=n,ot[i++]=t;else if(Array.isArray(t)){ot[i++]=t.length,ot[i++]=n;for(let e=0;e<t.length;e++)ot[i++]=t[e]}else"w"in t?(ot[i++]=4,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z,ot[i++]=t.w):"z"in t?(ot[i++]=3,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z):(ot[i++]=2,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(s.HEAPF32.set(ot.subarray(0,i),it/4),s.draw_meshWithUniforms(e,r.shader,rt,it,i)):s.draw_mesh(e,r.shader,rt)}},dt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ft(e){return dt[e]??-1}var pt;!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"}(pt||(pt={}));let _t=null,mt=0,yt=0,gt=0;function wt(e){_t=e,mt=_t._malloc(262144),yt=_t._malloc(65536),gt=_t._malloc(256)}function xt(){_t&&(mt&&_t._free(mt),yt&&_t._free(yt),gt&&_t._free(gt),mt=0,yt=0,gt=0),_t=null}function vt(){if(!_t)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return _t}const St={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,mt/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,gt,r).set(i),t.geometry_init(n,mt,s,gt,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,yt,s).set(e.indices),t.geometry_setIndices16(n,yt,s)}else{new Uint32Array(t.HEAPU8.buffer,yt,s).set(e.indices),t.geometry_setIndices32(n,yt,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,mt/4),s.geometry_updateVertices(e,mt,r,n)},release(e){e>0&&vt().geometry_release(e)},isValid:e=>!(!_t||e<=0)&&_t.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return St.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:pt.Float2},{name:"a_texCoord",type:pt.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,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return St.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.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 i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(r-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return St.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.Float2}],indices:new Uint16Array(o)})}};let Pt=null;function Ct(e){Pt=e}function bt(){Pt&&Et.isInitialized()&&Et.shutdown(),Pt=null}function Tt(){if(!Pt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pt}const Et={init:(e,t)=>Tt().postprocess_init(e,t),shutdown(){Tt().postprocess_shutdown()},resize(e,t){Tt().postprocess_resize(e,t)},addPass:(e,t)=>Tt().postprocess_addPass(e,t),removePass(e){Tt().postprocess_removePass(e)},setEnabled(e,t){Tt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Tt().postprocess_isPassEnabled(e),setUniform(e,t,n){Tt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Tt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Tt().postprocess_begin()},end(){Tt().postprocess_end()},getPassCount:()=>Tt().postprocess_getPassCount(),isInitialized:()=>!!Pt&&Pt.postprocess_isInitialized(),setBypass(e){Tt().postprocess_setBypass(e)},isBypassed:()=>!Pt||Pt.postprocess_isBypassed(),createBlur:()=>$e.createShader(Mt,"#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(Mt,"#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(Mt,"#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(Mt,"#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")},Mt="#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 Rt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rt||(Rt={}));let At=null,Ut=0;function Ft(e){At=e,Ut=At._malloc(64)}function zt(){At&&Ut&&(At._free(Ut),Ut=0),At=null}const Bt={init(e,t){At?.renderer_init(e,t)},resize(e,t){At?.renderer_resize(e,t)},begin(e,t){At&&Ut&&(At.HEAPF32.set(e,Ut/4),At.renderer_begin(Ut,t??0))},flush(){At?.renderer_flush()},end(){At?.renderer_end()},submitSprites(e){At&&At.renderer_submitSprites(e._cpp)},submitSpine(e){At&&At.renderer_submitSpine?.(e._cpp)},setStage(e){At?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>At?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){At?.renderer_releaseTarget(e)},getTargetTexture:e=>At?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>At?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){At?.renderer_setClearColor?.(e,t,n,s)},getStats:()=>At?{drawCalls:At.renderer_getDrawCalls(),triangles:At.renderer_getTriangles(),sprites:At.renderer_getSprites(),spine:At.renderer_getSpine?.()??0,meshes:At.renderer_getMeshes(),culled:At.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let It=null;function Lt(e){It=e}function kt(){It=null}const $t={enable(){It?.gl_enableErrorCheck(!0)},disable(){It?.gl_enableErrorCheck(!1)},check:e=>It?.gl_checkErrors(e)??0,diagnose(){It?.renderer_diagnose()}},Dt=new Map;function Wt(e,t){Dt.set(e,t)}function Ht(e){Dt.delete(e)}function Ot(){Dt.clear()}class Nt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;Bt.resize(s,r),Et.isInitialized()&&Et.getPassCount()>0&&!Et.isBypassed()&&Et.resize(s,r),Bt.begin(n),Bt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):Bt.submitSpine(t),Bt.flush();const o=Dt;if(o.size>0){ht.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}ht.end();for(const t of e)Ht(t)}Bt.end()}}class jt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(ce.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ce.FixedPreUpdate),this.runSchedule(ce.FixedUpdate),this.runSchedule(ce.FixedPostUpdate);this.runSchedule(ce.PreUpdate),this.runSchedule(ce.Update),this.runSchedule(ce.PostUpdate),this.runSchedule(ce.Last),requestAnimationFrame(this.mainLoop)},this.world_=new xe,this.resources_=new Z;for(const e of Object.values(ce))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new jt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ce.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ce.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new _e(this.world_,this.resources_),this.resources_.insert(ee,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ce.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,kt(),zt(),bt(),xt(),Le(),ct()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(ee),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(ee,n)}}function Vt(e,t){const n=jt.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),at(e),Ie(e),wt(e),Ct(e),Ft(e),Lt(e);const r=new Nt;n.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=s.entityCount(),a=Yt(s,n+1e3);if(a){const e=a.backgroundColor;Bt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const s=e.entityCount(),r=s+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const i=e.getCamera(s);if(!i.isActive)continue;const o=e.getLocalTransform(s),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=Yt(e,r);if(n){t=Kt(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=qt(-s,s,-t,t,-i.farPlane,i.farPlane)}else c=Jt(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return Zt(c,Qt(o.position.x,o.position.y,o.position.z))}return Gt}(s,e,t),l=(d()-i)/1e3;r.render({registry:{_cpp:s},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(ce.Last,a),n.addPlugin(et),n.addPlugin(we),n.addPlugin(Me),n}function Xt(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 Gt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yt(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Kt(e,t,n,s,r){const i=e*t/n,o=e;switch(s){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}}}function qt(e,t,n,s,r,i){const o=new Float32Array(16),a=t-e,c=s-n,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(s+n)/c,o[14]=-(i+r)/l,o[15]=1,o}function Jt(e,t,n,s){const r=new Float32Array(16),i=1/Math.tan(e/2),o=n-s;return r[0]=i/t,r[5]=i,r[10]=(s+n)/o,r[11]=-1,r[14]=2*s*n/o,r}function Qt(e,t,n){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-n,s}function Zt(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}function en(e,t){const n=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const r=n.createTexture(t.width,t.height,s,t.pixels.length,1);return e._free(s),r}function tn(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function nn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function sn(e,t,n,s,r){const i=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]=en(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,i);let o={};r&&(o=await async function(e,t,n,s){const r={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,o=n.data.atlasPath;if(!i||!o)continue;const a=s.resolvePath(i),c=s.resolvePath(o);try{const n=s.readText(o),l=a.endsWith(".skel");tn(t,a),l?t.FS.writeFile(a,s.readBinary(i)):t.FS.writeFile(a,s.readText(i));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;r[i]=u;const h=nn(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const r=d+"/"+h[n];try{const i=s.loadPixelsRaw?await s.loadPixelsRaw(r):await s.loadPixels(r),o=en(e,i),a=e.getResourceManager().getTextureGLId(o);t.spine_setAtlasPageTexture(u,n,a,i.width,i.height)}catch{}}}catch{}}return r}(t,r,n,s));const a=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 i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=$e.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=$e.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),c=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,D);r&&(r.texture=n[s.data.texture]||0,e.insert(t,D,r))}}}(e.world,n,i,c),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,D);n&&(n.material=r,e.insert(t,D,n))}else if("SpineAnimation"===s.type){const n=e.get(t,V);n&&(n.material=r,e.insert(t,V,n))}}}}(e.world,n,a,c),r){const s=function(e,t,n,s){const r={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.spine_createInstance(o);if(a<0)continue;const c=s.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return r}(r,n,o,c);!function(e,t,n,s){let r=0;e.setSpineRenderer((e,i)=>{let o=i-r;r=i,(o<=0||o>.5)&&(o=1/60);for(const e in s){const r=s[e];n.spine_update(r,o);const i=n.spine_getMeshBatchCount(r);for(let e=0;e<i;e++){const s=n.spine_getMeshBatchVertexCount(r,e),i=n.spine_getMeshBatchIndexCount(r,e);if(!s||!i)continue;const o=8*s*4,a=2*i,c=n._malloc(o),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(r,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*s),_=new Uint16Array(n.HEAPU8.buffer,l,i),m=t._malloc(o),y=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,y,i).set(_),t.renderer_submitTriangles(m,s,y,i,d,f,0),t._free(m),t._free(y),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,r,s)}}class rn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const s of e.entities)for(const e of s.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)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class on{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new rn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.module}await sn(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([W]);for(const s of n){if(e.get(s,W).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([H]);for(const r of s){const s=e.get(r,H);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(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,k,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(r,W,o)}}}const an={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bt.releaseRenderTarget(e._handle),an.create({width:t,height:n,depth:!0})),begin(e,t){Bt.begin(t,e._handle)},end(){Bt.end()},getDepthTexture:e=>Bt.getTargetDepthTexture(e._handle)};let cn=!1;function ln(e){cn=e}function un(){return cn}function hn(){return!cn}async function dn(e,t){if(t)return t();return(0,(await import(e)).default)()}const fn=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function pn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function _n(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class mn{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(fn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=dn(this.wasmUrl_,this.factory_).then(n=>{n.physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=e.world;e.addSystemToSchedule(ce.PostUpdate,ue([q(ee)],r=>{const i=s.getEntitiesWithComponents([S,k]),o=new Set;for(const r of i){o.add(r);const i=s.get(r,S),a=s.get(r,k);if(!t.has(r)){if(!i.enabled)continue;const s=pn(a.rotation);n.physics_createBody(r,i.bodyType,a.position.x,a.position.y,s,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation,i.bullet),yn(e,n,r),t.add(r)}if(i.bodyType===T.Kinematic){const e=pn(a.rotation);n.physics_setBodyTransform(r,a.position.x,a.position.y,e)}}for(const e of t)o.has(e)||(n.physics_destroyBody(e),t.delete(e));n.physics_step(r.delta),function(e,t){const n=t.physics_getDynamicBodyCount();if(0===n)return;const s=t.physics_getDynamicBodyTransforms(),r=s>>2;for(let s=0;s<n;s++){const n=r+4*s,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,k);if(!l)continue;l.position.x=o,l.position.y=a;const u=_n(c);l.rotation.w=u.w,l.rotation.x=u.x,l.rotation.y=u.y,l.rotation.z=u.z}}(e,n),function(e,t){const n=t.physics_getCollisionEvents(),s=[];for(let e=0;e<n.enters.size();e++){const t=n.enters.get(e);s.push(t)}const r=[];for(let e=0;e<n.exits.size();e++){const t=n.exits.get(e);r.push({entityA:t.entityA,entityB:t.entityB})}const i=[];for(let e=0;e<n.sensorEnters.size();e++)i.push(n.sensorEnters.get(e));const o=[];for(let e=0;e<n.sensorExits.size();e++)o.push(n.sensorExits.get(e));e.insertResource(fn,{collisionEnters:s,collisionExits:r,sensorEnters:i,sensorExits:o}),n.enters.delete(),n.exits.delete(),n.sensorEnters.delete(),n.sensorExits.delete()}(e,n)},{name:"PhysicsSystem"})),e.__physicsModule=n});e.__physicsInitPromise=n}}function yn(e,t,n){const s=e.world;if(s.has(n,P)){const e=s.get(n,P);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)}if(s.has(n,C)){const e=s.get(n,C);return void t.physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}if(s.has(n,b)){const e=s.get(n,b);t.physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor)}}class gn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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){return this.module_.physics_getLinearVelocity(e)}}var wn;e=wn=f,console.log(`[ESEngine] Platform: ${wn.name}`);export{jt as App,Ze as AssetPlugin,Je as AssetServer,Qe as Assets,qe as AsyncCache,Re as BlendMode,T as BodyType,P as BoxCollider,W as Camera,H as Canvas,b as CapsuleCollider,j as Children,C as CircleCollider,ie as Commands,ae as CommandsInstance,pt as DataType,ht as Draw,oe as EntityCommands,$t as GLDebug,St as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,ye as Input,ge as InputPlugin,me as InputState,k as LocalTransform,$e as Material,Ve as MaterialLoader,te as Mut,N as Parent,gn as Physics,fn as PhysicsEvents,mn as PhysicsPlugin,Et as PostProcess,on as PreviewPlugin,se as Query,re as QueryInstance,Nt as RenderPipeline,Rt as RenderStage,an as RenderTexture,Bt as Renderer,q as Res,J as ResMut,S as RigidBody,ce as Schedule,je as ShaderSources,V as SpineAnimation,D as Sprite,_e as SystemRunner,Ce as Text,ve as TextAlign,Pe as TextOverflow,Ee as TextPlugin,be as TextRenderer,Se as TextVerticalAlign,ee as Time,Te as UIRect,O as Velocity,rn as WebAssetProvider,xe as World,$ as WorldTransform,fe as addStartupSystem,de as addSystem,pe as addSystemToSchedule,et as assetPlugin,Ot as clearDrawCallbacks,z as clearUserComponents,w as color,Vt as createWebApp,A as defineComponent,K as defineResource,ue as defineSystem,U as defineTag,Xt as flushPendingSystems,G as getComponentDefaults,t as getPlatform,s as getPlatformType,F as getUserComponent,at as initDrawAPI,Lt as initGLDebugAPI,wt as initGeometryAPI,Ie as initMaterialAPI,Ct as initPostProcessAPI,Ft as initRendererAPI,we as inputPlugin,L as isBuiltinComponent,un as isEditor,n as isPlatformInitialized,hn as isRuntime,Ae as isTextureRef,r as isWeChat,i as isWeb,Ye as loadComponent,dn as loadPhysicsModule,sn as loadRuntimeScene,Xe as loadSceneData,Ge as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Wt as registerDrawCallback,tt as registerEmbeddedAssets,Ne as registerMaterialCallback,ln as setEditorMode,ct as shutdownDrawAPI,kt as shutdownGLDebugAPI,xt as shutdownGeometryAPI,Le as shutdownMaterialAPI,bt as shutdownPostProcessAPI,zt as shutdownRendererAPI,Me as textPlugin,Ht as unregisterDrawCallback,Ke as updateCameraAspectRatio,m as vec2,y as vec3,g as vec4};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),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){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),w=(e=1,t=1,n=1,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function v(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const b=v("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=v("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),S=v("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=v("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E={Static:0,Kinematic:1,Dynamic:2};let T=0;function A(e,t){const n=++T;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function M(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const n=M(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),z(e,t,!1),r}function U(e){const t=M(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),z(e,{},!0),s}function F(e){return M().get(e)}function B(){M().clear()}function z(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function k(e){return!0===e._builtin}const L=I("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=I("Sprite",{texture:_,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),H=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),W=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),O=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=I("Parent",{entity:0}),V=I("Children",{entities:[]}),j=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),X={LocalTransform:L,WorldTransform:$,Sprite:D,Camera:H,Canvas:W,Velocity:O,Parent:N,Children:V,SpineAnimation:j,RigidBody:b,BoxCollider:P,CircleCollider:S,CapsuleCollider:C};function G(e){const t=X[e];if(t)return{...t._default};const n=F(e);return n?{...n._default}:null}let Y=0;function K(e,t){const n=++Y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function q(e){return{_type:"res",_resource:e}}function J(e){return{_type:"res_mut",_resource:e}}class Q{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 Z{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 Q(this.get(e),t=>this.set(e,t))}}const ee=K({delta:0,elapsed:0,frameCount:0},"Time");function te(e){return{_type:"mut",_component:e}}function ne(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function se(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class re{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ne(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:s}=this.descriptor_,r=e.map(e=>this.getActualComponent(e)),i=[...r,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of s)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=r.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:r[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function ie(){return{_type:"commands"}}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 n;return n=k(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 ae{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new oe(this,null)}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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ce;!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"}(ce||(ce={}));let le=0;function ue(e,t,n){const s=++le;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function he(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function de(e){he().push({schedule:ce.Update,system:e})}function fe(e){he().push({schedule:ce.Startup,system:e})}function pe(e,t){he().push({schedule:e,system:t})}class _e{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof ae&&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 ae(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ge=K(new me,"Input");class ye{constructor(e){this.target_=e??null}build(e){const n=new me;e.insertResource(ge,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(ce.First,ue([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const we=new ye;class xe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return k(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return k(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return k(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){k(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,s)}return s}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);return this.getStorage(t).set(e,s),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)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let s=!0;for(const t of e)if(!this.has(n,t)){s=!1;break}s&&t.push(n)}return t}}var ve,be,Pe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ve||(ve={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(be||(be={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Pe||(Pe={}));const Se=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:ve.Left,verticalAlign:be.Top,wordWrap:!0,overflow:Pe.Visible,lineHeight:1.2,dirty:!0});class Ce{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,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===Pe.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(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 _=Math.round(255*e.color.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;n.clearRect(0,0,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===Pe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case be.Top:x=u;break;case be.Middle:x=(p-w)/2;break;case be.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let s;switch(e.align){case ve.Left:s=u;break;case ve.Center:s=f/2;break;case ve.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Pe.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.flipVertically(P,f,p),C=this.module.getResourceManager(),E=this.module._malloc(S.length);this.module.HEAPU8.set(S,E);const T=C.createTexture(f,p,E,S.length,1);return this.module._free(E),{textureHandle:T,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)}}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 ve.Left:return"left";case ve.Center:return"center";case ve.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const s=4*t,r=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*s,o=(n-1-t)*s;r.set(e.subarray(i,i+s),o)}return r}}const Ee=R("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Te{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ce(t),s=e.world;e.addSystemToSchedule(ce.PreUpdate,ue([],()=>{const e=s.getEntitiesWithComponents([Se]);for(const t of e){const e=s.get(t,Se);if(!e.dirty)continue;s.has(t,D)||s.insert(t,D,{texture:_,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const r=s.has(t,Ee)?s.get(t,Ee):null,i=n.renderForEntity(t,e,r),o=s.get(t,D);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},s.insert(t,D,o),e.dirty=!1}}))}}const Ae=new Te;var Me;function Re(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 Ue=null,Fe=null,Be=1;const ze=new Map;function Ie(e){Ue=e,Fe=e.getResourceManager(),Ne()}function ke(){0!==He&&Ue&&(Ue._free(He),He=0),ze.clear(),Be=1,De=!1,Fe=null,Ue=null}function Le(){if(!Fe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Fe}const $e={createShader:(e,t)=>Le().createShader(e,t),releaseShader(e){e>0&&Le().releaseShader(e)},create(e){const t=Be++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Me.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return ze.set(t,n),t},get:e=>ze.get(e),setUniform(e,t,n){const s=ze.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=ze.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=ze.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=ze.get(e);return t?.blendMode??Me.Normal},setDepthTest(e,t){const n=ze.get(e);n&&(n.depthTest=t)},getShader(e){const t=ze.get(e);return t?.shader??0},release(e){ze.delete(e)},isValid:e=>ze.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;"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=ze.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Be++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return ze.set(n,s),n},toAssetData(e,t){const n=ze.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=ze.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let De=!1,He=0;const We=4096;function Oe(e){const t=(0===He&&Ue&&(He=Ue._malloc(We)),He);if(0===t||!Ue)return{ptr:0,count:0};let n=0,s=0;const r=Ue.HEAPU8,i=Ue.HEAPU32,o=Ue.HEAPF32;for(const[a,c]of e){if(n+128>We)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ne(){if(!Ue||De)return;Ue.materialDataProvider=(e,t,n,s,r)=>{const i=ze.get(e);if(!i)return Ue.HEAPU32[t>>2]=0,Ue.HEAPU32[n>>2]=0,Ue.HEAPU32[s>>2]=0,void(Ue.HEAPU32[r>>2]=0);Ue.HEAPU32[t>>2]=i.shader,Ue.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Oe(i.uniforms);Ue.HEAPU32[s>>2]=o,Ue.HEAPU32[r>>2]=a},De=!0}const Ve={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 je{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 l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),i=await this.shaderLoader_.load(r);return{handle:$e.createFromAsset(s,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Xe(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t);for(const n of s.components)Ye(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 Ge(e,t,n){const s=new Map,r=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();s.set(o.id,t);for(const s of o.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,i.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("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await r.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ye(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 Ye(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,L,s);break;case"Sprite":e.insert(t,D,s);break;case"Camera":e.insert(t,H,s);break;case"Canvas":e.insert(t,W,s);break;case"Text":e.insert(t,Se,s);break;case"SpineAnimation":e.insert(t,j,s);break;case"UIRect":e.insert(t,Ee,s);break;default:{const r=F(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ke(e,t){const n=e.getEntitiesWithComponents([H]);for(const s of n){const n=e.get(s,H);n&&(n.aspectRatio=t,e.insert(s,H,n))}}class qe{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Je{constructor(e){this.textureCache_=new qe,this.shaderCache_=new qe,this.jsonCache_=new qe,this.textCache_=new qe,this.binaryCache_=new qe,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new je(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const 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);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 Ge(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>r(new Error(`Failed to load image: ${e}`)),i.src=s})}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 i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,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_.save(),s&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const r=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const 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;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return $e.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await o(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 Qe=K(null,"Assets");class Ze{build(e){const t=e.wasmModule;t?e.insertResource(Qe,new Je(t)):console.warn("AssetPlugin: No WASM module available")}}const et=new Ze;function tt(e,t){const n=e.getResource(Qe);n&&n.registerEmbeddedAssets(t)}let nt=null,st=0,rt=0,it=0;const ot=new Float32Array(256);function at(e){nt=e,st=nt._malloc(64),rt=nt._malloc(64),it=nt._malloc(1024)}function ct(){nt&&(st&&(nt._free(st),st=0),rt&&(nt._free(rt),rt=0),it&&(nt._free(it),it=0)),nt=null}function lt(){if(!nt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return nt}const ut={x:1,y:1,z:1,w:1},ht={begin(e){const t=lt();t.HEAPF32.set(e,st/4),t.draw_begin(st)},end(){lt().draw_end()},line(e,t,n,s=1){lt().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},rect(e,t,n,s=!0){lt().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},rectOutline(e,t,n,s=1){lt().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},circle(e,t,n,s=!0,r=32){lt().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,s,r)},circleOutline(e,t,n,s=1,r=32){lt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,s,r)},texture(e,t,n,s=ut){lt().draw_texture(e.x,e.y,t.x,t.y,n,s.x,s.y,s.z,s.w)},textureRotated(e,t,n,s,r=ut){lt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.x,r.y,r.z,r.w)},setLayer(e){lt().draw_setLayer(e)},setDepth(e){lt().draw_setDepth(e)},getDrawCallCount:()=>nt?nt.draw_getDrawCallCount():0,getPrimitiveCount:()=>nt?nt.draw_getPrimitiveCount():0,setBlendMode(e){lt().draw_setBlendMode(e)},setDepthTest(e){lt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=lt();s.HEAPF32.set(n,rt/4),s.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,n){const s=lt(),r=$e.get(t);if(!r)return;if(ht.setBlendMode(r.blendMode),ht.setDepthTest(r.depthTest),0===r.uniforms.size)return void ht.drawMesh(e,r.shader,n);s.HEAPF32.set(n,rt/4);let i=0,o=0;for(const[e,t]of r.uniforms){const n=ft(e);if(!(n<0)){if(Re(t))ot[i++]=10,ot[i++]=n,ot[i++]=t.slot??o++,ot[i++]=t.textureId;else if("number"==typeof t)ot[i++]=1,ot[i++]=n,ot[i++]=t;else if(Array.isArray(t)){ot[i++]=t.length,ot[i++]=n;for(let e=0;e<t.length;e++)ot[i++]=t[e]}else"w"in t?(ot[i++]=4,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z,ot[i++]=t.w):"z"in t?(ot[i++]=3,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z):(ot[i++]=2,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(s.HEAPF32.set(ot.subarray(0,i),it/4),s.draw_meshWithUniforms(e,r.shader,rt,it,i)):s.draw_mesh(e,r.shader,rt)}},dt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ft(e){return dt[e]??-1}var pt;!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"}(pt||(pt={}));let _t=null,mt=0,gt=0,yt=0;function wt(e){_t=e,mt=_t._malloc(262144),gt=_t._malloc(65536),yt=_t._malloc(256)}function xt(){_t&&(mt&&_t._free(mt),gt&&_t._free(gt),yt&&_t._free(yt),mt=0,gt=0,yt=0),_t=null}function vt(){if(!_t)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return _t}const bt={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,mt/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,yt,r).set(i),t.geometry_init(n,mt,s,yt,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,gt,s).set(e.indices),t.geometry_setIndices16(n,gt,s)}else{new Uint32Array(t.HEAPU8.buffer,gt,s).set(e.indices),t.geometry_setIndices32(n,gt,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,mt/4),s.geometry_updateVertices(e,mt,r,n)},release(e){e>0&&vt().geometry_release(e)},isValid:e=>!(!_t||e<=0)&&_t.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bt.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:pt.Float2},{name:"a_texCoord",type:pt.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,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.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 i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(r-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return bt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.Float2}],indices:new Uint16Array(o)})}};let Pt=null;function St(e){Pt=e}function Ct(){Pt&&Tt.isInitialized()&&Tt.shutdown(),Pt=null}function Et(){if(!Pt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pt}const Tt={init:(e,t)=>Et().postprocess_init(e,t),shutdown(){Et().postprocess_shutdown()},resize(e,t){Et().postprocess_resize(e,t)},addPass:(e,t)=>Et().postprocess_addPass(e,t),removePass(e){Et().postprocess_removePass(e)},setEnabled(e,t){Et().postprocess_setPassEnabled(e,t)},isEnabled:e=>Et().postprocess_isPassEnabled(e),setUniform(e,t,n){Et().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Et().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Et().postprocess_begin()},end(){Et().postprocess_end()},getPassCount:()=>Et().postprocess_getPassCount(),isInitialized:()=>!!Pt&&Pt.postprocess_isInitialized(),setBypass(e){Et().postprocess_setBypass(e)},isBypassed:()=>!Pt||Pt.postprocess_isBypassed(),createBlur:()=>$e.createShader(At,"#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(At,"#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(At,"#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(At,"#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")},At="#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 Mt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mt||(Mt={}));let Rt=null,Ut=0;function Ft(e){Rt=e,Ut=Rt._malloc(64)}function Bt(){Rt&&Ut&&(Rt._free(Ut),Ut=0),Rt=null}const zt={init(e,t){Rt?.renderer_init(e,t)},resize(e,t){Rt?.renderer_resize(e,t)},begin(e,t){Rt&&Ut&&(Rt.HEAPF32.set(e,Ut/4),Rt.renderer_begin(Ut,t??0))},flush(){Rt?.renderer_flush()},end(){Rt?.renderer_end()},submitSprites(e){Rt&&Rt.renderer_submitSprites(e._cpp)},submitSpine(e){Rt&&Rt.renderer_submitSpine?.(e._cpp)},setStage(e){Rt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rt?.renderer_releaseTarget(e)},getTargetTexture:e=>Rt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rt?.renderer_setClearColor?.(e,t,n,s)},getStats:()=>Rt?{drawCalls:Rt.renderer_getDrawCalls(),triangles:Rt.renderer_getTriangles(),sprites:Rt.renderer_getSprites(),spine:Rt.renderer_getSpine?.()??0,meshes:Rt.renderer_getMeshes(),culled:Rt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let It=null;function kt(e){It=e}function Lt(){It=null}const $t={enable(){It?.gl_enableErrorCheck(!0)},disable(){It?.gl_enableErrorCheck(!1)},check:e=>It?.gl_checkErrors(e)??0,diagnose(){It?.renderer_diagnose()}},Dt=new Map;function Ht(e,t){Dt.set(e,t)}function Wt(e){Dt.delete(e)}function Ot(){Dt.clear()}class Nt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;zt.resize(s,r),Tt.isInitialized()&&Tt.getPassCount()>0&&!Tt.isBypassed()&&Tt.resize(s,r),zt.begin(n),zt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):zt.submitSpine(t),zt.flush();const o=Dt;if(o.size>0){ht.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}ht.end();for(const t of e)Wt(t)}zt.end()}}class Vt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(ce.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ce.FixedPreUpdate),this.runSchedule(ce.FixedUpdate),this.runSchedule(ce.FixedPostUpdate);this.runSchedule(ce.PreUpdate),this.runSchedule(ce.Update),this.runSchedule(ce.PostUpdate),this.runSchedule(ce.Last),requestAnimationFrame(this.mainLoop)},this.world_=new xe,this.resources_=new Z;for(const e of Object.values(ce))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Vt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ce.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ce.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new _e(this.world_,this.resources_),this.resources_.insert(ee,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ce.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Lt(),Bt(),Ct(),xt(),ke(),ct()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(ee),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(ee,n)}}function jt(e,t){const n=Vt.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),at(e),Ie(e),wt(e),St(e),Ft(e),kt(e);const r=new Nt;n.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=s.entityCount(),a=Yt(s,n+1e3);if(a){const e=a.backgroundColor;zt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const s=e.entityCount(),r=s+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const i=e.getCamera(s);if(!i.isActive)continue;const o=e.getLocalTransform(s),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=Yt(e,r);if(n){t=Kt(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=qt(-s,s,-t,t,-i.farPlane,i.farPlane)}else c=Jt(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return Zt(c,Qt(o.position.x,o.position.y,o.position.z))}return Gt}(s,e,t),l=(d()-i)/1e3;r.render({registry:{_cpp:s},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(ce.Last,a),n.addPlugin(et),n.addPlugin(we),n.addPlugin(Ae),n}function Xt(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 Gt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yt(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Kt(e,t,n,s,r){const i=e*t/n,o=e;switch(s){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}}}function qt(e,t,n,s,r,i){const o=new Float32Array(16),a=t-e,c=s-n,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(s+n)/c,o[14]=-(i+r)/l,o[15]=1,o}function Jt(e,t,n,s){const r=new Float32Array(16),i=1/Math.tan(e/2),o=n-s;return r[0]=i/t,r[5]=i,r[10]=(s+n)/o,r[11]=-1,r[14]=2*s*n/o,r}function Qt(e,t,n){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-n,s}function Zt(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}function en(e,t){const n=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const r=n.createTexture(t.width,t.height,s,t.pixels.length,1);return e._free(s),r}function tn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}async function nn(e,t,n,s,r){const i=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]=en(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,i);let o={},a=null;r&&(a=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),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),o=await async function(e,t,n,s,r){const i={};for(const o of s.entities)for(const s of o.components){if("SpineAnimation"!==s.type||!s.data)continue;const o=s.data.skeletonPath,a=s.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const s=r.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(o),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;i[o]=f;const p=tn(s),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),o=en(e,i),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,a,n,s));const c=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 i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=$e.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=$e.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),l=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,D);r&&(r.texture=n[s.data.texture]||0,e.insert(t,D,r))}}}(e.world,n,i,l),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,D);n&&(n.material=r,e.insert(t,D,n))}else if("SpineAnimation"===s.type){const n=e.get(t,j);n&&(n.material=r,e.insert(t,j,n))}}}}(e.world,n,c,l),r&&a){const s=function(e,t,n,s){const r={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=s.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(a,n,o,l);!function(e,t,n,s,r){let i=0;e.setSpineRenderer((e,o)=>{let a=o-i;i=o,(a<=0||a>.5)&&(a=1/60);for(const e in r){const i=r[e];s.update(i,a);const o=s.getMeshBatchCount(i);for(let e=0;e<o;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,c=2*o,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),d=n._malloc(4);s.getMeshBatchData(i,e,l,u,h,d);const f=n.HEAPU32[h>>2],p=n.HEAPU32[d>>2],_=new Float32Array(n.HEAPF32.buffer,l,8*r),m=new Uint16Array(n.HEAPU8.buffer,u,o),g=t._malloc(a),y=t._malloc(c);t.HEAPF32.set(_,g>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(m),t.renderer_submitTriangles(g,r,y,o,f,p,0),t._free(g),t._free(y),n._free(l),n._free(u),n._free(h),n._free(d)}}})}(e,t,r,a,s)}}class sn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const s of e.entities)for(const e of s.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)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class rn{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new sn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await nn(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([H]);for(const s of n){if(e.get(s,H).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([W]);for(const r of s){const s=e.get(r,W);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(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,L,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(r,H,o)}}}const on={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=zt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:zt.getTargetTexture(n),width:e.width,height:e.height}},release(e){zt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(zt.releaseRenderTarget(e._handle),on.create({width:t,height:n,depth:!0})),begin(e,t){zt.begin(t,e._handle)},end(){zt.end()},getDepthTexture:e=>zt.getTargetDepthTexture(e._handle)};let an=!1;function cn(e){an=e}function ln(){return an}function un(){return!an}async function hn(e,t){if(t)return t();return(0,(await import(e)).default)()}const dn=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function fn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function pn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class _n{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(dn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=hn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=e.world;e.addSystemToSchedule(ce.PostUpdate,ue([q(ee)],r=>{const i=s.getEntitiesWithComponents([b,L]),o=new Set;for(const r of i){o.add(r);const i=s.get(r,b),a=s.get(r,L);if(!t.has(r)){if(!i.enabled)continue;const s=fn(a.rotation);n._physics_createBody(r,i.bodyType,a.position.x,a.position.y,s,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),mn(e,n,r),t.add(r)}if(i.bodyType===E.Kinematic){const e=fn(a.rotation);n._physics_setBodyTransform(r,a.position.x,a.position.y,e)}}for(const e of t)o.has(e)||(n._physics_destroyBody(e),t.delete(e));n._physics_step(r.delta),function(e,t){const n=t._physics_getDynamicBodyCount();if(0===n)return;const s=t._physics_getDynamicBodyTransforms(),r=s>>2;for(let s=0;s<n;s++){const n=r+4*s,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,L);if(!l)continue;l.position.x=o,l.position.y=a;const u=pn(c);l.rotation.w=u.w,l.rotation.x=u.x,l.rotation.y=u.y,l.rotation.z=u.z}}(e,n),function(e,t){t._physics_collectEvents();const n=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<s;r++){const s=e+6*r;n.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4],contactY:t.HEAPF32[s+5]})}}const r=[],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;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const o=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<a;n++){const s=e+2*n;o.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(dn,{collisionEnters:n,collisionExits:r,sensorEnters:o,sensorExits:c})}(e,n)},{name:"PhysicsSystem"})),e.__physicsModule=n});e.__physicsInitPromise=n}}function mn(e,t,n){const s=e.world;if(s.has(n,P)){const e=s.get(n,P);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,S)){const e=s.get(n,S);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,C)){const e=s.get(n,C);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 gn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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]}}}var yn;e=yn=f,console.log(`[ESEngine] Platform: ${yn.name}`);export{Vt as App,Ze as AssetPlugin,Je as AssetServer,Qe as Assets,qe as AsyncCache,Me as BlendMode,E as BodyType,P as BoxCollider,H as Camera,W as Canvas,C as CapsuleCollider,V as Children,S as CircleCollider,ie as Commands,ae as CommandsInstance,pt as DataType,ht as Draw,oe as EntityCommands,$t as GLDebug,bt as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,ge as Input,ye as InputPlugin,me as InputState,L as LocalTransform,$e as Material,je as MaterialLoader,te as Mut,N as Parent,gn as Physics,dn as PhysicsEvents,_n as PhysicsPlugin,Tt as PostProcess,rn as PreviewPlugin,se as Query,re as QueryInstance,Nt as RenderPipeline,Mt as RenderStage,on as RenderTexture,zt as Renderer,q as Res,J as ResMut,b as RigidBody,ce as Schedule,Ve as ShaderSources,j as SpineAnimation,D as Sprite,_e as SystemRunner,Se as Text,ve as TextAlign,Pe as TextOverflow,Te as TextPlugin,Ce as TextRenderer,be as TextVerticalAlign,ee as Time,Ee as UIRect,O as Velocity,sn as WebAssetProvider,xe as World,$ as WorldTransform,fe as addStartupSystem,de as addSystem,pe as addSystemToSchedule,et as assetPlugin,Ot as clearDrawCallbacks,B as clearUserComponents,w as color,jt as createWebApp,R as defineComponent,K as defineResource,ue as defineSystem,U as defineTag,Xt as flushPendingSystems,G as getComponentDefaults,t as getPlatform,s as getPlatformType,F as getUserComponent,at as initDrawAPI,kt as initGLDebugAPI,wt as initGeometryAPI,Ie as initMaterialAPI,St as initPostProcessAPI,Ft as initRendererAPI,we as inputPlugin,k as isBuiltinComponent,ln as isEditor,n as isPlatformInitialized,un as isRuntime,Re as isTextureRef,r as isWeChat,i as isWeb,Ye as loadComponent,hn as loadPhysicsModule,nn as loadRuntimeScene,Xe as loadSceneData,Ge as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Ht as registerDrawCallback,tt as registerEmbeddedAssets,Ne as registerMaterialCallback,cn as setEditorMode,ct as shutdownDrawAPI,Lt as shutdownGLDebugAPI,xt as shutdownGeometryAPI,ke as shutdownMaterialAPI,Ct as shutdownPostProcessAPI,Bt as shutdownRendererAPI,Ae as textPlugin,Wt as unregisterDrawCallback,Ke as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.tsindex b2796bbd8..92c02660b 100644--- a/desktop/public/sdk/esm/spine/index.d.ts+++ b/desktop/public/sdk/esm/spine/index.d.ts@@ -375,41 +375,63 @@ declare class App {* @brief Loads and initializes the standalone Spine WASM module*/interface SpineWasmModule {- spine_loadSkeleton(skelPath: string, atlasText: string, atlasLen: number, isBinary: boolean): number;- spine_unloadSkeleton(handle: number): void;- spine_getAtlasPageCount(handle: number): number;- spine_getAtlasPageTextureName(handle: number, pageIndex: number): string;- spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;- spine_createInstance(skeletonHandle: number): number;- spine_destroyInstance(instanceId: number): void;- spine_playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;- spine_addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;- spine_setSkin(instanceId: number, name: string): void;- spine_update(instanceId: number, dt: number): void;- spine_getAnimations(instanceId: number): string;- spine_getSkins(instanceId: number): string;- spine_getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;- spine_getBoneRotation(instanceId: number, bone: string): number;- spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;- spine_getMeshBatchCount(instanceId: number): number;- spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;- spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;- spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;+ _spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;+ _spine_unloadSkeleton(handle: number): void;+ _spine_getAtlasPageCount(handle: number): number;+ _spine_getAtlasPageTextureName(handle: number, pageIndex: number): number;+ _spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;+ _spine_createInstance(skeletonHandle: number): number;+ _spine_destroyInstance(instanceId: number): void;+ _spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;+ _spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;+ _spine_setSkin(instanceId: number, name: number): void;+ _spine_update(instanceId: number, dt: number): void;+ _spine_getAnimations(instanceId: number): number;+ _spine_getSkins(instanceId: number): number;+ _spine_getBonePosition(instanceId: number, bone: number, outXPtr: number, outYPtr: number): number;+ _spine_getBoneRotation(instanceId: number, bone: number): number;+ _spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;+ _spine_getMeshBatchCount(instanceId: number): number;+ _spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;+ _spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;+ _spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;+ cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;+ UTF8ToString(ptr: number): string;+ stringToNewUTF8(str: string): number;HEAPF32: Float32Array;HEAPU8: Uint8Array;HEAPU32: Uint32Array;_malloc(size: number): number;_free(ptr: number): void;- FS: {- writeFile(path: string, data: string | Uint8Array): void;- mkdirTree(path: string): void;- analyzePath(path: string): {- exists: boolean;- };- };}+interface SpineWrappedAPI {+ loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: string, atlasLen: number, isBinary: boolean): number;+ unloadSkeleton(handle: number): void;+ getAtlasPageCount(handle: number): number;+ getAtlasPageTextureName(handle: number, pageIndex: number): string;+ setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;+ createInstance(skeletonHandle: number): number;+ destroyInstance(instanceId: number): void;+ playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;+ addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;+ setSkin(instanceId: number, name: string): void;+ update(instanceId: number, dt: number): void;+ getAnimations(instanceId: number): string;+ getSkins(instanceId: number): string;+ getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;+ getBoneRotation(instanceId: number, bone: string): number;+ getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;+ getMeshBatchCount(instanceId: number): number;+ getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;+ getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;+ getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;+}+declare function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI;type SpineModuleFactory = (config?: Record<string, unknown>) => Promise<SpineWasmModule>;-declare function loadSpineModule(wasmUrl: string, factory?: SpineModuleFactory): Promise<SpineWasmModule>;+declare function loadSpineModule(wasmUrl: string, factory?: SpineModuleFactory): Promise<{+ raw: SpineWasmModule;+ api: SpineWrappedAPI;+}>;/*** @file SpineController.ts@@ -429,11 +451,12 @@ interface SpineEvent {stringValue?: string;}declare class SpineModuleController {- private module_;+ private raw_;+ private api_;private listeners_;- constructor(spineModule: SpineWasmModule);- get module(): SpineWasmModule;- loadSkeleton(skelPath: string, atlasText: string, isBinary: boolean): number;+ constructor(raw: SpineWasmModule, api: SpineWrappedAPI);+ get raw(): SpineWasmModule;+ loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number;unloadSkeleton(handle: number): void;getAtlasPageCount(handle: number): number;getAtlasPageTextureName(handle: number, pageIndex: number): string;@@ -474,5 +497,5 @@ declare class SpinePlugin implements Plugin {}declare function submitSpineMeshesToCore(coreModule: ESEngineModule, controller: SpineModuleController, instanceId: number, transform?: Float32Array): void;-export { SpineModuleController, SpinePlugin, SpineResource, loadSpineModule, submitSpineMeshesToCore };-export type { SpineEvent, SpineEventCallback, SpineEventType, SpineModuleFactory, SpineWasmModule };+export { SpineModuleController, SpinePlugin, SpineResource, loadSpineModule, submitSpineMeshesToCore, wrapSpineModule };+export type { SpineEvent, SpineEventCallback, SpineEventType, SpineModuleFactory, SpineWasmModule, SpineWrappedAPI };diff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.jsindex 1be2ebc9f..c01d4d59a 100644--- a/desktop/public/sdk/esm/spine/index.js+++ b/desktop/public/sdk/esm/spine/index.js@@ -1,2 +1,2 @@-let e=0;function t(t,s){const n=++e;return{_id:Symbol(`Resource_${n}_${s??""}`),_name:s??`Resource_${n}`,_default:t}}async function s(e,t){if(t)return t();return(0,(await import(e)).default)()}t({delta:0,elapsed:0,frameCount:0},"Time");class n{constructor(e){this.module_=e,this.listeners_=new Map}get module(){return this.module_}loadSkeleton(e,t,s){return this.module_.spine_loadSkeleton(e,t,t.length,s)}unloadSkeleton(e){this.module_.spine_unloadSkeleton(e)}getAtlasPageCount(e){return this.module_.spine_getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.module_.spine_getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,s,n,o){this.module_.spine_setAtlasPageTexture(e,t,s,n,o)}createInstance(e){return this.module_.spine_createInstance(e)}destroyInstance(e){this.module_.spine_destroyInstance(e),this.listeners_.delete(e)}play(e,t,s=!0,n=0){return this.module_.spine_playAnimation(e,t,s,n)}addAnimation(e,t,s=!0,n=0,o=0){return this.module_.spine_addAnimation(e,t,s,n,o)}setSkin(e,t){this.module_.spine_setSkin(e,t)}update(e,t){this.module_.spine_update(e,t)}getAnimations(e){const t=this.module_.spine_getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.module_.spine_getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const s=this.module_._malloc(4),n=this.module_._malloc(4);if(!this.module_.spine_getBonePosition(e,t,s,n))return this.module_._free(s),this.module_._free(n),null;const o=this.module_.HEAPF32[s>>2],i=this.module_.HEAPF32[n>>2];return this.module_._free(s),this.module_._free(n),{x:o,y:i}}getBoneRotation(e,t){return this.module_.spine_getBoneRotation(e,t)}getBounds(e){const t=this.module_._malloc(16);this.module_.spine_getBounds(e,t,t+4,t+8,t+12);const s=this.module_.HEAPF32,n=t>>2,o={x:s[n],y:s[n+1],width:s[n+2],height:s[n+3]};return this.module_._free(t),o}extractMeshBatches(e){const t=this.module_.spine_getMeshBatchCount(e),s=[],n=this.module_._malloc(8),o=n,i=n+4;for(let n=0;n<t;n++){const t=this.module_.spine_getMeshBatchVertexCount(e,n),r=this.module_.spine_getMeshBatchIndexCount(e,n);if(t<=0||r<=0)continue;const l=8*t*4,u=2*r,_=this.module_._malloc(l),a=this.module_._malloc(u);this.module_.spine_getMeshBatchData(e,n,_,a,o,i);const d=new Float32Array(this.module_.HEAPF32.buffer,_,8*t),h=new Uint16Array(this.module_.HEAPU8.buffer,a,r);s.push({vertices:new Float32Array(d),indices:new Uint16Array(h),textureId:this.module_.HEAPU32[o>>2],blendMode:this.module_.HEAPU32[i>>2]}),this.module_._free(_),this.module_._free(a)}return this.module_._free(n),s}on(e,t,s){this.listeners_.has(e)||this.listeners_.set(e,new Map);const n=this.listeners_.get(e);n.has(t)||n.set(t,new Set),n.get(t).add(s)}off(e,t,s){const n=this.listeners_.get(e);if(!n)return;const o=n.get(t);o&&o.delete(s)}removeAllListeners(e){this.listeners_.delete(e)}}const o=t(null,"SpineController");class i{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,i=s(this.wasmUrl_,this.factory_).then(s=>{const i=new n(s);return e.insertResource(o,i),{controller:i,coreModule:t}});e.insertResource(o,null),e.__spineInitPromise=i}}function r(e,t,s,n){const o=t.extractMeshBatches(s);let i=0;n&&(i=e._malloc(64),e.HEAPF32.set(n,i>>2));for(const t of o){const s=t.vertices.byteLength,n=t.indices.byteLength,o=e._malloc(s),r=e._malloc(n);e.HEAPF32.set(t.vertices,o>>2),new Uint16Array(e.HEAPU8.buffer,r,t.indices.length).set(t.indices),e.renderer_submitTriangles(o,t.vertices.length/8,r,t.indices.length,t.textureId,t.blendMode,i),e._free(o),e._free(r)}i&&e._free(i)}export{n as SpineModuleController,i as SpinePlugin,o as SpineResource,s as loadSpineModule,r as submitSpineMeshesToCore};+let e=0;function t(t,n){const s=++e;return{_id:Symbol(`Resource_${s}_${n??""}`),_name:n??`Resource_${s}`,_default:t}}function n(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function s(e,t){let s;if(t)s=await t();else{const t=(await import(e)).default;s=await t()}return{raw:s,api:n(s)}}t({delta:0,elapsed:0,frameCount:0},"Time");class r{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,r;if("string"==typeof e){const t=(new TextEncoder).encode(e);r=t.length,s=this.raw_._malloc(r+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+r]=0}else r=e.length,s=this.raw_._malloc(r),this.raw_.HEAPU8.set(e,s);const i=this.api_.loadSkeleton(s,r,t,t.length,n);return this.raw_._free(s),i}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,r){this.api_.setAtlasPageTexture(e,t,n,s,r)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,r=0){return!!this.api_.addAnimation(e,t,n,s,r)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const r=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:r,y:i}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,r={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),r}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),r=s,i=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),a=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||a<=0)continue;const o=8*t*4,u=2*a,l=this.raw_._malloc(o),_=this.raw_._malloc(u);this.api_.getMeshBatchData(e,s,l,_,r,i);const h=new Float32Array(this.raw_.HEAPF32.buffer,l,8*t),c=new Uint16Array(this.raw_.HEAPU8.buffer,_,a);n.push({vertices:new Float32Array(h),indices:new Uint16Array(c),textureId:this.raw_.HEAPU32[r>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(l),this.raw_._free(_)}return this.raw_._free(s),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const r=s.get(t);r&&r.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const i=t(null,"SpineController");class a{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=s(this.wasmUrl_,this.factory_).then(({raw:n,api:s})=>{const a=new r(n,s);return e.insertResource(i,a),{controller:a,coreModule:t}});e.insertResource(i,null),e.__spineInitPromise=n}}function o(e,t,n,s){const r=t.extractMeshBatches(n);let i=0;s&&(i=e._malloc(64),e.HEAPF32.set(s,i>>2));for(const t of r){const n=t.vertices.byteLength,s=t.indices.byteLength,r=e._malloc(n),a=e._malloc(s);e.HEAPF32.set(t.vertices,r>>2),new Uint16Array(e.HEAPU8.buffer,a,t.indices.length).set(t.indices),e.renderer_submitTriangles(r,t.vertices.length/8,a,t.indices.length,t.textureId,t.blendMode,i),e._free(r),e._free(a)}i&&e._free(i)}export{r as SpineModuleController,a as SpinePlugin,i as SpineResource,s as loadSpineModule,o as submitSpineMeshesToCore,n as wrapSpineModule};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/wasm/physics.js b/desktop/public/wasm/physics.jsindex 82f83d134..b4106f9d9 100644--- a/desktop/public/wasm/physics.js+++ b/desktop/public/wasm/physics.js@@ -1,2 +1,2 @@-var ESPhysicsModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("physics.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var installIndexedIterator=(proto,sizeMethodName,getMethodName)=>{const makeIterator=(size,getValue)=>{let index=0;return{next(){if(index>=size){return{done:true}}const current=index;index++;const value=getValue(current);return{value,done:false}},[Symbol.iterator](){return this}}};if(!proto[Symbol.iterator]){proto[Symbol.iterator]=function(){const size=this[sizeMethodName]();return makeIterator(size,i=>this[getMethodName](i))}}};var __embind_register_iterable=(rawClassType,rawElementType,sizeMethodName,getMethodName)=>{sizeMethodName=AsciiToString(sizeMethodName);getMethodName=AsciiToString(getMethodName);whenDependentTypesAreResolved([],[rawClassType,rawElementType],types=>{const classType=types[0];installIndexedIterator(classType.registeredClass.instancePrototype,sizeMethodName,getMethodName);return[]})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var EmValOptionalType=Object.assign({optional:true},EmValType);var __embind_register_optional=(rawOptionalType,rawType)=>{registerType(rawOptionalType,EmValOptionalType)};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var argN=new Array(argCount);var invokerFunction=(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=GenericWireTypeSize}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)};var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};init_ClassHandle();init_RegisteredPointer();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;var ___getTypeName,_free,_malloc,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["F"];_free=Module["_free"]=wasmExports["H"];_malloc=Module["_malloc"]=wasmExports["I"];__emscripten_timeout=wasmExports["J"];__emscripten_stack_restore=wasmExports["K"];__emscripten_stack_alloc=wasmExports["L"];_emscripten_stack_get_current=wasmExports["M"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["G"]}var wasmImports={s:___cxa_throw,w:__abort_js,f:__embind_finalize_value_object,o:__embind_register_bigint,B:__embind_register_bool,k:__embind_register_class,j:__embind_register_class_constructor,d:__embind_register_class_function,z:__embind_register_emval,n:__embind_register_float,b:__embind_register_function,e:__embind_register_integer,p:__embind_register_iterable,a:__embind_register_memory_view,l:__embind_register_optional,A:__embind_register_std_string,h:__embind_register_std_wstring,g:__embind_register_value_object,c:__embind_register_value_object_field,C:__embind_register_void,u:__emscripten_runtime_keepalive_clear,i:__emval_create_invoker,r:__emval_invoke,q:__emval_run_destructors,v:__setitimer_js,y:_clock_time_get,m:_emscripten_get_now,x:_emscripten_resize_heap,t:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}+var ESPhysicsModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["j"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("physics.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __abort_js=()=>abort("");var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;var _physics_init,_physics_shutdown,_physics_createBody,_physics_destroyBody,_physics_hasBody,_physics_addBoxShape,_physics_addCircleShape,_physics_addCapsuleShape,_physics_step,_physics_setBodyTransform,_physics_getDynamicBodyCount,_physics_getDynamicBodyTransforms,_physics_collectEvents,_physics_getCollisionEnterCount,_physics_getCollisionEnterBuffer,_physics_getCollisionExitCount,_physics_getCollisionExitBuffer,_physics_getSensorEnterCount,_physics_getSensorEnterBuffer,_physics_getSensorExitCount,_physics_getSensorExitBuffer,_physics_applyForce,_physics_applyImpulse,_physics_setLinearVelocity,_physics_getLinearVelocity,_free,_malloc,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_physics_init=Module["_physics_init"]=wasmExports["k"];_physics_shutdown=Module["_physics_shutdown"]=wasmExports["l"];_physics_createBody=Module["_physics_createBody"]=wasmExports["m"];_physics_destroyBody=Module["_physics_destroyBody"]=wasmExports["n"];_physics_hasBody=Module["_physics_hasBody"]=wasmExports["o"];_physics_addBoxShape=Module["_physics_addBoxShape"]=wasmExports["p"];_physics_addCircleShape=Module["_physics_addCircleShape"]=wasmExports["q"];_physics_addCapsuleShape=Module["_physics_addCapsuleShape"]=wasmExports["r"];_physics_step=Module["_physics_step"]=wasmExports["s"];_physics_setBodyTransform=Module["_physics_setBodyTransform"]=wasmExports["t"];_physics_getDynamicBodyCount=Module["_physics_getDynamicBodyCount"]=wasmExports["u"];_physics_getDynamicBodyTransforms=Module["_physics_getDynamicBodyTransforms"]=wasmExports["v"];_physics_collectEvents=Module["_physics_collectEvents"]=wasmExports["w"];_physics_getCollisionEnterCount=Module["_physics_getCollisionEnterCount"]=wasmExports["x"];_physics_getCollisionEnterBuffer=Module["_physics_getCollisionEnterBuffer"]=wasmExports["y"];_physics_getCollisionExitCount=Module["_physics_getCollisionExitCount"]=wasmExports["z"];_physics_getCollisionExitBuffer=Module["_physics_getCollisionExitBuffer"]=wasmExports["A"];_physics_getSensorEnterCount=Module["_physics_getSensorEnterCount"]=wasmExports["B"];_physics_getSensorEnterBuffer=Module["_physics_getSensorEnterBuffer"]=wasmExports["C"];_physics_getSensorExitCount=Module["_physics_getSensorExitCount"]=wasmExports["D"];_physics_getSensorExitBuffer=Module["_physics_getSensorExitBuffer"]=wasmExports["E"];_physics_applyForce=Module["_physics_applyForce"]=wasmExports["F"];_physics_applyImpulse=Module["_physics_applyImpulse"]=wasmExports["G"];_physics_setLinearVelocity=Module["_physics_setLinearVelocity"]=wasmExports["H"];_physics_getLinearVelocity=Module["_physics_getLinearVelocity"]=wasmExports["I"];_free=Module["_free"]=wasmExports["J"];_malloc=Module["_malloc"]=wasmExports["K"];__emscripten_timeout=wasmExports["L"];__emscripten_stack_restore=wasmExports["M"];__emscripten_stack_alloc=wasmExports["N"];_emscripten_stack_get_current=wasmExports["O"];memory=wasmMemory=wasmExports["i"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,f:__abort_js,d:__emscripten_runtime_keepalive_clear,e:__setitimer_js,h:_clock_time_get,a:_emscripten_get_now,g:_emscripten_resize_heap,c:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})};return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=ESPhysicsModule;module.exports.default=ESPhysicsModule}else if(typeof define==="function"&&define["amd"])define([],()=>ESPhysicsModule);diff --git a/desktop/public/wasm/spine38.js b/desktop/public/wasm/spine38.jsindex 09c03b1a9..4b88fcc92 100644--- a/desktop/public/wasm/spine38.js+++ b/desktop/public/wasm/spine38.js@@ -1,2 +1,2 @@-var ESSpineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["y"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("spine38.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var ___getTypeName,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["z"];_malloc=Module["_malloc"]=wasmExports["A"];_free=Module["_free"]=wasmExports["B"];__emscripten_timeout=wasmExports["D"];__emscripten_stack_restore=wasmExports["E"];__emscripten_stack_alloc=wasmExports["F"];_emscripten_stack_get_current=wasmExports["G"];memory=wasmMemory=wasmExports["x"];__indirect_function_table=wasmTable=wasmExports["C"]}var wasmImports={i:___cxa_throw,h:___syscall_fcntl64,v:___syscall_ioctl,w:___syscall_openat,q:__abort_js,f:__embind_register_bigint,l:__embind_register_bool,j:__embind_register_emval,e:__embind_register_float,a:__embind_register_function,c:__embind_register_integer,b:__embind_register_memory_view,k:__embind_register_std_string,d:__embind_register_std_wstring,p:__embind_register_void,n:__emscripten_runtime_keepalive_clear,o:__setitimer_js,r:_emscripten_resize_heap,g:_fd_close,u:_fd_read,s:_fd_seek,t:_fd_write,m:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}+var ESSpineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["g"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("spine38.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var __abort_js=()=>abort("");var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToNewUTF8"]=stringToNewUTF8;var _spine_loadSkeleton,_spine_unloadSkeleton,_spine_getAtlasPageCount,_spine_getAtlasPageTextureName,_spine_setAtlasPageTexture,_spine_createInstance,_spine_destroyInstance,_spine_playAnimation,_spine_addAnimation,_spine_setSkin,_spine_update,_spine_getAnimations,_spine_getSkins,_spine_getBonePosition,_spine_getBoneRotation,_spine_getBounds,_spine_getMeshBatchCount,_spine_getMeshBatchVertexCount,_spine_getMeshBatchIndexCount,_spine_getMeshBatchData,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_spine_loadSkeleton=Module["_spine_loadSkeleton"]=wasmExports["h"];_spine_unloadSkeleton=Module["_spine_unloadSkeleton"]=wasmExports["i"];_spine_getAtlasPageCount=Module["_spine_getAtlasPageCount"]=wasmExports["j"];_spine_getAtlasPageTextureName=Module["_spine_getAtlasPageTextureName"]=wasmExports["k"];_spine_setAtlasPageTexture=Module["_spine_setAtlasPageTexture"]=wasmExports["l"];_spine_createInstance=Module["_spine_createInstance"]=wasmExports["m"];_spine_destroyInstance=Module["_spine_destroyInstance"]=wasmExports["n"];_spine_playAnimation=Module["_spine_playAnimation"]=wasmExports["o"];_spine_addAnimation=Module["_spine_addAnimation"]=wasmExports["p"];_spine_setSkin=Module["_spine_setSkin"]=wasmExports["q"];_spine_update=Module["_spine_update"]=wasmExports["r"];_spine_getAnimations=Module["_spine_getAnimations"]=wasmExports["s"];_spine_getSkins=Module["_spine_getSkins"]=wasmExports["t"];_spine_getBonePosition=Module["_spine_getBonePosition"]=wasmExports["u"];_spine_getBoneRotation=Module["_spine_getBoneRotation"]=wasmExports["v"];_spine_getBounds=Module["_spine_getBounds"]=wasmExports["w"];_spine_getMeshBatchCount=Module["_spine_getMeshBatchCount"]=wasmExports["x"];_spine_getMeshBatchVertexCount=Module["_spine_getMeshBatchVertexCount"]=wasmExports["y"];_spine_getMeshBatchIndexCount=Module["_spine_getMeshBatchIndexCount"]=wasmExports["z"];_spine_getMeshBatchData=Module["_spine_getMeshBatchData"]=wasmExports["A"];_malloc=Module["_malloc"]=wasmExports["B"];_free=Module["_free"]=wasmExports["C"];__emscripten_timeout=wasmExports["D"];__emscripten_stack_restore=wasmExports["E"];__emscripten_stack_alloc=wasmExports["F"];_emscripten_stack_get_current=wasmExports["G"];memory=wasmMemory=wasmExports["f"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={e:__abort_js,b:__emscripten_runtime_keepalive_clear,c:__setitimer_js,d:_emscripten_resize_heap,a:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})};return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=ESSpineModule;module.exports.default=ESSpineModule}else if(typeof define==="function"&&define["amd"])define([],()=>ESSpineModule);diff --git a/desktop/public/wasm/spine42.js b/desktop/public/wasm/spine42.jsindex 3c6891906..0df3cb90c 100644--- a/desktop/public/wasm/spine42.js+++ b/desktop/public/wasm/spine42.js@@ -1,2 +1,2 @@-var ESSpineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["x"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("spine42.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var ___getTypeName,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["y"];_malloc=Module["_malloc"]=wasmExports["z"];_free=Module["_free"]=wasmExports["A"];__emscripten_timeout=wasmExports["C"];__emscripten_stack_restore=wasmExports["D"];__emscripten_stack_alloc=wasmExports["E"];_emscripten_stack_get_current=wasmExports["F"];memory=wasmMemory=wasmExports["w"];__indirect_function_table=wasmTable=wasmExports["B"]}var wasmImports={h:___cxa_throw,u:___syscall_ioctl,v:___syscall_openat,p:__abort_js,f:__embind_register_bigint,k:__embind_register_bool,i:__embind_register_emval,e:__embind_register_float,a:__embind_register_function,c:__embind_register_integer,b:__embind_register_memory_view,j:__embind_register_std_string,d:__embind_register_std_wstring,n:__embind_register_void,m:__emscripten_runtime_keepalive_clear,o:__setitimer_js,q:_emscripten_resize_heap,g:_fd_close,t:_fd_read,r:_fd_seek,s:_fd_write,l:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}+var ESSpineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["g"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("spine42.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var __abort_js=()=>abort("");var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToNewUTF8"]=stringToNewUTF8;var _spine_loadSkeleton,_spine_unloadSkeleton,_spine_getAtlasPageCount,_spine_getAtlasPageTextureName,_spine_setAtlasPageTexture,_spine_createInstance,_spine_destroyInstance,_spine_playAnimation,_spine_addAnimation,_spine_setSkin,_spine_update,_spine_getAnimations,_spine_getSkins,_spine_getBonePosition,_spine_getBoneRotation,_spine_getBounds,_spine_getMeshBatchCount,_spine_getMeshBatchVertexCount,_spine_getMeshBatchIndexCount,_spine_getMeshBatchData,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_spine_loadSkeleton=Module["_spine_loadSkeleton"]=wasmExports["h"];_spine_unloadSkeleton=Module["_spine_unloadSkeleton"]=wasmExports["i"];_spine_getAtlasPageCount=Module["_spine_getAtlasPageCount"]=wasmExports["j"];_spine_getAtlasPageTextureName=Module["_spine_getAtlasPageTextureName"]=wasmExports["k"];_spine_setAtlasPageTexture=Module["_spine_setAtlasPageTexture"]=wasmExports["l"];_spine_createInstance=Module["_spine_createInstance"]=wasmExports["m"];_spine_destroyInstance=Module["_spine_destroyInstance"]=wasmExports["n"];_spine_playAnimation=Module["_spine_playAnimation"]=wasmExports["o"];_spine_addAnimation=Module["_spine_addAnimation"]=wasmExports["p"];_spine_setSkin=Module["_spine_setSkin"]=wasmExports["q"];_spine_update=Module["_spine_update"]=wasmExports["r"];_spine_getAnimations=Module["_spine_getAnimations"]=wasmExports["s"];_spine_getSkins=Module["_spine_getSkins"]=wasmExports["t"];_spine_getBonePosition=Module["_spine_getBonePosition"]=wasmExports["u"];_spine_getBoneRotation=Module["_spine_getBoneRotation"]=wasmExports["v"];_spine_getBounds=Module["_spine_getBounds"]=wasmExports["w"];_spine_getMeshBatchCount=Module["_spine_getMeshBatchCount"]=wasmExports["x"];_spine_getMeshBatchVertexCount=Module["_spine_getMeshBatchVertexCount"]=wasmExports["y"];_spine_getMeshBatchIndexCount=Module["_spine_getMeshBatchIndexCount"]=wasmExports["z"];_spine_getMeshBatchData=Module["_spine_getMeshBatchData"]=wasmExports["A"];_malloc=Module["_malloc"]=wasmExports["B"];_free=Module["_free"]=wasmExports["C"];__emscripten_timeout=wasmExports["D"];__emscripten_stack_restore=wasmExports["E"];__emscripten_stack_alloc=wasmExports["F"];_emscripten_stack_get_current=wasmExports["G"];memory=wasmMemory=wasmExports["f"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={e:__abort_js,b:__emscripten_runtime_keepalive_clear,c:__setitimer_js,d:_emscripten_resize_heap,a:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})};return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=ESSpineModule;module.exports.default=ESSpineModule}else if(typeof define==="function"&&define["amd"])define([],()=>ESSpineModule);diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 3dd87fa54..d107f56da 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -25,6 +25,8 @@ const SPINE38_JS: &[u8] = include_bytes!("../../public/wasm/spine38.js");const SPINE38_WASM: &[u8] = include_bytes!("../../public/wasm/spine38.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@@ -153,6 +155,16 @@ fn get_spine42_wasm() -> Vec<u8> {SPINE42_WASM.to_vec()}+#[tauri::command]+fn get_physics_js() -> Vec<u8> {+ PHYSICS_JS.to_vec()+}++#[tauri::command]+fn get_physics_wasm() -> Vec<u8> {+ PHYSICS_WASM.to_vec()+}+#[derive(Clone, serde::Serialize)]struct CommandOutput {stream: String,@@ -251,6 +263,8 @@ pub fn run() {get_spine38_wasm,get_spine42_js,get_spine42_wasm,+ get_physics_js,+ get_physics_wasm,]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/desktop/src/native-fs.ts b/desktop/src/native-fs.tsindex 19b213956..0afe5241f 100644--- a/desktop/src/native-fs.ts+++ b/desktop/src/native-fs.ts@@ -76,6 +76,8 @@ export interface NativeFS {getEditorDts(): Promise<string>;getSpineJs(version: string): Promise<string>;getSpineWasm(version: string): Promise<Uint8Array>;+ getPhysicsJs(): Promise<string>;+ getPhysicsWasm(): Promise<Uint8Array>;toAssetUrl?(path: string): string;}@@ -349,6 +351,16 @@ export const nativeFS: NativeFS = {const data = await invoke<number[]>(cmd);return new Uint8Array(data);},++ async getPhysicsJs() {+ const data = await invoke<number[]>('get_physics_js');+ return new TextDecoder().decode(new Uint8Array(data));+ },++ async getPhysicsWasm() {+ const data = await invoke<number[]>('get_physics_wasm');+ return new Uint8Array(data);+ },};export const nativeShell: NativeShell = {diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex de22a7e9a..7323c9c43 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -28,7 +28,7 @@ import {clearExtensionPanels,isBuiltinPanel,} from './panels/PanelRegistry';-import { SpineModuleController, type SpineWasmModule } from 'esengine/spine';+import { SpineModuleController, wrapSpineModule, type SpineWasmModule } from 'esengine/spine';import { registerBuiltinPanels } from './panels/builtinPanels';import { registerBuiltinEditors } from './property/editors';import { registerMaterialEditors } from './property/materialEditors';@@ -170,7 +170,8 @@ export class Editor {this.spineModule_ = module;this.spineVersion_ = version;- const controller = module ? new SpineModuleController(module as SpineWasmModule) : null;+ const raw = module as SpineWasmModule;+ const controller = module ? new SpineModuleController(raw, wrapSpineModule(raw)) : null;for (const panel of this.panelInstances_.values()) {if (isSpineControllerAware(panel)) {panel.setSpineController(controller);@@ -368,6 +369,7 @@ export class Editor {if (config.spineVersion) {setSettingsValue('project.spineVersion', config.spineVersion);}+ setSettingsValue('project.enablePhysics', config.enablePhysics ?? false);const resolution = config.designResolution ?? { width: 1920, height: 1080 };setSettingsValue('project.designWidth', resolution.width);setSettingsValue('project.designHeight', resolution.height);@@ -391,6 +393,7 @@ export class Editor {config.version = getSettingsValue<string>('project.version') || config.version;config.defaultScene = getSettingsValue<string>('project.defaultScene') || config.defaultScene;config.spineVersion = getSettingsValue<string>('project.spineVersion') as SpineVersion;+ config.enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;config.designResolution = {width: getSettingsValue<number>('project.designWidth') || 1920,height: getSettingsValue<number>('project.designHeight') || 1080,diff --git a/editor/src/asset/AssetLoader.ts b/editor/src/asset/AssetLoader.tsindex f9771070d..c63baa623 100644--- a/editor/src/asset/AssetLoader.ts+++ b/editor/src/asset/AssetLoader.ts@@ -197,14 +197,9 @@ export class AssetLoader {return { success: false, error: `Failed to read skeleton: ${skelAbsPath}` };}- const spineFS = controller.module.FS;- const skelDir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));- if (skelDir) {- spineFS.mkdirTree(skelDir);- }- spineFS.writeFile(skeletonPath, skelData instanceof Uint8Array ? skelData : new TextEncoder().encode(skelData));-- const skeletonHandle = controller.loadSkeleton(skeletonPath, atlasContent, isBinary);+ const skeletonHandle = controller.loadSkeleton(+ skelData instanceof Uint8Array ? skelData : skelData as string,+ atlasContent, isBinary);if (skeletonHandle < 0) {return { success: false, error: `Failed to load skeleton in spine module: ${skeletonPath}` };}diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.tsindex 0b5755854..6f67fea06 100644--- a/editor/src/builder/BuildService.ts+++ b/editor/src/builder/BuildService.ts@@ -30,6 +30,7 @@ export interface BuildContext {projectPath: string;config: BuildConfig;spineVersion?: SpineVersion;+ enablePhysics?: boolean;progress?: BuildProgressReporter;cache?: BuildCache;}@@ -68,11 +69,13 @@ export class BuildService {const projectConfig = await loadProjectConfig(this.projectPath_);const spineVersion = projectConfig?.spineVersion;+ const enablePhysics = projectConfig?.enablePhysics ?? false;const context: BuildContext = {projectPath: this.projectPath_,config,spineVersion,+ enablePhysics,progress,cache: useCache ? this.cache_ : undefined,};diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.tsindex 9c5cb6650..b9a50149b 100644--- a/editor/src/builder/PlayableBuilder.ts+++ b/editor/src/builder/PlayableBuilder.ts@@ -62,6 +62,7 @@ html,body{width:100%;height:100%;overflow:hidden;background:#000}{{WASM_SDK}}</script>{{SPINE_SCRIPT}}+{{PHYSICS_SCRIPT}}<script>{{GAME_CODE}}</script>@@ -123,6 +124,21 @@ function decodeBinary(dataUrl){}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)},@@ -130,7 +146,7 @@ function decodeBinary(dataUrl){resolvePath:function(ref){return ref}};- await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule);+ await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule);var screenAspect=c.width/c.height;es.updateCameraAspectRatio(app.world,screenAspect);@@ -242,6 +258,20 @@ export class PlayableBuilder {}}+ // 7.5. Load physics module if needed+ let physicsJsSource = '';+ let physicsWasmBase64 = '';+ if (this.context_.enablePhysics && this.fs_?.getPhysicsJs) {+ this.progress_.setCurrentTask('Loading physics module...', 27);+ const physicsJs = await this.fs_.getPhysicsJs();+ const physicsWasm = await this.fs_.getPhysicsWasm();+ if (physicsJs && physicsWasm.length > 0) {+ physicsJsSource = physicsJs;+ physicsWasmBase64 = this.arrayBufferToBase64(physicsWasm);+ this.progress_.log('info', 'Physics module loaded');+ }+ }+// 8. Collect assets (keyed by UUID, excluding packed textures, adding atlas pages)this.progress_.setCurrentTask('Collecting assets...', 30);const assets = await this.collectAssets(packedPaths, compiledMaterials);@@ -254,7 +284,7 @@ export class PlayableBuilder {// 9. Assemble HTMLthis.progress_.setPhase('assembling');this.progress_.setCurrentTask('Assembling HTML...', 0);- const html = this.assembleHTML(wasmSdk, gameCode, rewrittenScene, assets, spineJsSource, spineWasmBase64);+ const html = this.assembleHTML(wasmSdk, gameCode, rewrittenScene, assets, spineJsSource, spineWasmBase64, physicsJsSource, physicsWasmBase64);this.progress_.log('info', `HTML assembled: ${html.length} bytes`);// 10. Write output@@ -607,7 +637,8 @@ ${imports}private assembleHTML(wasmSdk: string, gameCode: string, sceneData: string,assets: Map<string, string>,- spineJs?: string, spineWasmBase64?: string+ spineJs?: string, spineWasmBase64?: string,+ physicsJs?: string, physicsWasmBase64?: string,): string {const entries: string[] = [];for (const [path, dataUrl] of assets) {@@ -621,9 +652,17 @@ ${imports}spineScript = `<script>\nvar __SPINE_WASM_B64__="";\n</script>`;}+ let physicsScript = '';+ if (physicsJs && physicsWasmBase64) {+ physicsScript = `<script>\nvar __PHYSICS_WASM_B64__="${physicsWasmBase64}";\n${physicsJs}\n</script>`;+ } else {+ physicsScript = `<script>\nvar __PHYSICS_WASM_B64__="";\n</script>`;+ }+return HTML_TEMPLATE.replace('{{WASM_SDK}}', () => wasmSdk).replace('{{SPINE_SCRIPT}}', () => spineScript)+ .replace('{{PHYSICS_SCRIPT}}', () => physicsScript).replace('{{GAME_CODE}}', () => gameCode).replace('{{ASSETS_MAP}}', () => `{${entries.join(',')}}`).replace('{{SCENE_DATA}}', () => sceneData);diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.tsindex de0227367..446a2a4cf 100644--- a/editor/src/builder/WeChatBuilder.ts+++ b/editor/src/builder/WeChatBuilder.ts@@ -251,6 +251,22 @@ async function initSpineModule() {} catch(e) { console.warn('Spine module not available:', e); }}+var physicsModule = null;++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();@@ -290,6 +306,7 @@ async function initSpineModule() {SDK.flushPendingSystems(app);await initSpineModule();+ await initPhysicsModule();${firstSceneName ? `try {@@ -305,7 +322,7 @@ async function initSpineModule() {var sceneJson = wxfs.readFileSync('scenes/${firstSceneName}.json', 'utf-8');var sceneData = JSON.parse(sceneJson);- await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule);+ await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule, physicsModule);var screenAspect = canvas.width / canvas.height;SDK.updateCameraAspectRatio(app.world, screenAspect);@@ -352,6 +369,16 @@ async function initSpineModule() {console.log(`[WeChatBuilder] Copied Spine ${spineVersion} module`);}}++ if (this.context_.enablePhysics) {+ const physicsJs = await this.fs_!.getPhysicsJs();+ const physicsWasm = await this.fs_!.getPhysicsWasm();+ if (physicsJs && physicsWasm.length > 0) {+ await this.fs_!.writeFile(joinPath(outputDir, 'physics.js'), physicsJs);+ await this.fs_!.writeBinaryFile(joinPath(outputDir, 'physics.wasm'), physicsWasm);+ console.log(`[WeChatBuilder] Copied Physics module`);+ }+ }}private async compileScripts(scripts: string[]): Promise<string> {diff --git a/editor/src/settings/builtinSettings.ts b/editor/src/settings/builtinSettings.tsindex 207e726a9..ecd5f18d2 100644--- a/editor/src/settings/builtinSettings.ts+++ b/editor/src/settings/builtinSettings.ts@@ -59,6 +59,15 @@ export function registerBuiltinSettings(): void {],});+ registerSettingsItem({+ id: 'project.enablePhysics',+ section: 'project',+ label: 'Enable Physics',+ type: 'boolean',+ defaultValue: false,+ order: 0.5,+ });+registerSettingsItem({id: 'project.designWidth',section: 'project',diff --git a/editor/src/types/NativeFS.ts b/editor/src/types/NativeFS.tsindex 5a311ba6d..e84d3d6fb 100644--- a/editor/src/types/NativeFS.ts+++ b/editor/src/types/NativeFS.ts@@ -47,5 +47,7 @@ export interface NativeFS {getEditorDts(): Promise<string>;getSpineJs(version: string): Promise<string>;getSpineWasm(version: string): Promise<Uint8Array>;+ getPhysicsJs(): Promise<string>;+ getPhysicsWasm(): Promise<Uint8Array>;toAssetUrl?(path: string): string;}diff --git a/editor/src/types/ProjectTypes.ts b/editor/src/types/ProjectTypes.tsindex 4f2708e08..771dc2c97 100644--- a/editor/src/types/ProjectTypes.ts+++ b/editor/src/types/ProjectTypes.ts@@ -17,6 +17,7 @@ export interface ProjectConfig {created: string;modified: string;spineVersion?: SpineVersion;+ enablePhysics?: boolean;designResolution?: { width: number; height: number };}diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.tsindex 0f327887a..3e0e317e9 100644--- a/sdk/src/physics/PhysicsModuleLoader.ts+++ b/sdk/src/physics/PhysicsModuleLoader.ts@@ -1,40 +1,48 @@/*** @file PhysicsModuleLoader.ts- * @brief Loads and initializes the standalone Physics WASM module+ * @brief Loads and initializes the Physics WASM module (standalone or side module)*/export interface PhysicsWasmModule {- physics_init(gx: number, gy: number, timestep: number, substeps: number): void;- physics_shutdown(): void;+ _physics_init(gx: number, gy: number, timestep: number, substeps: number): void;+ _physics_shutdown(): void;- physics_createBody(entityId: number, bodyType: number, x: number, y: number, angle: number,+ _physics_createBody(entityId: number, bodyType: number, x: number, y: number, angle: number,gravityScale: number, linearDamping: number, angularDamping: number,- fixedRotation: boolean, bullet: boolean): void;- physics_destroyBody(entityId: number): void;- physics_hasBody(entityId: number): boolean;+ fixedRotation: number, bullet: number): void;+ _physics_destroyBody(entityId: number): void;+ _physics_hasBody(entityId: number): number;- physics_addBoxShape(entityId: number, halfW: number, halfH: number,+ _physics_addBoxShape(entityId: number, halfW: number, halfH: number,offX: number, offY: number,- density: number, friction: number, restitution: number, isSensor: boolean): void;- physics_addCircleShape(entityId: number, radius: number,+ density: number, friction: number, restitution: number, isSensor: number): void;+ _physics_addCircleShape(entityId: number, radius: number,offX: number, offY: number,- density: number, friction: number, restitution: number, isSensor: boolean): void;- physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number,+ density: number, friction: number, restitution: number, isSensor: number): void;+ _physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number,offX: number, offY: number,- density: number, friction: number, restitution: number, isSensor: boolean): void;+ density: number, friction: number, restitution: number, isSensor: number): void;- physics_step(dt: number): void;+ _physics_step(dt: number): void;- physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;- physics_getDynamicBodyCount(): number;- physics_getDynamicBodyTransforms(): number;+ _physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;+ _physics_getDynamicBodyCount(): number;+ _physics_getDynamicBodyTransforms(): number;- physics_getCollisionEvents(): CollisionEventsRaw;+ _physics_collectEvents(): void;+ _physics_getCollisionEnterCount(): number;+ _physics_getCollisionEnterBuffer(): number;+ _physics_getCollisionExitCount(): number;+ _physics_getCollisionExitBuffer(): number;+ _physics_getSensorEnterCount(): number;+ _physics_getSensorEnterBuffer(): number;+ _physics_getSensorExitCount(): number;+ _physics_getSensorExitBuffer(): number;- physics_applyForce(entityId: number, forceX: number, forceY: number): void;- physics_applyImpulse(entityId: number, impulseX: number, impulseY: number): void;- physics_setLinearVelocity(entityId: number, vx: number, vy: number): void;- physics_getLinearVelocity(entityId: number): { x: number; y: number };+ _physics_applyForce(entityId: number, forceX: number, forceY: number): void;+ _physics_applyImpulse(entityId: number, impulseX: number, impulseY: number): void;+ _physics_setLinearVelocity(entityId: number, vx: number, vy: number): void;+ _physics_getLinearVelocity(entityId: number): number;HEAPF32: Float32Array;HEAPU8: Uint8Array;@@ -43,33 +51,6 @@ export interface PhysicsWasmModule {_free(ptr: number): void;}-interface EmscriptenVector<T> {- size(): number;- get(index: number): T;- delete(): void;-}--export interface CollisionEventRaw {- entityA: number;- entityB: number;- normalX: number;- normalY: number;- contactX: number;- contactY: number;-}--export interface SensorEventRaw {- sensorEntity: number;- visitorEntity: number;-}--export interface CollisionEventsRaw {- enters: EmscriptenVector<CollisionEventRaw>;- exits: EmscriptenVector<CollisionEventRaw>;- sensorEnters: EmscriptenVector<SensorEventRaw>;- sensorExits: EmscriptenVector<SensorEventRaw>;-}-export type PhysicsModuleFactory = (config?: Record<string, unknown>) => Promise<PhysicsWasmModule>;export async function loadPhysicsModule(@@ -83,3 +64,65 @@ export async function loadPhysicsModule(const moduleFactory = (await import(/* webpackIgnore: true */ wasmUrl)).default as PhysicsModuleFactory;return moduleFactory();}++export interface ESEngineMainModule {+ loadDynamicLibrary(binary: Uint8Array, opts: { loadAsync: boolean; allowUndefined: boolean }): Promise<void>;+ cwrap(name: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;+ HEAPF32: Float32Array;+ HEAPU8: Uint8Array;+ HEAPU32: Uint32Array;+ _malloc(size: number): number;+ _free(ptr: number): void;+}++export async function loadPhysicsSideModule(+ wasmBinary: ArrayBuffer,+ mainModule: ESEngineMainModule+): Promise<PhysicsWasmModule> {+ await mainModule.loadDynamicLibrary(+ new Uint8Array(wasmBinary),+ { loadAsync: true, allowUndefined: true }+ );++ const cwrap = mainModule.cwrap.bind(mainModule);++ return {+ _physics_init: cwrap('physics_init', null, ['number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_init'],+ _physics_shutdown: cwrap('physics_shutdown', null, []) as PhysicsWasmModule['_physics_shutdown'],++ _physics_createBody: cwrap('physics_createBody', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createBody'],+ _physics_destroyBody: cwrap('physics_destroyBody', null, ['number']) as PhysicsWasmModule['_physics_destroyBody'],+ _physics_hasBody: cwrap('physics_hasBody', 'number', ['number']) as PhysicsWasmModule['_physics_hasBody'],++ _physics_addBoxShape: cwrap('physics_addBoxShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addBoxShape'],+ _physics_addCircleShape: cwrap('physics_addCircleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCircleShape'],+ _physics_addCapsuleShape: cwrap('physics_addCapsuleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCapsuleShape'],++ _physics_step: cwrap('physics_step', null, ['number']) as PhysicsWasmModule['_physics_step'],++ _physics_setBodyTransform: cwrap('physics_setBodyTransform', null, ['number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_setBodyTransform'],+ _physics_getDynamicBodyCount: cwrap('physics_getDynamicBodyCount', 'number', []) as PhysicsWasmModule['_physics_getDynamicBodyCount'],+ _physics_getDynamicBodyTransforms: cwrap('physics_getDynamicBodyTransforms', 'number', []) as PhysicsWasmModule['_physics_getDynamicBodyTransforms'],++ _physics_collectEvents: cwrap('physics_collectEvents', null, []) as PhysicsWasmModule['_physics_collectEvents'],+ _physics_getCollisionEnterCount: cwrap('physics_getCollisionEnterCount', 'number', []) as PhysicsWasmModule['_physics_getCollisionEnterCount'],+ _physics_getCollisionEnterBuffer: cwrap('physics_getCollisionEnterBuffer', 'number', []) as PhysicsWasmModule['_physics_getCollisionEnterBuffer'],+ _physics_getCollisionExitCount: cwrap('physics_getCollisionExitCount', 'number', []) as PhysicsWasmModule['_physics_getCollisionExitCount'],+ _physics_getCollisionExitBuffer: cwrap('physics_getCollisionExitBuffer', 'number', []) as PhysicsWasmModule['_physics_getCollisionExitBuffer'],+ _physics_getSensorEnterCount: cwrap('physics_getSensorEnterCount', 'number', []) as PhysicsWasmModule['_physics_getSensorEnterCount'],+ _physics_getSensorEnterBuffer: cwrap('physics_getSensorEnterBuffer', 'number', []) as PhysicsWasmModule['_physics_getSensorEnterBuffer'],+ _physics_getSensorExitCount: cwrap('physics_getSensorExitCount', 'number', []) as PhysicsWasmModule['_physics_getSensorExitCount'],+ _physics_getSensorExitBuffer: cwrap('physics_getSensorExitBuffer', 'number', []) as PhysicsWasmModule['_physics_getSensorExitBuffer'],++ _physics_applyForce: cwrap('physics_applyForce', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_applyForce'],+ _physics_applyImpulse: cwrap('physics_applyImpulse', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_applyImpulse'],+ _physics_setLinearVelocity: cwrap('physics_setLinearVelocity', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_setLinearVelocity'],+ _physics_getLinearVelocity: cwrap('physics_getLinearVelocity', 'number', ['number']) as PhysicsWasmModule['_physics_getLinearVelocity'],++ get HEAPF32() { return mainModule.HEAPF32; },+ get HEAPU8() { return mainModule.HEAPU8; },+ get HEAPU32() { return mainModule.HEAPU32; },+ _malloc: mainModule._malloc.bind(mainModule),+ _free: mainModule._free.bind(mainModule),+ } as PhysicsWasmModule;+}diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.tsindex b61b63964..a1f0a21ea 100644--- a/sdk/src/physics/PhysicsPlugin.ts+++ b/sdk/src/physics/PhysicsPlugin.ts@@ -13,8 +13,6 @@ import {loadPhysicsModule,type PhysicsWasmModule,type PhysicsModuleFactory,- type CollisionEventRaw,- type SensorEventRaw,} from './PhysicsModuleLoader';import type { RigidBodyData } from './PhysicsComponents';import { BodyType } from './PhysicsComponents';@@ -105,7 +103,7 @@ export class PhysicsPlugin implements Plugin {const initPromise = loadPhysicsModule(this.wasmUrl_, this.factory_).then((module: PhysicsWasmModule) => {- module.physics_init(+ module._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,@@ -132,11 +130,11 @@ export class PhysicsPlugin implements Plugin {const angle = quatToAngleZ(transform.rotation);- module.physics_createBody(+ module._physics_createBody(entity, rb.bodyType,transform.position.x, transform.position.y, angle,rb.gravityScale, rb.linearDamping, rb.angularDamping,- rb.fixedRotation, rb.bullet+ rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0);addShapeForEntity(app, module, entity);@@ -145,7 +143,7 @@ export class PhysicsPlugin implements Plugin {if (rb.bodyType === BodyType.Kinematic) {const angle = quatToAngleZ(transform.rotation);- module.physics_setBodyTransform(+ module._physics_setBodyTransform(entity,transform.position.x, transform.position.y,angle@@ -155,12 +153,12 @@ export class PhysicsPlugin implements Plugin {for (const entity of trackedEntities) {if (!currentEntities.has(entity)) {- module.physics_destroyBody(entity);+ module._physics_destroyBody(entity);trackedEntities.delete(entity);}}- module.physics_step(time.delta);+ module._physics_step(time.delta);syncDynamicTransforms(app, module);collectEvents(app, module);@@ -186,39 +184,39 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity):if (world.has(entity, BoxCollider)) {const box = world.get(entity, BoxCollider) as { halfExtents: Vec2; offset: Vec2; density: number; friction: number; restitution: number; isSensor: boolean };- module.physics_addBoxShape(+ module._physics_addBoxShape(entity, box.halfExtents.x, box.halfExtents.y,box.offset.x, box.offset.y,- box.density, box.friction, box.restitution, box.isSensor+ box.density, box.friction, box.restitution, box.isSensor ? 1 : 0);return;}if (world.has(entity, CircleCollider)) {const circle = world.get(entity, CircleCollider) as { radius: number; offset: Vec2; density: number; friction: number; restitution: number; isSensor: boolean };- module.physics_addCircleShape(+ module._physics_addCircleShape(entity, circle.radius,circle.offset.x, circle.offset.y,- circle.density, circle.friction, circle.restitution, circle.isSensor+ circle.density, circle.friction, circle.restitution, circle.isSensor ? 1 : 0);return;}if (world.has(entity, CapsuleCollider)) {const capsule = world.get(entity, CapsuleCollider) as { radius: number; halfHeight: number; offset: Vec2; density: number; friction: number; restitution: number; isSensor: boolean };- module.physics_addCapsuleShape(+ module._physics_addCapsuleShape(entity, capsule.radius, capsule.halfHeight,capsule.offset.x, capsule.offset.y,- capsule.density, capsule.friction, capsule.restitution, capsule.isSensor+ capsule.density, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0);}}function syncDynamicTransforms(app: App, module: PhysicsWasmModule): void {- const count = module.physics_getDynamicBodyCount();+ const count = module._physics_getDynamicBodyCount();if (count === 0) return;- const ptr = module.physics_getDynamicBodyTransforms();+ const ptr = module._physics_getDynamicBodyTransforms();const baseU32 = ptr >> 2;for (let i = 0; i < count; i++) {@@ -244,28 +242,62 @@ function syncDynamicTransforms(app: App, module: PhysicsWasmModule): void {}function collectEvents(app: App, module: PhysicsWasmModule): void {- const raw = module.physics_getCollisionEvents();+ module._physics_collectEvents();const collisionEnters: CollisionEnterEvent[] = [];- for (let i = 0; i < raw.enters.size(); i++) {- const e = raw.enters.get(i) as CollisionEventRaw;- collisionEnters.push(e);+ const enterCount = module._physics_getCollisionEnterCount();+ if (enterCount > 0) {+ const enterPtr = module._physics_getCollisionEnterBuffer() >> 2;+ for (let i = 0; i < enterCount; i++) {+ const base = enterPtr + i * 6;+ collisionEnters.push({+ entityA: module.HEAPU32[base] as Entity,+ entityB: module.HEAPU32[base + 1] as Entity,+ normalX: module.HEAPF32[base + 2],+ normalY: module.HEAPF32[base + 3],+ contactX: module.HEAPF32[base + 4],+ contactY: module.HEAPF32[base + 5],+ });+ }}const collisionExits: Array<{ entityA: Entity; entityB: Entity }> = [];- for (let i = 0; i < raw.exits.size(); i++) {- const e = raw.exits.get(i) as CollisionEventRaw;- collisionExits.push({ entityA: e.entityA as Entity, entityB: e.entityB as Entity });+ const exitCount = module._physics_getCollisionExitCount();+ if (exitCount > 0) {+ const exitPtr = module._physics_getCollisionExitBuffer() >> 2;+ for (let i = 0; i < exitCount; i++) {+ const base = exitPtr + i * 2;+ collisionExits.push({+ entityA: module.HEAPU32[base] as Entity,+ entityB: module.HEAPU32[base + 1] as Entity,+ });+ }}const sensorEnters: SensorEvent[] = [];- for (let i = 0; i < raw.sensorEnters.size(); i++) {- sensorEnters.push(raw.sensorEnters.get(i) as SensorEventRaw);+ const sensorEnterCount = module._physics_getSensorEnterCount();+ if (sensorEnterCount > 0) {+ const sensorEnterPtr = module._physics_getSensorEnterBuffer() >> 2;+ for (let i = 0; i < sensorEnterCount; i++) {+ const base = sensorEnterPtr + i * 2;+ sensorEnters.push({+ sensorEntity: module.HEAPU32[base] as Entity,+ visitorEntity: module.HEAPU32[base + 1] as Entity,+ });+ }}const sensorExits: SensorEvent[] = [];- for (let i = 0; i < raw.sensorExits.size(); i++) {- sensorExits.push(raw.sensorExits.get(i) as SensorEventRaw);+ const sensorExitCount = module._physics_getSensorExitCount();+ if (sensorExitCount > 0) {+ const sensorExitPtr = module._physics_getSensorExitBuffer() >> 2;+ for (let i = 0; i < sensorExitCount; i++) {+ const base = sensorExitPtr + i * 2;+ sensorExits.push({+ sensorEntity: module.HEAPU32[base] as Entity,+ visitorEntity: module.HEAPU32[base + 1] as Entity,+ });+ }}app.insertResource(PhysicsEvents, {@@ -274,11 +306,6 @@ function collectEvents(app: App, module: PhysicsWasmModule): void {sensorEnters,sensorExits});-- raw.enters.delete();- raw.exits.delete();- raw.sensorEnters.delete();- raw.sensorExits.delete();}// =============================================================================@@ -296,18 +323,20 @@ export class Physics {}applyForce(entity: Entity, force: Vec2): void {- this.module_.physics_applyForce(entity, force.x, force.y);+ this.module_._physics_applyForce(entity, force.x, force.y);}applyImpulse(entity: Entity, impulse: Vec2): void {- this.module_.physics_applyImpulse(entity, impulse.x, impulse.y);+ this.module_._physics_applyImpulse(entity, impulse.x, impulse.y);}setLinearVelocity(entity: Entity, velocity: Vec2): void {- this.module_.physics_setLinearVelocity(entity, velocity.x, velocity.y);+ this.module_._physics_setLinearVelocity(entity, velocity.x, velocity.y);}getLinearVelocity(entity: Entity): Vec2 {- return this.module_.physics_getLinearVelocity(entity);+ const ptr = this.module_._physics_getLinearVelocity(entity);+ const base = ptr >> 2;+ return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };}}diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.tsindex e33a509b0..57fd4e11e 100644--- a/sdk/src/physics/index.ts+++ b/sdk/src/physics/index.ts@@ -21,8 +21,10 @@ export {export {loadPhysicsModule,+ loadPhysicsSideModule,type PhysicsWasmModule,type PhysicsModuleFactory,+ type ESEngineMainModule,} from './PhysicsModuleLoader';export {diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 1d05b1e65..4f48dfc69 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -57,7 +57,7 @@ export class PreviewPlugin implements Plugin {const spinePromise = (this.app_ as any).__spineInitPromise;if (spinePromise) {const result = await spinePromise;- spineModule = result.controller.module;+ spineModule = result.controller.raw;}await loadRuntimeScene(this.app_, this.app_.wasmModule!, sceneData, provider, spineModule);diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex bae4954f2..c59b194db 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -7,7 +7,7 @@ import { Sprite, SpineAnimation } from './component';import { Material } from './material';import { loadSceneData, type SceneData } from './scene';import type { ESEngineModule } from './wasm';-import type { SpineWasmModule } from './spine/SpineModuleLoader';+import { wrapSpineModule, type SpineWasmModule, type SpineWrappedAPI } from './spine/SpineModuleLoader';import type { App } from './app';// =============================================================================@@ -104,13 +104,6 @@ function updateSpriteTextures(// Spine Helpers// =============================================================================-function ensureFSDir(mod: SpineWasmModule, path: string): void {- const dir = path.substring(0, path.lastIndexOf('/'));- if (dir) {- mod.FS.mkdirTree(dir);- }-}-function parseAtlasTextures(content: string): string[] {const textures: string[] = [];for (const line of content.split('\n')) {@@ -125,6 +118,7 @@ function parseAtlasTextures(content: string): string[] {async function loadSpineAssets(module: ESEngineModule,spineModule: SpineWasmModule,+ spineAPI: SpineWrappedAPI,sceneData: SceneData,provider: RuntimeAssetProvider,): Promise<Record<string, number>> {@@ -143,15 +137,26 @@ async function loadSpineAssets(const atlasContent = provider.readText(atlasRef);const isBinary = skelPath.endsWith('.skel');- ensureFSDir(spineModule, skelPath);+ let skelDataPtr: number;+ let skelDataLen: number;if (isBinary) {- spineModule.FS.writeFile(skelPath, provider.readBinary(skelRef));+ const bytes = provider.readBinary(skelRef);+ skelDataLen = bytes.length;+ skelDataPtr = spineModule._malloc(skelDataLen);+ spineModule.HEAPU8.set(bytes, skelDataPtr);} else {- spineModule.FS.writeFile(skelPath, provider.readText(skelRef));+ const text = provider.readText(skelRef);+ const encoder = new TextEncoder();+ const bytes = encoder.encode(text);+ skelDataLen = bytes.length;+ skelDataPtr = spineModule._malloc(skelDataLen + 1);+ spineModule.HEAPU8.set(bytes, skelDataPtr);+ spineModule.HEAPU8[skelDataPtr + skelDataLen] = 0;}- const skelHandle = spineModule.spine_loadSkeleton(- skelPath, atlasContent, atlasContent.length, isBinary);+ const skelHandle = spineAPI.loadSkeleton(+ skelDataPtr, skelDataLen, atlasContent, atlasContent.length, isBinary);+ spineModule._free(skelDataPtr);if (skelHandle < 0) continue;skeletons[skelRef] = skelHandle;@@ -167,7 +172,7 @@ async function loadSpineAssets(const handle = createTextureFromPixels(module, result);const rm = module.getResourceManager();const glId = rm.getTextureGLId(handle);- spineModule.spine_setAtlasPageTexture(skelHandle, k, glId, result.width, result.height);+ spineAPI.setAtlasPageTexture(skelHandle, k, glId, result.width, result.height);} catch { /* skip missing texture */ }}} catch { /* skip failed spine asset */ }@@ -177,7 +182,7 @@ async function loadSpineAssets(}function createSpineInstances(- spineModule: SpineWasmModule,+ spineAPI: SpineWrappedAPI,sceneData: SceneData,skeletons: Record<string, number>,entityMap: Map<number, number>,@@ -190,19 +195,19 @@ function createSpineInstances(const skelHandle = skeletons[skelRef];if (skelHandle === undefined) continue;- const instanceId = spineModule.spine_createInstance(skelHandle);+ const instanceId = spineAPI.createInstance(skelHandle);if (instanceId < 0) continue;const entity = entityMap.get(entityData.id);if (entity !== undefined) instances[entity] = instanceId;if (comp.data.animation) {- spineModule.spine_playAnimation(+ spineAPI.playAnimation(instanceId, comp.data.animation as string,comp.data.loop !== false, 0);}if (comp.data.skin) {- spineModule.spine_setSkin(instanceId, comp.data.skin as string);+ spineAPI.setSkin(instanceId, comp.data.skin as string);}}}@@ -213,6 +218,7 @@ function setupSpineRenderer(app: App,module: ESEngineModule,spineModule: SpineWasmModule,+ spineAPI: SpineWrappedAPI,instances: Record<number, number>,): void {let lastElapsed = 0;@@ -223,12 +229,12 @@ function setupSpineRenderer(for (const entity in instances) {const instanceId = instances[entity];- spineModule.spine_update(instanceId, dt);+ spineAPI.update(instanceId, dt);- const batchCount = spineModule.spine_getMeshBatchCount(instanceId);+ const batchCount = spineAPI.getMeshBatchCount(instanceId);for (let b = 0; b < batchCount; b++) {- const vertCount = spineModule.spine_getMeshBatchVertexCount(instanceId, b);- const idxCount = spineModule.spine_getMeshBatchIndexCount(instanceId, b);+ const vertCount = spineAPI.getMeshBatchVertexCount(instanceId, b);+ const idxCount = spineAPI.getMeshBatchIndexCount(instanceId, b);if (!vertCount || !idxCount) continue;const vertBytes = vertCount * 8 * 4;@@ -238,7 +244,7 @@ function setupSpineRenderer(const texIdPtr = spineModule._malloc(4);const blendPtr = spineModule._malloc(4);- spineModule.spine_getMeshBatchData(instanceId, b, vertPtr, idxPtr, texIdPtr, blendPtr);+ spineAPI.getMeshBatchData(instanceId, b, vertPtr, idxPtr, texIdPtr, blendPtr);const texId = spineModule.HEAPU32[texIdPtr >> 2];const blendMode = spineModule.HEAPU32[blendPtr >> 2];const srcVerts = new Float32Array(spineModule.HEAPF32.buffer, vertPtr, vertCount * 8);@@ -346,8 +352,10 @@ export async function loadRuntimeScene(applyTextureMetadata(module, sceneData, textureCache);let spineSkeletons: Record<string, number> = {};+ let spineAPI: SpineWrappedAPI | null = null;if (spineModule) {- spineSkeletons = await loadSpineAssets(module, spineModule, sceneData, provider);+ spineAPI = wrapSpineModule(spineModule);+ spineSkeletons = await loadSpineAssets(module, spineModule, spineAPI, sceneData, provider);}const materialCache = loadMaterials(sceneData, provider);@@ -356,8 +364,8 @@ export async function loadRuntimeScene(updateSpriteTextures(app.world, sceneData, textureCache, entityMap);updateMaterials(app.world, sceneData, materialCache, entityMap);- if (spineModule) {- const instances = createSpineInstances(spineModule, sceneData, spineSkeletons, entityMap);- setupSpineRenderer(app, module, spineModule, instances);+ if (spineModule && spineAPI) {+ const instances = createSpineInstances(spineAPI, sceneData, spineSkeletons, entityMap);+ setupSpineRenderer(app, module, spineModule, spineAPI, instances);}}diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex 34aa84e9a..8debb7b7d 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -4,7 +4,7 @@*/import type { Entity, Vec2 } from '../types';-import type { SpineWasmModule } from './SpineModuleLoader';+import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';@@ -22,41 +22,59 @@ export interface SpineEvent {}export class SpineModuleController {- private module_: SpineWasmModule;+ private raw_: SpineWasmModule;+ private api_: SpineWrappedAPI;private listeners_: Map<Entity, Map<SpineEventType, Set<SpineEventCallback>>>;- constructor(spineModule: SpineWasmModule) {- this.module_ = spineModule;+ constructor(raw: SpineWasmModule, api: SpineWrappedAPI) {+ this.raw_ = raw;+ this.api_ = api;this.listeners_ = new Map();}- get module(): SpineWasmModule {- return this.module_;+ get raw(): SpineWasmModule {+ return this.raw_;}// =========================================================================// Skeleton Management// =========================================================================- loadSkeleton(skelPath: string, atlasText: string, isBinary: boolean): number {- return this.module_.spine_loadSkeleton(skelPath, atlasText, atlasText.length, isBinary);+ loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number {+ let ptr: number;+ let len: number;+ if (typeof skelData === 'string') {+ const encoder = new TextEncoder();+ const bytes = encoder.encode(skelData);+ len = bytes.length;+ ptr = this.raw_._malloc(len + 1);+ this.raw_.HEAPU8.set(bytes, ptr);+ this.raw_.HEAPU8[ptr + len] = 0;+ } else {+ len = skelData.length;+ ptr = this.raw_._malloc(len);+ this.raw_.HEAPU8.set(skelData, ptr);+ }+ const result = this.api_.loadSkeleton(ptr, len, atlasText, atlasText.length, isBinary);+ this.raw_._free(ptr);+ return result;}unloadSkeleton(handle: number): void {- this.module_.spine_unloadSkeleton(handle);+ this.api_.unloadSkeleton(handle);}getAtlasPageCount(handle: number): number {- return this.module_.spine_getAtlasPageCount(handle);+ return this.api_.getAtlasPageCount(handle);}getAtlasPageTextureName(handle: number, pageIndex: number): string {- return this.module_.spine_getAtlasPageTextureName(handle, pageIndex);+ return this.api_.getAtlasPageTextureName(handle, pageIndex);}setAtlasPageTexture(handle: number, pageIndex: number,textureId: number, width: number, height: number): void {- this.module_.spine_setAtlasPageTexture(handle, pageIndex, textureId, width, height);+ this.api_.setAtlasPageTexture(handle, pageIndex, textureId, width, height);}// =========================================================================@@ -64,11 +82,11 @@ export class SpineModuleController {// =========================================================================createInstance(skeletonHandle: number): number {- return this.module_.spine_createInstance(skeletonHandle);+ return this.api_.createInstance(skeletonHandle);}destroyInstance(instanceId: number): void {- this.module_.spine_destroyInstance(instanceId);+ this.api_.destroyInstance(instanceId);this.listeners_.delete(instanceId as Entity);}@@ -77,20 +95,20 @@ export class SpineModuleController {// =========================================================================play(instanceId: number, animation: string, loop: boolean = true, track: number = 0): boolean {- return this.module_.spine_playAnimation(instanceId, animation, loop, track);+ return !!this.api_.playAnimation(instanceId, animation, loop, track);}addAnimation(instanceId: number, animation: string,loop: boolean = true, delay: number = 0, track: number = 0): boolean {- return this.module_.spine_addAnimation(instanceId, animation, loop, delay, track);+ return !!this.api_.addAnimation(instanceId, animation, loop, delay, track);}setSkin(instanceId: number, skinName: string): void {- this.module_.spine_setSkin(instanceId, skinName);+ this.api_.setSkin(instanceId, skinName);}update(instanceId: number, dt: number): void {- this.module_.spine_update(instanceId, dt);+ this.api_.update(instanceId, dt);}// =========================================================================@@ -98,7 +116,7 @@ export class SpineModuleController {// =========================================================================getAnimations(instanceId: number): string[] {- const json = this.module_.spine_getAnimations(instanceId);+ const json = this.api_.getAnimations(instanceId);try {return JSON.parse(json);} catch {@@ -107,7 +125,7 @@ export class SpineModuleController {}getSkins(instanceId: number): string[] {- const json = this.module_.spine_getSkins(instanceId);+ const json = this.api_.getSkins(instanceId);try {return JSON.parse(json);} catch {@@ -116,33 +134,33 @@ export class SpineModuleController {}getBonePosition(instanceId: number, boneName: string): Vec2 | null {- const xPtr = this.module_._malloc(4);- const yPtr = this.module_._malloc(4);+ const xPtr = this.raw_._malloc(4);+ const yPtr = this.raw_._malloc(4);- const found = this.module_.spine_getBonePosition(instanceId, boneName, xPtr, yPtr);+ const found = this.api_.getBonePosition(instanceId, boneName, xPtr, yPtr);if (!found) {- this.module_._free(xPtr);- this.module_._free(yPtr);+ this.raw_._free(xPtr);+ this.raw_._free(yPtr);return null;}- const x = this.module_.HEAPF32[xPtr >> 2];- const y = this.module_.HEAPF32[yPtr >> 2];- this.module_._free(xPtr);- this.module_._free(yPtr);+ const x = this.raw_.HEAPF32[xPtr >> 2];+ const y = this.raw_.HEAPF32[yPtr >> 2];+ this.raw_._free(xPtr);+ this.raw_._free(yPtr);return { x, y };}getBoneRotation(instanceId: number, boneName: string): number {- return this.module_.spine_getBoneRotation(instanceId, boneName);+ return this.api_.getBoneRotation(instanceId, boneName);}getBounds(instanceId: number): { x: number; y: number; width: number; height: number } {- const ptr = this.module_._malloc(16);- this.module_.spine_getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);+ const ptr = this.raw_._malloc(16);+ this.api_.getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);- const f32 = this.module_.HEAPF32;+ const f32 = this.raw_.HEAPF32;const base = ptr >> 2;const result = {x: f32[base],@@ -150,7 +168,7 @@ export class SpineModuleController {width: f32[base + 2],height: f32[base + 3],};- this.module_._free(ptr);+ this.raw_._free(ptr);return result;}@@ -164,7 +182,7 @@ export class SpineModuleController {textureId: number;blendMode: number;}[] {- const batchCount = this.module_.spine_getMeshBatchCount(instanceId);+ const batchCount = this.api_.getMeshBatchCount(instanceId);const batches: {vertices: Float32Array;indices: Uint16Array;@@ -172,40 +190,40 @@ export class SpineModuleController {blendMode: number;}[] = [];- const metaPtr = this.module_._malloc(8);+ const metaPtr = this.raw_._malloc(8);const texIdPtr = metaPtr;const blendPtr = metaPtr + 4;for (let i = 0; i < batchCount; i++) {- const vertexCount = this.module_.spine_getMeshBatchVertexCount(instanceId, i);- const indexCount = this.module_.spine_getMeshBatchIndexCount(instanceId, i);+ const vertexCount = this.api_.getMeshBatchVertexCount(instanceId, i);+ const indexCount = this.api_.getMeshBatchIndexCount(instanceId, i);if (vertexCount <= 0 || indexCount <= 0) continue;const vertBytes = vertexCount * 8 * 4;const idxBytes = indexCount * 2;- const vertPtr = this.module_._malloc(vertBytes);- const idxPtr = this.module_._malloc(idxBytes);+ const vertPtr = this.raw_._malloc(vertBytes);+ const idxPtr = this.raw_._malloc(idxBytes);- this.module_.spine_getMeshBatchData(+ this.api_.getMeshBatchData(instanceId, i, vertPtr, idxPtr, texIdPtr, blendPtr);const vertices = new Float32Array(- this.module_.HEAPF32.buffer, vertPtr, vertexCount * 8);+ this.raw_.HEAPF32.buffer, vertPtr, vertexCount * 8);const indices = new Uint16Array(- this.module_.HEAPU8.buffer, idxPtr, indexCount);+ this.raw_.HEAPU8.buffer, idxPtr, indexCount);batches.push({vertices: new Float32Array(vertices),indices: new Uint16Array(indices),- textureId: this.module_.HEAPU32[texIdPtr >> 2],- blendMode: this.module_.HEAPU32[blendPtr >> 2],+ textureId: this.raw_.HEAPU32[texIdPtr >> 2],+ blendMode: this.raw_.HEAPU32[blendPtr >> 2],});- this.module_._free(vertPtr);- this.module_._free(idxPtr);+ this.raw_._free(vertPtr);+ this.raw_._free(idxPtr);}- this.module_._free(metaPtr);+ this.raw_._free(metaPtr);return batches;}diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.tsindex 08d4cdf94..6e0d8ca30 100644--- a/sdk/src/spine/SpineModuleLoader.ts+++ b/sdk/src/spine/SpineModuleLoader.ts@@ -4,43 +4,92 @@*/export interface SpineWasmModule {- spine_loadSkeleton(skelPath: string, atlasText: string, atlasLen: number, isBinary: boolean): number;- spine_unloadSkeleton(handle: number): void;- spine_getAtlasPageCount(handle: number): number;- spine_getAtlasPageTextureName(handle: number, pageIndex: number): string;- spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;-- spine_createInstance(skeletonHandle: number): number;- spine_destroyInstance(instanceId: number): void;-- spine_playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;- spine_addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;- spine_setSkin(instanceId: number, name: string): void;- spine_update(instanceId: number, dt: number): void;-- spine_getAnimations(instanceId: number): string;- spine_getSkins(instanceId: number): string;- spine_getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;- spine_getBoneRotation(instanceId: number, bone: string): number;- spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;-- spine_getMeshBatchCount(instanceId: number): number;- spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;- spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;- spine_getMeshBatchData(instanceId: number, batchIndex: number,+ _spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;+ _spine_unloadSkeleton(handle: number): void;+ _spine_getAtlasPageCount(handle: number): number;+ _spine_getAtlasPageTextureName(handle: number, pageIndex: number): number;+ _spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;++ _spine_createInstance(skeletonHandle: number): number;+ _spine_destroyInstance(instanceId: number): void;++ _spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;+ _spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;+ _spine_setSkin(instanceId: number, name: number): void;+ _spine_update(instanceId: number, dt: number): void;++ _spine_getAnimations(instanceId: number): number;+ _spine_getSkins(instanceId: number): number;+ _spine_getBonePosition(instanceId: number, bone: number, outXPtr: number, outYPtr: number): number;+ _spine_getBoneRotation(instanceId: number, bone: number): number;+ _spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;++ _spine_getMeshBatchCount(instanceId: number): number;+ _spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;+ _spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;+ _spine_getMeshBatchData(instanceId: number, batchIndex: number,outVerticesPtr: number, outIndicesPtr: number,outTextureIdPtr: number, outBlendModePtr: number): void;+ cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;+ UTF8ToString(ptr: number): string;+ stringToNewUTF8(str: string): number;+HEAPF32: Float32Array;HEAPU8: Uint8Array;HEAPU32: Uint32Array;_malloc(size: number): number;_free(ptr: number): void;+}- FS: {- writeFile(path: string, data: string | Uint8Array): void;- mkdirTree(path: string): void;- analyzePath(path: string): { exists: boolean };+export interface SpineWrappedAPI {+ loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: string, atlasLen: number, isBinary: boolean): number;+ unloadSkeleton(handle: number): void;+ getAtlasPageCount(handle: number): number;+ getAtlasPageTextureName(handle: number, pageIndex: number): string;+ setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;+ createInstance(skeletonHandle: number): number;+ destroyInstance(instanceId: number): void;+ playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;+ addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;+ setSkin(instanceId: number, name: string): void;+ update(instanceId: number, dt: number): void;+ getAnimations(instanceId: number): string;+ getSkins(instanceId: number): string;+ getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;+ getBoneRotation(instanceId: number, bone: string): number;+ getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;+ getMeshBatchCount(instanceId: number): number;+ getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;+ getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;+ getMeshBatchData(instanceId: number, batchIndex: number,+ outVerticesPtr: number, outIndicesPtr: number,+ outTextureIdPtr: number, outBlendModePtr: number): void;+}++export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {+ const cw = raw.cwrap.bind(raw);+ return {+ loadSkeleton: cw('spine_loadSkeleton', 'number', ['number', 'number', 'string', 'number', 'number']) as SpineWrappedAPI['loadSkeleton'],+ unloadSkeleton: cw('spine_unloadSkeleton', null, ['number']) as SpineWrappedAPI['unloadSkeleton'],+ getAtlasPageCount: cw('spine_getAtlasPageCount', 'number', ['number']) as SpineWrappedAPI['getAtlasPageCount'],+ getAtlasPageTextureName: cw('spine_getAtlasPageTextureName', 'string', ['number', 'number']) as SpineWrappedAPI['getAtlasPageTextureName'],+ setAtlasPageTexture: cw('spine_setAtlasPageTexture', null, ['number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['setAtlasPageTexture'],+ createInstance: cw('spine_createInstance', 'number', ['number']) as SpineWrappedAPI['createInstance'],+ destroyInstance: cw('spine_destroyInstance', null, ['number']) as SpineWrappedAPI['destroyInstance'],+ playAnimation: cw('spine_playAnimation', 'number', ['number', 'string', 'number', 'number']) as SpineWrappedAPI['playAnimation'],+ addAnimation: cw('spine_addAnimation', 'number', ['number', 'string', 'number', 'number', 'number']) as SpineWrappedAPI['addAnimation'],+ setSkin: cw('spine_setSkin', null, ['number', 'string']) as SpineWrappedAPI['setSkin'],+ update: cw('spine_update', null, ['number', 'number']) as SpineWrappedAPI['update'],+ getAnimations: cw('spine_getAnimations', 'string', ['number']) as SpineWrappedAPI['getAnimations'],+ getSkins: cw('spine_getSkins', 'string', ['number']) as SpineWrappedAPI['getSkins'],+ getBonePosition: cw('spine_getBonePosition', 'number', ['number', 'string', 'number', 'number']) as SpineWrappedAPI['getBonePosition'],+ getBoneRotation: cw('spine_getBoneRotation', 'number', ['number', 'string']) as SpineWrappedAPI['getBoneRotation'],+ getBounds: cw('spine_getBounds', null, ['number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['getBounds'],+ getMeshBatchCount: cw('spine_getMeshBatchCount', 'number', ['number']) as SpineWrappedAPI['getMeshBatchCount'],+ getMeshBatchVertexCount: cw('spine_getMeshBatchVertexCount', 'number', ['number', 'number']) as SpineWrappedAPI['getMeshBatchVertexCount'],+ getMeshBatchIndexCount: cw('spine_getMeshBatchIndexCount', 'number', ['number', 'number']) as SpineWrappedAPI['getMeshBatchIndexCount'],+ getMeshBatchData: cw('spine_getMeshBatchData', null, ['number', 'number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['getMeshBatchData'],};}@@ -49,11 +98,13 @@ export type SpineModuleFactory = (config?: Record<string, unknown>) => Promise<Sexport async function loadSpineModule(wasmUrl: string,factory?: SpineModuleFactory-): Promise<SpineWasmModule> {+): Promise<{ raw: SpineWasmModule; api: SpineWrappedAPI }> {+ let raw: SpineWasmModule;if (factory) {- return factory();+ raw = await factory();+ } else {+ const moduleFactory = (await import(/* webpackIgnore: true */ wasmUrl)).default as SpineModuleFactory;+ raw = await moduleFactory();}-- const moduleFactory = (await import(/* webpackIgnore: true */ wasmUrl)).default as SpineModuleFactory;- return moduleFactory();+ return { raw, api: wrapSpineModule(raw) };}diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.tsindex 404bf61e4..f2861228e 100644--- a/sdk/src/spine/SpinePlugin.ts+++ b/sdk/src/spine/SpinePlugin.ts@@ -7,7 +7,7 @@ import type { Plugin } from '../app';import type { App } from '../app';import type { ESEngineModule } from '../wasm';import { defineResource } from '../resource';-import { loadSpineModule, type SpineWasmModule, type SpineModuleFactory } from './SpineModuleLoader';+import { loadSpineModule, type SpineModuleFactory } from './SpineModuleLoader';import { SpineModuleController } from './SpineController';export const SpineResource = defineResource<SpineModuleController | null>(null, 'SpineController');@@ -25,8 +25,8 @@ export class SpinePlugin implements Plugin {const coreModule = app.wasmModule!;const initPromise = loadSpineModule(this.wasmUrl_, this.factory_).then(- (spineModule: SpineWasmModule) => {- const controller = new SpineModuleController(spineModule);+ ({ raw, api }) => {+ const controller = new SpineModuleController(raw, api);app.insertResource(SpineResource, controller);return { controller, coreModule };}diff --git a/sdk/src/spine/index.ts b/sdk/src/spine/index.tsindex b77c4f148..403f11c0a 100644--- a/sdk/src/spine/index.ts+++ b/sdk/src/spine/index.ts@@ -18,6 +18,8 @@ export {} from './SpineController';export {loadSpineModule,+ wrapSpineModule,type SpineWasmModule,+ type SpineWrappedAPI,type SpineModuleFactory,} from './SpineModuleLoader';diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cppindex bd318b997..cdbd517f1 100644--- a/src/esengine/bindings/PhysicsModuleEntry.cpp+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp@@ -1,13 +1,14 @@/*** @file PhysicsModuleEntry.cpp- * @brief Standalone Physics WASM module entry point+ * @brief Physics WASM module entry point (supports both standalone and SIDE_MODULE)** Pure computation module (no GL/engine dependencies).* Handles: Box2D world management, body creation, stepping, transform extraction.+ *+ * All functions exported as extern "C" + EMSCRIPTEN_KEEPALIVE for SIDE_MODULE compatibility.*/#include <emscripten.h>-#include <emscripten/bind.h>#include <box2d/box2d.h>@@ -31,30 +32,15 @@ static std::unordered_map<uint32_t, b2ShapeId> g_entityToShape;// [entityId_bits, x, y, angle, ...]static std::vector<float> g_dynamicTransformBuffer;-// =============================================================================-// Collision Event Structures-// =============================================================================+// Collision event flat buffers: [entityA0_bits, entityB0_bits, nx0, ny0, cx0, cy0, ...]+static std::vector<float> g_collisionEnterBuffer;+// [entityA0_bits, entityB0_bits, ...]+static std::vector<float> g_collisionExitBuffer;+// [sensor0_bits, visitor0_bits, ...]+static std::vector<float> g_sensorEnterBuffer;+static std::vector<float> g_sensorExitBuffer;-struct CollisionEventJS {- uint32_t entityA;- uint32_t entityB;- float normalX;- float normalY;- float contactX;- float contactY;-};--struct SensorEventJS {- uint32_t sensorEntity;- uint32_t visitorEntity;-};--struct CollisionEventsJS {- std::vector<CollisionEventJS> enters;- std::vector<CollisionEventJS> exits;- std::vector<SensorEventJS> sensorEnters;- std::vector<SensorEventJS> sensorExits;-};+static float g_velocityBuffer[2];// =============================================================================// Helper: Entity ID from body user data@@ -71,10 +57,21 @@ static uint32_t entityFromShape(b2ShapeId shapeId) {return entityFromBody(bodyId);}+static void pushEntityBits(std::vector<float>& buf, uint32_t entityId) {+ float bits;+ std::memcpy(&bits, &entityId, sizeof(float));+ buf.push_back(bits);+}+// =============================================================================-// World Lifecycle+// Exported Functions// =============================================================================+extern "C" {++// World Lifecycle++EMSCRIPTEN_KEEPALIVEvoid physics_init(float gx, float gy, float timestep, int substeps) {if (b2World_IsValid(g_worldId)) return;@@ -87,25 +84,29 @@ void physics_init(float gx, float gy, float timestep, int substeps) {g_accumulator = 0.0f;}+EMSCRIPTEN_KEEPALIVEvoid physics_shutdown() {if (!b2World_IsValid(g_worldId)) return;g_entityToBody.clear();g_entityToShape.clear();g_dynamicTransformBuffer.clear();+ g_collisionEnterBuffer.clear();+ g_collisionExitBuffer.clear();+ g_sensorEnterBuffer.clear();+ g_sensorExitBuffer.clear();g_accumulator = 0.0f;b2DestroyWorld(g_worldId);g_worldId = b2_nullWorldId;}-// =============================================================================// Body Management-// =============================================================================+EMSCRIPTEN_KEEPALIVEvoid physics_createBody(uint32_t entityId, int bodyType, float x, float y, float angle,float gravityScale, float linearDamping, float angularDamping,- bool fixedRotation, bool bullet) {+ int fixedRotation, int bullet) {if (!b2World_IsValid(g_worldId)) return;if (g_entityToBody.contains(entityId)) return;@@ -122,14 +123,15 @@ void physics_createBody(uint32_t entityId, int bodyType, float x, float y, floatbodyDef.gravityScale = gravityScale;bodyDef.linearDamping = linearDamping;bodyDef.angularDamping = angularDamping;- bodyDef.isBullet = bullet;- bodyDef.motionLocks.angularZ = fixedRotation;+ bodyDef.isBullet = bullet != 0;+ bodyDef.motionLocks.angularZ = fixedRotation != 0;b2BodyId bodyId = b2CreateBody(g_worldId, &bodyDef);b2Body_SetUserData(bodyId, reinterpret_cast<void*>(static_cast<uintptr_t>(entityId)));g_entityToBody[entityId] = bodyId;}+EMSCRIPTEN_KEEPALIVEvoid physics_destroyBody(uint32_t entityId) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -141,17 +143,17 @@ void physics_destroyBody(uint32_t entityId) {g_entityToShape.erase(entityId);}-bool physics_hasBody(uint32_t entityId) {- return g_entityToBody.contains(entityId);+EMSCRIPTEN_KEEPALIVE+int physics_hasBody(uint32_t entityId) {+ return g_entityToBody.contains(entityId) ? 1 : 0;}-// =============================================================================// Shape Management-// =============================================================================+EMSCRIPTEN_KEEPALIVEvoid physics_addBoxShape(uint32_t entityId, float halfW, float halfH,float offX, float offY,- float density, float friction, float restitution, bool isSensor) {+ float density, float friction, float restitution, int isSensor) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -159,18 +161,19 @@ void physics_addBoxShape(uint32_t entityId, float halfW, float halfH,shapeDef.density = density;shapeDef.material.friction = friction;shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor;+ shapeDef.isSensor = isSensor != 0;shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor;+ shapeDef.enableSensorEvents = isSensor != 0;b2Polygon polygon = b2MakeOffsetBox(halfW, halfH, {offX, offY}, b2MakeRot(0.0f));b2ShapeId shapeId = b2CreatePolygonShape(it->second, &shapeDef, &polygon);g_entityToShape[entityId] = shapeId;}+EMSCRIPTEN_KEEPALIVEvoid physics_addCircleShape(uint32_t entityId, float radius,float offX, float offY,- float density, float friction, float restitution, bool isSensor) {+ float density, float friction, float restitution, int isSensor) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -178,9 +181,9 @@ void physics_addCircleShape(uint32_t entityId, float radius,shapeDef.density = density;shapeDef.material.friction = friction;shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor;+ shapeDef.isSensor = isSensor != 0;shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor;+ shapeDef.enableSensorEvents = isSensor != 0;b2Circle circle;circle.center = {offX, offY};@@ -190,9 +193,10 @@ void physics_addCircleShape(uint32_t entityId, float radius,g_entityToShape[entityId] = shapeId;}+EMSCRIPTEN_KEEPALIVEvoid physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,float offX, float offY,- float density, float friction, float restitution, bool isSensor) {+ float density, float friction, float restitution, int isSensor) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -200,9 +204,9 @@ void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,shapeDef.density = density;shapeDef.material.friction = friction;shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor;+ shapeDef.isSensor = isSensor != 0;shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor;+ shapeDef.enableSensorEvents = isSensor != 0;b2Capsule capsule;capsule.center1 = {offX, offY + halfHeight};@@ -213,10 +217,9 @@ void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,g_entityToShape[entityId] = shapeId;}-// =============================================================================// Simulation-// =============================================================================+EMSCRIPTEN_KEEPALIVEvoid physics_step(float dt) {if (!b2World_IsValid(g_worldId)) return;@@ -228,10 +231,9 @@ void physics_step(float dt) {}}-// =============================================================================// Transform Sync-// =============================================================================+EMSCRIPTEN_KEEPALIVEvoid physics_setBodyTransform(uint32_t entityId, float x, float y, float angle) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -240,6 +242,7 @@ void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle)b2Body_SetTransform(it->second, {x, y}, b2MakeRot(angle));}+EMSCRIPTEN_KEEPALIVEint physics_getDynamicBodyCount() {int count = 0;for (auto& [entityId, bodyId] : g_entityToBody) {@@ -251,6 +254,7 @@ int physics_getDynamicBodyCount() {return count;}+EMSCRIPTEN_KEEPALIVEuintptr_t physics_getDynamicBodyTransforms() {g_dynamicTransformBuffer.clear();@@ -261,10 +265,7 @@ uintptr_t physics_getDynamicBodyTransforms() {b2Vec2 pos = b2Body_GetPosition(bodyId);float angle = b2Rot_GetAngle(b2Body_GetRotation(bodyId));- float entityBits;- std::memcpy(&entityBits, &entityId, sizeof(float));-- g_dynamicTransformBuffer.push_back(entityBits);+ pushEntityBits(g_dynamicTransformBuffer, entityId);g_dynamicTransformBuffer.push_back(pos.x);g_dynamicTransformBuffer.push_back(pos.y);g_dynamicTransformBuffer.push_back(angle);@@ -273,13 +274,16 @@ uintptr_t physics_getDynamicBodyTransforms() {return reinterpret_cast<uintptr_t>(g_dynamicTransformBuffer.data());}-// =============================================================================-// Collision Events-// =============================================================================+// Collision Events (flat buffer)++EMSCRIPTEN_KEEPALIVE+void physics_collectEvents() {+ g_collisionEnterBuffer.clear();+ g_collisionExitBuffer.clear();+ g_sensorEnterBuffer.clear();+ g_sensorExitBuffer.clear();-CollisionEventsJS physics_getCollisionEvents() {- CollisionEventsJS result;- if (!b2World_IsValid(g_worldId)) return result;+ if (!b2World_IsValid(g_worldId)) return;b2ContactEvents contactEvents = b2World_GetContactEvents(g_worldId);@@ -289,7 +293,12 @@ CollisionEventsJS physics_getCollisionEvents() {uint32_t entityB = entityFromShape(evt.shapeIdB);if (entityA == 0xFFFFFFFF || entityB == 0xFFFFFFFF) continue;- result.enters.push_back({entityA, entityB, 0, 0, 0, 0});+ pushEntityBits(g_collisionEnterBuffer, entityA);+ pushEntityBits(g_collisionEnterBuffer, entityB);+ g_collisionEnterBuffer.push_back(0);+ g_collisionEnterBuffer.push_back(0);+ g_collisionEnterBuffer.push_back(0);+ g_collisionEnterBuffer.push_back(0);}for (int i = 0; i < contactEvents.endCount; ++i) {@@ -300,7 +309,8 @@ CollisionEventsJS physics_getCollisionEvents() {uint32_t entityB = entityFromShape(evt.shapeIdB);if (entityA == 0xFFFFFFFF || entityB == 0xFFFFFFFF) continue;- result.exits.push_back({entityA, entityB, 0, 0, 0, 0});+ pushEntityBits(g_collisionExitBuffer, entityA);+ pushEntityBits(g_collisionExitBuffer, entityB);}b2SensorEvents sensorEvents = b2World_GetSensorEvents(g_worldId);@@ -311,7 +321,8 @@ CollisionEventsJS physics_getCollisionEvents() {uint32_t visitor = entityFromShape(evt.visitorShapeId);if (sensor == 0xFFFFFFFF || visitor == 0xFFFFFFFF) continue;- result.sensorEnters.push_back({sensor, visitor});+ pushEntityBits(g_sensorEnterBuffer, sensor);+ pushEntityBits(g_sensorEnterBuffer, visitor);}for (int i = 0; i < sensorEvents.endCount; ++i) {@@ -322,16 +333,54 @@ CollisionEventsJS physics_getCollisionEvents() {uint32_t visitor = entityFromShape(evt.visitorShapeId);if (sensor == 0xFFFFFFFF || visitor == 0xFFFFFFFF) continue;- result.sensorExits.push_back({sensor, visitor});+ pushEntityBits(g_sensorExitBuffer, sensor);+ pushEntityBits(g_sensorExitBuffer, visitor);}+}- return result;+EMSCRIPTEN_KEEPALIVE+int physics_getCollisionEnterCount() {+ return static_cast<int>(g_collisionEnterBuffer.size() / 6);+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getCollisionEnterBuffer() {+ return reinterpret_cast<uintptr_t>(g_collisionEnterBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+int physics_getCollisionExitCount() {+ return static_cast<int>(g_collisionExitBuffer.size() / 2);+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getCollisionExitBuffer() {+ return reinterpret_cast<uintptr_t>(g_collisionExitBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+int physics_getSensorEnterCount() {+ return static_cast<int>(g_sensorEnterBuffer.size() / 2);+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getSensorEnterBuffer() {+ return reinterpret_cast<uintptr_t>(g_sensorEnterBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+int physics_getSensorExitCount() {+ return static_cast<int>(g_sensorExitBuffer.size() / 2);+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getSensorExitBuffer() {+ return reinterpret_cast<uintptr_t>(g_sensorExitBuffer.data());}-// =============================================================================// Force / Impulse / Velocity-// =============================================================================+EMSCRIPTEN_KEEPALIVEvoid physics_applyForce(uint32_t entityId, float forceX, float forceY) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -341,6 +390,7 @@ void physics_applyForce(uint32_t entityId, float forceX, float forceY) {b2Body_ApplyForce(it->second, {forceX, forceY}, center, true);}+EMSCRIPTEN_KEEPALIVEvoid physics_applyImpulse(uint32_t entityId, float impulseX, float impulseY) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -350,6 +400,7 @@ void physics_applyImpulse(uint32_t entityId, float impulseX, float impulseY) {b2Body_ApplyLinearImpulse(it->second, {impulseX, impulseY}, center, true);}+EMSCRIPTEN_KEEPALIVEvoid physics_setLinearVelocity(uint32_t entityId, float vx, float vy) {auto it = g_entityToBody.find(entityId);if (it == g_entityToBody.end()) return;@@ -358,71 +409,24 @@ void physics_setLinearVelocity(uint32_t entityId, float vx, float vy) {b2Body_SetLinearVelocity(it->second, {vx, vy});}-struct Vec2JS {- float x;- float y;-};--Vec2JS physics_getLinearVelocity(uint32_t entityId) {+EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getLinearVelocity(uint32_t entityId) {auto it = g_entityToBody.find(entityId);- if (it == g_entityToBody.end()) return {0, 0};- if (!b2Body_IsValid(it->second)) return {0, 0};+ if (it == g_entityToBody.end()) {+ g_velocityBuffer[0] = 0;+ g_velocityBuffer[1] = 0;+ return reinterpret_cast<uintptr_t>(g_velocityBuffer);+ }+ if (!b2Body_IsValid(it->second)) {+ g_velocityBuffer[0] = 0;+ g_velocityBuffer[1] = 0;+ return reinterpret_cast<uintptr_t>(g_velocityBuffer);+ }b2Vec2 v = b2Body_GetLinearVelocity(it->second);- return {v.x, v.y};+ g_velocityBuffer[0] = v.x;+ g_velocityBuffer[1] = v.y;+ return reinterpret_cast<uintptr_t>(g_velocityBuffer);}-// =============================================================================-// Emscripten Bindings-// =============================================================================--EMSCRIPTEN_BINDINGS(physics_module) {- emscripten::function("physics_init", &physics_init);- emscripten::function("physics_shutdown", &physics_shutdown);-- emscripten::function("physics_createBody", &physics_createBody);- emscripten::function("physics_destroyBody", &physics_destroyBody);- emscripten::function("physics_hasBody", &physics_hasBody);-- emscripten::function("physics_addBoxShape", &physics_addBoxShape);- emscripten::function("physics_addCircleShape", &physics_addCircleShape);- emscripten::function("physics_addCapsuleShape", &physics_addCapsuleShape);-- emscripten::function("physics_step", &physics_step);-- emscripten::function("physics_setBodyTransform", &physics_setBodyTransform);- emscripten::function("physics_getDynamicBodyCount", &physics_getDynamicBodyCount);- emscripten::function("physics_getDynamicBodyTransforms", &physics_getDynamicBodyTransforms);-- emscripten::function("physics_applyForce", &physics_applyForce);- emscripten::function("physics_applyImpulse", &physics_applyImpulse);- emscripten::function("physics_setLinearVelocity", &physics_setLinearVelocity);- emscripten::function("physics_getLinearVelocity", &physics_getLinearVelocity);-- emscripten::value_object<Vec2JS>("PhysicsVec2JS")- .field("x", &Vec2JS::x)- .field("y", &Vec2JS::y);-- emscripten::value_object<CollisionEventJS>("CollisionEventJS")- .field("entityA", &CollisionEventJS::entityA)- .field("entityB", &CollisionEventJS::entityB)- .field("normalX", &CollisionEventJS::normalX)- .field("normalY", &CollisionEventJS::normalY)- .field("contactX", &CollisionEventJS::contactX)- .field("contactY", &CollisionEventJS::contactY);-- emscripten::value_object<SensorEventJS>("SensorEventJS")- .field("sensorEntity", &SensorEventJS::sensorEntity)- .field("visitorEntity", &SensorEventJS::visitorEntity);-- emscripten::register_vector<CollisionEventJS>("CollisionEventJSVector");- emscripten::register_vector<SensorEventJS>("SensorEventJSVector");-- emscripten::value_object<CollisionEventsJS>("CollisionEventsJS")- .field("enters", &CollisionEventsJS::enters)- .field("exits", &CollisionEventsJS::exits)- .field("sensorEnters", &CollisionEventsJS::sensorEnters)- .field("sensorExits", &CollisionEventsJS::sensorExits);-- emscripten::function("physics_getCollisionEvents", &physics_getCollisionEvents);-}+} // extern "C"diff --git a/src/esengine/bindings/SpineModuleEntry.cpp b/src/esengine/bindings/SpineModuleEntry.cppindex b40e2fd39..6b389c3cb 100644--- a/src/esengine/bindings/SpineModuleEntry.cpp+++ b/src/esengine/bindings/SpineModuleEntry.cpp@@ -2,20 +2,17 @@* @file SpineModuleEntry.cpp* @brief Standalone Spine WASM module entry point*- * Pure computation module (no GL dependencies).+ * Pure computation module (no GL dependencies, no filesystem).* Handles: skeleton loading, animation update, mesh extraction.* Core WASM handles all rendering via renderer_submitTriangles.+ *+ * Uses spine-c (pure C runtime) for minimal WASM size.*/#include <emscripten.h>-#include <emscripten/bind.h>#include <spine/spine.h>-#include <spine/Extension.h>-#include <spine/Atlas.h>-#include <spine/RegionAttachment.h>-#include <spine/MeshAttachment.h>-#include <spine/ClippingAttachment.h>+#include <spine/extension.h>#include <unordered_map>#include <vector>@@ -24,86 +21,53 @@#include <cstdint>// =============================================================================-// Spine Extension (file I/O via Emscripten FS)+// Spine-C Required Callbacks// =============================================================================-class SpineModuleExtension : public spine::DefaultSpineExtension {-protected:- char* _readFile(const spine::String& path, int* length) override {- FILE* file = fopen(path.buffer(), "rb");- if (!file) {- *length = 0;- return nullptr;- }- fseek(file, 0, SEEK_END);- *length = static_cast<int>(ftell(file));- fseek(file, 0, SEEK_SET);-- char* data = SpineExtension::alloc<char>(*length, __FILE__, __LINE__);- fread(data, 1, *length, file);- fclose(file);- return data;- }-};--static SpineModuleExtension* g_extension = nullptr;--static void ensureExtension() {- if (!g_extension) {- g_extension = new SpineModuleExtension();- spine::SpineExtension::setInstance(g_extension);- }+void _spAtlasPage_createTexture(spAtlasPage* self, const char* path) {+ (void)self;+ (void)path;}-namespace spine {-SpineExtension* getDefaultExtension() {- if (!g_extension) {- g_extension = new SpineModuleExtension();- }- return g_extension;+void _spAtlasPage_disposeTexture(spAtlasPage* self) {+ (void)self;}++char* _spUtil_readFile(const char* path, int* length) {+ (void)path;+ *length = 0;+ return nullptr;}// =============================================================================-// Texture Loader (deferred — JS provides texture IDs)+// Texture ID Helpers// =============================================================================-class DeferredTextureLoader : public spine::TextureLoader {-public:- void load(spine::AtlasPage& page, const spine::String& path) override {- page.texturePath = path;- }-- void unload(void*) override {}-};-#ifdef ES_SPINE_38-static uint32_t getTextureId(spine::RegionAttachment* attachment) {- auto* atlasRegion = static_cast<spine::AtlasRegion*>(attachment->getRendererObject());- if (!atlasRegion || !atlasRegion->page) return 0;+static uint32_t getRegionTextureId(spRegionAttachment* attachment) {+ auto* region = reinterpret_cast<spAtlasRegion*>(attachment->rendererObject);+ if (!region || !region->page) return 0;return static_cast<uint32_t>(- reinterpret_cast<uintptr_t>(atlasRegion->page->getRendererObject()));+ reinterpret_cast<uintptr_t>(region->page->rendererObject));}-static uint32_t getTextureId(spine::MeshAttachment* attachment) {- auto* atlasRegion = static_cast<spine::AtlasRegion*>(attachment->getRendererObject());- if (!atlasRegion || !atlasRegion->page) return 0;+static uint32_t getMeshTextureId(spMeshAttachment* attachment) {+ auto* region = reinterpret_cast<spAtlasRegion*>(attachment->rendererObject);+ if (!region || !region->page) return 0;return static_cast<uint32_t>(- reinterpret_cast<uintptr_t>(atlasRegion->page->getRendererObject()));+ reinterpret_cast<uintptr_t>(region->page->rendererObject));}#else-static uint32_t getTextureId(spine::RegionAttachment* attachment) {- auto* region = attachment->getRegion();- if (!region) return 0;+static uint32_t getRegionTextureId(spRegionAttachment* attachment) {+ if (!attachment->region) return 0;return static_cast<uint32_t>(- reinterpret_cast<uintptr_t>(region->rendererObject));+ reinterpret_cast<uintptr_t>(attachment->region->rendererObject));}-static uint32_t getTextureId(spine::MeshAttachment* attachment) {- auto* region = attachment->getRegion();- if (!region) return 0;+static uint32_t getMeshTextureId(spMeshAttachment* attachment) {+ if (!attachment->region) return 0;return static_cast<uint32_t>(- reinterpret_cast<uintptr_t>(region->rendererObject));+ reinterpret_cast<uintptr_t>(attachment->region->rendererObject));}#endif@@ -112,15 +76,14 @@ static uint32_t getTextureId(spine::MeshAttachment* attachment) {// =============================================================================struct SkeletonHandle {- std::unique_ptr<spine::Atlas> atlas;- std::unique_ptr<spine::SkeletonData> skeletonData;- std::unique_ptr<spine::AnimationStateData> stateData;- DeferredTextureLoader textureLoader;+ spAtlas* atlas = nullptr;+ spSkeletonData* skeletonData = nullptr;+ spAnimationStateData* stateData = nullptr;};struct SpineInstance {- std::unique_ptr<spine::Skeleton> skeleton;- std::unique_ptr<spine::AnimationState> state;+ spSkeleton* skeleton = nullptr;+ spAnimationState* state = nullptr;int skeletonHandle = -1;};@@ -139,45 +102,65 @@ static int g_nextInstanceId = 1;static std::vector<MeshBatch> g_meshBatches;static std::vector<float> g_worldVertices;+static std::string g_stringBuffer;++static void destroyInstance(SpineInstance& inst) {+ if (inst.state) spAnimationState_dispose(inst.state);+ if (inst.skeleton) spSkeleton_dispose(inst.skeleton);+}++static void destroySkeleton(SkeletonHandle& h) {+ if (h.stateData) spAnimationStateData_dispose(h.stateData);+ if (h.skeletonData) spSkeletonData_dispose(h.skeletonData);+ if (h.atlas) spAtlas_dispose(h.atlas);+}+// =============================================================================// Resource Management// =============================================================================-int spine_loadSkeleton(const std::string& skelPath, const std::string& atlasText,- int atlasLen, bool isBinary) {- ensureExtension();+extern "C" {- auto& handle = g_skeletons[g_nextSkeletonId];+EMSCRIPTEN_KEEPALIVE+int spine_loadSkeleton(uintptr_t skelDataPtr, int skelDataLen,+ const char* atlasText, int atlasLen, int isBinary) {+ int id = g_nextSkeletonId;+ auto& handle = g_skeletons[id];- handle.atlas = std::make_unique<spine::Atlas>(- atlasText.c_str(), atlasLen, "", &handle.textureLoader, true);-- if (handle.atlas->getPages().size() == 0) {- g_skeletons.erase(g_nextSkeletonId);+ handle.atlas = spAtlas_create(atlasText, atlasLen, "", nullptr);+ if (!handle.atlas || !handle.atlas->pages) {+ g_skeletons.erase(id);return -1;}if (isBinary) {- spine::SkeletonBinary binary(handle.atlas.get());- binary.setScale(1.0f);- handle.skeletonData.reset(binary.readSkeletonDataFile(spine::String(skelPath.c_str())));+ spSkeletonBinary* binary = spSkeletonBinary_create(handle.atlas);+ binary->scale = 1.0f;+ handle.skeletonData = spSkeletonBinary_readSkeletonData(+ binary, reinterpret_cast<const unsigned char*>(skelDataPtr), skelDataLen);+ spSkeletonBinary_dispose(binary);} else {- spine::SkeletonJson json(handle.atlas.get());- json.setScale(1.0f);- handle.skeletonData.reset(json.readSkeletonDataFile(spine::String(skelPath.c_str())));+ spSkeletonJson* json = spSkeletonJson_create(handle.atlas);+ json->scale = 1.0f;+ handle.skeletonData = spSkeletonJson_readSkeletonData(+ json, reinterpret_cast<const char*>(skelDataPtr));+ spSkeletonJson_dispose(json);}if (!handle.skeletonData) {- g_skeletons.erase(g_nextSkeletonId);+ destroySkeleton(handle);+ g_skeletons.erase(id);return -1;}- handle.stateData = std::make_unique<spine::AnimationStateData>(handle.skeletonData.get());- handle.stateData->setDefaultMix(0.2f);+ handle.stateData = spAnimationStateData_create(handle.skeletonData);+ handle.stateData->defaultMix = 0.2f;- return g_nextSkeletonId++;+ g_nextSkeletonId++;+ return id;}+EMSCRIPTEN_KEEPALIVEvoid spine_unloadSkeleton(int handle) {auto it = g_skeletons.find(handle);if (it == g_skeletons.end()) return;@@ -189,127 +172,148 @@ void spine_unloadSkeleton(int handle) {}}for (int id : toRemove) {+ destroyInstance(g_instances[id]);g_instances.erase(id);}+ destroySkeleton(it->second);g_skeletons.erase(it);}+EMSCRIPTEN_KEEPALIVEint spine_getAtlasPageCount(int handle) {auto it = g_skeletons.find(handle);if (it == g_skeletons.end()) return 0;- return static_cast<int>(it->second.atlas->getPages().size());+ int count = 0;+ spAtlasPage* page = it->second.atlas->pages;+ while (page) {+ count++;+ page = page->next;+ }+ return count;}-std::string spine_getAtlasPageTextureName(int handle, int pageIndex) {+EMSCRIPTEN_KEEPALIVE+const char* spine_getAtlasPageTextureName(int handle, int pageIndex) {auto it = g_skeletons.find(handle);if (it == g_skeletons.end()) return "";- auto& pages = it->second.atlas->getPages();- if (pageIndex < 0 || pageIndex >= static_cast<int>(pages.size())) return "";- return std::string(pages[pageIndex]->texturePath.buffer());+ spAtlasPage* page = it->second.atlas->pages;+ for (int i = 0; i < pageIndex && page; i++) {+ page = page->next;+ }+ if (!page) return "";+ g_stringBuffer = page->name;+ return g_stringBuffer.c_str();}+EMSCRIPTEN_KEEPALIVEvoid spine_setAtlasPageTexture(int handle, int pageIndex,uint32_t textureId, int width, int height) {auto it = g_skeletons.find(handle);if (it == g_skeletons.end()) return;- auto& pages = it->second.atlas->getPages();- if (pageIndex < 0 || pageIndex >= static_cast<int>(pages.size())) return;+ spAtlasPage* page = it->second.atlas->pages;+ for (int i = 0; i < pageIndex && page; i++) {+ page = page->next;+ }+ if (!page) return;- auto* page = pages[pageIndex];void* texPtr = reinterpret_cast<void*>(static_cast<uintptr_t>(textureId));-#ifdef ES_SPINE_38- page->setRendererObject(texPtr);-#else- page->texture = texPtr;- auto& regions = it->second.atlas->getRegions();- for (size_t i = 0; i < regions.size(); ++i) {- if (regions[i]->page == page) {- regions[i]->rendererObject = texPtr;+ page->rendererObject = texPtr;+ page->width = width;+ page->height = height;++#ifndef ES_SPINE_38+ spAtlasRegion* region = it->second.atlas->regions;+ while (region) {+ if (region->page == page) {+ region->super.rendererObject = texPtr;}+ region = region->next;}#endif- page->width = width;- page->height = height;}// =============================================================================// Instance Management// =============================================================================+EMSCRIPTEN_KEEPALIVEint spine_createInstance(int skeletonHandle) {auto it = g_skeletons.find(skeletonHandle);if (it == g_skeletons.end()) return -1;- auto& skelData = it->second;- auto& inst = g_instances[g_nextInstanceId];+ int id = g_nextInstanceId;+ auto& inst = g_instances[id];inst.skeletonHandle = skeletonHandle;- inst.skeleton = std::make_unique<spine::Skeleton>(skelData.skeletonData.get());- inst.state = std::make_unique<spine::AnimationState>(skelData.stateData.get());- inst.skeleton->setToSetupPose();+ inst.skeleton = spSkeleton_create(it->second.skeletonData);+ inst.state = spAnimationState_create(it->second.stateData);+ spSkeleton_setToSetupPose(inst.skeleton);#ifdef ES_SPINE_38- inst.skeleton->updateWorldTransform();+ spSkeleton_updateWorldTransform(inst.skeleton);#else- inst.skeleton->updateWorldTransform(spine::Physics_Update);+ spSkeleton_updateWorldTransform(inst.skeleton, SP_PHYSICS_UPDATE);#endif- return g_nextInstanceId++;+ g_nextInstanceId++;+ return id;}+EMSCRIPTEN_KEEPALIVEvoid spine_destroyInstance(int instanceId) {- g_instances.erase(instanceId);+ auto it = g_instances.find(instanceId);+ if (it == g_instances.end()) return;+ destroyInstance(it->second);+ g_instances.erase(it);}// =============================================================================// Animation Control// =============================================================================-bool spine_playAnimation(int instanceId, const std::string& name, bool loop, int track) {+EMSCRIPTEN_KEEPALIVE+int spine_playAnimation(int instanceId, const char* name, int loop, int track) {auto it = g_instances.find(instanceId);- if (it == g_instances.end()) return false;-- auto* anim = it->second.skeleton->getData()->findAnimation(spine::String(name.c_str()));- if (!anim) return false;-- it->second.state->setAnimation(track, anim, loop);- return true;+ if (it == g_instances.end()) return 0;+ spTrackEntry* entry = spAnimationState_setAnimationByName(+ it->second.state, track, name, loop);+ return entry ? 1 : 0;}-bool spine_addAnimation(int instanceId, const std::string& name,- bool loop, float delay, int track) {+EMSCRIPTEN_KEEPALIVE+int spine_addAnimation(int instanceId, const char* name,+ int loop, float delay, int track) {auto it = g_instances.find(instanceId);- if (it == g_instances.end()) return false;-- auto* anim = it->second.skeleton->getData()->findAnimation(spine::String(name.c_str()));- if (!anim) return false;-- it->second.state->addAnimation(track, anim, loop, delay);- return true;+ if (it == g_instances.end()) return 0;+ spTrackEntry* entry = spAnimationState_addAnimationByName(+ it->second.state, track, name, loop, delay);+ return entry ? 1 : 0;}-void spine_setSkin(int instanceId, const std::string& name) {+EMSCRIPTEN_KEEPALIVE+void spine_setSkin(int instanceId, const char* name) {auto it = g_instances.find(instanceId);if (it == g_instances.end()) return;- if (name.empty()) {- it->second.skeleton->setSkin(nullptr);+ if (!name || name[0] == '\0') {+ spSkeleton_setSkin(it->second.skeleton, nullptr);} else {- it->second.skeleton->setSkin(spine::String(name.c_str()));+ spSkeleton_setSkinByName(it->second.skeleton, name);}- it->second.skeleton->setSlotsToSetupPose();+ spSkeleton_setSlotsToSetupPose(it->second.skeleton);}+EMSCRIPTEN_KEEPALIVEvoid spine_update(int instanceId, float dt) {auto it = g_instances.find(instanceId);if (it == g_instances.end()) return;- it->second.state->update(dt);- it->second.state->apply(*it->second.skeleton);+ spAnimationState_update(it->second.state, dt);+ spAnimationState_apply(it->second.state, it->second.skeleton);#ifdef ES_SPINE_38- it->second.skeleton->updateWorldTransform();+ spSkeleton_updateWorldTransform(it->second.skeleton);#else- it->second.skeleton->update(dt);- it->second.skeleton->updateWorldTransform(spine::Physics_Update);+ spSkeleton_update(it->second.skeleton, dt);+ spSkeleton_updateWorldTransform(it->second.skeleton, SP_PHYSICS_UPDATE);#endif}@@ -317,61 +321,72 @@ void spine_update(int instanceId, float dt) {// Query// =============================================================================-std::string spine_getAnimations(int instanceId) {+EMSCRIPTEN_KEEPALIVE+const char* spine_getAnimations(int instanceId) {auto it = g_instances.find(instanceId);- if (it == g_instances.end()) return "[]";-- auto& anims = it->second.skeleton->getData()->getAnimations();- std::string result = "[";- for (size_t i = 0; i < anims.size(); ++i) {- if (i > 0) result += ",";- result += "\"";- result += anims[i]->getName().buffer();- result += "\"";+ if (it == g_instances.end()) {+ g_stringBuffer = "[]";+ return g_stringBuffer.c_str();+ }++ spSkeletonData* data = it->second.skeleton->data;+ g_stringBuffer = "[";+ for (int i = 0; i < data->animationsCount; ++i) {+ if (i > 0) g_stringBuffer += ",";+ g_stringBuffer += "\"";+ g_stringBuffer += data->animations[i]->name;+ g_stringBuffer += "\"";}- result += "]";- return result;+ g_stringBuffer += "]";+ return g_stringBuffer.c_str();}-std::string spine_getSkins(int instanceId) {+EMSCRIPTEN_KEEPALIVE+const char* spine_getSkins(int instanceId) {auto it = g_instances.find(instanceId);- if (it == g_instances.end()) return "[]";-- auto& skins = it->second.skeleton->getData()->getSkins();- std::string result = "[";- for (size_t i = 0; i < skins.size(); ++i) {- if (i > 0) result += ",";- result += "\"";- result += skins[i]->getName().buffer();- result += "\"";+ if (it == g_instances.end()) {+ g_stringBuffer = "[]";+ return g_stringBuffer.c_str();+ }++ spSkeletonData* data = it->second.skeleton->data;+ g_stringBuffer = "[";+ for (int i = 0; i < data->skinsCount; ++i) {+ if (i > 0) g_stringBuffer += ",";+ g_stringBuffer += "\"";+ g_stringBuffer += data->skins[i]->name;+ g_stringBuffer += "\"";}- result += "]";- return result;+ g_stringBuffer += "]";+ return g_stringBuffer.c_str();}-bool spine_getBonePosition(int instanceId, const std::string& bone,- uintptr_t outXPtr, uintptr_t outYPtr) {+EMSCRIPTEN_KEEPALIVE+int spine_getBonePosition(int instanceId, const char* bone,+ uintptr_t outXPtr, uintptr_t outYPtr) {auto it = g_instances.find(instanceId);- if (it == g_instances.end()) return false;+ if (it == g_instances.end()) return 0;- auto* b = it->second.skeleton->findBone(spine::String(bone.c_str()));- if (!b) return false;+ spBone* b = spSkeleton_findBone(it->second.skeleton, bone);+ if (!b) return 0;- *reinterpret_cast<float*>(outXPtr) = b->getWorldX();- *reinterpret_cast<float*>(outYPtr) = b->getWorldY();- return true;+ *reinterpret_cast<float*>(outXPtr) = b->worldX;+ *reinterpret_cast<float*>(outYPtr) = b->worldY;+ return 1;}-float spine_getBoneRotation(int instanceId, const std::string& bone) {+EMSCRIPTEN_KEEPALIVE+float spine_getBoneRotation(int instanceId, const char* bone) {auto it = g_instances.find(instanceId);if (it == g_instances.end()) return 0.0f;- auto* b = it->second.skeleton->findBone(spine::String(bone.c_str()));+ spBone* b = spSkeleton_findBone(it->second.skeleton, bone);if (!b) return 0.0f;- return b->getWorldRotationX();+ return spBone_getWorldRotationX(b);}+EMSCRIPTEN_KEEPALIVEvoid spine_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr,uintptr_t outWPtr, uintptr_t outHPtr) {auto* outX = reinterpret_cast<float*>(outXPtr);@@ -385,8 +400,57 @@ void spine_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr,return;}- spine::Vector<float> verts;- it->second.skeleton->getBounds(*outX, *outY, *outW, *outH, verts);+ spSkeleton* skeleton = it->second.skeleton;+ float minX = 1e30f, minY = 1e30f, maxX = -1e30f, maxY = -1e30f;+ bool hasVerts = false;++ for (int i = 0; i < skeleton->slotsCount; i++) {+ spSlot* slot = skeleton->drawOrder[i];+ if (!slot->attachment) continue;++ float* verts = nullptr;+ int vertCount = 0;++ if (slot->attachment->type == SP_ATTACHMENT_REGION) {+ auto* region = reinterpret_cast<spRegionAttachment*>(slot->attachment);+ g_worldVertices.resize(8);+#ifdef ES_SPINE_38+ spRegionAttachment_computeWorldVertices(region, slot->bone, g_worldVertices.data(), 0, 2);+#else+ spRegionAttachment_computeWorldVertices(region, slot, g_worldVertices.data(), 0, 2);+#endif+ verts = g_worldVertices.data();+ vertCount = 4;+ } else if (slot->attachment->type == SP_ATTACHMENT_MESH) {+ auto* mesh = reinterpret_cast<spMeshAttachment*>(slot->attachment);+ vertCount = SUPER(mesh)->worldVerticesLength / 2;+ g_worldVertices.resize(SUPER(mesh)->worldVerticesLength);+ spVertexAttachment_computeWorldVertices(SUPER(mesh), slot, 0,+ SUPER(mesh)->worldVerticesLength, g_worldVertices.data(), 0, 2);+ verts = g_worldVertices.data();+ }++ if (verts && vertCount > 0) {+ hasVerts = true;+ for (int j = 0; j < vertCount; j++) {+ float x = verts[j * 2];+ float y = verts[j * 2 + 1];+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ }+ }++ if (hasVerts) {+ *outX = minX;+ *outY = minY;+ *outW = maxX - minX;+ *outH = maxY - minY;+ } else {+ *outX = *outY = *outW = *outH = 0;+ }}// =============================================================================@@ -399,42 +463,41 @@ static void extractMeshBatches(int instanceId) {auto it = g_instances.find(instanceId);if (it == g_instances.end()) return;- auto* skeleton = it->second.skeleton.get();- auto& drawOrder = skeleton->getDrawOrder();- auto& skelColor = skeleton->getColor();+ spSkeleton* skeleton = it->second.skeleton;+ spColor& skelColor = skeleton->color;MeshBatch* currentBatch = nullptr;uint32_t currentTexture = 0;int currentBlend = 0;- for (size_t i = 0; i < drawOrder.size(); ++i) {- auto* slot = drawOrder[i];+ for (int i = 0; i < skeleton->slotsCount; ++i) {+ spSlot* slot = skeleton->drawOrder[i];if (!slot) continue;- auto* attachment = slot->getAttachment();+ spAttachment* attachment = slot->attachment;if (!attachment) continue;#ifndef ES_SPINE_38- if (!slot->getData().isVisible()) continue;+ if (!slot->data->visible) continue;#endif- if (attachment->getRTTI().isExactly(spine::ClippingAttachment::rtti)) {+ if (attachment->type == SP_ATTACHMENT_CLIPPING) {continue;}- auto& slotColor = slot->getColor();+ spColor& slotColor = slot->color;int blendMode = 0;- switch (slot->getData().getBlendMode()) {- case spine::BlendMode_Normal: blendMode = 0; break;- case spine::BlendMode_Additive: blendMode = 1; break;- case spine::BlendMode_Multiply: blendMode = 2; break;- case spine::BlendMode_Screen: blendMode = 3; break;+ switch (slot->data->blendMode) {+ case SP_BLEND_MODE_NORMAL: blendMode = 0; break;+ case SP_BLEND_MODE_ADDITIVE: blendMode = 1; break;+ case SP_BLEND_MODE_MULTIPLY: blendMode = 2; break;+ case SP_BLEND_MODE_SCREEN: blendMode = 3; break;}- if (attachment->getRTTI().isExactly(spine::RegionAttachment::rtti)) {- auto* region = static_cast<spine::RegionAttachment*>(attachment);+ if (attachment->type == SP_ATTACHMENT_REGION) {+ auto* region = reinterpret_cast<spRegionAttachment*>(attachment);- uint32_t texId = getTextureId(region);+ uint32_t texId = getRegionTextureId(region);if (!texId) continue;if (!currentBatch || texId != currentTexture || blendMode != currentBlend) {@@ -448,13 +511,13 @@ static void extractMeshBatches(int instanceId) {g_worldVertices.resize(8);#ifdef ES_SPINE_38- region->computeWorldVertices(slot->getBone(), g_worldVertices.data(), 0, 2);+ spRegionAttachment_computeWorldVertices(region, slot->bone, g_worldVertices.data(), 0, 2);#else- region->computeWorldVertices(*slot, g_worldVertices.data(), 0, 2);+ spRegionAttachment_computeWorldVertices(region, slot, g_worldVertices.data(), 0, 2);#endif- auto& uvs = region->getUVs();- auto& attachColor = region->getColor();+ float* uvs = region->uvs;+ spColor& attachColor = region->color;float r = skelColor.r * slotColor.r * attachColor.r;float g = skelColor.g * slotColor.g * attachColor.g;@@ -464,7 +527,7 @@ static void extractMeshBatches(int instanceId) {auto baseIndex = static_cast<uint16_t>(currentBatch->vertices.size() / 8);- for (size_t j = 0; j < 4; ++j) {+ for (int j = 0; j < 4; ++j) {currentBatch->vertices.push_back(g_worldVertices[j * 2]);currentBatch->vertices.push_back(g_worldVertices[j * 2 + 1]);currentBatch->vertices.push_back(uvs[j * 2]);@@ -482,10 +545,10 @@ static void extractMeshBatches(int instanceId) {currentBatch->indices.push_back(baseIndex + 3);currentBatch->indices.push_back(baseIndex);- } else if (attachment->getRTTI().isExactly(spine::MeshAttachment::rtti)) {- auto* mesh = static_cast<spine::MeshAttachment*>(attachment);+ } else if (attachment->type == SP_ATTACHMENT_MESH) {+ auto* mesh = reinterpret_cast<spMeshAttachment*>(attachment);- uint32_t texId = getTextureId(mesh);+ uint32_t texId = getMeshTextureId(mesh);if (!texId) continue;if (!currentBatch || texId != currentTexture || blendMode != currentBlend) {@@ -497,14 +560,14 @@ static void extractMeshBatches(int instanceId) {currentBlend = blendMode;}- size_t vertexCount = mesh->getWorldVerticesLength() / 2;- g_worldVertices.resize(mesh->getWorldVerticesLength());- mesh->computeWorldVertices(*slot, 0, mesh->getWorldVerticesLength(),- g_worldVertices.data(), 0, 2);+ int worldVerticesLength = SUPER(mesh)->worldVerticesLength;+ int vertexCount = worldVerticesLength / 2;+ g_worldVertices.resize(worldVerticesLength);+ spVertexAttachment_computeWorldVertices(SUPER(mesh), slot, 0,+ worldVerticesLength, g_worldVertices.data(), 0, 2);- auto& uvs = mesh->getUVs();- auto& triangles = mesh->getTriangles();- auto& attachColor = mesh->getColor();+ float* uvs = mesh->uvs;+ spColor& attachColor = mesh->color;float r = skelColor.r * slotColor.r * attachColor.r;float g = skelColor.g * slotColor.g * attachColor.g;@@ -514,7 +577,7 @@ static void extractMeshBatches(int instanceId) {auto baseIndex = static_cast<uint16_t>(currentBatch->vertices.size() / 8);- for (size_t j = 0; j < vertexCount; ++j) {+ for (int j = 0; j < vertexCount; ++j) {currentBatch->vertices.push_back(g_worldVertices[j * 2]);currentBatch->vertices.push_back(g_worldVertices[j * 2 + 1]);currentBatch->vertices.push_back(uvs[j * 2]);@@ -525,31 +588,35 @@ static void extractMeshBatches(int instanceId) {currentBatch->vertices.push_back(a);}- for (size_t j = 0; j < triangles.size(); ++j) {+ for (int j = 0; j < mesh->trianglesCount; ++j) {currentBatch->indices.push_back(- static_cast<uint16_t>(baseIndex + triangles[j]));+ static_cast<uint16_t>(baseIndex + mesh->triangles[j]));}}}}+EMSCRIPTEN_KEEPALIVEint spine_getMeshBatchCount(int instanceId) {extractMeshBatches(instanceId);return static_cast<int>(g_meshBatches.size());}+EMSCRIPTEN_KEEPALIVEint spine_getMeshBatchVertexCount(int instanceId, int batchIndex) {(void)instanceId;if (batchIndex < 0 || batchIndex >= static_cast<int>(g_meshBatches.size())) return 0;return static_cast<int>(g_meshBatches[batchIndex].vertices.size() / 8);}+EMSCRIPTEN_KEEPALIVEint spine_getMeshBatchIndexCount(int instanceId, int batchIndex) {(void)instanceId;if (batchIndex < 0 || batchIndex >= static_cast<int>(g_meshBatches.size())) return 0;return static_cast<int>(g_meshBatches[batchIndex].indices.size());}+EMSCRIPTEN_KEEPALIVEvoid spine_getMeshBatchData(int instanceId, int batchIndex,uintptr_t outVerticesPtr, uintptr_t outIndicesPtr,uintptr_t outTextureIdPtr, uintptr_t outBlendModePtr) {@@ -571,36 +638,7 @@ void spine_getMeshBatchData(int instanceId, int batchIndex,*outBlendMode = batch.blendMode;}-// =============================================================================-// Emscripten Bindings-// =============================================================================--EMSCRIPTEN_BINDINGS(spine_module) {- emscripten::function("spine_loadSkeleton", &spine_loadSkeleton);- emscripten::function("spine_unloadSkeleton", &spine_unloadSkeleton);- emscripten::function("spine_getAtlasPageCount", &spine_getAtlasPageCount);- emscripten::function("spine_getAtlasPageTextureName", &spine_getAtlasPageTextureName);- emscripten::function("spine_setAtlasPageTexture", &spine_setAtlasPageTexture);-- emscripten::function("spine_createInstance", &spine_createInstance);- emscripten::function("spine_destroyInstance", &spine_destroyInstance);-- emscripten::function("spine_playAnimation", &spine_playAnimation);- emscripten::function("spine_addAnimation", &spine_addAnimation);- emscripten::function("spine_setSkin", &spine_setSkin);- emscripten::function("spine_update", &spine_update);-- emscripten::function("spine_getAnimations", &spine_getAnimations);- emscripten::function("spine_getSkins", &spine_getSkins);- emscripten::function("spine_getBonePosition", &spine_getBonePosition);- emscripten::function("spine_getBoneRotation", &spine_getBoneRotation);- emscripten::function("spine_getBounds", &spine_getBounds);-- emscripten::function("spine_getMeshBatchCount", &spine_getMeshBatchCount);- emscripten::function("spine_getMeshBatchVertexCount", &spine_getMeshBatchVertexCount);- emscripten::function("spine_getMeshBatchIndexCount", &spine_getMeshBatchIndexCount);- emscripten::function("spine_getMeshBatchData", &spine_getMeshBatchData);-}+} // extern "C"int main() {return 0;