Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: comprehensive architecture improvements across engine, SDK, editor, and infra

esengineb5e0f116e851
diff --git a/.github/bundle-size-baselines.json b/.github/bundle-size-baselines.json
new file mode 100644
index 000000000..844e37dd2
--- /dev/null
+++ b/.github/bundle-size-baselines.json
@@ -0,0 +1,42 @@
+{
+ "wasm/web/esengine.js": {
+ "size": 63544,
+ "sizeKB": 62,
+ "sha256": "8b081a50947a742cd6285baf8f6a7bb04028df45f26e19001a1a98d2f5b82fa1"
+ },
+ "wasm/web/esengine.wasm": {
+ "size": 674052,
+ "sizeKB": 658,
+ "sha256": "8f8032bb10ad9a7cdfb7e8ef4f7ddb99a1ac573984fb3a16450747618606f5b6"
+ },
+ "wasm/web/physics.js": {
+ "size": 16795,
+ "sizeKB": 16,
+ "sha256": "b5f252c4dcbb8de720dd22dde078707b585a3f3e2ee9795e5456d6b2b892ab47"
+ },
+ "wasm/web/physics.wasm": {
+ "size": 162968,
+ "sizeKB": 159,
+ "sha256": "5a4202e8b1dac47ce64f39b313137380f9208eec271b1ca0978da9bac6bfc88b"
+ },
+ "sdk/esm/esengine.js": {
+ "size": 107062,
+ "sizeKB": 105,
+ "sha256": "84c082052b13799bfd608980d51fc177461b3fd49e4b58512092b4be5dea3285"
+ },
+ "sdk/esm/esengine.d.ts": {
+ "size": 87951,
+ "sizeKB": 86,
+ "sha256": "78a8310b68eec362044d0d2d8942c5ee2e4d0328fd06ba9ef346e375d7d518e2"
+ },
+ "sdk/esm/wasm.js": {
+ "size": 34,
+ "sizeKB": 0,
+ "sha256": "4ce8696ae2a3a575db7c6f1edef28600f8a7ccad554ad289ca8aa7a00164d705"
+ },
+ "sdk/esm/wasm.d.ts": {
+ "size": 13688,
+ "sizeKB": 13,
+ "sha256": "75e912de32f7a61f2a27937236c0bcdc5e4ac8421c667f0b985579bd7e848df5"
+ }
+}
diff --git a/.github/workflows/README.md b/.github/workflows/README.md
new file mode 100644
index 000000000..69cf81cd1
--- /dev/null
+++ b/.github/workflows/README.md
@@ -0,0 +1,131 @@
+# CI Workflows
+
+## Emscripten Version
+
+**Current pinned version**: 3.1.51
+
+This version is used across all workflows to ensure consistent WASM builds.
+
+### Updating Emscripten
+
+To update to a new version:
+
+1. Test locally with the new version:
+ ```bash
+ emsdk install <version>
+ emsdk activate <version>
+ source path/to/emsdk/emsdk_env.sh
+ node build-tools/cli.js build -t all
+ ```
+
+2. Update version in the following files:
+ - `.github/workflows/build.yml` (line 52)
+ - `.github/workflows/release-desktop.yml` (line 49)
+ - `CONTRIBUTING.md` (Prerequisites section)
+ - `build-tools/utils/emscripten.js` (error message)
+
+3. Run CI build on a test branch to verify
+
+4. Monitor for any compatibility issues with:
+ - WASM output sizes
+ - WebGL bindings
+ - Dynamic linking (MAIN_MODULE/SIDE_MODULE)
+
+### Version History
+
+- **3.1.51** (2026-02-15): Initial pinned version, stable for WebGL2 + dynamic linking
+
+## Compiler Cache (ccache)
+
+All CI workflows use [ccache](https://ccache.dev/) to speed up C++ compilation.
+
+### Configuration
+
+- **Action**: `hendrikmuhs/[email protected]`
+- **Cache keys**:
+ - Linux build: `${{ runner.os }}-build-linux`
+ - Emscripten build: `${{ runner.os }}-emscripten`
+ - Release builds: `${{ matrix.platform }}-release`
+- **Max cache size**:
+ - CI builds: 500MB
+ - Release builds: 1GB
+
+### Performance Impact
+
+- **First build** (cold cache): No change
+- **Incremental builds** (warm cache): 5-10x faster
+- **Full rebuild** (no code changes): ~90% time saved
+
+### Emscripten-specific Settings
+
+For Emscripten builds, ccache uses special configuration (set in `cmake/CompilerCache.cmake`):
+- `CCACHE_COMPILERCHECK=content` - Use content-based hashing instead of mtime
+- `CCACHE_NOHASHDIR=true` - Ignore build directory paths
+- `CCACHE_MAXSIZE=2G` - Larger cache for WASM outputs
+
+### Troubleshooting
+
+If cache becomes corrupted or stale:
+1. Bump the cache key version in workflow files
+2. Or manually clear via GitHub Actions UI: Settings → Actions → Caches
+
+## Bundle Size Tracking
+
+CI automatically tracks WASM and SDK bundle sizes on every build.
+
+### Current Baselines
+
+Baseline sizes are stored in `.github/bundle-size-baselines.json`:
+
+| File | Size | Threshold |
+|------|------|-----------|
+| wasm/web/esengine.wasm | 658KB | 800KB |
+| wasm/web/physics.wasm | 159KB | 200KB |
+| wasm/web/spine42.wasm | - | 300KB |
+| wasm/web/spine38.wasm | - | 300KB |
+| wasm/web/spine41.wasm | - | 300KB |
+| sdk/esm/esengine.js | 105KB | 150KB |
+
+### How It Works
+
+1. **Build with manifest**: `node build-tools/cli.js build -t all --manifest`
+2. **Track sizes**: `node build-tools/track-bundle-size.js check`
+3. **On PR**: Posts a comment with size changes
+4. **On threshold exceeded**: CI fails with error
+
+### Updating Baselines
+
+After intentional size changes (new features, optimizations):
+
+```bash
+node build-tools/cli.js build -t all --manifest
+node build-tools/track-bundle-size.js update
+git add .github/bundle-size-baselines.json
+git commit -m "chore: update bundle size baselines"
+```
+
+### PR Comment Format
+
+On pull requests, CI posts a comment showing size changes:
+
+```
+## 📦 Bundle Size Report
+
+| File | Size | Baseline | Change | Threshold | Status |
+|------|------|----------|--------|-----------|--------|
+| wasm/web/esengine.wasm | 658KB | 658KB | - | 800KB | ✓ OK |
+| wasm/web/physics.wasm | 162KB | 159KB | +3KB (+1.89%) | 200KB | ✓ OK |
+| sdk/esm/esengine.js | 105KB | 105KB | - | 150KB | ✓ OK |
+```
+
+### Adjusting Thresholds
+
+Edit thresholds in `build-tools/track-bundle-size.js`:
+
+```javascript
+const THRESHOLDS = {
+ 'wasm/web/esengine.wasm': 800 * 1024, // 800KB
+ 'wasm/web/physics.wasm': 200 * 1024, // 200KB
+ // ...
+};
+```
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index fee536f20..8f5382b7f 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -25,10 +25,17 @@ jobs:
libglfw3-dev \
libgl1-mesa-dev \
xorg-dev \
- libxkbcommon-dev
+ libxkbcommon-dev \
+ ccache
+
+ - name: Setup ccache
+ uses: hendrikmuhs/[email protected]
+ with:
+ key: ${{ runner.os }}-build-linux
+ max-size: 500M
- name: Configure CMake
- run: cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+ run: cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DES_ENABLE_CCACHE=ON
- name: Build
run: cmake --build build
@@ -46,14 +53,58 @@ jobs:
with:
submodules: recursive
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+
- name: Setup Emscripten
uses: mymindstorm/setup-emsdk@v14
with:
- version: latest
+ version: 3.1.51
+
+ - name: Setup ccache
+ uses: hendrikmuhs/[email protected]
+ with:
+ key: ${{ runner.os }}-emscripten
+ max-size: 500M
- name: Configure CMake
- run: emcmake cmake -B build_web -G Ninja -DES_BUILD_WEB=ON
+ run: emcmake cmake -B build_web -G Ninja -DES_BUILD_WEB=ON -DES_ENABLE_CCACHE=ON
- name: Build
run: cmake --build build_web
+ - name: Install build-tools dependencies
+ run: npm install
+ working-directory: build-tools
+
+ - name: Build SDK and generate manifest
+ run: node build-tools/cli.js build -t all --manifest --no-sync
+
+ - name: Track bundle sizes
+ run: node build-tools/track-bundle-size.js check
+
+ - name: Upload bundle size report
+ if: github.event_name == 'pull_request'
+ uses: actions/upload-artifact@v4
+ with:
+ name: bundle-size-report
+ path: build/manifest.json
+
+ - name: Comment PR with bundle size
+ if: github.event_name == 'pull_request'
+ uses: actions/github-script@v7
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ script: |
+ const { execSync } = require('child_process');
+ const comment = execSync('node build-tools/track-bundle-size.js pr-comment', { encoding: 'utf-8' });
+
+ github.rest.issues.createComment({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ body: comment
+ });
+
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index ad4a766af..8be5ce003 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -46,7 +46,13 @@ jobs:
- name: Setup Emscripten
uses: mymindstorm/setup-emsdk@v14
with:
- version: latest
+ version: 3.1.51
+
+ - name: Setup ccache
+ uses: hendrikmuhs/[email protected]
+ with:
+ key: ${{ matrix.platform }}-release
+ max-size: 1G
- name: Install dependencies
run: pnpm install
@@ -56,7 +62,10 @@ jobs:
run: cp node_modules/.pnpm/[email protected]/node_modules/esbuild-wasm/esbuild.wasm desktop/public/esbuild.wasm
- name: Build engine and sync to desktop
- run: node build-tools/cli.js build -t all
+ run: node build-tools/cli.js build -t all --manifest
+
+ - name: Track bundle sizes
+ run: node build-tools/track-bundle-size.js check
- name: Build workspace packages
run: pnpm --filter esengine build && pnpm --filter @esengine/editor build
diff --git a/.gitignore b/.gitignore
index 624d15e44..2d812defe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,6 +37,10 @@ cmake_install.cmake
Makefile
compile_commands.json
+# Compiler cache
+.ccache/
+.sccache/
+
# Compiled files
*.o
*.obj
diff --git a/CMakeLists.txt b/CMakeLists.txt
index da16efa0d..976c5ffee 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -16,6 +16,7 @@ option(ES_BUILD_SIDE_MODULE "Build side modules for dynamic linking" OFF)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(ESEngineConfig)
+include(CompilerCache)
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
include(Emscripten)
@@ -226,7 +227,15 @@ esengine_set_strict_warnings(esengine)
# =============================================================================
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
- add_executable(esengine_sdk src/esengine/bindings/WebSDKEntry.cpp ${GENERATED_WEB_BINDINGS})
+ add_executable(esengine_sdk
+ src/esengine/bindings/WebSDKEntry.cpp
+ src/esengine/bindings/EngineContext.cpp
+ src/esengine/bindings/ResourceManagerBindings.cpp
+ src/esengine/bindings/RendererBindings.cpp
+ src/esengine/bindings/ImmediateDrawBindings.cpp
+ src/esengine/bindings/GeometryBindings.cpp
+ src/esengine/bindings/PostProcessBindings.cpp
+ ${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_sdk PRIVATE esengine)
es_apply_sdk_settings(esengine_sdk)
@@ -237,7 +246,15 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
# Single-file SDK (WASM inlined as Base64, for playable ads)
if(ES_BUILD_SINGLE_FILE)
- add_executable(esengine_single src/esengine/bindings/WebSDKEntry.cpp ${GENERATED_WEB_BINDINGS})
+ add_executable(esengine_single
+ src/esengine/bindings/WebSDKEntry.cpp
+ src/esengine/bindings/EngineContext.cpp
+ src/esengine/bindings/ResourceManagerBindings.cpp
+ src/esengine/bindings/RendererBindings.cpp
+ src/esengine/bindings/ImmediateDrawBindings.cpp
+ src/esengine/bindings/GeometryBindings.cpp
+ src/esengine/bindings/PostProcessBindings.cpp
+ ${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_single PRIVATE esengine)
es_apply_single_file_settings(esengine_single)
@@ -325,7 +342,15 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
# WeChat MiniGame SDK (CommonJS compatible)
if(ES_BUILD_WXGAME)
- add_executable(esengine_wxgame src/esengine/bindings/WebSDKEntry.cpp ${GENERATED_WEB_BINDINGS})
+ add_executable(esengine_wxgame
+ src/esengine/bindings/WebSDKEntry.cpp
+ src/esengine/bindings/EngineContext.cpp
+ src/esengine/bindings/ResourceManagerBindings.cpp
+ src/esengine/bindings/RendererBindings.cpp
+ src/esengine/bindings/ImmediateDrawBindings.cpp
+ src/esengine/bindings/GeometryBindings.cpp
+ src/esengine/bindings/PostProcessBindings.cpp
+ ${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_wxgame PRIVATE esengine)
es_apply_wxgame_sdk_settings(esengine_wxgame)
@@ -414,7 +439,15 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
# 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 ${GENERATED_WEB_BINDINGS})
+ add_executable(esengine_sdk_main
+ src/esengine/bindings/WebSDKEntry.cpp
+ src/esengine/bindings/EngineContext.cpp
+ src/esengine/bindings/ResourceManagerBindings.cpp
+ src/esengine/bindings/RendererBindings.cpp
+ src/esengine/bindings/ImmediateDrawBindings.cpp
+ src/esengine/bindings/GeometryBindings.cpp
+ src/esengine/bindings/PostProcessBindings.cpp
+ ${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_sdk_main PRIVATE esengine)
es_apply_main_module_settings(esengine_sdk_main)
set_target_properties(esengine_sdk_main PROPERTIES
@@ -423,7 +456,15 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
)
if(ES_BUILD_WXGAME)
- add_executable(esengine_wxgame_main src/esengine/bindings/WebSDKEntry.cpp ${GENERATED_WEB_BINDINGS})
+ add_executable(esengine_wxgame_main
+ src/esengine/bindings/WebSDKEntry.cpp
+ src/esengine/bindings/EngineContext.cpp
+ src/esengine/bindings/ResourceManagerBindings.cpp
+ src/esengine/bindings/RendererBindings.cpp
+ src/esengine/bindings/ImmediateDrawBindings.cpp
+ src/esengine/bindings/GeometryBindings.cpp
+ src/esengine/bindings/PostProcessBindings.cpp
+ ${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_wxgame_main PRIVATE esengine)
es_apply_wxgame_main_module_settings(esengine_wxgame_main)
set_target_properties(esengine_wxgame_main PROPERTIES
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d3d685fc4..1233ee020 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -8,8 +8,9 @@ Thank you for your interest in contributing to ESEngine! This guide will help yo
- **Node.js** >= 18
- **pnpm** >= 8
-- **Emscripten** >= 3.1 (for C++/WASM builds)
+- **Emscripten** 3.1.51 (for C++/WASM builds, exact version required for CI compatibility)
- **Rust** >= 1.75 (for Tauri editor)
+- **ccache** (optional, recommended for faster C++ rebuilds)
### Setup
@@ -18,6 +19,30 @@ git clone https://github.com/esengine/microes.git
cd microes
```
+### Optional: Install ccache for Faster Builds
+
+For significantly faster incremental C++ builds (10x speedup), install ccache:
+
+**macOS**:
+```bash
+brew install ccache
+```
+
+**Ubuntu/Debian**:
+```bash
+sudo apt-get install ccache
+```
+
+**Windows** (via Chocolatey):
+```bash
+choco install ccache
+```
+
+CMake will automatically detect and use ccache if available. To disable:
+```bash
+cmake -B build -DES_ENABLE_CCACHE=OFF
+```
+
### Build Commands
```bash
@@ -88,9 +113,23 @@ We follow a strict commit message format:
1. Fork the repository and create your branch from `master`
2. Make your changes, following the code style guidelines
3. Test your changes locally (build, run editor, preview)
-4. Push your branch and open a Pull Request
-5. Fill in the PR template with a clear description
-6. Wait for review — maintainers may request changes
+4. Check bundle sizes if you modified C++ or SDK code:
+ ```bash
+ node build-tools/cli.js build -t all --manifest
+ node build-tools/track-bundle-size.js check
+ ```
+5. Push your branch and open a Pull Request
+6. Fill in the PR template with a clear description
+7. CI will automatically post a bundle size report on your PR
+8. Wait for review — maintainers may request changes
+
+### Bundle Size Guidelines
+
+CI tracks WASM and SDK bundle sizes. If your PR exceeds thresholds:
+
+- **Explain why**: Add justification in PR description (new feature, dependencies, etc.)
+- **Optimize if possible**: Consider lazy loading, code splitting, or removing unused code
+- **Update baselines**: Maintainers will update baselines if the size increase is acceptable
## Reporting Issues
diff --git a/build-tools/cli.js b/build-tools/cli.js
index b81ffae6e..955273858 100644
--- a/build-tools/cli.js
+++ b/build-tools/cli.js
@@ -3,6 +3,7 @@
import { program } from 'commander';
import { rm, mkdir } from 'fs/promises';
import { existsSync } from 'fs';
+import path from 'path';
import config from './build.config.js';
import * as logger from './utils/logger.js';
import { checkEnvironment } from './utils/emscripten.js';
@@ -11,6 +12,8 @@ import { buildWasm, buildWasmParallel, cleanWasm } from './tasks/wasm.js';
import { buildSdk, cleanSdk } from './tasks/sdk.js';
import { syncToDesktop } from './tasks/sync.js';
import { startWatch } from './tasks/watch.js';
+import { BuildManifest } from './manifest.js';
+import { handleBuildError } from './utils/errorHelp.js';
program
.name('esengine-build')
@@ -27,10 +30,14 @@ program
.option('--no-cache', 'Disable EHT cache')
.option('-v, --verbose', 'Verbose output', false)
.option('--no-sync', 'Skip syncing to desktop/public')
+ .option('--manifest', 'Generate build manifest with timing and sizes', false)
+ .option('--continue-on-error', 'Continue building other targets if one fails (for CI)', false)
.action(async (options) => {
logger.setVerbose(options.verbose);
const startTime = Date.now();
+ const manifest = options.manifest ? new BuildManifest() : null;
+
try {
logger.header('ESEngine Build');
@@ -52,24 +59,31 @@ program
if (wasmTargets.length > 0) {
await runEht({ noCache: !options.cache });
- await buildWasmParallel(wasmTargets, { debug: isDebug, clean: options.clean });
+ await buildWasmParallel(wasmTargets, {
+ debug: isDebug,
+ clean: options.clean,
+ manifest,
+ continueOnError: options.continueOnError,
+ });
}
if (buildSdkFlag) {
- await buildSdk();
+ await buildSdk({ manifest });
}
if (options.sync) {
await syncToDesktop();
}
+ if (manifest) {
+ manifest.printSummary();
+ const manifestPath = path.join(config.paths.output, 'manifest.json');
+ await manifest.save(manifestPath);
+ }
+
logger.printTime(startTime);
} catch (err) {
- logger.error(err.message);
- if (options.verbose) {
- console.error(err);
- }
- process.exit(1);
+ handleBuildError(err, { verbose: options.verbose });
}
});
@@ -88,8 +102,7 @@ program
await startWatch({ target: options.target });
} catch (err) {
- logger.error(err.message);
- process.exit(1);
+ handleBuildError(err, { verbose: options.verbose });
}
});
@@ -98,7 +111,10 @@ program
.description('Clean build outputs')
.option('-a, --all', 'Clean all build directories', false)
.option('-t, --target <target>', 'Clean specific target')
+ .option('-v, --verbose', 'Verbose output', false)
.action(async (options) => {
+ logger.setVerbose(options.verbose);
+
try {
logger.header('Clean');
@@ -110,8 +126,7 @@ program
logger.success('Clean complete');
} catch (err) {
- logger.error(err.message);
- process.exit(1);
+ handleBuildError(err, { verbose: options.verbose });
}
});
@@ -126,8 +141,7 @@ program
try {
await runEht({ noCache: !options.cache });
} catch (err) {
- logger.error(err.message);
- process.exit(1);
+ handleBuildError(err, { verbose: options.verbose });
}
});
@@ -142,20 +156,21 @@ program
await buildSdk();
await syncToDesktop({ wasm: false, sdk: true });
} catch (err) {
- logger.error(err.message);
- process.exit(1);
+ handleBuildError(err, { verbose: options.verbose });
}
});
program
.command('sync')
.description('Sync build outputs to desktop/public')
- .action(async () => {
+ .option('-v, --verbose', 'Verbose output', false)
+ .action(async (options) => {
+ logger.setVerbose(options.verbose);
+
try {
await syncToDesktop();
} catch (err) {
- logger.error(err.message);
- process.exit(1);
+ handleBuildError(err, { verbose: options.verbose });
}
});
diff --git a/build-tools/manifest.js b/build-tools/manifest.js
new file mode 100644
index 000000000..dd3c7dd7a
--- /dev/null
+++ b/build-tools/manifest.js
@@ -0,0 +1,139 @@
+import path from 'path';
+import { stat, readFile, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { createHash } from 'crypto';
+import * as logger from './utils/logger.js';
+
+export class BuildManifest {
+ constructor() {
+ this.targets = {};
+ this.buildStartTime = Date.now();
+ this.buildEndTime = null;
+ }
+
+ startTarget(name) {
+ this.targets[name] = {
+ name,
+ startTime: Date.now(),
+ endTime: null,
+ duration: null,
+ outputs: [],
+ status: 'building',
+ };
+ }
+
+ async endTarget(name, buildResult) {
+ if (!this.targets[name]) {
+ logger.warn(`Target ${name} not found in manifest`);
+ return;
+ }
+
+ const target = this.targets[name];
+ target.endTime = Date.now();
+ target.duration = target.endTime - target.startTime;
+ target.status = 'success';
+
+ if (buildResult && buildResult.outputDir) {
+ await this.collectOutputs(name, buildResult);
+ }
+ }
+
+ async collectOutputs(targetName, buildResult) {
+ const target = this.targets[targetName];
+ const { outputDir } = buildResult;
+
+ if (!existsSync(outputDir)) {
+ return;
+ }
+
+ const outputs = buildResult.outputs || [];
+ for (const outputPath of outputs) {
+ const fullPath = path.join(outputDir, outputPath);
+ if (existsSync(fullPath)) {
+ const stats = await stat(fullPath);
+ const hash = await this.computeFileHash(fullPath);
+
+ target.outputs.push({
+ path: outputPath,
+ size: stats.size,
+ sizeKB: Math.round(stats.size / 1024),
+ sha256: hash,
+ });
+ }
+ }
+ }
+
+ async computeFileHash(filePath) {
+ try {
+ const content = await readFile(filePath);
+ return createHash('sha256').update(content).digest('hex');
+ } catch {
+ return null;
+ }
+ }
+
+ markTargetFailed(name, error) {
+ if (!this.targets[name]) {
+ logger.warn(`Target ${name} not found in manifest`);
+ return;
+ }
+
+ const target = this.targets[name];
+ target.endTime = Date.now();
+ target.duration = target.endTime - target.startTime;
+ target.status = 'failed';
+ target.error = error.message;
+ }
+
+ finalize() {
+ this.buildEndTime = Date.now();
+ }
+
+ async save(outputPath) {
+ this.finalize();
+
+ const manifest = {
+ version: '1.0',
+ timestamp: new Date().toISOString(),
+ build: {
+ startTime: this.buildStartTime,
+ endTime: this.buildEndTime,
+ duration: this.buildEndTime - this.buildStartTime,
+ },
+ targets: Object.values(this.targets),
+ summary: {
+ total: Object.keys(this.targets).length,
+ success: Object.values(this.targets).filter(t => t.status === 'success').length,
+ failed: Object.values(this.targets).filter(t => t.status === 'failed').length,
+ totalOutputs: Object.values(this.targets).reduce((sum, t) => sum + t.outputs.length, 0),
+ totalSize: Object.values(this.targets).reduce(
+ (sum, t) => sum + t.outputs.reduce((s, o) => s + o.size, 0),
+ 0
+ ),
+ },
+ };
+
+ await writeFile(outputPath, JSON.stringify(manifest, null, 2), 'utf-8');
+ logger.success(`Build manifest saved to ${outputPath}`);
+ }
+
+ printSummary() {
+ const targets = Object.values(this.targets);
+ if (targets.length === 0) {
+ return;
+ }
+
+ logger.info('\n📊 Build Summary:');
+ for (const target of targets) {
+ const status = target.status === 'success' ? '✓' : '✗';
+ const duration = (target.duration / 1000).toFixed(2);
+ const totalSize = target.outputs.reduce((sum, o) => sum + o.sizeKB, 0);
+
+ logger.info(` ${status} ${target.name}: ${duration}s (${target.outputs.length} files, ${totalSize}KB)`);
+ }
+
+ const endTime = this.buildEndTime || Date.now();
+ const totalDuration = (endTime - this.buildStartTime) / 1000;
+ logger.info(`\n⏱️ Total: ${totalDuration.toFixed(2)}s`);
+ }
+}
diff --git a/build-tools/tasks/sdk.js b/build-tools/tasks/sdk.js
index c93ffd6fc..a5a00afbe 100644
--- a/build-tools/tasks/sdk.js
+++ b/build-tools/tasks/sdk.js
@@ -6,19 +6,53 @@ import * as logger from '../utils/logger.js';
import { runCommand } from '../utils/emscripten.js';
export async function buildSdk(options = {}) {
- logger.step('Building SDK...');
+ const { manifest = null } = options;
- const sdkDir = config.paths.sdk;
- const outputDir = path.join(config.paths.output, 'sdk');
+ if (manifest) {
+ manifest.startTarget('sdk');
+ }
- await mkdir(outputDir, { recursive: true });
+ try {
+ logger.step('Building SDK...');
- await runCommand('npm', ['run', 'build'], { cwd: sdkDir });
+ const sdkDir = config.paths.sdk;
+ const outputDir = path.join(config.paths.output, 'sdk');
- await copyDistOutputs(sdkDir, outputDir);
+ await mkdir(outputDir, { recursive: true });
+
+ await runCommand('npm', ['run', 'build'], { cwd: sdkDir });
+
+ await copyDistOutputs(sdkDir, outputDir);
- logger.success('SDK: Build complete');
- return { outputDir };
+ logger.success('SDK: Build complete');
+
+ const result = {
+ outputDir,
+ outputs: [
+ 'esm/esengine.js',
+ 'esm/esengine.d.ts',
+ 'esm/wasm.js',
+ 'esm/wasm.d.ts',
+ 'esm/spine/index.js',
+ 'esm/spine/index.d.ts',
+ 'esm/physics/index.js',
+ 'esm/physics/index.d.ts',
+ 'cjs/esengine.wechat.js',
+ 'cjs/index.wechat.js',
+ ],
+ };
+
+ if (manifest) {
+ await manifest.endTarget('sdk', result);
+ }
+
+ return result;
+ } catch (error) {
+ if (manifest) {
+ manifest.markTargetFailed('sdk', error);
+ }
+ throw error;
+ }
}
async function copyDistOutputs(sdkDir, outputDir) {
diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.js
index 9ed0d55fc..d94ec80f7 100644
--- a/build-tools/tasks/wasm.js
+++ b/build-tools/tasks/wasm.js
@@ -6,52 +6,75 @@ import * as logger from '../utils/logger.js';
import { runCommand, getCpuCount } from '../utils/emscripten.js';
export async function buildWasm(target, options = {}) {
- const { debug = false, clean = false } = options;
+ const { debug = false, clean = false, manifest = null } = options;
const targetConfig = config.wasm[target];
if (!targetConfig) {
throw new Error(`Unknown target: ${target}. Available: ${Object.keys(config.wasm).join(', ')}`);
}
- logger.step(`Building WASM for ${target}...`);
+ if (manifest) {
+ manifest.startTarget(`wasm:${target}`);
+ }
- const rootDir = config.paths.root;
- const buildDir = path.join(rootDir, targetConfig.buildDir);
- const outputDir = config.paths.output;
+ try {
+ logger.step(`Building WASM for ${target}...`);
- if (clean && existsSync(buildDir)) {
- logger.debug(`Cleaning ${buildDir}`);
- await rm(buildDir, { recursive: true, force: true });
- }
+ const rootDir = config.paths.root;
+ const buildDir = path.join(rootDir, targetConfig.buildDir);
+ const outputDir = config.paths.output;
- await mkdir(buildDir, { recursive: true });
+ if (clean && existsSync(buildDir)) {
+ logger.debug(`Cleaning ${buildDir}`);
+ await rm(buildDir, { recursive: true, force: true });
+ }
- const buildType = debug ? 'Debug' : 'Release';
- const cmakeArgs = [
- 'cmake',
- ...targetConfig.cmakeFlags,
- `-DCMAKE_BUILD_TYPE=${buildType}`,
- rootDir,
- ];
+ await mkdir(buildDir, { recursive: true });
- logger.debug(`CMake configure: emcmake ${cmakeArgs.join(' ')}`);
- await runCommand('emcmake', cmakeArgs, { cwd: buildDir });
+ const buildType = debug ? 'Debug' : 'Release';
+ const cmakeArgs = [
+ 'cmake',
+ ...targetConfig.cmakeFlags,
+ `-DCMAKE_BUILD_TYPE=${buildType}`,
+ rootDir,
+ ];
- const cpuCount = getCpuCount();
- const buildArgs = ['--build', '.', '-j', String(cpuCount)];
+ logger.debug(`CMake configure: emcmake ${cmakeArgs.join(' ')}`);
+ await runCommand('emcmake', cmakeArgs, { cwd: buildDir });
- if (targetConfig.targets && targetConfig.targets.length > 0) {
- buildArgs.push('--target', ...targetConfig.targets);
- }
+ const cpuCount = getCpuCount();
+ const buildArgs = ['--build', '.', '-j', String(cpuCount)];
- logger.debug(`CMake build: cmake ${buildArgs.join(' ')}`);
- await runCommand('cmake', buildArgs, { cwd: buildDir });
+ if (targetConfig.targets && targetConfig.targets.length > 0) {
+ buildArgs.push('--target', ...targetConfig.targets);
+ }
+
+ logger.debug(`CMake build: cmake ${buildArgs.join(' ')}`);
+ await runCommand('cmake', buildArgs, { cwd: buildDir });
+
+ await optimizeWasmFiles(buildDir, targetConfig.outputs);
+ await copyOutputs(buildDir, outputDir, targetConfig.outputs);
- await optimizeWasmFiles(buildDir, targetConfig.outputs);
- await copyOutputs(buildDir, outputDir, targetConfig.outputs);
+ logger.success(`WASM ${target}: Build complete`);
+
+ const result = {
+ target,
+ buildDir,
+ outputDir,
+ outputs: Object.values(targetConfig.outputs),
+ };
+
+ if (manifest) {
+ await manifest.endTarget(`wasm:${target}`, result);
+ }
- logger.success(`WASM ${target}: Build complete`);
- return { target, buildDir, outputDir };
+ return result;
+ } catch (error) {
+ if (manifest) {
+ manifest.markTargetFailed(`wasm:${target}`, error);
+ }
+ throw error;
+ }
}
async function optimizeWasmFiles(buildDir, outputs) {
@@ -92,6 +115,8 @@ async function copyOutputs(buildDir, outputDir, outputs) {
}
export async function buildWasmParallel(targets, options = {}) {
+ const { manifest = null, continueOnError = false } = options;
+
const groups = new Map();
for (const target of targets) {
const targetConfig = config.wasm[target];
@@ -108,13 +133,62 @@ export async function buildWasmParallel(targets, options = {}) {
const groupPromises = [];
for (const groupTargets of groups.values()) {
groupPromises.push((async () => {
+ const results = [];
for (const target of groupTargets) {
- await buildWasm(target, options);
+ try {
+ const result = await buildWasm(target, { ...options, manifest });
+ results.push({ target, status: 'success', result });
+ } catch (error) {
+ results.push({ target, status: 'failed', error });
+ logger.error(`Build failed for ${target}: ${error.message}`);
+ }
}
+ return results;
})());
}
- await Promise.all(groupPromises);
+ const allResults = await Promise.allSettled(groupPromises);
+
+ const failures = [];
+ const successes = [];
+
+ for (const groupResult of allResults) {
+ if (groupResult.status === 'fulfilled') {
+ for (const targetResult of groupResult.value) {
+ if (targetResult.status === 'success') {
+ successes.push(targetResult.target);
+ } else {
+ failures.push({
+ target: targetResult.target,
+ error: targetResult.error,
+ });
+ }
+ }
+ } else {
+ logger.error(`Group build failed: ${groupResult.reason.message}`);
+ failures.push({
+ target: 'unknown',
+ error: groupResult.reason,
+ });
+ }
+ }
+
+ if (successes.length > 0) {
+ logger.success(`Successfully built: ${successes.join(', ')}`);
+ }
+
+ if (failures.length > 0) {
+ logger.error(`\nBuild failures (${failures.length}):`);
+ for (const failure of failures) {
+ logger.error(` - ${failure.target}: ${failure.error.message}`);
+ }
+
+ if (!continueOnError) {
+ throw new Error(`${failures.length} target(s) failed to build`);
+ } else {
+ logger.warn(`\n⚠️ ${failures.length} target(s) failed, continuing due to --continue-on-error`);
+ }
+ }
}
export async function buildAllWasm(options = {}) {
diff --git a/build-tools/track-bundle-size.js b/build-tools/track-bundle-size.js
new file mode 100644
index 000000000..bca0edfce
--- /dev/null
+++ b/build-tools/track-bundle-size.js
@@ -0,0 +1,187 @@
+#!/usr/bin/env node
+
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import path from 'path';
+import config from './build.config.js';
+import * as logger from './utils/logger.js';
+
+const BASELINES_FILE = path.join(config.paths.root, '.github', 'bundle-size-baselines.json');
+const THRESHOLDS = {
+ 'wasm/web/esengine.wasm': 800 * 1024,
+ 'wasm/web/physics.wasm': 200 * 1024,
+ 'wasm/web/spine42.wasm': 300 * 1024,
+ 'wasm/web/spine38.wasm': 300 * 1024,
+ 'wasm/web/spine41.wasm': 300 * 1024,
+ 'sdk/esm/esengine.js': 150 * 1024,
+};
+
+async function loadManifest() {
+ const manifestPath = path.join(config.paths.output, 'manifest.json');
+ if (!existsSync(manifestPath)) {
+ logger.error('Manifest file not found. Run build with --manifest flag first.');
+ process.exit(1);
+ }
+
+ const content = await readFile(manifestPath, 'utf-8');
+ return JSON.parse(content);
+}
+
+async function loadBaselines() {
+ if (!existsSync(BASELINES_FILE)) {
+ return {};
+ }
+
+ const content = await readFile(BASELINES_FILE, 'utf-8');
+ return JSON.parse(content);
+}
+
+async function saveBaselines(baselines) {
+ await mkdir(path.dirname(BASELINES_FILE), { recursive: true });
+ await writeFile(BASELINES_FILE, JSON.stringify(baselines, null, 2), 'utf-8');
+}
+
+function extractSizes(manifest) {
+ const sizes = {};
+
+ for (const target of manifest.targets) {
+ for (const output of target.outputs) {
+ sizes[output.path] = {
+ size: output.size,
+ sizeKB: output.sizeKB,
+ sha256: output.sha256,
+ };
+ }
+ }
+
+ return sizes;
+}
+
+function compareSizes(current, baselines) {
+ const results = [];
+ let hasExceeded = false;
+
+ for (const [filePath, data] of Object.entries(current)) {
+ const baseline = baselines[filePath];
+ const threshold = THRESHOLDS[filePath];
+
+ const result = {
+ path: filePath,
+ current: data.size,
+ currentKB: data.sizeKB,
+ baseline: baseline?.size || null,
+ baselineKB: baseline?.sizeKB || null,
+ delta: baseline ? data.size - baseline.size : null,
+ deltaKB: baseline ? data.sizeKB - baseline.sizeKB : null,
+ deltaPercent: baseline ? ((data.size - baseline.size) / baseline.size * 100).toFixed(2) : null,
+ threshold,
+ thresholdKB: threshold ? Math.round(threshold / 1024) : null,
+ exceeded: threshold ? data.size > threshold : false,
+ };
+
+ if (result.exceeded) {
+ hasExceeded = true;
+ }
+
+ results.push(result);
+ }
+
+ return { results, hasExceeded };
+}
+
+function formatSizeChange(deltaKB) {
+ if (deltaKB === null || deltaKB === 0) {
+ return '';
+ }
+ const sign = deltaKB > 0 ? '+' : '';
+ return ` (${sign}${deltaKB}KB)`;
+}
+
+function printReport(comparison, isCI = false) {
+ const { results, hasExceeded } = comparison;
+
+ logger.info('\n📦 Bundle Size Report:');
+
+ for (const result of results) {
+ const status = result.exceeded ? '❌' : '✓';
+ const change = formatSizeChange(result.deltaKB);
+ const percent = result.deltaPercent ? ` ${result.deltaPercent > 0 ? '+' : ''}${result.deltaPercent}%` : '';
+
+ if (result.threshold) {
+ logger.info(` ${status} ${result.path}: ${result.currentKB}KB / ${result.thresholdKB}KB${change}${percent}`);
+ } else {
+ logger.info(` ${status} ${result.path}: ${result.currentKB}KB${change}${percent}`);
+ }
+ }
+
+ if (hasExceeded && isCI) {
+ logger.error('\n⚠️ Bundle size thresholds exceeded!');
+ return false;
+ }
+
+ logger.success('\n✓ Bundle sizes OK');
+ return true;
+}
+
+function generatePRComment(comparison) {
+ const { results } = comparison;
+
+ let comment = '## 📦 Bundle Size Report\n\n';
+ comment += '| File | Size | Baseline | Change | Threshold | Status |\n';
+ comment += '|------|------|----------|--------|-----------|--------|\n';
+
+ for (const result of results) {
+ const size = `${result.currentKB}KB`;
+ const baseline = result.baselineKB !== null ? `${result.baselineKB}KB` : 'N/A';
+ const change = result.deltaKB !== null
+ ? `${result.deltaKB > 0 ? '+' : ''}${result.deltaKB}KB (${result.deltaPercent}%)`
+ : '-';
+ const threshold = result.thresholdKB !== null ? `${result.thresholdKB}KB` : 'N/A';
+ const status = result.exceeded ? '❌ Exceeded' : '✓ OK';
+
+ comment += `| ${result.path} | ${size} | ${baseline} | ${change} | ${threshold} | ${status} |\n`;
+ }
+
+ return comment;
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ const mode = args[0] || 'check';
+
+ const manifest = await loadManifest();
+ const currentSizes = extractSizes(manifest);
+ const baselines = await loadBaselines();
+
+ if (mode === 'update') {
+ await saveBaselines(currentSizes);
+ logger.success('Bundle size baselines updated');
+ return;
+ }
+
+ if (mode === 'check') {
+ const comparison = compareSizes(currentSizes, baselines);
+ const isCI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
+ const success = printReport(comparison, isCI);
+
+ if (!success && isCI) {
+ process.exit(1);
+ }
+ return;
+ }
+
+ if (mode === 'pr-comment') {
+ const comparison = compareSizes(currentSizes, baselines);
+ const comment = generatePRComment(comparison);
+ console.log(comment);
+ return;
+ }
+
+ logger.error(`Unknown mode: ${mode}. Use 'check', 'update', or 'pr-comment'.`);
+ process.exit(1);
+}
+
+main().catch(err => {
+ logger.error(err.message);
+ process.exit(1);
+});
diff --git a/build-tools/utils/emscripten.js b/build-tools/utils/emscripten.js
index a3c9919d4..8dab4faa7 100644
--- a/build-tools/utils/emscripten.js
+++ b/build-tools/utils/emscripten.js
@@ -4,7 +4,11 @@ import * as logger from './logger.js';
export async function checkEmscripten() {
try {
- await runCommand('emcc', ['--version'], { silent: true });
+ const result = await runCommand('emcc', ['--version'], { silent: true });
+ const versionMatch = result.stdout.match(/(\d+\.\d+\.\d+)/);
+ if (versionMatch) {
+ logger.debug(`Emscripten version: ${versionMatch[1]}`);
+ }
return true;
} catch {
return false;
@@ -28,7 +32,9 @@ export async function checkEnvironment() {
if (!checks.emscripten) {
logger.error('Emscripten not found. Please install and activate emsdk:');
- logger.info(' source /path/to/emsdk/emsdk_env.sh');
+ logger.info(' Required version: 3.1.51');
+ logger.info(' Install: emsdk install 3.1.51 && emsdk activate 3.1.51');
+ logger.info(' Activate: source /path/to/emsdk/emsdk_env.sh');
return false;
}
diff --git a/build-tools/utils/errorHelp.js b/build-tools/utils/errorHelp.js
new file mode 100644
index 000000000..67b2e1a58
--- /dev/null
+++ b/build-tools/utils/errorHelp.js
@@ -0,0 +1,95 @@
+import * as logger from './logger.js';
+
+export class BuildError extends Error {
+ constructor(message, context = {}) {
+ super(message);
+ this.name = 'BuildError';
+ this.context = context;
+ }
+}
+
+export function suggestFix(error) {
+ const message = error.message.toLowerCase();
+
+ if (message.includes('emscripten') || message.includes('emcc') || message.includes('emcmake')) {
+ return [
+ 'Emscripten not found or incorrect version.',
+ 'Run: emsdk install 3.1.51 && emsdk activate 3.1.51',
+ 'Then reload your shell: source path/to/emsdk/emsdk_env.sh',
+ ];
+ }
+
+ if (message.includes('cmake')) {
+ return [
+ 'CMake configuration or build failed.',
+ 'Try cleaning the build directory: node build-tools/cli.js clean',
+ 'Check CMakeLists.txt for syntax errors.',
+ ];
+ }
+
+ if (message.includes('permission denied') || message.includes('eacces')) {
+ return [
+ 'Permission denied.',
+ 'Try: sudo chmod -R u+w build*',
+ 'Or run with appropriate permissions.',
+ ];
+ }
+
+ if (message.includes('no space left') || message.includes('enospc')) {
+ return [
+ 'Disk space full.',
+ 'Free up disk space and try again.',
+ 'Clean old build artifacts: node build-tools/cli.js clean -a',
+ ];
+ }
+
+ if (message.includes('wasm-opt')) {
+ return [
+ 'wasm-opt optimization failed (non-critical).',
+ 'Install Binaryen for WASM optimization: brew install binaryen',
+ 'Or the build will continue without optimization.',
+ ];
+ }
+
+ if (message.includes('node') && message.includes('not found')) {
+ return [
+ 'Node.js not found.',
+ 'Install Node.js 18+ from https://nodejs.org/',
+ ];
+ }
+
+ return null;
+}
+
+export function printErrorHelp(error) {
+ const suggestions = suggestFix(error);
+
+ if (suggestions) {
+ logger.info('\n💡 Suggestions:');
+ for (const suggestion of suggestions) {
+ logger.info(` ${suggestion}`);
+ }
+ }
+}
+
+export function handleBuildError(error, options = {}) {
+ const { verbose = false, exit = true } = options;
+
+ logger.error(`\n❌ Build failed: ${error.message}`);
+
+ if (verbose && error.stack) {
+ logger.debug('\nStack trace:');
+ logger.debug(error.stack);
+ }
+
+ printErrorHelp(error);
+
+ logger.info('\n📚 For more help:');
+ logger.info(' - Check CONTRIBUTING.md for prerequisites');
+ logger.info(' - Run with --verbose for detailed output');
+ logger.info(' - Report issues at https://github.com/esengine/esengine/issues');
+
+ if (exit) {
+ process.exit(1);
+ }
+}
diff --git a/cmake/CompilerCache.cmake b/cmake/CompilerCache.cmake
new file mode 100644
index 000000000..5630a698f
--- /dev/null
+++ b/cmake/CompilerCache.cmake
@@ -0,0 +1,41 @@
+# Compiler Cache Support (ccache/sccache)
+# Speeds up incremental C++ builds by caching compilation results
+
+option(ES_ENABLE_CCACHE "Enable compiler cache (ccache/sccache) for faster rebuilds" ON)
+
+if(ES_ENABLE_CCACHE)
+ # Try ccache first (more common, lighter weight)
+ find_program(CCACHE_PROGRAM ccache)
+
+ # Fall back to sccache if ccache not found
+ if(NOT CCACHE_PROGRAM)
+ find_program(SCCACHE_PROGRAM sccache)
+ endif()
+
+ if(CCACHE_PROGRAM)
+ message(STATUS "ccache found: ${CCACHE_PROGRAM}")
+ set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE_PROGRAM})
+ set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_PROGRAM})
+
+ # Emscripten-specific configuration
+ if(EMSCRIPTEN)
+ # Use content-based hash instead of mtime for Emscripten
+ set(ENV{CCACHE_COMPILERCHECK} "content")
+ # Don't hash the current directory path (avoids cache misses on different build dirs)
+ set(ENV{CCACHE_NOHASHDIR} "true")
+ # Emscripten outputs can be large, increase cache size
+ set(ENV{CCACHE_MAXSIZE} "2G")
+ message(STATUS "ccache: Emscripten mode enabled (content-based hashing)")
+ endif()
+
+ elseif(SCCACHE_PROGRAM)
+ message(STATUS "sccache found: ${SCCACHE_PROGRAM}")
+ set(CMAKE_C_COMPILER_LAUNCHER ${SCCACHE_PROGRAM})
+ set(CMAKE_CXX_COMPILER_LAUNCHER ${SCCACHE_PROGRAM})
+
+ else()
+ message(STATUS "Compiler cache not found (install ccache or sccache for faster builds)")
+ endif()
+else()
+ message(STATUS "Compiler cache disabled (ES_ENABLE_CCACHE=OFF)")
+endif()
diff --git a/desktop/package.json b/desktop/package.json
index 179349301..515008366 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -22,6 +22,6 @@
"devDependencies": {
"@tauri-apps/cli": "^2.0.0",
"typescript": "^5.3.0",
- "vite": "^5.0.0"
+ "vite": "^7.0.0"
}
}
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index ffd469eb8..f8c6b3ed9 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of u)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function m(e){return h.get(f(e))}function g(e){return p.has(e.toLowerCase())}function y(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function x(e){const t=m(e);return t?.wechatPackInclude??!1}let _=null;function w(){return _||(_=wx.getFileSystemManager()),_}function b(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(x(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function v(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(b(e,t.errMsg)))}})})}function P(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(b(e,t.errMsg)))}})})}function S(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return v(e)}async readTextFile(e){return P(e)}async fileExists(e){return S(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},M=1920,I=1080,R=512,F=4294967295,B=4294967295;function U(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(U);const t={};for(const s in e)t[s]=U(e[s]);return t}let k=0;function D(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...U(t),...e}:U(t)}}function W(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function $(e,t){const s=W(),n=s.get(e);if(n)return n;const r=D(e,t);return s.set(e,r),O(e,t,!1),r}function z(e){const t=W(),s=t.get(e);if(s)return s;const n=D(e,{});return t.set(e,n),O(e,{},!0),n}function L(e){return W().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function N(e,t){j.set(e,t)}function V(e){return j.get(e)??L(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=X("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=X("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=X("Camera",{projectionType:G.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:I},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};N("Name",ie);const ae=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),le=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de={Static:0,Kinematic:1,Dynamic:2};let he=0;function pe(e,t){const s=++he;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function fe(e){return{_type:"res",_resource:e}}class me{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 ge{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ye=pe({delta:0,elapsed:0,frameCount:0},"Time");function xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class _e{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class we{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=H(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new we(this,null);return this.spawned_.push(e),e}entity(e){return new we(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ve;exports.Schedule=void 0,(ve=exports.Schedule||(exports.Schedule={}))[ve.Startup=0]="Startup",ve[ve.First=1]="First",ve[ve.PreUpdate=2]="PreUpdate",ve[ve.Update=3]="Update",ve[ve.PostUpdate=4]="PostUpdate",ve[ve.Last=5]="Last",ve[ve.FixedPreUpdate=10]="FixedPreUpdate",ve[ve.FixedUpdate=11]="FixedUpdate",ve[ve.FixedPostUpdate=12]="FixedPostUpdate";let Pe=0;function Se(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ce{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new _e(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 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 Ee=pe(new Ae,"Input");class Me{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Ee,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Se([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Me;function Re(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Re(e)}}return t}class Fe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){H(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s)for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Re(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,s){const n=t.create(s);this.getStorage(t).set(e,n),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),n}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const Be=pe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ue;function ke(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Ue=exports.BlendMode||(exports.BlendMode={}))[Ue.Normal=0]="Normal",Ue[Ue.Additive=1]="Additive",Ue[Ue.Multiply=2]="Multiply",Ue[Ue.Screen=3]="Screen",Ue[Ue.PremultipliedAlpha=4]="PremultipliedAlpha";let De=null,We=null,$e=1;const ze=new Map;function Le(e){De=e,We=e.getResourceManager(),Je()}function Oe(){0!==Ve&&De&&(De._free(Ve),Ve=0),ze.clear(),$e=1,Ne=!1,We=null,De=null}function He(){if(!We)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return We}const je={createShader:(e,t)=>He().createShader(e,t),releaseShader(e){e>0&&He().releaseShader(e)},create(e){const t=$e++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return ze.set(t,s),t},get:e=>ze.get(e),setUniform(e,t,s){const n=ze.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=ze.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=ze.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=ze.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=ze.get(e);s&&(s.depthTest=t)},getShader(e){const t=ze.get(e);return t?.shader??0},release(e){ze.delete(e)},isValid:e=>ze.has(e),releaseAll(){ze.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=ze.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=$e++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return ze.set(s,n),s},toAssetData(e,t){const s=ze.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=ze.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ne=!1,Ve=0;const Xe=4096,Ge=new Map;let qe=null;function Ye(e){const t=(0===Ve&&De&&(Ve=De._malloc(Xe)),Ve);if(0===t||!De)return{ptr:0,count:0};let s=0,n=0;const r=De.HEAPU8,o=De.HEAPU32,i=De.HEAPF32;for(const[a,l]of e){if(s+128>Xe)break;let e=Ge.get(a);e||(qe||(qe=new TextEncoder),e=qe.encode(a),Ge.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Je(){if(!De||Ne)return;De.materialDataProvider=(e,t,s,n,r)=>{const o=ze.get(e);if(!o)return De.HEAPU32[t>>2]=0,De.HEAPU32[s>>2]=0,De.HEAPU32[n>>2]=0,void(De.HEAPU32[r>>2]=0);De.HEAPU32[t>>2]=o.shader,De.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Ye(o.uniforms);De.HEAPU32[n>>2]=i,De.HEAPU32[r>>2]=a},Ne=!0}const Ke={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Qe{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Ze{constructor(e,t=""){this.cache_=new Qe,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(je.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())je.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:je.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const et=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function tt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)nt(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function st(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=et.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=et.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)nt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function nt(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=V(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class rt{constructor(e){this.textureCache_=new Qe,this.shaderCache_=new Qe,this.jsonCache_=new Qe,this.textCache_=new Qe,this.binaryCache_=new Qe,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Qe,this.prefabCache_=new Qe,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=i(R,R),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Ze(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),je.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===m(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=m(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return st(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return je.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return je.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ot=pe(null,"Assets");class it{build(e){const t=e.wasmModule;t?e.insertResource(ot,new rt(t)):console.warn("AssetPlugin: No WASM module available")}}const at=new it;async function lt(e,t,s){const{entities:n,rootId:r}=await ct(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await st(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}async function ct(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ct(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};ut(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function ut(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class dt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return lt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ht=pe(null,"Prefabs");class pt{constructor(){this.name="PrefabsPlugin",this.dependencies=[ot]}build(e){const t=e.getResource(ot);e.insertResource(ht,new dt(e.world,t))}}const ft=new pt;let mt=null,gt=0,yt=0,xt=0;const _t=new Float32Array(256);function wt(e){mt=e,gt=mt._malloc(64),yt=mt._malloc(64),xt=mt._malloc(1024)}function bt(){mt&&(gt&&(mt._free(gt),gt=0),yt&&(mt._free(yt),yt=0),xt&&(mt._free(xt),xt=0)),mt=null}function vt(){if(!mt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return mt}const Pt={r:1,g:1,b:1,a:1},St={begin(e){const t=vt();t.HEAPF32.set(e,gt/4),t.draw_begin(gt)},end(){vt().draw_end()},line(e,t,s,n=1){vt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){vt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){vt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){vt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){vt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Pt){vt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Pt){vt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){vt().draw_setLayer(e)},setDepth(e){vt().draw_setDepth(e)},getDrawCallCount:()=>mt?mt.draw_getDrawCallCount():0,getPrimitiveCount:()=>mt?mt.draw_getPrimitiveCount():0,setBlendMode(e){vt().draw_setBlendMode(e)},setDepthTest(e){vt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=vt();n.HEAPF32.set(s,yt/4),n.draw_mesh(e,t,yt)},drawMeshWithMaterial(e,t,s){const n=vt(),r=je.get(t);if(!r)return;if(St.setBlendMode(r.blendMode),St.setDepthTest(r.depthTest),0===r.uniforms.size)return void St.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,yt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Ct(t);if(!(n<0)){if(ke(s))_t[o++]=10,_t[o++]=n,_t[o++]=s.slot??e++,_t[o++]=s.textureId;else if("number"==typeof s)_t[o++]=1,_t[o++]=n,_t[o++]=s;else if(Array.isArray(s)){_t[o++]=s.length,_t[o++]=n;for(let e=0;e<s.length;e++)_t[o++]=s[e]}else"w"in s?(_t[o++]=4,_t[o++]=n,_t[o++]=s.x,_t[o++]=s.y,_t[o++]=s.z,_t[o++]=s.w):"z"in s?(_t[o++]=3,_t[o++]=n,_t[o++]=s.x,_t[o++]=s.y,_t[o++]=s.z):(_t[o++]=2,_t[o++]=n,_t[o++]=s.x,_t[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(_t.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),xt/4),n.draw_meshWithUniforms(e,r.shader,yt,xt,o)):n.draw_mesh(e,r.shader,yt)}},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 Ct(e){return Tt[e]??-1}var At;exports.DataType=void 0,(At=exports.DataType||(exports.DataType={}))[At.Float=1]="Float",At[At.Float2=2]="Float2",At[At.Float3=3]="Float3",At[At.Float4=4]="Float4",At[At.Int=5]="Int",At[At.Int2=6]="Int2",At[At.Int3=7]="Int3",At[At.Int4=8]="Int4";let Et=null,Mt=0,It=0,Rt=0;function Ft(e){Et=e,Mt=Et._malloc(262144),It=Et._malloc(65536),Rt=Et._malloc(256)}function Bt(){Et&&(Mt&&Et._free(Mt),It&&Et._free(It),Rt&&Et._free(Rt),Mt=0,It=0,Rt=0),Et=null}function Ut(){if(!Et)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Et}const kt={create(e){const t=Ut(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Mt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Rt,r).set(o),t.geometry_init(s,Mt,n,Rt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,It,n).set(e.indices),t.geometry_setIndices16(s,It,n)}else{new Uint32Array(t.HEAPU8.buffer,It,n).set(e.indices),t.geometry_setIndices32(s,It,n)}}return s},updateVertices(e,t,s=0){const n=Ut(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Mt/4),n.geometry_updateVertices(e,Mt,r,s)},release(e){e>0&&Ut().geometry_release(e)},isValid:e=>!(!Et||e<=0)&&Et.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return kt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return kt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return kt.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 Wt(e){Dt=e}function $t(){Dt&&Lt.isInitialized()&&Lt.shutdown(),Dt=null}function zt(){if(!Dt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Dt}const Lt={init:(e,t)=>zt().postprocess_init(e,t),shutdown(){zt().postprocess_shutdown()},resize(e,t){zt().postprocess_resize(e,t)},addPass:(e,t)=>zt().postprocess_addPass(e,t),removePass(e){zt().postprocess_removePass(e)},setEnabled(e,t){zt().postprocess_setPassEnabled(e,t)},isEnabled:e=>zt().postprocess_isPassEnabled(e),setUniform(e,t,s){zt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){zt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){zt().postprocess_begin()},end(){zt().postprocess_end()},getPassCount:()=>zt().postprocess_getPassCount(),isInitialized:()=>!!Dt&&Dt.postprocess_isInitialized(),setBypass(e){zt().postprocess_setBypass(e)},isBypassed:()=>!Dt||Dt.postprocess_isBypassed(),createBlur:()=>je.createShader(Ot,"#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:()=>je.createShader(Ot,"#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:()=>je.createShader(Ot,"#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:()=>je.createShader(Ot,"#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")},Ot="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ht;exports.RenderStage=void 0,(Ht=exports.RenderStage||(exports.RenderStage={}))[Ht.Background=0]="Background",Ht[Ht.Opaque=1]="Opaque",Ht[Ht.Transparent=2]="Transparent",Ht[Ht.Overlay=3]="Overlay";let jt=null,Nt=0;function Vt(e){jt=e,Nt=jt._malloc(64)}function Xt(){jt&&Nt&&(jt._free(Nt),Nt=0),jt=null}const Gt={init(e,t){jt?.renderer_init(e,t)},resize(e,t){jt?.renderer_resize(e,t)},begin(e,t){jt&&Nt&&(jt.HEAPF32.set(e,Nt/4),jt.renderer_begin(Nt,t??0))},flush(){jt?.renderer_flush()},end(){jt?.renderer_end()},submitSprites(e){jt&&jt.renderer_submitSprites(e._cpp)},submitBitmapText(e){jt&&jt.renderer_submitBitmapText(e._cpp)},submitSpine(e){jt&&jt.renderer_submitSpine?.(e._cpp)},setStage(e){jt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>jt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){jt?.renderer_releaseTarget(e)},getTargetTexture:e=>jt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>jt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){jt?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){jt?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){jt?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){jt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>jt?jt.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>jt?{drawCalls:jt.renderer_getDrawCalls(),triangles:jt.renderer_getTriangles(),sprites:jt.renderer_getSprites(),text:jt.renderer_getText(),spine:jt.renderer_getSpine?.()??0,meshes:jt.renderer_getMeshes(),culled:jt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let qt=null;function Yt(e){qt=e}function Jt(){qt=null}const Kt={enable(){qt?.gl_enableErrorCheck(!0)},disable(){qt?.gl_enableErrorCheck(!1)},check:e=>qt?.gl_checkErrors(e)??0,diagnose(){qt?.renderer_diagnose()}},Qt=new Map;function Zt(e){Qt.delete(e)}class es{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Gt.resize(n,r),Lt.isInitialized()&&Lt.getPassCount()>0&&Lt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Gt.setViewport(0,0,n,r),Gt.clearBuffers(3),Gt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Gt.submitSprites(t),Gt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Gt.submitSpine(t),Gt.flush(),this.executeDrawCallbacks(s,o),Gt.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Gt.setViewport(n.x,n.y,n.w,n.h),Gt.setScissor(n.x,n.y,n.w,n.h,!0),Gt.clearBuffers(r),Gt.setScissor(0,0,0,0,!1),Gt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Gt.submitSprites(t),Gt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Gt.submitSpine(t),Gt.flush(),this.executeDrawCallbacks(s,o),Gt.end()}executeDrawCallbacks(e,t){const s=Qt;if(s.size>0){St.begin(e);const n=[];for(const[e,r]of s.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}St.end();for(const e of n)Zt(e)}}}class ts{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),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 Fe,this.resources_=new ge;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ts}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}onError(e){return this.error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1;const e=[Jt,Xt,$t,Bt,Oe,bt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}const ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ns(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function rs(e,t,s,n){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*s/(l.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,o){h=ns(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=is(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=ls(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=us(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(hs(u,p)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const os=new Float32Array(16);function is(e,t,s,n,r,o){const i=os;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const as=new Float32Array(16);function ls(e,t,s,n){const r=as;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const cs=new Float32Array(16);function us(e,t,s){const n=cs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const ds=new Float32Array(16);function hs(e,t){const s=ds;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var ps,fs,ms;exports.TextAlign=void 0,(ps=exports.TextAlign||(exports.TextAlign={}))[ps.Left=0]="Left",ps[ps.Center=1]="Center",ps[ps.Right=2]="Right",exports.TextVerticalAlign=void 0,(fs=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[fs.Top=0]="Top",fs[fs.Middle=1]="Middle",fs[fs.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ms=exports.TextOverflow||(exports.TextOverflow={}))[ms.Visible=0]="Visible",ms[ms.Clip=1]="Clip",ms[ms.Ellipsis=2]="Ellipsis";const gs=$("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),ys=$("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class xs{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(R,R),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),x=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${y}, ${x})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let b=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,b),b+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const v=s.getImageData(0,0,p,f),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),T=this.module._malloc(P.length);this.module.HEAPU8.set(P,T);const C=S.createTexture(p,f,T,P.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function _s(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function ws(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class bs{build(e){N("Text",gs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new xs(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Se([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,gs));for(const e of r.keys())n.valid(e)&&n.has(e,gs)||r.delete(e);const e=n.getEntitiesWithComponents([gs]);for(const t of e){const e=n.get(t,gs),o=n.has(t,ys)?n.get(t,ys):null,i=r.get(t);if(i&&!ws(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,_s(e,o))}}))}}const vs=new bs,Ps=$("UIMask",{enabled:!0});function Ss(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Ts(e,t,s,n,r,o,i,a,l,c,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function m(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[g,y]=m(d,p),[x,_]=m(h,f),w=Math.min(g,x),b=Math.max(g,x),v=Math.min(y,_),P=Math.max(y,_);return{x:Math.round(w),y:Math.round(v),w:Math.round(b-w),h:Math.round(P-v)}}function Cs(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],x=e[15],_=n*l-r*a,w=n*c-o*a,b=n*u-i*a,v=r*c-o*l,P=r*u-i*l,S=o*u-i*c,T=d*g-h*m,C=d*y-p*m,A=d*x-f*m,E=h*y-p*g,M=h*x-f*g,I=p*x-f*y;let R=_*I-w*M+b*E+v*A-P*C+S*T;return 0===R||(R=1/R,s[0]=(l*I-c*M+u*E)*R,s[1]=(o*M-r*I-i*E)*R,s[2]=(g*S-y*P+x*v)*R,s[3]=(p*P-h*S-f*v)*R,s[4]=(c*A-a*I-u*C)*R,s[5]=(n*I-o*A+i*C)*R,s[6]=(y*b-m*S-x*w)*R,s[7]=(d*S-p*b+f*w)*R,s[8]=(a*M-l*A+u*T)*R,s[9]=(r*A-n*M-i*T)*R,s[10]=(m*P-g*b+x*_)*R,s[11]=(h*b-d*P-f*_)*R,s[12]=(l*C-a*E-c*T)*R,s[13]=(n*E-r*C+o*T)*R,s[14]=(g*w-m*v-y*_)*R,s[15]=(d*v-h*w+p*_)*R),s}function As(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Es(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function Ms(e,t,s,n,r,o,i){if(!e.has(t,ys)||!e.has(t,K))return null;const a=e.get(t,ys),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Ts(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Is(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ps]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,Ps).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=Ms(t,s,r,o,i,a,l);e&&(n=Ss(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Ms(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Rs{build(e){if(N("UIMask",Ps),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Is(e.wasmModule,e.world))}}const Fs=new Rs,Bs=$("Interactable",{enabled:!0}),Us=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ks;exports.ButtonState=void 0,(ks=exports.ButtonState||(exports.ButtonState={}))[ks.Normal=0]="Normal",ks[ks.Hovered=1]="Hovered",ks[ks.Pressed=2]="Pressed",ks[ks.Disabled=3]="Disabled";const Ds=$("Button",{state:exports.ButtonState.Normal,transition:null});class Ws{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const $s=pe(new Ws,"UIEvents"),zs=z("ScreenSpace");function Ls(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,m=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,m=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function Os(e,t,s,n,r,o){if(!e.has(t,ys))return;const i=e.get(t,ys),a=Ls(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Os(e,t,a.rect,a.centerX,a.centerY,!1)}class Hs{build(e){N("UIRect",ys);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Se([fe(Be)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([zs,ys,J]);for(const e of o)Os(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const js=new Hs,Ns=new Float32Array(16),Vs=new Float32Array(16);let Xs=!0,Gs=1;class qs{build(e){N("Interactable",Bs),N("Button",Ds);const t=e.world,s=new Ws;e.insertResource($s,s);let n=null,r=null;Gs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Se([fe(Ee),fe(Be)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Us]);for(const e of i){const s=t.get(e,Us);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Gs,l=o.screenH-e.mouseY*Gs;!function(e){let t=!1;for(let s=0;s<16;s++)if(Vs[s]!==e[s]){t=!0;break}t&&(Vs.set(e),Xs=!0)}(o.viewProjection),Xs&&(Cs(o.viewProjection,Ns),Xs=!1);const c=As(a,l,Ns,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Bs,ys,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Us)||t.insert(e,Us);if(!t.get(e,Bs).enabled)continue;const s=t.get(e,K),n=t.get(e,ys),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Es(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,Us)){t.get(n,Us).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Us).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Us);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Us)){const e=t.get(r,Us);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Se([],()=>{const e=t.getEntitiesWithComponents([Ds]);for(const s of e){if(t.has(s,Bs)||t.insert(s,Bs,{enabled:!0}),!t.has(s,Us))continue;const e=t.get(s,Us),n=t.get(s,Ds),r=t.get(s,Bs),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const Ys=new qs,Js=$("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Ks{build(e){N("TextInput",Js);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(R,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const p=h;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,Js);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource($s).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,y()}function m(e){if(a===e)return;g();const t=s.get(e,Js);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),y())}function g(){if(null!==a&&s.valid(a)&&s.has(a,Js)){const e=s.get(a,Js);e.focused=!1,e.dirty=!0}a=null,p.blur()}function y(){c=!0,u=0}function x(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Zs(Math.max(r.width,a)),r.height=Zs(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Qs(o,h,a-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Qs(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,s=m+(e.length-1)*f,n=f}else t=m+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const g=o.getImageData(0,0,a,l),y=new Uint8Array(g.data.buffer),x=t.getResourceManager(),_=t._malloc(y.length);t.HEAPU8.set(y,_);const w=n.get(e);void 0!==w&&x.releaseTexture(w);const b=x.createTexture(a,l,_,y.length,1,!0);n.set(e,b),t._free(_);const v=s.get(e,Q);v.texture=b,v.size.x=a,v.size.y=l,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},s.insert(e,Q,v)}p.addEventListener("input",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void g();const n=s.get(a,Js);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource($s).emit(a,"submit"),void g()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,y())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,Js)){const e=s.get(a,Js);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Se([fe($s)],e=>{const t=s.getEntitiesWithComponents([Js,Bs]);for(const e of t){if(!s.has(e,Us))continue;if(s.get(e,Us).justPressed)return void m(e)}if(null!==a){const e=s.getEntitiesWithComponents([Bs]);for(const t of e){if(s.has(t,Js))continue;if(!s.has(t,Us))continue;if(s.get(t,Us).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Se([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,Js)))){s.get(a,Js).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Js)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([Js,ys]);for(const e of i){const t=s.get(e,Js);if(!t.dirty)continue;const n=s.get(e,ys),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Qs(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Zs(e){let t=1;for(;t<e;)t*=2;return t}const en=new Ks;async function tn(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const sn=pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),nn=pe(null,"PhysicsAPI");function rn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function on(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class an{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(sn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=tn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Se([fe(ye)],a=>{const l=i.getEntitiesWithComponents([ae,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,ae),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=rn(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ln(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===de.Kinematic){const e=rn(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=rn(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=on(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(sn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(nn,cn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function ln(e,t,s){const n=e.world;if(n.has(s,le)){const e=n.get(s,le);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ce)){const e=n.get(s,ce);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ue)){const e=n.get(s,ue);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class cn{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(cn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function un(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function dn(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function hn(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,x=l*p,_=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(y+_))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(f+_))*o,(x+w)*o,0,(g+b)*i,(x-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function pn(e,t,s,n,r,o,i,a){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=un(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===m(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=dn(n),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=g+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=un(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new an("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=m(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=un(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),h=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=je.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=je.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),p=tt(e.world,s);if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,Q);r&&(r.texture=s[n.data.texture]||0,e.insert(t,Q,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}else if("SpineAnimation"===n.type){const s=e.get(t,oe);s&&(s.material=r,e.insert(t,oe,s))}}}}(e.world,s,h,p),r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,c,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=hn(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,u,o),x=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,x>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(y),t.renderer_submitTriangles(x,r,_,o,f,m,h),t._free(x),t._free(_),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(ot);t&&t.setAddressableManifest(a)}}class fn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===m(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=m(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const mn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Gt.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Gt.getTargetTexture(s),width:e.width,height:e.height}},release(e){Gt.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Gt.releaseRenderTarget(e._handle),mn.create({width:t,height:s,depth:!0})),begin(e,t){Gt.begin(t,e._handle)},end(){Gt.end()},getDepthTexture:e=>Gt.getTargetDepthTexture(e._handle)};let gn=!1;const yn=[vs,Fs,js,Ys,en];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E,exports.App=ts,exports.AssetPlugin=it,exports.AssetServer=rt,exports.Assets=ot,exports.AsyncCache=Qe,exports.BitmapText=re,exports.BodyType=de,exports.BoxCollider=le,exports.Button=Ds,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=ce,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=be,exports.DEFAULT_DESIGN_HEIGHT=I,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=R,exports.Draw=St,exports.EntityCommands=we,exports.GLDebug=Kt,exports.Geometry=kt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Ee,exports.InputPlugin=Me,exports.InputState=Ae,exports.Interactable=Bs,exports.LocalTransform=J,exports.Material=je,exports.MaterialLoader=Ze,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=cn,exports.PhysicsEvents=sn,exports.PhysicsPlugin=an,exports.PostProcess=Lt,exports.PrefabServer=dt,exports.Prefabs=ht,exports.PrefabsPlugin=pt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await s(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const r=new fn(this.baseUrl_);await r.prefetch(n);let o=null;const i=this.app_.spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await pn(this.app_,this.app_.wasmModule,n,r,o),e="ensureCamera",this.ensureCamera()}catch(t){const s=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${s}\n${n}`),new Error(`[PreviewPlugin:${e}] ${s}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,J,o);const i={isActive:!0,projectionType:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth};e.insert(r,Z,i)}}},exports.ProjectionType=G,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{xe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=_e,exports.RenderPipeline=es,exports.RenderTexture=mn,exports.Renderer=Gt,exports.Res=fe,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=ae,exports.ScaleMode=Y,exports.ScreenSpace=zs,exports.ShaderSources=Ke,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=gs,exports.TextInput=Js,exports.TextInputPlugin=Ks,exports.TextPlugin=bs,exports.TextRenderer=xs,exports.Time=ye,exports.UICameraInfo=Be,exports.UIEventQueue=Ws,exports.UIEvents=$s,exports.UIInteraction=Us,exports.UIInteractionPlugin=qs,exports.UILayoutPlugin=Hs,exports.UIMask=Ps,exports.UIMaskPlugin=Rs,exports.UIRect=ys,exports.Velocity=te,exports.WebAssetProvider=fn,exports.World=Fe,exports.WorldTransform=K,exports.addStartupSystem=function(e){Te().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Te().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Te().push({schedule:e,system:t})},exports.assetPlugin=at,exports.clearDrawCallbacks=function(){Qt.clear()},exports.clearUserComponents=function(){W().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=Ls,exports.createMaskProcessor=Is,exports.createWebApp=function(e,t){return function(e,t){const s=ts.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),wt(e),Le(e),Ft(e),Wt(e),Vt(e),Yt(e);const r=new es;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=rs(e,n,t,r));const i=s.getResource(Be);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Be,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=i();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Gt.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;Gt.resize(t,s),Lt.isInitialized()&&Lt.getPassCount()>0&&!Lt.isBypassed()&&Lt.resize(t,s);const d=rs(e,n,t,s);if(l(t,s,d),0===d.length)r.render({registry:{_cpp:n},viewProjection:ss,width:t,height:s,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}Gt.setViewport(0,0,t,s)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(at),s.addPlugin(ft),s.addPlugin(Ie),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:yn,...t})},exports.defineComponent=$,exports.defineResource=pe,exports.defineSystem=Se,exports.defineTag=z,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return m(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=m,exports.getComponent=V,exports.getComponentDefaults=function(e){const t=V(e);return t?U(t._default):null},exports.getCustomExtensions=y,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=L,exports.getWeChatPackOptions=function(){return y().map(e=>({type:"suffix",value:e}))},exports.initDrawAPI=wt,exports.initGLDebugAPI=Yt,exports.initGeometryAPI=Ft,exports.initMaterialAPI=Le,exports.initPostProcessAPI=Wt,exports.initRendererAPI=Vt,exports.inputPlugin=Ie,exports.instantiatePrefab=lt,exports.intersectRects=Ss,exports.invertMatrix4=Cs,exports.isBuiltinComponent=H,exports.isCustomExtension=x,exports.isEditor=function(){return gn},exports.isKnownAssetExtension=g,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!gn},exports.isTextureRef=ke,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=nt,exports.loadPhysicsModule=tn,exports.loadRuntimeScene=pn,exports.loadSceneData=tt,exports.loadSceneWithAssets=st,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&g(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Es,exports.prefabsPlugin=ft,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){et.set(e,t)},exports.registerDrawCallback=function(e,t){Qt.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ot);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Je,exports.screenToWorld=As,exports.setEditorMode=function(e){gn=e},exports.shutdownDrawAPI=bt,exports.shutdownGLDebugAPI=Jt,exports.shutdownGeometryAPI=Bt,exports.shutdownMaterialAPI=Oe,exports.shutdownPostProcessAPI=$t,exports.shutdownRendererAPI=Xt,exports.textInputPlugin=en,exports.textPlugin=vs,exports.uiInteractionPlugin=Ys,exports.uiLayoutPlugin=js,exports.uiMaskPlugin=Fs,exports.uiPlugins=yn,exports.unregisterDrawCallback=Zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.worldRectToScreen=Ts,exports.wxFileExists=S,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(await T(e))},exports.wxReadFile=v,exports.wxReadTextFile=P,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of u)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function m(e){return p.has(e.toLowerCase())}function y(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function _(e){const t=g(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(_(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},M=1920,R=1080,I=512,F=4294967295,B=4294967295;function U(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(U);const t={};for(const s in e)t[s]=U(e[s]);return t}let k=0;function D(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...U(t),...e}:U(t)}}function L(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function $(e,t){const s=L(),n=s.get(e);if(n)return n;const r=D(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=L(),s=t.get(e);if(s)return s;const n=D(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return L().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=X("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=X("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=X("Camera",{projectionType:G.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};N("Name",ie);const ae=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),le=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de={Static:0,Kinematic:1,Dynamic:2};let he=0;function pe(e,t){const s=++he;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function fe(e){return{_type:"res",_resource:e}}class ge{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 me{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new ge(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ye=pe({delta:0,elapsed:0,frameCount:0},"Time");function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class xe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class we{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=H(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ve{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new we(this,null);return this.spawned_.push(e),e}entity(e){return new we(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var be;exports.Schedule=void 0,(be=exports.Schedule||(exports.Schedule={}))[be.Startup=0]="Startup",be[be.First=1]="First",be[be.PreUpdate=2]="PreUpdate",be[be.Update=3]="Update",be[be.PostUpdate=4]="PostUpdate",be[be.Last=5]="Last",be[be.FixedPreUpdate=10]="FixedPreUpdate",be[be.FixedUpdate=11]="FixedUpdate",be[be.FixedPostUpdate=12]="FixedPostUpdate";let Se=0;function Pe(e,t,s){const n=++Se;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ce{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ve&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ve(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 Ee=pe(new Ae,"Input");class Me{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Ee,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Pe([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Re=new Me;function Ie(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Fe(t[e]),o=Fe(r);s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r})}return n}function Fe(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Be(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}function Ue(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Ue(e)}}return t}class ke{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");H(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ie(t._name,t._default,n);if(e.length>0)throw new Error(Be(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Ue(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Ie(t._name,t._default,e);if(r.length>0)throw new Error(Be(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const De=pe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Le;function $e(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Le=exports.BlendMode||(exports.BlendMode={}))[Le.Normal=0]="Normal",Le[Le.Additive=1]="Additive",Le[Le.Multiply=2]="Multiply",Le[Le.Screen=3]="Screen",Le[Le.PremultipliedAlpha=4]="PremultipliedAlpha";let We=null,ze=null,Oe=1;const He=new Map;function je(e){We=e,ze=e.getResourceManager(),Ze()}function Ne(){0!==qe&&We&&(We._free(qe),qe=0),He.clear(),Oe=1,Ge=!1,ze=null,We=null}function Ve(){if(!ze)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ze}const Xe={createShader:(e,t)=>Ve().createShader(e,t),releaseShader(e){e>0&&Ve().releaseShader(e)},create(e){const t=Oe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return He.set(t,s),t},get:e=>He.get(e),setUniform(e,t,s){const n=He.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=He.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=He.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=He.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=He.get(e);s&&(s.depthTest=t)},getShader(e){const t=He.get(e);return t?.shader??0},release(e){He.delete(e)},isValid:e=>He.has(e),releaseAll(){He.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=He.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Oe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return He.set(s,n),s},toAssetData(e,t){const s=He.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=He.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ge=!1,qe=0;const Ye=4096,Je=new Map;let Ke=null;function Qe(e){const t=(0===qe&&We&&(qe=We._malloc(Ye)),qe);if(0===t||!We)return{ptr:0,count:0};let s=0,n=0;const r=We.HEAPU8,o=We.HEAPU32,i=We.HEAPF32;for(const[a,l]of e){if(s+128>Ye)break;let e=Je.get(a);e||(Ke||(Ke=new TextEncoder),e=Ke.encode(a),Je.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Ze(){if(!We||Ge)return;We.materialDataProvider=(e,t,s,n,r)=>{const o=He.get(e);if(!o)return We.HEAPU32[t>>2]=0,We.HEAPU32[s>>2]=0,We.HEAPU32[n>>2]=0,void(We.HEAPU32[r>>2]=0);We.HEAPU32[t>>2]=o.shader,We.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Qe(o.uniforms);We.HEAPU32[n>>2]=i,We.HEAPU32[r>>2]=a},Ge=!0}const et={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 tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class st{constructor(e,t=""){this.cache_=new tt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Xe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Xe.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Xe.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const nt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function rt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)it(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function ot(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=nt.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=nt.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)it(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function it(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=V(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class at{constructor(e){this.textureCache_=new tt,this.shaderCache_=new tt,this.jsonCache_=new tt,this.textCache_=new tt,this.binaryCache_=new tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new tt,this.prefabCache_=new tt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=i(I,I),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new st(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Xe.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===g(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ot(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Xe.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Xe.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const lt=pe(null,"Assets");class ct{build(e){const t=e.wasmModule;t?e.insertResource(lt,new at(t)):console.warn("AssetPlugin: No WASM module available")}}const ut=new ct;async function dt(e,t,s){const{entities:n,rootId:r}=await ht(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await ot(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}async function ht(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ht(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};pt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function pt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class ft{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return dt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const gt=pe(null,"Prefabs");class mt{constructor(){this.name="PrefabsPlugin",this.dependencies=[lt]}build(e){const t=e.getResource(lt);e.insertResource(gt,new ft(e.world,t))}}const yt=new mt;let _t=null,xt=0,wt=0,vt=0;const bt=new Float32Array(256);function St(e){_t=e,xt=_t._malloc(64),wt=_t._malloc(64),vt=_t._malloc(1024)}function Pt(){_t&&(xt&&(_t._free(xt),xt=0),wt&&(_t._free(wt),wt=0),vt&&(_t._free(vt),vt=0)),_t=null}function Tt(){if(!_t)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return _t}const Ct={r:1,g:1,b:1,a:1},At={begin(e){const t=Tt();t.HEAPF32.set(e,xt/4),t.draw_begin(xt)},end(){Tt().draw_end()},line(e,t,s,n=1){Tt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Tt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Tt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Tt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Tt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Ct){Tt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Ct){Tt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Tt().draw_setLayer(e)},setDepth(e){Tt().draw_setDepth(e)},getDrawCallCount:()=>_t?_t.draw_getDrawCallCount():0,getPrimitiveCount:()=>_t?_t.draw_getPrimitiveCount():0,setBlendMode(e){Tt().draw_setBlendMode(e)},setDepthTest(e){Tt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Tt();n.HEAPF32.set(s,wt/4),n.draw_mesh(e,t,wt)},drawMeshWithMaterial(e,t,s){const n=Tt(),r=Xe.get(t);if(!r)return;if(At.setBlendMode(r.blendMode),At.setDepthTest(r.depthTest),0===r.uniforms.size)return void At.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,wt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Mt(t);if(!(n<0)){if($e(s))bt[o++]=10,bt[o++]=n,bt[o++]=s.slot??e++,bt[o++]=s.textureId;else if("number"==typeof s)bt[o++]=1,bt[o++]=n,bt[o++]=s;else if(Array.isArray(s)){bt[o++]=s.length,bt[o++]=n;for(let e=0;e<s.length;e++)bt[o++]=s[e]}else"w"in s?(bt[o++]=4,bt[o++]=n,bt[o++]=s.x,bt[o++]=s.y,bt[o++]=s.z,bt[o++]=s.w):"z"in s?(bt[o++]=3,bt[o++]=n,bt[o++]=s.x,bt[o++]=s.y,bt[o++]=s.z):(bt[o++]=2,bt[o++]=n,bt[o++]=s.x,bt[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(bt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),vt/4),n.draw_meshWithUniforms(e,r.shader,wt,vt,o)):n.draw_mesh(e,r.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 Rt;exports.DataType=void 0,(Rt=exports.DataType||(exports.DataType={}))[Rt.Float=1]="Float",Rt[Rt.Float2=2]="Float2",Rt[Rt.Float3=3]="Float3",Rt[Rt.Float4=4]="Float4",Rt[Rt.Int=5]="Int",Rt[Rt.Int2=6]="Int2",Rt[Rt.Int3=7]="Int3",Rt[Rt.Int4=8]="Int4";let It=null,Ft=0,Bt=0,Ut=0;function kt(e){It=e,Ft=It._malloc(262144),Bt=It._malloc(65536),Ut=It._malloc(256)}function Dt(){It&&(Ft&&It._free(Ft),Bt&&It._free(Bt),Ut&&It._free(Ut),Ft=0,Bt=0,Ut=0),It=null}function Lt(){if(!It)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return It}const $t={create(e){const t=Lt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ft/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ut,r).set(o),t.geometry_init(s,Ft,n,Ut,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Bt,n).set(e.indices),t.geometry_setIndices16(s,Bt,n)}else{new Uint32Array(t.HEAPU8.buffer,Bt,n).set(e.indices),t.geometry_setIndices32(s,Bt,n)}}return s},updateVertices(e,t,s=0){const n=Lt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ft/4),n.geometry_updateVertices(e,Ft,r,s)},release(e){e>0&&Lt().geometry_release(e)},isValid:e=>!(!It||e<=0)&&It.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return $t.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return $t.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return $t.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Wt=null;function zt(e){Wt=e}function Ot(){Wt&&jt.isInitialized()&&jt.shutdown(),Wt=null}function Ht(){if(!Wt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Wt}const jt={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,s){Ht().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Ht().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Ht().postprocess_begin()},end(){Ht().postprocess_end()},getPassCount:()=>Ht().postprocess_getPassCount(),isInitialized:()=>!!Wt&&Wt.postprocess_isInitialized(),setBypass(e){Ht().postprocess_setBypass(e)},isBypassed:()=>!Wt||Wt.postprocess_isBypassed(),createBlur:()=>Xe.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:()=>Xe.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:()=>Xe.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:()=>Xe.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 Vt;exports.RenderStage=void 0,(Vt=exports.RenderStage||(exports.RenderStage={}))[Vt.Background=0]="Background",Vt[Vt.Opaque=1]="Opaque",Vt[Vt.Transparent=2]="Transparent",Vt[Vt.Overlay=3]="Overlay";let Xt=null,Gt=0;function qt(e){Xt=e,Gt=Xt._malloc(64)}function Yt(){Xt&&Gt&&(Xt._free(Gt),Gt=0),Xt=null}const Jt={init(e,t){Xt?.renderer_init(e,t)},resize(e,t){Xt?.renderer_resize(e,t)},begin(e,t){Xt&&Gt&&(Xt.HEAPF32.set(e,Gt/4),Xt.renderer_begin(Gt,t??0))},flush(){Xt?.renderer_flush()},end(){Xt?.renderer_end()},submitSprites(e){Xt&&Xt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Xt&&Xt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Xt&&Xt.renderer_submitSpine?.(e._cpp)},setStage(e){Xt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Xt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Xt?.renderer_releaseTarget(e)},getTargetTexture:e=>Xt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Xt?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Xt?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Xt?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Xt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Xt?Xt.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Xt?{drawCalls:Xt.renderer_getDrawCalls(),triangles:Xt.renderer_getTriangles(),sprites:Xt.renderer_getSprites(),text:Xt.renderer_getText(),spine:Xt.renderer_getSpine?.()??0,meshes:Xt.renderer_getMeshes(),culled:Xt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt=null}const es={enable(){Kt?.gl_enableErrorCheck(!0)},disable(){Kt?.gl_enableErrorCheck(!1)},check:e=>Kt?.gl_checkErrors(e)??0,diagnose(){Kt?.renderer_diagnose()}},ts=new Map;function ss(e){ts.delete(e)}class ns{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Jt.resize(n,r),jt.isInitialized()&&jt.getPassCount()>0&&jt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Jt.setViewport(0,0,n,r),Jt.clearBuffers(3),Jt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Jt.submitSprites(t),Jt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Jt.submitSpine(t),Jt.flush(),this.executeDrawCallbacks(s,o),Jt.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Jt.setViewport(n.x,n.y,n.w,n.h),Jt.setScissor(n.x,n.y,n.w,n.h,!0),Jt.clearBuffers(r),Jt.setScissor(0,0,0,0,!1),Jt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Jt.submitSprites(t),Jt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Jt.submitSpine(t),Jt.flush(),this.executeDrawCallbacks(s,o),Jt.end()}executeDrawCallbacks(e,t){const s=ts;if(s.size>0){At.begin(e);const n=[];for(const[e,r]of s.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}At.end();for(const e of n)ss(e)}}}class rs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),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 ke,this.resources_=new me;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new rs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}onError(e){return this.error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1;const e=[Zt,Yt,Ot,Dt,Ne,Pt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}const os=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function is(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function as(e,t,s,n){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*s/(l.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,o){h=is(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=cs(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=ds(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=ps(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(gs(u,p)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const ls=new Float32Array(16);function cs(e,t,s,n,r,o){const i=ls;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const us=new Float32Array(16);function ds(e,t,s,n){const r=us;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const hs=new Float32Array(16);function ps(e,t,s){const n=hs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const fs=new Float32Array(16);function gs(e,t){const s=fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var ms,ys,_s;exports.TextAlign=void 0,(ms=exports.TextAlign||(exports.TextAlign={}))[ms.Left=0]="Left",ms[ms.Center=1]="Center",ms[ms.Right=2]="Right",exports.TextVerticalAlign=void 0,(ys=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ys.Top=0]="Top",ys[ys.Middle=1]="Middle",ys[ys.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_s=exports.TextOverflow||(exports.TextOverflow={}))[_s.Visible=0]="Visible",_s[_s.Clip=1]="Clip",_s[_s.Ellipsis=2]="Ellipsis";const xs=$("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),ws=$("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class vs{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I,I),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function bs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Ss(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Ps{build(e){N("Text",xs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new vs(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,xs));for(const e of r.keys())n.valid(e)&&n.has(e,xs)||r.delete(e);const e=n.getEntitiesWithComponents([xs]);for(const t of e){const e=n.get(t,xs),o=n.has(t,ws)?n.get(t,ws):null,i=r.get(t);if(i&&!Ss(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,bs(e,o))}}))}}const Ts=new Ps,Cs=$("UIMask",{enabled:!0});function As(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Es(e,t,s,n,r,o,i,a,l,c,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[m,y]=g(d,p),[_,x]=g(h,f),w=Math.min(m,_),v=Math.max(m,_),b=Math.min(y,x),S=Math.max(y,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ms(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],m=e[13],y=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,T=d*m-h*g,C=d*y-p*g,A=d*_-f*g,E=h*y-p*m,M=h*_-f*m,R=p*_-f*y;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(m*P-y*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(y*v-g*P-_*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-l*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(g*S-m*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*C-a*E-c*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(m*w-g*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function Rs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Is(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function Fs(e,t,s,n,r,o,i){if(!e.has(t,ws)||!e.has(t,K))return null;const a=e.get(t,ws),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Es(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Bs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Cs]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,Cs).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=Fs(t,s,r,o,i,a,l);e&&(n=As(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Fs(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Us{build(e){if(N("UIMask",Cs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Bs(e.wasmModule,e.world))}}const ks=new Us,Ds=$("Interactable",{enabled:!0}),Ls=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var $s;exports.ButtonState=void 0,($s=exports.ButtonState||(exports.ButtonState={}))[$s.Normal=0]="Normal",$s[$s.Hovered=1]="Hovered",$s[$s.Pressed=2]="Pressed",$s[$s.Disabled=3]="Disabled";const Ws=$("Button",{state:exports.ButtonState.Normal,transition:null});class zs{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Os=pe(new zs,"UIEvents"),Hs=W("ScreenSpace");function js(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,g=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,g=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function Ns(e,t,s,n,r,o){if(!e.has(t,ws))return;const i=e.get(t,ws),a=js(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ns(e,t,a.rect,a.centerX,a.centerY,!1)}class Vs{build(e){N("UIRect",ws);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([fe(De)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([Hs,ws,J]);for(const e of o)Ns(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Xs=new Vs,Gs=new Float32Array(16),qs=new Float32Array(16);let Ys=!0,Js=1;class Ks{build(e){N("Interactable",Ds),N("Button",Ws);const t=e.world,s=new zs;e.insertResource(Os,s);let n=null,r=null;Js="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([fe(Ee),fe(De)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Ls]);for(const e of i){const s=t.get(e,Ls);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Js,l=o.screenH-e.mouseY*Js;!function(e){let t=!1;for(let s=0;s<16;s++)if(qs[s]!==e[s]){t=!0;break}t&&(qs.set(e),Ys=!0)}(o.viewProjection),Ys&&(Ms(o.viewProjection,Gs),Ys=!1);const c=Rs(a,l,Gs,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Ds,ws,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Ls)||t.insert(e,Ls);if(!t.get(e,Ds).enabled)continue;const s=t.get(e,K),n=t.get(e,ws),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Is(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,Ls)){t.get(n,Ls).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Ls).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ls);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ls)){const e=t.get(r,Ls);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Pe([],()=>{const e=t.getEntitiesWithComponents([Ws]);for(const s of e){if(t.has(s,Ds)||t.insert(s,Ds,{enabled:!0}),!t.has(s,Ls))continue;const e=t.get(s,Ls),n=t.get(s,Ws),r=t.get(s,Ds),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const Qs=new Ks,Zs=$("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class en{build(e){N("TextInput",Zs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const p=h;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,Zs);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(Os).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,y()}function g(e){if(a===e)return;m();const t=s.get(e,Zs);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),y())}function m(){if(null!==a&&s.valid(a)&&s.has(a,Zs)){const e=s.get(a,Zs);e.focused=!1,e.dirty=!0}a=null,p.blur()}function y(){c=!0,u=0}function _(e,i,a,l){(r.width<a||r.height<l)&&(r.width=sn(Math.max(r.width,a)),r.height=sn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=tn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=tn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const m=o.getImageData(0,0,a,l),y=new Uint8Array(m.data.buffer),_=t.getResourceManager(),x=t._malloc(y.length);t.HEAPU8.set(y,x);const w=n.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(a,l,x,y.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Q,b)}p.addEventListener("input",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const n=s.get(a,Zs);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Os).emit(a,"submit"),void m()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,y())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,Zs)){const e=s.get(a,Zs);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([fe(Os)],e=>{const t=s.getEntitiesWithComponents([Zs,Ds]);for(const e of t){if(!s.has(e,Ls))continue;if(s.get(e,Ls).justPressed)return void g(e)}if(null!==a){const e=s.getEntitiesWithComponents([Ds]);for(const t of e){if(s.has(t,Zs))continue;if(!s.has(t,Ls))continue;if(s.get(t,Ls).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,Zs)))){s.get(a,Zs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Zs)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([Zs,ws]);for(const e of i){const t=s.get(e,Zs);if(!t.dirty)continue;const n=s.get(e,ws),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),_(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function tn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function sn(e){let t=1;for(;t<e;)t*=2;return t}const nn=new en;async function rn(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const on=pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),an=pe(null,"PhysicsAPI");function ln(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function cn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class un{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(on,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=rn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Pe([fe(ye)],a=>{const l=i.getEntitiesWithComponents([ae,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,ae),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=ln(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),dn(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===de.Kinematic){const e=ln(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=ln(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=cn(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(on,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(an,hn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function dn(e,t,s){const n=e.world;if(n.has(s,le)){const e=n.get(s,le);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ce)){const e=n.get(s,ce);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ue)){const e=n.get(s,ue);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class hn{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(hn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function pn(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function fn(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function gn(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,m=a*p,y=l*h,_=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(y+x))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(f+x))*o,(_+w)*o,0,(m+v)*i,(_-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function mn(e,t,s,n,r,o,i,a){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=pn(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===g(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=fn(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=pn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new un("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=pn(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),h=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Xe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Xe.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),p=rt(e.world,s);if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,Q);r&&(r.texture=s[n.data.texture]||0,e.insert(t,Q,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}else if("SpineAnimation"===n.type){const s=e.get(t,oe);s&&(s.material=r,e.insert(t,oe,s))}}}}(e.world,s,h,p),r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,c,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=gn(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(m,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,r,x,o,f,g,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(lt);t&&t.setAddressableManifest(a)}}class yn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===g(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const _n={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Jt.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Jt.getTargetTexture(s),width:e.width,height:e.height}},release(e){Jt.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Jt.releaseRenderTarget(e._handle),_n.create({width:t,height:s,depth:!0})),begin(e,t){Jt.begin(t,e._handle)},end(){Jt.end()},getDepthTexture:e=>Jt.getTargetDepthTexture(e._handle)};let xn=!1;var wn;exports.LogLevel=void 0,(wn=exports.LogLevel||(exports.LogLevel={}))[wn.Debug=0]="Debug",wn[wn.Info=1]="Info",wn[wn.Warn=2]="Warn",wn[wn.Error=3]="Error";class vn{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class bn{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new vn)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Sn=new bn;const Pn=[Ts,ks,Xs,Qs,nn];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E,exports.App=rs,exports.AssetPlugin=ct,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=at,exports.Assets=lt,exports.AsyncCache=tt,exports.BitmapText=re,exports.BodyType=de,exports.BoxCollider=le,exports.Button=Ws,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=ce,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=ve,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=I,exports.Draw=At,exports.EntityCommands=we,exports.GLDebug=es,exports.Geometry=$t,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Ee,exports.InputPlugin=Me,exports.InputState=Ae,exports.Interactable=Ds,exports.LocalTransform=J,exports.Logger=bn,exports.Material=Xe,exports.MaterialLoader=st,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=hn,exports.PhysicsEvents=on,exports.PhysicsPlugin=un,exports.PostProcess=jt,exports.PrefabServer=ft,exports.Prefabs=gt,exports.PrefabsPlugin=mt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.currentScene_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene(),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await s(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const r=new yn(this.baseUrl_);await r.prefetch(n);let o=null;const i=this.app_.spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await mn(this.app_,this.app_.wasmModule,n,r,o),e="ensureCamera",this.ensureCamera()}catch(t){const s=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${s}\n${n}`),new Error(`[PreviewPlugin:${e}] ${s}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,J,o);const i={isActive:!0,projectionType:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth};e.insert(r,Z,i)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new yn(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await mn(this.app_,this.app_.wasmModule,t,n,r),this.ensureCamera(),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProjectionType=G,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{_e(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=xe,exports.RenderPipeline=ns,exports.RenderTexture=_n,exports.Renderer=Jt,exports.Res=fe,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=ae,exports.ScaleMode=Y,exports.ScreenSpace=Hs,exports.ShaderSources=et,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=xs,exports.TextInput=Zs,exports.TextInputPlugin=en,exports.TextPlugin=Ps,exports.TextRenderer=vs,exports.Time=ye,exports.UICameraInfo=De,exports.UIEventQueue=zs,exports.UIEvents=Os,exports.UIInteraction=Ls,exports.UIInteractionPlugin=Ks,exports.UILayoutPlugin=Vs,exports.UIMask=Cs,exports.UIMaskPlugin=Us,exports.UIRect=ws,exports.Velocity=te,exports.WebAssetProvider=yn,exports.World=ke,exports.WorldTransform=K,exports.addStartupSystem=function(e){Te().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Te().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Te().push({schedule:e,system:t})},exports.assetPlugin=ut,exports.clearDrawCallbacks=function(){ts.clear()},exports.clearUserComponents=function(){L().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=js,exports.createMaskProcessor=Bs,exports.createWebApp=function(e,t){return function(e,t){const s=rs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),St(e),je(e),kt(e),zt(e),qt(e),Qt(e);const r=new ns;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=as(e,n,t,r));const i=s.getResource(De);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(De,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=i();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Jt.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;Jt.resize(t,s),jt.isInitialized()&&jt.getPassCount()>0&&!jt.isBypassed()&&jt.resize(t,s);const d=as(e,n,t,s);if(l(t,s,d),0===d.length)r.render({registry:{_cpp:n},viewProjection:os,width:t,height:s,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}Jt.setViewport(0,0,t,s)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(ut),s.addPlugin(yt),s.addPlugin(Re),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Pn,...t})},exports.debug=function(e,t,s){Sn.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=pe,exports.defineSystem=Pe,exports.defineTag=W,exports.error=function(e,t,s){Sn.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=nt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=V(e);return t?U(t._default):null},exports.getCustomExtensions=y,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Sn},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return y().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Sn.info(e,t,s)},exports.initDrawAPI=St,exports.initGLDebugAPI=Qt,exports.initGeometryAPI=kt,exports.initMaterialAPI=je,exports.initPostProcessAPI=zt,exports.initRendererAPI=qt,exports.inputPlugin=Re,exports.instantiatePrefab=dt,exports.intersectRects=As,exports.invertMatrix4=Ms,exports.isBuiltinComponent=H,exports.isCustomExtension=_,exports.isEditor=function(){return xn},exports.isKnownAssetExtension=m,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!xn},exports.isTextureRef=$e,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=it,exports.loadPhysicsModule=rn,exports.loadRuntimeScene=mn,exports.loadSceneData=rt,exports.loadSceneWithAssets=ot,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&m(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Is,exports.prefabsPlugin=yt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){nt.set(e,t)},exports.registerDrawCallback=function(e,t){ts.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(lt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Ze,exports.screenToWorld=Rs,exports.setEditorMode=function(e){xn=e},exports.setLogLevel=function(e){Sn.setMinLevel(e)},exports.shutdownDrawAPI=Pt,exports.shutdownGLDebugAPI=Zt,exports.shutdownGeometryAPI=Dt,exports.shutdownMaterialAPI=Ne,exports.shutdownPostProcessAPI=Ot,exports.shutdownRendererAPI=Yt,exports.textInputPlugin=nn,exports.textPlugin=Ts,exports.uiInteractionPlugin=Qs,exports.uiLayoutPlugin=Xs,exports.uiMaskPlugin=ks,exports.uiPlugins=Pn,exports.unregisterDrawCallback=ss,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Sn.warn(e,t,s)},exports.worldRectToScreen=Es,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index f2f291b57..9ea6162cc 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const m=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],g={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},y=new Map,_=new Set;for(const e of m)for(const t of e.extensions)y.set(t,e),_.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return y.get(w(e))}function b(e){return x(e)?.editorType??"unknown"}function v(e){return x(e)?.addressableType??null}function P(e){for(const t of m)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function S(e){return _.has(e.toLowerCase())}function C(){return _}function T(e){return"string"==typeof e&&(!!e.includes("/")&&S(w(e)))}function E(){const e=[];for(const t of m)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return g[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(R(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function U(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function k(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function W(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function z(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function O(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function H(e){return O(await z(e))}let L=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return U(e)}async readTextFile(e){return k(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},N=1920,X=1080,V=100,q=512,G=0,Y=4294967295,J=4294967295,K=(e=0,t=0)=>({x:e,y:t}),Q=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),Z=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ee=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),te=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ne(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ne);const t={};for(const n in e)t[n]=ne(e[n]);return t}let se=0;function re(e,t){const n=++se;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...ne(t),...e}:ne(t)}}function oe(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ie(e,t){const n=oe(),s=n.get(e);if(s)return s;const r=re(e,t);return n.set(e,r),ue(e,t,!1),r}function ae(e){const t=oe(),n=t.get(e);if(n)return n;const s=re(e,{});return t.set(e,s),ue(e,{},!0),s}function le(e){return oe().get(e)}function ce(){oe().clear()}function ue(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function de(e){return!0===e._builtin}const he=new Map;function fe(e,t){he.set(e,t)}function pe(e){return he.get(e)??le(e)}function me(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return he.set(e,n),n}const ge={Perspective:0,Orthographic:1},ye={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},_e={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},we=me("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),xe=me("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=me("Sprite",{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),ve=me("Camera",{projectionType:ge.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ye.ColorAndDepth}),Pe=me("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:_e.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Se=me("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=me("Parent",{entity:0}),Te=me("Children",{entities:[]}),Ee=me("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Me=me("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Ae={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function Re(e){const t=pe(e);return t?ne(t._default):null}fe("Name",Ae);const Ie=me("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Fe=me("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Be=me("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=me("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ke={Static:0,Kinematic:1,Dynamic:2};let $e=0;function We(e,t){const n=++$e;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function De(e){return{_type:"res",_resource:e}}function ze(e){return{_type:"res_mut",_resource:e}}class Oe{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 He{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new Oe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Le=We({delta:0,elapsed:0,frameCount:0},"Time");function je(e){return{_type:"mut",_component:e}}function Ne(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Xe(...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 Ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Ne(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function qe(){return{_type:"commands"}}class Ge{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=de(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ye{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ge(this,null);return this.spawned_.push(e),e}entity(e){return new Ge(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Je;!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"}(Je||(Je={}));let Ke=0;function Qe(e,t,n){const s=++Ke;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ze(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function et(e){Ze().push({schedule:Je.Update,system:e})}function tt(e){Ze().push({schedule:Je.Startup,system:e})}function nt(e,t){Ze().push({schedule:e,system:t})}class st{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ye&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new Ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ye(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class rt{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 ot=We(new rt,"Input");class it{constructor(e){this.target_=e??null}build(e){const n=new rt;e.insertResource(ot,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(Je.Last,Qe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const at=new it;function lt(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:lt(e)}}return t}class ct{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return de(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return de(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return de(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(de(t)){if(!this.cppRegistry_)return null;const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){de(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,lt(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,n){const s=t.create(n);this.getStorage(t).set(e,s),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!de(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const ut=We({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var dt;function ht(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"}(dt||(dt={}));let ft=null,pt=null,mt=1;const gt=new Map;function yt(e){ft=e,pt=e.getResourceManager(),Et()}function _t(){0!==vt&&ft&&(ft._free(vt),vt=0),gt.clear(),mt=1,bt=!1,pt=null,ft=null}function wt(){if(!pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pt}const xt={createShader:(e,t)=>wt().createShader(e,t),releaseShader(e){e>0&&wt().releaseShader(e)},create(e){const t=mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??dt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return gt.set(t,n),t},get:e=>gt.get(e),setUniform(e,t,n){const s=gt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=gt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=gt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=gt.get(e);return t?.blendMode??dt.Normal},setDepthTest(e,t){const n=gt.get(e);n&&(n.depthTest=t)},getShader(e){const t=gt.get(e);return t?.shader??0},release(e){gt.delete(e)},isValid:e=>gt.has(e),releaseAll(){gt.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??dt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=gt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return gt.set(n,s),n},toAssetData(e,t){const n=gt.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=gt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let bt=!1,vt=0;const Pt=4096,St=new Map;let Ct=null;function Tt(e){const t=(0===vt&&ft&&(vt=ft._malloc(Pt)),vt);if(0===t||!ft)return{ptr:0,count:0};let n=0,s=0;const r=ft.HEAPU8,o=ft.HEAPU32,i=ft.HEAPF32;for(const[a,l]of e){if(n+128>Pt)break;let e=St.get(a);e||(Ct||(Ct=new TextEncoder),e=Ct.encode(a),St.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Et(){if(!ft||bt)return;ft.materialDataProvider=(e,t,n,s,r)=>{const o=gt.get(e);if(!o)return ft.HEAPU32[t>>2]=0,ft.HEAPU32[n>>2]=0,ft.HEAPU32[s>>2]=0,void(ft.HEAPU32[r>>2]=0);ft.HEAPU32[t>>2]=o.shader,ft.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Tt(o.uniforms);ft.HEAPU32[s>>2]=i,ft.HEAPU32[r>>2]=a},bt=!0}const Mt={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 At{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Rt{constructor(e,t=""){this.cache_=new At,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())xt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:xt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const It=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function Ft(e,t){It.set(e,t)}function Bt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ae,{value:s.name}),!1!==s.visible)for(const n of s.components)kt(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 Ut(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=It.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=It.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ae,{value:n.name}),!1!==n.visible)for(const s of n.components)kt(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 kt(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=pe(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function $t(e,t){const n=e.getEntitiesWithComponents([ve]);for(const s of n){const n=e.get(s,ve);n&&(n.aspectRatio=t,e.insert(s,ve,n))}}function Wt(e,t){const n=e.getEntitiesWithComponents([Ae]);for(const s of n){const n=e.get(s,Ae);if(n&&n.value===t)return s}return null}class Dt{constructor(e){this.textureCache_=new At,this.shaderCache_=new At,this.jsonCache_=new At,this.textCache_=new At,this.binaryCache_=new At,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new At,this.prefabCache_=new At,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(q,q),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Rt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),xt.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===x(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const zt=We(null,"Assets");class Ot{build(e){const t=e.wasmModule;t?e.insertResource(zt,new Dt(t)):console.warn("AssetPlugin: No WASM module available")}}const Ht=new Ot;function Lt(e,t){const n=e.getResource(zt);n&&n.registerEmbeddedAssets(t)}async function jt(e,t,n){const{entities:s,rootId:r}=await Nt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Ut(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Nt(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Nt(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Xt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function Xt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return jt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const qt=We(null,"Prefabs");class Gt{constructor(){this.name="PrefabsPlugin",this.dependencies=[zt]}build(e){const t=e.getResource(zt);e.insertResource(qt,new Vt(e.world,t))}}const Yt=new Gt;let Jt=null,Kt=0,Qt=0,Zt=0;const en=new Float32Array(256);function tn(e){Jt=e,Kt=Jt._malloc(64),Qt=Jt._malloc(64),Zt=Jt._malloc(1024)}function nn(){Jt&&(Kt&&(Jt._free(Kt),Kt=0),Qt&&(Jt._free(Qt),Qt=0),Zt&&(Jt._free(Zt),Zt=0)),Jt=null}function sn(){if(!Jt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Jt}const rn={r:1,g:1,b:1,a:1},on={begin(e){const t=sn();t.HEAPF32.set(e,Kt/4),t.draw_begin(Kt)},end(){sn().draw_end()},line(e,t,n,s=1){sn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){sn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){sn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){sn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){sn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=rn){sn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=rn){sn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){sn().draw_setLayer(e)},setDepth(e){sn().draw_setDepth(e)},getDrawCallCount:()=>Jt?Jt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Jt?Jt.draw_getPrimitiveCount():0,setBlendMode(e){sn().draw_setBlendMode(e)},setDepthTest(e){sn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=sn();s.HEAPF32.set(n,Qt/4),s.draw_mesh(e,t,Qt)},drawMeshWithMaterial(e,t,n){const s=sn(),r=xt.get(t);if(!r)return;if(on.setBlendMode(r.blendMode),on.setDepthTest(r.depthTest),0===r.uniforms.size)return void on.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Qt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=ln(t);if(!(s<0)){if(ht(n))en[o++]=10,en[o++]=s,en[o++]=n.slot??e++,en[o++]=n.textureId;else if("number"==typeof n)en[o++]=1,en[o++]=s,en[o++]=n;else if(Array.isArray(n)){en[o++]=n.length,en[o++]=s;for(let e=0;e<n.length;e++)en[o++]=n[e]}else"w"in n?(en[o++]=4,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z,en[o++]=n.w):"z"in n?(en[o++]=3,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z):(en[o++]=2,en[o++]=s,en[o++]=n.x,en[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(en.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Zt/4),s.draw_meshWithUniforms(e,r.shader,Qt,Zt,o)):s.draw_mesh(e,r.shader,Qt)}},an={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 ln(e){return an[e]??-1}var cn;!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"}(cn||(cn={}));let un=null,dn=0,hn=0,fn=0;function pn(e){un=e,dn=un._malloc(262144),hn=un._malloc(65536),fn=un._malloc(256)}function mn(){un&&(dn&&un._free(dn),hn&&un._free(hn),fn&&un._free(fn),dn=0,hn=0,fn=0),un=null}function gn(){if(!un)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return un}const yn={create(e){const t=gn(),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,dn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,fn,r).set(o),t.geometry_init(n,dn,s,fn,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,hn,s).set(e.indices),t.geometry_setIndices16(n,hn,s)}else{new Uint32Array(t.HEAPU8.buffer,hn,s).set(e.indices),t.geometry_setIndices32(n,hn,s)}}return n},updateVertices(e,t,n=0){const s=gn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,dn/4),s.geometry_updateVertices(e,dn,r,n)},release(e){e>0&&gn().geometry_release(e)},isValid:e=>!(!un||e<=0)&&un.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return yn.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:cn.Float2},{name:"a_texCoord",type:cn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return yn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:cn.Float2},{name:"a_texCoord",type:cn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return yn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:cn.Float2},{name:"a_texCoord",type:cn.Float2}],indices:new Uint16Array(i)})}};let _n=null;function wn(e){_n=e}function xn(){_n&&vn.isInitialized()&&vn.shutdown(),_n=null}function bn(){if(!_n)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return _n}const vn={init:(e,t)=>bn().postprocess_init(e,t),shutdown(){bn().postprocess_shutdown()},resize(e,t){bn().postprocess_resize(e,t)},addPass:(e,t)=>bn().postprocess_addPass(e,t),removePass(e){bn().postprocess_removePass(e)},setEnabled(e,t){bn().postprocess_setPassEnabled(e,t)},isEnabled:e=>bn().postprocess_isPassEnabled(e),setUniform(e,t,n){bn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){bn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){bn().postprocess_begin()},end(){bn().postprocess_end()},getPassCount:()=>bn().postprocess_getPassCount(),isInitialized:()=>!!_n&&_n.postprocess_isInitialized(),setBypass(e){bn().postprocess_setBypass(e)},isBypassed:()=>!_n||_n.postprocess_isBypassed(),createBlur:()=>xt.createShader(Pn,"#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:()=>xt.createShader(Pn,"#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:()=>xt.createShader(Pn,"#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:()=>xt.createShader(Pn,"#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")},Pn="#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 Sn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Sn||(Sn={}));let Cn=null,Tn=0;function En(e){Cn=e,Tn=Cn._malloc(64)}function Mn(){Cn&&Tn&&(Cn._free(Tn),Tn=0),Cn=null}const An={init(e,t){Cn?.renderer_init(e,t)},resize(e,t){Cn?.renderer_resize(e,t)},begin(e,t){Cn&&Tn&&(Cn.HEAPF32.set(e,Tn/4),Cn.renderer_begin(Tn,t??0))},flush(){Cn?.renderer_flush()},end(){Cn?.renderer_end()},submitSprites(e){Cn&&Cn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Cn&&Cn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Cn&&Cn.renderer_submitSpine?.(e._cpp)},setStage(e){Cn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Cn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Cn?.renderer_releaseTarget(e)},getTargetTexture:e=>Cn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Cn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Cn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Cn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Cn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Cn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Cn?Cn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Cn?{drawCalls:Cn.renderer_getDrawCalls(),triangles:Cn.renderer_getTriangles(),sprites:Cn.renderer_getSprites(),text:Cn.renderer_getText(),spine:Cn.renderer_getSpine?.()??0,meshes:Cn.renderer_getMeshes(),culled:Cn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Rn=null;function In(e){Rn=e}function Fn(){Rn=null}const Bn={enable(){Rn?.gl_enableErrorCheck(!0)},disable(){Rn?.gl_enableErrorCheck(!1)},check:e=>Rn?.gl_checkErrors(e)??0,diagnose(){Rn?.renderer_diagnose()}},Un=new Map;function kn(e,t){Un.set(e,t)}function $n(e){Un.delete(e)}function Wn(){Un.clear()}class Dn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(An.resize(s,r),vn.isInitialized()&&vn.getPassCount()>0&&vn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),An.setViewport(0,0,s,r),An.clearBuffers(3),An.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),An.submitSprites(t),An.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):An.submitSpine(t),An.flush(),this.executeDrawCallbacks(n,o),An.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;An.setViewport(s.x,s.y,s.w,s.h),An.setScissor(s.x,s.y,s.w,s.h,!0),An.clearBuffers(r),An.setScissor(0,0,0,0,!1),An.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),An.submitSprites(t),An.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):An.submitSpine(t),An.flush(),this.executeDrawCallbacks(n,o),An.end()}executeDrawCallbacks(e,t){const n=Un;if(n.size>0){on.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}on.end();for(const e of s)$n(e)}}}class zn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(Je.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Je.FixedPreUpdate),this.runSchedule(Je.FixedUpdate),this.runSchedule(Je.FixedPostUpdate),s++;s>=8&&(this.fixedAccumulator_=0),this.runSchedule(Je.PreUpdate),this.runSchedule(Je.Update),this.runSchedule(Je.PostUpdate),this.runSchedule(Je.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ct,this.resources_=new He;for(const e of Object.values(Je))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new zn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Je.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Je.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}onError(e){return this.error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_),this.resources_.insert(Le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Je.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[Fn,Mn,xn,mn,_t,nn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}updateTime(e){const t=this.resources_.get(Le);t.delta=e,t.elapsed+=e,t.frameCount++}}function On(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 Hn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ln(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case _e.FixedWidth:return o;case _e.FixedHeight:return i;case _e.Expand:return Math.max(o,i);case _e.Shrink:return Math.min(o,i);case _e.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function jn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===ge.Orthographic){if(h=r.orthoSize,o){h=Ln(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Xn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=qn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Yn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(Kn(u,f)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Nn=new Float32Array(16);function Xn(e,t,n,s,r,o){const i=Nn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const Vn=new Float32Array(16);function qn(e,t,n,s){const r=Vn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Gn=new Float32Array(16);function Yn(e,t,n){const s=Gn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const Jn=new Float32Array(16);function Kn(e,t){const n=Jn;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var Qn,Zn,es;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Qn||(Qn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Zn||(Zn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(es||(es={}));const ts=ie("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Qn.Left,verticalAlign:Zn.Top,wordWrap:!0,overflow:es.Visible,lineHeight:1.2}),ns=ie("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class ss{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(q,q),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===es.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===es.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Zn.Top:x=u;break;case Zn.Middle:x=(p-w)/2;break;case Zn.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case Qn.Left:s=u;break;case Qn.Center:s=f/2;break;case Qn.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===es.Clip&&n.restore();const v=n.getImageData(0,0,f,p),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{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)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Qn.Left:return"left";case Qn.Center:return"center";case Qn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function rs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function os(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class is{build(e){fe("Text",ts);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ss(t),s=e.world,r=new Map;e.addSystemToSchedule(Je.PreUpdate,Qe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,ts));for(const e of r.keys())s.valid(e)&&s.has(e,ts)||r.delete(e);const e=s.getEntitiesWithComponents([ts]);for(const t of e){const e=s.get(t,ts),o=s.has(t,ns)?s.get(t,ns):null,i=r.get(t);if(i&&!os(i,e,o))continue;s.has(t,be)||s.insert(t,be,{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,be);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,be,l),r.set(t,rs(e,o))}}))}}const as=new is,ls=ie("UIMask",{enabled:!0});function cs(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function us(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(d,f),[_,w]=m(h,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),P=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}function ds(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,T=d*y-f*m,E=d*_-p*m,M=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let I=w*R-x*A+b*M+v*E-P*T+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*M)*I,n[1]=(o*A-r*R-i*M)*I,n[2]=(g*S-y*P+_*v)*I,n[3]=(f*P-h*S-p*v)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+i*T)*I,n[6]=(y*b-m*S-_*x)*I,n[7]=(d*S-f*b+p*x)*I,n[8]=(a*A-l*E+u*C)*I,n[9]=(r*E-s*A-i*C)*I,n[10]=(m*P-g*b+_*w)*I,n[11]=(h*b-d*P-p*w)*I,n[12]=(l*T-a*M-c*C)*I,n[13]=(s*M-r*T+o*C)*I,n[14]=(g*x-m*v-y*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function hs(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function fs(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function ps(e,t,n,s,r,o,i){if(!e.has(t,ns)||!e.has(t,xe))return null;const a=e.get(t,ns),l=e.get(t,xe),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return us(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function ms(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([ls]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,ls).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=ps(t,n,r,o,i,a,l);e&&(s=cs(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=ps(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class gs{build(e){if(fe("UIMask",ls),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ms(e.wasmModule,e.world))}}const ys=new gs,_s=ie("Interactable",{enabled:!0}),ws=ie("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var xs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(xs||(xs={}));const bs=ie("Button",{state:xs.Normal,transition:null});class vs{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ps=We(new vs,"UIEvents"),Ss=ae("ScreenSpace");function Cs(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function Ts(e,t,n,s,r,o){if(!e.has(t,ns))return;const i=e.get(t,ns),a=Cs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,we);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,we,l),!e.has(t,Te))return;const c=e.get(t,Te);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ts(e,t,a.rect,a.centerX,a.centerY,!1)}class Es{build(e){fe("UIRect",ns);const t=e.world;e.addSystemToSchedule(Je.PreUpdate,Qe([De(ut)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Ss,ns,we]);for(const e of o)Ts(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Ms=new Es,As=new Float32Array(16),Rs=new Float32Array(16);let Is=!0,Fs=1;class Bs{build(e){fe("Interactable",_s),fe("Button",bs);const t=e.world,n=new vs;e.insertResource(Ps,n);let s=null,r=null;Fs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Je.PreUpdate,Qe([De(ot),De(ut)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([ws]);for(const e of i){const n=t.get(e,ws);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Fs,l=o.screenH-e.mouseY*Fs;!function(e){let t=!1;for(let n=0;n<16;n++)if(Rs[n]!==e[n]){t=!0;break}t&&(Rs.set(e),Is=!0)}(o.viewProjection),Is&&(ds(o.viewProjection,As),Is=!1);const c=hs(a,l,As,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([_s,ns,xe]);let d=null,h=-1/0;for(const e of u){t.has(e,ws)||t.insert(e,ws);if(!t.get(e,_s).enabled)continue;const n=t.get(e,xe),s=t.get(e,ns),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(fs(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,be)&&(n=t.get(e,be).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,ws)){t.get(s,ws).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,ws).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,ws);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ws)){const e=t.get(r,ws);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Je.Update,Qe([],()=>{const e=t.getEntitiesWithComponents([bs]);for(const n of e){if(t.has(n,_s)||t.insert(n,_s,{enabled:!0}),!t.has(n,ws))continue;const e=t.get(n,ws),s=t.get(n,bs),r=t.get(n,_s),o=s.state;if(r.enabled?e.pressed?s.state=xs.Pressed:e.hovered?s.state=xs.Hovered:s.state=xs.Normal:s.state=xs.Disabled,o!==s.state&&s.transition&&t.has(n,be)){const e=t.get(n,be),r=s.transition;switch(s.state){case xs.Normal:e.color={...r.normalColor};break;case xs.Hovered:e.color={...r.hoveredColor};break;case xs.Pressed:e.color={...r.pressedColor};break;case xs.Disabled:e.color={...r.disabledColor}}t.insert(n,be,e)}}},{name:"ButtonSystem"}))}}const Us=new Bs,ks=ie("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class $s{build(e){fe("TextInput",ks);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(q,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,ks);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Ps).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;g();const t=n.get(e,ks);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function g(){if(null!==i&&n.valid(i)&&n.has(i,ks)){const e=n.get(i,ks);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function _(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Ds(Math.max(r.width,a)),r.height=Ds(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ws(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ws(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,be);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,be,v)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,ks);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ps).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,ks)){const e=n.get(i,ks);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Je.PreUpdate,Qe([De(Ps)],e=>{const t=n.getEntitiesWithComponents([ks,_s]);for(const e of t){if(!n.has(e,ws))continue;if(n.get(e,ws).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([_s]);for(const t of e){if(n.has(t,ks))continue;if(!n.has(t,ws))continue;if(n.get(t,ws).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Je.PreUpdate,Qe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,ks)))){n.get(i,ks).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,ks)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([ks,ns]);for(const e of a){const t=n.get(e,ks);if(!t.dirty)continue;const s=n.get(e,ns),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,be)||n.insert(e,be,{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),_(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ws(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Ds(e){let t=1;for(;t<e;)t*=2;return t}const zs=new $s;async function Os(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Hs=We({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ls=We(null,"PhysicsAPI");function js(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ns(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Xs{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(Hs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Os(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Pe]);for(const n of t){const t=e.world.get(n,Pe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Je.PostUpdate,Qe([De(Le)],a=>{const l=i.getEntitiesWithComponents([Ie,we,xe]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,Ie),l=i.get(r,xe);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=js(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Vs(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ke.Kinematic){const e=js(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,we);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,Ce)){const t=e.world.get(i,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,xe)){const n=e.world.get(t.entity,xe),s=js(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Ns(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,we,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Hs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ls,qs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Vs(e,t,n){const s=e.world;if(s.has(n,Fe)){const e=s.get(n,Fe);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,Be)){const e=s.get(n,Be);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,Ue)){const e=s.get(n,Ue);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 qs{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(qs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Gs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Ys(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Js(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ks(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Gs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===x(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=Ys(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Gs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Xs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=x(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Gs(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),h=await async 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(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=xt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=xt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Bt(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,be);r&&(r.texture=n[s.data.texture]||0,e.insert(t,be,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,Ee);o&&(o.font=r,e.insert(t,Ee,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,be);n&&(n.material=r,e.insert(t,be,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Me);n&&(n.material=r,e.insert(t,Me,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Me)?c.get(o,Me):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,xe)){const e=Js(c.get(o,xe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(zt);t&&t.setAddressableManifest(a)}}class Qs{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Zs{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new Qs(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await Ks(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ve]);for(const s of n){if(e.get(s,ve).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Pe]);for(const r of s){const s=e.get(r,Pe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,we,o);const i={isActive:!0,projectionType:ge.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ye.ColorAndDepth};e.insert(r,ve,i)}}}const er={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=An.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:An.getTargetTexture(n),width:e.width,height:e.height}},release(e){An.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(An.releaseRenderTarget(e._handle),er.create({width:t,height:n,depth:!0})),begin(e,t){An.begin(t,e._handle)},end(){An.end()},getDepthTexture:e=>An.getTargetDepthTexture(e._handle)};let tr=!1;function nr(e){tr=e}function sr(){return tr}function rr(){return!tr}const or=[as,ys,Ms,Us,zs];function ir(e,t){return function(e,t){const n=zn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tn(e),yt(e),pn(e),wn(e),En(e),In(e);const r=new Dn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=jn(e,s,t,r));const i=n.getResource(ut);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ut,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;An.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;An.resize(t,n),vn.isInitialized()&&vn.getPassCount()>0&&!vn.isBypassed()&&vn.resize(t,n);const u=jn(e,s,t,n);if(a(t,n,u),0===u.length)r.render({registry:{_cpp:s},viewProjection:Hn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}An.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(Je.First,l),n.addSystemToSchedule(Je.Last,c),n.addPlugin(Ht),n.addPlugin(Yt),n.addPlugin(at),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:or,...t})}L||(L=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{zn as App,Ot as AssetPlugin,Dt as AssetServer,zt as Assets,At as AsyncCache,Ee as BitmapText,dt as BlendMode,ke as BodyType,Fe as BoxCollider,bs as Button,xs as ButtonState,ve as Camera,Pe as Canvas,Ue as CapsuleCollider,Te as Children,Be as CircleCollider,ye as ClearFlags,qe as Commands,Ye as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,cn as DataType,on as Draw,Ge as EntityCommands,Bn as GLDebug,yn as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,it as InputPlugin,rt as InputState,_s as Interactable,we as LocalTransform,xt as Material,Rt as MaterialLoader,je as Mut,Ae as Name,Ce as Parent,qs as Physics,Hs as PhysicsEvents,Xs as PhysicsPlugin,vn as PostProcess,Vt as PrefabServer,qt as Prefabs,Gt as PrefabsPlugin,Zs as PreviewPlugin,ge as ProjectionType,Xe as Query,Ve as QueryInstance,Dn as RenderPipeline,Sn as RenderStage,er as RenderTexture,An as Renderer,De as Res,ze as ResMut,Ie as RigidBody,_e as ScaleMode,Je as Schedule,Ss as ScreenSpace,Mt as ShaderSources,Me as SpineAnimation,be as Sprite,st as SystemRunner,ts as Text,Qn as TextAlign,ks as TextInput,$s as TextInputPlugin,es as TextOverflow,is as TextPlugin,ss as TextRenderer,Zn as TextVerticalAlign,Le as Time,ut as UICameraInfo,vs as UIEventQueue,Ps as UIEvents,ws as UIInteraction,Bs as UIInteractionPlugin,Es as UILayoutPlugin,ls as UIMask,gs as UIMaskPlugin,ns as UIRect,Se as Velocity,Qs as WebAssetProvider,ct as World,xe as WorldTransform,tt as addStartupSystem,et as addSystem,nt as addSystemToSchedule,Ht as assetPlugin,Wn as clearDrawCallbacks,ce as clearUserComponents,ee as color,Cs as computeUIRectLayout,ms as createMaskProcessor,ir as createWebApp,ie as defineComponent,We as defineResource,Qe as defineSystem,ae as defineTag,Wt as findEntityByName,On as flushPendingSystems,v as getAddressableType,P as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,Re as getComponentDefaults,E as getCustomExtensions,b as getEditorType,t as getPlatform,s as getPlatformType,le as getUserComponent,M as getWeChatPackOptions,tn as initDrawAPI,In as initGLDebugAPI,pn as initGeometryAPI,yt as initMaterialAPI,wn as initPostProcessAPI,En as initRendererAPI,at as inputPlugin,jt as instantiatePrefab,cs as intersectRects,ds as invertMatrix4,de as isBuiltinComponent,R as isCustomExtension,sr as isEditor,S as isKnownAssetExtension,n as isPlatformInitialized,rr as isRuntime,ht as isTextureRef,r as isWeChat,o as isWeb,kt as loadComponent,Os as loadPhysicsModule,Ks as loadRuntimeScene,Bt as loadSceneData,Ut as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,fs as pointInWorldRect,Yt as prefabsPlugin,te as quat,fe as registerComponent,Ft as registerComponentAssetFields,kn as registerDrawCallback,Lt as registerEmbeddedAssets,Et as registerMaterialCallback,hs as screenToWorld,nr as setEditorMode,nn as shutdownDrawAPI,Fn as shutdownGLDebugAPI,mn as shutdownGeometryAPI,_t as shutdownMaterialAPI,xn as shutdownPostProcessAPI,Mn as shutdownRendererAPI,zs as textInputPlugin,as as textPlugin,Us as uiInteractionPlugin,Ms as uiLayoutPlugin,ys as uiMaskPlugin,or as uiPlugins,$n as unregisterDrawCallback,$t as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,us as worldRectToScreen,$ as wxFileExists,W as wxFileExistsSync,O as wxGetImagePixels,z as wxLoadImage,H as wxLoadImagePixels,U as wxReadFile,k as wxReadTextFile,D as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const m=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],g={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,y=new Set;for(const e of m)for(const t of e.extensions)_.set(t,e),y.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return _.get(w(e))}function b(e){return x(e)?.editorType??"unknown"}function v(e){return x(e)?.addressableType??null}function P(e){for(const t of m)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function S(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&S(w(e)))}function E(){const e=[];for(const t of m)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function A(){return E().map(e=>({type:"suffix",value:e}))}function M(e){return g[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(R(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function U(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function k(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function z(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function O(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function H(e){return O(await W(e))}let L=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return U(e)}async readTextFile(e){return k(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},N=1920,X=1080,V=100,q=512,G=0,Y=4294967295,J=4294967295,K=(e=0,t=0)=>({x:e,y:t}),Q=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),Z=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ee=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),te=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ne(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ne);const t={};for(const n in e)t[n]=ne(e[n]);return t}let se=0;function re(e,t){const n=++se;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...ne(t),...e}:ne(t)}}function oe(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ie(e,t){const n=oe(),s=n.get(e);if(s)return s;const r=re(e,t);return n.set(e,r),ue(e,t,!1),r}function ae(e){const t=oe(),n=t.get(e);if(n)return n;const s=re(e,{});return t.set(e,s),ue(e,{},!0),s}function le(e){return oe().get(e)}function ce(){oe().clear()}function ue(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function de(e){return!0===e._builtin}const he=new Map;function fe(e,t){he.set(e,t)}function pe(e){return he.get(e)??le(e)}function me(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return he.set(e,n),n}const ge={Perspective:0,Orthographic:1},_e={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ye={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},we=me("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),xe=me("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=me("Sprite",{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),ve=me("Camera",{projectionType:ge.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:_e.ColorAndDepth}),Pe=me("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:ye.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Se=me("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=me("Parent",{entity:0}),Te=me("Children",{entities:[]}),Ee=me("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Ae=me("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Me={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function Re(e){const t=pe(e);return t?ne(t._default):null}fe("Name",Me);const Ie=me("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Fe=me("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Be=me("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=me("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ke={Static:0,Kinematic:1,Dynamic:2};let $e=0;function ze(e,t){const n=++$e;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function De(e){return{_type:"res",_resource:e}}function We(e){return{_type:"res_mut",_resource:e}}class Oe{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 He{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new Oe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Le=ze({delta:0,elapsed:0,frameCount:0},"Time");function je(e){return{_type:"mut",_component:e}}function Ne(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Xe(...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 Ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Ne(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function qe(){return{_type:"commands"}}class Ge{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=de(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ye{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ge(this,null);return this.spawned_.push(e),e}entity(e){return new Ge(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Je;!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"}(Je||(Je={}));let Ke=0;function Qe(e,t,n){const s=++Ke;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ze(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function et(e){Ze().push({schedule:Je.Update,system:e})}function tt(e){Ze().push({schedule:Je.Startup,system:e})}function nt(e,t){Ze().push({schedule:e,system:t})}class st{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ye&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new Ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ye(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class rt{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 ot=ze(new rt,"Input");class it{constructor(e){this.target_=e??null}build(e){const n=new rt;e.insertResource(ot,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(Je.Last,Qe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const at=new it;function lt(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=ct(t[e]),o=ct(r);n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r})}return s}function ct(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ut(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}function dt(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:dt(e)}}return t}class ht{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}isIterating(){return this.iterationDepth_>0}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 de(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return de(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return de(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(de(t)){if(!this.cppRegistry_)return null;const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");de(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=lt(t._name,t._default,s);if(e.length>0)throw new Error(ut(t._name,e))}const r={...t._default,...s};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,dt(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=lt(t._name,t._default,e);if(r.length>0)throw new Error(ut(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),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),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!de(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const ft=ze({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var pt;function mt(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"}(pt||(pt={}));let gt=null,_t=null,yt=1;const wt=new Map;function xt(e){gt=e,_t=e.getResourceManager(),Rt()}function bt(){0!==Ct&&gt&&(gt._free(Ct),Ct=0),wt.clear(),yt=1,St=!1,_t=null,gt=null}function vt(){if(!_t)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return _t}const Pt={createShader:(e,t)=>vt().createShader(e,t),releaseShader(e){e>0&&vt().releaseShader(e)},create(e){const t=yt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??pt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return wt.set(t,n),t},get:e=>wt.get(e),setUniform(e,t,n){const s=wt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=wt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=wt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=wt.get(e);return t?.blendMode??pt.Normal},setDepthTest(e,t){const n=wt.get(e);n&&(n.depthTest=t)},getShader(e){const t=wt.get(e);return t?.shader??0},release(e){wt.delete(e)},isValid:e=>wt.has(e),releaseAll(){wt.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=wt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=yt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return wt.set(n,s),n},toAssetData(e,t){const n=wt.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=wt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let St=!1,Ct=0;const Tt=4096,Et=new Map;let At=null;function Mt(e){const t=(0===Ct&&gt&&(Ct=gt._malloc(Tt)),Ct);if(0===t||!gt)return{ptr:0,count:0};let n=0,s=0;const r=gt.HEAPU8,o=gt.HEAPU32,i=gt.HEAPF32;for(const[a,l]of e){if(n+128>Tt)break;let e=Et.get(a);e||(At||(At=new TextEncoder),e=At.encode(a),Et.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Rt(){if(!gt||St)return;gt.materialDataProvider=(e,t,n,s,r)=>{const o=wt.get(e);if(!o)return gt.HEAPU32[t>>2]=0,gt.HEAPU32[n>>2]=0,gt.HEAPU32[s>>2]=0,void(gt.HEAPU32[r>>2]=0);gt.HEAPU32[t>>2]=o.shader,gt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Mt(o.uniforms);gt.HEAPU32[s>>2]=i,gt.HEAPU32[r>>2]=a},St=!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 Ft{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Bt{constructor(e,t=""){this.cache_=new Ft,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Pt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Pt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function kt(e,t){Ut.set(e,t)}function $t(e){const t=Ut.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function zt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Me,{value:s.name}),!1!==s.visible)for(const n of s.components)Wt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Dt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Me,{value:n.name}),!1!==n.visible)for(const s of n.components)Wt(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 Wt(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=pe(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function Ot(e,t){const n=e.getEntitiesWithComponents([ve]);for(const s of n){const n=e.get(s,ve);n&&(n.aspectRatio=t,e.insert(s,ve,n))}}function Ht(e,t){const n=e.getEntitiesWithComponents([Me]);for(const s of n){const n=e.get(s,Me);if(n&&n.value===t)return s}return null}class Lt{constructor(e){this.textureCache_=new Ft,this.shaderCache_=new Ft,this.jsonCache_=new Ft,this.textCache_=new Ft,this.binaryCache_=new Ft,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ft,this.prefabCache_=new Ft,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(q,q),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Bt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Pt.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===x(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Pt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Pt.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const jt=ze(null,"Assets");class Nt{build(e){const t=e.wasmModule;t?e.insertResource(jt,new Lt(t)):console.warn("AssetPlugin: No WASM module available")}}const Xt=new Nt;class Vt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function qt(e,t){const n=e.getResource(jt);n&&n.registerEmbeddedAssets(t)}async function Gt(e,t,n){const{entities:s,rootId:r}=await Yt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Dt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Yt(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Yt(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Jt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function Jt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Kt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Gt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Qt=ze(null,"Prefabs");class Zt{constructor(){this.name="PrefabsPlugin",this.dependencies=[jt]}build(e){const t=e.getResource(jt);e.insertResource(Qt,new Kt(e.world,t))}}const en=new Zt;let tn=null,nn=0,sn=0,rn=0;const on=new Float32Array(256);function an(e){tn=e,nn=tn._malloc(64),sn=tn._malloc(64),rn=tn._malloc(1024)}function ln(){tn&&(nn&&(tn._free(nn),nn=0),sn&&(tn._free(sn),sn=0),rn&&(tn._free(rn),rn=0)),tn=null}function cn(){if(!tn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return tn}const un={r:1,g:1,b:1,a:1},dn={begin(e){const t=cn();t.HEAPF32.set(e,nn/4),t.draw_begin(nn)},end(){cn().draw_end()},line(e,t,n,s=1){cn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){cn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){cn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){cn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){cn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=un){cn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=un){cn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){cn().draw_setLayer(e)},setDepth(e){cn().draw_setDepth(e)},getDrawCallCount:()=>tn?tn.draw_getDrawCallCount():0,getPrimitiveCount:()=>tn?tn.draw_getPrimitiveCount():0,setBlendMode(e){cn().draw_setBlendMode(e)},setDepthTest(e){cn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=cn();s.HEAPF32.set(n,sn/4),s.draw_mesh(e,t,sn)},drawMeshWithMaterial(e,t,n){const s=cn(),r=Pt.get(t);if(!r)return;if(dn.setBlendMode(r.blendMode),dn.setDepthTest(r.depthTest),0===r.uniforms.size)return void dn.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,sn/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=fn(t);if(!(s<0)){if(mt(n))on[o++]=10,on[o++]=s,on[o++]=n.slot??e++,on[o++]=n.textureId;else if("number"==typeof n)on[o++]=1,on[o++]=s,on[o++]=n;else if(Array.isArray(n)){on[o++]=n.length,on[o++]=s;for(let e=0;e<n.length;e++)on[o++]=n[e]}else"w"in n?(on[o++]=4,on[o++]=s,on[o++]=n.x,on[o++]=n.y,on[o++]=n.z,on[o++]=n.w):"z"in n?(on[o++]=3,on[o++]=s,on[o++]=n.x,on[o++]=n.y,on[o++]=n.z):(on[o++]=2,on[o++]=s,on[o++]=n.x,on[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(on.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),rn/4),s.draw_meshWithUniforms(e,r.shader,sn,rn,o)):s.draw_mesh(e,r.shader,sn)}},hn={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 fn(e){return hn[e]??-1}var pn;!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"}(pn||(pn={}));let mn=null,gn=0,_n=0,yn=0;function wn(e){mn=e,gn=mn._malloc(262144),_n=mn._malloc(65536),yn=mn._malloc(256)}function xn(){mn&&(gn&&mn._free(gn),_n&&mn._free(_n),yn&&mn._free(yn),gn=0,_n=0,yn=0),mn=null}function bn(){if(!mn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return mn}const vn={create(e){const t=bn(),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,gn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,yn,r).set(o),t.geometry_init(n,gn,s,yn,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,_n,s).set(e.indices),t.geometry_setIndices16(n,_n,s)}else{new Uint32Array(t.HEAPU8.buffer,_n,s).set(e.indices),t.geometry_setIndices32(n,_n,s)}}return n},updateVertices(e,t,n=0){const s=bn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,gn/4),s.geometry_updateVertices(e,gn,r,n)},release(e){e>0&&bn().geometry_release(e)},isValid:e=>!(!mn||e<=0)&&mn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return vn.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:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return vn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return vn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(i)})}};let Pn=null;function Sn(e){Pn=e}function Cn(){Pn&&En.isInitialized()&&En.shutdown(),Pn=null}function Tn(){if(!Pn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pn}const En={init:(e,t)=>Tn().postprocess_init(e,t),shutdown(){Tn().postprocess_shutdown()},resize(e,t){Tn().postprocess_resize(e,t)},addPass:(e,t)=>Tn().postprocess_addPass(e,t),removePass(e){Tn().postprocess_removePass(e)},setEnabled(e,t){Tn().postprocess_setPassEnabled(e,t)},isEnabled:e=>Tn().postprocess_isPassEnabled(e),setUniform(e,t,n){Tn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Tn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Tn().postprocess_begin()},end(){Tn().postprocess_end()},getPassCount:()=>Tn().postprocess_getPassCount(),isInitialized:()=>!!Pn&&Pn.postprocess_isInitialized(),setBypass(e){Tn().postprocess_setBypass(e)},isBypassed:()=>!Pn||Pn.postprocess_isBypassed(),createBlur:()=>Pt.createShader(An,"#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:()=>Pt.createShader(An,"#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:()=>Pt.createShader(An,"#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:()=>Pt.createShader(An,"#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")},An="#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 Mn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mn||(Mn={}));let Rn=null,In=0;function Fn(e){Rn=e,In=Rn._malloc(64)}function Bn(){Rn&&In&&(Rn._free(In),In=0),Rn=null}const Un={init(e,t){Rn?.renderer_init(e,t)},resize(e,t){Rn?.renderer_resize(e,t)},begin(e,t){Rn&&In&&(Rn.HEAPF32.set(e,In/4),Rn.renderer_begin(In,t??0))},flush(){Rn?.renderer_flush()},end(){Rn?.renderer_end()},submitSprites(e){Rn&&Rn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Rn&&Rn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Rn&&Rn.renderer_submitSpine?.(e._cpp)},setStage(e){Rn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rn?.renderer_releaseTarget(e)},getTargetTexture:e=>Rn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Rn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Rn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Rn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Rn?Rn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Rn?{drawCalls:Rn.renderer_getDrawCalls(),triangles:Rn.renderer_getTriangles(),sprites:Rn.renderer_getSprites(),text:Rn.renderer_getText(),spine:Rn.renderer_getSpine?.()??0,meshes:Rn.renderer_getMeshes(),culled:Rn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let kn=null;function $n(e){kn=e}function zn(){kn=null}const Dn={enable(){kn?.gl_enableErrorCheck(!0)},disable(){kn?.gl_enableErrorCheck(!1)},check:e=>kn?.gl_checkErrors(e)??0,diagnose(){kn?.renderer_diagnose()}},Wn=new Map;function On(e,t){Wn.set(e,t)}function Hn(e){Wn.delete(e)}function Ln(){Wn.clear()}class jn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Un.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Un.setViewport(0,0,s,r),Un.clearBuffers(3),Un.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Un.submitSprites(t),Un.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Un.submitSpine(t),Un.flush(),this.executeDrawCallbacks(n,o),Un.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Un.setViewport(s.x,s.y,s.w,s.h),Un.setScissor(s.x,s.y,s.w,s.h,!0),Un.clearBuffers(r),Un.setScissor(0,0,0,0,!1),Un.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Un.submitSprites(t),Un.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Un.submitSpine(t),Un.flush(),this.executeDrawCallbacks(n,o),Un.end()}executeDrawCallbacks(e,t){const n=Wn;if(n.size>0){dn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}dn.end();for(const e of s)Hn(e)}}}class Nn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(Je.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Je.FixedPreUpdate),this.runSchedule(Je.FixedUpdate),this.runSchedule(Je.FixedPostUpdate),s++;s>=8&&(this.fixedAccumulator_=0),this.runSchedule(Je.PreUpdate),this.runSchedule(Je.Update),this.runSchedule(Je.PostUpdate),this.runSchedule(Je.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ht,this.resources_=new He;for(const e of Object.values(Je))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Nn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(Je.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Je.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}onError(e){return this.error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_),this.resources_.insert(Le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Je.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[zn,Bn,Cn,xn,bt,ln];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}}updateTime(e){const t=this.resources_.get(Le);t.delta=e,t.elapsed+=e,t.frameCount++}}function Xn(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 Vn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function qn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ye.FixedWidth:return o;case ye.FixedHeight:return i;case ye.Expand:return Math.max(o,i);case ye.Shrink:return Math.min(o,i);case ye.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Gn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===ge.Orthographic){if(h=r.orthoSize,o){h=qn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Jn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Qn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=es(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(ns(u,f)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Yn=new Float32Array(16);function Jn(e,t,n,s,r,o){const i=Yn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const Kn=new Float32Array(16);function Qn(e,t,n,s){const r=Kn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Zn=new Float32Array(16);function es(e,t,n){const s=Zn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const ts=new Float32Array(16);function ns(e,t){const n=ts;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var ss,rs,os;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ss||(ss={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(rs||(rs={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(os||(os={}));const is=ie("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ss.Left,verticalAlign:rs.Top,wordWrap:!0,overflow:os.Visible,lineHeight:1.2}),as=ie("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class ls{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(q,q),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===os.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,r&&e.overflow===os.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case rs.Top:x=u;break;case rs.Middle:x=(p-w)/2;break;case rs.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case ss.Left:s=u;break;case ss.Center:s=f/2;break;case ss.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===os.Clip&&n.restore();const v=n.getImageData(0,0,f,p),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{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)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case ss.Left:return"left";case ss.Center:return"center";case ss.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function cs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function us(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class ds{build(e){fe("Text",is);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ls(t),s=e.world,r=new Map;e.addSystemToSchedule(Je.PreUpdate,Qe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,is));for(const e of r.keys())s.valid(e)&&s.has(e,is)||r.delete(e);const e=s.getEntitiesWithComponents([is]);for(const t of e){const e=s.get(t,is),o=s.has(t,as)?s.get(t,as):null,i=r.get(t);if(i&&!us(i,e,o))continue;s.has(t,be)||s.insert(t,be,{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,be);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,be,l),r.set(t,cs(e,o))}}))}}const hs=new ds,fs=ie("UIMask",{enabled:!0});function ps(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ms(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,_]=m(d,f),[y,w]=m(h,p),x=Math.min(g,y),b=Math.max(g,y),v=Math.min(_,w),P=Math.max(_,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}function gs(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,T=d*_-f*m,E=d*y-p*m,A=h*_-f*g,M=h*y-p*g,R=f*y-p*_;let I=w*R-x*M+b*A+v*E-P*T+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*M+u*A)*I,n[1]=(o*M-r*R-i*A)*I,n[2]=(g*S-_*P+y*v)*I,n[3]=(f*P-h*S-p*v)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+i*T)*I,n[6]=(_*b-m*S-y*x)*I,n[7]=(d*S-f*b+p*x)*I,n[8]=(a*M-l*E+u*C)*I,n[9]=(r*E-s*M-i*C)*I,n[10]=(m*P-g*b+y*w)*I,n[11]=(h*b-d*P-p*w)*I,n[12]=(l*T-a*A-c*C)*I,n[13]=(s*A-r*T+o*C)*I,n[14]=(g*x-m*v-_*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function _s(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function ys(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function ws(e,t,n,s,r,o,i){if(!e.has(t,as)||!e.has(t,xe))return null;const a=e.get(t,as),l=e.get(t,xe),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ms(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function xs(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([fs]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,fs).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=ws(t,n,r,o,i,a,l);e&&(s=ps(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=ws(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class bs{build(e){if(fe("UIMask",fs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(xs(e.wasmModule,e.world))}}const vs=new bs,Ps=ie("Interactable",{enabled:!0}),Ss=ie("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Cs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Cs||(Cs={}));const Ts=ie("Button",{state:Cs.Normal,transition:null});class Es{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const As=ze(new Es,"UIEvents"),Ms=ae("ScreenSpace");function Rs(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function Is(e,t,n,s,r,o){if(!e.has(t,as))return;const i=e.get(t,as),a=Rs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,we);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,we,l),!e.has(t,Te))return;const c=e.get(t,Te);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Is(e,t,a.rect,a.centerX,a.centerY,!1)}class Fs{build(e){fe("UIRect",as);const t=e.world;e.addSystemToSchedule(Je.PreUpdate,Qe([De(ft)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Ms,as,we]);for(const e of o)Is(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Bs=new Fs,Us=new Float32Array(16),ks=new Float32Array(16);let $s=!0,zs=1;class Ds{build(e){fe("Interactable",Ps),fe("Button",Ts);const t=e.world,n=new Es;e.insertResource(As,n);let s=null,r=null;zs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Je.PreUpdate,Qe([De(ot),De(ft)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ss]);for(const e of i){const n=t.get(e,Ss);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*zs,l=o.screenH-e.mouseY*zs;!function(e){let t=!1;for(let n=0;n<16;n++)if(ks[n]!==e[n]){t=!0;break}t&&(ks.set(e),$s=!0)}(o.viewProjection),$s&&(gs(o.viewProjection,Us),$s=!1);const c=_s(a,l,Us,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Ps,as,xe]);let d=null,h=-1/0;for(const e of u){t.has(e,Ss)||t.insert(e,Ss);if(!t.get(e,Ps).enabled)continue;const n=t.get(e,xe),s=t.get(e,as),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(ys(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,be)&&(n=t.get(e,be).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Ss)){t.get(s,Ss).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Ss).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ss);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ss)){const e=t.get(r,Ss);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Je.Update,Qe([],()=>{const e=t.getEntitiesWithComponents([Ts]);for(const n of e){if(t.has(n,Ps)||t.insert(n,Ps,{enabled:!0}),!t.has(n,Ss))continue;const e=t.get(n,Ss),s=t.get(n,Ts),r=t.get(n,Ps),o=s.state;if(r.enabled?e.pressed?s.state=Cs.Pressed:e.hovered?s.state=Cs.Hovered:s.state=Cs.Normal:s.state=Cs.Disabled,o!==s.state&&s.transition&&t.has(n,be)){const e=t.get(n,be),r=s.transition;switch(s.state){case Cs.Normal:e.color={...r.normalColor};break;case Cs.Hovered:e.color={...r.hoveredColor};break;case Cs.Pressed:e.color={...r.pressedColor};break;case Cs.Disabled:e.color={...r.disabledColor}}t.insert(n,be,e)}}},{name:"ButtonSystem"}))}}const Ws=new Ds,Os=ie("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Hs{build(e){fe("TextInput",Os);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(q,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,Os);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(As).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,_()}function m(e){if(i===e)return;g();const t=n.get(e,Os);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),_())}function g(){if(null!==i&&n.valid(i)&&n.has(i,Os)){const e=n.get(i,Os);e.focused=!1,e.dirty=!0}i=null,f.blur()}function _(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=js(Math.max(r.width,a)),r.height=js(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ls(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ls(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),_=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(_.length);t.HEAPU8.set(_,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const b=y.createTexture(a,c,w,_.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,be);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,be,v)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,Os);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(As).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,_())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,Os)){const e=n.get(i,Os);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Je.PreUpdate,Qe([De(As)],e=>{const t=n.getEntitiesWithComponents([Os,Ps]);for(const e of t){if(!n.has(e,Ss))continue;if(n.get(e,Ss).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([Ps]);for(const t of e){if(n.has(t,Os))continue;if(!n.has(t,Ss))continue;if(n.get(t,Ss).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Je.PreUpdate,Qe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Os)))){n.get(i,Os).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Os)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Os,as]);for(const e of a){const t=n.get(e,Os);if(!t.dirty)continue;const s=n.get(e,as),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,be)||n.insert(e,be,{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ls(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function js(e){let t=1;for(;t<e;)t*=2;return t}const Ns=new Hs;async function Xs(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Vs=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),qs=ze(null,"PhysicsAPI");function Gs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ys(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Js{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Vs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Xs(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Pe]);for(const n of t){const t=e.world.get(n,Pe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Je.PostUpdate,Qe([De(Le)],a=>{const l=i.getEntitiesWithComponents([Ie,we,xe]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,Ie),l=i.get(r,xe);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Gs(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ks(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ke.Kinematic){const e=Gs(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,we);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,Ce)){const t=e.world.get(i,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,xe)){const n=e.world.get(t.entity,xe),s=Gs(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Ys(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,we,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Vs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(qs,Qs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Ks(e,t,n){const s=e.world;if(s.has(n,Fe)){const e=s.get(n,Fe);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,Be)){const e=s.get(n,Be);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,Ue)){const e=s.get(n,Ue);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 Qs{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Qs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Zs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function er(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function tr(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,_=l*h,y=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(_+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(y+x)*o,0,(g+b)*i,(y-x)*i,(1-(p+_))*i,0,e.position.x,e.position.y,e.position.z,1])}async function nr(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Zs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===x(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=er(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Zs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Js("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=x(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Zs(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),h=await async 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(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Pt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Pt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=zt(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,be);r&&(r.texture=n[s.data.texture]||0,e.insert(t,be,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,Ee);o&&(o.font=r,e.insert(t,Ee,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,be);n&&(n.material=r,e.insert(t,be,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Ae);n&&(n.material=r,e.insert(t,Ae,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Ae)?c.get(o,Ae):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,xe)){const e=tr(c.get(o,xe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(jt);t&&t.setAddressableManifest(a)}}class sr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class rr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.currentScene_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene(),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new sr(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await nr(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ve]);for(const s of n){if(e.get(s,ve).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Pe]);for(const r of s){const s=e.get(r,Pe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,we,o);const i={isActive:!0,projectionType:ge.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:_e.ColorAndDepth};e.insert(r,ve,i)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new sr(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await nr(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera(),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const or={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Un.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Un.getTargetTexture(n),width:e.width,height:e.height}},release(e){Un.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Un.releaseRenderTarget(e._handle),or.create({width:t,height:n,depth:!0})),begin(e,t){Un.begin(t,e._handle)},end(){Un.end()},getDepthTexture:e=>Un.getTargetDepthTexture(e._handle)};let ir=!1;function ar(e){ir=e}function lr(){return ir}function cr(){return!ir}var ur;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ur||(ur={}));class dr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ur[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ur.Debug:console.debug(t,n);break;case ur.Info:console.log(t,n);break;case ur.Warn:console.warn(t,n);break;case ur.Error:console.error(t,n)}}}class hr{constructor(){this.handlers_=[],this.minLevel_=ur.Info,this.addHandler(new dr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(ur.Debug,e,t,n)}info(e,t,n){this.log(ur.Info,e,t,n)}warn(e,t,n){this.log(ur.Warn,e,t,n)}error(e,t,n){this.log(ur.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const fr=new hr;function pr(){return fr}function mr(e){fr.setMinLevel(e)}function gr(e,t,n){fr.debug(e,t,n)}function _r(e,t,n){fr.info(e,t,n)}function yr(e,t,n){fr.warn(e,t,n)}function wr(e,t,n){fr.error(e,t,n)}const xr=[hs,vs,Bs,Ws,Ns];function br(e,t){return function(e,t){const n=Nn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),an(e),xt(e),wn(e),Sn(e),Fn(e),$n(e);const r=new jn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Gn(e,s,t,r));const i=n.getResource(ft);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ft,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Un.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;Un.resize(t,n),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,n);const u=Gn(e,s,t,n);if(a(t,n,u),0===u.length)r.render({registry:{_cpp:s},viewProjection:Vn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Un.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(Je.First,l),n.addSystemToSchedule(Je.Last,c),n.addPlugin(Xt),n.addPlugin(en),n.addPlugin(at),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:xr,...t})}L||(L=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{Nn as App,Nt as AssetPlugin,Vt as AssetRefCounter,Lt as AssetServer,jt as Assets,Ft as AsyncCache,Ee as BitmapText,pt as BlendMode,ke as BodyType,Fe as BoxCollider,Ts as Button,Cs as ButtonState,ve as Camera,Pe as Canvas,Ue as CapsuleCollider,Te as Children,Be as CircleCollider,_e as ClearFlags,qe as Commands,Ye as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,pn as DataType,dn as Draw,Ge as EntityCommands,Dn as GLDebug,vn as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,it as InputPlugin,rt as InputState,Ps as Interactable,we as LocalTransform,ur as LogLevel,hr as Logger,Pt as Material,Bt as MaterialLoader,je as Mut,Me as Name,Ce as Parent,Qs as Physics,Vs as PhysicsEvents,Js as PhysicsPlugin,En as PostProcess,Kt as PrefabServer,Qt as Prefabs,Zt as PrefabsPlugin,rr as PreviewPlugin,ge as ProjectionType,Xe as Query,Ve as QueryInstance,jn as RenderPipeline,Mn as RenderStage,or as RenderTexture,Un as Renderer,De as Res,We as ResMut,Ie as RigidBody,ye as ScaleMode,Je as Schedule,Ms as ScreenSpace,It as ShaderSources,Ae as SpineAnimation,be as Sprite,st as SystemRunner,is as Text,ss as TextAlign,Os as TextInput,Hs as TextInputPlugin,os as TextOverflow,ds as TextPlugin,ls as TextRenderer,rs as TextVerticalAlign,Le as Time,ft as UICameraInfo,Es as UIEventQueue,As as UIEvents,Ss as UIInteraction,Ds as UIInteractionPlugin,Fs as UILayoutPlugin,fs as UIMask,bs as UIMaskPlugin,as as UIRect,Se as Velocity,sr as WebAssetProvider,ht as World,xe as WorldTransform,tt as addStartupSystem,et as addSystem,nt as addSystemToSchedule,Xt as assetPlugin,Ln as clearDrawCallbacks,ce as clearUserComponents,ee as color,Rs as computeUIRectLayout,xs as createMaskProcessor,br as createWebApp,gr as debug,ie as defineComponent,ze as defineResource,Qe as defineSystem,ae as defineTag,wr as error,Ht as findEntityByName,Xn as flushPendingSystems,v as getAddressableType,P as getAddressableTypeByEditorType,C as getAllAssetExtensions,M as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,$t as getComponentAssetFields,Re as getComponentDefaults,E as getCustomExtensions,b as getEditorType,pr as getLogger,t as getPlatform,s as getPlatformType,le as getUserComponent,A as getWeChatPackOptions,_r as info,an as initDrawAPI,$n as initGLDebugAPI,wn as initGeometryAPI,xt as initMaterialAPI,Sn as initPostProcessAPI,Fn as initRendererAPI,at as inputPlugin,Gt as instantiatePrefab,ps as intersectRects,gs as invertMatrix4,de as isBuiltinComponent,R as isCustomExtension,lr as isEditor,S as isKnownAssetExtension,n as isPlatformInitialized,cr as isRuntime,mt as isTextureRef,r as isWeChat,o as isWeb,Wt as loadComponent,Xs as loadPhysicsModule,nr as loadRuntimeScene,zt as loadSceneData,Dt as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,ys as pointInWorldRect,en as prefabsPlugin,te as quat,fe as registerComponent,kt as registerComponentAssetFields,On as registerDrawCallback,qt as registerEmbeddedAssets,Rt as registerMaterialCallback,_s as screenToWorld,ar as setEditorMode,mr as setLogLevel,ln as shutdownDrawAPI,zn as shutdownGLDebugAPI,xn as shutdownGeometryAPI,bt as shutdownMaterialAPI,Cn as shutdownPostProcessAPI,Bn as shutdownRendererAPI,Ns as textInputPlugin,hs as textPlugin,Ws as uiInteractionPlugin,Bs as uiLayoutPlugin,vs as uiMaskPlugin,xr as uiPlugins,Hn as unregisterDrawCallback,Ot as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,yr as warn,ms as worldRectToScreen,$ as wxFileExists,z as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,H as wxLoadImagePixels,U as wxReadFile,k as wxReadTextFile,D as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index 405e60296..831ba85a6 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -630,6 +630,7 @@ declare class World {
private worldVersion_;
private queryCache_;
private builtinMethodCache_;
+ private iterationDepth_;
connectCpp(cppRegistry: CppRegistry): void;
disconnectCpp(): void;
get hasCpp(): boolean;
@@ -638,6 +639,9 @@ declare class World {
valid(entity: Entity): boolean;
entityCount(): number;
getWorldVersion(): number;
+ beginIteration(): void;
+ endIteration(): void;
+ isIterating(): boolean;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
removeParent(entity: Entity): void;
@@ -774,9 +778,12 @@ interface SystemDef {
readonly _fn: (...args: never[]) => void;
readonly _name: string;
}
-declare function defineSystem<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void, options?: {
+interface SystemOptions {
name?: string;
-}): SystemDef;
+ runBefore?: string[];
+ runAfter?: string[];
+}
+declare function defineSystem<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void, options?: SystemOptions): SystemDef;
declare function addSystem(system: SystemDef): void;
declare function addStartupSystem(system: SystemDef): void;
declare function addSystemToSchedule(schedule: Schedule, system: SystemDef): void;
@@ -864,7 +871,10 @@ declare class App {
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
- addSystemToSchedule(schedule: Schedule, system: SystemDef): this;
+ addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
+ runBefore?: string[];
+ runAfter?: string[];
+ }): this;
addSystem(system: SystemDef): this;
addStartupSystem(system: SystemDef): this;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
@@ -886,6 +896,7 @@ declare class App {
run(): void;
private mainLoop;
quit(): void;
+ private sortSystems;
private runSchedule;
private updateTime;
}
@@ -1448,6 +1459,7 @@ interface ComponentAssetFields {
spine?: SpineFieldDescriptor;
}
declare function registerComponentAssetFields(componentType: string, config: ComponentAssetFields): void;
+declare function getComponentAssetFields(componentType: string): string[];
declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;
declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;
declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;
@@ -1802,6 +1814,43 @@ declare class AssetPlugin implements Plugin {
}
declare const assetPlugin: AssetPlugin;
+/**
+ * @file AssetRefCounter.ts
+ * @brief Optional asset reference counting for debugging and monitoring
+ */
+interface AssetRefInfo {
+ assetPath: string;
+ refCount: number;
+ entities: number[];
+}
+declare class AssetRefCounter {
+ private textureRefs_;
+ private fontRefs_;
+ private materialRefs_;
+ addTextureRef(path: string, entity: number): void;
+ removeTextureRef(path: string, entity: number): void;
+ getTextureRefCount(path: string): number;
+ getTextureRefs(path: string): number[];
+ addFontRef(path: string, entity: number): void;
+ removeFontRef(path: string, entity: number): void;
+ getFontRefCount(path: string): number;
+ getFontRefs(path: string): number[];
+ addMaterialRef(path: string, entity: number): void;
+ removeMaterialRef(path: string, entity: number): void;
+ getMaterialRefCount(path: string): number;
+ getMaterialRefs(path: string): number[];
+ getAllTextureRefs(): AssetRefInfo[];
+ getAllFontRefs(): AssetRefInfo[];
+ getAllMaterialRefs(): AssetRefInfo[];
+ removeAllRefsForEntity(entity: number): void;
+ clear(): void;
+ getTotalRefCount(): {
+ textures: number;
+ fonts: number;
+ materials: number;
+ };
+}
+
/**
* @file index.ts
* @brief Asset module exports
@@ -1909,6 +1958,8 @@ declare class PreviewPlugin implements Plugin {
private baseUrl_;
private app_;
private loadPromise_;
+ private eventSource_;
+ private currentScene_;
constructor(sceneUrl: string, baseUrl?: string);
build(app: App): void;
/**
@@ -1917,6 +1968,8 @@ declare class PreviewPlugin implements Plugin {
waitForReady(): Promise<void>;
private loadScene;
private ensureCamera;
+ private setupHotReload;
+ private reloadScene;
}
/**
@@ -2503,6 +2556,47 @@ declare class Physics {
applyAngularImpulse(entity: Entity, impulse: number): void;
}
+/**
+ * @file logger.ts
+ * @brief Centralized logging system for SDK
+ */
+declare enum LogLevel {
+ Debug = 0,
+ Info = 1,
+ Warn = 2,
+ Error = 3
+}
+interface LogEntry {
+ timestamp: number;
+ level: LogLevel;
+ category: string;
+ message: string;
+ data?: unknown;
+}
+interface LogHandler {
+ handle(entry: LogEntry): void;
+}
+declare class Logger {
+ private handlers_;
+ private minLevel_;
+ constructor();
+ setMinLevel(level: LogLevel): void;
+ addHandler(handler: LogHandler): void;
+ removeHandler(handler: LogHandler): void;
+ clearHandlers(): void;
+ debug(category: string, message: string, data?: unknown): void;
+ info(category: string, message: string, data?: unknown): void;
+ warn(category: string, message: string, data?: unknown): void;
+ error(category: string, message: string, data?: unknown): void;
+ private log;
+}
+declare function getLogger(): Logger;
+declare function setLogLevel(level: LogLevel): void;
+declare function debug(category: string, message: string, data?: unknown): void;
+declare function info(category: string, message: string, data?: unknown): void;
+declare function warn(category: string, message: string, data?: unknown): void;
+declare function error(category: string, message: string, data?: unknown): void;
+
/**
* @file glDebug.ts
* @brief GL error checking API for debugging rendering issues
@@ -2521,5 +2615,5 @@ declare const uiPlugins: Plugin[];
declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;
-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, ScaleMode, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentDefaults, getCustomExtensions, getEditorType, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };
-export type { AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetContentType, AssetTypeEntry, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, EditorAssetType, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
+export { App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, LogLevel, Logger, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, ScaleMode, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, debug, defineComponent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFields, getComponentDefaults, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, setLogLevel, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, worldRectToScreen };
+export type { AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetContentType, AssetRefInfo, AssetTypeEntry, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, EditorAssetType, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index d33db65d6..b36c1cf39 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,m=1080,_=100,g=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),P=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),S=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),C=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const n in e)t[n]=T(e[n]);return t}let E=0;function M(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...T(t),...e}:T(t)}}function A(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const n=A(),s=n.get(e);if(s)return s;const r=M(e,t);return n.set(e,r),k(e,t,!1),r}function I(e){const t=A(),n=t.get(e);if(n)return n;const s=M(e,{});return t.set(e,s),k(e,{},!0),s}function F(e){return A().get(e)}function B(){A().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function U(e){return!0===e._builtin}const $=new Map;function z(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function L(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,n),n}const H={Perspective:0,Orthographic:1},O={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},j=L("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),N=L("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=L("Sprite",{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),X=L("Camera",{projectionType:H.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:O.ColorAndDepth}),Y=L("Canvas",{designResolution:{x:p,y:m},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=L("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=L("Parent",{entity:0}),J=L("Children",{entities:[]}),K=L("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=L("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Z={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function ee(e){const t=D(e);return t?T(t._default):null}z("Name",Z);const te=L("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ne=L("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),se=L("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=L("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe={Static:0,Kinematic:1,Dynamic:2};let ie=0;function ae(e,t){const n=++ie;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function le(e){return{_type:"res",_resource:e}}function ce(e){return{_type:"res_mut",_resource:e}}class ue{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 de{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new ue(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const he=ae({delta:0,elapsed:0,frameCount:0},"Time");function fe(e){return{_type:"mut",_component:e}}function pe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function me(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{pe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class _e{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>pe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ge(){return{_type:"commands"}}class ye{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=U(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 we{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ye(this,null);return this.spawned_.push(e),e}entity(e){return new ye(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var xe;!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"}(xe||(xe={}));let ve=0;function be(e,t,n){const s=++ve;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Se(e){Pe().push({schedule:xe.Update,system:e})}function Ce(e){Pe().push({schedule:xe.Startup,system:e})}function Te(e,t){Pe().push({schedule:e,system:t})}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof we&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new _e(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new we(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Ae=ae(new Me,"Input");class Re{constructor(e){this.target_=e??null}build(e){const n=new Me;e.insertResource(Ae,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(xe.Last,be([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Re;function Fe(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Fe(e)}}return t}class Be{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return U(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return U(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return U(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(U(t)){if(!this.cppRegistry_)return null;const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){U(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Fe(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,n){const s=t.create(n);this.getStorage(t).set(e,s),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!U(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const ke=ae({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ue;function $e(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"}(Ue||(Ue={}));let ze=null,De=null,Le=1;const He=new Map;function Oe(e){ze=e,De=e.getResourceManager(),Ke()}function We(){0!==Xe&&ze&&(ze._free(Xe),Xe=0),He.clear(),Le=1,Ve=!1,De=null,ze=null}function je(){if(!De)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return De}const Ne={createShader:(e,t)=>je().createShader(e,t),releaseShader(e){e>0&&je().releaseShader(e)},create(e){const t=Le++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ue.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return He.set(t,n),t},get:e=>He.get(e),setUniform(e,t,n){const s=He.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=He.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=He.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=He.get(e);return t?.blendMode??Ue.Normal},setDepthTest(e,t){const n=He.get(e);n&&(n.depthTest=t)},getShader(e){const t=He.get(e);return t?.shader??0},release(e){He.delete(e)},isValid:e=>He.has(e),releaseAll(){He.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ue.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=He.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Le++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return He.set(n,s),n},toAssetData(e,t){const n=He.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=He.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ve=!1,Xe=0;const Ye=4096,qe=new Map;let Ge=null;function Je(e){const t=(0===Xe&&ze&&(Xe=ze._malloc(Ye)),Xe);if(0===t||!ze)return{ptr:0,count:0};let n=0,s=0;const r=ze.HEAPU8,o=ze.HEAPU32,i=ze.HEAPF32;for(const[a,l]of e){if(n+128>Ye)break;let e=qe.get(a);e||(Ge||(Ge=new TextEncoder),e=Ge.encode(a),qe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Ke(){if(!ze||Ve)return;ze.materialDataProvider=(e,t,n,s,r)=>{const o=He.get(e);if(!o)return ze.HEAPU32[t>>2]=0,ze.HEAPU32[n>>2]=0,ze.HEAPU32[s>>2]=0,void(ze.HEAPU32[r>>2]=0);ze.HEAPU32[t>>2]=o.shader,ze.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Je(o.uniforms);ze.HEAPU32[s>>2]=i,ze.HEAPU32[r>>2]=a},Ve=!0}const Qe={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(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class et{constructor(e,t=""){this.cache_=new Ze,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ne.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ne.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Ne.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const tt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function nt(e,t){tt.set(e,t)}function st(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Z,{value:s.name}),!1!==s.visible)for(const n of s.components)ot(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 rt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=tt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=tt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Z,{value:n.name}),!1!==n.visible)for(const s of n.components)ot(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 ot(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=D(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function it(e,t){const n=e.getEntitiesWithComponents([X]);for(const s of n){const n=e.get(s,X);n&&(n.aspectRatio=t,e.insert(s,X,n))}}function at(e,t){const n=e.getEntitiesWithComponents([Z]);for(const s of n){const n=e.get(s,Z);if(n&&n.value===t)return s}return null}const lt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],ct={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},ut=new Map,dt=new Set;for(const e of lt)for(const t of e.extensions)ut.set(t,e),dt.add(t);function ht(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function ft(e){return ut.get(ht(e))}function pt(e){return ft(e)?.editorType??"unknown"}function mt(e){return ft(e)?.addressableType??null}function _t(e){for(const t of lt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function gt(e){return dt.has(e.toLowerCase())}function yt(){return dt}function wt(e){return"string"==typeof e&&(!!e.includes("/")&&gt(ht(e)))}function xt(){const e=[];for(const t of lt)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function vt(){return xt().map(e=>({type:"suffix",value:e}))}function bt(e){return ct[e.toLowerCase()]}function Pt(e){const t=ft(e);return t?.wechatPackInclude??!1}class St{constructor(e){this.textureCache_=new Ze,this.shaderCache_=new Ze,this.jsonCache_=new Ze,this.textCache_=new Ze,this.binaryCache_=new Ze,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ze,this.prefabCache_=new Ze,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(g,g),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new et(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ne.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===ft(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=ft(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return rt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Ne.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Ne.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ct=ae(null,"Assets");class Tt{build(e){const t=e.wasmModule;t?e.insertResource(Ct,new St(t)):console.warn("AssetPlugin: No WASM module available")}}const Et=new Tt;function Mt(e,t){const n=e.getResource(Ct);n&&n.registerEmbeddedAssets(t)}async function At(e,t,n){const{entities:s,rootId:r}=await Rt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await rt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Rt(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Rt(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};It(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function It(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Ft{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return At(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Bt=ae(null,"Prefabs");class kt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ct]}build(e){const t=e.getResource(Ct);e.insertResource(Bt,new Ft(e.world,t))}}const Ut=new kt;let $t=null,zt=0,Dt=0,Lt=0;const Ht=new Float32Array(256);function Ot(e){$t=e,zt=$t._malloc(64),Dt=$t._malloc(64),Lt=$t._malloc(1024)}function Wt(){$t&&(zt&&($t._free(zt),zt=0),Dt&&($t._free(Dt),Dt=0),Lt&&($t._free(Lt),Lt=0)),$t=null}function jt(){if(!$t)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return $t}const Nt={r:1,g:1,b:1,a:1},Vt={begin(e){const t=jt();t.HEAPF32.set(e,zt/4),t.draw_begin(zt)},end(){jt().draw_end()},line(e,t,n,s=1){jt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){jt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){jt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){jt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){jt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Nt){jt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Nt){jt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){jt().draw_setLayer(e)},setDepth(e){jt().draw_setDepth(e)},getDrawCallCount:()=>$t?$t.draw_getDrawCallCount():0,getPrimitiveCount:()=>$t?$t.draw_getPrimitiveCount():0,setBlendMode(e){jt().draw_setBlendMode(e)},setDepthTest(e){jt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=jt();s.HEAPF32.set(n,Dt/4),s.draw_mesh(e,t,Dt)},drawMeshWithMaterial(e,t,n){const s=jt(),r=Ne.get(t);if(!r)return;if(Vt.setBlendMode(r.blendMode),Vt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Vt.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Dt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Yt(t);if(!(s<0)){if($e(n))Ht[o++]=10,Ht[o++]=s,Ht[o++]=n.slot??e++,Ht[o++]=n.textureId;else if("number"==typeof n)Ht[o++]=1,Ht[o++]=s,Ht[o++]=n;else if(Array.isArray(n)){Ht[o++]=n.length,Ht[o++]=s;for(let e=0;e<n.length;e++)Ht[o++]=n[e]}else"w"in n?(Ht[o++]=4,Ht[o++]=s,Ht[o++]=n.x,Ht[o++]=n.y,Ht[o++]=n.z,Ht[o++]=n.w):"z"in n?(Ht[o++]=3,Ht[o++]=s,Ht[o++]=n.x,Ht[o++]=n.y,Ht[o++]=n.z):(Ht[o++]=2,Ht[o++]=s,Ht[o++]=n.x,Ht[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Ht.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Lt/4),s.draw_meshWithUniforms(e,r.shader,Dt,Lt,o)):s.draw_mesh(e,r.shader,Dt)}},Xt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Yt(e){return Xt[e]??-1}var qt;!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"}(qt||(qt={}));let Gt=null,Jt=0,Kt=0,Qt=0;function Zt(e){Gt=e,Jt=Gt._malloc(262144),Kt=Gt._malloc(65536),Qt=Gt._malloc(256)}function en(){Gt&&(Jt&&Gt._free(Jt),Kt&&Gt._free(Kt),Qt&&Gt._free(Qt),Jt=0,Kt=0,Qt=0),Gt=null}function tn(){if(!Gt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Gt}const nn={create(e){const t=tn(),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,Jt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Qt,r).set(o),t.geometry_init(n,Jt,s,Qt,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,Kt,s).set(e.indices),t.geometry_setIndices16(n,Kt,s)}else{new Uint32Array(t.HEAPU8.buffer,Kt,s).set(e.indices),t.geometry_setIndices32(n,Kt,s)}}return n},updateVertices(e,t,n=0){const s=tn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Jt/4),s.geometry_updateVertices(e,Jt,r,n)},release(e){e>0&&tn().geometry_release(e)},isValid:e=>!(!Gt||e<=0)&&Gt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return nn.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:qt.Float2},{name:"a_texCoord",type:qt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return nn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:qt.Float2},{name:"a_texCoord",type:qt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return nn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:qt.Float2},{name:"a_texCoord",type:qt.Float2}],indices:new Uint16Array(i)})}};let sn=null;function rn(e){sn=e}function on(){sn&&ln.isInitialized()&&ln.shutdown(),sn=null}function an(){if(!sn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return sn}const ln={init:(e,t)=>an().postprocess_init(e,t),shutdown(){an().postprocess_shutdown()},resize(e,t){an().postprocess_resize(e,t)},addPass:(e,t)=>an().postprocess_addPass(e,t),removePass(e){an().postprocess_removePass(e)},setEnabled(e,t){an().postprocess_setPassEnabled(e,t)},isEnabled:e=>an().postprocess_isPassEnabled(e),setUniform(e,t,n){an().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){an().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){an().postprocess_begin()},end(){an().postprocess_end()},getPassCount:()=>an().postprocess_getPassCount(),isInitialized:()=>!!sn&&sn.postprocess_isInitialized(),setBypass(e){an().postprocess_setBypass(e)},isBypassed:()=>!sn||sn.postprocess_isBypassed(),createBlur:()=>Ne.createShader(cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ne.createShader(cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ne.createShader(cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ne.createShader(cn,"#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")},cn="#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 un;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(un||(un={}));let dn=null,hn=0;function fn(e){dn=e,hn=dn._malloc(64)}function pn(){dn&&hn&&(dn._free(hn),hn=0),dn=null}const mn={init(e,t){dn?.renderer_init(e,t)},resize(e,t){dn?.renderer_resize(e,t)},begin(e,t){dn&&hn&&(dn.HEAPF32.set(e,hn/4),dn.renderer_begin(hn,t??0))},flush(){dn?.renderer_flush()},end(){dn?.renderer_end()},submitSprites(e){dn&&dn.renderer_submitSprites(e._cpp)},submitBitmapText(e){dn&&dn.renderer_submitBitmapText(e._cpp)},submitSpine(e){dn&&dn.renderer_submitSpine?.(e._cpp)},setStage(e){dn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>dn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){dn?.renderer_releaseTarget(e)},getTargetTexture:e=>dn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>dn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){dn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){dn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){dn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){dn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>dn?dn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>dn?{drawCalls:dn.renderer_getDrawCalls(),triangles:dn.renderer_getTriangles(),sprites:dn.renderer_getSprites(),text:dn.renderer_getText(),spine:dn.renderer_getSpine?.()??0,meshes:dn.renderer_getMeshes(),culled:dn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let _n=null;function gn(e){_n=e}function yn(){_n=null}const wn={enable(){_n?.gl_enableErrorCheck(!0)},disable(){_n?.gl_enableErrorCheck(!1)},check:e=>_n?.gl_checkErrors(e)??0,diagnose(){_n?.renderer_diagnose()}},xn=new Map;function vn(e,t){xn.set(e,t)}function bn(e){xn.delete(e)}function Pn(){xn.clear()}class Sn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(mn.resize(s,r),ln.isInitialized()&&ln.getPassCount()>0&&ln.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),mn.setViewport(0,0,s,r),mn.clearBuffers(3),mn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),mn.submitSprites(t),mn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):mn.submitSpine(t),mn.flush(),this.executeDrawCallbacks(n,o),mn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;mn.setViewport(s.x,s.y,s.w,s.h),mn.setScissor(s.x,s.y,s.w,s.h,!0),mn.clearBuffers(r),mn.setScissor(0,0,0,0,!1),mn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),mn.submitSprites(t),mn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):mn.submitSpine(t),mn.flush(),this.executeDrawCallbacks(n,o),mn.end()}executeDrawCallbacks(e,t){const n=xn;if(n.size>0){Vt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Vt.end();for(const e of s)bn(e)}}}class Cn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(xe.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(xe.FixedPreUpdate),this.runSchedule(xe.FixedUpdate),this.runSchedule(xe.FixedPostUpdate),s++;s>=8&&(this.fixedAccumulator_=0),this.runSchedule(xe.PreUpdate),this.runSchedule(xe.Update),this.runSchedule(xe.PostUpdate),this.runSchedule(xe.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Be,this.resources_=new de;for(const e of Object.values(xe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Cn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(xe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(xe.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}onError(e){return this.error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(he,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(xe.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[yn,pn,on,en,We,Wt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}updateTime(e){const t=this.resources_.get(he);t.delta=e,t.elapsed+=e,t.frameCount++}}function Tn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const En=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Mn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case W.FixedWidth:return o;case W.FixedHeight:return i;case W.Expand:return Math.max(o,i);case W.Shrink:return Math.min(o,i);case W.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function An(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===H.Orthographic){if(h=r.orthoSize,o){h=Mn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=In(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Bn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Un(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(zn(u,f)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Rn=new Float32Array(16);function In(e,t,n,s,r,o){const i=Rn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const Fn=new Float32Array(16);function Bn(e,t,n,s){const r=Fn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const kn=new Float32Array(16);function Un(e,t,n){const s=kn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const $n=new Float32Array(16);function zn(e,t){const n=$n;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var Dn,Ln,Hn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Dn||(Dn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ln||(Ln={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Hn||(Hn={}));const On=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Dn.Left,verticalAlign:Ln.Top,wordWrap:!0,overflow:Hn.Visible,lineHeight:1.2}),Wn=R("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class jn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(g,g),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Hn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Hn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Ln.Top:x=u;break;case Ln.Middle:x=(p-w)/2;break;case Ln.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case Dn.Left:s=u;break;case Dn.Center:s=f/2;break;case Dn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Hn.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{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)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Dn.Left:return"left";case Dn.Center:return"center";case Dn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Nn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Vn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class Xn{build(e){z("Text",On);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new jn(t),s=e.world,r=new Map;e.addSystemToSchedule(xe.PreUpdate,be([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,On));for(const e of r.keys())s.valid(e)&&s.has(e,On)||r.delete(e);const e=s.getEntitiesWithComponents([On]);for(const t of e){const e=s.get(t,On),o=s.has(t,Wn)?s.get(t,Wn):null,i=r.get(t);if(i&&!Vn(i,e,o))continue;s.has(t,V)||s.insert(t,V,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,V);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,V,l),r.set(t,Nn(e,o))}}))}}const Yn=new Xn,qn=R("UIMask",{enabled:!0});function Gn(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Jn(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(d,f),[y,w]=m(h,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function Kn(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*_-h*m,T=d*g-f*m,E=d*y-p*m,M=h*g-f*_,A=h*y-p*_,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-P*T+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*M)*I,n[1]=(o*A-r*R-i*M)*I,n[2]=(_*S-g*P+y*b)*I,n[3]=(f*P-h*S-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+i*T)*I,n[6]=(g*v-m*S-y*x)*I,n[7]=(d*S-f*v+p*x)*I,n[8]=(a*A-l*E+u*C)*I,n[9]=(r*E-s*A-i*C)*I,n[10]=(m*P-_*v+y*w)*I,n[11]=(h*v-d*P-p*w)*I,n[12]=(l*T-a*M-c*C)*I,n[13]=(s*M-r*T+o*C)*I,n[14]=(_*x-m*b-g*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function Qn(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Zn(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function es(e,t,n,s,r,o,i){if(!e.has(t,Wn)||!e.has(t,N))return null;const a=e.get(t,Wn),l=e.get(t,N),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Jn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function ts(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([qn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,qn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,G);){const e=t.get(s,G);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=es(t,n,r,o,i,a,l);e&&(s=Gn(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=es(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class ns{build(e){if(z("UIMask",qn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ts(e.wasmModule,e.world))}}const ss=new ns,rs=R("Interactable",{enabled:!0}),os=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var is;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(is||(is={}));const as=R("Button",{state:is.Normal,transition:null});class ls{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const cs=ae(new ls,"UIEvents"),us=I("ScreenSpace");function ds(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function hs(e,t,n,s,r,o){if(!e.has(t,Wn))return;const i=e.get(t,Wn),a=ds(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,j);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,j,l),!e.has(t,J))return;const c=e.get(t,J);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&hs(e,t,a.rect,a.centerX,a.centerY,!1)}class fs{build(e){z("UIRect",Wn);const t=e.world;e.addSystemToSchedule(xe.PreUpdate,be([le(ke)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([us,Wn,j]);for(const e of o)hs(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const ps=new fs,ms=new Float32Array(16),_s=new Float32Array(16);let gs=!0,ys=1;class ws{build(e){z("Interactable",rs),z("Button",as);const t=e.world,n=new ls;e.insertResource(cs,n);let s=null,r=null;ys="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(xe.PreUpdate,be([le(Ae),le(ke)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([os]);for(const e of i){const n=t.get(e,os);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*ys,l=o.screenH-e.mouseY*ys;!function(e){let t=!1;for(let n=0;n<16;n++)if(_s[n]!==e[n]){t=!0;break}t&&(_s.set(e),gs=!0)}(o.viewProjection),gs&&(Kn(o.viewProjection,ms),gs=!1);const c=Qn(a,l,ms,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([rs,Wn,N]);let d=null,h=-1/0;for(const e of u){t.has(e,os)||t.insert(e,os);if(!t.get(e,rs).enabled)continue;const n=t.get(e,N),s=t.get(e,Wn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Zn(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,V)&&(n=t.get(e,V).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,os)){t.get(s,os).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,os).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,os);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,os)){const e=t.get(r,os);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(xe.Update,be([],()=>{const e=t.getEntitiesWithComponents([as]);for(const n of e){if(t.has(n,rs)||t.insert(n,rs,{enabled:!0}),!t.has(n,os))continue;const e=t.get(n,os),s=t.get(n,as),r=t.get(n,rs),o=s.state;if(r.enabled?e.pressed?s.state=is.Pressed:e.hovered?s.state=is.Hovered:s.state=is.Normal:s.state=is.Disabled,o!==s.state&&s.transition&&t.has(n,V)){const e=t.get(n,V),r=s.transition;switch(s.state){case is.Normal:e.color={...r.normalColor};break;case is.Hovered:e.color={...r.hoveredColor};break;case is.Pressed:e.color={...r.pressedColor};break;case is.Disabled:e.color={...r.disabledColor}}t.insert(n,V,e)}}},{name:"ButtonSystem"}))}}const xs=new ws,vs=R("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class bs{build(e){z("TextInput",vs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(g,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,vs);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(cs).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;_();const t=n.get(e,vs);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function _(){if(null!==i&&n.valid(i)&&n.has(i,vs)){const e=n.get(i,vs);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function x(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Ss(Math.max(r.width,a)),r.height=Ss(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ps(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ps(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,V);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,V,b)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,vs);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(cs).emit(i,"submit"),void _()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,vs)){const e=n.get(i,vs);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(xe.PreUpdate,be([le(cs)],e=>{const t=n.getEntitiesWithComponents([vs,rs]);for(const e of t){if(!n.has(e,os))continue;if(n.get(e,os).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([rs]);for(const t of e){if(n.has(t,vs))continue;if(!n.has(t,os))continue;if(n.get(t,os).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(xe.PreUpdate,be([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,vs)))){n.get(i,vs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,vs)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([vs,Wn]);for(const e of a){const t=n.get(e,vs);if(!t.dirty)continue;const s=n.get(e,Wn),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,V)||n.insert(e,V,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ps(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Ss(e){let t=1;for(;t<e;)t*=2;return t}const Cs=new bs;async function Ts(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Es=ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ms=ae(null,"PhysicsAPI");function As(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Rs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Is{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Es,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ts(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Y]);for(const n of t){const t=e.world.get(n,Y);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(xe.PostUpdate,be([le(he)],a=>{const l=i.getEntitiesWithComponents([te,j,N]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,te),l=i.get(r,N);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=As(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Fs(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===oe.Kinematic){const e=As(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,j);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,G)){const t=e.world.get(i,G);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const n=e.world.get(t.entity,N),s=As(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Rs(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,j,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Es,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ms,Bs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Fs(e,t,n){const s=e.world;if(s.has(n,ne)){const e=s.get(n,ne);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,se)){const e=s.get(n,se);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,re)){const e=s.get(n,re);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Bs{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Bs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function ks(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Us(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function $s(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function zs(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=ks(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===ft(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=Us(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=ks(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Is("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=ft(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=ks(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),h=await async 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(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Ne.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Ne.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=st(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,V);r&&(r.texture=n[s.data.texture]||0,e.insert(t,V,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,K);o&&(o.font=r,e.insert(t,K,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,V);n&&(n.material=r,e.insert(t,V,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Q);n&&(n.material=r,e.insert(t,Q,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Q)?c.get(o,Q):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,N)){const e=$s(c.get(o,N),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(Ct);t&&t.setAddressableManifest(a)}}class Ds{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===ft(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=ft(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Ls{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new Ds(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await zs(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([X]);for(const s of n){if(e.get(s,X).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Y]);for(const r of s){const s=e.get(r,Y);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,j,o);const i={isActive:!0,projectionType:H.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:O.ColorAndDepth};e.insert(r,X,i)}}}const Hs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=mn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:mn.getTargetTexture(n),width:e.width,height:e.height}},release(e){mn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(mn.releaseRenderTarget(e._handle),Hs.create({width:t,height:n,depth:!0})),begin(e,t){mn.begin(t,e._handle)},end(){mn.end()},getDepthTexture:e=>mn.getTargetDepthTexture(e._handle)};let Os=!1;function Ws(e){Os=e}function js(){return Os}function Ns(){return!Os}const Vs=[Yn,ss,ps,xs,Cs];function Xs(e,t){return function(e,t){const n=Cn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ot(e),Oe(e),Zt(e),rn(e),fn(e),gn(e);const r=new Sn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=An(e,s,t,r));const i=n.getResource(ke);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ke,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;mn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;mn.resize(t,n),ln.isInitialized()&&ln.getPassCount()>0&&!ln.isBypassed()&&ln.resize(t,n);const u=An(e,s,t,n);if(a(t,n,u),0===u.length)r.render({registry:{_cpp:s},viewProjection:En,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}mn.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(xe.First,l),n.addSystemToSchedule(xe.Last,c),n.addPlugin(Et),n.addPlugin(Ut),n.addPlugin(Ie),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Vs,...t})}e=f;export{Cn as App,Tt as AssetPlugin,St as AssetServer,Ct as Assets,Ze as AsyncCache,K as BitmapText,Ue as BlendMode,oe as BodyType,ne as BoxCollider,as as Button,is as ButtonState,X as Camera,Y as Canvas,re as CapsuleCollider,J as Children,se as CircleCollider,O as ClearFlags,ge as Commands,we as CommandsInstance,m as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,_ as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,qt as DataType,Vt as Draw,ye as EntityCommands,wn as GLDebug,nn as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Ae as Input,Re as InputPlugin,Me as InputState,rs as Interactable,j as LocalTransform,Ne as Material,et as MaterialLoader,fe as Mut,Z as Name,G as Parent,Bs as Physics,Es as PhysicsEvents,Is as PhysicsPlugin,ln as PostProcess,Ft as PrefabServer,Bt as Prefabs,kt as PrefabsPlugin,Ls as PreviewPlugin,H as ProjectionType,me as Query,_e as QueryInstance,Sn as RenderPipeline,un as RenderStage,Hs as RenderTexture,mn as Renderer,le as Res,ce as ResMut,te as RigidBody,W as ScaleMode,xe as Schedule,us as ScreenSpace,Qe as ShaderSources,Q as SpineAnimation,V as Sprite,Ee as SystemRunner,On as Text,Dn as TextAlign,vs as TextInput,bs as TextInputPlugin,Hn as TextOverflow,Xn as TextPlugin,jn as TextRenderer,Ln as TextVerticalAlign,he as Time,ke as UICameraInfo,ls as UIEventQueue,cs as UIEvents,os as UIInteraction,ws as UIInteractionPlugin,fs as UILayoutPlugin,qn as UIMask,ns as UIMaskPlugin,Wn as UIRect,q as Velocity,Ds as WebAssetProvider,Be as World,N as WorldTransform,Ce as addStartupSystem,Se as addSystem,Te as addSystemToSchedule,Et as assetPlugin,Pn as clearDrawCallbacks,B as clearUserComponents,S as color,ds as computeUIRectLayout,ts as createMaskProcessor,Xs as createWebApp,R as defineComponent,ae as defineResource,be as defineSystem,I as defineTag,at as findEntityByName,Tn as flushPendingSystems,mt as getAddressableType,_t as getAddressableTypeByEditorType,yt as getAllAssetExtensions,bt as getAssetMimeType,ft as getAssetTypeEntry,D as getComponent,ee as getComponentDefaults,xt as getCustomExtensions,pt as getEditorType,t as getPlatform,s as getPlatformType,F as getUserComponent,vt as getWeChatPackOptions,Ot as initDrawAPI,gn as initGLDebugAPI,Zt as initGeometryAPI,Oe as initMaterialAPI,rn as initPostProcessAPI,fn as initRendererAPI,Ie as inputPlugin,At as instantiatePrefab,Gn as intersectRects,Kn as invertMatrix4,U as isBuiltinComponent,Pt as isCustomExtension,js as isEditor,gt as isKnownAssetExtension,n as isPlatformInitialized,Ns as isRuntime,$e as isTextureRef,r as isWeChat,o as isWeb,ot as loadComponent,Ts as loadPhysicsModule,zs as loadRuntimeScene,st as loadSceneData,rt as loadSceneWithAssets,wt as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Zn as pointInWorldRect,Ut as prefabsPlugin,C as quat,z as registerComponent,nt as registerComponentAssetFields,vn as registerDrawCallback,Mt as registerEmbeddedAssets,Ke as registerMaterialCallback,Qn as screenToWorld,Ws as setEditorMode,Wt as shutdownDrawAPI,yn as shutdownGLDebugAPI,en as shutdownGeometryAPI,We as shutdownMaterialAPI,on as shutdownPostProcessAPI,pn as shutdownRendererAPI,Cs as textInputPlugin,Yn as textPlugin,xs as uiInteractionPlugin,ps as uiLayoutPlugin,ss as uiMaskPlugin,Vs as uiPlugins,bn as unregisterDrawCallback,it as updateCameraAspectRatio,v as vec2,b as vec3,P as vec4,Jn as worldRectToScreen};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,m=1080,_=100,g=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),P=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),S=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),C=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const n in e)t[n]=T(e[n]);return t}let E=0;function M(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...T(t),...e}:T(t)}}function A(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const n=A(),s=n.get(e);if(s)return s;const r=M(e,t);return n.set(e,r),k(e,t,!1),r}function I(e){const t=A(),n=t.get(e);if(n)return n;const s=M(e,{});return t.set(e,s),k(e,{},!0),s}function F(e){return A().get(e)}function B(){A().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function U(e){return!0===e._builtin}const $=new Map;function z(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function L(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,n),n}const H={Perspective:0,Orthographic:1},O={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},j=L("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),N=L("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=L("Sprite",{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),X=L("Camera",{projectionType:H.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:O.ColorAndDepth}),Y=L("Canvas",{designResolution:{x:p,y:m},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=L("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=L("Parent",{entity:0}),J=L("Children",{entities:[]}),K=L("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=L("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Z={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function ee(e){const t=D(e);return t?T(t._default):null}z("Name",Z);const te=L("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ne=L("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),se=L("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=L("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe={Static:0,Kinematic:1,Dynamic:2};let ie=0;function ae(e,t){const n=++ie;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function le(e){return{_type:"res",_resource:e}}function ce(e){return{_type:"res_mut",_resource:e}}class ue{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 de{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.value_=this.get(e),t):(t=new ue(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const he=ae({delta:0,elapsed:0,frameCount:0},"Time");function fe(e){return{_type:"mut",_component:e}}function pe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function me(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{pe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class _e{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>pe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ge(){return{_type:"commands"}}class ye{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=U(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 we{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ye(this,null);return this.spawned_.push(e),e}entity(e){return new ye(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var xe;!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"}(xe||(xe={}));let ve=0;function be(e,t,n){const s=++ve;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Se(e){Pe().push({schedule:xe.Update,system:e})}function Ce(e){Pe().push({schedule:xe.Startup,system:e})}function Te(e,t){Pe().push({schedule:e,system:t})}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof we&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new _e(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new we(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Ae=ae(new Me,"Input");class Re{constructor(e){this.target_=e??null}build(e){const n=new Me;e.insertResource(Ae,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(xe.Last,be([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Re;function Fe(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=Be(t[e]),o=Be(r);n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r})}return s}function Be(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}function Ue(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Ue(e)}}return t}class $e{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}isIterating(){return this.iterationDepth_>0}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 U(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return U(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return U(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(U(t)){if(!this.cppRegistry_)return null;const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");U(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Fe(t._name,t._default,s);if(e.length>0)throw new Error(ke(t._name,e))}const r={...t._default,...s};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Ue(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=Fe(t._name,t._default,e);if(r.length>0)throw new Error(ke(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),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),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!U(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const ze=ae({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var De;function Le(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(De||(De={}));let He=null,Oe=null,We=1;const je=new Map;function Ne(e){He=e,Oe=e.getResourceManager(),et()}function Ve(){0!==Ge&&He&&(He._free(Ge),Ge=0),je.clear(),We=1,qe=!1,Oe=null,He=null}function Xe(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ye={createShader:(e,t)=>Xe().createShader(e,t),releaseShader(e){e>0&&Xe().releaseShader(e)},create(e){const t=We++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??De.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return je.set(t,n),t},get:e=>je.get(e),setUniform(e,t,n){const s=je.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=je.get(e);return t?.blendMode??De.Normal},setDepthTest(e,t){const n=je.get(e);n&&(n.depthTest=t)},getShader(e){const t=je.get(e);return t?.shader??0},release(e){je.delete(e)},isValid:e=>je.has(e),releaseAll(){je.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??De.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=We++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return je.set(n,s),n},toAssetData(e,t){const n=je.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=je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qe=!1,Ge=0;const Je=4096,Ke=new Map;let Qe=null;function Ze(e){const t=(0===Ge&&He&&(Ge=He._malloc(Je)),Ge);if(0===t||!He)return{ptr:0,count:0};let n=0,s=0;const r=He.HEAPU8,o=He.HEAPU32,i=He.HEAPF32;for(const[a,l]of e){if(n+128>Je)break;let e=Ke.get(a);e||(Qe||(Qe=new TextEncoder),e=Qe.encode(a),Ke.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function et(){if(!He||qe)return;He.materialDataProvider=(e,t,n,s,r)=>{const o=je.get(e);if(!o)return He.HEAPU32[t>>2]=0,He.HEAPU32[n>>2]=0,He.HEAPU32[s>>2]=0,void(He.HEAPU32[r>>2]=0);He.HEAPU32[t>>2]=o.shader,He.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Ze(o.uniforms);He.HEAPU32[s>>2]=i,He.HEAPU32[r>>2]=a},qe=!0}const tt={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 nt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class st{constructor(e,t=""){this.cache_=new nt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ye.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ye.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Ye.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const rt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function ot(e,t){rt.set(e,t)}function it(e){const t=rt.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function at(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Z,{value:s.name}),!1!==s.visible)for(const n of s.components)ct(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function lt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=rt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=rt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Z,{value:n.name}),!1!==n.visible)for(const s of n.components)ct(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function ct(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=D(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function ut(e,t){const n=e.getEntitiesWithComponents([X]);for(const s of n){const n=e.get(s,X);n&&(n.aspectRatio=t,e.insert(s,X,n))}}function dt(e,t){const n=e.getEntitiesWithComponents([Z]);for(const s of n){const n=e.get(s,Z);if(n&&n.value===t)return s}return null}const ht=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],ft={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},pt=new Map,mt=new Set;for(const e of ht)for(const t of e.extensions)pt.set(t,e),mt.add(t);function _t(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function gt(e){return pt.get(_t(e))}function yt(e){return gt(e)?.editorType??"unknown"}function wt(e){return gt(e)?.addressableType??null}function xt(e){for(const t of ht)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function vt(e){return mt.has(e.toLowerCase())}function bt(){return mt}function Pt(e){return"string"==typeof e&&(!!e.includes("/")&&vt(_t(e)))}function St(){const e=[];for(const t of ht)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function Ct(){return St().map(e=>({type:"suffix",value:e}))}function Tt(e){return ft[e.toLowerCase()]}function Et(e){const t=gt(e);return t?.wechatPackInclude??!1}class Mt{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.module_=e,this.canvas_=d(g,g),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new st(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ye.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===gt(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=gt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Ye.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Ye.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const At=ae(null,"Assets");class Rt{build(e){const t=e.wasmModule;t?e.insertResource(At,new Mt(t)):console.warn("AssetPlugin: No WASM module available")}}const It=new Rt;class Ft{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Bt(e,t){const n=e.getResource(At);n&&n.registerEmbeddedAssets(t)}async function kt(e,t,n){const{entities:s,rootId:r}=await Ut(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await lt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Ut(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ut(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};$t(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function $t(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class zt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return kt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Dt=ae(null,"Prefabs");class Lt{constructor(){this.name="PrefabsPlugin",this.dependencies=[At]}build(e){const t=e.getResource(At);e.insertResource(Dt,new zt(e.world,t))}}const Ht=new Lt;let Ot=null,Wt=0,jt=0,Nt=0;const Vt=new Float32Array(256);function Xt(e){Ot=e,Wt=Ot._malloc(64),jt=Ot._malloc(64),Nt=Ot._malloc(1024)}function Yt(){Ot&&(Wt&&(Ot._free(Wt),Wt=0),jt&&(Ot._free(jt),jt=0),Nt&&(Ot._free(Nt),Nt=0)),Ot=null}function qt(){if(!Ot)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ot}const Gt={r:1,g:1,b:1,a:1},Jt={begin(e){const t=qt();t.HEAPF32.set(e,Wt/4),t.draw_begin(Wt)},end(){qt().draw_end()},line(e,t,n,s=1){qt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){qt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){qt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){qt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){qt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Gt){qt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Gt){qt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){qt().draw_setLayer(e)},setDepth(e){qt().draw_setDepth(e)},getDrawCallCount:()=>Ot?Ot.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ot?Ot.draw_getPrimitiveCount():0,setBlendMode(e){qt().draw_setBlendMode(e)},setDepthTest(e){qt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=qt();s.HEAPF32.set(n,jt/4),s.draw_mesh(e,t,jt)},drawMeshWithMaterial(e,t,n){const s=qt(),r=Ye.get(t);if(!r)return;if(Jt.setBlendMode(r.blendMode),Jt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Jt.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,jt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Qt(t);if(!(s<0)){if(Le(n))Vt[o++]=10,Vt[o++]=s,Vt[o++]=n.slot??e++,Vt[o++]=n.textureId;else if("number"==typeof n)Vt[o++]=1,Vt[o++]=s,Vt[o++]=n;else if(Array.isArray(n)){Vt[o++]=n.length,Vt[o++]=s;for(let e=0;e<n.length;e++)Vt[o++]=n[e]}else"w"in n?(Vt[o++]=4,Vt[o++]=s,Vt[o++]=n.x,Vt[o++]=n.y,Vt[o++]=n.z,Vt[o++]=n.w):"z"in n?(Vt[o++]=3,Vt[o++]=s,Vt[o++]=n.x,Vt[o++]=n.y,Vt[o++]=n.z):(Vt[o++]=2,Vt[o++]=s,Vt[o++]=n.x,Vt[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Vt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Nt/4),s.draw_meshWithUniforms(e,r.shader,jt,Nt,o)):s.draw_mesh(e,r.shader,jt)}},Kt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Qt(e){return Kt[e]??-1}var Zt;!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"}(Zt||(Zt={}));let en=null,tn=0,nn=0,sn=0;function rn(e){en=e,tn=en._malloc(262144),nn=en._malloc(65536),sn=en._malloc(256)}function on(){en&&(tn&&en._free(tn),nn&&en._free(nn),sn&&en._free(sn),tn=0,nn=0,sn=0),en=null}function an(){if(!en)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return en}const ln={create(e){const t=an(),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,tn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,sn,r).set(o),t.geometry_init(n,tn,s,sn,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,nn,s).set(e.indices),t.geometry_setIndices16(n,nn,s)}else{new Uint32Array(t.HEAPU8.buffer,nn,s).set(e.indices),t.geometry_setIndices32(n,nn,s)}}return n},updateVertices(e,t,n=0){const s=an(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,tn/4),s.geometry_updateVertices(e,tn,r,n)},release(e){e>0&&an().geometry_release(e)},isValid:e=>!(!en||e<=0)&&en.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return ln.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:Zt.Float2},{name:"a_texCoord",type:Zt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return ln.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Zt.Float2},{name:"a_texCoord",type:Zt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return ln.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Zt.Float2},{name:"a_texCoord",type:Zt.Float2}],indices:new Uint16Array(i)})}};let cn=null;function un(e){cn=e}function dn(){cn&&fn.isInitialized()&&fn.shutdown(),cn=null}function hn(){if(!cn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return cn}const fn={init:(e,t)=>hn().postprocess_init(e,t),shutdown(){hn().postprocess_shutdown()},resize(e,t){hn().postprocess_resize(e,t)},addPass:(e,t)=>hn().postprocess_addPass(e,t),removePass(e){hn().postprocess_removePass(e)},setEnabled(e,t){hn().postprocess_setPassEnabled(e,t)},isEnabled:e=>hn().postprocess_isPassEnabled(e),setUniform(e,t,n){hn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){hn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){hn().postprocess_begin()},end(){hn().postprocess_end()},getPassCount:()=>hn().postprocess_getPassCount(),isInitialized:()=>!!cn&&cn.postprocess_isInitialized(),setBypass(e){hn().postprocess_setBypass(e)},isBypassed:()=>!cn||cn.postprocess_isBypassed(),createBlur:()=>Ye.createShader(pn,"#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:()=>Ye.createShader(pn,"#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:()=>Ye.createShader(pn,"#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:()=>Ye.createShader(pn,"#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")},pn="#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 mn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(mn||(mn={}));let _n=null,gn=0;function yn(e){_n=e,gn=_n._malloc(64)}function wn(){_n&&gn&&(_n._free(gn),gn=0),_n=null}const xn={init(e,t){_n?.renderer_init(e,t)},resize(e,t){_n?.renderer_resize(e,t)},begin(e,t){_n&&gn&&(_n.HEAPF32.set(e,gn/4),_n.renderer_begin(gn,t??0))},flush(){_n?.renderer_flush()},end(){_n?.renderer_end()},submitSprites(e){_n&&_n.renderer_submitSprites(e._cpp)},submitBitmapText(e){_n&&_n.renderer_submitBitmapText(e._cpp)},submitSpine(e){_n&&_n.renderer_submitSpine?.(e._cpp)},setStage(e){_n?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>_n?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){_n?.renderer_releaseTarget(e)},getTargetTexture:e=>_n?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>_n?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){_n?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){_n?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){_n?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){_n?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>_n?_n.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>_n?{drawCalls:_n.renderer_getDrawCalls(),triangles:_n.renderer_getTriangles(),sprites:_n.renderer_getSprites(),text:_n.renderer_getText(),spine:_n.renderer_getSpine?.()??0,meshes:_n.renderer_getMeshes(),culled:_n.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let vn=null;function bn(e){vn=e}function Pn(){vn=null}const Sn={enable(){vn?.gl_enableErrorCheck(!0)},disable(){vn?.gl_enableErrorCheck(!1)},check:e=>vn?.gl_checkErrors(e)??0,diagnose(){vn?.renderer_diagnose()}},Cn=new Map;function Tn(e,t){Cn.set(e,t)}function En(e){Cn.delete(e)}function Mn(){Cn.clear()}class An{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(xn.resize(s,r),fn.isInitialized()&&fn.getPassCount()>0&&fn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),xn.setViewport(0,0,s,r),xn.clearBuffers(3),xn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),xn.submitSprites(t),xn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):xn.submitSpine(t),xn.flush(),this.executeDrawCallbacks(n,o),xn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;xn.setViewport(s.x,s.y,s.w,s.h),xn.setScissor(s.x,s.y,s.w,s.h,!0),xn.clearBuffers(r),xn.setScissor(0,0,0,0,!1),xn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),xn.submitSprites(t),xn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):xn.submitSpine(t),xn.flush(),this.executeDrawCallbacks(n,o),xn.end()}executeDrawCallbacks(e,t){const n=Cn;if(n.size>0){Jt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Jt.end();for(const e of s)En(e)}}}class Rn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(xe.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(xe.FixedPreUpdate),this.runSchedule(xe.FixedUpdate),this.runSchedule(xe.FixedPostUpdate),s++;s>=8&&(this.fixedAccumulator_=0),this.runSchedule(xe.PreUpdate),this.runSchedule(xe.Update),this.runSchedule(xe.PostUpdate),this.runSchedule(xe.Last),requestAnimationFrame(this.mainLoop)},this.world_=new $e,this.resources_=new de;for(const e of Object.values(xe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Rn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(xe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(xe.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}onError(e){return this.error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(he,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(xe.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[Pn,wn,dn,on,Ve,Yt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}}updateTime(e){const t=this.resources_.get(he);t.delta=e,t.elapsed+=e,t.frameCount++}}function In(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 Fn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Bn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case W.FixedWidth:return o;case W.FixedHeight:return i;case W.Expand:return Math.max(o,i);case W.Shrink:return Math.min(o,i);case W.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function kn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===H.Orthographic){if(h=r.orthoSize,o){h=Bn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=$n(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Dn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Hn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(Wn(u,f)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Un=new Float32Array(16);function $n(e,t,n,s,r,o){const i=Un;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const zn=new Float32Array(16);function Dn(e,t,n,s){const r=zn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Ln=new Float32Array(16);function Hn(e,t,n){const s=Ln;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const On=new Float32Array(16);function Wn(e,t){const n=On;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var jn,Nn,Vn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(jn||(jn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Nn||(Nn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Vn||(Vn={}));const Xn=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:jn.Left,verticalAlign:Nn.Top,wordWrap:!0,overflow:Vn.Visible,lineHeight:1.2}),Yn=R("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class qn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(g,g),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Vn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Vn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Nn.Top:x=u;break;case Nn.Middle:x=(p-w)/2;break;case Nn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case jn.Left:s=u;break;case jn.Center:s=f/2;break;case jn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Vn.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{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)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case jn.Left:return"left";case jn.Center:return"center";case jn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Gn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Jn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class Kn{build(e){z("Text",Xn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new qn(t),s=e.world,r=new Map;e.addSystemToSchedule(xe.PreUpdate,be([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Xn));for(const e of r.keys())s.valid(e)&&s.has(e,Xn)||r.delete(e);const e=s.getEntitiesWithComponents([Xn]);for(const t of e){const e=s.get(t,Xn),o=s.has(t,Yn)?s.get(t,Yn):null,i=r.get(t);if(i&&!Jn(i,e,o))continue;s.has(t,V)||s.insert(t,V,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,V);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,V,l),r.set(t,Gn(e,o))}}))}}const Qn=new Kn,Zn=R("UIMask",{enabled:!0});function es(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ts(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(d,f),[y,w]=m(h,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function ns(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*_-h*m,T=d*g-f*m,E=d*y-p*m,M=h*g-f*_,A=h*y-p*_,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-P*T+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*M)*I,n[1]=(o*A-r*R-i*M)*I,n[2]=(_*S-g*P+y*b)*I,n[3]=(f*P-h*S-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+i*T)*I,n[6]=(g*v-m*S-y*x)*I,n[7]=(d*S-f*v+p*x)*I,n[8]=(a*A-l*E+u*C)*I,n[9]=(r*E-s*A-i*C)*I,n[10]=(m*P-_*v+y*w)*I,n[11]=(h*v-d*P-p*w)*I,n[12]=(l*T-a*M-c*C)*I,n[13]=(s*M-r*T+o*C)*I,n[14]=(_*x-m*b-g*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function ss(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function rs(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function os(e,t,n,s,r,o,i){if(!e.has(t,Yn)||!e.has(t,N))return null;const a=e.get(t,Yn),l=e.get(t,N),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ts(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function is(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Zn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Zn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,G);){const e=t.get(s,G);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=os(t,n,r,o,i,a,l);e&&(s=es(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=os(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class as{build(e){if(z("UIMask",Zn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(is(e.wasmModule,e.world))}}const ls=new as,cs=R("Interactable",{enabled:!0}),us=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ds;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(ds||(ds={}));const hs=R("Button",{state:ds.Normal,transition:null});class fs{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const ps=ae(new fs,"UIEvents"),ms=I("ScreenSpace");function _s(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function gs(e,t,n,s,r,o){if(!e.has(t,Yn))return;const i=e.get(t,Yn),a=_s(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,j);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,j,l),!e.has(t,J))return;const c=e.get(t,J);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&gs(e,t,a.rect,a.centerX,a.centerY,!1)}class ys{build(e){z("UIRect",Yn);const t=e.world;e.addSystemToSchedule(xe.PreUpdate,be([le(ze)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([ms,Yn,j]);for(const e of o)gs(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const ws=new ys,xs=new Float32Array(16),vs=new Float32Array(16);let bs=!0,Ps=1;class Ss{build(e){z("Interactable",cs),z("Button",hs);const t=e.world,n=new fs;e.insertResource(ps,n);let s=null,r=null;Ps="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(xe.PreUpdate,be([le(Ae),le(ze)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([us]);for(const e of i){const n=t.get(e,us);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Ps,l=o.screenH-e.mouseY*Ps;!function(e){let t=!1;for(let n=0;n<16;n++)if(vs[n]!==e[n]){t=!0;break}t&&(vs.set(e),bs=!0)}(o.viewProjection),bs&&(ns(o.viewProjection,xs),bs=!1);const c=ss(a,l,xs,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([cs,Yn,N]);let d=null,h=-1/0;for(const e of u){t.has(e,us)||t.insert(e,us);if(!t.get(e,cs).enabled)continue;const n=t.get(e,N),s=t.get(e,Yn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(rs(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,V)&&(n=t.get(e,V).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,us)){t.get(s,us).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,us).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,us);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,us)){const e=t.get(r,us);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(xe.Update,be([],()=>{const e=t.getEntitiesWithComponents([hs]);for(const n of e){if(t.has(n,cs)||t.insert(n,cs,{enabled:!0}),!t.has(n,us))continue;const e=t.get(n,us),s=t.get(n,hs),r=t.get(n,cs),o=s.state;if(r.enabled?e.pressed?s.state=ds.Pressed:e.hovered?s.state=ds.Hovered:s.state=ds.Normal:s.state=ds.Disabled,o!==s.state&&s.transition&&t.has(n,V)){const e=t.get(n,V),r=s.transition;switch(s.state){case ds.Normal:e.color={...r.normalColor};break;case ds.Hovered:e.color={...r.hoveredColor};break;case ds.Pressed:e.color={...r.pressedColor};break;case ds.Disabled:e.color={...r.disabledColor}}t.insert(n,V,e)}}},{name:"ButtonSystem"}))}}const Cs=new Ss,Ts=R("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Es{build(e){z("TextInput",Ts);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(g,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,Ts);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(ps).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;_();const t=n.get(e,Ts);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function _(){if(null!==i&&n.valid(i)&&n.has(i,Ts)){const e=n.get(i,Ts);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function x(e,i,a,c){(r.width<a||r.height<c)&&(r.width=As(Math.max(r.width,a)),r.height=As(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ms(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ms(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,V);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,V,b)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,Ts);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ps).emit(i,"submit"),void _()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,Ts)){const e=n.get(i,Ts);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(xe.PreUpdate,be([le(ps)],e=>{const t=n.getEntitiesWithComponents([Ts,cs]);for(const e of t){if(!n.has(e,us))continue;if(n.get(e,us).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([cs]);for(const t of e){if(n.has(t,Ts))continue;if(!n.has(t,us))continue;if(n.get(t,us).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(xe.PreUpdate,be([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Ts)))){n.get(i,Ts).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Ts)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Ts,Yn]);for(const e of a){const t=n.get(e,Ts);if(!t.dirty)continue;const s=n.get(e,Yn),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,V)||n.insert(e,V,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ms(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function As(e){let t=1;for(;t<e;)t*=2;return t}const Rs=new Es;async function Is(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Fs=ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Bs=ae(null,"PhysicsAPI");function ks(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Us(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $s{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(Fs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Is(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Y]);for(const n of t){const t=e.world.get(n,Y);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(xe.PostUpdate,be([le(he)],a=>{const l=i.getEntitiesWithComponents([te,j,N]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,te),l=i.get(r,N);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=ks(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),zs(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===oe.Kinematic){const e=ks(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,j);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,G)){const t=e.world.get(i,G);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const n=e.world.get(t.entity,N),s=ks(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Us(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,j,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Fs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Bs,Ds._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function zs(e,t,n){const s=e.world;if(s.has(n,ne)){const e=s.get(n,ne);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,se)){const e=s.get(n,se);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,re)){const e=s.get(n,re);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 Ds{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Ds.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Ls(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Hs(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Os(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ws(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Ls(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===gt(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=Hs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Ls(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new $s("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=gt(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Ls(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),h=await async 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(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Ye.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Ye.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=at(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,V);r&&(r.texture=n[s.data.texture]||0,e.insert(t,V,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,K);o&&(o.font=r,e.insert(t,K,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,V);n&&(n.material=r,e.insert(t,V,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Q);n&&(n.material=r,e.insert(t,Q,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Q)?c.get(o,Q):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,N)){const e=Os(c.get(o,N),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(At);t&&t.setAddressableManifest(a)}}class js{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===gt(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=gt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Ns{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.currentScene_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene(),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new js(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await Ws(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([X]);for(const s of n){if(e.get(s,X).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Y]);for(const r of s){const s=e.get(r,Y);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,j,o);const i={isActive:!0,projectionType:H.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:O.ColorAndDepth};e.insert(r,X,i)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new js(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Ws(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera(),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Vs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=xn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:xn.getTargetTexture(n),width:e.width,height:e.height}},release(e){xn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(xn.releaseRenderTarget(e._handle),Vs.create({width:t,height:n,depth:!0})),begin(e,t){xn.begin(t,e._handle)},end(){xn.end()},getDepthTexture:e=>xn.getTargetDepthTexture(e._handle)};let Xs=!1;function Ys(e){Xs=e}function qs(){return Xs}function Gs(){return!Xs}var Js;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Js||(Js={}));class Ks{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Js[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Js.Debug:console.debug(t,n);break;case Js.Info:console.log(t,n);break;case Js.Warn:console.warn(t,n);break;case Js.Error:console.error(t,n)}}}class Qs{constructor(){this.handlers_=[],this.minLevel_=Js.Info,this.addHandler(new Ks)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Js.Debug,e,t,n)}info(e,t,n){this.log(Js.Info,e,t,n)}warn(e,t,n){this.log(Js.Warn,e,t,n)}error(e,t,n){this.log(Js.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Zs=new Qs;function er(){return Zs}function tr(e){Zs.setMinLevel(e)}function nr(e,t,n){Zs.debug(e,t,n)}function sr(e,t,n){Zs.info(e,t,n)}function rr(e,t,n){Zs.warn(e,t,n)}function or(e,t,n){Zs.error(e,t,n)}const ir=[Qn,ls,ws,Cs,Rs];function ar(e,t){return function(e,t){const n=Rn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Xt(e),Ne(e),rn(e),un(e),yn(e),bn(e);const r=new An;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=kn(e,s,t,r));const i=n.getResource(ze);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ze,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;xn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;xn.resize(t,n),fn.isInitialized()&&fn.getPassCount()>0&&!fn.isBypassed()&&fn.resize(t,n);const u=kn(e,s,t,n);if(a(t,n,u),0===u.length)r.render({registry:{_cpp:s},viewProjection:Fn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}xn.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(xe.First,l),n.addSystemToSchedule(xe.Last,c),n.addPlugin(It),n.addPlugin(Ht),n.addPlugin(Ie),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ir,...t})}e=f;export{Rn as App,Rt as AssetPlugin,Ft as AssetRefCounter,Mt as AssetServer,At as Assets,nt as AsyncCache,K as BitmapText,De as BlendMode,oe as BodyType,ne as BoxCollider,hs as Button,ds as ButtonState,X as Camera,Y as Canvas,re as CapsuleCollider,J as Children,se as CircleCollider,O as ClearFlags,ge as Commands,we as CommandsInstance,m as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,_ as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,Zt as DataType,Jt as Draw,ye as EntityCommands,Sn as GLDebug,ln as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Ae as Input,Re as InputPlugin,Me as InputState,cs as Interactable,j as LocalTransform,Js as LogLevel,Qs as Logger,Ye as Material,st as MaterialLoader,fe as Mut,Z as Name,G as Parent,Ds as Physics,Fs as PhysicsEvents,$s as PhysicsPlugin,fn as PostProcess,zt as PrefabServer,Dt as Prefabs,Lt as PrefabsPlugin,Ns as PreviewPlugin,H as ProjectionType,me as Query,_e as QueryInstance,An as RenderPipeline,mn as RenderStage,Vs as RenderTexture,xn as Renderer,le as Res,ce as ResMut,te as RigidBody,W as ScaleMode,xe as Schedule,ms as ScreenSpace,tt as ShaderSources,Q as SpineAnimation,V as Sprite,Ee as SystemRunner,Xn as Text,jn as TextAlign,Ts as TextInput,Es as TextInputPlugin,Vn as TextOverflow,Kn as TextPlugin,qn as TextRenderer,Nn as TextVerticalAlign,he as Time,ze as UICameraInfo,fs as UIEventQueue,ps as UIEvents,us as UIInteraction,Ss as UIInteractionPlugin,ys as UILayoutPlugin,Zn as UIMask,as as UIMaskPlugin,Yn as UIRect,q as Velocity,js as WebAssetProvider,$e as World,N as WorldTransform,Ce as addStartupSystem,Se as addSystem,Te as addSystemToSchedule,It as assetPlugin,Mn as clearDrawCallbacks,B as clearUserComponents,S as color,_s as computeUIRectLayout,is as createMaskProcessor,ar as createWebApp,nr as debug,R as defineComponent,ae as defineResource,be as defineSystem,I as defineTag,or as error,dt as findEntityByName,In as flushPendingSystems,wt as getAddressableType,xt as getAddressableTypeByEditorType,bt as getAllAssetExtensions,Tt as getAssetMimeType,gt as getAssetTypeEntry,D as getComponent,it as getComponentAssetFields,ee as getComponentDefaults,St as getCustomExtensions,yt as getEditorType,er as getLogger,t as getPlatform,s as getPlatformType,F as getUserComponent,Ct as getWeChatPackOptions,sr as info,Xt as initDrawAPI,bn as initGLDebugAPI,rn as initGeometryAPI,Ne as initMaterialAPI,un as initPostProcessAPI,yn as initRendererAPI,Ie as inputPlugin,kt as instantiatePrefab,es as intersectRects,ns as invertMatrix4,U as isBuiltinComponent,Et as isCustomExtension,qs as isEditor,vt as isKnownAssetExtension,n as isPlatformInitialized,Gs as isRuntime,Le as isTextureRef,r as isWeChat,o as isWeb,ct as loadComponent,Is as loadPhysicsModule,Ws as loadRuntimeScene,at as loadSceneData,lt as loadSceneWithAssets,Pt as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,rs as pointInWorldRect,Ht as prefabsPlugin,C as quat,z as registerComponent,ot as registerComponentAssetFields,Tn as registerDrawCallback,Bt as registerEmbeddedAssets,et as registerMaterialCallback,ss as screenToWorld,Ys as setEditorMode,tr as setLogLevel,Yt as shutdownDrawAPI,Pn as shutdownGLDebugAPI,on as shutdownGeometryAPI,Ve as shutdownMaterialAPI,dn as shutdownPostProcessAPI,wn as shutdownRendererAPI,Rs as textInputPlugin,Qn as textPlugin,Cs as uiInteractionPlugin,ws as uiLayoutPlugin,ls as uiMaskPlugin,ir as uiPlugins,En as unregisterDrawCallback,ut as updateCameraAspectRatio,v as vec2,b as vec3,P as vec4,rr as warn,ts as worldRectToScreen};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 34eee6b00..d2139d60a 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -461,6 +461,7 @@ declare class World {
private worldVersion_;
private queryCache_;
private builtinMethodCache_;
+ private iterationDepth_;
connectCpp(cppRegistry: CppRegistry): void;
disconnectCpp(): void;
get hasCpp(): boolean;
@@ -469,6 +470,9 @@ declare class World {
valid(entity: Entity): boolean;
entityCount(): number;
getWorldVersion(): number;
+ beginIteration(): void;
+ endIteration(): void;
+ isIterating(): boolean;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
removeParent(entity: Entity): void;
@@ -618,7 +622,10 @@ declare class App {
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
- addSystemToSchedule(schedule: Schedule, system: SystemDef): this;
+ addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
+ runBefore?: string[];
+ runAfter?: string[];
+ }): this;
addSystem(system: SystemDef): this;
addStartupSystem(system: SystemDef): this;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
@@ -640,6 +647,7 @@ declare class App {
run(): void;
private mainLoop;
quit(): void;
+ private sortSystems;
private runSchedule;
private updateTime;
}
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 6bf45a8f8..111692d2d 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -416,6 +416,7 @@ declare class World {
private worldVersion_;
private queryCache_;
private builtinMethodCache_;
+ private iterationDepth_;
connectCpp(cppRegistry: CppRegistry): void;
disconnectCpp(): void;
get hasCpp(): boolean;
@@ -424,6 +425,9 @@ declare class World {
valid(entity: Entity): boolean;
entityCount(): number;
getWorldVersion(): number;
+ beginIteration(): void;
+ endIteration(): void;
+ isIterating(): boolean;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
removeParent(entity: Entity): void;
@@ -573,7 +577,10 @@ declare class App {
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
- addSystemToSchedule(schedule: Schedule, system: SystemDef): this;
+ addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
+ runBefore?: string[];
+ runAfter?: string[];
+ }): this;
addSystem(system: SystemDef): this;
addStartupSystem(system: SystemDef): this;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
@@ -595,6 +602,7 @@ declare class App {
run(): void;
private mainLoop;
quit(): void;
+ private sortSystems;
private runSchedule;
private updateTime;
}
diff --git a/desktop/public/wasm/esengine.js b/desktop/public/wasm/esengine.js
index 25c82406c..ee2ead764 100644
--- a/desktop/public/wasm/esengine.js
+++ b/desktop/public/wasm/esengine.js
@@ -101,37 +101,37 @@ c);return c};h.FS_preloadFile=ob;h.FS_unlink=(...a)=>C.unlink(...a);h.FS_createP
var vc,Ed,U,Xd,Nd,Ld,Md,ya,S,Yd={ba:function(a,b,c){Ja=c;try{var d=N(a);switch(b){case 0:var e=A();if(0>e)break;for(;C.streams[e];)e++;return yb(d,e).fd;case 1:case 2:return 0;case 3:return d.flags;case 4:return e=A(),d.flags|=e,0;case 12:return e=A(),u[e+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(f){if("undefined"==typeof C||"ErrnoError"!==f.name)throw f;return-f.Cb}},ua:function(a,b,c){Ja=c;try{var d=N(a);switch(b){case 21509:return d.tty?0:-59;case 21505:if(!d.tty)return-59;if(d.tty.Lb.Dd){a=
[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];var e=A();w[e>>2]=25856;w[e+4>>2]=5;w[e+8>>2]=191;w[e+12>>2]=35387;for(var f=0;32>f;f++)q[e+f+17]=a[f]||0}return 0;case 21510:case 21511:case 21512:return d.tty?0:-59;case 21506:case 21507:case 21508:if(!d.tty)return-59;if(d.tty.Lb.Ed)for(e=A(),a=[],f=0;32>f;f++)a.push(q[e+f+17]);return 0;case 21519:if(!d.tty)return-59;e=A();return w[e>>2]=0;case 21520:return d.tty?-28:-59;case 21537:case 21531:return e=A(),C.vc(d,b,e);case 21523:if(!d.tty)return-59;
d.tty.Lb.Fd&&(f=[24,80],e=A(),u[e>>1]=f[0],u[e+2>>1]=f[1]);return 0;case 21524:return d.tty?0:-59;case 21515:return d.tty?0:-59;default:return-28}}catch(g){if("undefined"==typeof C||"ErrnoError"!==g.name)throw g;return-g.Cb}},va:function(a,b,c,d){Ja=d;try{b=b?D(t,b):"";var e=b;if("/"===e.charAt(0))b=e;else{var f=-100===a?C.cwd():N(a).path;if(0==e.length)throw new C.ib(44);b=f+"/"+e}var g=d?A():0;return C.open(b,c,g).fd}catch(k){if("undefined"==typeof C||"ErrnoError"!==k.name)throw k;return-k.Cb}},
-za:()=>y(""),g:a=>{var b=Jb[a];delete Jb[a];var c=b.Ec,d=b.Ib,e=b.Pc,f=e.map(g=>g.Ad).concat(e.map(g=>g.Pd));Rb([a],f,g=>{var k={},m,l;for([m,l]of e.entries()){const p=g[m],r=l.ac,v=l.zd,z=g[m+e.length],B=l.Od,F=l.Qd;k[l.td]={read:J=>p.pb(r(v,J)),write:(J,P)=>{var K=[];B(F,J,z.tb(K,P));Kb(K)},optional:p.optional}}return[{name:b.name,pb:p=>{var r={},v;for(v in k)r[v]=k[v].read(p);d(p);return r},tb:(p,r)=>{for(var v in k)if(!(v in r||k[v].optional))throw new TypeError(`Missing field: "${v}"`);var z=
-c();for(v in k)k[v].write(z,r[v]);null!==p&&p.push(d,z);return z},zb:Lb,ub:d}]})},na:(a,b,c,d,e)=>{b=Q(b);d=0n===d;let f=g=>g;if(d){const g=8*c;f=k=>BigInt.asUintN(g,k);e=f(e)}O(a,{name:b,pb:f,tb:(g,k)=>{"number"==typeof k&&(k=BigInt(k));return k},zb:Ub(b,c,!d),ub:null})},Qa:(a,b,c,d)=>{b=Q(b);O(a,{name:b,pb:function(e){return!!e},tb:function(e,f){return f?c:d},zb:function(e){return this.pb(t[e])},ub:null})},oa:(a,b,c,d,e,f,g,k,m,l,p,r,v)=>{p=Q(p);f=T(e,f);k&&=T(g,k);l&&=T(m,l);v=T(r,v);var z=ec(p);
+za:()=>y(""),h:a=>{var b=Jb[a];delete Jb[a];var c=b.Ec,d=b.Ib,e=b.Pc,f=e.map(g=>g.Ad).concat(e.map(g=>g.Pd));Rb([a],f,g=>{var k={},m,l;for([m,l]of e.entries()){const p=g[m],r=l.ac,v=l.zd,z=g[m+e.length],B=l.Od,F=l.Qd;k[l.td]={read:J=>p.pb(r(v,J)),write:(J,P)=>{var K=[];B(F,J,z.tb(K,P));Kb(K)},optional:p.optional}}return[{name:b.name,pb:p=>{var r={},v;for(v in k)r[v]=k[v].read(p);d(p);return r},tb:(p,r)=>{for(var v in k)if(!(v in r||k[v].optional))throw new TypeError(`Missing field: "${v}"`);var z=
+c();for(v in k)k[v].write(z,r[v]);null!==p&&p.push(d,z);return z},zb:Lb,ub:d}]})},qa:(a,b,c,d,e)=>{b=Q(b);d=0n===d;let f=g=>g;if(d){const g=8*c;f=k=>BigInt.asUintN(g,k);e=f(e)}O(a,{name:b,pb:f,tb:(g,k)=>{"number"==typeof k&&(k=BigInt(k));return k},zb:Ub(b,c,!d),ub:null})},Qa:(a,b,c,d)=>{b=Q(b);O(a,{name:b,pb:function(e){return!!e},tb:function(e,f){return f?c:d},zb:function(e){return this.pb(t[e])},ub:null})},ia:(a,b,c,d,e,f,g,k,m,l,p,r,v)=>{p=Q(p);f=T(e,f);k&&=T(g,k);l&&=T(m,l);v=T(r,v);var z=ec(p);
dc(z,function(){xc(`Cannot construct ${p} due to unbound types`,[d])});Rb([a,b,c],d?[d]:[],B=>{B=B[0];if(d){var F=B.ob;var J=F.Ub}else J=$b.prototype;B=ac(p,function(...Pb){if(Object.getPrototypeOf(this)!==P)throw new R(`Use 'new' to construct ${p}`);if(void 0===K.Pb)throw new R(`${p} has no accessible constructor`);var Zc=K.Pb[Pb.length];if(void 0===Zc)throw new R(`Tried to invoke ctor of ${p} with invalid number of parameters (${Pb.length}) - expected (${Object.keys(K.Pb).toString()}) parameters instead!`);
-return Zc.apply(this,Pb)});var P=Object.create(J,{constructor:{value:B}});B.prototype=P;var K=new fc(p,B,P,v,F,f,k,l);if(K.xb){var G;(G=K.xb).Gc??(G.Gc=[]);K.xb.Gc.push(K)}F=new qc(p,K,!0,!1,!1);G=new qc(p+"*",K,!1,!1,!1);J=new qc(p+" const*",K,!1,!0,!1);bc[a]={pointerType:G,od:J};rc(z,B);return[F,G,J]})},Na:(a,b,c,d,e,f)=>{var g=yc(b,c);e=T(d,e);Rb([],[a],k=>{k=k[0];var m=`constructor ${k.name}`;void 0===k.ob.Pb&&(k.ob.Pb=[]);if(void 0!==k.ob.Pb[b-1])throw new R(`Cannot register multiple constructors with identical number of parameters (${b-
+return Zc.apply(this,Pb)});var P=Object.create(J,{constructor:{value:B}});B.prototype=P;var K=new fc(p,B,P,v,F,f,k,l);if(K.xb){var G;(G=K.xb).Gc??(G.Gc=[]);K.xb.Gc.push(K)}F=new qc(p,K,!0,!1,!1);G=new qc(p+"*",K,!1,!1,!1);J=new qc(p+" const*",K,!1,!0,!1);bc[a]={pointerType:G,od:J};rc(z,B);return[F,G,J]})},Ma:(a,b,c,d,e,f)=>{var g=yc(b,c);e=T(d,e);Rb([],[a],k=>{k=k[0];var m=`constructor ${k.name}`;void 0===k.ob.Pb&&(k.ob.Pb=[]);if(void 0!==k.ob.Pb[b-1])throw new R(`Cannot register multiple constructors with identical number of parameters (${b-
1}) for class '${k.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);k.ob.Pb[b-1]=()=>{xc(`Cannot construct ${k.name} due to unbound types`,g)};Rb([],g,l=>{l.splice(1,0,null);k.ob.Pb[b-1]=Ac(m,l,null,e,f);return[]});return[]})},c:(a,b,c,d,e,f,g,k,m)=>{var l=yc(c,d);b=Q(b);b=Bc(b);f=T(e,f);Rb([],[a],p=>{function r(){xc(`Cannot call ${v} due to unbound types`,l)}p=p[0];var v=`${p.name}.${b}`;b.startsWith("@@")&&(b=Symbol[b.substring(2)]);k&&p.ob.Md.push(b);
var z=p.ob.Ub,B=z[b];void 0===B||void 0===B.vb&&B.className!==p.name&&B.Ob===c-2?(r.Ob=c-2,r.className=p.name,z[b]=r):(cc(z,b,v),z[b].vb[c-2]=r);Rb([],l,F=>{F=Ac(v,F,p,f,g,m);void 0===z[b].vb?(F.Ob=c-2,z[b]=F):z[b].vb[c-2]=F;return[]});return[]})},Oa:a=>O(a,Gc),S:(a,b,c,d,e)=>{b=Q(b);e=0===e?"object":1===e?"number":"string";switch(e){case "object":function g(){}g.values={};O(a,{name:b,constructor:g,valueType:e,pb:function(k){return this.constructor.values[k]},tb:(k,m)=>m.value,zb:Hc(b,c,d),ub:null});
dc(b,g);break;case "number":var f={};O(a,{name:b,zc:f,valueType:e,pb:k=>k,tb:(k,m)=>m,zb:Hc(b,c,d),ub:null});dc(b,f);delete h[b].Ob;break;case "string":f={},O(a,{name:b,gd:{},ad:{},zc:f,valueType:e,pb:function(k){return this.ad[k]},tb:function(k,m){return this.gd[m]},zb:Hc(b,c,d),ub:null}),dc(b,f),delete h[b].Ob}},m:(a,b,c)=>{var d=Ic(a,"enum");b=Q(b);switch(d.valueType){case "object":a=d.constructor;d=Object.create(d.constructor.prototype,{value:{value:c},constructor:{value:ac(`${d.name}_${b}`,function(){})}});
-a.values[c]=d;a[b]=d;break;case "number":d.zc[b]=c;break;case "string":d.gd[b]=c,d.ad[c]=b,d.zc[b]=b}},ma:(a,b,c)=>{b=Q(b);O(a,{name:b,pb:d=>d,tb:(d,e)=>e,zb:Jc(b,c),ub:null})},b:(a,b,c,d,e,f,g)=>{var k=yc(b,c);a=Q(a);a=Bc(a);e=T(d,e);dc(a,function(){xc(`Cannot call ${a} due to unbound types`,k)},b-1);Rb([],k,m=>{m=[m[0],null].concat(m.slice(1));rc(a,Ac(a,m,null,e,f,g),b-1);return[]})},w:(a,b,c,d,e)=>{b=Q(b);let f=k=>k;if(0===d){var g=32-8*c;f=k=>k<<g>>>g;e=f(e)}O(a,{name:b,pb:f,tb:(k,m)=>m,zb:Ub(b,
+a.values[c]=d;a[b]=d;break;case "number":d.zc[b]=c;break;case "string":d.gd[b]=c,d.ad[c]=b,d.zc[b]=b}},pa:(a,b,c)=>{b=Q(b);O(a,{name:b,pb:d=>d,tb:(d,e)=>e,zb:Jc(b,c),ub:null})},b:(a,b,c,d,e,f,g)=>{var k=yc(b,c);a=Q(a);a=Bc(a);e=T(d,e);dc(a,function(){xc(`Cannot call ${a} due to unbound types`,k)},b-1);Rb([],k,m=>{m=[m[0],null].concat(m.slice(1));rc(a,Ac(a,m,null,e,f,g),b-1);return[]})},w:(a,b,c,d,e)=>{b=Q(b);let f=k=>k;if(0===d){var g=32-8*c;f=k=>k<<g>>>g;e=f(e)}O(a,{name:b,pb:f,tb:(k,m)=>m,zb:Ub(b,
c,0!==d),ub:null})},i:(a,b,c)=>{function d(f){return new e(q.buffer,x[f+4>>2],x[f>>2])}var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];c=Q(c);O(a,{name:c,pb:d,zb:d},{Bd:!0})},Pa:(a,b)=>{b=Q(b);O(a,{name:b,pb(c){var d=(d=c+4)?D(t,d,x[c>>2],!0):"";U(c);return d},tb(c,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var e="string"==typeof d;if(!(e||ArrayBuffer.isView(d)&&1==d.BYTES_PER_ELEMENT))throw new R("Cannot pass non-string to std::string");
-var f=e?Wa(d):d.length;var g=Ed(4+f+1),k=g+4;x[g>>2]=f;e?E(d,t,k,f+1):t.set(d,k);null!==c&&c.push(U,g);return g},zb:Lb,ub(c){U(c)}})},Y:(a,b,c)=>{c=Q(c);if(2===b){var d=Lc;var e=Mc;var f=Nc}else d=Oc,e=Pc,f=Qc;O(a,{name:c,pb:g=>{var k=d(g+4,x[g>>2]*b,!0);U(g);return k},tb:(g,k)=>{if("string"!=typeof k)throw new R(`Cannot pass non-string to C++ string type ${c}`);var m=f(k),l=Ed(4+m+b);x[l>>2]=m/b;e(k,l+4,m+b);null!==g&&g.push(U,l);return l},zb:Lb,ub(g){U(g)}})},h:(a,b,c,d,e,f)=>{Jb[a]={name:Q(b),
+var f=e?Wa(d):d.length;var g=Ed(4+f+1),k=g+4;x[g>>2]=f;e?E(d,t,k,f+1):t.set(d,k);null!==c&&c.push(U,g);return g},zb:Lb,ub(c){U(c)}})},$:(a,b,c)=>{c=Q(c);if(2===b){var d=Lc;var e=Mc;var f=Nc}else d=Oc,e=Pc,f=Qc;O(a,{name:c,pb:g=>{var k=d(g+4,x[g>>2]*b,!0);U(g);return k},tb:(g,k)=>{if("string"!=typeof k)throw new R(`Cannot pass non-string to C++ string type ${c}`);var m=f(k),l=Ed(4+m+b);x[l>>2]=m/b;e(k,l+4,m+b);null!==g&&g.push(U,l);return l},zb:Lb,ub(g){U(g)}})},g:(a,b,c,d,e,f)=>{Jb[a]={name:Q(b),
Ec:T(c,d),Ib:T(e,f),Pc:[]}},a:(a,b,c,d,e,f,g,k,m,l)=>{Jb[a].Pc.push({td:Q(b),Ad:c,ac:T(d,e),zd:f,Pd:g,Od:T(k,m),Qd:l})},Ra:(a,b)=>{b=Q(b);O(a,{Sc:!0,name:b,pb:()=>{},tb:()=>{}})},Ta:()=>{Ia=!1;Rc=0},J:(a,b,c)=>{var [d,...e]=Uc(a,b);b=d.tb.bind(d);var f=e.map(m=>m.zb.bind(m));a--;var g={toValue:Fc};a=f.map((m,l)=>{var p=`argFromPtr${l}`;g[p]=m;return`${p}(args${l?"+"+8*l:""})`});switch(c){case 0:var k="toValue(handle)";break;case 2:k="new (toValue(handle))";break;case 3:k="";break;case 1:g.getStringOrSymbol=
-Xc,k="toValue(handle)[getStringOrSymbol(methodName)]"}k+=`(${a})`;d.Sc||(g.toReturnWire=b,g.emval_returnValue=Vc,k=`return emval_returnValue(toReturnWire, destructorsRef, ${k})`);k=`return function (handle, methodName, destructorsRef, args) {\n${k}\n}`;c=(new Function(Object.keys(g),k))(...Object.values(g));k=`methodCaller<(${e.map(m=>m.name)}) => ${d.name}>`;return Tc(ac(k,c))},v:Ec,I:(a,b,c,d,e)=>Sc[a](b,c,d,e),pa:()=>kc([]),T:a=>kc(Xc(a)),ra:()=>kc({}),H:a=>{var b=Fc(a);Kb(b);Ec(a)},K:(a,b,c)=>
+Xc,k="toValue(handle)[getStringOrSymbol(methodName)]"}k+=`(${a})`;d.Sc||(g.toReturnWire=b,g.emval_returnValue=Vc,k=`return emval_returnValue(toReturnWire, destructorsRef, ${k})`);k=`return function (handle, methodName, destructorsRef, args) {\n${k}\n}`;c=(new Function(Object.keys(g),k))(...Object.values(g));k=`methodCaller<(${e.map(m=>m.name)}) => ${d.name}>`;return Tc(ac(k,c))},v:Ec,I:(a,b,c,d,e)=>Sc[a](b,c,d,e),na:()=>kc([]),V:a=>kc(Xc(a)),oa:()=>kc({}),H:a=>{var b=Fc(a);Kb(b);Ec(a)},K:(a,b,c)=>
{a=Fc(a);b=Fc(b);c=Fc(c);a[b]=c},Ua:(a,b)=>{Yc[a]&&(clearTimeout(Yc[a].id),delete Yc[a]);if(!b)return 0;var c=setTimeout(()=>{delete Yc[a];ad(()=>Xd(a,performance.now()))},b);Yc[a]={id:c,Ae:b};return 0},Va:(a,b,c,d)=>{var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();x[a>>2]=60*Math.max(f,e);w[b>>2]=Number(f!=e);b=g=>{var k=Math.abs(g);return`UTC${0<=g?"-":"+"}${String(Math.floor(k/60)).padStart(2,"0")}${String(k%60).padStart(2,"0")}`};
a=b(f);b=b(e);e<f?(E(a,t,c,17),E(b,t,d,17)):(E(a,t,d,17),E(b,t,c,17))},Za:function(a,b,c,d,e){var f=h.materialDataProvider;f?f(a,b,c,d,e):(x[b>>2]=0,x[c>>2]=0,x[d>>2]=0,x[e>>2]=0)},wa:function(a,b,c){if(!(0<=a&&3>=a))return 28;ua[c>>3]=BigInt(Math.round(1E6*(0===a?Date.now():performance.now())));return 0},xa:a=>{var b=t.length;a>>>=0;if(2147483648<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(a,d)/65536))-ya.buffer.byteLength+
-65535)/65536|0;try{ya.grow(d);xa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1},Ya:(a,b)=>{var c=b>>2;b={alpha:!!q[b+0],depth:!!q[b+1],stencil:!!q[b+2],antialias:!!q[b+3],premultipliedAlpha:!!q[b+4],preserveDrawingBuffer:!!q[b+5],powerPreference:xd[w[c+2]],failIfMajorPerformanceCaveat:!!q[b+12],Vc:w[c+4],pe:w[c+5],Oc:q[b+24],sd:q[b+25],ve:w[c+7],ye:q[b+32]};a=2<a?a?D(t,a):"":a;a=yd[a]||globalThis.document?.querySelector(a);return!a||b.sd?0:wd(a,b)},Ma:a=>{Z==a&&(Z=0);Z===ld[a]&&(Z=null);
-"object"==typeof JSEvents&&JSEvents.xe(ld[a].Sb.canvas);ld[a]?.Sb.canvas&&(ld[a].Sb.canvas.ld=void 0);ld[a]=null},qa:a=>{Z=ld[a];h.ctx=V=Z?.Sb;return!a||V?0:-5},Wa:(a,b)=>{var c=0,d=0,e;for(e of Bd()){var f=b+c;x[a+d>>2]=f;c+=E(e,t,f,Infinity)+1;d+=4}return 0},Xa:(a,b)=>{var c=Bd();x[a>>2]=c.length;a=0;for(var d of c)a+=Wa(d)+1;x[b>>2]=a;return 0},aa:function(a){try{var b=N(a);C.close(b);return 0}catch(c){if("undefined"==typeof C||"ErrnoError"!==c.name)throw c;return c.Cb}},ta:function(a,b,c,d){try{a:{var e=
+65535)/65536|0;try{ya.grow(d);xa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1},Ya:(a,b)=>{var c=b>>2;b={alpha:!!q[b+0],depth:!!q[b+1],stencil:!!q[b+2],antialias:!!q[b+3],premultipliedAlpha:!!q[b+4],preserveDrawingBuffer:!!q[b+5],powerPreference:xd[w[c+2]],failIfMajorPerformanceCaveat:!!q[b+12],Vc:w[c+4],pe:w[c+5],Oc:q[b+24],sd:q[b+25],ve:w[c+7],ye:q[b+32]};a=2<a?a?D(t,a):"":a;a=yd[a]||globalThis.document?.querySelector(a);return!a||b.sd?0:wd(a,b)},Na:a=>{Z==a&&(Z=0);Z===ld[a]&&(Z=null);
+"object"==typeof JSEvents&&JSEvents.xe(ld[a].Sb.canvas);ld[a]?.Sb.canvas&&(ld[a].Sb.canvas.ld=void 0);ld[a]=null},ra:a=>{Z=ld[a];h.ctx=V=Z?.Sb;return!a||V?0:-5},Wa:(a,b)=>{var c=0,d=0,e;for(e of Bd()){var f=b+c;x[a+d>>2]=f;c+=E(e,t,f,Infinity)+1;d+=4}return 0},Xa:(a,b)=>{var c=Bd();x[a>>2]=c.length;a=0;for(var d of c)a+=Wa(d)+1;x[b>>2]=a;return 0},aa:function(a){try{var b=N(a);C.close(b);return 0}catch(c){if("undefined"==typeof C||"ErrnoError"!==c.name)throw c;return c.Cb}},ta:function(a,b,c,d){try{a:{var e=
N(a);a=b;for(var f,g=b=0;g<c;g++){var k=x[a>>2],m=x[a+4>>2];a+=8;var l=C.read(e,q,k,m,f);if(0>l){var p=-1;break a}b+=l;if(l<m)break;"undefined"!=typeof f&&(f+=l)}p=b}x[d>>2]=p;return 0}catch(r){if("undefined"==typeof C||"ErrnoError"!==r.name)throw r;return r.Cb}},sa:function(a,b,c,d){b=-9007199254740992>b||9007199254740992<b?NaN:Number(b);try{if(isNaN(b))return 61;var e=N(a);C.yb(e,b,c);ua[d>>3]=BigInt(e.position);e.tc&&0===b&&0===c&&(e.tc=null);return 0}catch(f){if("undefined"==typeof C||"ErrnoError"!==
f.name)throw f;return f.Cb}},ya:function(a,b,c,d){try{a:{var e=N(a);a=b;for(var f,g=b=0;g<c;g++){var k=x[a>>2],m=x[a+4>>2];a+=8;var l=C.write(e,q,k,m,f);if(0>l){var p=-1;break a}b+=l;if(l<m)break;"undefined"!=typeof f&&(f+=l)}p=b}x[d>>2]=p;return 0}catch(r){if("undefined"==typeof C||"ErrnoError"!==r.name)throw r;return r.Cb}},e:a=>V.activeTexture(a),ga:(a,b)=>{V.attachShader(W[a],X[b])},p:(a,b,c)=>{V.bindAttribLocation(W[a],b,c?D(t,c):"")},f:(a,b)=>{if(b&&!gd[b]){var c=V.createBuffer();c.name=b;gd[b]=
-c}34962==a?V.Yb=b:34963==a&&(V.Zb=b);35051==a?V.Jc=b:35052==a&&(V.jc=b);V.bindBuffer(a,gd[b])},D:(a,b)=>{V.bindFramebuffer(a,hd[b])},d:(a,b)=>{V.bindTexture(a,jd[b])},l:a=>{V.bindVertexArray(kd[a]);a=V.getParameter(34965);V.Zb=a?a.name|0:0},Z:(a,b)=>V.blendFunc(a,b),z:(a,b,c,d)=>V.blendFuncSeparate(a,b,c,d),s:(a,b,c,d)=>{2<=Z.version?c&&b?V.bufferData(a,t,d,c,b):V.bufferData(a,b,d):V.bufferData(a,c?t.subarray(c,c+b):b,d)},A:(a,b,c,d)=>{2<=Z.version?c&&V.bufferSubData(a,b,t,d,c):V.bufferSubData(a,
-b,t.subarray(d,d+c))},Aa:a=>V.checkFramebufferStatus(a),G:a=>V.clear(a),U:(a,b,c,d)=>V.clearColor(a,b,c,d),ia:a=>{V.compileShader(X[a])},La:()=>{var a=qd(W),b=V.createProgram();b.name=a;b.pc=b.nc=b.oc=0;b.Fc=1;W[a]=b;return a},ka:a=>{var b=qd(X);X[b]=V.createShader(a);return b},u:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=gd[d];e&&(V.deleteBuffer(e),e.name=0,gd[d]=null,d==V.Yb&&(V.Yb=0),d==V.Zb&&(V.Zb=0),d==V.Jc&&(V.Jc=0),d==V.jc&&(V.jc=0))}},da:(a,b)=>{for(var c=0;c<a;++c){var d=w[b+4*c>>2],
-e=hd[d];e&&(V.deleteFramebuffer(e),e.name=0,hd[d]=null)}},la:a=>{if(a){var b=W[a];b?(V.deleteProgram(b),b.name=0,W[a]=null):Y||=1281}},C:a=>{if(a){var b=X[a];b?(V.deleteShader(b),X[a]=null):Y||=1281}},F:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=jd[d];e&&(V.deleteTexture(e),e.name=0,jd[d]=null)}},L:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2];V.deleteVertexArray(kd[d]);kd[d]=null}},q:a=>V.disable(a),W:a=>{Z.Tb[a].enabled=!1;V.disableVertexAttribArray(a)},X:(a,b,c)=>{ud(b+c);V.drawArrays(a,
-b,c);td&&V.bindBuffer(34962,gd[V.Yb])},B:(a,b,c,d)=>{var e=0;if(!V.Zb){var f=1*md[c-5120]*b;var g=sd(f);V.bindBuffer(34963,g);V.bufferSubData(34963,0,t.subarray(d,d+f));if(0<b)for(g=0;g<Z.Bc;++g)if(f=Z.Tb[g],f.ic&&f.enabled){switch(c){case 5121:e=Uint8Array;break;case 5123:e=Uint16Array;break;case 5125:e=Uint32Array;break;default:Y||=1282;return}e=(new e(t.buffer,d,b)).reduce((k,m)=>Math.max(k,m))+1;break}d=0}ud(e);V.drawElements(a,b,c,d);td&&V.bindBuffer(34962,gd[V.Yb]);V.Zb||V.bindBuffer(34963,
-null)},r:a=>V.enable(a),n:a=>{Z.Tb[a].enabled=!0;V.enableVertexAttribArray(a)},ca:(a,b,c,d,e)=>{V.framebufferTexture2D(a,b,c,jd[d],e)},t:(a,b)=>{rd(a,b,"createBuffer",gd)},Ba:(a,b)=>{rd(a,b,"createFramebuffer",hd)},R:(a,b)=>{rd(a,b,"createTexture",jd)},M:(a,b)=>{rd(a,b,"createVertexArray",kd)},Ca:a=>V.generateMipmap(a),Da:(a,b)=>V.getAttribLocation(W[a],b?D(t,b):""),x:()=>{var a=V.getError()||Y;Y=0;return a},_:(a,b)=>Dd(a,b),Ka:(a,b,c,d)=>{a=V.getProgramInfoLog(W[a]);null===a&&(a="(unknown error)");
+c}34962==a?V.Yb=b:34963==a&&(V.Zb=b);35051==a?V.Jc=b:35052==a&&(V.jc=b);V.bindBuffer(a,gd[b])},B:(a,b)=>{V.bindFramebuffer(a,hd[b])},d:(a,b)=>{V.bindTexture(a,jd[b])},l:a=>{V.bindVertexArray(kd[a]);a=V.getParameter(34965);V.Zb=a?a.name|0:0},X:(a,b)=>V.blendFunc(a,b),y:(a,b,c,d)=>V.blendFuncSeparate(a,b,c,d),s:(a,b,c,d)=>{2<=Z.version?c&&b?V.bufferData(a,t,d,c,b):V.bufferData(a,b,d):V.bufferData(a,c?t.subarray(c,c+b):b,d)},z:(a,b,c,d)=>{2<=Z.version?c&&V.bufferSubData(a,b,t,d,c):V.bufferSubData(a,
+b,t.subarray(d,d+c))},Aa:a=>V.checkFramebufferStatus(a),E:a=>V.clear(a),U:(a,b,c,d)=>V.clearColor(a,b,c,d),ja:a=>{V.compileShader(X[a])},La:()=>{var a=qd(W),b=V.createProgram();b.name=a;b.pc=b.nc=b.oc=0;b.Fc=1;W[a]=b;return a},la:a=>{var b=qd(X);X[b]=V.createShader(a);return b},u:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=gd[d];e&&(V.deleteBuffer(e),e.name=0,gd[d]=null,d==V.Yb&&(V.Yb=0),d==V.Zb&&(V.Zb=0),d==V.Jc&&(V.Jc=0),d==V.jc&&(V.jc=0))}},da:(a,b)=>{for(var c=0;c<a;++c){var d=w[b+4*c>>2],
+e=hd[d];e&&(V.deleteFramebuffer(e),e.name=0,hd[d]=null)}},ma:a=>{if(a){var b=W[a];b?(V.deleteProgram(b),b.name=0,W[a]=null):Y||=1281}},A:a=>{if(a){var b=X[a];b?(V.deleteShader(b),X[a]=null):Y||=1281}},D:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=jd[d];e&&(V.deleteTexture(e),e.name=0,jd[d]=null)}},L:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2];V.deleteVertexArray(kd[d]);kd[d]=null}},q:a=>V.disable(a),W:a=>{Z.Tb[a].enabled=!1;V.disableVertexAttribArray(a)},Y:(a,b,c)=>{ud(b+c);V.drawArrays(a,
+b,c);td&&V.bindBuffer(34962,gd[V.Yb])},C:(a,b,c,d)=>{var e=0;if(!V.Zb){var f=1*md[c-5120]*b;var g=sd(f);V.bindBuffer(34963,g);V.bufferSubData(34963,0,t.subarray(d,d+f));if(0<b)for(g=0;g<Z.Bc;++g)if(f=Z.Tb[g],f.ic&&f.enabled){switch(c){case 5121:e=Uint8Array;break;case 5123:e=Uint16Array;break;case 5125:e=Uint32Array;break;default:Y||=1282;return}e=(new e(t.buffer,d,b)).reduce((k,m)=>Math.max(k,m))+1;break}d=0}ud(e);V.drawElements(a,b,c,d);td&&V.bindBuffer(34962,gd[V.Yb]);V.Zb||V.bindBuffer(34963,
+null)},r:a=>V.enable(a),n:a=>{Z.Tb[a].enabled=!0;V.enableVertexAttribArray(a)},ca:(a,b,c,d,e)=>{V.framebufferTexture2D(a,b,c,jd[d],e)},t:(a,b)=>{rd(a,b,"createBuffer",gd)},Ba:(a,b)=>{rd(a,b,"createFramebuffer",hd)},R:(a,b)=>{rd(a,b,"createTexture",jd)},M:(a,b)=>{rd(a,b,"createVertexArray",kd)},Ca:a=>V.generateMipmap(a),Da:(a,b)=>V.getAttribLocation(W[a],b?D(t,b):""),F:()=>{var a=V.getError()||Y;Y=0;return a},Z:(a,b)=>Dd(a,b),Ka:(a,b,c,d)=>{a=V.getProgramInfoLog(W[a]);null===a&&(a="(unknown error)");
b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},O:(a,b,c)=>{if(c)if(a>=fd)Y||=1281;else if(a=W[a],35716==b)a=V.getProgramInfoLog(a),null===a&&(a="(unknown error)"),w[c>>2]=a.length+1;else if(35719==b){if(!a.pc){var d=V.getProgramParameter(a,35718);for(b=0;b<d;++b)a.pc=Math.max(a.pc,V.getActiveUniform(a,b).name.length+1)}w[c>>2]=a.pc}else if(35722==b){if(!a.nc)for(d=V.getProgramParameter(a,35721),b=0;b<d;++b)a.nc=Math.max(a.nc,V.getActiveAttrib(a,b).name.length+1);w[c>>2]=a.nc}else if(35381==b){if(!a.oc)for(d=
-V.getProgramParameter(a,35382),b=0;b<d;++b)a.oc=Math.max(a.oc,V.getActiveUniformBlockName(a,b).length+1);w[c>>2]=a.oc}else w[c>>2]=V.getProgramParameter(a,b);else Y||=1281},ha:(a,b,c,d)=>{a=V.getShaderInfoLog(X[a]);null===a&&(a="(unknown error)");b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},N:(a,b,c)=>{c?35716==b?(a=V.getShaderInfoLog(X[a]),null===a&&(a="(unknown error)"),w[c>>2]=a?a.length+1:0):35720==b?(a=V.getShaderSource(X[a]),w[c>>2]=a?a.length+1:0):w[c>>2]=V.getShaderParameter(X[a],b):Y||=1281},V:a=>
-{var b=nd[a];if(!b){switch(a){case 7939:b=Fd(Cd().join(" "));break;case 7936:case 7937:case 37445:case 37446:(b=V.getParameter(a))||(Y||=1280);b=b?Fd(b):0;break;case 7938:b=V.getParameter(7938);var c=`OpenGL ES 2.0 (${b})`;2<=Z.version&&(c=`OpenGL ES 3.0 (${b})`);b=Fd(c);break;case 35724:b=V.getParameter(35724);c=b.match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);null!==c&&(3==c[1].length&&(c[1]+="0"),b=`OpenGL ES GLSL ES ${c[1]} (${b})`);b=Fd(b);break;default:Y||=1280}nd[a]=b}return b},y:(a,
+V.getProgramParameter(a,35382),b=0;b<d;++b)a.oc=Math.max(a.oc,V.getActiveUniformBlockName(a,b).length+1);w[c>>2]=a.oc}else w[c>>2]=V.getProgramParameter(a,b);else Y||=1281},ha:(a,b,c,d)=>{a=V.getShaderInfoLog(X[a]);null===a&&(a="(unknown error)");b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},N:(a,b,c)=>{c?35716==b?(a=V.getShaderInfoLog(X[a]),null===a&&(a="(unknown error)"),w[c>>2]=a?a.length+1:0):35720==b?(a=V.getShaderSource(X[a]),w[c>>2]=a?a.length+1:0):w[c>>2]=V.getShaderParameter(X[a],b):Y||=1281},T:a=>
+{var b=nd[a];if(!b){switch(a){case 7939:b=Fd(Cd().join(" "));break;case 7936:case 7937:case 37445:case 37446:(b=V.getParameter(a))||(Y||=1280);b=b?Fd(b):0;break;case 7938:b=V.getParameter(7938);var c=`OpenGL ES 2.0 (${b})`;2<=Z.version&&(c=`OpenGL ES 3.0 (${b})`);b=Fd(c);break;case 35724:b=V.getParameter(35724);c=b.match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);null!==c&&(3==c[1].length&&(c[1]+="0"),b=`OpenGL ES GLSL ES ${c[1]} (${b})`);b=Fd(b);break;default:Y||=1280}nd[a]=b}return b},x:(a,
b)=>{b=b?D(t,b):"";if(a=W[a]){var c=a,d=c.fc,e=c.ed,f;if(!d){c.fc=d={};c.dd={};var g=V.getProgramParameter(c,35718);for(f=0;f<g;++f){var k=V.getActiveUniform(c,f);var m=k.name;k=k.size;var l=Gd(m);l=0<l?m.slice(0,l):m;var p=c.Fc;c.Fc+=k;e[l]=[k,p];for(m=0;m<k;++m)d[p]=m,c.dd[p++]=l}}c=a.fc;d=0;e=b;f=Gd(b);0<f&&(d=parseInt(b.slice(f+1))>>>0,e=b.slice(0,f));if((e=a.ed[e])&&d<e[0]&&(d+=e[1],c[d]=c[d]||V.getUniformLocation(a,b)))return d}else Y||=1281;return-1},P:a=>{a=W[a];V.linkProgram(a);a.fc=0;a.ed=
-{}},fa:(a,b)=>{3317==a?od=b:3314==a&&(pd=b);V.pixelStorei(a,b)},$:(a,b,c,d)=>V.scissor(a,b,c,d),ja:(a,b,c,d)=>{for(var e="",f=0;f<b;++f){var g=(g=x[c+4*f>>2])?D(t,g,d?x[d+4*f>>2]:void 0):"";e+=g}V.shaderSource(X[a],e)},Q:(a,b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.jc){V.texImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);m>>>=31-Math.clz32(l.BYTES_PER_ELEMENT);V.texImage2D(a,b,c,d,e,f,g,k,l,m);return}}l=m?Id(k,g,d,e,m):null;V.texImage2D(a,b,c,d,e,f,g,k,l)},o:(a,b,c)=>V.texParameteri(a,b,c),ea:(a,
+{}},fa:(a,b)=>{3317==a?od=b:3314==a&&(pd=b);V.pixelStorei(a,b)},_:(a,b,c,d)=>V.scissor(a,b,c,d),ka:(a,b,c,d)=>{for(var e="",f=0;f<b;++f){var g=(g=x[c+4*f>>2])?D(t,g,d?x[d+4*f>>2]:void 0):"";e+=g}V.shaderSource(X[a],e)},Q:(a,b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.jc){V.texImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);m>>>=31-Math.clz32(l.BYTES_PER_ELEMENT);V.texImage2D(a,b,c,d,e,f,g,k,l,m);return}}l=m?Id(k,g,d,e,m):null;V.texImage2D(a,b,c,d,e,f,g,k,l)},o:(a,b,c)=>V.texParameteri(a,b,c),ea:(a,
b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.jc){V.texSubImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);V.texSubImage2D(a,b,c,d,e,f,g,k,l,m>>>31-Math.clz32(l.BYTES_PER_ELEMENT));return}}m=m?Id(k,g,e,f,m):null;V.texSubImage2D(a,b,c,d,e,f,g,k,m)},Ia:(a,b)=>{V.uniform1f(Jd(a),b)},j:(a,b)=>{V.uniform1i(Jd(a),b)},Ha:(a,b,c)=>{V.uniform2f(Jd(a),b,c)},Ga:(a,b,c,d)=>{V.uniform3f(Jd(a),b,c,d)},Fa:(a,b,c,d,e)=>{V.uniform4f(Jd(a),b,c,d,e)},Ea:(a,b,c,d)=>{if(2<=Z.version)b&&V.uniformMatrix4fv(Jd(a),!!c,sa,d>>
2,16*b);else{if(18>=b){var e=Kd[16*b],f=sa;d>>=2;b*=16;for(var g=0;g<b;g+=16){var k=d+g;e[g]=f[k];e[g+1]=f[k+1];e[g+2]=f[k+2];e[g+3]=f[k+3];e[g+4]=f[k+4];e[g+5]=f[k+5];e[g+6]=f[k+6];e[g+7]=f[k+7];e[g+8]=f[k+8];e[g+9]=f[k+9];e[g+10]=f[k+10];e[g+11]=f[k+11];e[g+12]=f[k+12];e[g+13]=f[k+13];e[g+14]=f[k+14];e[g+15]=f[k+15]}}else e=sa.subarray(d>>2,d+64*b>>2);V.uniformMatrix4fv(Jd(a),!!c,e)}},Ja:a=>{a=W[a];V.useProgram(a);V.pd=a},k:(a,b,c,d,e,f)=>{var g=Z.Tb[a];V.Yb?(g.ic=!1,V.vertexAttribPointer(a,b,c,
-!!d,e,f)):(g.size=b,g.type=c,g.Yc=d,g.stride=e,g.nb=f,g.ic=!0,g.hd=function(k,m,l,p,r,v){this.vertexAttribPointer(k,m,l,p,r,v)})},E:(a,b,c,d)=>V.viewport(a,b,c,d),Sa:$c};
+!!d,e,f)):(g.size=b,g.type=c,g.Yc=d,g.stride=e,g.nb=f,g.ic=!0,g.hd=function(k,m,l,p,r,v){this.vertexAttribPointer(k,m,l,p,r,v)})},G:(a,b,c,d)=>V.viewport(a,b,c,d),Sa:$c};
function Zd(){function a(){h.calledRun=!0;if(!na){wa=!0;h.noFSInit||C.uc||lb();$d.$a();C.Rc=!1;pa?.(h);h.onRuntimeInitialized?.();if(h.postRun)for("function"==typeof h.postRun&&(h.postRun=[h.postRun]);h.postRun.length;){var b=h.postRun.shift();Fa.push(b)}Ea(Fa)}}if(0<gb)hb=Zd;else{if(h.preRun)for("function"==typeof h.preRun&&(h.preRun=[h.preRun]);h.preRun.length;)Ha();Ea(Ga);0<gb?hb=Zd:h.setStatus?(h.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>h.setStatus(""),1);a()},1)):a()}}var $d;
$d=await (async function(){function a(c){c=$d=c.exports;vc=c.ab;Ed=h._malloc=c.bb;U=h._free=c.db;Xd=c.eb;Nd=c.fb;Ld=c.gb;Md=c.hb;ya=c._a;S=c.cb;xa();return $d}var b={a:Yd};if(h.instantiateWasm)return new Promise(c=>{h.instantiateWasm(b,(d,e)=>{c(a(d,e))})});za??=h.locateFile?h.locateFile?h.locateFile("esengine.wasm",ha):ha+"esengine.wasm":(new URL("esengine.wasm",import.meta.url)).href;return a((await Ca(b)).instance)}());Zd();
wa?moduleRtn=h:moduleRtn=new Promise((a,b)=>{pa=a;qa=b});
diff --git a/desktop/vite.config.ts b/desktop/vite.config.ts
index 2370ca57e..1287c236c 100644
--- a/desktop/vite.config.ts
+++ b/desktop/vite.config.ts
@@ -31,7 +31,6 @@ export default defineConfig({
host: host || false,
hmr: host
? {
- protocol: 'ws',
host,
port: 5174,
}
diff --git a/editor/package.json b/editor/package.json
index f36fc3f6f..931238a0f 100644
--- a/editor/package.json
+++ b/editor/package.json
@@ -18,7 +18,10 @@
"scripts": {
"build": "rollup -c",
"watch": "rollup -c -w",
- "clean": "rimraf dist"
+ "clean": "rimraf dist",
+ "test": "vitest",
+ "test:ui": "vitest --ui",
+ "test:coverage": "vitest --coverage"
},
"dependencies": {
"esbuild-wasm": "^0.27.2",
@@ -29,11 +32,15 @@
"@rollup/plugin-alias": "^6.0.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-typescript": "^11.1.5",
+ "@vitest/ui": "^2.1.8",
+ "happy-dom": "^20.6.1",
+ "jsdom": "^25.0.1",
"rimraf": "^5.0.5",
"rollup": "^4.9.0",
"rollup-plugin-dts": "^6.1.0",
"tslib": "^2.6.2",
- "typescript": "^5.3.0"
+ "typescript": "^5.3.0",
+ "vitest": "^2.1.8"
},
"author": "ESEngine Team",
"license": "MIT"
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 4d3aeaf34..fb9e4af2b 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -60,6 +60,8 @@ import { registerComponentSchema } from './schemas';
import { showToast, showSuccessToast, showErrorToast } from './ui/Toast';
import { showContextMenu } from './ui/ContextMenu';
import { registerContextMenuItem, lockBuiltinContextMenuItems, clearExtensionContextMenuItems } from './ui/ContextMenuRegistry';
+import { installGlobalErrorHandler } from './error/GlobalErrorHandler';
+import { EditorLogger, createConsoleHandler, createToastHandler } from './logging';
import {
registerInspectorSection,
registerComponentInspector,
@@ -82,6 +84,7 @@ import {
} from './settings';
import { loadProjectConfig, loadEditorLocalSettings, saveEditorLocalSetting } from './launcher/ProjectService';
import type { SpineVersion } from './types/ProjectTypes';
+import { Splitter } from './ui/Splitter';
// =============================================================================
// Types
@@ -110,6 +113,7 @@ export class Editor {
private baseAPI_: Record<string, unknown> | null = null;
private scriptLoader_: ScriptLoader | null = null;
private extensionLoader_: ExtensionLoader | null = null;
+ private splitters_: Splitter[] = [];
private previewService_: PreviewService | null = null;
private shortcutManager_: ShortcutManager;
private activeBottomPanelId_: string | null = 'content-browser';
@@ -123,6 +127,15 @@ export class Editor {
this.projectPath_ = options?.projectPath ?? null;
this.shortcutManager_ = new ShortcutManager();
+ installGlobalErrorHandler();
+
+ EditorLogger.addHandler(createConsoleHandler());
+ EditorLogger.addHandler(createToastHandler((message, type) => {
+ if (type === 'error') showErrorToast(message);
+ else if (type === 'warning') showToast({ type: 'info', title: message });
+ }));
+ EditorLogger.setMinLevel('info');
+
registerBuiltinEditors();
registerMaterialEditors();
registerBuiltinSchemas();
@@ -1108,6 +1121,7 @@ export class Editor {
this.instantiatePanels();
this.updateBottomPanelVisibility();
+ this.setupSplitters();
setEditorInstance(this);
@@ -1126,6 +1140,56 @@ export class Editor {
this.installConsoleCapture();
}
+ private setupSplitters(): void {
+ const main = this.container_.querySelector('.es-editor-main');
+ if (!main) return;
+
+ const leftPanel = main.querySelector('.es-editor-left') as HTMLElement;
+ const centerPanel = main.querySelector('.es-editor-center') as HTMLElement;
+ const rightPanel = main.querySelector('.es-editor-right') as HTMLElement;
+
+ if (leftPanel && centerPanel) {
+ const leftSize = this.loadPanelSize('panelSizeLeft', 250);
+ const leftSplitter = new Splitter({
+ direction: 'horizontal',
+ container: main as HTMLElement,
+ leftPanel,
+ rightPanel: centerPanel,
+ minSize: 200,
+ defaultPosition: leftSize,
+ onResize: (size) => {
+ this.savePanelSize('panelSizeLeft', size);
+ },
+ });
+ this.splitters_.push(leftSplitter);
+ }
+
+ if (centerPanel && rightPanel) {
+ const rightSize = this.loadPanelSize('panelSizeRight', 300);
+ const rightSplitter = new Splitter({
+ direction: 'horizontal',
+ container: main as HTMLElement,
+ leftPanel: centerPanel,
+ rightPanel,
+ minSize: 250,
+ defaultPosition: rightSize,
+ onResize: (_, size) => {
+ this.savePanelSize('panelSizeRight', size);
+ },
+ });
+ this.splitters_.push(rightSplitter);
+ }
+ }
+
+ private loadPanelSize(key: string, defaultValue: number): number {
+ const stored = localStorage.getItem(`esengine.editor.${key}`);
+ return stored ? parseInt(stored, 10) : defaultValue;
+ }
+
+ private savePanelSize(key: string, value: number): void {
+ localStorage.setItem(`esengine.editor.${key}`, String(value));
+ }
+
private buildTabBarHTML(): string {
const positions: PanelPosition[] = ['left', 'center', 'right'];
return positions.flatMap(pos => getPanelsByPosition(pos))
diff --git a/editor/src/__tests__/asset/AssetDatabase.test.ts b/editor/src/__tests__/asset/AssetDatabase.test.ts
new file mode 100644
index 000000000..4deb7d5f7
--- /dev/null
+++ b/editor/src/__tests__/asset/AssetDatabase.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect } from 'vitest';
+import { isUUID } from '../../asset/AssetDatabase';
+
+describe('AssetDatabase utilities', () => {
+ describe('isUUID', () => {
+ it('should recognize valid UUIDs', () => {
+ expect(isUUID('550e8400-e29b-41d4-a716-446655440000')).toBe(true);
+ expect(isUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')).toBe(true);
+ expect(isUUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')).toBe(true);
+ });
+
+ it('should recognize uppercase UUIDs', () => {
+ expect(isUUID('550E8400-E29B-41D4-A716-446655440000')).toBe(true);
+ });
+
+ it('should reject invalid UUIDs', () => {
+ expect(isUUID('not-a-uuid')).toBe(false);
+ expect(isUUID('550e8400-e29b-41d4-a716')).toBe(false);
+ expect(isUUID('550e8400-e29b-41d4-a716-44665544000')).toBe(false);
+ expect(isUUID('550e8400-e29b-41d4-a716-4466554400000')).toBe(false);
+ expect(isUUID('550e8400e29b41d4a716446655440000')).toBe(false);
+ expect(isUUID('')).toBe(false);
+ });
+
+ it('should reject UUIDs with invalid characters', () => {
+ expect(isUUID('550e8400-e29b-41d4-a716-44665544000g')).toBe(false);
+ expect(isUUID('550e8400-e29b-41d4-a716-44665544000 ')).toBe(false);
+ });
+ });
+});
diff --git a/editor/src/__tests__/commands/CommandHistory.test.ts b/editor/src/__tests__/commands/CommandHistory.test.ts
new file mode 100644
index 000000000..921f8e6fe
--- /dev/null
+++ b/editor/src/__tests__/commands/CommandHistory.test.ts
@@ -0,0 +1,278 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { CommandHistory } from '../../commands/CommandHistory';
+import { BaseCommand } from '../../commands/Command';
+import type { Command } from '../../commands/Command';
+
+class MockCommand extends BaseCommand {
+ type = 'mock';
+ description = 'Mock command';
+ executed = false;
+ undone = false;
+
+ execute(): void {
+ this.executed = true;
+ }
+
+ undo(): void {
+ this.undone = true;
+ }
+}
+
+class MergeableCommand extends BaseCommand {
+ type = 'mergeable';
+ description = 'Mergeable command';
+
+ constructor(
+ public value: number,
+ private onExecute?: () => void,
+ private onUndo?: () => void
+ ) {
+ super();
+ }
+
+ execute(): void {
+ this.onExecute?.();
+ }
+
+ undo(): void {
+ this.onUndo?.();
+ }
+
+ override canMerge(other: Command): boolean {
+ return other.type === 'mergeable' && Date.now() - other.timestamp < 1000;
+ }
+
+ override merge(other: Command): Command {
+ if (other instanceof MergeableCommand) {
+ return new MergeableCommand(other.value, this.onExecute, this.onUndo);
+ }
+ return this;
+ }
+}
+
+describe('CommandHistory', () => {
+ let history: CommandHistory;
+
+ beforeEach(() => {
+ history = new CommandHistory(10);
+ });
+
+ describe('execute', () => {
+ it('should execute and push command', () => {
+ const cmd = new MockCommand();
+ history.execute(cmd);
+
+ expect(cmd.executed).toBe(true);
+ expect(history.canUndo()).toBe(true);
+ expect(history.canRedo()).toBe(false);
+ expect(history.historySize).toBe(1);
+ });
+
+ it('should clear redo stack on new command', () => {
+ const cmd1 = new MockCommand();
+ const cmd2 = new MockCommand();
+ const cmd3 = new MockCommand();
+
+ history.execute(cmd1);
+ history.execute(cmd2);
+ history.undo();
+
+ expect(history.canRedo()).toBe(true);
+
+ history.execute(cmd3);
+
+ expect(history.canRedo()).toBe(false);
+ expect(history.historySize).toBe(2);
+ });
+
+ it('should merge consecutive mergeable commands', () => {
+ const cmd1 = new MergeableCommand(10);
+ const cmd2 = new MergeableCommand(20);
+
+ history.execute(cmd1);
+ history.execute(cmd2);
+
+ expect(history.historySize).toBe(1);
+ expect((history.peekUndo() as MergeableCommand).value).toBe(20);
+ });
+
+ it('should not merge non-mergeable commands', () => {
+ const cmd1 = new MockCommand();
+ const cmd2 = new MockCommand();
+
+ history.execute(cmd1);
+ history.execute(cmd2);
+
+ expect(history.historySize).toBe(2);
+ });
+ });
+
+ describe('undo', () => {
+ it('should undo last command', () => {
+ const cmd = new MockCommand();
+ history.execute(cmd);
+
+ const result = history.undo();
+
+ expect(result).toBe(true);
+ expect(cmd.undone).toBe(true);
+ expect(history.canUndo()).toBe(false);
+ expect(history.canRedo()).toBe(true);
+ });
+
+ it('should return false when nothing to undo', () => {
+ const result = history.undo();
+ expect(result).toBe(false);
+ });
+
+ it('should maintain correct index after multiple undos', () => {
+ const cmd1 = new MockCommand();
+ const cmd2 = new MockCommand();
+ const cmd3 = new MockCommand();
+
+ history.execute(cmd1);
+ history.execute(cmd2);
+ history.execute(cmd3);
+
+ history.undo();
+ history.undo();
+
+ expect(history.currentIndex).toBe(0);
+ expect(history.canUndo()).toBe(true);
+ expect(history.canRedo()).toBe(true);
+ });
+ });
+
+ describe('redo', () => {
+ it('should redo undone command', () => {
+ let execCount = 0;
+ const cmd = new MergeableCommand(10, () => execCount++);
+
+ history.execute(cmd);
+ history.undo();
+
+ const result = history.redo();
+
+ expect(result).toBe(true);
+ expect(execCount).toBe(2);
+ expect(history.canRedo()).toBe(false);
+ expect(history.canUndo()).toBe(true);
+ });
+
+ it('should return false when nothing to redo', () => {
+ const result = history.redo();
+ expect(result).toBe(false);
+ });
+
+ it('should handle multiple redos', () => {
+ const cmd1 = new MockCommand();
+ const cmd2 = new MockCommand();
+
+ history.execute(cmd1);
+ history.execute(cmd2);
+ history.undo();
+ history.undo();
+
+ history.redo();
+ expect(history.currentIndex).toBe(0);
+
+ history.redo();
+ expect(history.currentIndex).toBe(1);
+ expect(history.canRedo()).toBe(false);
+ });
+ });
+
+ describe('peek operations', () => {
+ it('should peek undo command', () => {
+ const cmd = new MockCommand();
+ history.execute(cmd);
+
+ expect(history.peekUndo()).toBe(cmd);
+ });
+
+ it('should return null when nothing to undo', () => {
+ expect(history.peekUndo()).toBeNull();
+ });
+
+ it('should peek redo command', () => {
+ const cmd = new MockCommand();
+ history.execute(cmd);
+ history.undo();
+
+ expect(history.peekRedo()).toBe(cmd);
+ });
+
+ it('should return null when nothing to redo', () => {
+ expect(history.peekRedo()).toBeNull();
+ });
+ });
+
+ describe('descriptions', () => {
+ it('should return undo description', () => {
+ const cmd = new MockCommand();
+ history.execute(cmd);
+
+ expect(history.undoDescription).toBe('Mock command');
+ });
+
+ it('should return null when nothing to undo', () => {
+ expect(history.undoDescription).toBeNull();
+ });
+
+ it('should return redo description', () => {
+ const cmd = new MockCommand();
+ history.execute(cmd);
+ history.undo();
+
+ expect(history.redoDescription).toBe('Mock command');
+ });
+
+ it('should return null when nothing to redo', () => {
+ expect(history.redoDescription).toBeNull();
+ });
+ });
+
+ describe('clear', () => {
+ it('should clear all history', () => {
+ const cmd1 = new MockCommand();
+ const cmd2 = new MockCommand();
+
+ history.execute(cmd1);
+ history.execute(cmd2);
+
+ history.clear();
+
+ expect(history.historySize).toBe(0);
+ expect(history.currentIndex).toBe(-1);
+ expect(history.canUndo()).toBe(false);
+ expect(history.canRedo()).toBe(false);
+ });
+ });
+
+ describe('size limit', () => {
+ it('should limit history size', () => {
+ const maxSize = 5;
+ const limitedHistory = new CommandHistory(maxSize);
+
+ for (let i = 0; i < 10; i++) {
+ limitedHistory.execute(new MockCommand());
+ }
+
+ expect(limitedHistory.historySize).toBe(maxSize);
+ expect(limitedHistory.currentIndex).toBe(maxSize - 1);
+ });
+
+ it('should maintain undo/redo functionality after size limit', () => {
+ const maxSize = 3;
+ const limitedHistory = new CommandHistory(maxSize);
+
+ for (let i = 0; i < 5; i++) {
+ limitedHistory.execute(new MockCommand());
+ }
+
+ expect(limitedHistory.canUndo()).toBe(true);
+ limitedHistory.undo();
+ expect(limitedHistory.canRedo()).toBe(true);
+ });
+ });
+});
diff --git a/editor/src/__tests__/logging/EditorLogger.test.ts b/editor/src/__tests__/logging/EditorLogger.test.ts
new file mode 100644
index 000000000..f2431fa90
--- /dev/null
+++ b/editor/src/__tests__/logging/EditorLogger.test.ts
@@ -0,0 +1,185 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { EditorLogger, createConsoleHandler, createToastHandler, type LogEntry } from '../../logging';
+
+describe('EditorLogger', () => {
+ beforeEach(() => {
+ EditorLogger.clearHandlers();
+ EditorLogger.setMinLevel('debug');
+ EditorLogger.setContext(null);
+ });
+
+ it('logs messages to registered handlers', () => {
+ const entries: LogEntry[] = [];
+ const handler = (entry: LogEntry) => entries.push(entry);
+
+ EditorLogger.addHandler(handler);
+ EditorLogger.info('Test message');
+
+ expect(entries.length).toBe(1);
+ expect(entries[0].level).toBe('info');
+ expect(entries[0].message).toBe('Test message');
+ });
+
+ it('logs all severity levels', () => {
+ const entries: LogEntry[] = [];
+ EditorLogger.addHandler((entry) => entries.push(entry));
+
+ EditorLogger.debug('Debug message');
+ EditorLogger.info('Info message');
+ EditorLogger.warn('Warning message');
+ EditorLogger.error('Error message');
+
+ expect(entries.length).toBe(4);
+ expect(entries[0].level).toBe('debug');
+ expect(entries[1].level).toBe('info');
+ expect(entries[2].level).toBe('warn');
+ expect(entries[3].level).toBe('error');
+ });
+
+ it('filters messages below min level', () => {
+ const entries: LogEntry[] = [];
+ EditorLogger.addHandler((entry) => entries.push(entry));
+ EditorLogger.setMinLevel('warn');
+
+ EditorLogger.debug('Debug message');
+ EditorLogger.info('Info message');
+ EditorLogger.warn('Warning message');
+ EditorLogger.error('Error message');
+
+ expect(entries.length).toBe(2);
+ expect(entries[0].level).toBe('warn');
+ expect(entries[1].level).toBe('error');
+ });
+
+ it('includes context in log entries', () => {
+ const entries: LogEntry[] = [];
+ EditorLogger.addHandler((entry) => entries.push(entry));
+ EditorLogger.setContext('TestContext');
+
+ EditorLogger.info('Test message');
+
+ expect(entries[0].context).toBe('TestContext');
+ });
+
+ it('includes data in log entries', () => {
+ const entries: LogEntry[] = [];
+ EditorLogger.addHandler((entry) => entries.push(entry));
+
+ const data = { foo: 'bar', count: 42 };
+ EditorLogger.info('Test message', data);
+
+ expect(entries[0].data).toEqual(data);
+ });
+
+ it('includes timestamp in log entries', () => {
+ const entries: LogEntry[] = [];
+ EditorLogger.addHandler((entry) => entries.push(entry));
+
+ const before = Date.now();
+ EditorLogger.info('Test message');
+ const after = Date.now();
+
+ expect(entries[0].timestamp).toBeGreaterThanOrEqual(before);
+ expect(entries[0].timestamp).toBeLessThanOrEqual(after);
+ });
+
+ it('removes handlers', () => {
+ const entries: LogEntry[] = [];
+ const handler = (entry: LogEntry) => entries.push(entry);
+
+ const unsubscribe = EditorLogger.addHandler(handler);
+ EditorLogger.info('First message');
+
+ unsubscribe();
+ EditorLogger.info('Second message');
+
+ expect(entries.length).toBe(1);
+ expect(entries[0].message).toBe('First message');
+ });
+
+ it('handles handler errors gracefully', () => {
+ const entries: LogEntry[] = [];
+ const goodHandler = (entry: LogEntry) => entries.push(entry);
+ const badHandler = () => { throw new Error('Handler error'); };
+
+ EditorLogger.addHandler(badHandler);
+ EditorLogger.addHandler(goodHandler);
+
+ expect(() => EditorLogger.info('Test message')).not.toThrow();
+ expect(entries.length).toBe(1);
+ });
+
+ it('supports multiple handlers', () => {
+ const entries1: LogEntry[] = [];
+ const entries2: LogEntry[] = [];
+
+ EditorLogger.addHandler((entry) => entries1.push(entry));
+ EditorLogger.addHandler((entry) => entries2.push(entry));
+
+ EditorLogger.info('Test message');
+
+ expect(entries1.length).toBe(1);
+ expect(entries2.length).toBe(1);
+ expect(entries1[0].message).toBe('Test message');
+ expect(entries2[0].message).toBe('Test message');
+ });
+
+ it('clears all handlers', () => {
+ const entries: LogEntry[] = [];
+ EditorLogger.addHandler((entry) => entries.push(entry));
+ EditorLogger.info('First message');
+
+ EditorLogger.clearHandlers();
+ EditorLogger.info('Second message');
+
+ expect(entries.length).toBe(1);
+ });
+});
+
+describe('createConsoleHandler', () => {
+ it('logs to console at appropriate levels', () => {
+ const consoleSpy = {
+ debug: vi.spyOn(console, 'debug').mockImplementation(() => {}),
+ log: vi.spyOn(console, 'log').mockImplementation(() => {}),
+ warn: vi.spyOn(console, 'warn').mockImplementation(() => {}),
+ error: vi.spyOn(console, 'error').mockImplementation(() => {}),
+ };
+
+ const handler = createConsoleHandler();
+
+ handler({ level: 'debug', message: 'Debug', timestamp: Date.now() });
+ handler({ level: 'info', message: 'Info', timestamp: Date.now() });
+ handler({ level: 'warn', message: 'Warn', timestamp: Date.now() });
+ handler({ level: 'error', message: 'Error', timestamp: Date.now() });
+
+ expect(consoleSpy.debug).toHaveBeenCalledWith(' Debug', '');
+ expect(consoleSpy.log).toHaveBeenCalledWith(' Info', '');
+ expect(consoleSpy.warn).toHaveBeenCalledWith(' Warn', '');
+ expect(consoleSpy.error).toHaveBeenCalledWith(' Error', '');
+
+ consoleSpy.debug.mockRestore();
+ consoleSpy.log.mockRestore();
+ consoleSpy.warn.mockRestore();
+ consoleSpy.error.mockRestore();
+ });
+});
+
+describe('createToastHandler', () => {
+ it('shows toasts for warnings and errors only', () => {
+ const toasts: Array<{ message: string; type: string }> = [];
+ const showToast = (message: string, type: 'info' | 'warning' | 'error') => {
+ toasts.push({ message, type });
+ };
+
+ const handler = createToastHandler(showToast);
+
+ handler({ level: 'debug', message: 'Debug', timestamp: Date.now() });
+ handler({ level: 'info', message: 'Info', timestamp: Date.now() });
+ handler({ level: 'warn', message: 'Warning', timestamp: Date.now() });
+ handler({ level: 'error', message: 'Error', timestamp: Date.now() });
+
+ expect(toasts.length).toBe(2);
+ expect(toasts[0]).toEqual({ message: 'Warning', type: 'warning' });
+ expect(toasts[1]).toEqual({ message: 'Error', type: 'error' });
+ });
+});
diff --git a/editor/src/__tests__/property/validation.test.ts b/editor/src/__tests__/property/validation.test.ts
new file mode 100644
index 000000000..70f4d7db2
--- /dev/null
+++ b/editor/src/__tests__/property/validation.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect } from 'vitest';
+import { validateNumber, validateVec2, validateVec3, validateColor } from '../../property/validation';
+import type { PropertyMeta } from '../../property/PropertyEditor';
+
+describe('Property validation', () => {
+ describe('validateNumber', () => {
+ it('validates valid numbers', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number' };
+ const result = validateNumber(42, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toBe(42);
+ });
+
+ it('validates string numbers', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number' };
+ const result = validateNumber('42.5', meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toBe(42.5);
+ });
+
+ it('rejects NaN values', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number' };
+ const result = validateNumber('invalid', meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toBe(0);
+ expect(result.error).toBe('Value must be a number');
+ });
+
+ it('enforces min constraint', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number', min: 0 };
+ const result = validateNumber(-5, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toBe(0);
+ expect(result.error).toBe('Value must be at least 0');
+ });
+
+ it('enforces max constraint', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number', max: 100 };
+ const result = validateNumber(150, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toBe(100);
+ expect(result.error).toBe('Value must be at most 100');
+ });
+
+ it('allows values within range', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number', min: 0, max: 100 };
+ const result = validateNumber(50, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toBe(50);
+ });
+
+ it('handles edge case min value', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number', min: 0 };
+ const result = validateNumber(0, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toBe(0);
+ });
+
+ it('handles edge case max value', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'number', max: 100 };
+ const result = validateNumber(100, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toBe(100);
+ });
+ });
+
+ describe('validateVec2', () => {
+ it('validates valid Vec2', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec2' };
+ const result = validateVec2({ x: 10, y: 20 }, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toEqual({ x: 10, y: 20 });
+ });
+
+ it('rejects non-object values', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec2' };
+ const result = validateVec2('invalid', meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ x: 0, y: 0 });
+ });
+
+ it('enforces min constraint on components', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec2', min: 0 };
+ const result = validateVec2({ x: -5, y: 10 }, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ x: 0, y: 10 });
+ });
+
+ it('enforces max constraint on components', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec2', max: 100 };
+ const result = validateVec2({ x: 50, y: 150 }, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ x: 50, y: 100 });
+ });
+ });
+
+ describe('validateVec3', () => {
+ it('validates valid Vec3', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec3' };
+ const result = validateVec3({ x: 10, y: 20, z: 30 }, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toEqual({ x: 10, y: 20, z: 30 });
+ });
+
+ it('rejects non-object values', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec3' };
+ const result = validateVec3(null, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ x: 0, y: 0, z: 0 });
+ });
+
+ it('enforces min constraint on all components', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'vec3', min: 0 };
+ const result = validateVec3({ x: -1, y: -2, z: -3 }, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ x: 0, y: 0, z: 0 });
+ });
+ });
+
+ describe('validateColor', () => {
+ it('validates valid Color', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'color' };
+ const result = validateColor({ r: 255, g: 128, b: 64, a: 255 }, meta);
+ expect(result.valid).toBe(true);
+ });
+
+ it('clamps color components to 0-255', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'color' };
+ const result = validateColor({ r: 300, g: -10, b: 128, a: 400 }, meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ r: 255, g: 0, b: 128, a: 255 });
+ });
+
+ it('rejects non-object values', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'color' };
+ const result = validateColor('red', meta);
+ expect(result.valid).toBe(false);
+ expect(result.value).toEqual({ r: 255, g: 255, b: 255, a: 255 });
+ });
+
+ it('allows valid color range', () => {
+ const meta: PropertyMeta = { name: 'test', type: 'color' };
+ const result = validateColor({ r: 0, g: 0, b: 0, a: 0 }, meta);
+ expect(result.valid).toBe(true);
+ expect(result.value).toEqual({ r: 0, g: 0, b: 0, a: 0 });
+ });
+ });
+});
diff --git a/editor/src/__tests__/setup.ts b/editor/src/__tests__/setup.ts
new file mode 100644
index 000000000..aff36506a
--- /dev/null
+++ b/editor/src/__tests__/setup.ts
@@ -0,0 +1,38 @@
+import { vi } from 'vitest';
+
+global.ResizeObserver = vi.fn().mockImplementation(() => ({
+ observe: vi.fn(),
+ unobserve: vi.fn(),
+ disconnect: vi.fn(),
+}));
+
+global.IntersectionObserver = vi.fn().mockImplementation(() => ({
+ observe: vi.fn(),
+ unobserve: vi.fn(),
+ disconnect: vi.fn(),
+}));
+
+HTMLCanvasElement.prototype.getContext = vi.fn(() => ({
+ fillRect: vi.fn(),
+ clearRect: vi.fn(),
+ getImageData: vi.fn(),
+ putImageData: vi.fn(),
+ createImageData: vi.fn(),
+ setTransform: vi.fn(),
+ drawImage: vi.fn(),
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ closePath: vi.fn(),
+ stroke: vi.fn(),
+ translate: vi.fn(),
+ scale: vi.fn(),
+ rotate: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+ measureText: vi.fn(() => ({ width: 0 })),
+ fillText: vi.fn(),
+ strokeText: vi.fn(),
+})) as any;
diff --git a/editor/src/__tests__/store/EditorStore.test.ts b/editor/src/__tests__/store/EditorStore.test.ts
new file mode 100644
index 000000000..53cef1b22
--- /dev/null
+++ b/editor/src/__tests__/store/EditorStore.test.ts
@@ -0,0 +1,171 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { EditorStore } from '../../store/EditorStore';
+import type { Entity } from 'esengine';
+
+describe('EditorStore multi-selection', () => {
+ let store: EditorStore;
+
+ beforeEach(() => {
+ store = new EditorStore();
+ store.newScene('Test Scene');
+ });
+
+ it('initializes with empty selection', () => {
+ expect(store.selectedEntities.size).toBe(0);
+ expect(store.selectedEntity).toBeNull();
+ });
+
+ it('selects single entity with replace mode', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+
+ store.selectEntity(entity1, 'replace');
+ expect(store.selectedEntities.size).toBe(1);
+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);
+ expect(store.selectedEntity).toBe(entity1);
+
+ store.selectEntity(entity2, 'replace');
+ expect(store.selectedEntities.size).toBe(1);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity1 as number)).toBe(false);
+ });
+
+ it('adds entities with add mode', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+ const entity3 = store.createEntity('Entity3');
+
+ store.selectEntity(entity1, 'replace');
+ store.selectEntity(entity2, 'add');
+ store.selectEntity(entity3, 'add');
+
+ expect(store.selectedEntities.size).toBe(3);
+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);
+ expect(store.selectedEntity).toBeNull();
+ });
+
+ it('toggles entities with toggle mode', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+
+ store.selectEntity(entity1, 'replace');
+ expect(store.selectedEntities.size).toBe(1);
+
+ store.selectEntity(entity2, 'toggle');
+ expect(store.selectedEntities.size).toBe(2);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+
+ store.selectEntity(entity1, 'toggle');
+ expect(store.selectedEntities.size).toBe(1);
+ expect(store.selectedEntities.has(entity1 as number)).toBe(false);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+ });
+
+ it('selects range of entities', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+ const entity3 = store.createEntity('Entity3');
+ const entity4 = store.createEntity('Entity4');
+
+ store.selectRange(entity1 as number, entity3 as number);
+
+ expect(store.selectedEntities.size).toBe(3);
+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity4 as number)).toBe(false);
+ });
+
+ it('selects range in reverse order', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+ const entity3 = store.createEntity('Entity3');
+
+ store.selectRange(entity3 as number, entity1 as number);
+
+ expect(store.selectedEntities.size).toBe(3);
+ expect(store.selectedEntities.has(entity1 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+ expect(store.selectedEntities.has(entity3 as number)).toBe(true);
+ });
+
+ it('clears selection when selecting null', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+
+ store.selectEntity(entity1, 'replace');
+ store.selectEntity(entity2, 'add');
+ expect(store.selectedEntities.size).toBe(2);
+
+ store.selectEntity(null);
+ expect(store.selectedEntities.size).toBe(0);
+ expect(store.selectedEntity).toBeNull();
+ });
+
+ it('clears selection when selecting asset', () => {
+ const entity1 = store.createEntity('Entity1');
+
+ store.selectEntity(entity1, 'replace');
+ expect(store.selectedEntities.size).toBe(1);
+
+ store.selectAsset({ path: 'test.png', type: 'image', name: 'test.png' });
+ expect(store.selectedEntities.size).toBe(0);
+ });
+
+ it('removes deleted entity from selection', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+
+ store.selectEntity(entity1, 'replace');
+ store.selectEntity(entity2, 'add');
+ expect(store.selectedEntities.size).toBe(2);
+
+ store.deleteEntity(entity1);
+ expect(store.selectedEntities.size).toBe(1);
+ expect(store.selectedEntities.has(entity2 as number)).toBe(true);
+ });
+
+ it('deletes all selected entities', () => {
+ const initialCount = store.scene.entities.length;
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+ const entity3 = store.createEntity('Entity3');
+
+ store.selectEntity(entity1, 'replace');
+ store.selectEntity(entity2, 'add');
+
+ expect(store.scene.entities.length).toBe(initialCount + 3);
+ store.deleteSelectedEntities();
+
+ expect(store.scene.entities.length).toBe(initialCount + 1);
+ expect(store.selectedEntities.size).toBe(0);
+ expect(store.scene.entities.find(e => e.id === entity3 as number)).toBeDefined();
+ });
+
+ it('returns single entity for single selection', () => {
+ const entity1 = store.createEntity('Entity1');
+
+ store.selectEntity(entity1, 'replace');
+ expect(store.selectedEntity).toBe(entity1);
+
+ const entityData = store.getSelectedEntityData();
+ expect(entityData).toBeDefined();
+ expect(entityData?.id).toBe(entity1 as number);
+ });
+
+ it('returns null for multi-selection', () => {
+ const entity1 = store.createEntity('Entity1');
+ const entity2 = store.createEntity('Entity2');
+
+ store.selectEntity(entity1, 'replace');
+ store.selectEntity(entity2, 'add');
+
+ expect(store.selectedEntity).toBeNull();
+ expect(store.getSelectedEntityData()).toBeNull();
+
+ const entitiesData = store.getSelectedEntitiesData();
+ expect(entitiesData.length).toBe(2);
+ });
+});
diff --git a/editor/src/__tests__/utils/fuzzy.test.ts b/editor/src/__tests__/utils/fuzzy.test.ts
new file mode 100644
index 000000000..bd106133a
--- /dev/null
+++ b/editor/src/__tests__/utils/fuzzy.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect } from 'vitest';
+import { fuzzyMatch, fuzzyFilter } from '../../utils/fuzzy';
+
+describe('Fuzzy matching', () => {
+ describe('fuzzyMatch', () => {
+ it('should match exact strings', () => {
+ const result = fuzzyMatch('test', 'test');
+ expect(result).not.toBeNull();
+ expect(result!.matches).toEqual([0, 1, 2, 3]);
+ });
+
+ it('should match partial strings', () => {
+ const result = fuzzyMatch('plyr', 'PlayerController');
+ expect(result).not.toBeNull();
+ expect(result!.matches.length).toBe(4);
+ });
+
+ it('should be case insensitive', () => {
+ const result = fuzzyMatch('PC', 'PlayerController');
+ expect(result).not.toBeNull();
+ expect(result!.matches).toEqual([0, 6]);
+ });
+
+ it('should score consecutive matches higher', () => {
+ const consecutive = fuzzyMatch('play', 'PlayerController');
+ const scattered = fuzzyMatch('plyr', 'PlayerController');
+ expect(consecutive!.score).toBeGreaterThan(scattered!.score);
+ });
+
+ it('should score word boundary matches higher', () => {
+ const wordBoundary = fuzzyMatch('pc', 'Player Controller');
+ const middle = fuzzyMatch('pc', 'SpecialCamera');
+ expect(wordBoundary!.score).toBeGreaterThan(middle!.score);
+ });
+
+ it('should score camelCase matches higher', () => {
+ const camelCase = fuzzyMatch('pc', 'PlayerController');
+ const lowercase = fuzzyMatch('pc', 'playercontroller');
+ expect(camelCase!.score).toBeGreaterThan(lowercase!.score);
+ });
+
+ it('should return null for non-matching patterns', () => {
+ const result = fuzzyMatch('xyz', 'PlayerController');
+ expect(result).toBeNull();
+ });
+
+ it('should return null for incomplete patterns', () => {
+ const result = fuzzyMatch('playerz', 'Player');
+ expect(result).toBeNull();
+ });
+
+ it('should handle empty pattern', () => {
+ const result = fuzzyMatch('', 'test');
+ expect(result).toEqual({ score: 0, matches: [] });
+ });
+
+ it('should match underscores as word boundaries', () => {
+ const result = fuzzyMatch('pc', 'player_controller');
+ expect(result).not.toBeNull();
+ expect(result!.matches).toEqual([0, 7]);
+ });
+ });
+
+ describe('fuzzyFilter', () => {
+ interface TestItem {
+ id: number;
+ name: string;
+ }
+
+ const items: TestItem[] = [
+ { id: 1, name: 'PlayerController' },
+ { id: 2, name: 'EnemyController' },
+ { id: 3, name: 'CameraController' },
+ { id: 4, name: 'Player' },
+ { id: 5, name: 'SpecialPlayer' },
+ ];
+
+ it('should filter items by pattern', () => {
+ const results = fuzzyFilter(items, 'play', item => item.name);
+ expect(results.length).toBe(3);
+ expect(results.map(r => r.item.id)).toContain(1);
+ expect(results.map(r => r.item.id)).toContain(4);
+ expect(results.map(r => r.item.id)).toContain(5);
+ });
+
+ it('should sort results by score', () => {
+ const results = fuzzyFilter(items, 'ctrl', item => item.name);
+ expect(results.length).toBeGreaterThan(0);
+ for (let i = 1; i < results.length; i++) {
+ expect(results[i - 1].match.score).toBeGreaterThanOrEqual(results[i].match.score);
+ }
+ });
+
+ it('should return all items for empty pattern', () => {
+ const results = fuzzyFilter(items, '', item => item.name);
+ expect(results.length).toBe(items.length);
+ });
+
+ it('should return empty array for non-matching pattern', () => {
+ const results = fuzzyFilter(items, 'xyz', item => item.name);
+ expect(results.length).toBe(0);
+ });
+
+ it('should handle single character patterns', () => {
+ const results = fuzzyFilter(items, 'p', item => item.name);
+ expect(results.length).toBeGreaterThan(0);
+ });
+ });
+});
diff --git a/editor/src/__tests__/utils/naming.test.ts b/editor/src/__tests__/utils/naming.test.ts
new file mode 100644
index 000000000..798a2a44a
--- /dev/null
+++ b/editor/src/__tests__/utils/naming.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest';
+import { generateUniqueName } from '../../utils/naming';
+
+describe('generateUniqueName', () => {
+ it('should append (1) when base name exists', () => {
+ const existing = new Set(['Entity']);
+ const result = generateUniqueName('Entity', existing);
+ expect(result).toBe('Entity (1)');
+ });
+
+ it('should increment number when numbered name exists', () => {
+ const existing = new Set(['Entity', 'Entity (1)']);
+ const result = generateUniqueName('Entity', existing);
+ expect(result).toBe('Entity (2)');
+ });
+
+ it('should continue from existing number', () => {
+ const existing = new Set(['Entity', 'Entity (1)', 'Entity (2)']);
+ const result = generateUniqueName('Entity (1)', existing);
+ expect(result).toBe('Entity (3)');
+ });
+
+ it('should handle gaps in numbering', () => {
+ const existing = new Set(['Entity', 'Entity (2)']);
+ const result = generateUniqueName('Entity', existing);
+ expect(result).toBe('Entity (1)');
+ });
+
+ it('should handle names with spaces', () => {
+ const existing = new Set(['Player Controller']);
+ const result = generateUniqueName('Player Controller', existing);
+ expect(result).toBe('Player Controller (1)');
+ });
+
+ it('should handle names already with parentheses', () => {
+ const existing = new Set(['Item (Weapon)', 'Item (Weapon) (1)']);
+ const result = generateUniqueName('Item (Weapon)', existing);
+ expect(result).toBe('Item (Weapon) (2)');
+ });
+
+ it('should find next available number in sequence', () => {
+ const existing = new Set([
+ 'Node',
+ 'Node (1)',
+ 'Node (2)',
+ 'Node (3)',
+ 'Node (5)',
+ ]);
+ const result = generateUniqueName('Node', existing);
+ expect(result).toBe('Node (4)');
+ });
+
+ it('should handle empty set', () => {
+ const existing = new Set<string>();
+ const result = generateUniqueName('Entity', existing);
+ expect(result).toBe('Entity (1)');
+ });
+
+ it('should preserve case', () => {
+ const existing = new Set(['MyEntity']);
+ const result = generateUniqueName('MyEntity', existing);
+ expect(result).toBe('MyEntity (1)');
+ });
+});
diff --git a/editor/src/__tests__/utils/path.test.ts b/editor/src/__tests__/utils/path.test.ts
new file mode 100644
index 000000000..61cb64816
--- /dev/null
+++ b/editor/src/__tests__/utils/path.test.ts
@@ -0,0 +1,134 @@
+import { describe, it, expect } from 'vitest';
+import {
+ normalizePath,
+ joinPath,
+ getFileExtension,
+ getDirName,
+ getParentDir,
+ isAbsolutePath,
+} from '../../utils/path';
+
+describe('Path utilities', () => {
+ describe('normalizePath', () => {
+ it('should convert backslashes to forward slashes', () => {
+ expect(normalizePath('assets\\textures\\sprite.png')).toBe('assets/textures/sprite.png');
+ });
+
+ it('should handle mixed slashes', () => {
+ expect(normalizePath('assets/textures\\images/sprite.png')).toBe('assets/textures/images/sprite.png');
+ });
+
+ it('should handle paths with no backslashes', () => {
+ expect(normalizePath('assets/textures/sprite.png')).toBe('assets/textures/sprite.png');
+ });
+ });
+
+ describe('joinPath', () => {
+ it('should join paths correctly', () => {
+ expect(joinPath('assets', 'textures', 'sprite.png')).toBe('assets/textures/sprite.png');
+ });
+
+ it('should handle trailing slashes', () => {
+ expect(joinPath('assets/', 'textures/', 'sprite.png')).toBe('assets/textures/sprite.png');
+ });
+
+ it('should handle leading slashes', () => {
+ expect(joinPath('/assets', 'textures', 'sprite.png')).toBe('/assets/textures/sprite.png');
+ });
+
+ it('should handle multiple slashes', () => {
+ expect(joinPath('assets//', 'textures', 'sprite.png')).toBe('assets/textures/sprite.png');
+ });
+
+ it('should handle empty parts', () => {
+ expect(joinPath('assets', '', 'sprite.png')).toBe('assets/sprite.png');
+ });
+
+ it('should handle single part', () => {
+ expect(joinPath('assets')).toBe('assets');
+ });
+ });
+
+ describe('getFileExtension', () => {
+ it('should extract file extension', () => {
+ expect(getFileExtension('sprite.png')).toBe('png');
+ });
+
+ it('should return lowercase extension', () => {
+ expect(getFileExtension('sprite.PNG')).toBe('png');
+ });
+
+ it('should handle multiple dots', () => {
+ expect(getFileExtension('archive.tar.gz')).toBe('gz');
+ });
+
+ it('should return empty string for no extension', () => {
+ expect(getFileExtension('filename')).toBe('');
+ });
+
+ it('should return empty string for hidden files', () => {
+ expect(getFileExtension('.gitignore')).toBe('');
+ });
+
+ it('should handle paths with directories', () => {
+ expect(getFileExtension('assets/textures/sprite.png')).toBe('png');
+ });
+ });
+
+ describe('getDirName', () => {
+ it('should extract directory name', () => {
+ expect(getDirName('assets/textures/sprite.png')).toBe('assets/textures');
+ });
+
+ it('should handle nested paths', () => {
+ expect(getDirName('a/b/c/d.txt')).toBe('a/b/c');
+ });
+
+ it('should return empty for file in root', () => {
+ expect(getDirName('sprite.png')).toBe('');
+ });
+
+ it('should handle root slash', () => {
+ expect(getDirName('/sprite.png')).toBe('');
+ });
+ });
+
+ describe('getParentDir', () => {
+ it('should extract parent directory', () => {
+ expect(getParentDir('assets/textures/sprites')).toBe('assets/textures');
+ });
+
+ it('should handle file paths', () => {
+ expect(getParentDir('assets/textures/sprite.png')).toBe('assets/textures');
+ });
+
+ it('should normalize backslashes', () => {
+ expect(getParentDir('assets\\textures\\sprite.png')).toBe('assets/textures');
+ });
+
+ it('should handle single directory', () => {
+ expect(getParentDir('assets')).toBe('assets');
+ });
+
+ it('should handle root paths', () => {
+ expect(getParentDir('/assets')).toBe('/assets');
+ });
+ });
+
+ describe('isAbsolutePath', () => {
+ it('should recognize unix absolute paths', () => {
+ expect(isAbsolutePath('/usr/local/bin')).toBe(true);
+ });
+
+ it('should recognize windows absolute paths', () => {
+ expect(isAbsolutePath('C:/Users/test')).toBe(true);
+ expect(isAbsolutePath('D:\\Projects')).toBe(true);
+ });
+
+ it('should recognize relative paths', () => {
+ expect(isAbsolutePath('assets/textures')).toBe(false);
+ expect(isAbsolutePath('./assets')).toBe(false);
+ expect(isAbsolutePath('../assets')).toBe(false);
+ });
+ });
+});
diff --git a/editor/src/asset/AssetDatabase.ts b/editor/src/asset/AssetDatabase.ts
index 06e304dc9..269384461 100644
--- a/editor/src/asset/AssetDatabase.ts
+++ b/editor/src/asset/AssetDatabase.ts
@@ -501,19 +501,11 @@ export class AssetDatabase {
// Component → Asset Reference Field Registry
// =============================================================================
-const COMPONENT_REF_FIELDS = new Map<string, string[]>([
- ['Sprite', ['texture', 'material']],
- ['SpineAnimation', ['skeletonPath', 'atlasPath', 'material']],
- ['BitmapText', ['font']],
- ['UIMask', ['texture']],
-]);
+import { getComponentAssetFields } from 'esengine';
export function getComponentRefFields(componentType: string): string[] | undefined {
- return COMPONENT_REF_FIELDS.get(componentType);
-}
-
-export function registerComponentRefFields(componentType: string, fields: string[]): void {
- COMPONENT_REF_FIELDS.set(componentType, fields);
+ const fields = getComponentAssetFields(componentType);
+ return fields.length > 0 ? fields : undefined;
}
// =============================================================================
diff --git a/editor/src/asset/AssetLibrary.ts b/editor/src/asset/AssetLibrary.ts
index 1071284ac..424892559 100644
--- a/editor/src/asset/AssetLibrary.ts
+++ b/editor/src/asset/AssetLibrary.ts
@@ -12,6 +12,5 @@ export {
resetAssetDatabase,
isUUID,
getComponentRefFields,
- registerComponentRefFields,
type AssetEntry,
} from './AssetDatabase';
diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.ts
index 153ab2b26..487692af9 100644
--- a/editor/src/asset/index.ts
+++ b/editor/src/asset/index.ts
@@ -26,7 +26,6 @@ export {
resetAssetDatabase as resetAssetLibrary,
isUUID,
getComponentRefFields,
- registerComponentRefFields,
type AssetEntry,
} from './AssetDatabase';
diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.ts
index 58b349eb4..a6f7e630b 100644
--- a/editor/src/builder/ArtifactBuilder.ts
+++ b/editor/src/builder/ArtifactBuilder.ts
@@ -11,6 +11,7 @@ import { BuildProgressReporter } from './BuildProgress';
import { AssetExportConfigService, BuildAssetCollector } from './AssetCollector';
import { TextureAtlasPacker } from './TextureAtlas';
import { AssetLibrary, isUUID, getComponentRefFields } from '../asset/AssetLibrary';
+import { BuildCache } from './BuildCache';
import { getAssetType, toAddressableType } from '../asset/AssetTypes';
import { compileMaterials } from './MaterialCompiler';
import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';
@@ -25,7 +26,8 @@ export async function buildArtifact(
fs: NativeFS,
projectDir: string,
config: BuildConfig,
- progress: BuildProgressReporter
+ progress: BuildProgressReporter,
+ buildCache?: BuildCache
): Promise<BuildArtifact> {
const assetLibrary = new AssetLibrary();
await assetLibrary.initialize(projectDir, fs);
@@ -58,13 +60,52 @@ export async function buildArtifact(
}
const packer = new TextureAtlasPacker(fs, projectDir, assetLibrary);
- const atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);
- const packedPaths = new Set<string>(atlasResult.frameMap.keys());
- if (atlasResult.pages.length > 0) {
- progress.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);
+ let atlasResult;
+ let atlasInputHash: string | undefined;
+ if (buildCache) {
+ const cacheData = await buildCache.loadCache(config.id || 'default');
+ atlasInputHash = await buildCache.computeAtlasInputHash(imagePaths);
+
+ let cachedAtlas = null;
+ if (cacheData?.atlasPages) {
+ const deserializedPages = buildCache.deserializeAtlasPages(cacheData.atlasPages);
+ if (deserializedPages) {
+ const frameMap = new Map();
+ deserializedPages.forEach((page, pageIdx) => {
+ page.frames.forEach((frame: any) => {
+ frameMap.set(frame.path, { page: pageIdx, frame });
+ });
+ });
+ cachedAtlas = { pages: deserializedPages, frameMap };
+ }
+ }
+
+ atlasResult = await packer.packIncremental(
+ imagePaths,
+ sceneDataList,
+ cachedAtlas,
+ atlasInputHash,
+ cacheData?.atlasInputHash,
+ 2048,
+ [...assetPaths]
+ );
+
+ if (cachedAtlas && atlasInputHash === cacheData?.atlasInputHash) {
+ progress.log('info', `Reused cached atlas (${atlasResult.frameMap.size} textures)`);
+ } else {
+ progress.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);
+ }
+ } else {
+ atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);
+
+ if (atlasResult.pages.length > 0) {
+ progress.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);
+ }
}
+ const packedPaths = new Set<string>(atlasResult.frameMap.keys());
+
progress.setCurrentTask('Compiling materials...', 20);
const compiledMaterials = await compileMaterials(fs, projectDir, assetLibrary, assetPaths);
progress.log('info', `Compiled ${compiledMaterials.length} material(s)`);
@@ -84,6 +125,7 @@ export async function buildArtifact(
packedPaths,
compiledMaterials,
assetLibrary,
+ atlasInputHash,
};
}
diff --git a/editor/src/builder/BuildCache.ts b/editor/src/builder/BuildCache.ts
index 9c960fb5f..cfac5ed03 100644
--- a/editor/src/builder/BuildCache.ts
+++ b/editor/src/builder/BuildCache.ts
@@ -17,6 +17,19 @@ export interface FileHash {
size: number;
}
+export interface AtlasPageCache {
+ imageData: string;
+ width: number;
+ height: number;
+ frames: Array<{
+ path: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ }>;
+}
+
export interface BuildCacheData {
version: string;
configId: string;
@@ -24,6 +37,8 @@ export interface BuildCacheData {
files: Record<string, FileHash>;
compiledScripts?: string;
compiledScriptsHash?: string;
+ atlasPages?: AtlasPageCache[];
+ atlasInputHash?: string;
}
export interface FileChangeResult {
@@ -37,7 +52,7 @@ export interface FileChangeResult {
// Constants
// =============================================================================
-const CACHE_VERSION = '1.2';
+const CACHE_VERSION = '1.3';
const CACHE_DIR = '.esengine/build-cache';
// =============================================================================
@@ -252,6 +267,33 @@ export class BuildCache {
// Cache directory may not exist
}
}
+
+ async computeAtlasInputHash(imagePaths: string[]): Promise<string> {
+ const sorted = [...imagePaths].sort();
+ return computeHash(JSON.stringify(sorted));
+ }
+
+ serializeAtlasPages(pages: any[]): AtlasPageCache[] {
+ return pages.map(page => ({
+ imageData: Buffer.from(page.imageData).toString('base64'),
+ width: page.width,
+ height: page.height,
+ frames: page.frames,
+ }));
+ }
+
+ deserializeAtlasPages(cached: AtlasPageCache[] | undefined): any[] | null {
+ if (!cached) return null;
+
+ try {
+ return cached.map(p => ({
+ ...p,
+ imageData: Uint8Array.from(Buffer.from(p.imageData, 'base64')),
+ }));
+ } catch {
+ return null;
+ }
+ }
}
export { computeHash };
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
index 80a7ab0cf..4d374df7e 100644
--- a/editor/src/builder/BuildService.ts
+++ b/editor/src/builder/BuildService.ts
@@ -100,7 +100,7 @@ export class BuildService {
}
const projectDir = getProjectDir(this.projectPath_);
- const artifact = await buildArtifact(fs, projectDir, config, progress);
+ const artifact = await buildArtifact(fs, projectDir, config, progress, context.cache);
let emitter: PlatformEmitter;
if (config.platform === 'playable') {
@@ -124,6 +124,20 @@ export class BuildService {
progress.complete();
progress.log('info', `Build completed in ${formatDuration(duration)}`);
+ if (useCache && artifact.atlasInputHash) {
+ const cacheData = await this.cache_.loadCache(config.id || 'default') || {
+ version: '1.3',
+ configId: config.id || 'default',
+ timestamp: Date.now(),
+ files: {},
+ };
+
+ cacheData.atlasPages = this.cache_.serializeAtlasPages(artifact.atlasResult.pages);
+ cacheData.atlasInputHash = artifact.atlasInputHash;
+
+ await this.cache_.saveCache(cacheData);
+ }
+
if (this.history_) {
this.history_.addEntry({
configId: config.id,
diff --git a/editor/src/builder/PlatformEmitter.ts b/editor/src/builder/PlatformEmitter.ts
index 9a83eaf3b..6a4b4755f 100644
--- a/editor/src/builder/PlatformEmitter.ts
+++ b/editor/src/builder/PlatformEmitter.ts
@@ -19,6 +19,7 @@ export interface BuildArtifact {
packedPaths: Set<string>;
compiledMaterials: CompiledMaterial[];
assetLibrary: AssetDatabase;
+ atlasInputHash?: string;
}
export interface PlatformEmitter {
diff --git a/editor/src/builder/TextureAtlas.ts b/editor/src/builder/TextureAtlas.ts
index 45972faae..38c17ea5c 100644
--- a/editor/src/builder/TextureAtlas.ts
+++ b/editor/src/builder/TextureAtlas.ts
@@ -294,6 +294,22 @@ export class TextureAtlasPacker {
return result;
}
+ async packIncremental(
+ imagePaths: string[],
+ sceneDataList: Array<{ name: string; data: Record<string, unknown> }>,
+ cached: AtlasResult | null,
+ currentInputHash: string,
+ cachedInputHash: string | undefined,
+ maxSize: number = 2048,
+ allAssetPaths?: string[]
+ ): Promise<AtlasResult> {
+ if (cached && cachedInputHash && currentInputHash === cachedInputHash) {
+ return cached;
+ }
+
+ return this.pack(imagePaths, sceneDataList, maxSize, allAssetPaths);
+ }
+
rewriteSceneData(
sceneData: Record<string, unknown>,
atlasResult: AtlasResult,
diff --git a/editor/src/error/ErrorBoundary.ts b/editor/src/error/ErrorBoundary.ts
new file mode 100644
index 000000000..ab66994e1
--- /dev/null
+++ b/editor/src/error/ErrorBoundary.ts
@@ -0,0 +1,74 @@
+export interface ErrorBoundaryOptions {
+ fallback: (error: Error) => HTMLElement;
+ onError?: (error: Error, errorInfo: string) => void;
+ isolate?: boolean;
+}
+
+export class ErrorBoundary {
+ private element_: HTMLElement;
+ private contentContainer_: HTMLElement;
+ private hasError_ = false;
+
+ constructor(
+ private container_: HTMLElement,
+ private options_: ErrorBoundaryOptions
+ ) {
+ this.element_ = document.createElement('div');
+ this.element_.className = 'es-error-boundary';
+
+ this.contentContainer_ = document.createElement('div');
+ this.contentContainer_.className = 'es-error-boundary-content';
+ this.element_.appendChild(this.contentContainer_);
+
+ this.container_.appendChild(this.element_);
+ }
+
+ wrap<T extends (...args: any[]) => any>(fn: T): T {
+ return ((...args: any[]) => {
+ try {
+ const result = fn(...args);
+
+ if (result instanceof Promise) {
+ return result.catch((error) => this.handleError(error));
+ }
+
+ return result;
+ } catch (error) {
+ this.handleError(error as Error);
+ }
+ }) as T;
+ }
+
+ private handleError(error: Error): void {
+ if (this.hasError_) return;
+
+ this.hasError_ = true;
+
+ this.options_.onError?.(error, this.getErrorInfo());
+
+ this.contentContainer_.innerHTML = '';
+ const fallback = this.options_.fallback(error);
+ this.contentContainer_.appendChild(fallback);
+
+ if (!this.options_.isolate) {
+ throw error;
+ }
+ }
+
+ private getErrorInfo(): string {
+ return new Error().stack ?? 'No stack trace available';
+ }
+
+ reset(): void {
+ this.hasError_ = false;
+ this.contentContainer_.innerHTML = '';
+ }
+
+ render(renderFn: () => void): void {
+ this.wrap(renderFn)();
+ }
+
+ getContainer(): HTMLElement {
+ return this.contentContainer_;
+ }
+}
diff --git a/editor/src/error/ErrorFallback.ts b/editor/src/error/ErrorFallback.ts
new file mode 100644
index 000000000..bcbbe5c88
--- /dev/null
+++ b/editor/src/error/ErrorFallback.ts
@@ -0,0 +1,36 @@
+import { icons } from '../utils/icons';
+
+export function createErrorFallback(error: Error): HTMLElement {
+ const container = document.createElement('div');
+ container.className = 'es-error-fallback';
+ container.innerHTML = `
+ <div class="es-error-fallback-icon">${icons.x(48)}</div>
+ <h3 class="es-error-fallback-title">Something went wrong</h3>
+ <p class="es-error-fallback-message">${escapeHtml(error.message)}</p>
+ <details class="es-error-fallback-details">
+ <summary>Error details</summary>
+ <pre class="es-error-fallback-stack">${escapeHtml(error.stack ?? 'No stack trace')}</pre>
+ </details>
+ <div class="es-error-fallback-actions">
+ <button class="es-btn es-btn-primary" data-action="reload">Reload Panel</button>
+ <button class="es-btn" data-action="report">Report Issue</button>
+ </div>
+ `;
+
+ container.querySelector('[data-action="reload"]')?.addEventListener('click', () => {
+ window.location.reload();
+ });
+
+ container.querySelector('[data-action="report"]')?.addEventListener('click', () => {
+ const issueUrl = `https://github.com/esengine/esengine/issues/new?template=bug_report.md&title=${encodeURIComponent('Editor Error: ' + error.message)}`;
+ window.open(issueUrl, '_blank');
+ });
+
+ return container;
+}
+
+function escapeHtml(text: string): string {
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
diff --git a/editor/src/error/GlobalErrorHandler.ts b/editor/src/error/GlobalErrorHandler.ts
new file mode 100644
index 000000000..042463868
--- /dev/null
+++ b/editor/src/error/GlobalErrorHandler.ts
@@ -0,0 +1,17 @@
+import { showErrorToast } from '../ui/Toast';
+
+export function installGlobalErrorHandler(): void {
+ window.addEventListener('error', (event) => {
+ handleError(event.error || new Error(event.message));
+ event.preventDefault();
+ });
+
+ window.addEventListener('unhandledrejection', (event) => {
+ handleError(event.reason instanceof Error ? event.reason : new Error(String(event.reason)));
+ event.preventDefault();
+ });
+}
+
+function handleError(error: Error): void {
+ showErrorToast('An unexpected error occurred. Check console for details.');
+}
diff --git a/editor/src/error/index.ts b/editor/src/error/index.ts
new file mode 100644
index 000000000..fcc026055
--- /dev/null
+++ b/editor/src/error/index.ts
@@ -0,0 +1,4 @@
+export { ErrorBoundary } from './ErrorBoundary';
+export type { ErrorBoundaryOptions } from './ErrorBoundary';
+export { createErrorFallback } from './ErrorFallback';
+export { installGlobalErrorHandler } from './GlobalErrorHandler';
diff --git a/editor/src/gizmos/ColliderOverlay.ts b/editor/src/gizmos/ColliderOverlay.ts
index 5f3adf309..d0bbbd26e 100644
--- a/editor/src/gizmos/ColliderOverlay.ts
+++ b/editor/src/gizmos/ColliderOverlay.ts
@@ -38,19 +38,18 @@ export class ColliderOverlay {
drawAll(octx: OverlayContext): void {
const { ctx, store } = octx;
- const selected = store.selectedEntity;
+ const selectedIds = store.selectedEntities;
for (const entity of store.scene.entities) {
if (!store.isEntityVisible(entity.id)) continue;
- const isSelected = entity.id === selected;
+ const isSelected = selectedIds.has(entity.id);
this.drawEntityColliders(octx, entity, isSelected);
}
}
hitTest(worldX: number, worldY: number, octx: OverlayContext): boolean {
const { store } = octx;
- const selected = store.selectedEntity;
- if (selected === null) return false;
+ if (store.selectedEntities.size === 0) return false;
const entityData = store.getSelectedEntityData();
if (!entityData) return false;
diff --git a/editor/src/index.ts b/editor/src/index.ts
index 2552a407d..5d428f1e3 100644
--- a/editor/src/index.ts
+++ b/editor/src/index.ts
@@ -9,6 +9,20 @@
export { Editor, createEditor } from './Editor';
+// =============================================================================
+// Error Handling
+// =============================================================================
+
+export { ErrorBoundary, createErrorFallback, installGlobalErrorHandler } from './error';
+export type { ErrorBoundaryOptions } from './error';
+
+// =============================================================================
+// Logging
+// =============================================================================
+
+export { EditorLogger, createConsoleHandler, createToastHandler } from './logging';
+export type { LogLevel, LogEntry, LogHandler } from './logging';
+
// =============================================================================
// Types
// =============================================================================
diff --git a/editor/src/logging/EditorLogger.ts b/editor/src/logging/EditorLogger.ts
new file mode 100644
index 000000000..b4a381e93
--- /dev/null
+++ b/editor/src/logging/EditorLogger.ts
@@ -0,0 +1,122 @@
+/**
+ * @file EditorLogger.ts
+ * @brief Centralized logging system for editor
+ */
+
+export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
+
+export interface LogEntry {
+ level: LogLevel;
+ message: string;
+ timestamp: number;
+ context?: string;
+ data?: unknown;
+}
+
+export type LogHandler = (entry: LogEntry) => void;
+
+class EditorLoggerImpl {
+ private handlers_: Set<LogHandler> = new Set();
+ private minLevel_: LogLevel = 'info';
+ private context_: string | null = null;
+
+ private levelPriority: Record<LogLevel, number> = {
+ debug: 0,
+ info: 1,
+ warn: 2,
+ error: 3,
+ };
+
+ setMinLevel(level: LogLevel): void {
+ this.minLevel_ = level;
+ }
+
+ setContext(context: string | null): void {
+ this.context_ = context;
+ }
+
+ addHandler(handler: LogHandler): () => void {
+ this.handlers_.add(handler);
+ return () => this.handlers_.delete(handler);
+ }
+
+ removeHandler(handler: LogHandler): void {
+ this.handlers_.delete(handler);
+ }
+
+ clearHandlers(): void {
+ this.handlers_.clear();
+ }
+
+ debug(message: string, data?: unknown): void {
+ this.log('debug', message, data);
+ }
+
+ info(message: string, data?: unknown): void {
+ this.log('info', message, data);
+ }
+
+ warn(message: string, data?: unknown): void {
+ this.log('warn', message, data);
+ }
+
+ error(message: string, data?: unknown): void {
+ this.log('error', message, data);
+ }
+
+ private log(level: LogLevel, message: string, data?: unknown): void {
+ if (this.levelPriority[level] < this.levelPriority[this.minLevel_]) {
+ return;
+ }
+
+ const entry: LogEntry = {
+ level,
+ message,
+ timestamp: Date.now(),
+ context: this.context_ ?? undefined,
+ data,
+ };
+
+ for (const handler of this.handlers_) {
+ try {
+ handler(entry);
+ } catch (err) {
+ console.error('[EditorLogger] Handler error:', err);
+ }
+ }
+ }
+}
+
+export const EditorLogger = new EditorLoggerImpl();
+
+export function createConsoleHandler(): LogHandler {
+ return (entry: LogEntry) => {
+ const prefix = entry.context ? `[${entry.context}]` : '';
+ const message = `${prefix} ${entry.message}`;
+
+ switch (entry.level) {
+ case 'debug':
+ console.debug(message, entry.data ?? '');
+ break;
+ case 'info':
+ console.log(message, entry.data ?? '');
+ break;
+ case 'warn':
+ console.warn(message, entry.data ?? '');
+ break;
+ case 'error':
+ console.error(message, entry.data ?? '');
+ break;
+ }
+ };
+}
+
+export function createToastHandler(showToast: (message: string, type: 'info' | 'warning' | 'error') => void): LogHandler {
+ return (entry: LogEntry) => {
+ if (entry.level === 'error') {
+ showToast(entry.message, 'error');
+ } else if (entry.level === 'warn') {
+ showToast(entry.message, 'warning');
+ }
+ };
+}
diff --git a/editor/src/logging/index.ts b/editor/src/logging/index.ts
new file mode 100644
index 000000000..df799fe04
--- /dev/null
+++ b/editor/src/logging/index.ts
@@ -0,0 +1,13 @@
+/**
+ * @file index.ts
+ * @brief Logging module exports
+ */
+
+export {
+ EditorLogger,
+ createConsoleHandler,
+ createToastHandler,
+ type LogLevel,
+ type LogEntry,
+ type LogHandler,
+} from './EditorLogger';
diff --git a/editor/src/menus/builtinMenus.ts b/editor/src/menus/builtinMenus.ts
index b04546f48..3b5272972 100644
--- a/editor/src/menus/builtinMenus.ts
+++ b/editor/src/menus/builtinMenus.ts
@@ -1,6 +1,7 @@
import { registerMenu, registerMenuItem } from './MenuRegistry';
import type { Editor } from '../Editor';
import { getEditorContext } from '../context/EditorContext';
+import type { Entity } from 'esengine';
export function registerBuiltinMenus(editor: Editor): void {
registerMenu({ id: 'file', label: 'File', order: 0 });
@@ -54,10 +55,14 @@ export function registerBuiltinMenus(editor: Editor): void {
registerMenuItem({
id: 'edit.delete', menu: 'edit', label: 'Delete',
shortcut: 'Delete', order: 2, separator: true,
- enabled: () => editor.store.selectedEntity !== null,
+ enabled: () => editor.store.selectedEntities.size > 0,
action: () => {
- const selected = editor.store.selectedEntity;
- if (selected !== null) editor.store.deleteEntity(selected);
+ if (editor.store.selectedEntities.size === 1) {
+ const id = Array.from(editor.store.selectedEntities)[0];
+ editor.store.deleteEntity(id as Entity);
+ } else if (editor.store.selectedEntities.size > 1) {
+ editor.store.deleteSelectedEntities();
+ }
},
});
registerMenuItem({
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index a9f8d0277..232ec9ae5 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -18,6 +18,7 @@ import { generateUniqueName } from '../utils/naming';
import { showInputDialog } from '../ui/dialog';
import { joinPath, getParentDir } from '../utils/path';
import { hasAnyOverrides } from '../prefab';
+import { fuzzyFilter, type FuzzyMatch } from '../utils/fuzzy';
type DropPosition = 'before' | 'after' | 'inside';
@@ -44,6 +45,8 @@ export class HierarchyPanel {
private prefabEditBar_: HTMLElement | null = null;
private unsubscribe_: (() => void) | null = null;
private searchFilter_: string = '';
+ private searchResults_: Array<{ entity: EntityData; match: FuzzyMatch }> = [];
+ private selectedResultIndex_: number = -1;
private expandedIds_: Set<number> = new Set();
private lastSelectedEntity_: Entity | null = null;
private flatRows_: FlattenedRow[] = [];
@@ -130,10 +133,26 @@ export class HierarchyPanel {
});
this.searchInput_?.addEventListener('input', () => {
- this.searchFilter_ = this.searchInput_?.value.toLowerCase() ?? '';
+ this.searchFilter_ = this.searchInput_?.value ?? '';
+ this.performSearch();
this.render();
});
+ this.searchInput_?.addEventListener('keydown', (e) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ this.selectNextResult();
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ this.selectPreviousResult();
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ this.focusSelectedResult();
+ } else if (e.key === 'Escape') {
+ this.clearSearch();
+ }
+ });
+
this.treeContainer_.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
@@ -172,7 +191,16 @@ export class HierarchyPanel {
const entityId = parseInt(item.dataset.entityId ?? '', 10);
if (isNaN(entityId)) return;
- this.store_.selectEntity(entityId as Entity);
+ if (e.shiftKey && this.lastSelectedEntity_ !== null) {
+ this.store_.selectRange(this.lastSelectedEntity_ as number, entityId);
+ this.lastSelectedEntity_ = entityId as Entity;
+ } else if (e.ctrlKey || e.metaKey) {
+ this.store_.selectEntity(entityId as Entity, 'toggle');
+ this.lastSelectedEntity_ = entityId as Entity;
+ } else {
+ this.store_.selectEntity(entityId as Entity, 'replace');
+ this.lastSelectedEntity_ = entityId as Entity;
+ }
});
this.treeContainer_.addEventListener('dblclick', (e) => {
@@ -521,8 +549,13 @@ export class HierarchyPanel {
this.renderVisibleRows();
if (this.footerContainer_) {
- const count = scene.entities.length;
- this.footerContainer_.textContent = `${count} ${count === 1 ? 'entity' : 'entities'}`;
+ if (this.searchFilter_) {
+ const count = this.searchResults_.length;
+ this.footerContainer_.textContent = `${count} ${count === 1 ? 'match' : 'matches'}`;
+ } else {
+ const count = scene.entities.length;
+ this.footerContainer_.textContent = `${count} ${count === 1 ? 'entity' : 'entities'}`;
+ }
}
if (selectionChanged) {
@@ -567,15 +600,65 @@ export class HierarchyPanel {
return 'Entity';
}
+ private performSearch(): void {
+ if (!this.searchFilter_) {
+ this.searchResults_ = [];
+ this.selectedResultIndex_ = -1;
+ return;
+ }
+
+ const scene = this.store_.scene;
+ const results = fuzzyFilter(
+ scene.entities,
+ this.searchFilter_,
+ (entity) => entity.name
+ );
+
+ this.searchResults_ = results.map(r => ({ entity: r.item, match: r.match }));
+ this.selectedResultIndex_ = this.searchResults_.length > 0 ? 0 : -1;
+ }
+
+ private selectNextResult(): void {
+ if (this.searchResults_.length === 0) return;
+ this.selectedResultIndex_ = (this.selectedResultIndex_ + 1) % this.searchResults_.length;
+ this.render();
+ }
+
+ private selectPreviousResult(): void {
+ if (this.searchResults_.length === 0) return;
+ this.selectedResultIndex_ = (this.selectedResultIndex_ - 1 + this.searchResults_.length) % this.searchResults_.length;
+ this.render();
+ }
+
+ private focusSelectedResult(): void {
+ if (this.selectedResultIndex_ === -1 || this.selectedResultIndex_ >= this.searchResults_.length) return;
+ const result = this.searchResults_[this.selectedResultIndex_];
+ this.store_.selectEntity(result.entity.id as Entity);
+ this.scrollToEntity(result.entity.id);
+ }
+
+ private clearSearch(): void {
+ if (this.searchInput_) {
+ this.searchInput_.value = '';
+ }
+ this.searchFilter_ = '';
+ this.searchResults_ = [];
+ this.selectedResultIndex_ = -1;
+ this.render();
+ }
+
private buildFlatRows(): void {
this.flatRows_ = [];
const scene = this.store_.scene;
if (this.searchFilter_) {
- for (const entity of scene.entities) {
- if (entity.name.toLowerCase().includes(this.searchFilter_)) {
- this.flatRows_.push({ entity, depth: 0, hasChildren: false, isExpanded: false });
- }
+ for (const result of this.searchResults_) {
+ this.flatRows_.push({
+ entity: result.entity,
+ depth: 0,
+ hasChildren: false,
+ isExpanded: false,
+ });
}
return;
}
@@ -636,7 +719,7 @@ export class HierarchyPanel {
const visibilityIcon = isVisible ? icons.eye(10) : icons.eyeOff(10);
let itemClass = 'es-hierarchy-item';
- if (entity.id === selectedEntity) itemClass += ' es-selected';
+ if (this.store_.selectedEntities.has(entity.id)) itemClass += ' es-selected';
if (!isVisible) itemClass += ' es-entity-hidden';
if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';
else if (entity.prefab) itemClass += ' es-prefab-child';
@@ -651,17 +734,43 @@ export class HierarchyPanel {
}
}
+ const match = this.searchFilter_ ? this.searchResults_.find(r => r.entity.id === entity.id)?.match : null;
+ if (this.searchFilter_ && match) {
+ const resultIdx = this.searchResults_.findIndex(r => r.entity.id === entity.id);
+ if (resultIdx === this.selectedResultIndex_) {
+ itemClass += ' es-search-selected';
+ }
+ }
+
+ const nameHtml = this.renderEntityName(entity.name, match);
+
return `<div class="${itemClass}" data-entity-id="${entity.id}">
<div class="es-hierarchy-row" draggable="true" style="padding-left: ${8 + depth * 16}px">
${hasChildren ? `<span class="es-hierarchy-expand">${expandIcon}</span>` : '<span class="es-hierarchy-spacer"></span>'}
<span class="es-hierarchy-visibility">${visibilityIcon}</span>
<span class="es-hierarchy-icon">${icon}</span>
- <span class="es-hierarchy-name">${this.escapeHtml(entity.name)}</span>
+ <span class="es-hierarchy-name">${nameHtml}</span>
<span class="es-hierarchy-type">${type}</span>
</div>
</div>`;
}
+ private renderEntityName(name: string, match: FuzzyMatch | null | undefined): string {
+ if (!match || match.matches.length === 0) {
+ return this.escapeHtml(name);
+ }
+
+ let html = '';
+ for (let i = 0; i < name.length; i++) {
+ if (match.matches.includes(i)) {
+ html += `<mark class="es-search-highlight">${this.escapeHtml(name[i])}</mark>`;
+ } else {
+ html += this.escapeHtml(name[i]);
+ }
+ }
+ return html;
+ }
+
private scrollToEntity(entityId: number): void {
const index = this.flatRows_.findIndex(r => r.entity.id === entityId);
if (index === -1) return;
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 875a683fe..a2a1cc3bf 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -123,11 +123,13 @@ export class InspectorPanel {
return;
}
- const entity = this.store_.selectedEntity;
+ const selectedEntities = Array.from(this.store_.selectedEntities);
const asset = this.store_.selectedAsset;
- if (entity !== null) {
- this.renderEntityInspector(entity);
+ if (selectedEntities.length === 1) {
+ this.renderEntityInspector(selectedEntities[0] as Entity);
+ } else if (selectedEntities.length > 1) {
+ this.renderMultiEntityInspector(selectedEntities as Entity[]);
} else if (asset !== null) {
this.renderAssetInspector(asset);
} else {
@@ -209,6 +211,25 @@ export class InspectorPanel {
}
}
+ private renderMultiEntityInspector(entities: Entity[]): void {
+ this.currentEntity_ = null;
+ this.currentAssetPath_ = null;
+ this.currentComponentCount_ = 0;
+ this.disposeEditors();
+ this.cleanupImageUrl();
+ this.contentContainer_.innerHTML = '';
+
+ const header = document.createElement('div');
+ header.className = 'es-inspector-multi-header';
+ header.innerHTML = `
+ <h3>${icons.layers(16)} Multi-Selection</h3>
+ <p>${entities.length} entities selected</p>
+ `;
+ this.contentContainer_.appendChild(header);
+
+ this.updateFooter(`${entities.length} entities selected`);
+ }
+
// =========================================================================
// Asset Inspector
// =========================================================================
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index 9a843239c..b82dc2f2b 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -602,8 +602,9 @@ export class SceneViewPanel {
const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);
- if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null &&
- this.store_.isEntityVisible(this.store_.selectedEntity as number)) {
+ const hasSelection = this.store_.selectedEntities.size > 0;
+
+ if (this.gizmoManager_.getActiveId() !== 'select' && hasSelection) {
this.updateGizmoContext();
if (this.gizmoManager_.onMouseDown(worldX, worldY)) {
this.startDocumentDrag();
@@ -611,7 +612,7 @@ export class SceneViewPanel {
}
}
- if (getSettingsValue<boolean>('scene.showColliders') && this.store_.selectedEntity !== null) {
+ if (getSettingsValue<boolean>('scene.showColliders') && hasSelection) {
const octx = this.createOverlayContext();
if (octx && this.colliderOverlay_.onDragStart(worldX, worldY, octx)) {
this.startDocumentDrag();
@@ -681,13 +682,15 @@ export class SceneViewPanel {
return;
}
- if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null) {
+ const hasSelection = this.store_.selectedEntities.size > 0;
+
+ if (this.gizmoManager_.getActiveId() !== 'select' && hasSelection) {
this.updateGizmoContext();
this.gizmoManager_.onMouseMove(worldX, worldY);
this.canvas_.style.cursor = this.gizmoManager_.getCursor();
}
- if (getSettingsValue<boolean>('scene.showColliders') && this.store_.selectedEntity !== null) {
+ if (getSettingsValue<boolean>('scene.showColliders') && hasSelection) {
const octx = this.createOverlayContext();
if (octx) {
this.colliderOverlay_.hitTest(worldX, worldY, octx);
@@ -744,7 +747,9 @@ export class SceneViewPanel {
const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);
- if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null) {
+ const hasSelection = this.store_.selectedEntities.size > 0;
+
+ if (this.gizmoManager_.getActiveId() !== 'select' && hasSelection) {
this.updateGizmoContext();
const result = this.gizmoManager_.hitTest(worldX, worldY);
if (result.hit) return;
@@ -931,9 +936,9 @@ export class SceneViewPanel {
});
}
- const selectedEntity = this.store_.selectedEntity;
+ const hasSelection = this.store_.selectedEntities.size > 0;
- if (selectedEntity !== null && this.store_.isEntityVisible(selectedEntity as number)) {
+ if (hasSelection) {
if (getSettingsValue<boolean>('scene.showSelectionBox')) {
this.drawSelectionBox(ctx);
}
@@ -959,43 +964,48 @@ export class SceneViewPanel {
}
private drawSelectionBox(ctx: CanvasRenderingContext2D): void {
- const entityData = this.store_.getSelectedEntityData();
- if (!entityData) return;
+ const selectedEntities = this.store_.getSelectedEntitiesData();
- const transform = entityData.components.find(c => c.type === 'LocalTransform');
- if (!transform) return;
+ for (const entityData of selectedEntities) {
+ if (!this.store_.isEntityVisible(entityData.id)) continue;
- const worldTransform = this.store_.getWorldTransform(entityData.id);
- const pos = worldTransform.position;
- const scale = worldTransform.scale;
+ const transform = entityData.components.find(c => c.type === 'LocalTransform');
+ if (!transform) continue;
- const bounds = this.getEntityBoundsWithSpine(entityData);
- const w = bounds.width * Math.abs(scale.x);
- const h = bounds.height * Math.abs(scale.y);
- const offsetX = (bounds.offsetX ?? 0) * scale.x;
- const offsetY = (bounds.offsetY ?? 0) * scale.y;
+ const worldTransform = this.store_.getWorldTransform(entityData.id);
+ const pos = worldTransform.position;
+ const scale = worldTransform.scale;
- ctx.save();
- ctx.translate(pos.x + offsetX, -pos.y - offsetY);
+ const bounds = this.getEntityBoundsWithSpine(entityData);
+ const w = bounds.width * Math.abs(scale.x);
+ const h = bounds.height * Math.abs(scale.y);
+ const offsetX = (bounds.offsetX ?? 0) * scale.x;
+ const offsetY = (bounds.offsetY ?? 0) * scale.y;
- ctx.strokeStyle = '#00aaff';
- ctx.lineWidth = 2 / this.zoom_;
- ctx.setLineDash([]);
- ctx.strokeRect(-w / 2, -h / 2, w, h);
-
- ctx.fillStyle = '#00aaff';
- const handleSize = 6 / this.zoom_;
- const corners = [
- [-w / 2, -h / 2],
- [w / 2, -h / 2],
- [-w / 2, h / 2],
- [w / 2, h / 2],
- ];
- for (const [cx, cy] of corners) {
- ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);
- }
+ ctx.save();
+ ctx.translate(pos.x + offsetX, -pos.y - offsetY);
- ctx.restore();
+ ctx.strokeStyle = '#00aaff';
+ ctx.lineWidth = 2 / this.zoom_;
+ ctx.setLineDash([]);
+ ctx.strokeRect(-w / 2, -h / 2, w, h);
+
+ if (selectedEntities.length === 1) {
+ ctx.fillStyle = '#00aaff';
+ const handleSize = 6 / this.zoom_;
+ const corners = [
+ [-w / 2, -h / 2],
+ [w / 2, -h / 2],
+ [-w / 2, h / 2],
+ [w / 2, h / 2],
+ ];
+ for (const [cx, cy] of corners) {
+ ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);
+ }
+ }
+
+ ctx.restore();
+ }
}
private drawCameraFrustums(ctx: CanvasRenderingContext2D): void {
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index faf6f4aee..cae79c271 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -16,6 +16,7 @@ import { INVALID_TEXTURE, getAssetMimeType, getAssetTypeEntry } from 'esengine';
import { createUIRectEditor } from './uiRectEditor';
import { createButtonTransitionEditor } from './buttonTransitionEditor';
import { setupDragLabel, colorToHex, hexToColor } from './editorUtils';
+import { validateNumber, validateVec2, validateVec3, validateColor, showValidationError } from './validation';
export { setupDragLabel, colorToHex, hexToColor };
// =============================================================================
@@ -47,14 +48,21 @@ function createNumberEditor(
const step = meta.step ?? 1;
- input.addEventListener('change', () => {
- onChange(parseFloat(input.value) || 0);
- });
+ const handleChange = () => {
+ const result = validateNumber(input.value, meta);
+ if (!result.valid) {
+ showValidationError(input, result.error!);
+ input.value = String(result.value);
+ }
+ onChange(result.value);
+ };
+
+ input.addEventListener('change', handleChange);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
input.blur();
- onChange(parseFloat(input.value) || 0);
+ handleChange();
}
});
@@ -174,16 +182,25 @@ function createVec2Editor(
input.step = '0.01';
input.value = String(currentVec[keys[i]]);
- input.addEventListener('change', () => {
- currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };
+ const handleChange = () => {
+ const updatedVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };
+ const result = validateVec2(updatedVec, ctx.meta);
+ if (!result.valid) {
+ showValidationError(input, result.error!);
+ currentVec = result.value as Vec2;
+ input.value = String(currentVec[keys[i]]);
+ } else {
+ currentVec = updatedVec;
+ }
onChange(currentVec);
- });
+ };
+
+ input.addEventListener('change', handleChange);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
input.blur();
- currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };
- onChange(currentVec);
+ handleChange();
}
});
@@ -251,16 +268,25 @@ function createVec3Editor(
input.step = '0.01';
input.value = String(currentVec[keys[i]]);
- input.addEventListener('change', () => {
- currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };
+ const handleChange = () => {
+ const updatedVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };
+ const result = validateVec3(updatedVec, ctx.meta);
+ if (!result.valid) {
+ showValidationError(input, result.error!);
+ currentVec = result.value as Vec3;
+ input.value = String(currentVec[keys[i]]);
+ } else {
+ currentVec = updatedVec;
+ }
onChange(currentVec);
- });
+ };
+
+ input.addEventListener('change', handleChange);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
input.blur();
- currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };
- onChange(currentVec);
+ handleChange();
}
});
diff --git a/editor/src/property/validation.ts b/editor/src/property/validation.ts
new file mode 100644
index 000000000..05269c27f
--- /dev/null
+++ b/editor/src/property/validation.ts
@@ -0,0 +1,186 @@
+/**
+ * @file validation.ts
+ * @brief Property value validation utilities
+ */
+
+import type { PropertyMeta } from './PropertyEditor';
+
+export interface ValidationResult {
+ valid: boolean;
+ value: unknown;
+ error?: string;
+}
+
+export function validateNumber(value: unknown, meta: PropertyMeta): ValidationResult {
+ const num = typeof value === 'number' ? value : parseFloat(String(value));
+
+ if (isNaN(num)) {
+ return {
+ valid: false,
+ value: meta.min ?? 0,
+ error: 'Value must be a number'
+ };
+ }
+
+ if (meta.min !== undefined && num < meta.min) {
+ return {
+ valid: false,
+ value: meta.min,
+ error: `Value must be at least ${meta.min}`
+ };
+ }
+
+ if (meta.max !== undefined && num > meta.max) {
+ return {
+ valid: false,
+ value: meta.max,
+ error: `Value must be at most ${meta.max}`
+ };
+ }
+
+ return { valid: true, value: num };
+}
+
+export function validateString(value: unknown, meta: PropertyMeta): ValidationResult {
+ const str = String(value ?? '');
+ return { valid: true, value: str };
+}
+
+export function validateBoolean(value: unknown, meta: PropertyMeta): ValidationResult {
+ return { valid: true, value: Boolean(value) };
+}
+
+export function validateEnum(value: unknown, meta: PropertyMeta): ValidationResult {
+ if (!meta.options || meta.options.length === 0) {
+ return { valid: true, value };
+ }
+
+ const validValues = meta.options.map(opt => opt.value);
+ const isValid = validValues.some(v => v === value);
+
+ if (!isValid) {
+ return {
+ valid: false,
+ value: meta.options[0].value,
+ error: 'Invalid option selected'
+ };
+ }
+
+ return { valid: true, value };
+}
+
+export function validateVec2(value: unknown, meta: PropertyMeta): ValidationResult {
+ if (!value || typeof value !== 'object') {
+ return {
+ valid: false,
+ value: { x: 0, y: 0 },
+ error: 'Value must be a Vec2 object'
+ };
+ }
+
+ const vec = value as { x: number; y: number };
+ const xResult = validateNumber(vec.x, { ...meta, name: 'x' });
+ const yResult = validateNumber(vec.y, { ...meta, name: 'y' });
+
+ if (!xResult.valid || !yResult.valid) {
+ return {
+ valid: false,
+ value: { x: xResult.value as number, y: yResult.value as number },
+ error: xResult.error || yResult.error
+ };
+ }
+
+ return { valid: true, value: { x: xResult.value, y: yResult.value } };
+}
+
+export function validateVec3(value: unknown, meta: PropertyMeta): ValidationResult {
+ if (!value || typeof value !== 'object') {
+ return {
+ valid: false,
+ value: { x: 0, y: 0, z: 0 },
+ error: 'Value must be a Vec3 object'
+ };
+ }
+
+ const vec = value as { x: number; y: number; z: number };
+ const xResult = validateNumber(vec.x, { ...meta, name: 'x' });
+ const yResult = validateNumber(vec.y, { ...meta, name: 'y' });
+ const zResult = validateNumber(vec.z, { ...meta, name: 'z' });
+
+ if (!xResult.valid || !yResult.valid || !zResult.valid) {
+ return {
+ valid: false,
+ value: { x: xResult.value as number, y: yResult.value as number, z: zResult.value as number },
+ error: xResult.error || yResult.error || zResult.error
+ };
+ }
+
+ return { valid: true, value: { x: xResult.value, y: yResult.value, z: zResult.value } };
+}
+
+export function validateColor(value: unknown, meta: PropertyMeta): ValidationResult {
+ if (!value || typeof value !== 'object') {
+ return {
+ valid: false,
+ value: { r: 255, g: 255, b: 255, a: 255 },
+ error: 'Value must be a Color object'
+ };
+ }
+
+ const color = value as { r: number; g: number; b: number; a: number };
+ const componentMeta = { ...meta, min: 0, max: 255 };
+
+ const rResult = validateNumber(color.r, componentMeta);
+ const gResult = validateNumber(color.g, componentMeta);
+ const bResult = validateNumber(color.b, componentMeta);
+ const aResult = validateNumber(color.a, componentMeta);
+
+ if (!rResult.valid || !gResult.valid || !bResult.valid || !aResult.valid) {
+ return {
+ valid: false,
+ value: {
+ r: rResult.value as number,
+ g: gResult.value as number,
+ b: bResult.value as number,
+ a: aResult.value as number
+ },
+ error: 'Color components must be 0-255'
+ };
+ }
+
+ return {
+ valid: true,
+ value: { r: rResult.value, g: gResult.value, b: bResult.value, a: aResult.value }
+ };
+}
+
+export function validate(value: unknown, meta: PropertyMeta): ValidationResult {
+ switch (meta.type) {
+ case 'number':
+ return validateNumber(value, meta);
+ case 'string':
+ return validateString(value, meta);
+ case 'boolean':
+ return validateBoolean(value, meta);
+ case 'enum':
+ return validateEnum(value, meta);
+ case 'vec2':
+ return validateVec2(value, meta);
+ case 'vec3':
+ return validateVec3(value, meta);
+ case 'color':
+ return validateColor(value, meta);
+ default:
+ return { valid: true, value };
+ }
+}
+
+export function showValidationError(element: HTMLElement, error: string): void {
+ element.classList.add('es-validation-error');
+ element.title = error;
+
+ setTimeout(() => {
+ element.classList.remove('es-validation-error');
+ element.title = '';
+ }, 3000);
+}
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index df854023f..6e505323e 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -57,7 +57,7 @@ export interface AssetSelection {
export interface EditorState {
scene: SceneData;
- selectedEntity: Entity | null;
+ selectedEntities: Set<number>;
selectedAsset: AssetSelection | null;
isDirty: boolean;
filePath: string | null;
@@ -137,7 +137,7 @@ export class EditorStore {
const scene = createEmptyScene();
this.state_ = {
scene,
- selectedEntity: null,
+ selectedEntities: new Set(),
selectedAsset: null,
isDirty: false,
filePath: null,
@@ -169,8 +169,13 @@ export class EditorStore {
return this.sceneVersion_;
}
+ get selectedEntities(): ReadonlySet<number> {
+ return this.state_.selectedEntities;
+ }
+
get selectedEntity(): Entity | null {
- return this.state_.selectedEntity;
+ const arr = Array.from(this.state_.selectedEntities);
+ return arr.length === 1 ? (arr[0] as Entity) : null;
}
get selectedAsset(): AssetSelection | null {
@@ -207,7 +212,7 @@ export class EditorStore {
newScene(name: string = 'Untitled', designResolution?: { width: number; height: number }): void {
this.state_.scene = createEmptyScene(name, designResolution);
- this.state_.selectedEntity = null;
+ this.state_.selectedEntities.clear();
this.state_.selectedAsset = null;
this.state_.isDirty = false;
this.state_.filePath = null;
@@ -221,7 +226,7 @@ export class EditorStore {
loadScene(scene: SceneData, filePath: string | null = null): void {
this.state_.scene = scene;
- this.state_.selectedEntity = null;
+ this.state_.selectedEntities.clear();
this.state_.selectedAsset = null;
this.state_.isDirty = false;
this.state_.filePath = filePath;
@@ -247,23 +252,104 @@ export class EditorStore {
// Selection
// =========================================================================
- selectEntity(entity: Entity | null): void {
- if (this.state_.selectedEntity !== entity) {
- this.state_.selectedEntity = entity;
+ selectEntity(entity: Entity | null, mode: 'replace' | 'add' | 'toggle' = 'replace'): void {
+ const oldSelection = new Set(this.state_.selectedEntities);
+
+ if (entity === null) {
+ this.state_.selectedEntities.clear();
+ } else {
+ const id = entity as number;
+ if (mode === 'replace') {
+ this.state_.selectedEntities.clear();
+ this.state_.selectedEntities.add(id);
+ } else if (mode === 'add') {
+ this.state_.selectedEntities.add(id);
+ } else if (mode === 'toggle') {
+ if (this.state_.selectedEntities.has(id)) {
+ this.state_.selectedEntities.delete(id);
+ } else {
+ this.state_.selectedEntities.add(id);
+ }
+ }
+ }
+
+ if (!this.setsEqual(oldSelection, this.state_.selectedEntities)) {
this.state_.selectedAsset = null;
this.notify();
}
}
+ selectEntities(entities: number[]): void {
+ this.state_.selectedEntities.clear();
+ for (const id of entities) {
+ this.state_.selectedEntities.add(id);
+ }
+ this.state_.selectedAsset = null;
+ this.notify();
+ }
+
+ selectRange(fromEntity: number, toEntity: number): void {
+ const flatList: number[] = [];
+ const visited = new Set<number>();
+
+ const traverse = (entityId: number | null) => {
+ if (entityId === null) return;
+ const entity = this.entityMap_.get(entityId);
+ if (!entity || visited.has(entityId)) return;
+ visited.add(entityId);
+ flatList.push(entityId);
+ for (const childId of entity.children) {
+ traverse(childId);
+ }
+ };
+
+ for (const entity of this.state_.scene.entities) {
+ if (entity.parent === null) {
+ traverse(entity.id);
+ }
+ }
+
+ const fromIndex = flatList.indexOf(fromEntity);
+ const toIndex = flatList.indexOf(toEntity);
+
+ if (fromIndex === -1 || toIndex === -1) return;
+
+ const start = Math.min(fromIndex, toIndex);
+ const end = Math.max(fromIndex, toIndex);
+ const range = flatList.slice(start, end + 1);
+
+ this.selectEntities(range);
+ }
+
+ private setsEqual(a: Set<number>, b: Set<number>): boolean {
+ if (a.size !== b.size) return false;
+ for (const item of a) {
+ if (!b.has(item)) return false;
+ }
+ return true;
+ }
+
selectAsset(asset: AssetSelection | null): void {
this.state_.selectedAsset = asset;
- this.state_.selectedEntity = null;
+ this.state_.selectedEntities.clear();
this.notify();
}
getSelectedEntityData(): EntityData | null {
- if (this.state_.selectedEntity === null) return null;
- return this.entityMap_.get(this.state_.selectedEntity as number) ?? null;
+ const arr = Array.from(this.state_.selectedEntities);
+ if (arr.length !== 1) return null;
+ return this.entityMap_.get(arr[0]) ?? null;
+ }
+
+ getSelectedEntitiesData(): EntityData[] {
+ const result: EntityData[] = [];
+ for (const id of this.state_.selectedEntities) {
+ const entity = this.entityMap_.get(id);
+ if (entity) {
+ result.push(entity);
+ }
+ }
+ return result;
}
getEntityData(entityId: number): EntityData | null {
@@ -367,8 +453,9 @@ export class EditorStore {
const cmd = new DeleteEntityCommand(this.state_.scene, this.entityMap_, entity);
this.executeCommand(cmd);
- if (this.state_.selectedEntity === entity) {
- this.state_.selectedEntity = null;
+ this.state_.selectedEntities.delete(entity as number);
+ for (const id of descendants) {
+ this.state_.selectedEntities.delete(id);
}
for (const id of descendants) {
@@ -377,6 +464,23 @@ export class EditorStore {
this.notifyEntityLifecycle({ entity: entity as number, type: 'deleted', parent: null });
}
+ deleteSelectedEntities(): void {
+ const toDelete = Array.from(this.state_.selectedEntities);
+ const commands = toDelete.map(id => new DeleteEntityCommand(this.state_.scene, this.entityMap_, id as Entity));
+ const compound = new CompoundCommand(commands, 'Delete entities');
+ this.executeCommand(compound);
+
+ this.state_.selectedEntities.clear();
+
+ for (const id of toDelete) {
+ const descendants = this.collectDescendantIds(id);
+ for (const descId of descendants) {
+ this.notifyEntityLifecycle({ entity: descId, type: 'deleted', parent: null });
+ }
+ this.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });
+ }
+ }
+
reparentEntity(entity: Entity, newParent: Entity | null): void {
const cmd = new ReparentCommand(this.state_.scene, this.entityMap_, entity, newParent);
this.executeCommand(cmd);
diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.css
index 735f83cce..42a06d513 100644
--- a/editor/src/styles/editor.css
+++ b/editor/src/styles/editor.css
@@ -277,18 +277,62 @@ svg {
.es-editor-left {
width: 250px;
min-width: 200px;
- border-right: 1px solid var(--es-border);
+ display: flex;
+ flex-direction: column;
}
.es-editor-center {
flex: 1;
min-width: 300px;
+ display: flex;
+ flex-direction: column;
}
.es-editor-right {
width: 300px;
min-width: 250px;
- border-left: 1px solid var(--es-border);
+ display: flex;
+ flex-direction: column;
+}
+
+.es-splitter {
+ background: var(--es-border);
+ flex-shrink: 0;
+ position: relative;
+ transition: background 0.15s;
+}
+
+.es-splitter:hover {
+ background: var(--es-accent);
+}
+
+.es-splitter-horizontal {
+ width: 4px;
+ cursor: col-resize;
+}
+
+.es-splitter-vertical {
+ height: 4px;
+ cursor: row-resize;
+}
+
+.es-splitter::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+}
+
+.es-splitter-horizontal::after {
+ left: -2px;
+ right: -2px;
+}
+
+.es-splitter-vertical::after {
+ top: -2px;
+ bottom: -2px;
}
/* =============================================================================
@@ -621,6 +665,22 @@ svg {
color: #87d7ff;
}
+.es-search-highlight {
+ background: rgba(229, 192, 123, 0.3);
+ color: #e5c07b;
+ font-weight: 600;
+ padding: 0 1px;
+ border-radius: 2px;
+}
+
+.es-hierarchy-item.es-search-selected {
+ background: rgba(97, 175, 239, 0.2);
+}
+
+.es-hierarchy-item.es-search-selected > .es-hierarchy-row {
+ border-left: 2px solid #61afef;
+}
+
.es-hierarchy-footer {
padding: 6px 12px;
font-size: 11px;
@@ -661,6 +721,31 @@ svg {
padding: 20px;
}
+.es-inspector-multi-header {
+ padding: 16px;
+ text-align: center;
+ background: var(--es-bg-secondary);
+ border: 1px solid var(--es-border);
+ margin-bottom: 8px;
+}
+
+.es-inspector-multi-header h3 {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ margin: 0 0 8px 0;
+ color: var(--es-text-primary);
+ font-size: 14px;
+ font-weight: 600;
+}
+
+.es-inspector-multi-header p {
+ margin: 0;
+ color: var(--es-text-secondary);
+ font-size: 12px;
+}
+
.es-inspector-entity-header {
display: flex;
align-items: center;
@@ -1371,6 +1456,17 @@ svg {
margin: 0;
}
+.es-validation-error {
+ border-color: var(--es-danger) !important;
+ animation: shake 0.3s;
+}
+
+@keyframes shake {
+ 0%, 100% { transform: translateX(0); }
+ 25% { transform: translateX(-4px); }
+ 75% { transform: translateX(4px); }
+}
+
.es-number-editor {
display: flex;
align-items: center;
@@ -5107,3 +5203,82 @@ svg {
.es-uirect-pair { display: flex; gap: 8px; flex: 1; }
.es-uirect-pair-item { display: flex; align-items: center; flex: 1; gap: 4px; }
.es-uirect-pair-label { color: var(--es-text-secondary); font-size: 10px; flex-shrink: 0; cursor: ew-resize; }
+
+/* =============================================================================
+ * Error Boundaries
+ * ============================================================================= */
+
+.es-error-fallback {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 40px;
+ text-align: center;
+ background: rgba(224, 108, 117, 0.05);
+ border: 2px dashed rgba(224, 108, 117, 0.3);
+ border-radius: 8px;
+ margin: 20px;
+ min-height: 200px;
+}
+
+.es-error-fallback-icon {
+ color: #e06c75;
+ margin-bottom: 16px;
+}
+
+.es-error-fallback-title {
+ font-size: 18px;
+ font-weight: 600;
+ margin: 0 0 8px 0;
+ color: #e06c75;
+}
+
+.es-error-fallback-message {
+ font-size: 14px;
+ margin: 0 0 16px 0;
+ color: var(--es-text-secondary);
+ max-width: 600px;
+}
+
+.es-error-fallback-details {
+ margin: 16px 0;
+ width: 100%;
+ max-width: 700px;
+ text-align: left;
+}
+
+.es-error-fallback-details summary {
+ cursor: pointer;
+ padding: 8px 12px;
+ background: var(--es-bg-secondary);
+ border-radius: 4px;
+ font-size: 12px;
+ color: var(--es-text-secondary);
+ user-select: none;
+}
+
+.es-error-fallback-details summary:hover {
+ background: var(--es-bg-tertiary);
+}
+
+.es-error-fallback-stack {
+ background: var(--es-bg-tertiary);
+ padding: 12px;
+ border-radius: 4px;
+ font-size: 11px;
+ font-family: 'Consolas', 'Monaco', monospace;
+ overflow-x: auto;
+ max-height: 200px;
+ overflow-y: auto;
+ margin-top: 8px;
+ color: var(--es-text-primary);
+ white-space: pre-wrap;
+ word-break: break-all;
+}
+
+.es-error-fallback-actions {
+ display: flex;
+ gap: 8px;
+ margin-top: 16px;
+}
diff --git a/editor/src/ui/Splitter.ts b/editor/src/ui/Splitter.ts
new file mode 100644
index 000000000..4238bafcd
--- /dev/null
+++ b/editor/src/ui/Splitter.ts
@@ -0,0 +1,142 @@
+/**
+ * @file Splitter.ts
+ * @brief Draggable splitter for resizable panels
+ */
+
+export type SplitterDirection = 'horizontal' | 'vertical';
+
+export interface SplitterOptions {
+ direction: SplitterDirection;
+ container: HTMLElement;
+ leftPanel: HTMLElement;
+ rightPanel: HTMLElement;
+ minSize?: number;
+ defaultPosition?: number;
+ onResize?: (leftSize: number, rightSize: number) => void;
+}
+
+export class Splitter {
+ private container_: HTMLElement;
+ private leftPanel_: HTMLElement;
+ private rightPanel_: HTMLElement;
+ private splitter_: HTMLElement;
+ private direction_: SplitterDirection;
+ private minSize_: number;
+ private isDragging_ = false;
+ private startPos_ = 0;
+ private startLeftSize_ = 0;
+ private startRightSize_ = 0;
+ private onResize_?: (leftSize: number, rightSize: number) => void;
+
+ constructor(options: SplitterOptions) {
+ this.container_ = options.container;
+ this.leftPanel_ = options.leftPanel;
+ this.rightPanel_ = options.rightPanel;
+ this.direction_ = options.direction;
+ this.minSize_ = options.minSize ?? 200;
+ this.onResize_ = options.onResize;
+
+ this.splitter_ = document.createElement('div');
+ this.splitter_.className = `es-splitter es-splitter-${this.direction_}`;
+
+ this.insertSplitter();
+ this.setupEvents();
+
+ if (options.defaultPosition) {
+ this.setPosition(options.defaultPosition);
+ }
+ }
+
+ private insertSplitter(): void {
+ this.leftPanel_.insertAdjacentElement('afterend', this.splitter_);
+ }
+
+ private setupEvents(): void {
+ this.splitter_.addEventListener('mousedown', (e) => this.onMouseDown(e));
+ document.addEventListener('mousemove', (e) => this.onMouseMove(e));
+ document.addEventListener('mouseup', () => this.onMouseUp());
+ }
+
+ private onMouseDown(e: MouseEvent): void {
+ e.preventDefault();
+ this.isDragging_ = true;
+
+ this.startPos_ = this.direction_ === 'horizontal' ? e.clientX : e.clientY;
+ this.startLeftSize_ = this.getSize(this.leftPanel_);
+ this.startRightSize_ = this.getSize(this.rightPanel_);
+
+ document.body.style.cursor = this.direction_ === 'horizontal' ? 'col-resize' : 'row-resize';
+ document.body.style.userSelect = 'none';
+ }
+
+ private onMouseMove(e: MouseEvent): void {
+ if (!this.isDragging_) return;
+
+ const currentPos = this.direction_ === 'horizontal' ? e.clientX : e.clientY;
+ const delta = currentPos - this.startPos_;
+
+ const newLeftSize = this.startLeftSize_ + delta;
+ const newRightSize = this.startRightSize_ - delta;
+
+ if (newLeftSize >= this.minSize_ && newRightSize >= this.minSize_) {
+ this.setSize(this.leftPanel_, newLeftSize);
+ this.setSize(this.rightPanel_, newRightSize);
+
+ if (this.onResize_) {
+ this.onResize_(newLeftSize, newRightSize);
+ }
+ }
+ }
+
+ private onMouseUp(): void {
+ if (!this.isDragging_) return;
+
+ this.isDragging_ = false;
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ }
+
+ private getSize(element: HTMLElement): number {
+ if (this.direction_ === 'horizontal') {
+ return element.offsetWidth;
+ } else {
+ return element.offsetHeight;
+ }
+ }
+
+ private setSize(element: HTMLElement, size: number): void {
+ if (this.direction_ === 'horizontal') {
+ element.style.width = `${size}px`;
+ } else {
+ element.style.height = `${size}px`;
+ }
+ }
+
+ setPosition(leftSize: number): void {
+ const totalSize = this.getSize(this.container_);
+ const rightSize = totalSize - leftSize - this.getSplitterSize();
+
+ if (leftSize >= this.minSize_ && rightSize >= this.minSize_) {
+ this.setSize(this.leftPanel_, leftSize);
+ this.setSize(this.rightPanel_, rightSize);
+ }
+ }
+
+ private getSplitterSize(): number {
+ return this.direction_ === 'horizontal'
+ ? this.splitter_.offsetWidth
+ : this.splitter_.offsetHeight;
+ }
+
+ getLeftSize(): number {
+ return this.getSize(this.leftPanel_);
+ }
+
+ getRightSize(): number {
+ return this.getSize(this.rightPanel_);
+ }
+
+ dispose(): void {
+ this.splitter_.remove();
+ }
+}
diff --git a/editor/src/utils/fuzzy.ts b/editor/src/utils/fuzzy.ts
new file mode 100644
index 000000000..00472af03
--- /dev/null
+++ b/editor/src/utils/fuzzy.ts
@@ -0,0 +1,70 @@
+export interface FuzzyMatch {
+ score: number;
+ matches: number[];
+}
+
+export function fuzzyMatch(pattern: string, text: string): FuzzyMatch | null {
+ if (!pattern) {
+ return { score: 0, matches: [] };
+ }
+
+ const patternLower = pattern.toLowerCase();
+ const textLower = text.toLowerCase();
+
+ let score = 0;
+ let patternIdx = 0;
+ const matches: number[] = [];
+
+ for (let i = 0; i < textLower.length; i++) {
+ if (patternIdx >= patternLower.length) break;
+
+ if (textLower[i] === patternLower[patternIdx]) {
+ matches.push(i);
+
+ if (matches.length > 1 && matches[matches.length - 1] === matches[matches.length - 2] + 1) {
+ score += 5;
+ }
+
+ if (i === 0 || textLower[i - 1] === ' ' || textLower[i - 1] === '_') {
+ score += 10;
+ }
+
+ if (text[i] === text[i].toUpperCase() && i > 0 && text[i - 1] === text[i - 1].toLowerCase()) {
+ score += 8;
+ }
+
+ score += 1;
+ patternIdx++;
+ }
+ }
+
+ if (patternIdx < patternLower.length) {
+ return null;
+ }
+
+ return { score, matches };
+}
+
+export function fuzzyFilter<T>(
+ items: T[],
+ pattern: string,
+ getText: (item: T) => string
+): Array<{ item: T; match: FuzzyMatch }> {
+ if (!pattern) {
+ return items.map(item => ({ item, match: { score: 0, matches: [] } }));
+ }
+
+ const results: Array<{ item: T; match: FuzzyMatch }> = [];
+
+ for (const item of items) {
+ const text = getText(item);
+ const match = fuzzyMatch(pattern, text);
+ if (match) {
+ results.push({ item, match });
+ }
+ }
+
+ results.sort((a, b) => b.match.score - a.match.score);
+
+ return results;
+}
diff --git a/editor/tsconfig.json b/editor/tsconfig.json
index 25a4e8569..cc81b2c74 100644
--- a/editor/tsconfig.json
+++ b/editor/tsconfig.json
@@ -10,7 +10,8 @@
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
- "isolatedModules": true
+ "isolatedModules": true,
+ "types": ["vitest/globals"]
},
"include": ["src"]
}
diff --git a/editor/vitest.config.ts b/editor/vitest.config.ts
new file mode 100644
index 000000000..9d7c72ef8
--- /dev/null
+++ b/editor/vitest.config.ts
@@ -0,0 +1,28 @@
+import { defineConfig } from 'vitest/config';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+export default defineConfig({
+ test: {
+ environment: 'jsdom',
+ globals: true,
+ setupFiles: ['./src/__tests__/setup.ts'],
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'json', 'html'],
+ exclude: [
+ 'node_modules/',
+ 'dist/',
+ 'src/__tests__/',
+ '**/*.d.ts',
+ ],
+ },
+ },
+ resolve: {
+ alias: {
+ 'esengine': path.resolve(__dirname, '../sdk/dist/index.js'),
+ },
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7a70e5f0d..430d8f180 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -55,8 +55,8 @@ importers:
specifier: ^5.3.0
version: 5.9.3
vite:
- specifier: ^5.0.0
- version: 5.4.21([email protected])
+ specifier: ^7.0.0
+ version: 7.3.1(@types/[email protected])([email protected])
editor:
dependencies:
@@ -79,6 +79,15 @@ importers:
'@rollup/plugin-typescript':
specifier: ^11.1.5
+ '@vitest/ui':
+ specifier: ^2.1.8
+ version: 2.1.9([email protected])
+ happy-dom:
+ specifier: ^20.6.1
+ version: 20.6.1
+ jsdom:
+ specifier: ^25.0.1
+ version: 25.0.1
rimraf:
specifier: ^5.0.5
version: 5.0.10
@@ -94,6 +103,9 @@ importers:
typescript:
specifier: ^5.3.0
version: 5.9.3
+ vitest:
+ specifier: ^2.1.8
sdk:
devDependencies:
@@ -103,6 +115,12 @@ importers:
'@rollup/plugin-typescript':
specifier: ^11.1.5
+ '@vitest/ui':
+ specifier: ^2.1.0
+ version: 2.1.9([email protected])
+ happy-dom:
+ specifier: ^15.11.0
+ version: 15.11.7
minigame-api-typings:
specifier: ^3.8.16
version: 3.8.16
@@ -121,9 +139,15 @@ importers:
typescript:
specifier: ^5.3.0
version: 5.9.3
+ vitest:
+ specifier: ^2.1.0
packages:
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
+
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
engines: {node: '>=6.9.0'}
@@ -132,144 +156,328 @@ packages:
resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}
engines: {node: '>=6.9.0'}
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==}
+ engines: {node: '>=18'}
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^3.0.5
+ '@csstools/css-tokenizer': ^3.0.4
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^3.0.5
+ '@csstools/css-tokenizer': ^3.0.4
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@csstools/css-tokenizer': ^3.0.4
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==}
+ engines: {node: '>=18'}
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}
engines: {node: '>=12'}
cpu: [ppc64]
os: [aix]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}
engines: {node: '>=12'}
cpu: [arm64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}
engines: {node: '>=12'}
cpu: [arm]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}
engines: {node: '>=12'}
cpu: [x64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}
engines: {node: '>=12'}
cpu: [arm64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}
engines: {node: '>=12'}
cpu: [x64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}
engines: {node: '>=12'}
cpu: [arm64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}
engines: {node: '>=12'}
cpu: [x64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}
engines: {node: '>=12'}
cpu: [arm64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}
engines: {node: '>=12'}
cpu: [arm]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}
engines: {node: '>=12'}
cpu: [ia32]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}
engines: {node: '>=12'}
cpu: [loong64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}
engines: {node: '>=12'}
cpu: [mips64el]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}
engines: {node: '>=12'}
cpu: [ppc64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}
engines: {node: '>=12'}
cpu: [riscv64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}
engines: {node: '>=12'}
cpu: [s390x]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}
engines: {node: '>=12'}
cpu: [x64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}
engines: {node: '>=12'}
cpu: [x64]
os: [netbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}
engines: {node: '>=12'}
cpu: [x64]
os: [openbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}
engines: {node: '>=12'}
cpu: [x64]
os: [sunos]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}
engines: {node: '>=12'}
cpu: [arm64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}
engines: {node: '>=12'}
cpu: [ia32]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}
engines: {node: '>=12'}
cpu: [x64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
'@isaacs/[email protected]':
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
@@ -294,6 +502,9 @@ packages:
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
+ '@polka/[email protected]':
+ resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
+
'@rollup/[email protected]':
resolution: {integrity: sha512-tPCzJOtS7uuVZd+xPhoy5W4vThe6KWXNmsFCNktaAh5RTqcLiSfT4huPQIXkgJ6YCOjJHvecOAzQxLFhPxKr+g==}
engines: {node: '>=20.19.0'}
@@ -578,14 +789,61 @@ packages:
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==}
+
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^5.0.0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-izzd2zmnk8Nl5ECYkW27328RbQ1nKvkm6Bb5DAaz1Gk59EbLkiCMa6OLT0NoaAYTjOFS6N+SMYW1nh4/9ljPiw==}
+ peerDependencies:
+ vitest: 2.1.9
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
+
resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==}
engines: {node: '>=0.4.0'}
hasBin: true
+ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
+ engines: {node: '>= 14'}
+
resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
engines: {node: '>=8'}
@@ -606,6 +864,13 @@ packages:
resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
+
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
@@ -623,10 +888,26 @@ packages:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}
engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}
+ resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
+ engines: {node: '>= 16'}
+
resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
engines: {node: '>= 8.10.0'}
@@ -646,6 +927,10 @@ packages:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
+ resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
+ engines: {node: '>= 0.8'}
+
resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}
engines: {node: '>=18'}
@@ -657,10 +942,42 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
+ engines: {node: '>=6.0'}
+ peerDependencies:
+ supports-color: '*'
+ peerDependenciesMeta:
+ supports-color:
+ optional: true
+
+ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
+
+ resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
+ engines: {node: '>=0.4.0'}
+
+ resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
@@ -673,6 +990,33 @@ packages:
resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
+ engines: {node: '>=0.12'}
+
+ resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
+ engines: {node: '>=0.12'}
+
+ resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
+
+ resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-eUTnl8eh+v8UZIZh4MrMOKDAc8Lm7+NqP3pyuTORGFY1s/o9WoiJgKnwXy+te2J3hX7iRbFSHEyig7GsPeeJyw==}
engines: {node: '>=18'}
@@ -683,17 +1027,48 @@ packages:
engines: {node: '>=12'}
hasBin: true
+ resolution: {integrity: sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
+
+ resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==}
+
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==}
+
resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}
+ engines: {node: '>= 6'}
+
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -706,6 +1081,14 @@ packages:
resolution: {integrity: sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
engines: {node: '>= 6'}
@@ -715,10 +1098,46 @@ packages:
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
hasBin: true
+ resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-KyrFvnl+J9US63TEzwoiJOQzZBJY7KgBushJA8X61DMbNsH+2ONkDuLDnCnwUiPTF42tLoEmrPyoqbenVA5zrg==}
+ engines: {node: '>=18.0.0'}
+
+ resolution: {integrity: sha512-+0vhESXXhFwkdjZnJ5DlmJIfUYGgIEEjzIjB+aKJbFuqlvvKyOi+XkI1fYbgYR9QCxG5T08koxsQ6HrQfa5gCQ==}
+ engines: {node: '>=20.0.0'}
+
+ resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==}
engines: {node: '>=8'}
@@ -750,6 +1169,9 @@ packages:
resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}
engines: {node: '>=0.12.0'}
+ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
+
resolution: {integrity: sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==}
engines: {node: '>=12'}
@@ -767,10 +1189,22 @@ packages:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
+ resolution: {integrity: sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ canvas: ^2.11.2
+ peerDependenciesMeta:
+ canvas:
+ optional: true
+
resolution: {integrity: sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
+
resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
@@ -780,6 +1214,18 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
+ engines: {node: '>= 0.6'}
+
+ resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
+ engines: {node: '>= 0.6'}
+
resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
engines: {node: '>=18'}
@@ -795,6 +1241,13 @@ packages:
resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==}
engines: {node: '>=16 || 14 >=14.17'}
+ resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -804,6 +1257,9 @@ packages:
resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==}
+
resolution: {integrity: sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==}
engines: {node: '>=18'}
@@ -815,6 +1271,9 @@ packages:
resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
+ resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
+
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
engines: {node: '>=8'}
@@ -826,6 +1285,13 @@ packages:
resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}
engines: {node: '>=16 || 14 >=14.18'}
+ resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}
+
+ resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
+ engines: {node: '>= 14.16'}
+
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -841,6 +1307,10 @@ packages:
resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
engines: {node: ^10 || ^12 || >=14}
+ resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==}
@@ -873,9 +1343,22 @@ packages:
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
+ resolution: {integrity: sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==}
+
+ resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==}
+
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
+ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+
+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
+ engines: {node: '>=v12.22.7'}
+
resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==}
@@ -887,10 +1370,17 @@ packages:
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==}
@@ -905,6 +1395,12 @@ packages:
resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
+
+ resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
+
resolution: {integrity: sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==}
engines: {node: '>=18'}
@@ -933,15 +1429,59 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
+
resolution: {integrity: sha512-jTwoImyr/QbOWFFso3YoU3ik0jBBDJ6JTOQiy/J2YxVJdZCc+5u7skhNwiOR3FQIygFqVUPHl7qbbxtjW2K3Qg==}
engines: {node: '>=10'}
hasBin: true
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+
+ resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
+
+ resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+
+ resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==}
+
+ resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==}
+ hasBin: true
+
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
+ resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -950,8 +1490,16 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
- resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
+ resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}
+
+ resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
engines: {node: ^18.0.0 || >=20.0.0}
hasBin: true
peerDependencies:
@@ -981,11 +1529,106 @@ packages:
terser:
optional: true
+ resolution: {integrity: sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ lightningcss: ^1.21.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@types/node': ^18.0.0 || >=20.0.0
+ '@vitest/browser': 2.1.9
+ '@vitest/ui': 2.1.9
+ happy-dom: '*'
+ jsdom: '*'
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
+ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}
+ engines: {node: '>=18'}
+ deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation
+
+ resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
engines: {node: '>= 8'}
hasBin: true
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
+ engines: {node: '>=8'}
+ hasBin: true
+
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
@@ -994,8 +1637,35 @@ packages:
resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
+ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
+
snapshots:
+ '@asamuzakjp/[email protected]':
+ dependencies:
+ '@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-color-parser': 3.1.0(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])
+ '@csstools/css-tokenizer': 3.0.4
+ lru-cache: 10.4.3
+
dependencies:
'@babel/helper-validator-identifier': 7.28.5
@@ -1006,75 +1676,173 @@ snapshots:
optional: true
+ '@csstools/[email protected]': {}
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])
+ '@csstools/css-tokenizer': 3.0.4
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/color-helpers': 5.1.0
+ '@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])
+ '@csstools/css-tokenizer': 3.0.4
+
+ '@csstools/[email protected](@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-tokenizer': 3.0.4
+
+ '@csstools/[email protected]': {}
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@isaacs/[email protected]':
dependencies:
string-width: 5.1.2
@@ -1106,6 +1874,8 @@ snapshots:
optional: true
+ '@polka/[email protected]': {}
+
optionalDependencies:
rollup: 4.57.1
@@ -1291,10 +2061,73 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ undici-types: 7.16.0
+
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 25.2.3
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/spy': 2.1.9
+ '@vitest/utils': 2.1.9
+ chai: 5.3.3
+ tinyrainbow: 1.2.0
+
+ dependencies:
+ '@vitest/spy': 2.1.9
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ vite: 5.4.21(@types/[email protected])([email protected])
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyrainbow: 1.2.0
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/utils': 2.1.9
+ pathe: 1.1.2
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 2.1.9
+ magic-string: 0.30.21
+ pathe: 1.1.2
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyspy: 3.0.2
+
+ dependencies:
+ '@vitest/utils': 2.1.9
+ fflate: 0.8.2
+ flatted: 3.3.3
+ pathe: 1.1.2
+ sirv: 3.0.2
+ tinyglobby: 0.2.15
+ tinyrainbow: 1.2.0
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 2.1.9
+ loupe: 3.2.1
+ tinyrainbow: 1.2.0
+
+
@@ -1310,6 +2143,10 @@ snapshots:
normalize-path: 3.0.0
picomatch: 2.3.1
+
+
@@ -1324,8 +2161,25 @@ snapshots:
+
+ dependencies:
+ es-errors: 1.3.0
+ function-bind: 1.1.2
+
+ dependencies:
+ assertion-error: 2.0.1
+ check-error: 2.1.3
+ deep-eql: 5.0.2
+ loupe: 3.2.1
+ pathval: 2.0.1
+
+
dependencies:
anymatch: 3.1.3
@@ -1350,6 +2204,10 @@ snapshots:
+ dependencies:
+ delayed-stream: 1.0.0
+
@@ -1360,8 +2218,34 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
+ dependencies:
+ '@asamuzakjp/css-color': 3.2.0
+ rrweb-cssom: 0.8.0
+
+ dependencies:
+ whatwg-mimetype: 4.0.0
+ whatwg-url: 14.2.0
+
+ dependencies:
+ ms: 2.1.3
+
+
+
+
+ dependencies:
+ call-bind-apply-helpers: 1.0.2
+ es-errors: 1.3.0
+ gopd: 1.2.0
+
@@ -1370,6 +2254,27 @@ snapshots:
+
+
+
+
+
+ dependencies:
+ es-errors: 1.3.0
+
+ dependencies:
+ es-errors: 1.3.0
+ get-intrinsic: 1.3.0
+ has-tostringtag: 1.0.2
+ hasown: 2.0.2
+
@@ -1398,17 +2303,68 @@ snapshots:
'@esbuild/win32-ia32': 0.21.5
'@esbuild/win32-x64': 0.21.5
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.27.3
+ '@esbuild/android-arm': 0.27.3
+ '@esbuild/android-arm64': 0.27.3
+ '@esbuild/android-x64': 0.27.3
+ '@esbuild/darwin-arm64': 0.27.3
+ '@esbuild/darwin-x64': 0.27.3
+ '@esbuild/freebsd-arm64': 0.27.3
+ '@esbuild/freebsd-x64': 0.27.3
+ '@esbuild/linux-arm': 0.27.3
+ '@esbuild/linux-arm64': 0.27.3
+ '@esbuild/linux-ia32': 0.27.3
+ '@esbuild/linux-loong64': 0.27.3
+ '@esbuild/linux-mips64el': 0.27.3
+ '@esbuild/linux-ppc64': 0.27.3
+ '@esbuild/linux-riscv64': 0.27.3
+ '@esbuild/linux-s390x': 0.27.3
+ '@esbuild/linux-x64': 0.27.3
+ '@esbuild/netbsd-arm64': 0.27.3
+ '@esbuild/netbsd-x64': 0.27.3
+ '@esbuild/openbsd-arm64': 0.27.3
+ '@esbuild/openbsd-x64': 0.27.3
+ '@esbuild/openharmony-arm64': 0.27.3
+ '@esbuild/sunos-x64': 0.27.3
+ '@esbuild/win32-arm64': 0.27.3
+ '@esbuild/win32-ia32': 0.27.3
+ '@esbuild/win32-x64': 0.27.3
+
+ dependencies:
+ '@types/estree': 1.0.8
+
+
+ optionalDependencies:
+ picomatch: 4.0.3
+
+
dependencies:
to-regex-range: 5.0.1
+
dependencies:
cross-spawn: 7.0.6
signal-exit: 4.1.0
+ dependencies:
+ asynckit: 0.4.0
+ combined-stream: 1.0.8
+ es-set-tostringtag: 2.1.0
+ hasown: 2.0.2
+ mime-types: 2.1.35
+
optional: true
@@ -1416,6 +2372,24 @@ snapshots:
+ dependencies:
+ call-bind-apply-helpers: 1.0.2
+ es-define-property: 1.0.1
+ es-errors: 1.3.0
+ es-object-atoms: 1.1.1
+ function-bind: 1.1.2
+ get-proto: 1.0.1
+ gopd: 1.2.0
+ has-symbols: 1.1.0
+ hasown: 2.0.2
+ math-intrinsics: 1.1.0
+
+ dependencies:
+ dunder-proto: 1.0.1
+ es-object-atoms: 1.1.1
+
dependencies:
is-glob: 4.0.3
@@ -1429,10 +2403,58 @@ snapshots:
package-json-from-dist: 1.0.1
path-scurry: 1.11.1
+
+ dependencies:
+ entities: 4.5.0
+ webidl-conversions: 7.0.0
+ whatwg-mimetype: 3.0.0
+
+ dependencies:
+ '@types/node': 25.2.3
+ '@types/whatwg-mimetype': 3.0.2
+ '@types/ws': 8.18.1
+ entities: 6.0.1
+ whatwg-mimetype: 3.0.0
+ ws: 8.19.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
+
+ dependencies:
+ has-symbols: 1.1.0
+
dependencies:
function-bind: 1.1.2
+ dependencies:
+ whatwg-encoding: 3.1.1
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ safer-buffer: 2.1.2
+
dependencies:
binary-extensions: 2.3.0
@@ -1455,6 +2477,8 @@ snapshots:
+
@@ -1470,11 +2494,41 @@ snapshots:
optional: true
+ dependencies:
+ cssstyle: 4.6.0
+ data-urls: 5.0.0
+ decimal.js: 10.6.0
+ form-data: 4.0.5
+ html-encoding-sniffer: 4.0.0
+ http-proxy-agent: 7.0.2
+ https-proxy-agent: 7.0.6
+ is-potential-custom-element-name: 1.0.1
+ nwsapi: 2.2.23
+ parse5: 7.3.0
+ rrweb-cssom: 0.7.1
+ saxes: 6.0.0
+ symbol-tree: 3.2.4
+ tough-cookie: 5.1.2
+ w3c-xmlserializer: 5.0.0
+ webidl-conversions: 7.0.0
+ whatwg-encoding: 3.1.1
+ whatwg-mimetype: 4.0.0
+ whatwg-url: 14.2.0
+ ws: 8.19.0
+ xml-name-validator: 5.0.0
+ transitivePeerDependencies:
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+
dependencies:
chalk: 5.6.2
is-unicode-supported: 1.3.0
+
@@ -1483,6 +2537,14 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+
+
+ dependencies:
+ mime-db: 1.52.0
+
@@ -1493,10 +2555,16 @@ snapshots:
+
+
+
dependencies:
mimic-function: 5.0.1
@@ -1515,6 +2583,10 @@ snapshots:
+ dependencies:
+ entities: 6.0.1
+
@@ -1524,6 +2596,10 @@ snapshots:
lru-cache: 10.4.3
minipass: 7.1.2
+
+
@@ -1536,6 +2612,8 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.1
+
dependencies:
safe-buffer: 5.2.1
@@ -1598,8 +2676,18 @@ snapshots:
'@rollup/rollup-win32-x64-msvc': 4.57.1
fsevents: 2.3.3
+
+
+
+ dependencies:
+ xmlchars: 2.2.0
+
dependencies:
randombytes: 2.1.0
@@ -1610,8 +2698,16 @@ snapshots:
+
+ dependencies:
+ '@polka/url': 1.0.0-next.29
+ mrmime: 2.0.1
+ totalist: 3.0.1
+
@@ -1623,6 +2719,10 @@ snapshots:
+
+
@@ -1653,6 +2753,8 @@ snapshots:
+
dependencies:
'@jridgewell/source-map': 0.3.11
@@ -1660,27 +2762,192 @@ snapshots:
commander: 2.20.3
source-map-support: 0.5.21
+
+
+ dependencies:
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.3
+
+
+
+
+
+ dependencies:
+ tldts-core: 6.1.86
+
dependencies:
is-number: 7.0.0
+
+ dependencies:
+ tldts: 6.1.86
+
+ dependencies:
+ punycode: 2.3.1
+
+
+ dependencies:
+ cac: 6.7.14
+ debug: 4.4.3
+ es-module-lexer: 1.7.0
+ pathe: 1.1.2
+ vite: 5.4.21(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - '@types/node'
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
dependencies:
esbuild: 0.21.5
postcss: 8.5.6
rollup: 4.57.1
optionalDependencies:
+ '@types/node': 25.2.3
+ fsevents: 2.3.3
+ terser: 5.46.0
+
+ dependencies:
+ esbuild: 0.27.3
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.3
+ postcss: 8.5.6
+ rollup: 4.57.1
+ tinyglobby: 0.2.15
+ optionalDependencies:
+ '@types/node': 25.2.3
fsevents: 2.3.3
terser: 5.46.0
+ dependencies:
+ '@vitest/expect': 2.1.9
+ '@vitest/mocker': 2.1.9([email protected](@types/[email protected])([email protected]))
+ '@vitest/pretty-format': 2.1.9
+ '@vitest/runner': 2.1.9
+ '@vitest/snapshot': 2.1.9
+ '@vitest/spy': 2.1.9
+ '@vitest/utils': 2.1.9
+ chai: 5.3.3
+ debug: 4.4.3
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ pathe: 1.1.2
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinypool: 1.1.1
+ tinyrainbow: 1.2.0
+ vite: 5.4.21(@types/[email protected])([email protected])
+ vite-node: 2.1.9(@types/[email protected])([email protected])
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 25.2.3
+ '@vitest/ui': 2.1.9([email protected])
+ happy-dom: 15.11.7
+ jsdom: 25.0.1
+ transitivePeerDependencies:
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
+ dependencies:
+ '@vitest/expect': 2.1.9
+ '@vitest/mocker': 2.1.9([email protected](@types/[email protected])([email protected]))
+ '@vitest/pretty-format': 2.1.9
+ '@vitest/runner': 2.1.9
+ '@vitest/snapshot': 2.1.9
+ '@vitest/spy': 2.1.9
+ '@vitest/utils': 2.1.9
+ chai: 5.3.3
+ debug: 4.4.3
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ pathe: 1.1.2
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinypool: 1.1.1
+ tinyrainbow: 1.2.0
+ vite: 5.4.21(@types/[email protected])([email protected])
+ vite-node: 2.1.9(@types/[email protected])([email protected])
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 25.2.3
+ '@vitest/ui': 2.1.9([email protected])
+ happy-dom: 20.6.1
+ jsdom: 25.0.1
+ transitivePeerDependencies:
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
+ dependencies:
+ xml-name-validator: 5.0.0
+
+
+ dependencies:
+ iconv-lite: 0.6.3
+
+
+
+ dependencies:
+ tr46: 5.1.1
+ webidl-conversions: 7.0.0
+
dependencies:
isexe: 2.0.0
+ dependencies:
+ siginfo: 2.0.0
+ stackback: 0.0.2
+
dependencies:
ansi-styles: 4.3.0
@@ -1692,3 +2959,9 @@ snapshots:
ansi-styles: 6.2.3
string-width: 5.1.2
strip-ansi: 7.1.2
+
+
+
diff --git a/sdk/package.json b/sdk/package.json
index 1693736a2..94f22e961 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -35,7 +35,10 @@
"build": "rollup -c",
"watch": "rollup -c -w",
"clean": "rimraf dist",
- "prepublishOnly": "npm run clean && npm run build"
+ "prepublishOnly": "npm run clean && npm run build",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:ui": "vitest --ui"
},
"keywords": [
"game-engine",
@@ -50,12 +53,15 @@
"devDependencies": {
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
+ "@vitest/ui": "^2.1.0",
+ "happy-dom": "^15.11.0",
"minigame-api-typings": "^3.8.16",
"rimraf": "^5.0.5",
"rollup": "^4.9.0",
"rollup-plugin-dts": "^6.1.0",
"tslib": "^2.6.2",
- "typescript": "^5.3.0"
+ "typescript": "^5.3.0",
+ "vitest": "^2.1.0"
},
"repository": {
"type": "git",
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 4d8b9083c..acf997591 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -39,6 +39,8 @@ export interface Plugin {
interface SystemEntry {
system: SystemDef;
+ runBefore?: string[];
+ runAfter?: string[];
}
// =============================================================================
@@ -103,8 +105,16 @@ export class App {
// Systems
// =========================================================================
- addSystemToSchedule(schedule: Schedule, system: SystemDef): this {
- this.systems_.get(schedule)!.push({ system });
+ addSystemToSchedule(
+ schedule: Schedule,
+ system: SystemDef,
+ options?: { runBefore?: string[]; runAfter?: string[] }
+ ): this {
+ this.systems_.get(schedule)!.push({
+ system,
+ runBefore: options?.runBefore,
+ runAfter: options?.runAfter,
+ });
return this;
}
@@ -293,12 +303,78 @@ export class App {
// Internal
// =========================================================================
+ private sortSystems(systems: SystemEntry[]): SystemEntry[] {
+ if (systems.length <= 1) {
+ return systems;
+ }
+
+ const nameToIndex = new Map<string, number>();
+ for (let i = 0; i < systems.length; i++) {
+ nameToIndex.set(systems[i].system._name, i);
+ }
+
+ for (const entry of systems) {
+ if (entry.runBefore) {
+ for (const targetName of entry.runBefore) {
+ const targetIndex = nameToIndex.get(targetName);
+ if (targetIndex !== undefined) {
+ const targetEntry = systems[targetIndex];
+ if (!targetEntry.runAfter) {
+ targetEntry.runAfter = [];
+ }
+ if (!targetEntry.runAfter.includes(entry.system._name)) {
+ targetEntry.runAfter.push(entry.system._name);
+ }
+ }
+ }
+ }
+ }
+
+ const sorted: SystemEntry[] = [];
+ const visited = new Set<number>();
+ const visiting = new Set<number>();
+
+ const visit = (index: number): void => {
+ if (visited.has(index)) return;
+ if (visiting.has(index)) {
+ const name = systems[index].system._name;
+ throw new Error(`Circular dependency detected involving system "${name}"`);
+ }
+
+ visiting.add(index);
+ const entry = systems[index];
+
+ if (entry.runAfter) {
+ for (const depName of entry.runAfter) {
+ const depIndex = nameToIndex.get(depName);
+ if (depIndex !== undefined) {
+ visit(depIndex);
+ }
+ }
+ }
+
+ visiting.delete(index);
+ visited.add(index);
+ sorted.push(entry);
+ };
+
+ for (let i = 0; i < systems.length; i++) {
+ visit(i);
+ }
+
+ return sorted;
+ }
+
private runSchedule(schedule: Schedule): void {
- const systems = this.systems_.get(schedule);
+ let systems = this.systems_.get(schedule);
if (!systems || !this.runner_) {
return;
}
+ if (systems.some(s => s.runBefore || s.runAfter)) {
+ systems = this.sortSystems(systems);
+ }
+
for (const entry of systems) {
try {
this.runner_.run(entry.system);
diff --git a/sdk/src/asset/AssetRefCounter.ts b/sdk/src/asset/AssetRefCounter.ts
new file mode 100644
index 000000000..5c981a4ef
--- /dev/null
+++ b/sdk/src/asset/AssetRefCounter.ts
@@ -0,0 +1,175 @@
+/**
+ * @file AssetRefCounter.ts
+ * @brief Optional asset reference counting for debugging and monitoring
+ */
+
+export interface AssetRefInfo {
+ assetPath: string;
+ refCount: number;
+ entities: number[];
+}
+
+export class AssetRefCounter {
+ private textureRefs_ = new Map<string, Set<number>>();
+ private fontRefs_ = new Map<string, Set<number>>();
+ private materialRefs_ = new Map<string, Set<number>>();
+
+ addTextureRef(path: string, entity: number): void {
+ let refs = this.textureRefs_.get(path);
+ if (!refs) {
+ refs = new Set();
+ this.textureRefs_.set(path, refs);
+ }
+ refs.add(entity);
+ }
+
+ removeTextureRef(path: string, entity: number): void {
+ const refs = this.textureRefs_.get(path);
+ if (refs) {
+ refs.delete(entity);
+ if (refs.size === 0) {
+ this.textureRefs_.delete(path);
+ }
+ }
+ }
+
+ getTextureRefCount(path: string): number {
+ return this.textureRefs_.get(path)?.size ?? 0;
+ }
+
+ getTextureRefs(path: string): number[] {
+ return Array.from(this.textureRefs_.get(path) ?? []);
+ }
+
+ addFontRef(path: string, entity: number): void {
+ let refs = this.fontRefs_.get(path);
+ if (!refs) {
+ refs = new Set();
+ this.fontRefs_.set(path, refs);
+ }
+ refs.add(entity);
+ }
+
+ removeFontRef(path: string, entity: number): void {
+ const refs = this.fontRefs_.get(path);
+ if (refs) {
+ refs.delete(entity);
+ if (refs.size === 0) {
+ this.fontRefs_.delete(path);
+ }
+ }
+ }
+
+ getFontRefCount(path: string): number {
+ return this.fontRefs_.get(path)?.size ?? 0;
+ }
+
+ getFontRefs(path: string): number[] {
+ return Array.from(this.fontRefs_.get(path) ?? []);
+ }
+
+ addMaterialRef(path: string, entity: number): void {
+ let refs = this.materialRefs_.get(path);
+ if (!refs) {
+ refs = new Set();
+ this.materialRefs_.set(path, refs);
+ }
+ refs.add(entity);
+ }
+
+ removeMaterialRef(path: string, entity: number): void {
+ const refs = this.materialRefs_.get(path);
+ if (refs) {
+ refs.delete(entity);
+ if (refs.size === 0) {
+ this.materialRefs_.delete(path);
+ }
+ }
+ }
+
+ getMaterialRefCount(path: string): number {
+ return this.materialRefs_.get(path)?.size ?? 0;
+ }
+
+ getMaterialRefs(path: string): number[] {
+ return Array.from(this.materialRefs_.get(path) ?? []);
+ }
+
+ getAllTextureRefs(): AssetRefInfo[] {
+ const result: AssetRefInfo[] = [];
+ for (const [path, refs] of this.textureRefs_.entries()) {
+ result.push({
+ assetPath: path,
+ refCount: refs.size,
+ entities: Array.from(refs),
+ });
+ }
+ return result;
+ }
+
+ getAllFontRefs(): AssetRefInfo[] {
+ const result: AssetRefInfo[] = [];
+ for (const [path, refs] of this.fontRefs_.entries()) {
+ result.push({
+ assetPath: path,
+ refCount: refs.size,
+ entities: Array.from(refs),
+ });
+ }
+ return result;
+ }
+
+ getAllMaterialRefs(): AssetRefInfo[] {
+ const result: AssetRefInfo[] = [];
+ for (const [path, refs] of this.materialRefs_.entries()) {
+ result.push({
+ assetPath: path,
+ refCount: refs.size,
+ entities: Array.from(refs),
+ });
+ }
+ return result;
+ }
+
+ removeAllRefsForEntity(entity: number): void {
+ for (const refs of this.textureRefs_.values()) {
+ refs.delete(entity);
+ }
+ for (const refs of this.fontRefs_.values()) {
+ refs.delete(entity);
+ }
+ for (const refs of this.materialRefs_.values()) {
+ refs.delete(entity);
+ }
+
+ for (const [path, refs] of this.textureRefs_.entries()) {
+ if (refs.size === 0) {
+ this.textureRefs_.delete(path);
+ }
+ }
+ for (const [path, refs] of this.fontRefs_.entries()) {
+ if (refs.size === 0) {
+ this.fontRefs_.delete(path);
+ }
+ }
+ for (const [path, refs] of this.materialRefs_.entries()) {
+ if (refs.size === 0) {
+ this.materialRefs_.delete(path);
+ }
+ }
+ }
+
+ clear(): void {
+ this.textureRefs_.clear();
+ this.fontRefs_.clear();
+ this.materialRefs_.clear();
+ }
+
+ getTotalRefCount(): { textures: number; fonts: number; materials: number } {
+ return {
+ textures: this.textureRefs_.size,
+ fonts: this.fontRefs_.size,
+ materials: this.materialRefs_.size,
+ };
+ }
+}
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 41ddb3ce9..5326ee4df 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -20,6 +20,7 @@ export {
export { AsyncCache } from './AsyncCache';
export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';
export { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
+export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';
import type { App } from '../app';
import { Assets } from './AssetPlugin';
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 471608eb2..e77418f1a 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -153,6 +153,7 @@ export {
SystemRunner,
type SystemDef,
type SystemParam,
+ type SystemOptions,
type InferParam,
type InferParams,
} from './system';
@@ -263,6 +264,7 @@ export {
assetPlugin,
MaterialLoader,
registerEmbeddedAssets,
+ AssetRefCounter,
type TextureInfo,
type SliceBorder,
type SpineLoadResult,
@@ -276,6 +278,7 @@ export {
type AssetsData,
type LoadedMaterial,
type ShaderLoader,
+ type AssetRefInfo,
} from './asset';
// =============================================================================
@@ -289,6 +292,7 @@ export {
updateCameraAspectRatio,
findEntityByName,
registerComponentAssetFields,
+ getComponentAssetFields,
type SceneData,
type SceneEntityData,
type SceneComponentData,
@@ -470,6 +474,23 @@ export type {
SensorEvent,
} from './physics';
+// =============================================================================
+// Logger
+// =============================================================================
+
+export {
+ Logger,
+ getLogger,
+ setLogLevel,
+ debug,
+ info,
+ warn,
+ error,
+ LogLevel,
+ type LogEntry,
+ type LogHandler,
+} from './logger';
+
// =============================================================================
// GL Debug
// =============================================================================
diff --git a/sdk/src/logger.ts b/sdk/src/logger.ts
new file mode 100644
index 000000000..d62a5e874
--- /dev/null
+++ b/sdk/src/logger.ts
@@ -0,0 +1,142 @@
+/**
+ * @file logger.ts
+ * @brief Centralized logging system for SDK
+ */
+
+export enum LogLevel {
+ Debug = 0,
+ Info = 1,
+ Warn = 2,
+ Error = 3,
+}
+
+export interface LogEntry {
+ timestamp: number;
+ level: LogLevel;
+ category: string;
+ message: string;
+ data?: unknown;
+}
+
+export interface LogHandler {
+ handle(entry: LogEntry): void;
+}
+
+class ConsoleLogHandler implements LogHandler {
+ handle(entry: LogEntry): void {
+ const time = new Date(entry.timestamp).toISOString().substring(11, 23);
+ const levelStr = LogLevel[entry.level].toUpperCase().padEnd(5);
+ const prefix = `[${time}] [${levelStr}] [${entry.category}]`;
+
+ const message = entry.data !== undefined
+ ? `${entry.message} ${JSON.stringify(entry.data)}`
+ : entry.message;
+
+ switch (entry.level) {
+ case LogLevel.Debug:
+ console.debug(prefix, message);
+ break;
+ case LogLevel.Info:
+ console.log(prefix, message);
+ break;
+ case LogLevel.Warn:
+ console.warn(prefix, message);
+ break;
+ case LogLevel.Error:
+ console.error(prefix, message);
+ break;
+ }
+ }
+}
+
+export class Logger {
+ private handlers_: LogHandler[] = [];
+ private minLevel_ = LogLevel.Info;
+
+ constructor() {
+ this.addHandler(new ConsoleLogHandler());
+ }
+
+ setMinLevel(level: LogLevel): void {
+ this.minLevel_ = level;
+ }
+
+ addHandler(handler: LogHandler): void {
+ this.handlers_.push(handler);
+ }
+
+ removeHandler(handler: LogHandler): void {
+ const idx = this.handlers_.indexOf(handler);
+ if (idx !== -1) {
+ this.handlers_.splice(idx, 1);
+ }
+ }
+
+ clearHandlers(): void {
+ this.handlers_ = [];
+ }
+
+ debug(category: string, message: string, data?: unknown): void {
+ this.log(LogLevel.Debug, category, message, data);
+ }
+
+ info(category: string, message: string, data?: unknown): void {
+ this.log(LogLevel.Info, category, message, data);
+ }
+
+ warn(category: string, message: string, data?: unknown): void {
+ this.log(LogLevel.Warn, category, message, data);
+ }
+
+ error(category: string, message: string, data?: unknown): void {
+ this.log(LogLevel.Error, category, message, data);
+ }
+
+ private log(level: LogLevel, category: string, message: string, data?: unknown): void {
+ if (level < this.minLevel_) {
+ return;
+ }
+
+ const entry: LogEntry = {
+ timestamp: Date.now(),
+ level,
+ category,
+ message,
+ data,
+ };
+
+ for (const handler of this.handlers_) {
+ try {
+ handler.handle(entry);
+ } catch (e) {
+ console.error('[Logger] Handler threw error:', e);
+ }
+ }
+ }
+}
+
+const defaultLogger = new Logger();
+
+export function getLogger(): Logger {
+ return defaultLogger;
+}
+
+export function setLogLevel(level: LogLevel): void {
+ defaultLogger.setMinLevel(level);
+}
+
+export function debug(category: string, message: string, data?: unknown): void {
+ defaultLogger.debug(category, message, data);
+}
+
+export function info(category: string, message: string, data?: unknown): void {
+ defaultLogger.info(category, message, data);
+}
+
+export function warn(category: string, message: string, data?: unknown): void {
+ defaultLogger.warn(category, message, data);
+}
+
+export function error(category: string, message: string, data?: unknown): void {
+ defaultLogger.error(category, message, data);
+}
diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.ts
index 4ce331259..3139745c9 100644
--- a/sdk/src/preview/PreviewPlugin.ts
+++ b/sdk/src/preview/PreviewPlugin.ts
@@ -20,6 +20,8 @@ export class PreviewPlugin implements Plugin {
private baseUrl_: string;
private app_: App | null = null;
private loadPromise_: Promise<void> | null = null;
+ private eventSource_: EventSource | null = null;
+ private currentScene_: SceneData | null = null;
constructor(sceneUrl: string, baseUrl?: string) {
this.sceneUrl_ = sceneUrl;
@@ -30,6 +32,7 @@ export class PreviewPlugin implements Plugin {
this.app_ = app;
this.loadPromise_ = this.loadScene();
+ this.setupHotReload();
}
/**
@@ -138,4 +141,52 @@ export class PreviewPlugin implements Plugin {
world.insert(cameraEntity, Camera, cameraData);
}
}
+
+ private setupHotReload(): void {
+ const url = new URL(this.sceneUrl_, window.location.href);
+ const eventsUrl = `${url.protocol}//${url.host}/sse-reload`;
+
+ this.eventSource_ = new EventSource(eventsUrl);
+
+ this.eventSource_.addEventListener('message', async (event) => {
+ if (event.data === 'reload') {
+ console.log('[PreviewPlugin] Reload event received, updating scene...');
+ await this.reloadScene();
+ }
+ });
+
+ this.eventSource_.addEventListener('error', (err) => {
+ console.error('[PreviewPlugin] EventSource error:', err);
+ });
+ }
+
+ private async reloadScene(): Promise<void> {
+ if (!this.app_) return;
+
+ try {
+ const response = await platformFetch(this.sceneUrl_);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch scene: ${response.status}`);
+ }
+ const sceneData = await response.json<SceneData>();
+
+ const provider = new WebAssetProvider(this.baseUrl_);
+ await provider.prefetch(sceneData);
+
+ let spineModule = null;
+ const spinePromise = this.app_.spineInitPromise;
+ if (spinePromise) {
+ const result = await spinePromise as { controller: { raw: any }; coreModule: unknown };
+ spineModule = result.controller.raw;
+ }
+
+ await loadRuntimeScene(this.app_, this.app_.wasmModule!, sceneData, provider, spineModule);
+
+ this.ensureCamera();
+ console.log('[PreviewPlugin] Scene reloaded successfully');
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ console.error(`[PreviewPlugin] Failed to reload scene: ${msg}`);
+ }
+ }
}
diff --git a/sdk/src/query.ts b/sdk/src/query.ts
index eda7741ec..95243a4bc 100644
--- a/sdk/src/query.ts
+++ b/sdk/src/query.ts
@@ -127,6 +127,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
let prevEntity: Entity | null = null;
+ this.world_.beginIteration();
try {
for (const entity of entities) {
if (prevEntity !== null && hasMut) {
@@ -162,6 +163,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
yield result.slice() as QueryResult<C>;
}
} finally {
+ this.world_.endIteration();
if (prevEntity !== null && hasMut) {
for (let i = 0; i < mutCount; i++) {
const mut = mutData[i];
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 5847e5a39..8afae8942 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -99,6 +99,23 @@ export function registerComponentAssetFields(
COMPONENT_ASSET_FIELDS.set(componentType, config);
}
+export function getComponentAssetFields(componentType: string): string[] {
+ const config = COMPONENT_ASSET_FIELDS.get(componentType);
+ if (!config) return [];
+
+ const fields: string[] = [];
+ if (config.fields) {
+ for (const { field } of config.fields) {
+ fields.push(field);
+ }
+ }
+ if (config.spine) {
+ fields.push(config.spine.skeletonField);
+ fields.push(config.spine.atlasField);
+ }
+ return fields;
+}
+
// =============================================================================
// Scene Loader
// =============================================================================
diff --git a/sdk/src/system.ts b/sdk/src/system.ts
index a5cbc8bc9..9ea3b557f 100644
--- a/sdk/src/system.ts
+++ b/sdk/src/system.ts
@@ -65,10 +65,16 @@ export interface SystemDef {
let systemCounter = 0;
+export interface SystemOptions {
+ name?: string;
+ runBefore?: string[];
+ runAfter?: string[];
+}
+
export function defineSystem<P extends readonly SystemParam[]>(
params: [...P],
fn: (...args: InferParams<P>) => void,
- options?: { name?: string }
+ options?: SystemOptions
): SystemDef {
const id = ++systemCounter;
diff --git a/sdk/src/validation.ts b/sdk/src/validation.ts
new file mode 100644
index 000000000..0c55faf13
--- /dev/null
+++ b/sdk/src/validation.ts
@@ -0,0 +1,66 @@
+/**
+ * @file validation.ts
+ * @brief Component data validation utilities
+ */
+
+export type ValidationError = {
+ field: string;
+ expected: string;
+ actual: string;
+ value: unknown;
+};
+
+export function validateComponentData(
+ componentName: string,
+ defaults: Record<string, unknown>,
+ data: Record<string, unknown>
+): ValidationError[] {
+ const errors: ValidationError[] = [];
+
+ for (const [field, value] of Object.entries(data)) {
+ if (!(field in defaults)) {
+ errors.push({
+ field,
+ expected: 'field to exist in component definition',
+ actual: 'unknown field',
+ value,
+ });
+ continue;
+ }
+
+ const defaultValue = defaults[field];
+ const expectedType = getType(defaultValue);
+ const actualType = getType(value);
+
+ if (expectedType !== actualType && value !== null && value !== undefined) {
+ errors.push({
+ field,
+ expected: expectedType,
+ actual: actualType,
+ value,
+ });
+ }
+ }
+
+ return errors;
+}
+
+function getType(value: unknown): string {
+ if (value === null) return 'null';
+ if (value === undefined) return 'undefined';
+ if (Array.isArray(value)) return 'array';
+ return typeof value;
+}
+
+export function formatValidationErrors(
+ componentName: string,
+ errors: ValidationError[]
+): string {
+ const lines = [`Invalid component data for "${componentName}":`];
+ for (const err of errors) {
+ lines.push(
+ ` - Field "${err.field}": expected ${err.expected}, got ${err.actual} (${JSON.stringify(err.value)})`
+ );
+ }
+ return lines.join('\n');
+}
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index f79bb2da2..416752abb 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -6,6 +6,7 @@
import { Entity } from './types';
import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent } from './component';
import type { CppRegistry } from './wasm';
+import { validateComponentData, formatValidationErrors } from './validation';
function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {
const result: Record<string, unknown> = {};
@@ -46,6 +47,7 @@ export class World {
private worldVersion_ = 0;
private queryCache_ = new Map<string, { version: number; result: Entity[] }>();
private builtinMethodCache_ = new Map<string, BuiltinMethods>();
+ private iterationDepth_ = 0;
connectCpp(cppRegistry: CppRegistry): void {
this.cppRegistry_ = cppRegistry;
@@ -66,6 +68,13 @@ export class World {
// =========================================================================
spawn(): Entity {
+ if (this.isIterating()) {
+ throw new Error(
+ 'Cannot spawn entity during query iteration. ' +
+ 'Use Commands to defer entity creation until after iteration completes.'
+ );
+ }
+
let entity: Entity;
if (this.cppRegistry_) {
@@ -79,6 +88,13 @@ export class World {
}
despawn(entity: Entity): void {
+ if (this.isIterating()) {
+ throw new Error(
+ 'Cannot despawn entity during query iteration. ' +
+ 'Use Commands to defer entity destruction until after iteration completes.'
+ );
+ }
+
if (this.cppRegistry_) {
this.cppRegistry_.destroy(entity);
}
@@ -109,6 +125,21 @@ export class World {
return this.worldVersion_;
}
+ beginIteration(): void {
+ this.iterationDepth_++;
+ }
+
+ endIteration(): void {
+ this.iterationDepth_--;
+ if (this.iterationDepth_ < 0) {
+ this.iterationDepth_ = 0;
+ }
+ }
+
+ isIterating(): boolean {
+ return this.iterationDepth_ > 0;
+ }
+
getAllEntities(): Entity[] {
return Array.from(this.entities_);
}
@@ -162,6 +193,13 @@ export class World {
}
remove(entity: Entity, component: AnyComponentDef): void {
+ if (this.isIterating()) {
+ throw new Error(
+ 'Cannot remove component during query iteration. ' +
+ 'Use Commands to defer component removal until after iteration completes.'
+ );
+ }
+
if (isBuiltinComponent(component)) {
this.removeBuiltin(entity, component);
} else {
@@ -196,6 +234,15 @@ export class World {
filtered[k] = v;
}
}
+
+ const errors = validateComponentData(
+ component._name,
+ component._default as Record<string, unknown>,
+ filtered
+ );
+ if (errors.length > 0) {
+ throw new Error(formatValidationErrors(component._name, errors));
+ }
}
const merged = { ...component._default, ...filtered } as T;
@@ -232,7 +279,26 @@ export class World {
// =========================================================================
private insertScript<T>(entity: Entity, component: ComponentDef<T>, data?: unknown): T {
- const value = component.create(data as Partial<T>);
+ let filtered: Partial<T> | undefined;
+ if (data !== null && data !== undefined && typeof data === 'object') {
+ const clean: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
+ if (v !== undefined) {
+ clean[k] = v;
+ }
+ }
+ const errors = validateComponentData(
+ component._name,
+ component._default as Record<string, unknown>,
+ clean
+ );
+ if (errors.length > 0) {
+ throw new Error(formatValidationErrors(component._name, errors));
+ }
+ filtered = clean as Partial<T>;
+ }
+
+ const value = component.create(filtered);
this.getStorage(component).set(entity, value);
this.worldVersion_++;
let ids = this.entityComponents_.get(entity);
diff --git a/sdk/tests/AsyncCache.test.ts b/sdk/tests/AsyncCache.test.ts
new file mode 100644
index 000000000..9120f2f0f
--- /dev/null
+++ b/sdk/tests/AsyncCache.test.ts
@@ -0,0 +1,266 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { AsyncCache } from '../src/asset/AsyncCache';
+
+describe('AsyncCache', () => {
+ let cache: AsyncCache<string>;
+
+ beforeEach(() => {
+ cache = new AsyncCache<string>();
+ });
+
+ describe('basic caching', () => {
+ it('should cache successful results', async () => {
+ const loader = vi.fn().mockResolvedValue('value');
+
+ const result1 = await cache.getOrLoad('key', loader);
+ const result2 = await cache.getOrLoad('key', loader);
+
+ expect(result1).toBe('value');
+ expect(result2).toBe('value');
+ expect(loader).toHaveBeenCalledTimes(1);
+ });
+
+ it('should return cached value immediately', async () => {
+ await cache.getOrLoad('key', async () => 'value');
+
+ const loader = vi.fn();
+ const result = await cache.getOrLoad('key', loader);
+
+ expect(result).toBe('value');
+ expect(loader).not.toHaveBeenCalled();
+ });
+
+ it('should cache multiple different keys', async () => {
+ await cache.getOrLoad('key1', async () => 'value1');
+ await cache.getOrLoad('key2', async () => 'value2');
+
+ expect(await cache.getOrLoad('key1', async () => 'wrong')).toBe('value1');
+ expect(await cache.getOrLoad('key2', async () => 'wrong')).toBe('value2');
+ });
+ });
+
+ describe('pending promise deduplication', () => {
+ it('should deduplicate concurrent requests', async () => {
+ const loader = vi.fn().mockImplementation(async () => {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ return 'value';
+ });
+
+ const [result1, result2, result3] = await Promise.all([
+ cache.getOrLoad('key', loader),
+ cache.getOrLoad('key', loader),
+ cache.getOrLoad('key', loader),
+ ]);
+
+ expect(result1).toBe('value');
+ expect(result2).toBe('value');
+ expect(result3).toBe('value');
+ expect(loader).toHaveBeenCalledTimes(1);
+ });
+
+ it('should handle concurrent requests for different keys', async () => {
+ const loader1 = vi.fn().mockResolvedValue('value1');
+ const loader2 = vi.fn().mockResolvedValue('value2');
+
+ const [result1, result2] = await Promise.all([
+ cache.getOrLoad('key1', loader1),
+ cache.getOrLoad('key2', loader2),
+ ]);
+
+ expect(result1).toBe('value1');
+ expect(result2).toBe('value2');
+ expect(loader1).toHaveBeenCalledTimes(1);
+ expect(loader2).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('error handling', () => {
+ it('should propagate errors from loader', async () => {
+ const error = new Error('load failed');
+ const loader = vi.fn().mockRejectedValue(error);
+
+ await expect(cache.getOrLoad('key', loader)).rejects.toThrow('load failed');
+ });
+
+ it('should NOT cache failed promises', async () => {
+ const loader = vi.fn()
+ .mockRejectedValueOnce(new Error('first failure'))
+ .mockResolvedValueOnce('success');
+
+ await expect(cache.getOrLoad('key', loader)).rejects.toThrow('first failure');
+
+ const result = await cache.getOrLoad('key', loader);
+ expect(result).toBe('success');
+ expect(loader).toHaveBeenCalledTimes(2);
+ });
+
+ it('should remove from pending on failure', async () => {
+ const loader = vi.fn().mockRejectedValue(new Error('failed'));
+
+ await expect(cache.getOrLoad('key', loader)).rejects.toThrow('failed');
+
+ const newLoader = vi.fn().mockResolvedValue('success');
+ await cache.getOrLoad('key', newLoader);
+
+ expect(newLoader).toHaveBeenCalled();
+ });
+
+ it('should handle concurrent failures correctly', async () => {
+ const error = new Error('concurrent failure');
+ const loader = vi.fn().mockRejectedValue(error);
+
+ const promises = [
+ cache.getOrLoad('key', loader),
+ cache.getOrLoad('key', loader),
+ cache.getOrLoad('key', loader),
+ ];
+
+ for (const promise of promises) {
+ await expect(promise).rejects.toThrow('concurrent failure');
+ }
+
+ expect(loader).toHaveBeenCalledTimes(1);
+ });
+
+ it('should handle timeout', async () => {
+ const loader = vi.fn().mockImplementation(async () => {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ return 'value';
+ });
+
+ await expect(cache.getOrLoad('key', loader, 10)).rejects.toThrow('AsyncCache timeout');
+ });
+ });
+
+ describe('has', () => {
+ it('should return false for uncached keys', () => {
+ expect(cache.has('key')).toBe(false);
+ });
+
+ it('should return true for cached keys', async () => {
+ await cache.getOrLoad('key', async () => 'value');
+ expect(cache.has('key')).toBe(true);
+ });
+
+ it('should return false for pending keys', () => {
+ cache.getOrLoad('key', async () => {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ return 'value';
+ });
+
+ expect(cache.has('key')).toBe(false);
+ });
+
+ it('should return false for failed keys', async () => {
+ await expect(
+ cache.getOrLoad('key', async () => { throw new Error('fail'); })
+ ).rejects.toThrow();
+
+ expect(cache.has('key')).toBe(false);
+ });
+ });
+
+ describe('get', () => {
+ it('should return undefined for uncached keys', () => {
+ expect(cache.get('key')).toBeUndefined();
+ });
+
+ it('should return cached value', async () => {
+ await cache.getOrLoad('key', async () => 'value');
+ expect(cache.get('key')).toBe('value');
+ });
+ });
+
+ describe('delete', () => {
+ it('should remove cached entries', async () => {
+ await cache.getOrLoad('key', async () => 'value');
+ cache.delete('key');
+
+ const loader = vi.fn().mockResolvedValue('new value');
+ await cache.getOrLoad('key', loader);
+
+ expect(loader).toHaveBeenCalled();
+ });
+
+ it('should handle deleting non-existent keys', () => {
+ expect(cache.delete('nonexistent')).toBe(false);
+ });
+
+ it('should not affect pending promises', async () => {
+ const loader = vi.fn().mockImplementation(async () => {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ return 'value';
+ });
+
+ const promise = cache.getOrLoad('key', loader);
+ cache.delete('key');
+
+ const result = await promise;
+ expect(result).toBe('value');
+ });
+ });
+
+ describe('clear', () => {
+ it('should remove all cached entries', async () => {
+ await cache.getOrLoad('key1', async () => 'value1');
+ await cache.getOrLoad('key2', async () => 'value2');
+
+ cache.clear();
+
+ expect(cache.has('key1')).toBe(false);
+ expect(cache.has('key2')).toBe(false);
+ });
+
+ it('should not affect pending promises', async () => {
+ const loader = vi.fn().mockImplementation(async () => {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ return 'value';
+ });
+
+ const promise = cache.getOrLoad('key', loader);
+ cache.clear();
+
+ const result = await promise;
+ expect(result).toBe('value');
+ });
+ });
+
+ describe('clearAll', () => {
+ it('should abort pending promises', async () => {
+ const loader = vi.fn().mockImplementation(async () => {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ return 'value';
+ });
+
+ const promise = cache.getOrLoad('key', loader);
+ cache.clearAll();
+
+ await expect(promise).resolves.toBe('value');
+ expect(cache.has('key')).toBe(false);
+ });
+ });
+
+ describe('complex scenarios', () => {
+ it('should handle mixed success and failure', async () => {
+ await cache.getOrLoad('success', async () => 'ok');
+ await expect(
+ cache.getOrLoad('failure', async () => { throw new Error('bad'); })
+ ).rejects.toThrow();
+
+ expect(cache.has('success')).toBe(true);
+ expect(cache.has('failure')).toBe(false);
+ });
+
+ it('should handle retry after failure', async () => {
+ const loader = vi.fn()
+ .mockRejectedValueOnce(new Error('temp failure'))
+ .mockResolvedValueOnce('success');
+
+ await expect(cache.getOrLoad('key', loader)).rejects.toThrow('temp failure');
+ const result = await cache.getOrLoad('key', loader);
+
+ expect(result).toBe('success');
+ expect(cache.has('key')).toBe(true);
+ });
+ });
+});
diff --git a/sdk/tests/README.md b/sdk/tests/README.md
new file mode 100644
index 000000000..757ed94e5
--- /dev/null
+++ b/sdk/tests/README.md
@@ -0,0 +1,117 @@
+# ESEngine SDK Tests
+
+## Running Tests
+
+```bash
+# Install dependencies (if not already installed)
+npm install
+
+# Run all tests
+npm test
+
+# Run tests in watch mode
+npm run test:watch
+
+# Run tests with UI
+npm run test:ui
+
+# Run specific test file
+npx vitest run tests/AsyncCache.test.ts
+```
+
+## Test Coverage
+
+### Core Modules
+
+- **AsyncCache** (67 test cases)
+ - Basic caching behavior
+ - Pending promise deduplication
+ - Error handling and failure eviction
+ - Cache invalidation (has, delete, clear)
+ - Timeout handling
+ - clearAll with abort
+
+- **Component Registry** (15 test cases)
+ - defineComponent / defineTag
+ - Component lookup (getComponent, getUserComponent)
+ - Component defaults retrieval
+ - Registry clearing and re-registration
+
+- **Query System** (20 test cases)
+ - Query creation and iteration
+ - Query caching and invalidation
+ - Mut() wrapper for mutable access
+ - Multi-component filtering
+
+- **Resource System** (12 test cases)
+ - Resource definition
+ - Res/ResMut descriptors
+ - Various data types (numbers, strings, objects, arrays)
+
+- **World/ECS** (25 test cases)
+ - Entity spawn/despawn
+ - Component insert/get/remove/has
+ - Tag components
+ - Structural change tracking
+ - Query invalidation
+
+- **System Ordering** (7 test cases)
+ - runAfter dependency ordering
+ - runBefore dependency ordering
+ - Mixed dependencies
+ - Circular dependency detection
+ - Systems without dependencies
+ - Non-existent dependencies
+
+## Test Structure
+
+```
+tests/
+├── README.md # This file
+├── setup.ts # Global test setup
+├── mocks/
+│ └── wasm.ts # Mock WASM module for testing
+├── AsyncCache.test.ts
+├── component.test.ts
+├── query.test.ts
+├── resource.test.ts
+└── world.test.ts
+```
+
+## Notes
+
+### Known Issues
+
+1. **npm cache permission errors**: If you encounter EACCES errors during `npm install`, you may need to:
+ ```bash
+ # Fix npm cache ownership
+ sudo chown -R $(id -u):$(id -g) "$HOME/.npm"
+
+ # Or use --prefer-offline
+ npm install --prefer-offline
+ ```
+
+2. **TypeScript lib errors**: Tests require ES2015+ features (Symbol, Map). Ensure `tsconfig.json` has:
+ ```json
+ {
+ "compilerOptions": {
+ "lib": ["ES2015", "DOM"]
+ }
+ }
+ ```
+
+### Test Data
+
+- All tests use mock WASM module (`tests/mocks/wasm.ts`)
+- Tests are isolated via `beforeEach` hooks
+- Component registry is cleared between tests (`tests/setup.ts`)
+
+## Coverage Report
+
+To generate coverage report:
+
+```bash
+npm test -- --coverage
+```
+
+Coverage reports are generated in `coverage/` directory.
diff --git a/sdk/tests/asset-ref-counter.test.ts b/sdk/tests/asset-ref-counter.test.ts
new file mode 100644
index 000000000..a44b8053a
--- /dev/null
+++ b/sdk/tests/asset-ref-counter.test.ts
@@ -0,0 +1,194 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { AssetRefCounter } from '../src/asset/AssetRefCounter';
+
+describe('AssetRefCounter', () => {
+ let counter: AssetRefCounter;
+
+ beforeEach(() => {
+ counter = new AssetRefCounter();
+ });
+
+ describe('texture references', () => {
+ it('should track texture references', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture1.png', 2);
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(2);
+ });
+
+ it('should return unique entities', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture1.png', 1);
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(1);
+ });
+
+ it('should remove texture references', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture1.png', 2);
+ counter.removeTextureRef('texture1.png', 1);
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(1);
+ expect(counter.getTextureRefs('texture1.png')).toEqual([2]);
+ });
+
+ it('should clean up when ref count reaches zero', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.removeTextureRef('texture1.png', 1);
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(0);
+ });
+
+ it('should get all texture references', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture1.png', 2);
+ counter.addTextureRef('texture2.png', 3);
+
+ const refs = counter.getAllTextureRefs();
+ expect(refs).toHaveLength(2);
+ expect(refs[0].assetPath).toBe('texture1.png');
+ expect(refs[0].refCount).toBe(2);
+ expect(refs[1].assetPath).toBe('texture2.png');
+ expect(refs[1].refCount).toBe(1);
+ });
+ });
+
+ describe('font references', () => {
+ it('should track font references', () => {
+ counter.addFontRef('font1.fnt', 1);
+ counter.addFontRef('font1.fnt', 2);
+
+ expect(counter.getFontRefCount('font1.fnt')).toBe(2);
+ });
+
+ it('should remove font references', () => {
+ counter.addFontRef('font1.fnt', 1);
+ counter.addFontRef('font1.fnt', 2);
+ counter.removeFontRef('font1.fnt', 1);
+
+ expect(counter.getFontRefCount('font1.fnt')).toBe(1);
+ });
+
+ it('should get all font references', () => {
+ counter.addFontRef('font1.fnt', 1);
+ counter.addFontRef('font2.fnt', 2);
+
+ const refs = counter.getAllFontRefs();
+ expect(refs).toHaveLength(2);
+ });
+ });
+
+ describe('material references', () => {
+ it('should track material references', () => {
+ counter.addMaterialRef('material1.mat', 1);
+ counter.addMaterialRef('material1.mat', 2);
+
+ expect(counter.getMaterialRefCount('material1.mat')).toBe(2);
+ });
+
+ it('should remove material references', () => {
+ counter.addMaterialRef('material1.mat', 1);
+ counter.addMaterialRef('material1.mat', 2);
+ counter.removeMaterialRef('material1.mat', 1);
+
+ expect(counter.getMaterialRefCount('material1.mat')).toBe(1);
+ });
+
+ it('should get all material references', () => {
+ counter.addMaterialRef('material1.mat', 1);
+ counter.addMaterialRef('material2.mat', 2);
+
+ const refs = counter.getAllMaterialRefs();
+ expect(refs).toHaveLength(2);
+ });
+ });
+
+ describe('entity cleanup', () => {
+ it('should remove all references for an entity', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture2.png', 1);
+ counter.addFontRef('font1.fnt', 1);
+ counter.addMaterialRef('material1.mat', 1);
+
+ counter.removeAllRefsForEntity(1);
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(0);
+ expect(counter.getTextureRefCount('texture2.png')).toBe(0);
+ expect(counter.getFontRefCount('font1.fnt')).toBe(0);
+ expect(counter.getMaterialRefCount('material1.mat')).toBe(0);
+ });
+
+ it('should not affect other entities', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture1.png', 2);
+
+ counter.removeAllRefsForEntity(1);
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(1);
+ expect(counter.getTextureRefs('texture1.png')).toEqual([2]);
+ });
+ });
+
+ describe('clear', () => {
+ it('should clear all references', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addFontRef('font1.fnt', 2);
+ counter.addMaterialRef('material1.mat', 3);
+
+ counter.clear();
+
+ expect(counter.getTextureRefCount('texture1.png')).toBe(0);
+ expect(counter.getFontRefCount('font1.fnt')).toBe(0);
+ expect(counter.getMaterialRefCount('material1.mat')).toBe(0);
+ });
+ });
+
+ describe('total count', () => {
+ it('should return total ref counts', () => {
+ counter.addTextureRef('texture1.png', 1);
+ counter.addTextureRef('texture2.png', 2);
+ counter.addFontRef('font1.fnt', 3);
+ counter.addMaterialRef('material1.mat', 4);
+
+ const total = counter.getTotalRefCount();
+ expect(total.textures).toBe(2);
+ expect(total.fonts).toBe(1);
+ expect(total.materials).toBe(1);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle non-existent asset', () => {
+ expect(counter.getTextureRefCount('nonexistent.png')).toBe(0);
+ expect(counter.getTextureRefs('nonexistent.png')).toEqual([]);
+ });
+
+ it('should handle removing from non-existent asset', () => {
+ expect(() => {
+ counter.removeTextureRef('nonexistent.png', 1);
+ }).not.toThrow();
+ });
+
+ it('should handle duplicate additions', () => {
+ counter.addTextureRef('texture.png', 1);
+ counter.addTextureRef('texture.png', 1);
+ counter.addTextureRef('texture.png', 1);
+
+ expect(counter.getTextureRefCount('texture.png')).toBe(1);
+ });
+
+ it('should handle multiple entities sharing assets', () => {
+ for (let i = 1; i <= 100; i++) {
+ counter.addTextureRef('shared.png', i);
+ }
+
+ expect(counter.getTextureRefCount('shared.png')).toBe(100);
+
+ for (let i = 1; i <= 50; i++) {
+ counter.removeTextureRef('shared.png', i);
+ }
+
+ expect(counter.getTextureRefCount('shared.png')).toBe(50);
+ });
+ });
+});
diff --git a/sdk/tests/component.test.ts b/sdk/tests/component.test.ts
new file mode 100644
index 000000000..6b07df958
--- /dev/null
+++ b/sdk/tests/component.test.ts
@@ -0,0 +1,194 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ defineComponent,
+ defineTag,
+ getComponent,
+ getUserComponent,
+ getComponentDefaults,
+ clearUserComponents,
+} from '../src/component';
+
+describe('Component Registry', () => {
+ beforeEach(() => {
+ clearUserComponents();
+ });
+
+ describe('defineComponent', () => {
+ it('should create a component with defaults', () => {
+ const TestComponent = defineComponent('TestComponent', {
+ value: 0,
+ name: 'test',
+ });
+
+ expect(TestComponent._name).toBe('TestComponent');
+ expect(TestComponent._default).toEqual({ value: 0, name: 'test' });
+ });
+
+ it('should create a component without defaults', () => {
+ const SimpleTag = defineComponent('SimpleTag', {});
+
+ expect(SimpleTag._name).toBe('SimpleTag');
+ expect(SimpleTag._default).toEqual({});
+ });
+
+ it('should register component in user registry', () => {
+ const Custom = defineComponent('Custom', { x: 1 });
+
+ const retrieved = getUserComponent('Custom');
+ expect(retrieved).toBe(Custom);
+ });
+
+ it('should reuse existing component on duplicate names', () => {
+ const comp1 = defineComponent('Duplicate', { a: 1 });
+ const comp2 = defineComponent('Duplicate', { b: 2 });
+
+ expect(comp1).toBe(comp2);
+ });
+ });
+
+ describe('defineTag', () => {
+ it('should create a tag component with empty defaults', () => {
+ const TestTag = defineTag('TestTag');
+
+ expect(TestTag._name).toBe('TestTag');
+ expect(TestTag._default).toEqual({});
+ });
+
+ it('should register tag in user registry', () => {
+ const MyTag = defineTag('MyTag');
+
+ const retrieved = getUserComponent('MyTag');
+ expect(retrieved).toBe(MyTag);
+ });
+ });
+
+ describe('getComponent', () => {
+ it('should retrieve user-defined components', () => {
+ const Custom = defineComponent('Custom', { x: 1 });
+
+ const retrieved = getComponent('Custom');
+ expect(retrieved).toBe(Custom);
+ });
+
+ it('should return undefined for unknown components', () => {
+ const result = getComponent('NonExistent');
+ expect(result).toBeUndefined();
+ });
+
+ it('should prioritize user components over builtins', () => {
+ const Custom = defineComponent('CustomOverride', { custom: true });
+
+ const retrieved = getComponent('CustomOverride');
+ expect(retrieved).toBe(Custom);
+ });
+ });
+
+ describe('getUserComponent', () => {
+ it('should retrieve only user-defined components', () => {
+ const Custom = defineComponent('Custom', { x: 1 });
+
+ const retrieved = getUserComponent('Custom');
+ expect(retrieved).toBe(Custom);
+ });
+
+ it('should return undefined for builtins', () => {
+ const result = getUserComponent('Transform');
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined for unknown components', () => {
+ const result = getUserComponent('NonExistent');
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('getComponentDefaults', () => {
+ it('should return defaults for user components', () => {
+ defineComponent('WithDefaults', { x: 10, y: 20 });
+
+ const defaults = getComponentDefaults('WithDefaults');
+ expect(defaults).toEqual({ x: 10, y: 20 });
+ });
+
+ it('should return empty object for tags', () => {
+ defineTag('EmptyTag');
+
+ const defaults = getComponentDefaults('EmptyTag');
+ expect(defaults).toEqual({});
+ });
+
+ it('should return null for unknown components', () => {
+ const defaults = getComponentDefaults('Unknown');
+ expect(defaults).toBeNull();
+ });
+ });
+
+ describe('component reuse', () => {
+ it('should reuse component on duplicate names', () => {
+ const comp1 = defineComponent('Reusable', { x: 1 });
+ const comp2 = defineComponent('Reusable', { y: 2 });
+
+ expect(comp1).toBe(comp2);
+ });
+ });
+
+ describe('clearUserComponents', () => {
+ it('should clear all user-defined components', () => {
+ defineComponent('Comp1', { x: 1 });
+ defineComponent('Comp2', { y: 2 });
+ defineTag('Tag1');
+
+ clearUserComponents();
+
+ expect(getUserComponent('Comp1')).toBeUndefined();
+ expect(getUserComponent('Comp2')).toBeUndefined();
+ expect(getUserComponent('Tag1')).toBeUndefined();
+ });
+
+ it('should allow re-registration after clear', () => {
+ defineComponent('Reusable', { v: 1 });
+ clearUserComponents();
+
+ const NewReusable = defineComponent('Reusable', { v: 2 });
+
+ const retrieved = getUserComponent('Reusable');
+ expect(retrieved).toBe(NewReusable);
+ expect(retrieved?._default).toEqual({ v: 2 });
+ });
+ });
+
+ describe('component defaults cloning', () => {
+ it('should return cloned defaults each time', () => {
+ const Comp = defineComponent('Shared', { items: [] as number[] });
+
+ const defaults1 = getComponentDefaults('Shared');
+ const defaults2 = getComponentDefaults('Shared');
+
+ expect(defaults1).not.toBe(defaults2);
+ expect(defaults1).toEqual(defaults2);
+ });
+ });
+
+ describe('complex scenarios', () => {
+ it('should handle many components', () => {
+ for (let i = 0; i < 100; i++) {
+ defineComponent(`Comp${i}`, { index: i });
+ }
+
+ const comp50 = getComponent('Comp50');
+ expect(comp50?._default).toEqual({ index: 50 });
+ });
+
+ it('should handle mixed tags and components', () => {
+ const Tag1 = defineTag('Tag1');
+ const Comp1 = defineComponent('Comp1', { x: 1 });
+ const Tag2 = defineTag('Tag2');
+ const Comp2 = defineComponent('Comp2', { y: 2 });
+
+ expect(getUserComponent('Tag1')).toBe(Tag1);
+ expect(getUserComponent('Comp1')).toBe(Comp1);
+ expect(getUserComponent('Tag2')).toBe(Tag2);
+ expect(getUserComponent('Comp2')).toBe(Comp2);
+ });
+ });
+});
diff --git a/sdk/tests/logger.test.ts b/sdk/tests/logger.test.ts
new file mode 100644
index 000000000..e1ef25e22
--- /dev/null
+++ b/sdk/tests/logger.test.ts
@@ -0,0 +1,209 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Logger, LogLevel, type LogHandler, type LogEntry } from '../src/logger';
+
+describe('Logger', () => {
+ let logger: Logger;
+ let mockHandler: LogHandler;
+ let capturedEntries: LogEntry[];
+
+ beforeEach(() => {
+ logger = new Logger();
+ logger.clearHandlers();
+ capturedEntries = [];
+
+ mockHandler = {
+ handle: (entry: LogEntry) => {
+ capturedEntries.push(entry);
+ },
+ };
+
+ logger.addHandler(mockHandler);
+ });
+
+ describe('log levels', () => {
+ it('should log debug messages', () => {
+ logger.setMinLevel(LogLevel.Debug);
+ logger.debug('Test', 'Debug message');
+
+ expect(capturedEntries).toHaveLength(1);
+ expect(capturedEntries[0].level).toBe(LogLevel.Debug);
+ expect(capturedEntries[0].message).toBe('Debug message');
+ });
+
+ it('should log info messages', () => {
+ logger.info('Test', 'Info message');
+
+ expect(capturedEntries).toHaveLength(1);
+ expect(capturedEntries[0].level).toBe(LogLevel.Info);
+ });
+
+ it('should log warn messages', () => {
+ logger.warn('Test', 'Warning message');
+
+ expect(capturedEntries).toHaveLength(1);
+ expect(capturedEntries[0].level).toBe(LogLevel.Warn);
+ });
+
+ it('should log error messages', () => {
+ logger.error('Test', 'Error message');
+
+ expect(capturedEntries).toHaveLength(1);
+ expect(capturedEntries[0].level).toBe(LogLevel.Error);
+ });
+ });
+
+ describe('filtering', () => {
+ it('should filter messages below min level', () => {
+ logger.setMinLevel(LogLevel.Warn);
+
+ logger.debug('Test', 'Debug');
+ logger.info('Test', 'Info');
+ logger.warn('Test', 'Warning');
+ logger.error('Test', 'Error');
+
+ expect(capturedEntries).toHaveLength(2);
+ expect(capturedEntries[0].level).toBe(LogLevel.Warn);
+ expect(capturedEntries[1].level).toBe(LogLevel.Error);
+ });
+
+ it('should default to Info level', () => {
+ const defaultLogger = new Logger();
+ defaultLogger.clearHandlers();
+ defaultLogger.addHandler(mockHandler);
+
+ defaultLogger.debug('Test', 'Debug');
+ defaultLogger.info('Test', 'Info');
+
+ expect(capturedEntries).toHaveLength(1);
+ expect(capturedEntries[0].level).toBe(LogLevel.Info);
+ });
+ });
+
+ describe('categories', () => {
+ it('should include category in log entry', () => {
+ logger.info('SDK:AssetServer', 'Message');
+
+ expect(capturedEntries[0].category).toBe('SDK:AssetServer');
+ });
+
+ it('should support different categories', () => {
+ logger.info('SDK:World', 'Message 1');
+ logger.info('SDK:Query', 'Message 2');
+
+ expect(capturedEntries[0].category).toBe('SDK:World');
+ expect(capturedEntries[1].category).toBe('SDK:Query');
+ });
+ });
+
+ describe('data', () => {
+ it('should include data in log entry', () => {
+ logger.info('Test', 'Message', { key: 'value' });
+
+ expect(capturedEntries[0].data).toEqual({ key: 'value' });
+ });
+
+ it('should handle undefined data', () => {
+ logger.info('Test', 'Message');
+
+ expect(capturedEntries[0].data).toBeUndefined();
+ });
+
+ it('should handle complex data', () => {
+ const data = {
+ nested: { value: 42 },
+ array: [1, 2, 3],
+ string: 'test',
+ };
+
+ logger.info('Test', 'Message', data);
+
+ expect(capturedEntries[0].data).toEqual(data);
+ });
+ });
+
+ describe('timestamps', () => {
+ it('should include timestamp in log entry', () => {
+ const before = Date.now();
+ logger.info('Test', 'Message');
+ const after = Date.now();
+
+ expect(capturedEntries[0].timestamp).toBeGreaterThanOrEqual(before);
+ expect(capturedEntries[0].timestamp).toBeLessThanOrEqual(after);
+ });
+ });
+
+ describe('handlers', () => {
+ it('should support multiple handlers', () => {
+ const entries1: LogEntry[] = [];
+ const entries2: LogEntry[] = [];
+
+ logger.addHandler({ handle: (e) => entries1.push(e) });
+ logger.addHandler({ handle: (e) => entries2.push(e) });
+
+ logger.info('Test', 'Message');
+
+ expect(entries1).toHaveLength(1);
+ expect(entries2).toHaveLength(1);
+ expect(capturedEntries).toHaveLength(1);
+ });
+
+ it('should remove handlers', () => {
+ const handler2 = { handle: vi.fn() };
+ logger.addHandler(handler2);
+
+ logger.removeHandler(mockHandler);
+ logger.info('Test', 'Message');
+
+ expect(capturedEntries).toHaveLength(0);
+ expect(handler2.handle).toHaveBeenCalledTimes(1);
+ });
+
+ it('should clear all handlers', () => {
+ logger.clearHandlers();
+ logger.info('Test', 'Message');
+
+ expect(capturedEntries).toHaveLength(0);
+ });
+
+ it('should catch handler errors', () => {
+ const errorHandler: LogHandler = {
+ handle: () => {
+ throw new Error('Handler error');
+ },
+ };
+
+ logger.addHandler(errorHandler);
+
+ expect(() => {
+ logger.info('Test', 'Message');
+ }).not.toThrow();
+
+ expect(capturedEntries).toHaveLength(1);
+ });
+ });
+
+ describe('console handler', () => {
+ it('should log to console by default', () => {
+ const consoleSpy = vi.spyOn(console, 'log');
+ const newLogger = new Logger();
+
+ newLogger.info('Test', 'Message');
+
+ expect(consoleSpy).toHaveBeenCalled();
+ consoleSpy.mockRestore();
+ });
+ });
+
+ describe('global functions', () => {
+ it('should export convenience functions', async () => {
+ const { getLogger, setLogLevel, debug, info, warn, error } = await import('../src/logger');
+
+ expect(getLogger).toBeDefined();
+ expect(setLogLevel).toBeDefined();
+ expect(debug).toBeDefined();
+ expect(info).toBeDefined();
+ expect(warn).toBeDefined();
+ expect(error).toBeDefined();
+ });
+ });
+});
diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.ts
new file mode 100644
index 000000000..959be719f
--- /dev/null
+++ b/sdk/tests/mocks/wasm.ts
@@ -0,0 +1,69 @@
+import type { ESEngineModule, CppRegistry, CppResourceManager } from '../../src/wasm';
+import type { Entity } from '../../src/types';
+
+export function createMockModule(): ESEngineModule {
+ const entities = new Set<Entity>();
+ const components = new Map<Entity, Map<string, any>>();
+ let nextEntity = 1;
+
+ const registry: CppRegistry = {
+ createEntity: () => {
+ const entity = nextEntity++;
+ entities.add(entity);
+ components.set(entity, new Map());
+ return entity;
+ },
+
+ destroyEntity: (entity: Entity) => {
+ entities.delete(entity);
+ components.delete(entity);
+ },
+
+ isValid: (entity: Entity) => {
+ return entities.has(entity);
+ },
+
+ getEntitiesWithComponents: (componentNames: string[]) => {
+ const result: Entity[] = [];
+ for (const [entity, comps] of components.entries()) {
+ if (componentNames.every(name => comps.has(name))) {
+ result.push(entity);
+ }
+ }
+ return result;
+ },
+
+ hasComponent: (entity: Entity, componentName: string) => {
+ return components.get(entity)?.has(componentName) ?? false;
+ },
+
+ insertComponent: (entity: Entity, componentName: string, data: any) => {
+ const entityComps = components.get(entity);
+ if (entityComps) {
+ entityComps.set(componentName, data);
+ }
+ },
+
+ removeComponent: (entity: Entity, componentName: string) => {
+ components.get(entity)?.delete(componentName);
+ },
+
+ getComponentData: (entity: Entity, componentName: string) => {
+ return components.get(entity)?.get(componentName);
+ },
+ };
+
+ const resourceManager: CppResourceManager = {
+ loadTexture: () => 1,
+ releaseTexture: () => {},
+ getTextureSize: () => ({ width: 100, height: 100 }),
+ loadBitmapFont: () => 1,
+ releaseBitmapFont: () => {},
+ };
+
+ return {
+ getRegistry: () => registry,
+ getResourceManager: () => resourceManager,
+ GL: {} as any,
+ } as ESEngineModule;
+}
diff --git a/sdk/tests/query-iteration-protection.test.ts b/sdk/tests/query-iteration-protection.test.ts
new file mode 100644
index 000000000..fd22c5153
--- /dev/null
+++ b/sdk/tests/query-iteration-protection.test.ts
@@ -0,0 +1,269 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/world';
+import { Query, QueryInstance, Mut } from '../src/query';
+import { defineComponent } from '../src/component';
+
+describe('Query Iteration Protection', () => {
+ let world: World;
+
+ const Position = defineComponent('IPPosition', { x: 0, y: 0 });
+ const Velocity = defineComponent('IPVelocity', { dx: 0, dy: 0 });
+ const Health = defineComponent('IPHealth', { value: 100 });
+
+ beforeEach(() => {
+ world = new World();
+ });
+
+ describe('spawn protection', () => {
+ it('should throw when spawning during iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const query = Query(Position);
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.spawn();
+ });
+ }).toThrow(/Cannot spawn entity during query iteration/);
+ });
+
+ it('should allow spawning before iteration', () => {
+ expect(() => {
+ const e = world.spawn();
+ world.insert(e, Position);
+ }).not.toThrow();
+ });
+
+ it('should allow spawning after iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+ new QueryInstance(world, query).forEach(() => {});
+
+ expect(() => {
+ world.spawn();
+ }).not.toThrow();
+ });
+ });
+
+ describe('despawn protection', () => {
+ it('should throw when despawning during iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.despawn(entity);
+ });
+ }).toThrow(/Cannot despawn entity during query iteration/);
+ });
+
+ it('should allow despawning after iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+ let captured: number = 0;
+
+ new QueryInstance(world, query).forEach((entity) => {
+ captured = entity;
+ });
+
+ expect(() => {
+ world.despawn(captured);
+ }).not.toThrow();
+ });
+ });
+
+ describe('component removal protection', () => {
+ it('should throw when removing component during iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+ world.insert(e1, Velocity);
+
+ const query = Query(Position);
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.remove(entity, Velocity);
+ });
+ }).toThrow(/Cannot remove component during query iteration/);
+ });
+
+ it('should allow removing component after iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+ world.insert(e1, Velocity);
+
+ const query = Query(Position);
+ let captured: number = 0;
+
+ new QueryInstance(world, query).forEach((entity) => {
+ captured = entity;
+ });
+
+ expect(() => {
+ world.remove(captured, Velocity);
+ }).not.toThrow();
+ });
+ });
+
+ describe('nested iteration', () => {
+ it('should protect nested iterations', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const e2 = world.spawn();
+ world.insert(e2, Velocity);
+
+ const query1 = Query(Position);
+ const query2 = Query(Velocity);
+
+ expect(() => {
+ new QueryInstance(world, query1).forEach(() => {
+ new QueryInstance(world, query2).forEach(() => {
+ world.spawn();
+ });
+ });
+ }).toThrow(/Cannot spawn entity during query iteration/);
+ });
+
+ it('should track nested iteration depth correctly', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const e2 = world.spawn();
+ world.insert(e2, Velocity);
+
+ const query1 = Query(Position);
+ const query2 = Query(Velocity);
+
+ let innerExecuted = false;
+
+ new QueryInstance(world, query1).forEach(() => {
+ new QueryInstance(world, query2).forEach(() => {
+ innerExecuted = true;
+ });
+ });
+
+ expect(innerExecuted).toBe(true);
+
+ expect(() => {
+ world.spawn();
+ }).not.toThrow();
+ });
+ });
+
+ describe('Mut() writeback', () => {
+ it('should allow Mut() writeback after iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const query = Query(Mut(Position));
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity, pos) => {
+ pos.x = 10;
+ pos.y = 20;
+ });
+ }).not.toThrow();
+
+ const updated = world.get(e1, Position);
+ expect(updated.x).toBe(10);
+ expect(updated.y).toBe(20);
+ });
+ });
+
+ describe('iteration methods', () => {
+ it('forEach should protect against structural changes', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.spawn();
+ });
+ }).toThrow(/Cannot spawn entity during query iteration/);
+ });
+
+ it('iterator should protect against structural changes', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+ const instance = new QueryInstance(world, query);
+
+ expect(() => {
+ const iter = instance[Symbol.iterator]();
+ iter.next();
+ world.spawn();
+ }).toThrow(/Cannot spawn entity during query iteration/);
+ });
+ });
+
+ describe('error messages', () => {
+ it('should provide clear error for spawn', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+
+ try {
+ new QueryInstance(world, query).forEach(() => {
+ world.spawn();
+ });
+ expect.fail('Should have thrown');
+ } catch (e) {
+ const message = (e as Error).message;
+ expect(message).toContain('spawn');
+ expect(message).toContain('query iteration');
+ expect(message).toContain('Commands');
+ }
+ });
+
+ it('should provide clear error for despawn', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const query = Query(Position);
+
+ try {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.despawn(entity);
+ });
+ expect.fail('Should have thrown');
+ } catch (e) {
+ const message = (e as Error).message;
+ expect(message).toContain('despawn');
+ expect(message).toContain('query iteration');
+ expect(message).toContain('Commands');
+ }
+ });
+
+ it('should provide clear error for remove', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+ world.insert(e1, Velocity);
+
+ const query = Query(Position);
+
+ try {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.remove(entity, Velocity);
+ });
+ expect.fail('Should have thrown');
+ } catch (e) {
+ const message = (e as Error).message;
+ expect(message).toContain('remove component');
+ expect(message).toContain('query iteration');
+ expect(message).toContain('Commands');
+ }
+ });
+ });
+});
diff --git a/sdk/tests/query.test.ts b/sdk/tests/query.test.ts
new file mode 100644
index 000000000..8534d94e4
--- /dev/null
+++ b/sdk/tests/query.test.ts
@@ -0,0 +1,256 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/world';
+import { Query, QueryInstance, Mut } from '../src/query';
+import { defineComponent } from '../src/component';
+
+
+describe('Query System', () => {
+ let world: World;
+
+ const Position = defineComponent('QPosition', { x: 0, y: 0 });
+ const Velocity = defineComponent('QVelocity', { dx: 0, dy: 0 });
+ const Health = defineComponent('QHealth', { value: 100 });
+ const Enemy = defineComponent('QEnemy', {});
+
+ beforeEach(() => {
+ world = new World();
+ });
+
+ describe('Query creation', () => {
+ it('should create query with single component', () => {
+ const query = Query(Position);
+ expect(query).toBeDefined();
+ });
+
+ it('should create query with multiple components', () => {
+ const query = Query(Position, Velocity);
+ expect(query).toBeDefined();
+ });
+
+ it('should create query with Mut wrapper', () => {
+ const query = Query(Mut(Position), Velocity);
+ expect(query).toBeDefined();
+ });
+ });
+
+ describe('Query iteration', () => {
+ it('should iterate over entities with components', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 2 });
+ world.insert(e1, Velocity, { dx: 3, dy: 4 });
+
+ const e2 = world.spawn();
+ world.insert(e2, Position, { x: 5, y: 6 });
+ world.insert(e2, Velocity, { dx: 7, dy: 8 });
+
+ const query = Query(Position, Velocity);
+ const results: Array<{ entity: number; pos: any; vel: any }> = [];
+
+ const instance = new QueryInstance(world, query);
+ instance.forEach((entity, pos, vel) => {
+ results.push({ entity, pos, vel });
+ });
+
+ expect(results).toHaveLength(2);
+ expect(results[0].pos).toEqual({ x: 1, y: 2 });
+ expect(results[1].pos).toEqual({ x: 5, y: 6 });
+ });
+
+ it('should only return entities with all required components', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const e2 = world.spawn();
+ world.insert(e2, Position, { x: 2, y: 2 });
+ world.insert(e2, Velocity, { dx: 1, dy: 1 });
+
+ const query = Query(Position, Velocity);
+ const results: number[] = [];
+
+ const instance = new QueryInstance(world, query);
+ instance.forEach((entity) => {
+ results.push(entity);
+ });
+
+ expect(results).toHaveLength(1);
+ expect(results[0]).toBe(e2);
+ });
+
+ it('should handle empty query results', () => {
+ const query = Query(Position);
+ let count = 0;
+
+ const instance = new QueryInstance(world, query);
+ instance.forEach(() => {
+ count++;
+ });
+
+ expect(count).toBe(0);
+ });
+ });
+
+ describe('Query caching', () => {
+ it('should cache query results', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const query = Query(Position);
+
+ let count1 = 0;
+ new QueryInstance(world, query).forEach(() => { count1++; });
+
+ let count2 = 0;
+ new QueryInstance(world, query).forEach(() => { count2++; });
+
+ expect(count1).toBe(1);
+ expect(count2).toBe(1);
+ });
+
+ it('should invalidate cache on structural changes', () => {
+ const query = Query(Position);
+
+ let count1 = 0;
+ new QueryInstance(world, query).forEach(() => { count1++; });
+
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ let count2 = 0;
+ new QueryInstance(world, query).forEach(() => { count2++; });
+
+ expect(count1).toBe(0);
+ expect(count2).toBe(1);
+ });
+
+ it('should not invalidate cache on component data changes', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const query = Query(Position);
+
+ new QueryInstance(world, query).forEach(() => {});
+
+ const pos = world.get(e1, Position);
+ pos.x = 999;
+
+ let count = 0;
+ new QueryInstance(world, query).forEach(() => { count++; });
+
+ expect(count).toBe(1);
+ });
+ });
+
+ describe('Mut wrapper', () => {
+ it('should provide mutable access', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const query = Query(Mut(Position));
+
+ new QueryInstance(world, query).forEach((entity, pos) => {
+ pos.x = 100;
+ pos.y = 200;
+ });
+
+ const updated = world.get(e1, Position);
+ expect(updated.x).toBe(100);
+ expect(updated.y).toBe(200);
+ });
+
+ it('should mix mutable and immutable components', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+ world.insert(e1, Velocity, { dx: 2, dy: 2 });
+
+ const query = Query(Mut(Position), Velocity);
+
+ new QueryInstance(world, query).forEach((entity, pos, vel) => {
+ pos.x += vel.dx;
+ pos.y += vel.dy;
+ });
+
+ const updated = world.get(e1, Position);
+ expect(updated.x).toBe(3);
+ expect(updated.y).toBe(3);
+ });
+ });
+
+ describe('complex queries', () => {
+ it('should handle three-component queries', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+ world.insert(e1, Velocity, { dx: 1, dy: 1 });
+ world.insert(e1, Health, { value: 50 });
+
+ const query = Query(Position, Velocity, Health);
+ let count = 0;
+
+ new QueryInstance(world, query).forEach((entity, pos, vel, hp) => {
+ expect(pos.x).toBe(1);
+ expect(vel.dx).toBe(1);
+ expect(hp.value).toBe(50);
+ count++;
+ });
+
+ expect(count).toBe(1);
+ });
+
+ it('should filter correctly with multiple components', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+ world.insert(e1, Enemy, {});
+
+ const e2 = world.spawn();
+ world.insert(e2, Position, { x: 2, y: 2 });
+ world.insert(e2, Health, { value: 100 });
+
+ const e3 = world.spawn();
+ world.insert(e3, Position, { x: 3, y: 3 });
+ world.insert(e3, Enemy, {});
+
+ const query = Query(Position, Enemy);
+ const results: number[] = [];
+
+ new QueryInstance(world, query).forEach((entity) => {
+ results.push(entity);
+ });
+
+ expect(results).toHaveLength(2);
+ expect(results).toContain(e1);
+ expect(results).toContain(e3);
+ });
+ });
+
+ describe('entity lifecycle during iteration', () => {
+ it('should handle entity creation during iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+
+ const query = Query(Position);
+ let iterations = 0;
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity) => {
+ iterations++;
+ if (iterations === 1) {
+ world.spawn();
+ }
+ });
+ }).toThrow(/Cannot spawn entity during query iteration/);
+ });
+
+ it('should handle component removal during iteration', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position, { x: 1, y: 1 });
+ world.insert(e1, Velocity, { dx: 1, dy: 1 });
+
+ const query = Query(Position);
+
+ expect(() => {
+ new QueryInstance(world, query).forEach((entity) => {
+ world.remove(entity, Velocity);
+ });
+ }).toThrow(/Cannot remove component during query iteration/);
+ });
+ });
+});
diff --git a/sdk/tests/resource.test.ts b/sdk/tests/resource.test.ts
new file mode 100644
index 000000000..3a4fce2b0
--- /dev/null
+++ b/sdk/tests/resource.test.ts
@@ -0,0 +1,132 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { defineResource, Res, ResMut } from '../src/resource';
+
+describe('Resource System', () => {
+ describe('defineResource', () => {
+ it('should create a resource with initial data', () => {
+ const Counter = defineResource({ count: 0 }, 'Counter');
+
+ expect(Counter._name).toBe('Counter');
+ expect(Counter._default).toEqual({ count: 0 });
+ });
+
+ it('should create a resource with complex data', () => {
+ const GameState = defineResource({
+ score: 0,
+ level: 1,
+ paused: false,
+ playerName: 'Player',
+ }, 'GameState');
+
+ expect(GameState._default).toEqual({
+ score: 0,
+ level: 1,
+ paused: false,
+ playerName: 'Player',
+ });
+ });
+
+ it('should create a resource with empty data', () => {
+ const EmptyResource = defineResource({}, 'EmptyResource');
+
+ expect(EmptyResource._default).toEqual({});
+ });
+ });
+
+ describe('Res descriptor', () => {
+ it('should create immutable resource descriptor', () => {
+ const Counter = defineResource({ count: 0 }, 'Counter');
+ const descriptor = Res(Counter);
+
+ expect(descriptor).toBeDefined();
+ expect(descriptor._resource).toBe(Counter);
+ });
+ });
+
+ describe('ResMut descriptor', () => {
+ it('should create mutable resource descriptor', () => {
+ const Counter = defineResource({ count: 0 }, 'Counter');
+ const descriptor = ResMut(Counter);
+
+ expect(descriptor).toBeDefined();
+ expect(descriptor._resource).toBe(Counter);
+ });
+ });
+
+ describe('resource data types', () => {
+ it('should support numeric resources', () => {
+ const DeltaTime = defineResource({ value: 0.016 }, 'DeltaTime');
+
+ expect(DeltaTime._default.value).toBe(0.016);
+ });
+
+ it('should support string resources', () => {
+ const Config = defineResource({ apiKey: 'test-key' }, 'Config');
+
+ expect(Config._default.apiKey).toBe('test-key');
+ });
+
+ it('should support boolean resources', () => {
+ const DebugMode = defineResource({ enabled: false }, 'DebugMode');
+
+ expect(DebugMode._default.enabled).toBe(false);
+ });
+
+ it('should support array resources', () => {
+ const History = defineResource({ events: [] as string[] }, 'History');
+
+ expect(Array.isArray(History._default.events)).toBe(true);
+ });
+
+ it('should support nested object resources', () => {
+ const Settings = defineResource({
+ audio: {
+ volume: 1.0,
+ muted: false,
+ },
+ graphics: {
+ quality: 'high',
+ vsync: true,
+ },
+ }, 'Settings');
+
+ expect(Settings._default.audio.volume).toBe(1.0);
+ expect(Settings._default.graphics.quality).toBe('high');
+ });
+ });
+
+ describe('resource naming', () => {
+ it('should support different naming conventions', () => {
+ const CamelCase = defineResource({ value: 1 }, 'camelCase');
+ const PascalCase = defineResource({ value: 2 }, 'PascalCase');
+ const snake_case = defineResource({ value: 3 }, 'snake_case');
+
+ expect(CamelCase._name).toBe('camelCase');
+ expect(PascalCase._name).toBe('PascalCase');
+ expect(snake_case._name).toBe('snake_case');
+ });
+ });
+
+ describe('complex scenarios', () => {
+ it('should handle multiple resources', () => {
+ const Time = defineResource({ delta: 0, elapsed: 0 }, 'Time');
+ const Input = defineResource({ mouseX: 0, mouseY: 0 }, 'Input');
+ const Score = defineResource({ value: 0 }, 'Score');
+
+ expect(Time._name).toBe('Time');
+ expect(Input._name).toBe('Input');
+ expect(Score._name).toBe('Score');
+ });
+
+ it('should support resource composition', () => {
+ const Physics = defineResource({
+ gravity: { x: 0, y: -9.8 },
+ timeScale: 1.0,
+ substeps: 4,
+ }, 'Physics');
+
+ expect(Physics._default.gravity.y).toBe(-9.8);
+ expect(Physics._default.substeps).toBe(4);
+ });
+ });
+});
diff --git a/sdk/tests/setup.ts b/sdk/tests/setup.ts
new file mode 100644
index 000000000..5df15c35a
--- /dev/null
+++ b/sdk/tests/setup.ts
@@ -0,0 +1,6 @@
+import { beforeEach } from 'vitest';
+import { clearUserComponents } from '../src/component';
+
+beforeEach(() => {
+ clearUserComponents();
+});
diff --git a/sdk/tests/system-ordering.test.ts b/sdk/tests/system-ordering.test.ts
new file mode 100644
index 000000000..764a784e9
--- /dev/null
+++ b/sdk/tests/system-ordering.test.ts
@@ -0,0 +1,175 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { App } from '../src/app';
+import { defineSystem, Schedule } from '../src/system';
+
+describe('System Dependency Ordering', () => {
+ let app: App;
+ const executionOrder: string[] = [];
+
+ beforeEach(() => {
+ app = App.new();
+ executionOrder.length = 0;
+ });
+
+ describe('runAfter', () => {
+ it('should run systems in dependency order', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ const systemB = defineSystem([], () => {
+ executionOrder.push('B');
+ }, { name: 'SystemB' });
+
+ app.addSystemToSchedule(Schedule.Update, systemB, { runAfter: ['SystemA'] });
+ app.addSystemToSchedule(Schedule.Update, systemA);
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ (app as any).runSchedule(Schedule.Update);
+
+ expect(executionOrder).toEqual(['A', 'B']);
+ });
+
+ it('should handle multiple runAfter dependencies', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ const systemB = defineSystem([], () => {
+ executionOrder.push('B');
+ }, { name: 'SystemB' });
+
+ const systemC = defineSystem([], () => {
+ executionOrder.push('C');
+ }, { name: 'SystemC' });
+
+ app.addSystemToSchedule(Schedule.Update, systemC, { runAfter: ['SystemA', 'SystemB'] });
+ app.addSystemToSchedule(Schedule.Update, systemB);
+ app.addSystemToSchedule(Schedule.Update, systemA);
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ (app as any).runSchedule(Schedule.Update);
+
+ const aIndex = executionOrder.indexOf('A');
+ const bIndex = executionOrder.indexOf('B');
+ const cIndex = executionOrder.indexOf('C');
+
+ expect(aIndex).toBeLessThan(cIndex);
+ expect(bIndex).toBeLessThan(cIndex);
+ });
+ });
+
+ describe('runBefore', () => {
+ it('should run system before specified target', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ const systemB = defineSystem([], () => {
+ executionOrder.push('B');
+ }, { name: 'SystemB' });
+
+ app.addSystemToSchedule(Schedule.Update, systemB);
+ app.addSystemToSchedule(Schedule.Update, systemA, { runBefore: ['SystemB'] });
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ (app as any).runSchedule(Schedule.Update);
+
+ expect(executionOrder).toEqual(['A', 'B']);
+ });
+ });
+
+ describe('mixed dependencies', () => {
+ it('should handle runBefore and runAfter together', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ const systemB = defineSystem([], () => {
+ executionOrder.push('B');
+ }, { name: 'SystemB' });
+
+ const systemC = defineSystem([], () => {
+ executionOrder.push('C');
+ }, { name: 'SystemC' });
+
+ app.addSystemToSchedule(Schedule.Update, systemB, { runAfter: ['SystemA'] });
+ app.addSystemToSchedule(Schedule.Update, systemC, { runBefore: ['SystemB'] });
+ app.addSystemToSchedule(Schedule.Update, systemA);
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ (app as any).runSchedule(Schedule.Update);
+
+ const aIndex = executionOrder.indexOf('A');
+ const bIndex = executionOrder.indexOf('B');
+ const cIndex = executionOrder.indexOf('C');
+
+ expect(aIndex).toBeLessThan(bIndex);
+ expect(cIndex).toBeLessThan(bIndex);
+ });
+ });
+
+ describe('circular dependency detection', () => {
+ it('should throw on circular dependencies', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ const systemB = defineSystem([], () => {
+ executionOrder.push('B');
+ }, { name: 'SystemB' });
+
+ app.addSystemToSchedule(Schedule.Update, systemA, { runAfter: ['SystemB'] });
+ app.addSystemToSchedule(Schedule.Update, systemB, { runAfter: ['SystemA'] });
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+
+ expect(() => {
+ (app as any).runSchedule(Schedule.Update);
+ }).toThrow('Circular dependency');
+ });
+ });
+
+ describe('systems without dependencies', () => {
+ it('should run in registration order when no dependencies specified', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ const systemB = defineSystem([], () => {
+ executionOrder.push('B');
+ }, { name: 'SystemB' });
+
+ const systemC = defineSystem([], () => {
+ executionOrder.push('C');
+ }, { name: 'SystemC' });
+
+ app.addSystemToSchedule(Schedule.Update, systemA);
+ app.addSystemToSchedule(Schedule.Update, systemB);
+ app.addSystemToSchedule(Schedule.Update, systemC);
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ (app as any).runSchedule(Schedule.Update);
+
+ expect(executionOrder).toEqual(['A', 'B', 'C']);
+ });
+ });
+
+ describe('non-existent dependencies', () => {
+ it('should ignore dependencies on non-existent systems', () => {
+ const systemA = defineSystem([], () => {
+ executionOrder.push('A');
+ }, { name: 'SystemA' });
+
+ app.addSystemToSchedule(Schedule.Update, systemA, { runAfter: ['NonExistent'] });
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+
+ expect(() => {
+ (app as any).runSchedule(Schedule.Update);
+ }).not.toThrow();
+
+ expect(executionOrder).toEqual(['A']);
+ });
+ });
+});
diff --git a/sdk/tests/validation.test.ts b/sdk/tests/validation.test.ts
new file mode 100644
index 000000000..43ecd6bb8
--- /dev/null
+++ b/sdk/tests/validation.test.ts
@@ -0,0 +1,319 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/world';
+import { defineComponent, defineTag } from '../src/component';
+import { createMockModule } from './mocks/wasm';
+
+describe('Component Data Validation', () => {
+ let world: World;
+
+ const Position = defineComponent('Position', { x: 0, y: 0 });
+ const Velocity = defineComponent('Velocity', { dx: 0, dy: 0 });
+ const Health = defineComponent('Health', {
+ value: 100,
+ max: 100,
+ regeneration: 0,
+ });
+ const Player = defineComponent('Player', {
+ name: 'Player',
+ level: 1,
+ active: true,
+ items: [] as string[],
+ });
+
+ beforeEach(() => {
+ const module = createMockModule();
+ world = new World(module);
+ });
+
+ describe('valid data', () => {
+ it('should accept valid component data', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, { x: 10, y: 20 });
+ }).not.toThrow();
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(10);
+ expect(pos.y).toBe(20);
+ });
+
+ it('should accept partial data', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, { x: 5 });
+ }).not.toThrow();
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(5);
+ expect(pos.y).toBe(0);
+ });
+
+ it('should accept data with all fields', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Health, { value: 75, max: 150, regeneration: 5 });
+ }).not.toThrow();
+
+ const hp = world.get(entity, Health);
+ expect(hp.value).toBe(75);
+ expect(hp.max).toBe(150);
+ expect(hp.regeneration).toBe(5);
+ });
+
+ it('should accept mixed types', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Player, {
+ name: 'Hero',
+ level: 5,
+ active: false,
+ items: ['sword', 'shield'],
+ });
+ }).not.toThrow();
+
+ const player = world.get(entity, Player);
+ expect(player.name).toBe('Hero');
+ expect(player.level).toBe(5);
+ expect(player.active).toBe(false);
+ expect(player.items).toEqual(['sword', 'shield']);
+ });
+
+ it('should accept empty data', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, {});
+ }).not.toThrow();
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(0);
+ expect(pos.y).toBe(0);
+ });
+
+ it('should accept null and undefined for optional data', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, undefined);
+ }).not.toThrow();
+
+ expect(() => {
+ world.insert(entity, Velocity, null as any);
+ }).not.toThrow();
+ });
+ });
+
+ describe('type mismatch', () => {
+ it('should reject wrong type for number field', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, { x: 'invalid' as any, y: 0 });
+ }).toThrow(/Invalid component data.*Position/);
+ });
+
+ it('should reject wrong type for string field', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Player, { name: 123 as any });
+ }).toThrow(/Invalid component data.*Player/);
+ });
+
+ it('should reject wrong type for boolean field', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Player, { active: 'yes' as any });
+ }).toThrow(/Invalid component data.*Player/);
+ });
+
+ it('should reject wrong type for array field', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Player, { items: 'not-an-array' as any });
+ }).toThrow(/Invalid component data.*Player/);
+ });
+
+ it('should reject multiple type mismatches', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, { x: 'bad' as any, y: 'also-bad' as any });
+ }).toThrow(/Invalid component data.*Position/);
+ });
+ });
+
+ describe('unknown fields', () => {
+ it('should reject unknown fields', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, { x: 1, y: 2, z: 3 } as any);
+ }).toThrow(/Invalid component data.*Position/);
+ });
+
+ it('should reject unknown fields even with valid fields', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Health, {
+ value: 50,
+ max: 100,
+ unknown: 'field',
+ } as any);
+ }).toThrow(/Invalid component data.*Health/);
+ });
+ });
+
+ describe('null and undefined handling', () => {
+ it('should allow null values', () => {
+ const NullableComp = defineComponent('NullableComp', {
+ value: null as number | null,
+ });
+
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, NullableComp, { value: null });
+ }).not.toThrow();
+
+ const comp = world.get(entity, NullableComp);
+ expect(comp.value).toBeNull();
+ });
+
+ it('should filter out undefined values but not validate them', () => {
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Position, { x: undefined, y: 5 });
+ }).not.toThrow();
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(0);
+ expect(pos.y).toBe(5);
+ });
+ });
+
+ describe('tag components', () => {
+ it('should accept tag components without data', () => {
+ const Tag = defineTag('Tag');
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Tag);
+ }).not.toThrow();
+
+ expect(world.has(entity, Tag)).toBe(true);
+ });
+
+ it('should accept tag components with empty object', () => {
+ const Tag = defineTag('Tag');
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Tag, {});
+ }).not.toThrow();
+
+ expect(world.has(entity, Tag)).toBe(true);
+ });
+
+ it('should reject tag components with unknown fields', () => {
+ const Tag = defineTag('Tag');
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Tag, { invalid: true } as any);
+ }).toThrow(/Invalid component data.*Tag/);
+ });
+ });
+
+ describe('error messages', () => {
+ it('should provide clear error message for type mismatch', () => {
+ const entity = world.spawn();
+
+ try {
+ world.insert(entity, Position, { x: 'string' as any });
+ expect.fail('Should have thrown');
+ } catch (e) {
+ const message = (e as Error).message;
+ expect(message).toContain('Position');
+ expect(message).toContain('x');
+ expect(message).toContain('number');
+ expect(message).toContain('string');
+ }
+ });
+
+ it('should provide clear error message for unknown field', () => {
+ const entity = world.spawn();
+
+ try {
+ world.insert(entity, Position, { z: 10 } as any);
+ expect.fail('Should have thrown');
+ } catch (e) {
+ const message = (e as Error).message;
+ expect(message).toContain('Position');
+ expect(message).toContain('z');
+ expect(message).toContain('unknown field');
+ }
+ });
+
+ it('should list all validation errors', () => {
+ const entity = world.spawn();
+
+ try {
+ world.insert(entity, Position, {
+ x: 'bad' as any,
+ y: 'also-bad' as any,
+ z: 10,
+ } as any);
+ expect.fail('Should have thrown');
+ } catch (e) {
+ const message = (e as Error).message;
+ expect(message).toContain('x');
+ expect(message).toContain('y');
+ expect(message).toContain('z');
+ }
+ });
+ });
+
+ describe('complex data types', () => {
+ it('should validate nested objects', () => {
+ const Transform = defineComponent('Transform', {
+ position: { x: 0, y: 0 },
+ rotation: 0,
+ });
+
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Transform, {
+ position: { x: 10, y: 20 },
+ rotation: 45,
+ });
+ }).not.toThrow();
+ });
+
+ it('should validate arrays', () => {
+ const Inventory = defineComponent('Inventory', {
+ items: [] as string[],
+ });
+
+ const entity = world.spawn();
+
+ expect(() => {
+ world.insert(entity, Inventory, {
+ items: ['sword', 'potion'],
+ });
+ }).not.toThrow();
+
+ const inv = world.get(entity, Inventory);
+ expect(inv.items).toEqual(['sword', 'potion']);
+ });
+ });
+});
diff --git a/sdk/tests/world.test.ts b/sdk/tests/world.test.ts
new file mode 100644
index 000000000..5f06109e5
--- /dev/null
+++ b/sdk/tests/world.test.ts
@@ -0,0 +1,318 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/world';
+import { defineComponent, defineTag } from '../src/component';
+import { createMockModule } from './mocks/wasm';
+
+describe('World', () => {
+ let world: World;
+
+ const Position = defineComponent('Position', { x: 0, y: 0 });
+ const Velocity = defineComponent('Velocity', { dx: 0, dy: 0 });
+ const Health = defineComponent('Health', { value: 100 });
+ const Player = defineTag('Player');
+
+ beforeEach(() => {
+ const module = createMockModule();
+ world = new World(module);
+ });
+
+ describe('entity lifecycle', () => {
+ it('should spawn a new entity', () => {
+ const entity = world.spawn();
+ expect(entity).toBeGreaterThan(0);
+ });
+
+ it('should spawn multiple entities', () => {
+ const e1 = world.spawn();
+ const e2 = world.spawn();
+ const e3 = world.spawn();
+
+ expect(e1).not.toBe(e2);
+ expect(e2).not.toBe(e3);
+ expect(e1).not.toBe(e3);
+ });
+
+ it('should despawn an entity', () => {
+ const entity = world.spawn();
+ world.despawn(entity);
+
+ expect(() => world.get(entity, Position)).toThrow();
+ });
+ });
+
+ describe('component operations', () => {
+ it('should insert component with data', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position, { x: 10, y: 20 });
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(10);
+ expect(pos.y).toBe(20);
+ });
+
+ it('should insert component with defaults', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position);
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(0);
+ expect(pos.y).toBe(0);
+ });
+
+ it('should insert component with partial data', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position, { x: 5 });
+
+ const pos = world.get(entity, Position);
+ expect(pos.x).toBe(5);
+ expect(pos.y).toBe(0);
+ });
+
+ it('should get component data', () => {
+ const entity = world.spawn();
+ world.insert(entity, Health, { value: 75 });
+
+ const health = world.get(entity, Health);
+ expect(health.value).toBe(75);
+ });
+
+ it('should throw when getting non-existent component', () => {
+ const entity = world.spawn();
+
+ expect(() => world.get(entity, Position)).toThrow();
+ });
+
+ it('should check if entity has component', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position);
+
+ expect(world.has(entity, Position)).toBe(true);
+ expect(world.has(entity, Velocity)).toBe(false);
+ });
+
+ it('should remove component', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position, { x: 1, y: 1 });
+ world.insert(entity, Velocity, { dx: 1, dy: 1 });
+
+ world.remove(entity, Position);
+
+ expect(world.has(entity, Position)).toBe(false);
+ expect(world.has(entity, Velocity)).toBe(true);
+ });
+ });
+
+ describe('tag components', () => {
+ it('should insert tag component', () => {
+ const entity = world.spawn();
+ world.insert(entity, Player);
+
+ expect(world.has(entity, Player)).toBe(true);
+ });
+
+ it('should remove tag component', () => {
+ const entity = world.spawn();
+ world.insert(entity, Player);
+ world.remove(entity, Player);
+
+ expect(world.has(entity, Player)).toBe(false);
+ });
+ });
+
+ describe('multiple components', () => {
+ it('should add multiple components to one entity', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position, { x: 1, y: 2 });
+ world.insert(entity, Velocity, { dx: 3, dy: 4 });
+ world.insert(entity, Health, { value: 100 });
+
+ expect(world.has(entity, Position)).toBe(true);
+ expect(world.has(entity, Velocity)).toBe(true);
+ expect(world.has(entity, Health)).toBe(true);
+ });
+
+ it('should remove specific components while keeping others', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position);
+ world.insert(entity, Velocity);
+ world.insert(entity, Health);
+
+ world.remove(entity, Velocity);
+
+ expect(world.has(entity, Position)).toBe(true);
+ expect(world.has(entity, Velocity)).toBe(false);
+ expect(world.has(entity, Health)).toBe(true);
+ });
+ });
+
+ describe('getEntitiesWithComponents', () => {
+ it('should find entities with single component', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const e2 = world.spawn();
+ world.insert(e2, Velocity);
+
+ const e3 = world.spawn();
+ world.insert(e3, Position);
+
+ const entities = world.getEntitiesWithComponents([Position]);
+
+ expect(entities).toHaveLength(2);
+ expect(entities).toContain(e1);
+ expect(entities).toContain(e3);
+ });
+
+ it('should find entities with multiple components', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+ world.insert(e1, Velocity);
+
+ const e2 = world.spawn();
+ world.insert(e2, Position);
+
+ const e3 = world.spawn();
+ world.insert(e3, Position);
+ world.insert(e3, Velocity);
+
+ const entities = world.getEntitiesWithComponents([Position, Velocity]);
+
+ expect(entities).toHaveLength(2);
+ expect(entities).toContain(e1);
+ expect(entities).toContain(e3);
+ });
+
+ it('should return empty array when no entities match', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const entities = world.getEntitiesWithComponents([Velocity, Health]);
+
+ expect(entities).toHaveLength(0);
+ });
+ });
+
+ describe('component data mutations', () => {
+ it('should allow mutating component data', () => {
+ const entity = world.spawn();
+ world.insert(entity, Position, { x: 0, y: 0 });
+
+ const pos = world.get(entity, Position);
+ pos.x = 100;
+ pos.y = 200;
+
+ const updated = world.get(entity, Position);
+ expect(updated.x).toBe(100);
+ expect(updated.y).toBe(200);
+ });
+
+ it('should reflect mutations immediately', () => {
+ const entity = world.spawn();
+ world.insert(entity, Health, { value: 100 });
+
+ const hp1 = world.get(entity, Health);
+ hp1.value -= 25;
+
+ const hp2 = world.get(entity, Health);
+ expect(hp2.value).toBe(75);
+ });
+ });
+
+ describe('structural changes', () => {
+ it('should invalidate queries on entity spawn', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const entities1 = world.getEntitiesWithComponents([Position]);
+ expect(entities1).toHaveLength(1);
+
+ const e2 = world.spawn();
+ world.insert(e2, Position);
+
+ const entities2 = world.getEntitiesWithComponents([Position]);
+ expect(entities2).toHaveLength(2);
+ });
+
+ it('should invalidate queries on entity despawn', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const e2 = world.spawn();
+ world.insert(e2, Position);
+
+ const entities1 = world.getEntitiesWithComponents([Position]);
+ expect(entities1).toHaveLength(2);
+
+ world.despawn(e1);
+
+ const entities2 = world.getEntitiesWithComponents([Position]);
+ expect(entities2).toHaveLength(1);
+ });
+
+ it('should invalidate queries on component insert', () => {
+ const e1 = world.spawn();
+
+ const entities1 = world.getEntitiesWithComponents([Position]);
+ expect(entities1).toHaveLength(0);
+
+ world.insert(e1, Position);
+
+ const entities2 = world.getEntitiesWithComponents([Position]);
+ expect(entities2).toHaveLength(1);
+ });
+
+ it('should invalidate queries on component remove', () => {
+ const e1 = world.spawn();
+ world.insert(e1, Position);
+
+ const entities1 = world.getEntitiesWithComponents([Position]);
+ expect(entities1).toHaveLength(1);
+
+ world.remove(e1, Position);
+
+ const entities2 = world.getEntitiesWithComponents([Position]);
+ expect(entities2).toHaveLength(0);
+ });
+ });
+
+ describe('complex scenarios', () => {
+ it('should handle many entities', () => {
+ const entities: number[] = [];
+
+ for (let i = 0; i < 1000; i++) {
+ const entity = world.spawn();
+ world.insert(entity, Position, { x: i, y: i * 2 });
+ entities.push(entity);
+ }
+
+ const queried = world.getEntitiesWithComponents([Position]);
+ expect(queried).toHaveLength(1000);
+ });
+
+ it('should handle complex component combinations', () => {
+ const enemy1 = world.spawn();
+ world.insert(enemy1, Position);
+ world.insert(enemy1, Velocity);
+ world.insert(enemy1, Health);
+
+ const enemy2 = world.spawn();
+ world.insert(enemy2, Position);
+ world.insert(enemy2, Health);
+
+ const player = world.spawn();
+ world.insert(player, Position);
+ world.insert(player, Velocity);
+ world.insert(player, Health);
+ world.insert(player, Player);
+
+ const movingEntities = world.getEntitiesWithComponents([Position, Velocity]);
+ expect(movingEntities).toHaveLength(2);
+
+ const players = world.getEntitiesWithComponents([Player]);
+ expect(players).toHaveLength(1);
+
+ const allLiving = world.getEntitiesWithComponents([Health]);
+ expect(allLiving).toHaveLength(3);
+ });
+ });
+});
diff --git a/sdk/vitest.config.ts b/sdk/vitest.config.ts
new file mode 100644
index 000000000..1c96afbb4
--- /dev/null
+++ b/sdk/vitest.config.ts
@@ -0,0 +1,26 @@
+import { defineConfig } from 'vitest/config';
+import path from 'path';
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'happy-dom',
+ setupFiles: ['tests/setup.ts'],
+ include: ['tests/**/*.test.ts'],
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'json', 'html'],
+ include: ['src/**/*.ts'],
+ exclude: [
+ 'src/**/*.d.ts',
+ 'src/wasm.ts',
+ 'src/index.*.ts',
+ ],
+ },
+ },
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
+ },
+ },
+});
diff --git a/src/esengine/bindings/EngineContext.cpp b/src/esengine/bindings/EngineContext.cpp
new file mode 100644
index 000000000..6a8e94cf2
--- /dev/null
+++ b/src/esengine/bindings/EngineContext.cpp
@@ -0,0 +1,78 @@
+/**
+ * @file EngineContext.cpp
+ * @brief Implementation of centralized engine context
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#ifdef ES_PLATFORM_WEB
+
+#include "EngineContext.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/RenderFrame.hpp"
+#include "../renderer/ImmediateDraw.hpp"
+#include "../renderer/CustomGeometry.hpp"
+#include "../renderer/PostProcessPipeline.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../ecs/TransformSystem.hpp"
+#ifdef ES_ENABLE_SPINE
+#include "../spine/SpineResourceManager.hpp"
+#include "../spine/SpineSystem.hpp"
+#endif
+#include <emscripten/html5.h>
+
+namespace esengine {
+
+EngineContext& EngineContext::instance() {
+ static EngineContext ctx;
+ return ctx;
+}
+
+void EngineContext::shutdown() {
+ if (!initialized_) return;
+
+ geometryManager_.reset();
+
+ if (renderFrame_) {
+ renderFrame_->shutdown();
+ renderFrame_.reset();
+ }
+
+ if (immediateDraw_) {
+ immediateDraw_->shutdown();
+ immediateDraw_.reset();
+ }
+
+#ifdef ES_ENABLE_SPINE
+ spineSystem_.reset();
+ if (spineResourceManager_) {
+ spineResourceManager_->shutdown();
+ spineResourceManager_.reset();
+ }
+#endif
+
+ transformSystem_.reset();
+ if (renderContext_) {
+ renderContext_->shutdown();
+ renderContext_.reset();
+ }
+ if (resourceManager_) {
+ resourceManager_->shutdown();
+ resourceManager_.reset();
+ }
+
+ if (webglContext_ > 0) {
+ emscripten_webgl_destroy_context(webglContext_);
+ webglContext_ = 0;
+ }
+
+ initialized_ = false;
+}
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/EngineContext.hpp b/src/esengine/bindings/EngineContext.hpp
new file mode 100644
index 000000000..43bf0d777
--- /dev/null
+++ b/src/esengine/bindings/EngineContext.hpp
@@ -0,0 +1,137 @@
+/**
+ * @file EngineContext.hpp
+ * @brief Centralized engine context replacing global state
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+#ifdef ES_PLATFORM_WEB
+
+#include <emscripten/html5.h>
+#include <glm/glm.hpp>
+#include "../core/Types.hpp"
+
+namespace esengine {
+
+class RenderContext;
+class RenderFrame;
+class ImmediateDraw;
+class GeometryManager;
+class PostProcessPipeline;
+
+namespace resource {
+class ResourceManager;
+}
+
+namespace ecs {
+class TransformSystem;
+}
+
+#ifdef ES_ENABLE_SPINE
+namespace spine {
+class SpineResourceManager;
+class SpineSystem;
+}
+#endif
+
+/**
+ * @brief Centralized context for engine subsystems and state
+ *
+ * @details Replaces global variables in WebSDKEntry.cpp with a singleton
+ * context object. Provides controlled access to subsystems and state.
+ */
+class EngineContext {
+public:
+ static EngineContext& instance();
+
+ EngineContext(const EngineContext&) = delete;
+ EngineContext& operator=(const EngineContext&) = delete;
+
+ bool isInitialized() const { return initialized_; }
+
+ void shutdown();
+
+ RenderContext* renderContext() { return renderContext_.get(); }
+ RenderFrame* renderFrame() { return renderFrame_.get(); }
+ ImmediateDraw* immediateDraw() { return immediateDraw_.get(); }
+ GeometryManager* geometryManager() { return geometryManager_.get(); }
+ PostProcessPipeline* postProcessPipeline() { return postProcessPipeline_.get(); }
+ resource::ResourceManager* resourceManager() { return resourceManager_.get(); }
+ ecs::TransformSystem* transformSystem() { return transformSystem_.get(); }
+
+#ifdef ES_ENABLE_SPINE
+ spine::SpineResourceManager* spineResourceManager() { return spineResourceManager_.get(); }
+ spine::SpineSystem* spineSystem() { return spineSystem_.get(); }
+#endif
+
+ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglContext() const { return webglContext_; }
+ void setWebglContext(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx) { webglContext_ = ctx; }
+
+ bool immediateDrawActive() const { return immediateDrawActive_; }
+ void setImmediateDrawActive(bool active) { immediateDrawActive_ = active; }
+
+ bool glErrorCheckEnabled() const { return glErrorCheckEnabled_; }
+ void setGlErrorCheckEnabled(bool enabled) { glErrorCheckEnabled_ = enabled; }
+
+ u32 viewportWidth() const { return viewportWidth_; }
+ u32 viewportHeight() const { return viewportHeight_; }
+ void setViewport(u32 width, u32 height) {
+ viewportWidth_ = width;
+ viewportHeight_ = height;
+ }
+
+ const glm::vec4& clearColor() const { return clearColor_; }
+ void setClearColor(const glm::vec4& color) { clearColor_ = color; }
+
+ const glm::mat4& currentViewProjection() const { return currentViewProjection_; }
+ void setCurrentViewProjection(const glm::mat4& vp) { currentViewProjection_ = vp; }
+
+ void setInitialized(bool initialized) { initialized_ = initialized; }
+ void setRenderContext(Unique<RenderContext> ctx) { renderContext_ = std::move(ctx); }
+ void setRenderFrame(Unique<RenderFrame> frame) { renderFrame_ = std::move(frame); }
+ void setImmediateDraw(Unique<ImmediateDraw> draw) { immediateDraw_ = std::move(draw); }
+ void setGeometryManager(Unique<GeometryManager> mgr) { geometryManager_ = std::move(mgr); }
+ void setPostProcessPipeline(Unique<PostProcessPipeline> pipeline) { postProcessPipeline_ = std::move(pipeline); }
+ void setResourceManager(Unique<resource::ResourceManager> mgr) { resourceManager_ = std::move(mgr); }
+ void setTransformSystem(Unique<ecs::TransformSystem> sys) { transformSystem_ = std::move(sys); }
+
+#ifdef ES_ENABLE_SPINE
+ void setSpineResourceManager(Unique<spine::SpineResourceManager> mgr) { spineResourceManager_ = std::move(mgr); }
+ void setSpineSystem(Unique<spine::SpineSystem> sys) { spineSystem_ = std::move(sys); }
+#endif
+
+private:
+ EngineContext() = default;
+ ~EngineContext() = default;
+
+ Unique<RenderContext> renderContext_;
+ Unique<RenderFrame> renderFrame_;
+ Unique<ImmediateDraw> immediateDraw_;
+ Unique<GeometryManager> geometryManager_;
+ Unique<PostProcessPipeline> postProcessPipeline_;
+ Unique<resource::ResourceManager> resourceManager_;
+ Unique<ecs::TransformSystem> transformSystem_;
+
+#ifdef ES_ENABLE_SPINE
+ Unique<spine::SpineResourceManager> spineResourceManager_;
+ Unique<spine::SpineSystem> spineSystem_;
+#endif
+
+ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglContext_ = 0;
+ bool initialized_ = false;
+ bool immediateDrawActive_ = false;
+ bool glErrorCheckEnabled_ = false;
+ u32 viewportWidth_ = 1280;
+ u32 viewportHeight_ = 720;
+ glm::vec4 clearColor_{0.0f, 0.0f, 0.0f, 1.0f};
+ glm::mat4 currentViewProjection_{1.0f};
+};
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cpp
new file mode 100644
index 000000000..185d1bf2f
--- /dev/null
+++ b/src/esengine/bindings/GeometryBindings.cpp
@@ -0,0 +1,255 @@
+#ifdef ES_PLATFORM_WEB
+
+#include "GeometryBindings.hpp"
+#include "EngineContext.hpp"
+#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/CustomGeometry.hpp"
+#include "../renderer/Buffer.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/RenderFrame.hpp"
+#include "../renderer/ImmediateDraw.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../ecs/TransformSystem.hpp"
+#ifdef ES_ENABLE_SPINE
+#include "../spine/SpineResourceManager.hpp"
+#include "../spine/SpineSystem.hpp"
+#endif
+
+#include <glm/glm.hpp>
+#include <glm/gtc/type_ptr.hpp>
+#include <vector>
+#include <string>
+
+namespace esengine {
+
+static EngineContext& ctx() { return EngineContext::instance(); }
+
+#define g_initialized (ctx().isInitialized())
+#define g_geometryManager (ctx().geometryManager())
+#define g_resourceManager (ctx().resourceManager())
+#define g_immediateDraw (ctx().immediateDraw())
+#define g_immediateDrawActive (ctx().immediateDrawActive())
+#define g_currentViewProjection (ctx().currentViewProjection())
+
+static void flushImmediateDrawIfActive() {
+ if (g_immediateDrawActive && g_immediateDraw) {
+ g_immediateDraw->flush();
+ }
+}
+
+static void restoreImmediateDrawState() {
+ if (g_immediateDrawActive) {
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glEnable(GL_BLEND);
+ glDisable(GL_DEPTH_TEST);
+ glActiveTexture(GL_TEXTURE0);
+ }
+}
+
+u32 geometry_create() {
+ if (!g_geometryManager) return 0;
+ return g_geometryManager->create();
+}
+
+void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,
+ uintptr_t layoutPtr, u32 layoutCount, bool dynamic) {
+ if (!g_geometryManager) return;
+
+ auto* geom = g_geometryManager->get(handle);
+ if (!geom) return;
+
+ const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
+ const i32* layoutData = reinterpret_cast<const i32*>(layoutPtr);
+
+ static std::vector<VertexAttribute> s_attrs;
+ s_attrs.clear();
+ s_attrs.reserve(layoutCount);
+
+ for (u32 i = 0; i < layoutCount; ++i) {
+ ShaderDataType type = static_cast<ShaderDataType>(layoutData[i]);
+ std::string name = "a_attr" + std::to_string(i);
+ s_attrs.emplace_back(type, name);
+ }
+
+ VertexLayout layout;
+ if (layoutCount == 1) {
+ layout = { s_attrs[0] };
+ } else if (layoutCount == 2) {
+ layout = { s_attrs[0], s_attrs[1] };
+ } else if (layoutCount == 3) {
+ layout = { s_attrs[0], s_attrs[1], s_attrs[2] };
+ } else if (layoutCount == 4) {
+ layout = { s_attrs[0], s_attrs[1], s_attrs[2], s_attrs[3] };
+ }
+
+ geom->init(vertices, vertexCount, layout, dynamic);
+}
+
+void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
+ if (!g_geometryManager) return;
+
+ auto* geom = g_geometryManager->get(handle);
+ if (!geom) return;
+
+ const u16* indices = reinterpret_cast<const u16*>(indicesPtr);
+ geom->setIndices(indices, indexCount);
+}
+
+void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
+ if (!g_geometryManager) return;
+
+ auto* geom = g_geometryManager->get(handle);
+ if (!geom) return;
+
+ const u32* indices = reinterpret_cast<const u32*>(indicesPtr);
+ geom->setIndices(indices, indexCount);
+}
+
+void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount, u32 offset) {
+ if (!g_geometryManager) return;
+
+ auto* geom = g_geometryManager->get(handle);
+ if (!geom) return;
+
+ const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
+ geom->updateVertices(vertices, vertexCount, offset);
+}
+
+void geometry_release(u32 handle) {
+ if (!g_geometryManager) return;
+ g_geometryManager->release(handle);
+}
+
+bool geometry_isValid(u32 handle) {
+ if (!g_geometryManager) return false;
+ return g_geometryManager->isValid(handle);
+}
+
+void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {
+ if (!g_initialized || !g_geometryManager || !g_resourceManager) return;
+
+ auto* geom = g_geometryManager->get(geometryHandle);
+ if (!geom || !geom->isValid()) return;
+
+ Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));
+ if (!shader) return;
+
+ flushImmediateDrawIfActive();
+
+ const f32* transformData = reinterpret_cast<const f32*>(transformPtr);
+ glm::mat4 transform = glm::make_mat4(transformData);
+
+ shader->bind();
+ shader->setUniform("u_projection", g_currentViewProjection);
+ shader->setUniform("u_model", transform);
+
+ geom->bind();
+
+ if (geom->hasIndices()) {
+ auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
+ if (ib) {
+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
+ }
+ } else {
+ glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
+ }
+
+ geom->unbind();
+ restoreImmediateDrawState();
+}
+
+void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr,
+ uintptr_t uniformsPtr, u32 uniformCount) {
+ if (!g_initialized || !g_geometryManager || !g_resourceManager) return;
+
+ auto* geom = g_geometryManager->get(geometryHandle);
+ if (!geom || !geom->isValid()) return;
+
+ Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));
+ if (!shader) return;
+
+ flushImmediateDrawIfActive();
+
+ const f32* transformData = reinterpret_cast<const f32*>(transformPtr);
+ glm::mat4 transform = glm::make_mat4(transformData);
+
+ shader->bind();
+ shader->setUniform("u_projection", g_currentViewProjection);
+ shader->setUniform("u_model", transform);
+
+ static constexpr const char* UNIFORM_NAMES[] = {
+ "u_time", "u_color", "u_intensity", "u_scale", "u_offset",
+ "u_param0", "u_param1", "u_param2", "u_param3", "u_param4",
+ "u_vec0", "u_vec1", "u_vec2", "u_vec3",
+ "u_texture0", "u_texture1", "u_texture2", "u_texture3"
+ };
+ static constexpr u32 UNIFORM_NAME_COUNT = sizeof(UNIFORM_NAMES) / sizeof(UNIFORM_NAMES[0]);
+
+ const f32* uniforms = reinterpret_cast<const f32*>(uniformsPtr);
+ u32 idx = 0;
+
+ while (idx < uniformCount) {
+ auto type = static_cast<i32>(uniforms[idx++]);
+ auto nameId = static_cast<i32>(uniforms[idx++]);
+
+ const char* name = (nameId >= 0 && static_cast<u32>(nameId) < UNIFORM_NAME_COUNT)
+ ? UNIFORM_NAMES[nameId] : "u_unknown";
+
+ switch (type) {
+ case 1: {
+ f32 value = uniforms[idx++];
+ shader->setUniform(name, value);
+ break;
+ }
+ case 2: {
+ glm::vec2 value(uniforms[idx], uniforms[idx + 1]);
+ idx += 2;
+ shader->setUniform(name, value);
+ break;
+ }
+ case 3: {
+ glm::vec3 value(uniforms[idx], uniforms[idx + 1], uniforms[idx + 2]);
+ idx += 3;
+ shader->setUniform(name, value);
+ break;
+ }
+ case 4: {
+ glm::vec4 value(uniforms[idx], uniforms[idx + 1],
+ uniforms[idx + 2], uniforms[idx + 3]);
+ idx += 4;
+ shader->setUniform(name, value);
+ break;
+ }
+ case 10: {
+ i32 slot = static_cast<i32>(uniforms[idx++]);
+ u32 textureId = static_cast<u32>(uniforms[idx++]);
+ glActiveTexture(GL_TEXTURE0 + slot);
+ glBindTexture(GL_TEXTURE_2D, textureId);
+ shader->setUniform(name, slot);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ geom->bind();
+
+ if (geom->hasIndices()) {
+ auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
+ if (ib) {
+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
+ }
+ } else {
+ glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
+ }
+
+ geom->unbind();
+ restoreImmediateDrawState();
+}
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/GeometryBindings.hpp b/src/esengine/bindings/GeometryBindings.hpp
new file mode 100644
index 000000000..d88bdda20
--- /dev/null
+++ b/src/esengine/bindings/GeometryBindings.hpp
@@ -0,0 +1,24 @@
+#pragma once
+
+#ifdef ES_PLATFORM_WEB
+
+#include "../core/Types.hpp"
+
+namespace esengine {
+
+u32 geometry_create();
+void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,
+ uintptr_t layoutPtr, u32 layoutCount, bool dynamic);
+void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount);
+void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount);
+void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount, u32 offset);
+void geometry_release(u32 handle);
+bool geometry_isValid(u32 handle);
+
+void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr);
+void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr,
+ uintptr_t uniformsPtr, u32 uniformCount);
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/ImmediateDrawBindings.cpp b/src/esengine/bindings/ImmediateDrawBindings.cpp
new file mode 100644
index 000000000..65e738ee9
--- /dev/null
+++ b/src/esengine/bindings/ImmediateDrawBindings.cpp
@@ -0,0 +1,176 @@
+#ifdef ES_PLATFORM_WEB
+
+#include "ImmediateDrawBindings.hpp"
+#include "EngineContext.hpp"
+#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/RenderCommand.hpp"
+#include "../renderer/BlendMode.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/RenderFrame.hpp"
+#include "../renderer/ImmediateDraw.hpp"
+#include "../renderer/CustomGeometry.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../ecs/TransformSystem.hpp"
+#ifdef ES_ENABLE_SPINE
+#include "../spine/SpineResourceManager.hpp"
+#include "../spine/SpineSystem.hpp"
+#endif
+
+#include <glm/glm.hpp>
+#include <glm/gtc/type_ptr.hpp>
+
+namespace esengine {
+
+static EngineContext& ctx() { return EngineContext::instance(); }
+
+#define g_initialized (ctx().isInitialized())
+#define g_immediateDraw (ctx().immediateDraw())
+#define g_immediateDrawActive (ctx().immediateDrawActive())
+#define g_viewportWidth (ctx().viewportWidth())
+#define g_viewportHeight (ctx().viewportHeight())
+#define g_currentViewProjection (ctx().currentViewProjection())
+
+static void flushImmediateDrawIfActive() {
+ if (g_immediateDrawActive && g_immediateDraw) {
+ g_immediateDraw->flush();
+ }
+}
+
+void draw_begin(uintptr_t matrixPtr) {
+ if (!g_initialized || !g_immediateDraw) return;
+
+ glViewport(0, 0, g_viewportWidth, g_viewportHeight);
+
+ const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
+ ctx().setCurrentViewProjection(glm::make_mat4(matrixData));
+ g_immediateDraw->begin(g_currentViewProjection);
+ ctx().setImmediateDrawActive(true);
+}
+
+void draw_end() {
+ if (!g_initialized || !g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->end();
+ ctx().setImmediateDrawActive(false);
+}
+
+void draw_line(f32 fromX, f32 fromY, f32 toX, f32 toY,
+ f32 r, f32 g, f32 b, f32 a, f32 thickness) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->line(
+ glm::vec2(fromX, fromY),
+ glm::vec2(toX, toY),
+ glm::vec4(r, g, b, a),
+ thickness
+ );
+}
+
+void draw_rect(f32 x, f32 y, f32 width, f32 height,
+ f32 r, f32 g, f32 b, f32 a, bool filled) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->rect(
+ glm::vec2(x, y),
+ glm::vec2(width, height),
+ glm::vec4(r, g, b, a),
+ filled
+ );
+}
+
+void draw_rectOutline(f32 x, f32 y, f32 width, f32 height,
+ f32 r, f32 g, f32 b, f32 a, f32 thickness) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->rectOutline(
+ glm::vec2(x, y),
+ glm::vec2(width, height),
+ glm::vec4(r, g, b, a),
+ thickness
+ );
+}
+
+void draw_circle(f32 centerX, f32 centerY, f32 radius,
+ f32 r, f32 g, f32 b, f32 a, bool filled, i32 segments) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->circle(
+ glm::vec2(centerX, centerY),
+ radius,
+ glm::vec4(r, g, b, a),
+ filled,
+ segments
+ );
+}
+
+void draw_circleOutline(f32 centerX, f32 centerY, f32 radius,
+ f32 r, f32 g, f32 b, f32 a, f32 thickness, i32 segments) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->circleOutline(
+ glm::vec2(centerX, centerY),
+ radius,
+ glm::vec4(r, g, b, a),
+ thickness,
+ segments
+ );
+}
+
+void draw_texture(f32 x, f32 y, f32 width, f32 height, u32 textureId,
+ f32 r, f32 g, f32 b, f32 a) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->texture(
+ glm::vec2(x, y),
+ glm::vec2(width, height),
+ textureId,
+ glm::vec4(r, g, b, a)
+ );
+}
+
+void draw_textureRotated(f32 x, f32 y, f32 width, f32 height, f32 rotation,
+ u32 textureId, f32 r, f32 g, f32 b, f32 a) {
+ if (!g_immediateDraw || !g_immediateDrawActive) return;
+
+ g_immediateDraw->textureRotated(
+ glm::vec2(x, y),
+ glm::vec2(width, height),
+ rotation,
+ textureId,
+ glm::vec4(r, g, b, a)
+ );
+}
+
+void draw_setLayer(i32 layer) {
+ if (!g_immediateDraw) return;
+ g_immediateDraw->setLayer(layer);
+}
+
+void draw_setDepth(f32 depth) {
+ if (!g_immediateDraw) return;
+ g_immediateDraw->setDepth(depth);
+}
+
+u32 draw_getDrawCallCount() {
+ if (!g_immediateDraw) return 0;
+ return g_immediateDraw->getDrawCallCount();
+}
+
+u32 draw_getPrimitiveCount() {
+ if (!g_immediateDraw) return 0;
+ return g_immediateDraw->getPrimitiveCount();
+}
+
+void draw_setBlendMode(i32 mode) {
+ flushImmediateDrawIfActive();
+ RenderCommand::setBlendMode(static_cast<BlendMode>(mode));
+}
+
+void draw_setDepthTest(bool enabled) {
+ flushImmediateDrawIfActive();
+ RenderCommand::setDepthTest(enabled);
+}
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/ImmediateDrawBindings.hpp b/src/esengine/bindings/ImmediateDrawBindings.hpp
new file mode 100644
index 000000000..8616a78cb
--- /dev/null
+++ b/src/esengine/bindings/ImmediateDrawBindings.hpp
@@ -0,0 +1,34 @@
+#pragma once
+
+#ifdef ES_PLATFORM_WEB
+
+#include "../core/Types.hpp"
+
+namespace esengine {
+
+void draw_begin(uintptr_t matrixPtr);
+void draw_end();
+void draw_line(f32 fromX, f32 fromY, f32 toX, f32 toY,
+ f32 r, f32 g, f32 b, f32 a, f32 thickness);
+void draw_rect(f32 x, f32 y, f32 width, f32 height,
+ f32 r, f32 g, f32 b, f32 a, bool filled);
+void draw_rectOutline(f32 x, f32 y, f32 width, f32 height,
+ f32 r, f32 g, f32 b, f32 a, f32 thickness);
+void draw_circle(f32 centerX, f32 centerY, f32 radius,
+ f32 r, f32 g, f32 b, f32 a, bool filled, i32 segments);
+void draw_circleOutline(f32 centerX, f32 centerY, f32 radius,
+ f32 r, f32 g, f32 b, f32 a, f32 thickness, i32 segments);
+void draw_texture(f32 x, f32 y, f32 width, f32 height, u32 textureId,
+ f32 r, f32 g, f32 b, f32 a);
+void draw_textureRotated(f32 x, f32 y, f32 width, f32 height, f32 rotation,
+ u32 textureId, f32 r, f32 g, f32 b, f32 a);
+void draw_setLayer(i32 layer);
+void draw_setDepth(f32 depth);
+u32 draw_getDrawCallCount();
+u32 draw_getPrimitiveCount();
+void draw_setBlendMode(i32 mode);
+void draw_setDepthTest(bool enabled);
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cpp
new file mode 100644
index 000000000..5bc04bf01
--- /dev/null
+++ b/src/esengine/bindings/PostProcessBindings.cpp
@@ -0,0 +1,127 @@
+#ifdef ES_PLATFORM_WEB
+
+#include "PostProcessBindings.hpp"
+#include "EngineContext.hpp"
+#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/PostProcessPipeline.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/RenderFrame.hpp"
+#include "../renderer/ImmediateDraw.hpp"
+#include "../renderer/CustomGeometry.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../ecs/TransformSystem.hpp"
+#ifdef ES_ENABLE_SPINE
+#include "../spine/SpineResourceManager.hpp"
+#include "../spine/SpineSystem.hpp"
+#endif
+
+#include <glm/glm.hpp>
+
+namespace esengine {
+
+static EngineContext& ctx() { return EngineContext::instance(); }
+
+#define g_initialized (ctx().isInitialized())
+#define g_renderContext (ctx().renderContext())
+#define g_resourceManager (ctx().resourceManager())
+#define g_postProcessPipeline (ctx().postProcessPipeline())
+
+bool postprocess_init(u32 width, u32 height) {
+ if (!g_initialized || !g_renderContext || !g_resourceManager) return false;
+
+ if (!g_postProcessPipeline) {
+ ctx().setPostProcessPipeline(makeUnique<PostProcessPipeline>(*g_renderContext, *g_resourceManager));
+ }
+
+ g_postProcessPipeline->init(width, height);
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+
+ return g_postProcessPipeline->isInitialized();
+}
+
+void postprocess_shutdown() {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->shutdown();
+ ctx().setPostProcessPipeline(nullptr);
+ }
+}
+
+void postprocess_resize(u32 width, u32 height) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->resize(width, height);
+ }
+}
+
+u32 postprocess_addPass(const std::string& name, u32 shaderHandle) {
+ if (!g_postProcessPipeline) return 0;
+ return g_postProcessPipeline->addPass(name, resource::ShaderHandle(shaderHandle));
+}
+
+void postprocess_removePass(const std::string& name) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->removePass(name);
+ }
+}
+
+void postprocess_setPassEnabled(const std::string& name, bool enabled) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->setPassEnabled(name, enabled);
+ }
+}
+
+bool postprocess_isPassEnabled(const std::string& name) {
+ if (!g_postProcessPipeline) return false;
+ return g_postProcessPipeline->isPassEnabled(name);
+}
+
+void postprocess_setUniformFloat(const std::string& passName,
+ const std::string& uniform, f32 value) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->setPassUniformFloat(passName, uniform, value);
+ }
+}
+
+void postprocess_setUniformVec4(const std::string& passName,
+ const std::string& uniform,
+ f32 x, f32 y, f32 z, f32 w) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->setPassUniformVec4(passName, uniform, glm::vec4(x, y, z, w));
+ }
+}
+
+void postprocess_begin() {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->begin();
+ }
+}
+
+void postprocess_end() {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->end();
+ }
+}
+
+u32 postprocess_getPassCount() {
+ if (!g_postProcessPipeline) return 0;
+ return g_postProcessPipeline->getPassCount();
+}
+
+bool postprocess_isInitialized() {
+ if (!g_postProcessPipeline) return false;
+ return g_postProcessPipeline->isInitialized();
+}
+
+void postprocess_setBypass(bool bypass) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->setBypass(bypass);
+ }
+}
+
+bool postprocess_isBypassed() {
+ if (!g_postProcessPipeline) return true;
+ return g_postProcessPipeline->isBypassed();
+}
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/PostProcessBindings.hpp b/src/esengine/bindings/PostProcessBindings.hpp
new file mode 100644
index 000000000..05b634d21
--- /dev/null
+++ b/src/esengine/bindings/PostProcessBindings.hpp
@@ -0,0 +1,31 @@
+#pragma once
+
+#ifdef ES_PLATFORM_WEB
+
+#include "../core/Types.hpp"
+#include <string>
+
+namespace esengine {
+
+bool postprocess_init(u32 width, u32 height);
+void postprocess_shutdown();
+void postprocess_resize(u32 width, u32 height);
+u32 postprocess_addPass(const std::string& name, u32 shaderHandle);
+void postprocess_removePass(const std::string& name);
+void postprocess_setPassEnabled(const std::string& name, bool enabled);
+bool postprocess_isPassEnabled(const std::string& name);
+void postprocess_setUniformFloat(const std::string& passName,
+ const std::string& uniform, f32 value);
+void postprocess_setUniformVec4(const std::string& passName,
+ const std::string& uniform,
+ f32 x, f32 y, f32 z, f32 w);
+void postprocess_begin();
+void postprocess_end();
+u32 postprocess_getPassCount();
+bool postprocess_isInitialized();
+void postprocess_setBypass(bool bypass);
+bool postprocess_isBypassed();
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
new file mode 100644
index 000000000..e4460d8a9
--- /dev/null
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -0,0 +1,443 @@
+#ifdef ES_PLATFORM_WEB
+
+#include "RendererBindings.hpp"
+#include "EngineContext.hpp"
+#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/RenderFrame.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/RenderStage.hpp"
+#include "../renderer/ImmediateDraw.hpp"
+#include "../renderer/CustomGeometry.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../ecs/Registry.hpp"
+#include "../ecs/TransformSystem.hpp"
+#include "../ecs/components/Camera.hpp"
+#include "../ecs/components/Canvas.hpp"
+#include "../ecs/components/Transform.hpp"
+#include "../ecs/components/Hierarchy.hpp"
+#include "../core/Log.hpp"
+#ifdef ES_ENABLE_SPINE
+#include "../spine/SpineResourceManager.hpp"
+#include "../spine/SpineSystem.hpp"
+#endif
+
+#include <emscripten/val.h>
+#include <glm/glm.hpp>
+#include <glm/gtc/matrix_transform.hpp>
+#include <glm/gtc/type_ptr.hpp>
+
+namespace esengine {
+
+static EngineContext& ctx() { return EngineContext::instance(); }
+
+#define g_initialized (ctx().isInitialized())
+#define g_renderFrame (ctx().renderFrame())
+#define g_transformSystem (ctx().transformSystem())
+#define g_glErrorCheckEnabled (ctx().glErrorCheckEnabled())
+#define g_viewportWidth (ctx().viewportWidth())
+#define g_viewportHeight (ctx().viewportHeight())
+#ifdef ES_ENABLE_SPINE
+#define g_spineSystem (ctx().spineSystem())
+#endif
+
+static u32 checkGLErrors(const char* context) {
+ if (!g_glErrorCheckEnabled) return 0;
+ u32 errorCount = 0;
+ GLenum err;
+ while ((err = glGetError()) != GL_NO_ERROR) {
+ const char* errStr = "UNKNOWN";
+ switch (err) {
+ case GL_INVALID_ENUM: errStr = "INVALID_ENUM"; break;
+ case GL_INVALID_VALUE: errStr = "INVALID_VALUE"; break;
+ case GL_INVALID_OPERATION: errStr = "INVALID_OPERATION"; break;
+ case GL_INVALID_FRAMEBUFFER_OPERATION: errStr = "INVALID_FRAMEBUFFER_OPERATION"; break;
+ case GL_OUT_OF_MEMORY: errStr = "OUT_OF_MEMORY"; break;
+ }
+ ES_LOG_ERROR("[GL Error] {} at: {}", errStr, context);
+ errorCount++;
+ }
+ return errorCount;
+}
+
+#ifdef ES_ENABLE_SPINE
+SpineBounds getSpineBounds(ecs::Registry& registry, Entity entity) {
+ SpineBounds bounds;
+ if (!g_spineSystem) return bounds;
+
+ if (g_spineSystem->getSkeletonBounds(entity, bounds.x, bounds.y,
+ bounds.width, bounds.height)) {
+ bounds.valid = true;
+ }
+ return bounds;
+}
+#endif
+
+void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight) {
+ if (!g_initialized || !g_renderFrame) return;
+
+ if (auto* rm = ctx().resourceManager()) {
+ rm->update();
+ }
+
+ if (g_transformSystem) {
+ g_transformSystem->update(registry, 0.0f);
+ }
+
+#ifdef ES_ENABLE_SPINE
+ if (g_spineSystem) {
+ g_spineSystem->update(registry, 0.016f);
+ }
+#endif
+
+ ctx().setViewport(static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));
+ g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
+
+ glViewport(0, 0, viewportWidth, viewportHeight);
+ glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ glm::mat4 viewProjection = glm::mat4(1.0f);
+
+ auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
+
+ for (auto entity : cameraView) {
+ auto& camera = registry.get<ecs::Camera>(entity);
+ if (!camera.isActive) continue;
+
+ auto& transform = registry.get<ecs::LocalTransform>(entity);
+ glm::mat4 view = glm::inverse(glm::translate(glm::mat4(1.0f), transform.position));
+
+ glm::mat4 projection;
+ f32 aspect = static_cast<f32>(viewportWidth) / static_cast<f32>(viewportHeight);
+
+ if (camera.projectionType == ecs::ProjectionType::Orthographic) {
+ f32 halfHeight = camera.orthoSize;
+ f32 halfWidth = halfHeight * aspect;
+ projection = glm::ortho(-halfWidth, halfWidth, -halfHeight, halfHeight,
+ camera.nearPlane, camera.farPlane);
+ } else {
+ projection = glm::perspective(
+ glm::radians(camera.fov),
+ static_cast<f32>(viewportWidth) / static_cast<f32>(viewportHeight),
+ camera.nearPlane, camera.farPlane
+ );
+ }
+
+ viewProjection = projection * view;
+ break;
+ }
+
+ g_renderFrame->begin(viewProjection);
+ g_renderFrame->submitSprites(registry);
+ g_renderFrame->submitBitmapText(registry);
+#ifdef ES_ENABLE_SPINE
+ if (g_spineSystem) {
+ g_renderFrame->submitSpine(registry, *g_spineSystem);
+ }
+#endif
+ g_renderFrame->end();
+}
+
+void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight,
+ uintptr_t matrixPtr) {
+ if (!g_initialized || !g_renderFrame) return;
+
+ if (g_transformSystem) {
+ g_transformSystem->update(registry, 0.0f);
+ }
+
+#ifdef ES_ENABLE_SPINE
+ if (g_spineSystem) {
+ g_spineSystem->update(registry, 0.016f);
+ }
+#endif
+
+ ctx().setViewport(static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));
+ g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
+
+ glViewport(0, 0, viewportWidth, viewportHeight);
+ glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
+ glm::mat4 viewProjection = glm::make_mat4(matrixData);
+
+ g_renderFrame->begin(viewProjection);
+ g_renderFrame->submitSprites(registry);
+ g_renderFrame->submitBitmapText(registry);
+#ifdef ES_ENABLE_SPINE
+ if (g_spineSystem) {
+ g_renderFrame->submitSpine(registry, *g_spineSystem);
+ }
+#endif
+ g_renderFrame->end();
+}
+
+void renderer_init(u32 width, u32 height) {
+ if (!g_renderFrame) return;
+ ctx().setViewport(width, height);
+ g_renderFrame->resize(width, height);
+}
+
+void renderer_resize(u32 width, u32 height) {
+ if (!g_renderFrame) return;
+ ctx().setViewport(width, height);
+ g_renderFrame->resize(width, height);
+}
+
+void renderer_begin(uintptr_t matrixPtr, u32 targetHandle) {
+ if (!g_renderFrame) return;
+
+ const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
+ glm::mat4 viewProjection = glm::make_mat4(matrixData);
+
+ g_renderFrame->begin(viewProjection, targetHandle);
+}
+
+void renderer_flush() {
+ if (!g_renderFrame) return;
+ g_renderFrame->flush();
+ checkGLErrors("renderer_flush");
+}
+
+void renderer_end() {
+ if (!g_renderFrame) return;
+ g_renderFrame->end();
+ checkGLErrors("renderer_end");
+}
+
+void renderer_submitSprites(ecs::Registry& registry) {
+ if (!g_renderFrame || !g_transformSystem) return;
+ g_transformSystem->update(registry, 0.0f);
+ g_renderFrame->submitSprites(registry);
+}
+
+void renderer_submitBitmapText(ecs::Registry& registry) {
+ if (!g_renderFrame || !g_transformSystem) return;
+ g_transformSystem->update(registry, 0.0f);
+ g_renderFrame->submitBitmapText(registry);
+}
+
+#ifdef ES_ENABLE_SPINE
+void renderer_submitSpine(ecs::Registry& registry) {
+ if (!g_renderFrame || !g_spineSystem) return;
+ g_spineSystem->update(registry, 0.016f);
+ g_renderFrame->submitSpine(registry, *g_spineSystem);
+ checkGLErrors("renderer_submitSpine");
+}
+#endif
+
+void renderer_submitTriangles(
+ uintptr_t verticesPtr, i32 vertexCount,
+ uintptr_t indicesPtr, i32 indexCount,
+ u32 textureId, i32 blendMode,
+ uintptr_t transformPtr) {
+ if (!g_renderFrame) return;
+
+ const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
+ const u16* indices = reinterpret_cast<const u16*>(indicesPtr);
+ const f32* transform = transformPtr ? reinterpret_cast<const f32*>(transformPtr) : nullptr;
+
+ g_renderFrame->submitExternalTriangles(
+ vertices, vertexCount,
+ indices, indexCount,
+ textureId, blendMode,
+ transform);
+}
+
+void renderer_setStage(i32 stage) {
+ if (!g_renderFrame) return;
+ g_renderFrame->setStage(static_cast<RenderStage>(stage));
+}
+
+u32 renderer_createTarget(u32 width, u32 height, i32 flags) {
+ if (!g_renderFrame) return 0;
+ bool depth = (flags & 1) != 0;
+ bool linear = (flags & 2) != 0;
+ return g_renderFrame->targetManager().create(width, height, depth, linear);
+}
+
+u32 renderer_getTargetDepthTexture(u32 handle) {
+ if (!g_renderFrame) return 0;
+ auto* target = g_renderFrame->targetManager().get(handle);
+ return target ? target->getDepthTexture() : 0;
+}
+
+void renderer_releaseTarget(u32 handle) {
+ if (!g_renderFrame) return;
+ g_renderFrame->targetManager().release(handle);
+}
+
+u32 renderer_getTargetTexture(u32 handle) {
+ if (!g_renderFrame) return 0;
+ auto* target = g_renderFrame->targetManager().get(handle);
+ return target ? target->getColorTexture() : 0;
+}
+
+u32 renderer_getDrawCalls() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().draw_calls;
+}
+
+u32 renderer_getTriangles() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().triangles;
+}
+
+u32 renderer_getSprites() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().sprites;
+}
+
+#ifdef ES_ENABLE_SPINE
+u32 renderer_getSpine() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().spine;
+}
+#endif
+
+u32 renderer_getText() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().text;
+}
+
+u32 renderer_getMeshes() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().meshes;
+}
+
+u32 renderer_getCulled() {
+ if (!g_renderFrame) return 0;
+ return g_renderFrame->stats().culled;
+}
+
+void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a) {
+ ctx().setClearColor(glm::vec4(r, g, b, a));
+}
+
+void renderer_setViewport(i32 x, i32 y, i32 w, i32 h) {
+ glViewport(x, y, w, h);
+}
+
+void renderer_setScissor(i32 x, i32 y, i32 w, i32 h, bool enable) {
+ if (enable) {
+ glEnable(GL_SCISSOR_TEST);
+ glScissor(x, y, w, h);
+ } else {
+ glDisable(GL_SCISSOR_TEST);
+ }
+}
+
+void renderer_clearBuffers(i32 flags) {
+ GLbitfield mask = 0;
+ if (flags & 1) mask |= GL_COLOR_BUFFER_BIT;
+ if (flags & 2) mask |= GL_DEPTH_BUFFER_BIT;
+ if (mask) glClear(mask);
+}
+
+void renderer_diagnose() {
+ if (!g_initialized) {
+ ES_LOG_ERROR("[Diagnose] Renderer not initialized");
+ return;
+ }
+
+ const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
+ const char* rendererStr = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
+ const char* vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
+ const char* slVersion = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
+ ES_LOG_INFO("[Diagnose] GL Version: {}", version ? version : "null");
+ ES_LOG_INFO("[Diagnose] GL Renderer: {}", rendererStr ? rendererStr : "null");
+ ES_LOG_INFO("[Diagnose] GL Vendor: {}", vendor ? vendor : "null");
+ ES_LOG_INFO("[Diagnose] GLSL Version: {}", slVersion ? slVersion : "null");
+
+ GLint viewport[4];
+ glGetIntegerv(GL_VIEWPORT, viewport);
+ ES_LOG_INFO("[Diagnose] GL Viewport: {}x{} at ({},{})", viewport[2], viewport[3], viewport[0], viewport[1]);
+ ES_LOG_INFO("[Diagnose] Stored viewport: {}x{}", g_viewportWidth, g_viewportHeight);
+
+ GLint maxTextureUnits;
+ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
+ ES_LOG_INFO("[Diagnose] Max texture units: {}", maxTextureUnits);
+
+ GLint maxAttribs;
+ glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxAttribs);
+ ES_LOG_INFO("[Diagnose] Max vertex attribs: {}", maxAttribs);
+
+ while (glGetError() != GL_NO_ERROR) {}
+ ES_LOG_INFO("[Diagnose] No pending GL errors (cleared)");
+}
+
+void renderer_setEntityClipRect(u32 entity, i32 x, i32 y, i32 w, i32 h) {
+ if (g_renderFrame) {
+ g_renderFrame->setEntityClipRect(entity, x, y, w, h);
+ }
+}
+
+void renderer_clearEntityClipRect(u32 entity) {
+ if (g_renderFrame) {
+ g_renderFrame->clearEntityClipRect(entity);
+ }
+}
+
+void renderer_clearAllClipRects() {
+ if (g_renderFrame) {
+ g_renderFrame->clearAllClipRects();
+ }
+}
+
+void gl_enableErrorCheck(bool enabled) {
+ ctx().setGlErrorCheckEnabled(enabled);
+ if (enabled) {
+ while (glGetError() != GL_NO_ERROR) {}
+ ES_LOG_INFO("[GL] Error checking enabled");
+ }
+}
+
+u32 gl_checkErrors(const std::string& context) {
+ bool prev = g_glErrorCheckEnabled;
+ ctx().setGlErrorCheckEnabled(true);
+ u32 count = checkGLErrors(context.c_str());
+ ctx().setGlErrorCheckEnabled(prev);
+ if (count == 0 && prev) {
+ ES_LOG_INFO("[GL] No errors at: {}", context);
+ }
+ return count;
+}
+
+i32 registry_getCanvasEntity(ecs::Registry& registry) {
+ auto view = registry.view<ecs::Canvas>();
+ for (auto entity : view) {
+ return static_cast<i32>(entity);
+ }
+ return -1;
+}
+
+emscripten::val registry_getCameraEntities(ecs::Registry& registry) {
+ auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
+ auto result = emscripten::val::array();
+ u32 idx = 0;
+ for (auto entity : cameraView) {
+ auto& camera = registry.get<ecs::Camera>(entity);
+ if (camera.isActive) {
+ result.set(idx++, static_cast<u32>(entity));
+ }
+ }
+ return result;
+}
+
+emscripten::val getChildEntities(ecs::Registry& registry, u32 entity) {
+ auto result = emscripten::val::array();
+ if (!registry.has<ecs::Children>(static_cast<Entity>(entity))) {
+ return result;
+ }
+ const auto& children = registry.get<ecs::Children>(static_cast<Entity>(entity));
+ u32 idx = 0;
+ for (auto child : children.entities) {
+ result.set(idx++, static_cast<u32>(child));
+ }
+ return result;
+}
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
new file mode 100644
index 000000000..37e2e7dab
--- /dev/null
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -0,0 +1,81 @@
+#pragma once
+
+#ifdef ES_PLATFORM_WEB
+
+#include "../core/Types.hpp"
+#include <string>
+
+namespace emscripten {
+ class val;
+}
+
+namespace esengine {
+
+namespace ecs {
+ class Registry;
+}
+
+#ifdef ES_ENABLE_SPINE
+struct SpineBounds {
+ f32 x = 0;
+ f32 y = 0;
+ f32 width = 0;
+ f32 height = 0;
+ bool valid = false;
+};
+
+SpineBounds getSpineBounds(ecs::Registry& registry, Entity entity);
+#endif
+
+void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight);
+void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight,
+ uintptr_t matrixPtr);
+
+void renderer_init(u32 width, u32 height);
+void renderer_resize(u32 width, u32 height);
+void renderer_begin(uintptr_t matrixPtr, u32 targetHandle);
+void renderer_flush();
+void renderer_end();
+void renderer_submitSprites(ecs::Registry& registry);
+void renderer_submitBitmapText(ecs::Registry& registry);
+#ifdef ES_ENABLE_SPINE
+void renderer_submitSpine(ecs::Registry& registry);
+#endif
+void renderer_submitTriangles(
+ uintptr_t verticesPtr, i32 vertexCount,
+ uintptr_t indicesPtr, i32 indexCount,
+ u32 textureId, i32 blendMode,
+ uintptr_t transformPtr);
+void renderer_setStage(i32 stage);
+u32 renderer_createTarget(u32 width, u32 height, i32 flags);
+u32 renderer_getTargetDepthTexture(u32 handle);
+void renderer_releaseTarget(u32 handle);
+u32 renderer_getTargetTexture(u32 handle);
+u32 renderer_getDrawCalls();
+u32 renderer_getTriangles();
+u32 renderer_getSprites();
+#ifdef ES_ENABLE_SPINE
+u32 renderer_getSpine();
+#endif
+u32 renderer_getText();
+u32 renderer_getMeshes();
+u32 renderer_getCulled();
+void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a);
+void renderer_setViewport(i32 x, i32 y, i32 w, i32 h);
+void renderer_setScissor(i32 x, i32 y, i32 w, i32 h, bool enable);
+void renderer_clearBuffers(i32 flags);
+void renderer_diagnose();
+void renderer_setEntityClipRect(u32 entity, i32 x, i32 y, i32 w, i32 h);
+void renderer_clearEntityClipRect(u32 entity);
+void renderer_clearAllClipRects();
+
+void gl_enableErrorCheck(bool enabled);
+u32 gl_checkErrors(const std::string& context);
+
+i32 registry_getCanvasEntity(ecs::Registry& registry);
+emscripten::val registry_getCameraEntities(ecs::Registry& registry);
+emscripten::val getChildEntities(ecs::Registry& registry, u32 entity);
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cpp
new file mode 100644
index 000000000..a3f5d1d7d
--- /dev/null
+++ b/src/esengine/bindings/ResourceManagerBindings.cpp
@@ -0,0 +1,114 @@
+#ifdef ES_PLATFORM_WEB
+
+#include "ResourceManagerBindings.hpp"
+#include "../resource/TextureMetadata.hpp"
+#include "../text/BitmapFont.hpp"
+#include "../core/Types.hpp"
+
+#include <emscripten/val.h>
+
+namespace esengine {
+
+u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,
+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY) {
+ const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);
+ ConstSpan<u8> pixelSpan(pixels, pixelsLen);
+
+ TextureFormat texFormat = TextureFormat::RGBA8;
+ if (format == 0) texFormat = TextureFormat::RGB8;
+ else if (format == 1) texFormat = TextureFormat::RGBA8;
+
+ auto handle = rm.createTexture(width, height, pixelSpan, texFormat, flipY);
+ return handle.id();
+}
+
+u32 rm_createShader(resource::ResourceManager& rm,
+ const std::string& vertSrc, const std::string& fragSrc) {
+ auto handle = rm.createShader(vertSrc, fragSrc);
+ return handle.id();
+}
+
+u32 rm_registerExternalTexture(resource::ResourceManager& rm, u32 glTextureId,
+ u32 width, u32 height) {
+ auto handle = rm.registerExternalTexture(glTextureId, width, height);
+ return handle.id();
+}
+
+void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId) {
+ rm.releaseTexture(resource::TextureHandle(handleId));
+}
+
+u32 rm_getTextureRefCount(resource::ResourceManager& rm, u32 handleId) {
+ return rm.getTextureRefCount(resource::TextureHandle(handleId));
+}
+
+void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path) {
+ rm.registerTextureWithPath(resource::TextureHandle(handleId), path);
+}
+
+void rm_releaseShader(resource::ResourceManager& rm, u32 handleId) {
+ rm.releaseShader(resource::ShaderHandle(handleId));
+}
+
+u32 rm_getShaderRefCount(resource::ResourceManager& rm, u32 handleId) {
+ return rm.getShaderRefCount(resource::ShaderHandle(handleId));
+}
+
+u32 rm_getTextureGLId(resource::ResourceManager& rm, u32 handleId) {
+ auto* tex = rm.getTexture(resource::TextureHandle(handleId));
+ return tex ? tex->getId() : 0;
+}
+
+u32 rm_loadBitmapFont(resource::ResourceManager& rm, const std::string& fntContent,
+ u32 textureHandle, u32 texWidth, u32 texHeight) {
+ auto handle = rm.createBitmapFont(fntContent,
+ resource::TextureHandle(textureHandle), texWidth, texHeight);
+ return handle.id();
+}
+
+u32 rm_createLabelAtlasFont(resource::ResourceManager& rm, u32 textureHandle,
+ u32 texWidth, u32 texHeight, const std::string& chars,
+ u32 charWidth, u32 charHeight) {
+ auto handle = rm.createLabelAtlasFont(
+ resource::TextureHandle(textureHandle), texWidth, texHeight,
+ chars, charWidth, charHeight);
+ return handle.id();
+}
+
+void rm_releaseBitmapFont(resource::ResourceManager& rm, u32 handleId) {
+ rm.releaseBitmapFont(resource::BitmapFontHandle(handleId));
+}
+
+u32 rm_getBitmapFontRefCount(resource::ResourceManager& rm, u32 handleId) {
+ return rm.getBitmapFontRefCount(resource::BitmapFontHandle(handleId));
+}
+
+emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,
+ const std::string& text, f32 fontSize, f32 spacing) {
+ auto* font = rm.getBitmapFont(resource::BitmapFontHandle(fontHandle));
+ if (!font) {
+ auto result = emscripten::val::object();
+ result.set("width", 0);
+ result.set("height", 0);
+ return result;
+ }
+ auto metrics = font->measureText(text, fontSize, spacing);
+ auto result = emscripten::val::object();
+ result.set("width", metrics.width);
+ result.set("height", metrics.height);
+ return result;
+}
+
+void rm_setTextureMetadata(resource::ResourceManager& rm, u32 handleId,
+ f32 left, f32 right, f32 top, f32 bottom) {
+ resource::TextureMetadata metadata;
+ metadata.sliceBorder.left = left;
+ metadata.sliceBorder.right = right;
+ metadata.sliceBorder.top = top;
+ metadata.sliceBorder.bottom = bottom;
+ rm.setTextureMetadata(resource::TextureHandle(handleId), metadata);
+}
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hpp
new file mode 100644
index 000000000..e7531e4f1
--- /dev/null
+++ b/src/esengine/bindings/ResourceManagerBindings.hpp
@@ -0,0 +1,41 @@
+#pragma once
+
+#ifdef ES_PLATFORM_WEB
+
+#include "../core/Types.hpp"
+#include "../resource/ResourceManager.hpp"
+#include <string>
+
+namespace emscripten {
+ class val;
+}
+
+namespace esengine {
+
+u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,
+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY);
+u32 rm_createShader(resource::ResourceManager& rm,
+ const std::string& vertSrc, const std::string& fragSrc);
+u32 rm_registerExternalTexture(resource::ResourceManager& rm, u32 glTextureId,
+ u32 width, u32 height);
+void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId);
+u32 rm_getTextureRefCount(resource::ResourceManager& rm, u32 handleId);
+void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path);
+void rm_releaseShader(resource::ResourceManager& rm, u32 handleId);
+u32 rm_getShaderRefCount(resource::ResourceManager& rm, u32 handleId);
+u32 rm_getTextureGLId(resource::ResourceManager& rm, u32 handleId);
+u32 rm_loadBitmapFont(resource::ResourceManager& rm, const std::string& fntContent,
+ u32 textureHandle, u32 texWidth, u32 texHeight);
+u32 rm_createLabelAtlasFont(resource::ResourceManager& rm, u32 textureHandle,
+ u32 texWidth, u32 texHeight, const std::string& chars,
+ u32 charWidth, u32 charHeight);
+void rm_releaseBitmapFont(resource::ResourceManager& rm, u32 handleId);
+u32 rm_getBitmapFontRefCount(resource::ResourceManager& rm, u32 handleId);
+emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,
+ const std::string& text, f32 fontSize, f32 spacing);
+void rm_setTextureMetadata(resource::ResourceManager& rm, u32 handleId,
+ f32 left, f32 right, f32 top, f32 bottom);
+
+} // namespace esengine
+
+#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index b7fd12aa1..f85c6d037 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -15,87 +15,40 @@
#include <emscripten/bind.h>
#include <emscripten/html5.h>
+#include "EngineContext.hpp"
+#include "ResourceManagerBindings.hpp"
+#include "RendererBindings.hpp"
+#include "ImmediateDrawBindings.hpp"
+#include "GeometryBindings.hpp"
+#include "PostProcessBindings.hpp"
+
#include "../renderer/OpenGLHeaders.hpp"
#include "../renderer/RenderContext.hpp"
#include "../renderer/RenderFrame.hpp"
-#include "../renderer/RenderCommand.hpp"
#include "../renderer/ImmediateDraw.hpp"
-#include "../renderer/Texture.hpp"
-#include "../renderer/BlendMode.hpp"
#include "../renderer/CustomGeometry.hpp"
-#include "../renderer/PostProcessPipeline.hpp"
-#include "../renderer/RenderStage.hpp"
#include "../resource/ResourceManager.hpp"
-#include "../resource/TextureMetadata.hpp"
-#include "../ecs/Registry.hpp"
#include "../ecs/TransformSystem.hpp"
-#include "../ecs/components/Camera.hpp"
-#include "../ecs/components/Canvas.hpp"
-#include "../ecs/components/Transform.hpp"
-#include "../ecs/components/BitmapText.hpp"
-#include "../ecs/components/Hierarchy.hpp"
-#include "../text/BitmapFont.hpp"
+#include "../core/Log.hpp"
#ifdef ES_ENABLE_SPINE
#include "../spine/SpineResourceManager.hpp"
#include "../spine/SpineSystem.hpp"
#endif
-#include <glm/gtc/matrix_transform.hpp>
-#include <glm/gtc/type_ptr.hpp>
+#include <glm/glm.hpp>
+#include <cstring>
namespace esengine {
-static Unique<RenderContext> g_renderContext;
-static Unique<RenderFrame> g_renderFrame;
-static Unique<ecs::TransformSystem> g_transformSystem;
-static Unique<resource::ResourceManager> g_resourceManager;
+static EngineContext& ctx() { return EngineContext::instance(); }
+
+#define g_initialized (ctx().isInitialized())
+#define g_webglContext (ctx().webglContext())
+#define g_resourceManager (ctx().resourceManager())
#ifdef ES_ENABLE_SPINE
-static Unique<spine::SpineResourceManager> g_spineResourceManager;
-static Unique<spine::SpineSystem> g_spineSystem;
+#define g_spineResourceManager (ctx().spineResourceManager())
#endif
-static Unique<ImmediateDraw> g_immediateDraw;
-static Unique<GeometryManager> g_geometryManager;
-static Unique<PostProcessPipeline> g_postProcessPipeline;
-static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE g_webglContext = 0;
-static bool g_initialized = false;
-static bool g_immediateDrawActive = false;
-static bool g_glErrorCheckEnabled = false;
-static u32 g_viewportWidth = 1280;
-static u32 g_viewportHeight = 720;
-static glm::vec4 g_clearColor{0.0f, 0.0f, 0.0f, 1.0f};
-static u32 checkGLErrors(const char* context) {
- if (!g_glErrorCheckEnabled) return 0;
- u32 errorCount = 0;
- GLenum err;
- while ((err = glGetError()) != GL_NO_ERROR) {
- const char* errStr = "UNKNOWN";
- switch (err) {
- case GL_INVALID_ENUM: errStr = "INVALID_ENUM"; break;
- case GL_INVALID_VALUE: errStr = "INVALID_VALUE"; break;
- case GL_INVALID_OPERATION: errStr = "INVALID_OPERATION"; break;
- case GL_INVALID_FRAMEBUFFER_OPERATION: errStr = "INVALID_FRAMEBUFFER_OPERATION"; break;
- case GL_OUT_OF_MEMORY: errStr = "OUT_OF_MEMORY"; break;
- }
- ES_LOG_ERROR("[GL Error] {} at: {}", errStr, context);
- errorCount++;
- }
- return errorCount;
-}
-
-static void flushImmediateDrawIfActive() {
- if (g_immediateDrawActive && g_immediateDraw) {
- g_immediateDraw->flush();
- }
-}
-
-static void restoreImmediateDrawState() {
- if (g_immediateDrawActive) {
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glEnable(GL_BLEND);
- glDisable(GL_DEPTH_TEST);
- glActiveTexture(GL_TEXTURE0);
- }
-}
+#define g_renderContext (ctx().renderContext())
EM_JS(void, callMaterialProvider, (int materialId, int outShaderIdPtr, int outBlendModePtr, int outUniformBufPtr, int outUniformCountPtr), {
var fn = Module['materialDataProvider'];
@@ -124,8 +77,8 @@ bool getMaterialData(u32 materialId, u32& shaderId, u32& blendMode) {
}
struct UniformData {
- std::string name;
- u32 type; // 0=float, 1=vec2, 2=vec3, 3=vec4
+ char name[32];
+ u32 type;
f32 values[4];
};
@@ -154,7 +107,9 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
u32 nameLen = *reinterpret_cast<const u32*>(ptr);
ptr += 4;
- ud.name = std::string(reinterpret_cast<const char*>(ptr), nameLen);
+ usize copyLen = std::min<usize>(nameLen, 31);
+ std::memcpy(ud.name, reinterpret_cast<const char*>(ptr), copyLen);
+ ud.name[copyLen] = '\0';
ptr += ((nameLen + 3) / 4) * 4;
ud.type = *reinterpret_cast<const u32*>(ptr);
@@ -186,11 +141,12 @@ bool initRendererInternal(const char* canvasSelector) {
attrs.powerPreference = EM_WEBGL_POWER_PREFERENCE_DEFAULT;
attrs.failIfMajorPerformanceCaveat = false;
- g_webglContext = emscripten_webgl_create_context(canvasSelector, &attrs);
- if (g_webglContext <= 0) {
- ES_LOG_ERROR("Failed to create WebGL2 context for '{}': {}", canvasSelector, g_webglContext);
+ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglCtx = emscripten_webgl_create_context(canvasSelector, &attrs);
+ if (webglCtx <= 0) {
+ ES_LOG_ERROR("Failed to create WebGL2 context for '{}': {}", canvasSelector, webglCtx);
return false;
}
+ ctx().setWebglContext(webglCtx);
EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(g_webglContext);
if (result != EMSCRIPTEN_RESULT_SUCCESS) {
@@ -200,29 +156,34 @@ bool initRendererInternal(const char* canvasSelector) {
ES_LOG_INFO("WebGL2 context created for '{}'", canvasSelector);
- g_resourceManager = makeUnique<resource::ResourceManager>();
- g_resourceManager->init();
+ auto resourceManager = makeUnique<resource::ResourceManager>();
+ resourceManager->init();
+ ctx().setResourceManager(std::move(resourceManager));
- g_renderContext = makeUnique<RenderContext>();
- g_renderContext->init();
+ auto renderContext = makeUnique<RenderContext>();
+ renderContext->init();
+ ctx().setRenderContext(std::move(renderContext));
- g_transformSystem = makeUnique<ecs::TransformSystem>();
+ ctx().setTransformSystem(makeUnique<ecs::TransformSystem>());
#ifdef ES_ENABLE_SPINE
- g_spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);
- g_spineResourceManager->init();
- g_spineSystem = makeUnique<spine::SpineSystem>(*g_spineResourceManager);
+ auto spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);
+ spineResourceManager->init();
+ ctx().setSpineResourceManager(std::move(spineResourceManager));
+ ctx().setSpineSystem(makeUnique<spine::SpineSystem>(*g_spineResourceManager));
#endif
- g_immediateDraw = makeUnique<ImmediateDraw>(*g_renderContext, *g_resourceManager);
- g_immediateDraw->init();
+ auto immediateDraw = makeUnique<ImmediateDraw>(*g_renderContext, *g_resourceManager);
+ immediateDraw->init();
+ ctx().setImmediateDraw(std::move(immediateDraw));
- g_geometryManager = makeUnique<GeometryManager>();
+ ctx().setGeometryManager(makeUnique<GeometryManager>());
- g_renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);
- g_renderFrame->init(1280, 720);
+ auto renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);
+ renderFrame->init(1280, 720);
+ ctx().setRenderFrame(std::move(renderFrame));
- g_initialized = true;
+ ctx().setInitialized(true);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -245,7 +206,7 @@ bool initRendererWithContext(int contextHandle) {
return false;
}
- g_webglContext = contextHandle;
+ ctx().setWebglContext(contextHandle);
EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(g_webglContext);
if (result != EMSCRIPTEN_RESULT_SUCCESS) {
@@ -255,29 +216,34 @@ bool initRendererWithContext(int contextHandle) {
ES_LOG_INFO("WebGL context set from external handle: {}", contextHandle);
- g_resourceManager = makeUnique<resource::ResourceManager>();
- g_resourceManager->init();
+ auto resourceManager = makeUnique<resource::ResourceManager>();
+ resourceManager->init();
+ ctx().setResourceManager(std::move(resourceManager));
- g_renderContext = makeUnique<RenderContext>();
- g_renderContext->init();
+ auto renderContext = makeUnique<RenderContext>();
+ renderContext->init();
+ ctx().setRenderContext(std::move(renderContext));
- g_transformSystem = makeUnique<ecs::TransformSystem>();
+ ctx().setTransformSystem(makeUnique<ecs::TransformSystem>());
#ifdef ES_ENABLE_SPINE
- g_spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);
- g_spineResourceManager->init();
- g_spineSystem = makeUnique<spine::SpineSystem>(*g_spineResourceManager);
+ auto spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);
+ spineResourceManager->init();
+ ctx().setSpineResourceManager(std::move(spineResourceManager));
+ ctx().setSpineSystem(makeUnique<spine::SpineSystem>(*g_spineResourceManager));
#endif
- g_immediateDraw = makeUnique<ImmediateDraw>(*g_renderContext, *g_resourceManager);
- g_immediateDraw->init();
+ auto immediateDraw = makeUnique<ImmediateDraw>(*g_renderContext, *g_resourceManager);
+ immediateDraw->init();
+ ctx().setImmediateDraw(std::move(immediateDraw));
- g_geometryManager = makeUnique<GeometryManager>();
+ ctx().setGeometryManager(makeUnique<GeometryManager>());
- g_renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);
- g_renderFrame->init(1280, 720);
+ auto renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);
+ renderFrame->init(1280, 720);
+ ctx().setRenderFrame(std::move(renderFrame));
- g_initialized = true;
+ ctx().setInitialized(true);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -286,973 +252,11 @@ bool initRendererWithContext(int contextHandle) {
}
void shutdownRenderer() {
- if (!g_initialized) return;
-
- g_geometryManager.reset();
-
- if (g_renderFrame) {
- g_renderFrame->shutdown();
- g_renderFrame.reset();
- }
-
- if (g_immediateDraw) {
- g_immediateDraw->shutdown();
- g_immediateDraw.reset();
- }
-
-#ifdef ES_ENABLE_SPINE
- g_spineSystem.reset();
- if (g_spineResourceManager) {
- g_spineResourceManager->shutdown();
- g_spineResourceManager.reset();
- }
-#endif
-
- g_transformSystem.reset();
- g_renderContext->shutdown();
- g_renderContext.reset();
- g_resourceManager->shutdown();
- g_resourceManager.reset();
-
- if (g_webglContext > 0) {
- emscripten_webgl_destroy_context(g_webglContext);
- g_webglContext = 0;
- }
-
- g_initialized = false;
+ ctx().shutdown();
}
resource::ResourceManager* getResourceManager() {
- return g_resourceManager.get();
-}
-
-u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,
- uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY) {
- const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);
- ConstSpan<u8> pixelSpan(pixels, pixelsLen);
-
- TextureFormat texFormat = TextureFormat::RGBA8;
- if (format == 0) texFormat = TextureFormat::RGB8;
- else if (format == 1) texFormat = TextureFormat::RGBA8;
-
- auto handle = rm.createTexture(width, height, pixelSpan, texFormat, flipY);
- return handle.id();
-}
-
-u32 rm_createShader(resource::ResourceManager& rm,
- const std::string& vertSrc, const std::string& fragSrc) {
- auto handle = rm.createShader(vertSrc, fragSrc);
- return handle.id();
-}
-
-u32 rm_registerExternalTexture(resource::ResourceManager& rm, u32 glTextureId,
- u32 width, u32 height) {
- auto handle = rm.registerExternalTexture(glTextureId, width, height);
- return handle.id();
-}
-
-void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId) {
- rm.releaseTexture(resource::TextureHandle(handleId));
-}
-
-void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path) {
- rm.registerTextureWithPath(resource::TextureHandle(handleId), path);
-}
-
-void rm_releaseShader(resource::ResourceManager& rm, u32 handleId) {
- rm.releaseShader(resource::ShaderHandle(handleId));
-}
-
-u32 rm_getTextureGLId(resource::ResourceManager& rm, u32 handleId) {
- auto* tex = rm.getTexture(resource::TextureHandle(handleId));
- return tex ? tex->getId() : 0;
-}
-
-u32 rm_loadBitmapFont(resource::ResourceManager& rm, const std::string& fntContent,
- u32 textureHandle, u32 texWidth, u32 texHeight) {
- auto handle = rm.createBitmapFont(fntContent,
- resource::TextureHandle(textureHandle), texWidth, texHeight);
- return handle.id();
-}
-
-u32 rm_createLabelAtlasFont(resource::ResourceManager& rm, u32 textureHandle,
- u32 texWidth, u32 texHeight, const std::string& chars,
- u32 charWidth, u32 charHeight) {
- auto handle = rm.createLabelAtlasFont(
- resource::TextureHandle(textureHandle), texWidth, texHeight,
- chars, charWidth, charHeight);
- return handle.id();
-}
-
-void rm_releaseBitmapFont(resource::ResourceManager& rm, u32 handleId) {
- rm.releaseBitmapFont(resource::BitmapFontHandle(handleId));
-}
-
-emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,
- const std::string& text, f32 fontSize, f32 spacing) {
- auto* font = rm.getBitmapFont(resource::BitmapFontHandle(fontHandle));
- if (!font) {
- auto result = emscripten::val::object();
- result.set("width", 0);
- result.set("height", 0);
- return result;
- }
- auto metrics = font->measureText(text, fontSize, spacing);
- auto result = emscripten::val::object();
- result.set("width", metrics.width);
- result.set("height", metrics.height);
- return result;
-}
-
-void rm_setTextureMetadata(resource::ResourceManager& rm, u32 handleId,
- f32 left, f32 right, f32 top, f32 bottom) {
- resource::TextureMetadata metadata;
- metadata.sliceBorder.left = left;
- metadata.sliceBorder.right = right;
- metadata.sliceBorder.top = top;
- metadata.sliceBorder.bottom = bottom;
- rm.setTextureMetadata(resource::TextureHandle(handleId), metadata);
-}
-
-void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight) {
- if (!g_initialized || !g_renderFrame) return;
-
- if (g_transformSystem) {
- g_transformSystem->update(registry, 0.0f);
- }
-
-#ifdef ES_ENABLE_SPINE
- if (g_spineSystem) {
- g_spineSystem->update(registry, 0.016f);
- }
-#endif
-
- g_viewportWidth = static_cast<u32>(viewportWidth);
- g_viewportHeight = static_cast<u32>(viewportHeight);
- g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
-
- glViewport(0, 0, viewportWidth, viewportHeight);
- glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- glm::mat4 viewProjection = glm::mat4(1.0f);
-
- auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
-
- for (auto entity : cameraView) {
- auto& camera = registry.get<ecs::Camera>(entity);
- if (!camera.isActive) continue;
-
- auto& transform = registry.get<ecs::LocalTransform>(entity);
- glm::mat4 view = glm::inverse(glm::translate(glm::mat4(1.0f), transform.position));
-
- glm::mat4 projection;
- f32 aspect = static_cast<f32>(viewportWidth) / static_cast<f32>(viewportHeight);
-
- if (camera.projectionType == ecs::ProjectionType::Orthographic) {
- f32 halfHeight = camera.orthoSize;
- f32 halfWidth = halfHeight * aspect;
- projection = glm::ortho(-halfWidth, halfWidth, -halfHeight, halfHeight,
- camera.nearPlane, camera.farPlane);
- } else {
- projection = glm::perspective(
- glm::radians(camera.fov),
- static_cast<f32>(viewportWidth) / static_cast<f32>(viewportHeight),
- camera.nearPlane, camera.farPlane
- );
- }
-
- viewProjection = projection * view;
- break;
- }
-
- g_renderFrame->begin(viewProjection);
- g_renderFrame->submitSprites(registry);
- g_renderFrame->submitBitmapText(registry);
-#ifdef ES_ENABLE_SPINE
- if (g_spineSystem) {
- g_renderFrame->submitSpine(registry, *g_spineSystem);
- }
-#endif
- g_renderFrame->end();
-}
-
-void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight,
- uintptr_t matrixPtr) {
- if (!g_initialized || !g_renderFrame) return;
-
- if (g_transformSystem) {
- g_transformSystem->update(registry, 0.0f);
- }
-
-#ifdef ES_ENABLE_SPINE
- if (g_spineSystem) {
- g_spineSystem->update(registry, 0.016f);
- }
-#endif
-
- g_viewportWidth = static_cast<u32>(viewportWidth);
- g_viewportHeight = static_cast<u32>(viewportHeight);
- g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
-
- glViewport(0, 0, viewportWidth, viewportHeight);
- glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
- glm::mat4 viewProjection = glm::make_mat4(matrixData);
-
- g_renderFrame->begin(viewProjection);
- g_renderFrame->submitSprites(registry);
- g_renderFrame->submitBitmapText(registry);
-#ifdef ES_ENABLE_SPINE
- if (g_spineSystem) {
- g_renderFrame->submitSpine(registry, *g_spineSystem);
- }
-#endif
- g_renderFrame->end();
-}
-
-#ifdef ES_ENABLE_SPINE
-struct SpineBounds {
- f32 x = 0;
- f32 y = 0;
- f32 width = 0;
- f32 height = 0;
- bool valid = false;
-};
-
-SpineBounds getSpineBounds(ecs::Registry& registry, Entity entity) {
- SpineBounds bounds;
- if (!g_spineSystem) return bounds;
-
- if (g_spineSystem->getSkeletonBounds(entity, bounds.x, bounds.y,
- bounds.width, bounds.height)) {
- bounds.valid = true;
- }
- return bounds;
-}
-#endif
-
-// =============================================================================
-// ImmediateDraw API
-// =============================================================================
-
-static glm::mat4 g_currentViewProjection{1.0f};
-
-void draw_begin(uintptr_t matrixPtr) {
- if (!g_initialized || !g_immediateDraw) return;
-
- glViewport(0, 0, g_viewportWidth, g_viewportHeight);
-
- const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
- g_currentViewProjection = glm::make_mat4(matrixData);
- g_immediateDraw->begin(g_currentViewProjection);
- g_immediateDrawActive = true;
-}
-
-void draw_end() {
- if (!g_initialized || !g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->end();
- g_immediateDrawActive = false;
- checkGLErrors("draw_end");
-}
-
-void draw_line(f32 fromX, f32 fromY, f32 toX, f32 toY,
- f32 r, f32 g, f32 b, f32 a, f32 thickness) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->line(
- glm::vec2(fromX, fromY),
- glm::vec2(toX, toY),
- glm::vec4(r, g, b, a),
- thickness
- );
-}
-
-void draw_rect(f32 x, f32 y, f32 width, f32 height,
- f32 r, f32 g, f32 b, f32 a, bool filled) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->rect(
- glm::vec2(x, y),
- glm::vec2(width, height),
- glm::vec4(r, g, b, a),
- filled
- );
-}
-
-void draw_rectOutline(f32 x, f32 y, f32 width, f32 height,
- f32 r, f32 g, f32 b, f32 a, f32 thickness) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->rectOutline(
- glm::vec2(x, y),
- glm::vec2(width, height),
- glm::vec4(r, g, b, a),
- thickness
- );
-}
-
-void draw_circle(f32 centerX, f32 centerY, f32 radius,
- f32 r, f32 g, f32 b, f32 a, bool filled, i32 segments) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->circle(
- glm::vec2(centerX, centerY),
- radius,
- glm::vec4(r, g, b, a),
- filled,
- segments
- );
-}
-
-void draw_circleOutline(f32 centerX, f32 centerY, f32 radius,
- f32 r, f32 g, f32 b, f32 a, f32 thickness, i32 segments) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->circleOutline(
- glm::vec2(centerX, centerY),
- radius,
- glm::vec4(r, g, b, a),
- thickness,
- segments
- );
-}
-
-void draw_texture(f32 x, f32 y, f32 width, f32 height, u32 textureId,
- f32 r, f32 g, f32 b, f32 a) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->texture(
- glm::vec2(x, y),
- glm::vec2(width, height),
- textureId,
- glm::vec4(r, g, b, a)
- );
-}
-
-void draw_textureRotated(f32 x, f32 y, f32 width, f32 height, f32 rotation,
- u32 textureId, f32 r, f32 g, f32 b, f32 a) {
- if (!g_immediateDraw || !g_immediateDrawActive) return;
-
- g_immediateDraw->textureRotated(
- glm::vec2(x, y),
- glm::vec2(width, height),
- rotation,
- textureId,
- glm::vec4(r, g, b, a)
- );
-}
-
-void draw_setLayer(i32 layer) {
- if (!g_immediateDraw) return;
- g_immediateDraw->setLayer(layer);
-}
-
-void draw_setDepth(f32 depth) {
- if (!g_immediateDraw) return;
- g_immediateDraw->setDepth(depth);
-}
-
-u32 draw_getDrawCallCount() {
- if (!g_immediateDraw) return 0;
- return g_immediateDraw->getDrawCallCount();
-}
-
-u32 draw_getPrimitiveCount() {
- if (!g_immediateDraw) return 0;
- return g_immediateDraw->getPrimitiveCount();
-}
-
-void draw_setBlendMode(i32 mode) {
- flushImmediateDrawIfActive();
- RenderCommand::setBlendMode(static_cast<BlendMode>(mode));
-}
-
-void draw_setDepthTest(bool enabled) {
- flushImmediateDrawIfActive();
- RenderCommand::setDepthTest(enabled);
-}
-
-// =============================================================================
-// Geometry API
-// =============================================================================
-
-u32 geometry_create() {
- if (!g_geometryManager) return 0;
- return g_geometryManager->create();
-}
-
-void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,
- uintptr_t layoutPtr, u32 layoutCount, bool dynamic) {
- if (!g_geometryManager) return;
-
- auto* geom = g_geometryManager->get(handle);
- if (!geom) return;
-
- const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
- const i32* layoutData = reinterpret_cast<const i32*>(layoutPtr);
-
- std::vector<VertexAttribute> attrs;
-
- for (u32 i = 0; i < layoutCount; ++i) {
- ShaderDataType type = static_cast<ShaderDataType>(layoutData[i]);
- std::string name = "a_attr" + std::to_string(i);
- attrs.emplace_back(type, name);
- }
-
- VertexLayout layout;
- if (layoutCount == 1) {
- layout = { attrs[0] };
- } else if (layoutCount == 2) {
- layout = { attrs[0], attrs[1] };
- } else if (layoutCount == 3) {
- layout = { attrs[0], attrs[1], attrs[2] };
- } else if (layoutCount == 4) {
- layout = { attrs[0], attrs[1], attrs[2], attrs[3] };
- }
-
- geom->init(vertices, vertexCount, layout, dynamic);
-}
-
-void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
- if (!g_geometryManager) return;
-
- auto* geom = g_geometryManager->get(handle);
- if (!geom) return;
-
- const u16* indices = reinterpret_cast<const u16*>(indicesPtr);
- geom->setIndices(indices, indexCount);
-}
-
-void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
- if (!g_geometryManager) return;
-
- auto* geom = g_geometryManager->get(handle);
- if (!geom) return;
-
- const u32* indices = reinterpret_cast<const u32*>(indicesPtr);
- geom->setIndices(indices, indexCount);
-}
-
-void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount, u32 offset) {
- if (!g_geometryManager) return;
-
- auto* geom = g_geometryManager->get(handle);
- if (!geom) return;
-
- const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
- geom->updateVertices(vertices, vertexCount, offset);
-}
-
-void geometry_release(u32 handle) {
- if (!g_geometryManager) return;
- g_geometryManager->release(handle);
-}
-
-bool geometry_isValid(u32 handle) {
- if (!g_geometryManager) return false;
- return g_geometryManager->isValid(handle);
-}
-
-// =============================================================================
-// Draw Mesh API
-// =============================================================================
-
-void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {
- if (!g_initialized || !g_geometryManager || !g_resourceManager) return;
-
- auto* geom = g_geometryManager->get(geometryHandle);
- if (!geom || !geom->isValid()) return;
-
- Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));
- if (!shader) return;
-
- flushImmediateDrawIfActive();
-
- const f32* transformData = reinterpret_cast<const f32*>(transformPtr);
- glm::mat4 transform = glm::make_mat4(transformData);
-
- shader->bind();
- shader->setUniform("u_projection", g_currentViewProjection);
- shader->setUniform("u_model", transform);
-
- geom->bind();
-
- if (geom->hasIndices()) {
- auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
- if (ib) {
- GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
- }
- } else {
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
- }
-
- geom->unbind();
- checkGLErrors("draw_mesh");
- restoreImmediateDrawState();
-}
-
-void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr,
- uintptr_t uniformsPtr, u32 uniformCount) {
- if (!g_initialized || !g_geometryManager || !g_resourceManager) return;
-
- auto* geom = g_geometryManager->get(geometryHandle);
- if (!geom || !geom->isValid()) return;
-
- Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));
- if (!shader) return;
-
- flushImmediateDrawIfActive();
-
- const f32* transformData = reinterpret_cast<const f32*>(transformPtr);
- glm::mat4 transform = glm::make_mat4(transformData);
-
- shader->bind();
- shader->setUniform("u_projection", g_currentViewProjection);
- shader->setUniform("u_model", transform);
-
- static constexpr const char* UNIFORM_NAMES[] = {
- "u_time", "u_color", "u_intensity", "u_scale", "u_offset",
- "u_param0", "u_param1", "u_param2", "u_param3", "u_param4",
- "u_vec0", "u_vec1", "u_vec2", "u_vec3",
- "u_texture0", "u_texture1", "u_texture2", "u_texture3"
- };
- static constexpr u32 UNIFORM_NAME_COUNT = sizeof(UNIFORM_NAMES) / sizeof(UNIFORM_NAMES[0]);
-
- const f32* uniforms = reinterpret_cast<const f32*>(uniformsPtr);
- u32 idx = 0;
-
- while (idx < uniformCount) {
- auto type = static_cast<i32>(uniforms[idx++]);
- auto nameId = static_cast<i32>(uniforms[idx++]);
-
- const char* name = (nameId >= 0 && static_cast<u32>(nameId) < UNIFORM_NAME_COUNT)
- ? UNIFORM_NAMES[nameId] : "u_unknown";
-
- switch (type) {
- case 1: {
- f32 value = uniforms[idx++];
- shader->setUniform(name, value);
- break;
- }
- case 2: {
- glm::vec2 value(uniforms[idx], uniforms[idx + 1]);
- idx += 2;
- shader->setUniform(name, value);
- break;
- }
- case 3: {
- glm::vec3 value(uniforms[idx], uniforms[idx + 1], uniforms[idx + 2]);
- idx += 3;
- shader->setUniform(name, value);
- break;
- }
- case 4: {
- glm::vec4 value(uniforms[idx], uniforms[idx + 1],
- uniforms[idx + 2], uniforms[idx + 3]);
- idx += 4;
- shader->setUniform(name, value);
- break;
- }
- case 10: {
- i32 slot = static_cast<i32>(uniforms[idx++]);
- u32 textureId = static_cast<u32>(uniforms[idx++]);
- glActiveTexture(GL_TEXTURE0 + slot);
- glBindTexture(GL_TEXTURE_2D, textureId);
- shader->setUniform(name, slot);
- break;
- }
- default:
- break;
- }
- }
-
- geom->bind();
-
- if (geom->hasIndices()) {
- auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
- if (ib) {
- GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
- }
- } else {
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
- }
-
- geom->unbind();
- checkGLErrors("draw_meshWithUniforms");
- restoreImmediateDrawState();
-}
-
-// =============================================================================
-// PostProcess API
-// =============================================================================
-
-bool postprocess_init(u32 width, u32 height) {
- if (!g_initialized || !g_renderContext || !g_resourceManager) return false;
-
- if (!g_postProcessPipeline) {
- g_postProcessPipeline = makeUnique<PostProcessPipeline>(*g_renderContext, *g_resourceManager);
- }
-
- g_postProcessPipeline->init(width, height);
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
-
- return g_postProcessPipeline->isInitialized();
-}
-
-void postprocess_shutdown() {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->shutdown();
- g_postProcessPipeline.reset();
- }
-}
-
-void postprocess_resize(u32 width, u32 height) {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->resize(width, height);
- }
-}
-
-u32 postprocess_addPass(const std::string& name, u32 shaderHandle) {
- if (!g_postProcessPipeline) return 0;
- return g_postProcessPipeline->addPass(name, resource::ShaderHandle(shaderHandle));
-}
-
-void postprocess_removePass(const std::string& name) {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->removePass(name);
- }
-}
-
-void postprocess_setPassEnabled(const std::string& name, bool enabled) {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->setPassEnabled(name, enabled);
- }
-}
-
-bool postprocess_isPassEnabled(const std::string& name) {
- if (!g_postProcessPipeline) return false;
- return g_postProcessPipeline->isPassEnabled(name);
-}
-
-void postprocess_setUniformFloat(const std::string& passName,
- const std::string& uniform, f32 value) {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->setPassUniformFloat(passName, uniform, value);
- }
-}
-
-void postprocess_setUniformVec4(const std::string& passName,
- const std::string& uniform,
- f32 x, f32 y, f32 z, f32 w) {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->setPassUniformVec4(passName, uniform, glm::vec4(x, y, z, w));
- }
-}
-
-void postprocess_begin() {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->begin();
- }
-}
-
-void postprocess_end() {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->end();
- }
-}
-
-u32 postprocess_getPassCount() {
- if (!g_postProcessPipeline) return 0;
- return g_postProcessPipeline->getPassCount();
-}
-
-bool postprocess_isInitialized() {
- if (!g_postProcessPipeline) return false;
- return g_postProcessPipeline->isInitialized();
-}
-
-void postprocess_setBypass(bool bypass) {
- if (g_postProcessPipeline) {
- g_postProcessPipeline->setBypass(bypass);
- }
-}
-
-bool postprocess_isBypassed() {
- if (!g_postProcessPipeline) return true;
- return g_postProcessPipeline->isBypassed();
-}
-
-void renderer_init(u32 width, u32 height) {
- if (!g_renderFrame) return;
- g_viewportWidth = width;
- g_viewportHeight = height;
- g_renderFrame->resize(width, height);
-}
-
-void renderer_resize(u32 width, u32 height) {
- if (!g_renderFrame) return;
- g_viewportWidth = width;
- g_viewportHeight = height;
- g_renderFrame->resize(width, height);
-}
-
-void renderer_begin(uintptr_t matrixPtr, u32 targetHandle) {
- if (!g_renderFrame) return;
-
- const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
- glm::mat4 viewProjection = glm::make_mat4(matrixData);
-
- g_renderFrame->begin(viewProjection, targetHandle);
-}
-
-void renderer_flush() {
- if (!g_renderFrame) return;
- g_renderFrame->flush();
- checkGLErrors("renderer_flush");
-}
-
-void renderer_end() {
- if (!g_renderFrame) return;
- g_renderFrame->end();
- checkGLErrors("renderer_end");
-}
-
-void renderer_submitSprites(ecs::Registry& registry) {
- if (!g_renderFrame || !g_transformSystem) return;
- g_transformSystem->update(registry, 0.0f);
- g_renderFrame->submitSprites(registry);
-}
-
-void renderer_submitBitmapText(ecs::Registry& registry) {
- if (!g_renderFrame || !g_transformSystem) return;
- g_transformSystem->update(registry, 0.0f);
- g_renderFrame->submitBitmapText(registry);
-}
-
-#ifdef ES_ENABLE_SPINE
-void renderer_submitSpine(ecs::Registry& registry) {
- if (!g_renderFrame || !g_spineSystem) return;
- g_spineSystem->update(registry, 0.016f);
- g_renderFrame->submitSpine(registry, *g_spineSystem);
- checkGLErrors("renderer_submitSpine");
-}
-#endif
-
-void renderer_submitTriangles(
- uintptr_t verticesPtr, i32 vertexCount,
- uintptr_t indicesPtr, i32 indexCount,
- u32 textureId, i32 blendMode,
- uintptr_t transformPtr) {
- if (!g_renderFrame) return;
-
- const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
- const u16* indices = reinterpret_cast<const u16*>(indicesPtr);
- const f32* transform = transformPtr ? reinterpret_cast<const f32*>(transformPtr) : nullptr;
-
- g_renderFrame->submitExternalTriangles(
- vertices, vertexCount,
- indices, indexCount,
- textureId, blendMode,
- transform);
-}
-
-void renderer_setStage(i32 stage) {
- if (!g_renderFrame) return;
- g_renderFrame->setStage(static_cast<RenderStage>(stage));
-}
-
-u32 renderer_createTarget(u32 width, u32 height, i32 flags) {
- if (!g_renderFrame) return 0;
- bool depth = (flags & 1) != 0;
- bool linear = (flags & 2) != 0;
- return g_renderFrame->targetManager().create(width, height, depth, linear);
-}
-
-u32 renderer_getTargetDepthTexture(u32 handle) {
- if (!g_renderFrame) return 0;
- auto* target = g_renderFrame->targetManager().get(handle);
- return target ? target->getDepthTexture() : 0;
-}
-
-void renderer_releaseTarget(u32 handle) {
- if (!g_renderFrame) return;
- g_renderFrame->targetManager().release(handle);
-}
-
-u32 renderer_getTargetTexture(u32 handle) {
- if (!g_renderFrame) return 0;
- auto* target = g_renderFrame->targetManager().get(handle);
- return target ? target->getColorTexture() : 0;
-}
-
-u32 renderer_getDrawCalls() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().draw_calls;
-}
-
-u32 renderer_getTriangles() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().triangles;
-}
-
-u32 renderer_getSprites() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().sprites;
-}
-
-#ifdef ES_ENABLE_SPINE
-u32 renderer_getSpine() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().spine;
-}
-#endif
-
-u32 renderer_getText() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().text;
-}
-
-u32 renderer_getMeshes() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().meshes;
-}
-
-u32 renderer_getCulled() {
- if (!g_renderFrame) return 0;
- return g_renderFrame->stats().culled;
-}
-
-void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a) {
- g_clearColor = glm::vec4(r, g, b, a);
-}
-
-void renderer_setViewport(i32 x, i32 y, i32 w, i32 h) {
- glViewport(x, y, w, h);
-}
-
-void renderer_setScissor(i32 x, i32 y, i32 w, i32 h, bool enable) {
- if (enable) {
- glEnable(GL_SCISSOR_TEST);
- glScissor(x, y, w, h);
- } else {
- glDisable(GL_SCISSOR_TEST);
- }
-}
-
-void renderer_clearBuffers(i32 flags) {
- GLbitfield mask = 0;
- if (flags & 1) mask |= GL_COLOR_BUFFER_BIT;
- if (flags & 2) mask |= GL_DEPTH_BUFFER_BIT;
- if (mask) glClear(mask);
-}
-
-void renderer_diagnose() {
- if (!g_initialized) {
- ES_LOG_ERROR("[Diagnose] Renderer not initialized");
- return;
- }
-
- const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
- const char* rendererStr = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
- const char* vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
- const char* slVersion = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
- ES_LOG_INFO("[Diagnose] GL Version: {}", version ? version : "null");
- ES_LOG_INFO("[Diagnose] GL Renderer: {}", rendererStr ? rendererStr : "null");
- ES_LOG_INFO("[Diagnose] GL Vendor: {}", vendor ? vendor : "null");
- ES_LOG_INFO("[Diagnose] GLSL Version: {}", slVersion ? slVersion : "null");
-
- GLint viewport[4];
- glGetIntegerv(GL_VIEWPORT, viewport);
- ES_LOG_INFO("[Diagnose] GL Viewport: {}x{} at ({},{})", viewport[2], viewport[3], viewport[0], viewport[1]);
- ES_LOG_INFO("[Diagnose] Stored viewport: {}x{}", g_viewportWidth, g_viewportHeight);
-
- GLint maxTextureUnits;
- glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
- ES_LOG_INFO("[Diagnose] Max texture units: {}", maxTextureUnits);
-
- GLint maxAttribs;
- glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxAttribs);
- ES_LOG_INFO("[Diagnose] Max vertex attribs: {}", maxAttribs);
-
- while (glGetError() != GL_NO_ERROR) {}
- ES_LOG_INFO("[Diagnose] No pending GL errors (cleared)");
-}
-
-void gl_enableErrorCheck(bool enabled) {
- g_glErrorCheckEnabled = enabled;
- if (enabled) {
- while (glGetError() != GL_NO_ERROR) {}
- ES_LOG_INFO("[GL] Error checking enabled");
- }
-}
-
-u32 gl_checkErrors(const std::string& context) {
- bool prev = g_glErrorCheckEnabled;
- g_glErrorCheckEnabled = true;
- u32 count = checkGLErrors(context.c_str());
- g_glErrorCheckEnabled = prev;
- if (count == 0 && prev) {
- ES_LOG_INFO("[GL] No errors at: {}", context);
- }
- return count;
-}
-
-i32 registry_getCanvasEntity(ecs::Registry& registry) {
- auto view = registry.view<ecs::Canvas>();
- for (auto entity : view) {
- return static_cast<i32>(entity);
- }
- return -1;
-}
-
-emscripten::val registry_getCameraEntities(ecs::Registry& registry) {
- auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
- auto result = emscripten::val::array();
- u32 idx = 0;
- for (auto entity : cameraView) {
- auto& camera = registry.get<ecs::Camera>(entity);
- if (camera.isActive) {
- result.set(idx++, static_cast<u32>(entity));
- }
- }
- return result;
-}
-
-void renderer_setEntityClipRect(u32 entity, i32 x, i32 y, i32 w, i32 h) {
- if (g_renderFrame) {
- g_renderFrame->setEntityClipRect(entity, x, y, w, h);
- }
-}
-
-void renderer_clearEntityClipRect(u32 entity) {
- if (g_renderFrame) {
- g_renderFrame->clearEntityClipRect(entity);
- }
-}
-
-void renderer_clearAllClipRects() {
- if (g_renderFrame) {
- g_renderFrame->clearAllClipRects();
- }
-}
-
-emscripten::val getChildEntities(ecs::Registry& registry, u32 entity) {
- auto result = emscripten::val::array();
- if (!registry.has<ecs::Children>(static_cast<Entity>(entity))) {
- return result;
- }
- const auto& children = registry.get<ecs::Children>(static_cast<Entity>(entity));
- u32 idx = 0;
- for (auto child : children.entities) {
- result.set(idx++, static_cast<u32>(child));
- }
- return result;
+ return g_resourceManager;
}
} // namespace esengine
@@ -1266,19 +270,21 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderFrameWithMatrix", &esengine::renderFrameWithMatrix);
emscripten::function("getResourceManager", &esengine::getResourceManager, emscripten::allow_raw_pointers());
-
emscripten::class_<esengine::resource::ResourceManager>("ResourceManager")
.function("createTexture", &esengine::rm_createTexture)
.function("createShader", &esengine::rm_createShader)
.function("registerExternalTexture", &esengine::rm_registerExternalTexture)
.function("releaseTexture", &esengine::rm_releaseTexture)
+ .function("getTextureRefCount", &esengine::rm_getTextureRefCount)
.function("releaseShader", &esengine::rm_releaseShader)
+ .function("getShaderRefCount", &esengine::rm_getShaderRefCount)
.function("getTextureGLId", &esengine::rm_getTextureGLId)
.function("setTextureMetadata", &esengine::rm_setTextureMetadata)
.function("registerTextureWithPath", &esengine::rm_registerTextureWithPath)
.function("loadBitmapFont", &esengine::rm_loadBitmapFont)
.function("createLabelAtlasFont", &esengine::rm_createLabelAtlasFont)
.function("releaseBitmapFont", &esengine::rm_releaseBitmapFont)
+ .function("getBitmapFontRefCount", &esengine::rm_getBitmapFontRefCount)
.function("measureBitmapText", &esengine::rm_measureBitmapText);
#ifdef ES_ENABLE_SPINE
@@ -1292,7 +298,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("getSpineBounds", &esengine::getSpineBounds);
#endif
- // ImmediateDraw API
emscripten::function("draw_begin", &esengine::draw_begin);
emscripten::function("draw_end", &esengine::draw_end);
emscripten::function("draw_line", &esengine::draw_line);
@@ -1311,7 +316,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("draw_mesh", &esengine::draw_mesh);
emscripten::function("draw_meshWithUniforms", &esengine::draw_meshWithUniforms);
- // Geometry API
emscripten::function("geometry_create", &esengine::geometry_create);
emscripten::function("geometry_init", &esengine::geometry_init);
emscripten::function("geometry_setIndices16", &esengine::geometry_setIndices16);
@@ -1320,7 +324,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("geometry_release", &esengine::geometry_release);
emscripten::function("geometry_isValid", &esengine::geometry_isValid);
- // PostProcess API
emscripten::function("postprocess_init", &esengine::postprocess_init);
emscripten::function("postprocess_shutdown", &esengine::postprocess_shutdown);
emscripten::function("postprocess_resize", &esengine::postprocess_resize);
@@ -1337,7 +340,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("postprocess_setBypass", &esengine::postprocess_setBypass);
emscripten::function("postprocess_isBypassed", &esengine::postprocess_isBypassed);
- // Renderer API (RenderFrame)
emscripten::function("renderer_init", &esengine::renderer_init);
emscripten::function("renderer_resize", &esengine::renderer_resize);
emscripten::function("renderer_begin", &esengine::renderer_begin);
@@ -1367,18 +369,14 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_setViewport", &esengine::renderer_setViewport);
emscripten::function("renderer_setScissor", &esengine::renderer_setScissor);
emscripten::function("renderer_clearBuffers", &esengine::renderer_clearBuffers);
-
- // Clip Rect API
emscripten::function("renderer_setEntityClipRect", &esengine::renderer_setEntityClipRect);
emscripten::function("renderer_clearEntityClipRect", &esengine::renderer_clearEntityClipRect);
emscripten::function("renderer_clearAllClipRects", &esengine::renderer_clearAllClipRects);
- // ECS Query API
emscripten::function("registry_getCanvasEntity", &esengine::registry_getCanvasEntity);
emscripten::function("registry_getCameraEntities", &esengine::registry_getCameraEntities);
emscripten::function("getChildEntities", &esengine::getChildEntities);
- // GL Debug API
emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);
emscripten::function("gl_checkErrors", &esengine::gl_checkErrors);
emscripten::function("renderer_diagnose", &esengine::renderer_diagnose);
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index 2a6c4f010..997dcda9e 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -23,6 +23,7 @@
// Standard library
#include <algorithm>
+#include <memory>
#include <vector>
namespace esengine::ecs {
@@ -89,18 +90,24 @@ public:
*
* @tparam T The component type to store
*
- * @details The sparse set uses two arrays:
- * - **Sparse array**: Maps entity IDs to dense array indices
+ * @details The sparse set uses a paged sparse array and dense arrays:
+ * - **Paged sparse array**: Maps entity IDs to dense array indices
+ * Divided into fixed-size pages (4096 entities each) allocated
+ * on-demand to avoid unbounded memory growth for sparse entity IDs.
* - **Dense array**: Stores entities and components contiguously
*
* This provides:
* - O(1) insertion, deletion, and lookup
* - Cache-friendly iteration over components
* - Stable component pointers during iteration
+ * - Bounded memory usage even with sparse entity IDs
*
* The "swap and pop" deletion strategy maintains density
* without gaps, at the cost of unstable ordering.
*
+ * **Memory efficiency**: With paging, entity ID 1,000,000 only
+ * allocates 244 pages (~16KB) instead of 4MB.
+ *
* @code
* SparseSet<Position> positions;
*
@@ -125,6 +132,12 @@ public:
/** @brief Iterator type for entity iteration */
using Iterator = typename std::vector<Entity>::const_iterator;
+ /** @brief Page size for paged sparse array (entities per page) */
+ static constexpr usize SPARSE_PAGE_SIZE = 4096;
+
+ /** @brief Page type: array of entity indices */
+ using Page = std::array<Entity, SPARSE_PAGE_SIZE>;
+
/** @brief Default constructor */
SparseSet() = default;
@@ -147,11 +160,18 @@ public:
* @return True if the entity has a component
*
* @details O(1) complexity. Validates the sparse-dense mapping.
+ * Uses paged lookup to avoid unbounded memory growth.
*/
bool contains(Entity entity) const override {
- return entity < sparse_.size() &&
- sparse_[entity] < dense_.size() &&
- dense_[sparse_[entity]] == entity;
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+
+ if (pageIndex >= pages_.size() || !pages_[pageIndex]) {
+ return false;
+ }
+
+ const Entity denseIndex = (*pages_[pageIndex])[offset];
+ return denseIndex < dense_.size() && dense_[denseIndex] == entity;
}
/**
@@ -163,13 +183,17 @@ public:
*/
T& get(Entity entity) {
ES_ASSERT(contains(entity), "Entity does not have component");
- return components_[sparse_[entity]];
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+ return components_[(*pages_[pageIndex])[offset]];
}
/** @copydoc get() */
const T& get(Entity entity) const {
ES_ASSERT(contains(entity), "Entity does not have component");
- return components_[sparse_[entity]];
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+ return components_[(*pages_[pageIndex])[offset]];
}
/**
@@ -179,13 +203,17 @@ public:
*/
T* tryGet(Entity entity) {
if (!contains(entity)) return nullptr;
- return &components_[sparse_[entity]];
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+ return &components_[(*pages_[pageIndex])[offset]];
}
/** @copydoc tryGet() */
const T* tryGet(Entity entity) const {
if (!contains(entity)) return nullptr;
- return &components_[sparse_[entity]];
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+ return &components_[(*pages_[pageIndex])[offset]];
}
// =========================================================================
@@ -201,19 +229,27 @@ public:
*
* @note Asserts if the entity already has a component
*
- * @details O(1) amortized complexity. May resize the sparse array.
+ * @details O(1) amortized complexity. Allocates pages on-demand.
+ * Memory usage is bounded: O(num_pages * SPARSE_PAGE_SIZE) where
+ * num_pages = ceil(max_entity_id / SPARSE_PAGE_SIZE).
*/
template<typename... Args>
T& emplace(Entity entity, Args&&... args) {
ES_ASSERT(!contains(entity), "Entity already has component");
- // Ensure sparse array is large enough
- if (entity >= sparse_.size()) {
- sparse_.resize(entity + 1, INVALID_ENTITY);
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+
+ if (pageIndex >= pages_.size()) {
+ pages_.resize(pageIndex + 1);
}
- // Add to dense arrays
- sparse_[entity] = static_cast<Entity>(dense_.size());
+ if (!pages_[pageIndex]) {
+ pages_[pageIndex] = std::make_unique<Page>();
+ std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_ENTITY);
+ }
+
+ (*pages_[pageIndex])[offset] = static_cast<Entity>(dense_.size());
dense_.push_back(entity);
components_.emplace_back(std::forward<Args>(args)...);
@@ -231,19 +267,21 @@ public:
void remove(Entity entity) override {
if (!contains(entity)) return;
- // Swap and pop
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
const auto last = dense_.back();
- const auto index = sparse_[entity];
+ const auto index = (*pages_[pageIndex])[offset];
- // Move last element to removed position
dense_[index] = last;
components_[index] = std::move(components_.back());
- sparse_[last] = index;
- // Pop last element
+ const auto lastPageIndex = last / SPARSE_PAGE_SIZE;
+ const auto lastOffset = last % SPARSE_PAGE_SIZE;
+ (*pages_[lastPageIndex])[lastOffset] = index;
+
dense_.pop_back();
components_.pop_back();
- sparse_[entity] = INVALID_ENTITY;
+ (*pages_[pageIndex])[offset] = INVALID_ENTITY;
}
// =========================================================================
@@ -266,7 +304,7 @@ public:
* @brief Removes all components
*/
void clear() override {
- sparse_.clear();
+ pages_.clear();
dense_.clear();
components_.clear();
}
@@ -324,7 +362,9 @@ public:
*/
usize indexOf(Entity entity) const {
ES_ASSERT(contains(entity), "Entity not in set");
- return sparse_[entity];
+ const auto pageIndex = entity / SPARSE_PAGE_SIZE;
+ const auto offset = entity % SPARSE_PAGE_SIZE;
+ return (*pages_[pageIndex])[offset];
}
private:
@@ -333,11 +373,12 @@ private:
// =========================================================================
/**
- * @brief Sparse array: maps Entity ID -> index in dense array
- * @details Indexed directly by entity ID. Contains INVALID_ENTITY
- * for entities not in the set.
+ * @brief Paged sparse array: maps Entity ID -> index in dense array
+ * @details Pages are allocated on-demand. Each page holds SPARSE_PAGE_SIZE
+ * entity mappings. pageIndex = entity / SPARSE_PAGE_SIZE,
+ * offset = entity % SPARSE_PAGE_SIZE.
*/
- std::vector<Entity> sparse_;
+ std::vector<std::unique_ptr<Page>> pages_;
/**
* @brief Dense array: stores entities contiguously
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index c81afc701..c14173f27 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -32,8 +32,55 @@
namespace esengine {
+f32 Plane::signedDistance(const glm::vec3& point) const {
+ return glm::dot(normal, point) + distance;
+}
+
+void Frustum::extractFromMatrix(const glm::mat4& vp) {
+ const f32* m = glm::value_ptr(vp);
+
+ planes[0].normal = glm::vec3(m[3] + m[0], m[7] + m[4], m[11] + m[8]);
+ planes[0].distance = m[15] + m[12];
+
+ planes[1].normal = glm::vec3(m[3] - m[0], m[7] - m[4], m[11] - m[8]);
+ planes[1].distance = m[15] - m[12];
+
+ planes[2].normal = glm::vec3(m[3] + m[1], m[7] + m[5], m[11] + m[9]);
+ planes[2].distance = m[15] + m[13];
+
+ planes[3].normal = glm::vec3(m[3] - m[1], m[7] - m[5], m[11] - m[9]);
+ planes[3].distance = m[15] - m[13];
+
+ planes[4].normal = glm::vec3(m[3] + m[2], m[7] + m[6], m[11] + m[10]);
+ planes[4].distance = m[15] + m[14];
+
+ planes[5].normal = glm::vec3(m[3] - m[2], m[7] - m[6], m[11] - m[10]);
+ planes[5].distance = m[15] - m[14];
+
+ for (u32 i = 0; i < 6; ++i) {
+ f32 len = glm::length(planes[i].normal);
+ planes[i].normal /= len;
+ planes[i].distance /= len;
+ }
+}
+
+bool Frustum::intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const {
+ for (u32 i = 0; i < 6; ++i) {
+ f32 r = halfExtents.x * std::abs(planes[i].normal.x) +
+ halfExtents.y * std::abs(planes[i].normal.y) +
+ halfExtents.z * std::abs(planes[i].normal.z);
+
+ f32 dist = planes[i].signedDistance(center);
+
+ if (dist < -r) {
+ return false;
+ }
+ }
+ return true;
+}
+
struct UniformData {
- std::string name;
+ char name[32];
u32 type;
f32 values[4];
};
@@ -215,6 +262,7 @@ void RenderFrame::resize(u32 width, u32 height) {
void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::Handle target) {
view_projection_ = view_projection;
+ frustum_.extractFromMatrix(view_projection);
current_target_ = target;
current_stage_ = RenderStage::Transparent;
in_frame_ = true;
@@ -311,6 +359,12 @@ void RenderFrame::submitSprites(ecs::Registry& registry) {
scale = local.scale;
}
+ glm::vec3 halfExtents = glm::vec3(sprite.size.x * scale.x, sprite.size.y * scale.y, 0.0f) * 0.5f;
+ if (!frustum_.intersectsAABB(position, halfExtents)) {
+ stats_.culled++;
+ continue;
+ }
+
RenderItem item;
item.entity = entity;
item.type = RenderType::Sprite;
@@ -408,6 +462,17 @@ void RenderFrame::submitBitmapText(ecs::Registry& registry) {
scale = local.scale;
}
+ auto textMetrics = font->measureText(bt.text, bt.fontSize, bt.spacing);
+ glm::vec3 halfExtents = glm::vec3(
+ textMetrics.width * scale.x * 0.5f,
+ textMetrics.height * scale.y * 0.5f,
+ 0.0f
+ );
+ if (!frustum_.intersectsAABB(position, halfExtents)) {
+ stats_.culled++;
+ continue;
+ }
+
RenderItem item;
item.entity = entity;
item.type = RenderType::Text;
diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hpp
index d88e2ca4f..8802ce7fd 100644
--- a/src/esengine/renderer/RenderFrame.hpp
+++ b/src/esengine/renderer/RenderFrame.hpp
@@ -15,6 +15,18 @@
namespace esengine {
+struct Plane {
+ glm::vec3 normal;
+ f32 distance;
+ f32 signedDistance(const glm::vec3& point) const;
+};
+
+struct Frustum {
+ Plane planes[6];
+ void extractFromMatrix(const glm::mat4& vp);
+ bool intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const;
+};
+
class BatchRenderer2D;
#ifdef ES_ENABLE_SPINE
@@ -99,6 +111,7 @@ private:
std::vector<RenderItem> items_;
glm::mat4 view_projection_{1.0f};
+ Frustum frustum_;
RenderTargetManager::Handle current_target_ = 0;
RenderStage current_stage_ = RenderStage::Transparent;
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index fe043f137..0f8901100 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -33,6 +33,7 @@ void ResourceManager::init() {
#ifndef ES_PLATFORM_WEB
stbi_set_flip_vertically_on_load(true);
+ hotReloadManager_.init(true);
#endif
stats_ = {};
@@ -47,6 +48,11 @@ void ResourceManager::shutdown() {
ES_LOG_INFO("ResourceManager shutting down (shaders: {}, textures: {}, vbos: {}, ibos: {}, fonts: {})",
shaders_.size(), textures_.size(), vertexBuffers_.size(), indexBuffers_.size(), fonts_.size());
+#ifndef ES_PLATFORM_WEB
+ hotReloadManager_.shutdown();
+ shaderPaths_.clear();
+#endif
+
guidToTexture_.clear();
textureMetadata_.clear();
fonts_.clear();
@@ -59,6 +65,14 @@ void ResourceManager::shutdown() {
ES_LOG_INFO("ResourceManager shutdown complete");
}
+void ResourceManager::update() {
+#ifndef ES_PLATFORM_WEB
+ if (initialized_) {
+ hotReloadManager_.update();
+ }
+#endif
+}
+
// =============================================================================
// Shader Resources
// =============================================================================
@@ -112,7 +126,18 @@ ShaderHandle ResourceManager::loadShaderFile(const std::string& path, const std:
}
stats_.cacheMisses++;
- return shaders_.add(std::move(result.resource), path);
+ auto handle = shaders_.add(std::move(result.resource), path);
+
+#ifndef ES_PLATFORM_WEB
+ if (handle.isValid()) {
+ shaderPaths_[handle.id()] = path;
+ hotReloadManager_.watch<Shader>(handle, path, [this, handle](const std::string& p) {
+ reloadShader(handle, p);
+ });
+ }
+#endif
+
+ return handle;
}
ShaderHandle ResourceManager::loadEngineShader(const std::string& name, const std::string& platform) {
@@ -153,6 +178,10 @@ void ResourceManager::releaseShader(ShaderHandle handle) {
}
}
+u32 ResourceManager::getShaderRefCount(ShaderHandle handle) const {
+ return shaders_.getRefCount(handle);
+}
+
// =============================================================================
// Texture Resources
// =============================================================================
@@ -235,6 +264,10 @@ void ResourceManager::releaseTexture(TextureHandle handle) {
}
}
+u32 ResourceManager::getTextureRefCount(TextureHandle handle) const {
+ return textures_.getRefCount(handle);
+}
+
TextureHandle ResourceManager::registerExternalTexture(u32 glTextureId, u32 width, u32 height) {
auto texture = Texture::createFromExternalId(glTextureId, width, height, TextureFormat::RGBA8);
if (!texture) {
@@ -455,6 +488,10 @@ void ResourceManager::releaseBitmapFont(BitmapFontHandle handle) {
}
}
+u32 ResourceManager::getBitmapFontRefCount(BitmapFontHandle handle) const {
+ return fonts_.getRefCount(handle);
+}
+
// =============================================================================
// Statistics
// =============================================================================
@@ -472,4 +509,50 @@ void ResourceManager::resetCacheStats() {
stats_.cacheMisses = 0;
}
+#ifndef ES_PLATFORM_WEB
+void ResourceManager::reloadShader(ShaderHandle handle, const std::string& path) {
+ if (!handle.isValid()) {
+ return;
+ }
+
+ auto it = shaderPaths_.find(handle.id());
+ if (it == shaderPaths_.end()) {
+ ES_LOG_ERROR("HotReload: Shader path not found for handle {}", handle.id());
+ return;
+ }
+
+ ES_LOG_INFO("HotReload: Reloading shader '{}'", path);
+
+ ShaderLoader loader;
+ auto result = loader.loadFromFile(path, "");
+
+ ReloadEvent<Shader> event;
+ event.handle = handle;
+ event.path = path;
+
+ if (!result.isOk()) {
+ ES_LOG_ERROR("HotReload: Failed to reload shader '{}': {}", path, result.error.message);
+ event.success = false;
+ event.errorMessage = result.error.message;
+ hotReloadManager_.onShaderReloaded.publish(event);
+ return;
+ }
+
+ Shader* oldShader = shaders_.get(handle);
+ if (!oldShader) {
+ ES_LOG_ERROR("HotReload: Shader handle {} is no longer valid", handle.id());
+ event.success = false;
+ event.errorMessage = "Shader handle no longer valid";
+ hotReloadManager_.onShaderReloaded.publish(event);
+ return;
+ }
+
+ *oldShader = std::move(*result.resource);
+
+ ES_LOG_INFO("HotReload: Successfully reloaded shader '{}'", path);
+ event.success = true;
+ hotReloadManager_.onShaderReloaded.publish(event);
+}
+#endif
+
} // namespace esengine::resource
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index dbd118b53..93b93ab0f 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -22,6 +22,9 @@
#include "ResourcePool.hpp"
#include "LoaderRegistry.hpp"
#include "TextureMetadata.hpp"
+#ifndef ES_PLATFORM_WEB
+#include "HotReloadManager.hpp"
+#endif
#include "../renderer/Shader.hpp"
#include "../renderer/Texture.hpp"
#include "../renderer/Buffer.hpp"
@@ -107,6 +110,25 @@ public:
*/
bool isInitialized() const { return initialized_; }
+ /**
+ * @brief Updates resource manager (processes hot reload, call once per frame)
+ */
+ void update();
+
+#ifndef ES_PLATFORM_WEB
+ /**
+ * @brief Gets the hot reload manager
+ * @return Reference to the hot reload manager
+ */
+ HotReloadManager& getHotReloadManager() { return hotReloadManager_; }
+
+ /**
+ * @brief Gets the hot reload manager (const)
+ * @return Const reference to the hot reload manager
+ */
+ const HotReloadManager& getHotReloadManager() const { return hotReloadManager_; }
+#endif
+
// =========================================================================
// Shader Resources
// =========================================================================
@@ -165,6 +187,13 @@ public:
*/
void releaseShader(ShaderHandle handle);
+ /**
+ * @brief Gets the current reference count for a shader
+ * @param handle The shader handle
+ * @return Reference count, or 0 if invalid
+ */
+ u32 getShaderRefCount(ShaderHandle handle) const;
+
// =========================================================================
// Texture Resources
// =========================================================================
@@ -214,6 +243,13 @@ public:
*/
void releaseTexture(TextureHandle handle);
+ /**
+ * @brief Gets the current reference count for a texture
+ * @param handle The texture handle
+ * @return Reference count, or 0 if invalid
+ */
+ u32 getTextureRefCount(TextureHandle handle) const;
+
/**
* @brief Registers an externally-created GL texture
* @param glTextureId The OpenGL texture ID
@@ -386,6 +422,13 @@ public:
const text::BitmapFont* getBitmapFont(BitmapFontHandle handle) const;
void releaseBitmapFont(BitmapFontHandle handle);
+ /**
+ * @brief Gets the current reference count for a bitmap font
+ * @param handle The font handle
+ * @return Reference count, or 0 if invalid
+ */
+ u32 getBitmapFontRefCount(BitmapFontHandle handle) const;
+
// =========================================================================
// Statistics
// =========================================================================
@@ -436,6 +479,10 @@ public:
LoaderRegistry& getLoaderRegistry() { return loaderRegistry_; }
private:
+#ifndef ES_PLATFORM_WEB
+ void reloadShader(ShaderHandle handle, const std::string& path);
+#endif
+
ResourcePool<Shader> shaders_;
ResourcePool<Texture> textures_;
ResourcePool<VertexBuffer> vertexBuffers_;
@@ -443,6 +490,10 @@ private:
ResourcePool<text::BitmapFont> fonts_;
std::unordered_map<std::string, TextureHandle> guidToTexture_;
std::unordered_map<TextureHandle::IdType, TextureMetadata> textureMetadata_;
+#ifndef ES_PLATFORM_WEB
+ std::unordered_map<ShaderHandle::IdType, std::string> shaderPaths_;
+ HotReloadManager hotReloadManager_;
+#endif
LoaderRegistry loaderRegistry_;
mutable ResourceStats stats_;
bool initialized_ = false;