A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
chore: sync SDK and WASM dist files
esengine35fa85c696e8
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex f3c1eb27b..192c3890f 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,4390 +1,2 @@-'use strict';--/**- * @file base.ts- * @brief Base platform adapter - no platform-specific code- */-// =============================================================================-// Platform Instance (set by entry point)-// =============================================================================-let currentPlatform = null;-/**- * Set the platform adapter (called by entry point)- */-function setPlatform(adapter) {- currentPlatform = adapter;- console.log(`[ESEngine] Platform: ${adapter.name}`);-}-/**- * Get the current platform adapter- * @throws Error if platform not initialized- */-function getPlatform() {- if (!currentPlatform) {- throw new Error('[ESEngine] Platform not initialized. ' +- 'Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');- }- return currentPlatform;-}-/**- * Check if platform is initialized- */-function isPlatformInitialized() {- return currentPlatform !== null;-}-/**- * Get platform type- */-function getPlatformType() {- return currentPlatform?.name ?? null;-}-/**- * Check if running on WeChat- */-function isWeChat() {- return currentPlatform?.name === 'wechat';-}-/**- * Check if running on Web- */-function isWeb() {- return currentPlatform?.name === 'web';-}-// =============================================================================-// Convenience Functions-// =============================================================================-async function platformFetch(url, options) {- return getPlatform().fetch(url, options);-}-async function platformReadFile(path) {- return getPlatform().readFile(path);-}-async function platformReadTextFile(path) {- return getPlatform().readTextFile(path);-}-async function platformFileExists(path) {- return getPlatform().fileExists(path);-}-async function platformInstantiateWasm(pathOrBuffer, imports) {- return getPlatform().instantiateWasm(pathOrBuffer, imports);-}--/**- * @file fetch.ts- * @brief Fetch polyfill for WeChat MiniGame using wx.request- */-// =============================================================================-// WeChat Fetch Implementation-// =============================================================================-function wxFetch(url, options) {- return new Promise((resolve, reject) => {- const responseType = options?.responseType ?? 'text';- wx.request({- url,- method: (options?.method ?? 'GET'),- data: options?.body,- header: options?.headers,- responseType: responseType === 'arraybuffer' ? 'arraybuffer' : 'text',- timeout: options?.timeout,- success: (res) => {- const ok = res.statusCode >= 200 && res.statusCode < 300;- const headers = {};- if (res.header) {- for (const key of Object.keys(res.header)) {- headers[key.toLowerCase()] = res.header[key];- }- }- resolve({- ok,- status: res.statusCode,- statusText: ok ? 'OK' : 'Error',- headers,- json: () => {- if (typeof res.data === 'string') {- return Promise.resolve(JSON.parse(res.data));- }- return Promise.resolve(res.data);- },- text: () => {- if (typeof res.data === 'string') {- return Promise.resolve(res.data);- }- return Promise.resolve(JSON.stringify(res.data));- },- arrayBuffer: () => {- if (res.data instanceof ArrayBuffer) {- return Promise.resolve(res.data);- }- // Convert string to ArrayBuffer- const encoder = new TextEncoder();- const data = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);- return Promise.resolve(encoder.encode(data).buffer);- },- });- },- fail: (err) => {- reject(new Error(`wx.request failed: ${err.errMsg}`));- },- });- });-}-// =============================================================================-// Global Fetch Polyfill-// =============================================================================-function polyfillFetch() {- if (typeof globalThis.fetch === 'undefined') {- globalThis.fetch = async (input, init) => {- const url = typeof input === 'string' ? input : input.toString();- const options = {- method: init?.method ?? 'GET',- headers: init?.headers,- body: init?.body,- };- const response = await wxFetch(url, options);- // Return a Response-like object- return {- ok: response.ok,- status: response.status,- statusText: response.statusText,- headers: new Headers(response.headers),- json: () => response.json(),- text: () => response.text(),- arrayBuffer: () => response.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: false,- redirected: false,- type: 'basic',- url,- };- };- }-}--/**- * @file wasm.ts- * @brief WebAssembly adapter for WeChat MiniGame using WXWebAssembly- */-// =============================================================================-// WeChat WASM Implementation-// =============================================================================-/**- * Instantiate WASM using WXWebAssembly- * Note: WeChat requires path to be a string (package-relative path), not ArrayBuffer- */-async function wxInstantiateWasm(path, imports) {- if (typeof WXWebAssembly === 'undefined') {- throw new Error('WXWebAssembly is not available. Requires WeChat base library >= 2.13.0');- }- // WeChat requires the path to be a package-relative path string- // e.g., "esengine.wasm" not "/esengine.wasm" or ArrayBuffer- const normalizedPath = path.startsWith('/') ? path.slice(1) : path;- try {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const result = await WXWebAssembly.instantiate(normalizedPath, imports);- return {- // WXWebAssembly.instantiate returns { instance, module } but types are slightly different- instance: result.instance ?? result,- module: result.module,- };- }- catch (err) {- const message = err instanceof Error ? err.message : String(err);- throw new Error(`WXWebAssembly.instantiate failed for "${normalizedPath}": ${message}`);- }-}-// =============================================================================-// Global WebAssembly Polyfill-// =============================================================================-/**- * Polyfill global WebAssembly with WXWebAssembly- * This allows existing code using WebAssembly.instantiate to work on WeChat- */-function polyfillWebAssembly() {- if (typeof WXWebAssembly !== 'undefined' && typeof WebAssembly === 'undefined') {- globalThis.WebAssembly = {- instantiate: async (bufferOrPath, imports) => {- if (typeof bufferOrPath !== 'string') {- throw new Error('WeChat WXWebAssembly requires a file path string, not ArrayBuffer. ' +- 'Use platform adapter instead of direct WebAssembly.instantiate.');- }- return wxInstantiateWasm(bufferOrPath, imports ?? {});- },- 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,- };- }-}--/**- * @file fs.ts- * @brief File system adapter for WeChat MiniGame- */-/// <reference types="minigame-api-typings" />-// =============================================================================-// WeChat File System-// =============================================================================-let fsManager = null;-function getFileSystemManager() {- if (!fsManager) {- fsManager = wx.getFileSystemManager();- }- return fsManager;-}-/**- * Read file as ArrayBuffer (async)- */-function wxReadFile(path) {- return new Promise((resolve, reject) => {- const fs = getFileSystemManager();- fs.readFile({- filePath: path,- success: (res) => {- resolve(res.data);- },- fail: (err) => {- reject(new Error(`Failed to read file "${path}": ${err.errMsg}`));- },- });- });-}-/**- * Read file as string (async)- */-function wxReadTextFile(path, encoding = 'utf-8') {- return new Promise((resolve, reject) => {- const fs = getFileSystemManager();- fs.readFile({- filePath: path,- encoding,- success: (res) => {- resolve(res.data);- },- fail: (err) => {- reject(new Error(`Failed to read file "${path}": ${err.errMsg}`));- },- });- });-}-/**- * Check if file exists- */-function wxFileExists(path) {- return new Promise((resolve) => {- const fs = getFileSystemManager();- fs.access({- path,- success: () => resolve(true),- fail: () => resolve(false),- });- });-}-/**- * Check if file exists (sync)- */-function wxFileExistsSync(path) {- const fs = getFileSystemManager();- try {- fs.accessSync(path);- return true;- }- catch {- return false;- }-}-/**- * Write file- */-function wxWriteFile(path, data) {- return new Promise((resolve, reject) => {- const fs = getFileSystemManager();- fs.writeFile({- filePath: path,- data,- success: () => resolve(),- fail: (err) => {- reject(new Error(`Failed to write file "${path}": ${err.errMsg}`));- },- });- });-}--/**- * @file image.ts- * @brief WeChat MiniGame image loading utilities- */-/// <reference types="minigame-api-typings" />-// =============================================================================-// Canvas Management-// =============================================================================-let offscreenCanvas = null;-let offscreenCtx = null;-function getOffscreenCanvas(width, height) {- if (!offscreenCanvas) {- offscreenCanvas = wx.createCanvas();- offscreenCanvas.width = width;- offscreenCanvas.height = height;- offscreenCtx = offscreenCanvas.getContext('2d');- }- if (offscreenCanvas.width < width || offscreenCanvas.height < height) {- offscreenCanvas.width = Math.max(offscreenCanvas.width, width);- offscreenCanvas.height = Math.max(offscreenCanvas.height, height);- }- return { canvas: offscreenCanvas, ctx: offscreenCtx };-}-// =============================================================================-// Image Loading-// =============================================================================-/**- * Load an image from a file path- * @param path - File path relative to game root- */-function wxLoadImage(path) {- return new Promise((resolve, reject) => {- const img = wx.createImage();- img.onload = () => resolve(img);- img.onerror = (err) => reject(new Error(`Failed to load image: ${path}, ${err}`));- img.src = path;- });-}-/**- * Extract pixel data from an image- * @param img - Loaded image object- * @param flipY - Whether to flip the image vertically (default: true for OpenGL)- */-function wxGetImagePixels(img, flipY = true) {- const { width, height } = img;- const { ctx } = getOffscreenCanvas(width, height);- ctx.clearRect(0, 0, width, height);- ctx.save();- if (flipY) {- ctx.translate(0, height);- ctx.scale(1, -1);- }- ctx.drawImage(img, 0, 0);- ctx.restore();- const imageData = ctx.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- return { width, height, pixels };-}-/**- * Load image and get pixel data in one call- * @param path - File path relative to game root- * @param flipY - Whether to flip the image vertically (default: true for OpenGL)- */-async function wxLoadImagePixels(path, flipY = true) {- const img = await wxLoadImage(path);- return wxGetImagePixels(img, flipY);-}--/**- * @file index.ts- * @brief WeChat MiniGame platform adapter- */-// =============================================================================-// WeChat Platform Adapter-// =============================================================================-class WeChatPlatformAdapter {- constructor() {- this.name = 'wechat';- }- async fetch(url, options) {- return wxFetch(url, options);- }- async readFile(path) {- return wxReadFile(path);- }- async readTextFile(path) {- return wxReadTextFile(path);- }- async fileExists(path) {- return wxFileExists(path);- }- async instantiateWasm(pathOrBuffer, imports) {- if (typeof pathOrBuffer !== 'string') {- throw new Error('WeChat WXWebAssembly requires a file path string, not ArrayBuffer');- }- return wxInstantiateWasm(pathOrBuffer, imports);- }-}-// =============================================================================-// Initialization-// =============================================================================-let initialized = false;-/**- * Initialize WeChat platform polyfills- * Call this at the entry point of your game- */-function initWeChatPlatform() {- if (initialized)- return;- initialized = true;- polyfillFetch();- polyfillWebAssembly();- console.log('[ESEngine] WeChat platform initialized');-}-// =============================================================================-// Export-// =============================================================================-const wechatAdapter = new WeChatPlatformAdapter();--/**- * @file types.ts- * @brief Core type definitions for ESEngine SDK- */-const INVALID_ENTITY = 0;-const INVALID_TEXTURE = 0xFFFFFFFF;-// =============================================================================-// Factory Functions-// =============================================================================-const vec2 = (x = 0, y = 0) => ({ x, y });-const vec3 = (x = 0, y = 0, z = 0) => ({ x, y, z });-const vec4 = (x = 0, y = 0, z = 0, w = 1) => ({ x, y, z, w });-const color = (r = 1, g = 1, b = 1, a = 1) => ({ x: r, y: g, z: b, w: a });-const quat = (w = 1, x = 0, y = 0, z = 0) => ({ w, x, y, z });--/**- * @file component.ts- * @brief Component definition and builtin components- */-let componentCounter = 0;-function createComponentDef(name, defaults) {- const id = ++componentCounter;- return {- _id: Symbol(`Component_${id}_${name}`),- _name: name,- _default: defaults,- _builtin: false,- create(data) {- return { ...defaults, ...data };- }- };-}-function getComponentRegistry() {- if (typeof window === 'undefined')- return new Map();- return (window.__esengine_componentRegistry ?? (window.__esengine_componentRegistry = new Map()));-}-function defineComponent(name, defaults) {- const registry = getComponentRegistry();- const existing = registry.get(name);- if (existing)- return existing;- const def = createComponentDef(name, defaults);- registry.set(name, def);- registerToEditor(name, defaults, false);- return def;-}-function defineTag(name) {- const registry = getComponentRegistry();- const existing = registry.get(name);- if (existing)- return existing;- const def = createComponentDef(name, {});- registry.set(name, def);- registerToEditor(name, {}, true);- return def;-}-function getUserComponent(name) {- return getComponentRegistry().get(name);-}-function clearUserComponents() {- getComponentRegistry().clear();-}-function registerToEditor(name, defaults, isTag) {- if (typeof window !== 'undefined' && window.__esengine_registerComponent) {- window.__esengine_registerComponent(name, defaults, isTag);- }-}-function defineBuiltin(name, defaults) {- return {- _id: Symbol(`Builtin_${name}`),- _name: name,- _cppName: name,- _builtin: true,- _default: defaults- };-}-function isBuiltinComponent(comp) {- return comp._builtin === true;-}-// =============================================================================-// Builtin Component Instances-// =============================================================================-const LocalTransform = defineBuiltin('LocalTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const WorldTransform = defineBuiltin('WorldTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const Sprite = defineBuiltin('Sprite', {- texture: INVALID_TEXTURE,- color: { x: 1, y: 1, z: 1, w: 1 },- size: { x: 32, y: 32 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0-});-const Camera = defineBuiltin('Camera', {- projectionType: 0,- fov: 60,- orthoSize: 5,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- isActive: true,- priority: 0-});-const Canvas = defineBuiltin('Canvas', {- designResolution: { x: 1920, y: 1080 },- pixelsPerUnit: 100,- scaleMode: 0,- matchWidthOrHeight: 0.5,- backgroundColor: { x: 0, y: 0, z: 0, w: 1 }-});-const Velocity = defineBuiltin('Velocity', {- linear: { x: 0, y: 0, z: 0 },- angular: { x: 0, y: 0, z: 0 }-});-const Parent = defineBuiltin('Parent', {- entity: 0-});-const Children = defineBuiltin('Children', {- entities: []-});-const SpineAnimation = defineBuiltin('SpineAnimation', {- skeletonPath: '',- atlasPath: '',- skin: '',- animation: '',- timeScale: 1.0,- loop: true,- playing: true,- flipX: false,- flipY: false,- color: { x: 1, y: 1, z: 1, w: 1 },- layer: 0,- skeletonScale: 1.0,- material: 0-});-// =============================================================================-// Component Defaults Registry-// =============================================================================-const builtinComponents = {- LocalTransform,- WorldTransform,- Sprite,- Camera,- Canvas,- Velocity,- Parent,- Children,- SpineAnimation,-};-function getComponentDefaults(typeName) {- const builtin = builtinComponents[typeName];- if (builtin)- return { ...builtin._default };- const userComp = getUserComponent(typeName);- if (userComp)- return { ...userComp._default };- return null;-}--/**- * @file resource.ts- * @brief Resource system for global singleton data- */-let resourceCounter = 0;-function defineResource(defaultValue, name) {- const id = ++resourceCounter;- return {- _id: Symbol(`Resource_${id}_${name ?? ''}`),- _name: name ?? `Resource_${id}`,- _default: defaultValue- };-}-function Res(resource) {- return { _type: 'res', _resource: resource };-}-function ResMut(resource) {- return { _type: 'res_mut', _resource: resource };-}-// =============================================================================-// Resource Instances (Runtime)-// =============================================================================-class ResMutInstance {- constructor(value, setter) {- this.value_ = value;- this.setter_ = setter;- }- get() {- return this.value_;- }- set(value) {- this.value_ = value;- this.setter_(value);- }- modify(fn) {- fn(this.value_);- this.setter_(this.value_);- }-}-// =============================================================================-// Resource Storage-// =============================================================================-class ResourceStorage {- constructor() {- this.resources_ = new Map();- }- insert(resource, value) {- this.resources_.set(resource._id, value);- }- get(resource) {- if (!this.resources_.has(resource._id)) {- this.resources_.set(resource._id, resource._default);- }- return this.resources_.get(resource._id);- }- set(resource, value) {- this.resources_.set(resource._id, value);- }- has(resource) {- return this.resources_.has(resource._id);- }- remove(resource) {- this.resources_.delete(resource._id);- }- getResMut(resource) {- return new ResMutInstance(this.get(resource), (v) => this.set(resource, v));- }-}-const Time = defineResource({- delta: 0,- elapsed: 0,- frameCount: 0-}, 'Time');-const Input = defineResource({- keysDown: new Set(),- keysPressed: new Set(),- keysReleased: new Set(),- mouseX: 0,- mouseY: 0,- mouseButtons: new Set()-}, 'Input');--/**- * @file query.ts- * @brief Component query system with mutable component support- */-function Mut(component) {- return { _type: 'mut', _component: component };-}-function isMutWrapper(value) {- return typeof value === 'object' && value !== null && value._type === 'mut';-}-function createQueryDescriptor(components, withFilters = [], withoutFilters = []) {- const mutIndices = [];- components.forEach((comp, i) => {- if (isMutWrapper(comp)) {- mutIndices.push(i);- }- });- return {- _type: 'query',- _components: components,- _mutIndices: mutIndices,- _with: withFilters,- _without: withoutFilters- };-}-// =============================================================================-// Query Factory-// =============================================================================-function Query(...components) {- return createQueryDescriptor(components);-}-class QueryInstance {- constructor(world, descriptor) {- this.pendingMutations_ = [];- this.world_ = world;- this.descriptor_ = descriptor;- }- getActualComponent(arg) {- return isMutWrapper(arg) ? arg._component : arg;- }- commitPending() {- for (const mutation of this.pendingMutations_) {- this.world_.insert(mutation.entity, mutation.component, mutation.data);- }- this.pendingMutations_ = [];- }- *[Symbol.iterator]() {- const { _components, _mutIndices, _with, _without } = this.descriptor_;- const actualComponents = _components.map(c => this.getActualComponent(c));- const allRequired = [...actualComponents, ..._with];- const entities = this.world_.getEntitiesWithComponents(allRequired);- let prevEntity = null;- let prevMutData = [];- try {- for (const entity of entities) {- // Commit previous entity's mutations before moving to next- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- prevMutData = [];- let excluded = false;- for (const comp of _without) {- if (this.world_.has(entity, comp)) {- excluded = true;- break;- }- }- if (excluded)- continue;- const components = actualComponents.map(comp => this.world_.get(entity, comp));- // Track mutable components for write-back- for (const idx of _mutIndices) {- prevMutData.push({- component: actualComponents[idx],- data: components[idx]- });- }- prevEntity = entity;- yield [entity, ...components];- }- }- finally {- // Commit last entity's mutations- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- }- }- forEach(callback) {- for (const [entity, ...components] of this) {- callback(entity, ...components);- }- }- single() {- for (const result of this) {- return result;- }- return null;- }- isEmpty() {- return this.single() === null;- }- count() {- let n = 0;- for (const _ of this) {- n++;- }- return n;- }- toArray() {- return [...this];- }-}--/**- * @file commands.ts- * @brief Deferred entity/component operations- */-function Commands() {- return { _type: 'commands' };-}-// =============================================================================-// Entity Commands (Builder for spawning)-// =============================================================================-class EntityCommands {- constructor(commands, entity) {- this.components_ = [];- this.commands_ = commands;- if (entity === null) {- this.entityRef_ = { entity: 0 };- this.isNew_ = true;- }- else {- this.entityRef_ = { entity };- this.isNew_ = false;- }- }- insert(component, data) {- let instance;- if (isBuiltinComponent(component)) {- instance = { ...component._default, ...data };- }- else {- instance = component.create(data);- }- if (this.isNew_) {- this.components_.push({ component, data: instance });- }- else {- this.commands_.queueInsert(this.entityRef_.entity, component, instance);- }- return this;- }- remove(component) {- if (!this.isNew_) {- this.commands_.queueRemove(this.entityRef_.entity, component);- }- return this;- }- id() {- if (this.isNew_ && this.entityRef_.entity === 0) {- this.finalize();- }- return this.entityRef_.entity;- }- finalize() {- if (this.isNew_) {- this.commands_.spawnImmediate(this.components_, this.entityRef_);- this.isNew_ = false;- }- }-}-// =============================================================================-// Commands Instance (Runtime)-// =============================================================================-class CommandsInstance {- constructor(world, resources) {- this.pending_ = [];- this.world_ = world;- this.resources_ = resources;- }- spawn() {- return new EntityCommands(this, null);- }- entity(entity) {- return new EntityCommands(this, entity);- }- despawn(entity) {- this.pending_.push({ type: 'despawn', entity });- return this;- }- insertResource(resource, value) {- this.pending_.push({- type: 'insert_resource',- resource: resource,- value- });- return this;- }- queueInsert(entity, component, data) {- this.pending_.push({ type: 'insert', entity, component, data });- }- queueRemove(entity, component) {- this.pending_.push({ type: 'remove', entity, component });- }- spawnImmediate(components, entityRef) {- const entity = this.world_.spawn();- entityRef.entity = entity;- for (const entry of components) {- this.world_.insert(entity, entry.component, entry.data);- }- }- flush() {- for (const cmd of this.pending_) {- this.executeCommand(cmd);- }- this.pending_ = [];- }- executeCommand(cmd) {- switch (cmd.type) {- case 'spawn': {- const entity = this.world_.spawn();- cmd.entityRef.entity = entity;- for (const entry of cmd.components) {- this.world_.insert(entity, entry.component, entry.data);- }- break;- }- case 'despawn':- this.world_.despawn(cmd.entity);- break;- case 'insert':- this.world_.insert(cmd.entity, cmd.component, cmd.data);- break;- case 'remove':- this.world_.remove(cmd.entity, cmd.component);- break;- case 'insert_resource':- this.resources_.insert(cmd.resource, cmd.value);- break;- }- }-}--/**- * @file system.ts- * @brief System definition and scheduling- */-// =============================================================================-// Schedule Phases-// =============================================================================-exports.Schedule = void 0;-(function (Schedule) {- Schedule[Schedule["Startup"] = 0] = "Startup";- Schedule[Schedule["First"] = 1] = "First";- Schedule[Schedule["PreUpdate"] = 2] = "PreUpdate";- Schedule[Schedule["Update"] = 3] = "Update";- Schedule[Schedule["PostUpdate"] = 4] = "PostUpdate";- Schedule[Schedule["Last"] = 5] = "Last";- Schedule[Schedule["FixedPreUpdate"] = 10] = "FixedPreUpdate";- Schedule[Schedule["FixedUpdate"] = 11] = "FixedUpdate";- Schedule[Schedule["FixedPostUpdate"] = 12] = "FixedPostUpdate";-})(exports.Schedule || (exports.Schedule = {}));-let systemCounter = 0;-function defineSystem(params, fn, options) {- const id = ++systemCounter;- return {- _id: Symbol(`System_${id}_${options?.name ?? ''}`),- _params: params,- _fn: fn,- _name: options?.name ?? `System_${id}`- };-}-// =============================================================================-// Global System Registration-// =============================================================================-function getPendingSystems() {- if (typeof window === 'undefined')- return [];- return (window.__esengine_pendingSystems ?? (window.__esengine_pendingSystems = []));-}-function addSystem(system) {- getPendingSystems().push({ schedule: exports.Schedule.Update, system });-}-function addStartupSystem(system) {- getPendingSystems().push({ schedule: exports.Schedule.Startup, system });-}-function addSystemToSchedule(schedule, system) {- getPendingSystems().push({ schedule, system });-}-// =============================================================================-// System Runner-// =============================================================================-class SystemRunner {- constructor(world, resources) {- this.world_ = world;- this.resources_ = resources;- }- run(system) {- const args = system._params.map(param => this.resolveParam(param));- system._fn(...args);- for (const arg of args) {- if (arg instanceof CommandsInstance) {- arg.flush();- }- }- }- resolveParam(param) {- switch (param._type) {- case 'query':- return new QueryInstance(this.world_, param);- case 'res':- return this.resources_.get(param._resource);- case 'res_mut':- return this.resources_.getResMut(param._resource);- case 'commands':- return new CommandsInstance(this.world_, this.resources_);- default:- throw new Error('Unknown system parameter type');- }- }-}--/**- * @file world.ts- * @brief ECS World with C++ Registry integration- */-// =============================================================================-// World-// =============================================================================-class World {- constructor() {- this.cppRegistry_ = null;- this.entities_ = new Set();- this.tsStorage_ = new Map();- }- connectCpp(cppRegistry) {- this.cppRegistry_ = cppRegistry;- }- get hasCpp() {- return this.cppRegistry_ !== null;- }- // =========================================================================- // Entity Management- // =========================================================================- spawn() {- let entity;- if (this.cppRegistry_) {- entity = this.cppRegistry_.create();- }- else {- entity = (this.entities_.size + 1);- }- this.entities_.add(entity);- return entity;- }- despawn(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.destroy(entity);- }- this.entities_.delete(entity);- for (const storage of this.tsStorage_.values()) {- storage.delete(entity);- }- }- valid(entity) {- if (this.cppRegistry_) {- return this.cppRegistry_.valid(entity);- }- return this.entities_.has(entity);- }- entityCount() {- return this.entities_.size;- }- getAllEntities() {- return Array.from(this.entities_);- }- setParent(child, parent) {- if (this.cppRegistry_) {- this.cppRegistry_.setParent(child, parent);- }- }- removeParent(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.removeParent(entity);- }- }- // =========================================================================- // Component Management- // =========================================================================- insert(entity, component, data) {- if (isBuiltinComponent(component)) {- return this.insertBuiltin(entity, component, data);- }- return this.insertScript(entity, component, data);- }- get(entity, component) {- if (isBuiltinComponent(component)) {- return this.getBuiltin(entity, component);- }- return this.getScript(entity, component);- }- has(entity, component) {- if (isBuiltinComponent(component)) {- return this.hasBuiltin(entity, component);- }- return this.hasScript(entity, component);- }- remove(entity, component) {- if (isBuiltinComponent(component)) {- this.removeBuiltin(entity, component);- }- else {- this.removeScript(entity, component);- }- }- // =========================================================================- // Builtin Component Operations (C++ Registry)- // =========================================================================- insertBuiltin(entity, component, data) {- const merged = { ...component._default, ...data };- if (this.cppRegistry_) {- const adder = `add${component._cppName}`;- const fn = this.cppRegistry_[adder];- fn.call(this.cppRegistry_, entity, merged);- }- return merged;- }- getBuiltin(entity, component) {- if (!this.cppRegistry_) {- throw new Error('C++ Registry not connected');- }- const getter = `get${component._cppName}`;- const fn = this.cppRegistry_[getter];- return fn.call(this.cppRegistry_, entity);- }- hasBuiltin(entity, component) {- if (!this.cppRegistry_) {- return false;- }- const checker = `has${component._cppName}`;- const fn = this.cppRegistry_[checker];- return fn.call(this.cppRegistry_, entity);- }- removeBuiltin(entity, component) {- if (!this.cppRegistry_) {- return;- }- const remover = `remove${component._cppName}`;- const fn = this.cppRegistry_[remover];- fn.call(this.cppRegistry_, entity);- }- // =========================================================================- // Script Component Operations (TypeScript storage)- // =========================================================================- insertScript(entity, component, data) {- const value = component.create(data);- this.getStorage(component).set(entity, value);- return value;- }- getScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- if (!storage) {- throw new Error(`Component not found: ${component._name}`);- }- return storage.get(entity);- }- hasScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- return storage?.has(entity) ?? false;- }- removeScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- storage?.delete(entity);- }- getStorage(component) {- let storage = this.tsStorage_.get(component._id);- if (!storage) {- storage = new Map();- this.tsStorage_.set(component._id, storage);- }- return storage;- }- // =========================================================================- // Query Support- // =========================================================================- getEntitiesWithComponents(components) {- if (components.length === 0) {- return this.getAllEntities();- }- const entities = [];- for (const entity of this.entities_) {- let hasAll = true;- for (const comp of components) {- if (!this.has(entity, comp)) {- hasAll = false;- break;- }- }- if (hasAll) {- entities.push(entity);- }- }- return entities;- }-}--/**- * @file text.ts- * @brief Text component definition for UI text rendering- */-// =============================================================================-// Text Alignment Enums-// =============================================================================-exports.TextAlign = void 0;-(function (TextAlign) {- TextAlign[TextAlign["Left"] = 0] = "Left";- TextAlign[TextAlign["Center"] = 1] = "Center";- TextAlign[TextAlign["Right"] = 2] = "Right";-})(exports.TextAlign || (exports.TextAlign = {}));-exports.TextVerticalAlign = void 0;-(function (TextVerticalAlign) {- TextVerticalAlign[TextVerticalAlign["Top"] = 0] = "Top";- TextVerticalAlign[TextVerticalAlign["Middle"] = 1] = "Middle";- TextVerticalAlign[TextVerticalAlign["Bottom"] = 2] = "Bottom";-})(exports.TextVerticalAlign || (exports.TextVerticalAlign = {}));-exports.TextOverflow = void 0;-(function (TextOverflow) {- TextOverflow[TextOverflow["Visible"] = 0] = "Visible";- TextOverflow[TextOverflow["Clip"] = 1] = "Clip";- TextOverflow[TextOverflow["Ellipsis"] = 2] = "Ellipsis";-})(exports.TextOverflow || (exports.TextOverflow = {}));-// =============================================================================-// Text Component Definition-// =============================================================================-const Text = defineComponent('Text', {- content: '',- fontFamily: 'Arial',- fontSize: 24,- color: { x: 1, y: 1, z: 1, w: 1 },- align: exports.TextAlign.Left,- verticalAlign: exports.TextVerticalAlign.Top,- wordWrap: true,- overflow: exports.TextOverflow.Visible,- lineHeight: 1.2,- dirty: true,-});--/**- * @file TextRenderer.ts- * @brief Renders text to GPU textures using Canvas 2D API- */-// =============================================================================-// Text Renderer-// =============================================================================-class TextRenderer {- constructor(module) {- this.cache = new Map();- this.module = module;- if (typeof OffscreenCanvas !== 'undefined') {- this.canvas = new OffscreenCanvas(512, 512);- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- else {- this.canvas = document.createElement('canvas');- this.canvas.width = 512;- this.canvas.height = 512;- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- }- /**- * Renders text to a texture and returns the handle- */- renderText(text, uiRect) {- const ctx = this.ctx;- const canvas = this.canvas;- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- const hasContainer = uiRect && uiRect.size.x > 0 && uiRect.size.y > 0;- const containerWidth = hasContainer ? uiRect.size.x : 0;- const containerHeight = hasContainer ? uiRect.size.y : 0;- const shouldWrap = text.wordWrap && hasContainer;- let lines = this.wrapText(text.content, shouldWrap ? containerWidth : 0);- const lineHeightPx = Math.ceil(text.fontSize * text.lineHeight);- const padding = Math.ceil(text.fontSize * 0.2);- const measuredWidth = Math.ceil(this.measureWidth(lines));- const measuredHeight = Math.ceil(lines.length * lineHeightPx);- const width = hasContainer ? Math.ceil(containerWidth) : measuredWidth + padding * 2;- const height = hasContainer ? Math.ceil(containerHeight) : measuredHeight + padding * 2;- // Handle overflow ellipsis- if (hasContainer && text.overflow === exports.TextOverflow.Ellipsis && measuredHeight > containerHeight) {- const maxLines = Math.floor(containerHeight / lineHeightPx);- if (maxLines > 0 && lines.length > maxLines) {- lines = lines.slice(0, maxLines);- const lastLine = lines[maxLines - 1];- lines[maxLines - 1] = this.truncateWithEllipsis(lastLine, containerWidth);- }- }- if (canvas.width < width || canvas.height < height) {- const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));- const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));- canvas.width = newWidth;- canvas.height = newHeight;- }- const r = Math.round(text.color.x * 255);- const g = Math.round(text.color.y * 255);- const b = Math.round(text.color.z * 255);- const a = text.color.w;- ctx.clearRect(0, 0, canvas.width, canvas.height);- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- ctx.textAlign = this.mapAlign(text.align);- ctx.textBaseline = 'top';- ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;- // Handle overflow clip- if (hasContainer && text.overflow === exports.TextOverflow.Clip) {- ctx.save();- ctx.beginPath();- ctx.rect(0, 0, width, height);- ctx.clip();- }- const textBlockHeight = lines.length * lineHeightPx;- let startY;- if (hasContainer) {- switch (text.verticalAlign) {- case exports.TextVerticalAlign.Top:- startY = padding;- break;- case exports.TextVerticalAlign.Middle:- startY = (height - textBlockHeight) / 2;- break;- case exports.TextVerticalAlign.Bottom:- startY = height - textBlockHeight - padding;- break;- default: startY = padding;- }- }- else {- startY = padding;- }- let y = startY;- for (const line of lines) {- let x;- switch (text.align) {- case exports.TextAlign.Left:- x = padding;- break;- case exports.TextAlign.Center:- x = width / 2;- break;- case exports.TextAlign.Right:- x = width - padding;- break;- default:- x = padding;- }- ctx.fillText(line, x, y);- y += lineHeightPx;- }- if (hasContainer && text.overflow === exports.TextOverflow.Clip) {- ctx.restore();- }- const imageData = ctx.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- const flipped = this.flipVertically(pixels, width, height);- const rm = this.module.getResourceManager();- const ptr = this.module._malloc(flipped.length);- this.module.HEAPU8.set(flipped, ptr);- const textureHandle = rm.createTexture(width, height, ptr, flipped.length, 1);- this.module._free(ptr);- return { textureHandle, width, height };- }- truncateWithEllipsis(text, maxWidth) {- const ellipsis = '...';- if (this.ctx.measureText(text).width <= maxWidth) {- return text;- }- let truncated = text;- while (truncated.length > 0 && this.ctx.measureText(truncated + ellipsis).width > maxWidth) {- truncated = truncated.slice(0, -1);- }- return truncated + ellipsis;- }- /**- * Renders text for an entity and caches the result- */- renderForEntity(entity, text, uiRect) {- const existing = this.cache.get(entity);- if (existing) {- const rm = this.module.getResourceManager();- rm.releaseTexture(existing.textureHandle);- }- const result = this.renderText(text, uiRect);- this.cache.set(entity, result);- return result;- }- /**- * Gets cached render result for entity- */- getCached(entity) {- return this.cache.get(entity);- }- /**- * Releases texture for entity- */- release(entity) {- const cached = this.cache.get(entity);- if (cached) {- const rm = this.module.getResourceManager();- rm.releaseTexture(cached.textureHandle);- this.cache.delete(entity);- }- }- /**- * Releases all cached textures- */- releaseAll() {- const rm = this.module.getResourceManager();- for (const result of this.cache.values()) {- rm.releaseTexture(result.textureHandle);- }- this.cache.clear();- }- // =========================================================================- // Private Methods- // =========================================================================- wrapText(text, maxWidth) {- if (!text)- return [''];- if (maxWidth <= 0)- return text.split('\n');- const paragraphs = text.split('\n');- const lines = [];- for (const paragraph of paragraphs) {- if (!paragraph) {- lines.push('');- continue;- }- let currentLine = '';- for (const char of paragraph) {- const testLine = currentLine + char;- const metrics = this.ctx.measureText(testLine);- if (metrics.width > maxWidth && currentLine) {- lines.push(currentLine);- currentLine = char;- }- else {- currentLine = testLine;- }- }- if (currentLine) {- lines.push(currentLine);- }- }- return lines.length > 0 ? lines : [''];- }- measureWidth(lines) {- let maxWidth = 0;- for (const line of lines) {- const metrics = this.ctx.measureText(line);- const width = metrics.actualBoundingBoxLeft !== undefined- ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight- : metrics.width;- maxWidth = Math.max(maxWidth, width);- }- return maxWidth;- }- mapAlign(align) {- switch (align) {- case exports.TextAlign.Left:- return 'left';- case exports.TextAlign.Center:- return 'center';- case exports.TextAlign.Right:- return 'right';- }- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- flipVertically(pixels, width, height) {- const rowSize = width * 4;- const flipped = new Uint8Array(pixels.length);- for (let y = 0; y < height; y++) {- const srcOffset = y * rowSize;- const dstOffset = (height - 1 - y) * rowSize;- flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);- }- return flipped;- }-}--/**- * @file UIRect.ts- * @brief UIRect component for UI layout with anchor and pivot- */-// =============================================================================-// UIRect Component Definition-// =============================================================================-const UIRect = defineComponent('UIRect', {- size: { x: 100, y: 100 },- anchor: { x: 0.5, y: 0.5 },- pivot: { x: 0.5, y: 0.5 },-});--/**- * @file TextPlugin.ts- * @brief Plugin that automatically syncs Text components to Sprite textures- */-// =============================================================================-// Text Plugin-// =============================================================================-class TextPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('TextPlugin: No WASM module available');- return;- }- const renderer = new TextRenderer(module);- const world = app.world;- app.addSystemToSchedule(exports.Schedule.PreUpdate, defineSystem([], () => {- const entities = world.getEntitiesWithComponents([Text]);- for (const entity of entities) {- const text = world.get(entity, Text);- if (!text.dirty)- continue;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- size: { x: 0, y: 0 },- color: { x: 1, y: 1, z: 1, w: 1 },- anchor: { x: 0.5, y: 0.5 },- flip: { x: false, y: false }- });- }- const uiRect = world.has(entity, UIRect)- ? world.get(entity, UIRect)- : null;- const result = renderer.renderForEntity(entity, text, uiRect);- const sprite = world.get(entity, Sprite);- sprite.texture = result.textureHandle;- sprite.size = { x: result.width, y: result.height };- sprite.uvOffset = { x: 0, y: 0 };- sprite.uvScale = { x: 1, y: 1 };- world.insert(entity, Sprite, sprite);- text.dirty = false;- }- }));- }-}-const textPlugin = new TextPlugin();--/**- * @file blend.ts- * @brief Blend mode definitions for rendering- */-exports.BlendMode = void 0;-(function (BlendMode) {- BlendMode[BlendMode["Normal"] = 0] = "Normal";- BlendMode[BlendMode["Additive"] = 1] = "Additive";- BlendMode[BlendMode["Multiply"] = 2] = "Multiply";- BlendMode[BlendMode["Screen"] = 3] = "Screen";- BlendMode[BlendMode["PremultipliedAlpha"] = 4] = "PremultipliedAlpha";-})(exports.BlendMode || (exports.BlendMode = {}));--/**- * @file material.ts- * @brief Material and Shader API for custom rendering- * @details Provides shader creation and material management for custom visual effects.- */-function isTextureRef(v) {- return typeof v === 'object' && v !== null && '__textureRef' in v;-}-// =============================================================================-// Internal State-// =============================================================================-let module$5 = null;-let resourceManager = null;-let nextMaterialId = 1;-const materials = new Map();-// =============================================================================-// Initialization-// =============================================================================-function initMaterialAPI(wasmModule) {- module$5 = wasmModule;- resourceManager = wasmModule.getResourceManager();- registerMaterialCallback();-}-function shutdownMaterialAPI() {- if (uniformBuffer$1 !== 0 && module$5) {- module$5._free(uniformBuffer$1);- uniformBuffer$1 = 0;- }- materials.clear();- nextMaterialId = 1;- materialCallbackRegistered = false;- resourceManager = null;- module$5 = null;-}-// =============================================================================-// Shader API-// =============================================================================-function getResourceManager() {- if (!resourceManager) {- throw new Error('Material API not initialized. Call initMaterialAPI() first.');- }- return resourceManager;-}-const Material = {- /**- * Creates a shader from vertex and fragment source code.- * @param vertexSrc GLSL vertex shader source- * @param fragmentSrc GLSL fragment shader source- * @returns Shader handle, or 0 on failure- */- createShader(vertexSrc, fragmentSrc) {- return getResourceManager().createShader(vertexSrc, fragmentSrc);- },- /**- * Releases a shader.- * @param shader Shader handle to release- */- releaseShader(shader) {- if (shader > 0) {- getResourceManager().releaseShader(shader);- }- },- /**- * Creates a material with a shader and optional settings.- * @param options Material creation options- * @returns Material handle- */- create(options) {- const handle = nextMaterialId++;- const data = {- shader: options.shader,- uniforms: new Map(),- blendMode: options.blendMode ?? exports.BlendMode.Normal,- depthTest: options.depthTest ?? false,- };- if (options.uniforms) {- for (const [key, value] of Object.entries(options.uniforms)) {- data.uniforms.set(key, value);- }- }- materials.set(handle, data);- return handle;- },- /**- * Gets material data by handle.- * @param material Material handle- * @returns Material data or undefined- */- get(material) {- return materials.get(material);- },- /**- * Sets a uniform value on a material.- * @param material Material handle- * @param name Uniform name- * @param value Uniform value- */- setUniform(material, name, value) {- const data = materials.get(material);- if (data) {- data.uniforms.set(name, value);- }- },- /**- * Gets a uniform value from a material.- * @param material Material handle- * @param name Uniform name- * @returns Uniform value or undefined- */- getUniform(material, name) {- const data = materials.get(material);- return data?.uniforms.get(name);- },- /**- * Sets the blend mode for a material.- * @param material Material handle- * @param mode Blend mode- */- setBlendMode(material, mode) {- const data = materials.get(material);- if (data) {- data.blendMode = mode;- }- },- /**- * Gets the blend mode of a material.- * @param material Material handle- * @returns Blend mode- */- getBlendMode(material) {- const data = materials.get(material);- return data?.blendMode ?? exports.BlendMode.Normal;- },- /**- * Sets depth test enabled for a material.- * @param material Material handle- * @param enabled Whether depth test is enabled- */- setDepthTest(material, enabled) {- const data = materials.get(material);- if (data) {- data.depthTest = enabled;- }- },- /**- * Gets the shader handle for a material.- * @param material Material handle- * @returns Shader handle- */- getShader(material) {- const data = materials.get(material);- return data?.shader ?? 0;- },- /**- * Releases a material (does not release the shader).- * @param material Material handle- */- release(material) {- materials.delete(material);- },- /**- * Checks if a material exists.- * @param material Material handle- * @returns True if material exists- */- isValid(material) {- return materials.has(material);- },- /**- * Creates a material from asset data.- * @param data Material asset data (properties object)- * @param shaderHandle Pre-loaded shader handle- * @returns Material handle- */- createFromAsset(data, shaderHandle) {- const uniforms = {};- for (const [key, value] of Object.entries(data.properties)) {- if (typeof value === 'number') {- uniforms[key] = value;- }- else if (typeof value === 'object' && value !== null) {- const obj = value;- if ('w' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };- }- else if ('z' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };- }- else if ('y' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0 };- }- }- }- return this.create({- shader: shaderHandle,- uniforms,- blendMode: data.blendMode ?? exports.BlendMode.Normal,- depthTest: data.depthTest ?? false,- });- },- /**- * Creates a material instance that shares the shader with source.- * @param source Source material handle- * @returns New material handle with copied settings- */- createInstance(source) {- const sourceData = materials.get(source);- if (!sourceData) {- throw new Error(`Invalid source material: ${source}`);- }- const handle = nextMaterialId++;- const data = {- shader: sourceData.shader,- uniforms: new Map(sourceData.uniforms),- blendMode: sourceData.blendMode,- depthTest: sourceData.depthTest,- };- materials.set(handle, data);- return handle;- },- /**- * Exports material to serializable asset data.- * @param material Material handle- * @param shaderPath Shader file path for asset reference- * @returns Material asset data- */- toAssetData(material, shaderPath) {- const data = materials.get(material);- if (!data)- return null;- const properties = {};- for (const [key, value] of data.uniforms) {- properties[key] = value;- }- return {- version: '1.0',- type: 'material',- shader: shaderPath,- blendMode: data.blendMode,- depthTest: data.depthTest,- properties,- };- },- /**- * Gets all uniforms from a material.- * @param material Material handle- * @returns Map of uniform names to values- */- getUniforms(material) {- const data = materials.get(material);- return data ? new Map(data.uniforms) : new Map();- },- tex(textureId, slot) {- return { __textureRef: true, textureId, slot };- },-};-// =============================================================================-// Material Callback Registration-// =============================================================================-let materialCallbackRegistered = false;-let uniformBuffer$1 = 0;-const UNIFORM_BUFFER_SIZE = 4096;-function ensureUniformBuffer() {- if (uniformBuffer$1 === 0 && module$5) {- uniformBuffer$1 = module$5._malloc(UNIFORM_BUFFER_SIZE);- }- return uniformBuffer$1;-}-function serializeUniforms(uniforms) {- const bufferPtr = ensureUniformBuffer();- if (bufferPtr === 0 || !module$5)- return { ptr: 0, count: 0 };- let offset = 0;- let count = 0;- const heap8 = module$5.HEAPU8;- const heap32 = module$5.HEAPU32;- const heapF32 = module$5.HEAPF32;- for (const [name, value] of uniforms) {- if (offset + 128 > UNIFORM_BUFFER_SIZE)- break;- const nameBytes = new TextEncoder().encode(name);- const nameLen = nameBytes.length;- const namePadded = Math.ceil(nameLen / 4) * 4;- heap32[(bufferPtr + offset) >> 2] = nameLen;- offset += 4;- heap8.set(nameBytes, bufferPtr + offset);- offset += namePadded;- let type = 0;- let values = [0, 0, 0, 0];- if (typeof value === 'number') {- type = 0;- values[0] = value;- }- else if (Array.isArray(value)) {- type = Math.min(value.length - 1, 3);- for (let i = 0; i < Math.min(value.length, 4); i++) {- values[i] = value[i];- }- }- else if ('w' in value) {- type = 3;- values = [value.x, value.y, value.z, value.w];- }- else if ('z' in value) {- type = 2;- values = [value.x, value.y, value.z, 0];- }- else if ('y' in value) {- type = 1;- values = [value.x, value.y, 0, 0];- }- heap32[(bufferPtr + offset) >> 2] = type;- offset += 4;- for (let i = 0; i < 4; i++) {- heapF32[(bufferPtr + offset) >> 2] = values[i];- offset += 4;- }- count++;- }- return { ptr: bufferPtr, count };-}-function registerMaterialCallback() {- if (!module$5 || materialCallbackRegistered)- return;- const callback = (materialId, outShaderIdPtr, outBlendModePtr, outUniformBufferPtr, outUniformCountPtr) => {- const data = materials.get(materialId);- if (!data) {- module$5.HEAPU32[outShaderIdPtr >> 2] = 0;- module$5.HEAPU32[outBlendModePtr >> 2] = 0;- module$5.HEAPU32[outUniformBufferPtr >> 2] = 0;- module$5.HEAPU32[outUniformCountPtr >> 2] = 0;- return;- }- module$5.HEAPU32[outShaderIdPtr >> 2] = data.shader;- module$5.HEAPU32[outBlendModePtr >> 2] = data.blendMode;- const { ptr, count } = serializeUniforms(data.uniforms);- module$5.HEAPU32[outUniformBufferPtr >> 2] = ptr;- module$5.HEAPU32[outUniformCountPtr >> 2] = count;- };- module$5.materialDataProvider = callback;- materialCallbackRegistered = true;-}-// =============================================================================-// Built-in Shader Sources-// =============================================================================-const ShaderSources = {- SPRITE_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;-layout(location = 2) in vec2 a_texCoord;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;-out vec2 v_texCoord;--void main() {- v_color = a_color;- v_texCoord = a_texCoord;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- SPRITE_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;-in vec2 v_texCoord;--uniform sampler2D u_texture;--out vec4 fragColor;--void main() {- fragColor = texture(u_texture, v_texCoord) * v_color;-}-`,- COLOR_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;--void main() {- v_color = a_color;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- COLOR_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;--out vec4 fragColor;--void main() {- fragColor = v_color;-}-`,-};--/**- * @file draw.ts- * @brief Immediate mode 2D drawing API- * @details Provides simple drawing primitives (lines, rectangles, circles)- * with automatic batching. All draw commands are cleared each frame.- */-// =============================================================================-// Internal State-// =============================================================================-let module$4 = null;-let viewProjectionPtr$1 = 0;-let transformPtr = 0;-let uniformsPtr = 0;-const UNIFORMS_BUFFER_SIZE = 256;-const uniformBuffer = new Float32Array(UNIFORMS_BUFFER_SIZE);-// =============================================================================-// Initialization-// =============================================================================-function initDrawAPI(wasmModule) {- module$4 = wasmModule;- viewProjectionPtr$1 = module$4._malloc(16 * 4);- transformPtr = module$4._malloc(16 * 4);- uniformsPtr = module$4._malloc(UNIFORMS_BUFFER_SIZE * 4);-}-function shutdownDrawAPI() {- if (module$4) {- if (viewProjectionPtr$1) {- module$4._free(viewProjectionPtr$1);- viewProjectionPtr$1 = 0;- }- if (transformPtr) {- module$4._free(transformPtr);- transformPtr = 0;- }- if (uniformsPtr) {- module$4._free(uniformsPtr);- uniformsPtr = 0;- }- }- module$4 = null;-}-// =============================================================================-// Draw Implementation-// =============================================================================-function getModule$2() {- if (!module$4) {- throw new Error('Draw API not initialized. Call initDrawAPI() first.');- }- return module$4;-}-const WHITE = { x: 1, y: 1, z: 1, w: 1 };-const Draw = {- begin(viewProjection) {- const m = getModule$2();- m.HEAPF32.set(viewProjection, viewProjectionPtr$1 / 4);- m.draw_begin(viewProjectionPtr$1);- },- end() {- getModule$2().draw_end();- },- line(from, to, color, thickness = 1) {- getModule$2().draw_line(from.x, from.y, to.x, to.y, color.x, color.y, color.z, color.w, thickness);- },- rect(position, size, color, filled = true) {- getModule$2().draw_rect(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, filled);- },- rectOutline(position, size, color, thickness = 1) {- getModule$2().draw_rectOutline(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, thickness);- },- circle(center, radius, color, filled = true, segments = 32) {- getModule$2().draw_circle(center.x, center.y, radius, color.x, color.y, color.z, color.w, filled, segments);- },- circleOutline(center, radius, color, thickness = 1, segments = 32) {- getModule$2().draw_circleOutline(center.x, center.y, radius, color.x, color.y, color.z, color.w, thickness, segments);- },- texture(position, size, textureHandle, tint = WHITE) {- getModule$2().draw_texture(position.x, position.y, size.x, size.y, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- textureRotated(position, size, rotation, textureHandle, tint = WHITE) {- getModule$2().draw_textureRotated(position.x, position.y, size.x, size.y, rotation, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- setLayer(layer) {- getModule$2().draw_setLayer(layer);- },- setDepth(depth) {- getModule$2().draw_setDepth(depth);- },- getDrawCallCount() {- if (!module$4)- return 0;- return module$4.draw_getDrawCallCount();- },- getPrimitiveCount() {- if (!module$4)- return 0;- return module$4.draw_getPrimitiveCount();- },- setBlendMode(mode) {- getModule$2().draw_setBlendMode(mode);- },- setDepthTest(enabled) {- getModule$2().draw_setDepthTest(enabled);- },- drawMesh(geometry, shader, transform) {- const m = getModule$2();- m.HEAPF32.set(transform, transformPtr / 4);- m.draw_mesh(geometry, shader, transformPtr);- },- drawMeshWithMaterial(geometry, material, transform) {- const m = getModule$2();- const matData = Material.get(material);- if (!matData)- return;- Draw.setBlendMode(matData.blendMode);- Draw.setDepthTest(matData.depthTest);- if (matData.uniforms.size === 0) {- Draw.drawMesh(geometry, matData.shader, transform);- return;- }- m.HEAPF32.set(transform, transformPtr / 4);- let idx = 0;- let autoTextureSlot = 0;- for (const [name, value] of matData.uniforms) {- const nameId = getUniformNameId(name);- if (nameId < 0)- continue;- if (isTextureRef(value)) {- uniformBuffer[idx++] = 10;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.slot ?? autoTextureSlot++;- uniformBuffer[idx++] = value.textureId;- }- else if (typeof value === 'number') {- uniformBuffer[idx++] = 1;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value;- }- else if (Array.isArray(value)) {- uniformBuffer[idx++] = value.length;- uniformBuffer[idx++] = nameId;- for (let i = 0; i < value.length; i++) {- uniformBuffer[idx++] = value[i];- }- }- else if ('w' in value) {- uniformBuffer[idx++] = 4;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- uniformBuffer[idx++] = value.w;- }- else if ('z' in value) {- uniformBuffer[idx++] = 3;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- }- else {- uniformBuffer[idx++] = 2;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- }- if (idx > UNIFORMS_BUFFER_SIZE - 6) {- console.warn('Uniform buffer overflow, some uniforms will be ignored');- break;- }- }- if (idx === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);- return;- }- m.HEAPF32.set(uniformBuffer.subarray(0, idx), uniformsPtr / 4);- m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);- },-};-const UNIFORM_NAME_MAP = {- '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 getUniformNameId(name) {- return UNIFORM_NAME_MAP[name] ?? -1;-}--/**- * @file geometry.ts- * @brief Geometry API for custom mesh rendering- * @details Provides geometry creation and management for custom shapes,- * particles, trails, and other procedural meshes.- */-exports.DataType = void 0;-(function (DataType) {- DataType[DataType["Float"] = 1] = "Float";- DataType[DataType["Float2"] = 2] = "Float2";- DataType[DataType["Float3"] = 3] = "Float3";- DataType[DataType["Float4"] = 4] = "Float4";- DataType[DataType["Int"] = 5] = "Int";- DataType[DataType["Int2"] = 6] = "Int2";- DataType[DataType["Int3"] = 7] = "Int3";- DataType[DataType["Int4"] = 8] = "Int4";-})(exports.DataType || (exports.DataType = {}));-// =============================================================================-// Internal State-// =============================================================================-let module$3 = null;-let vertexPtr = 0;-let indexPtr = 0;-let layoutPtr = 0;-const VERTEX_BUFFER_SIZE = 64 * 1024;-const INDEX_BUFFER_SIZE = 16 * 1024;-const LAYOUT_BUFFER_SIZE = 64;-// =============================================================================-// Initialization-// =============================================================================-function initGeometryAPI(wasmModule) {- module$3 = wasmModule;- vertexPtr = module$3._malloc(VERTEX_BUFFER_SIZE * 4);- indexPtr = module$3._malloc(INDEX_BUFFER_SIZE * 4);- layoutPtr = module$3._malloc(LAYOUT_BUFFER_SIZE * 4);-}-function shutdownGeometryAPI() {- if (module$3) {- if (vertexPtr)- module$3._free(vertexPtr);- if (indexPtr)- module$3._free(indexPtr);- if (layoutPtr)- module$3._free(layoutPtr);- vertexPtr = 0;- indexPtr = 0;- layoutPtr = 0;- }- module$3 = null;-}-// =============================================================================-// Geometry API-// =============================================================================-function getModule$1() {- if (!module$3) {- throw new Error('Geometry API not initialized. Call initGeometryAPI() first.');- }- return module$3;-}-const Geometry = {- /**- * Creates a new geometry with vertices and optional indices.- * @param options Geometry creation options- * @returns Geometry handle- */- create(options) {- const m = getModule$1();- const handle = m.geometry_create();- if (handle === 0) {- throw new Error('Failed to create geometry');- }- const vertexCount = options.vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(options.vertices, vertexPtr / 4);- const layoutCount = options.layout.length;- const layoutArray = new Int32Array(layoutCount);- for (let i = 0; i < layoutCount; i++) {- layoutArray[i] = options.layout[i].type;- }- const heap32 = new Int32Array(m.HEAPU8.buffer, layoutPtr, layoutCount);- heap32.set(layoutArray);- m.geometry_init(handle, vertexPtr, vertexCount, layoutPtr, layoutCount, options.dynamic ?? false);- if (options.indices) {- const indexCount = options.indices.length;- if (indexCount * 4 > INDEX_BUFFER_SIZE * 4) {- throw new Error(`Index data too large: ${indexCount} indices (max ${INDEX_BUFFER_SIZE})`);- }- if (options.indices instanceof Uint16Array) {- const heap16 = new Uint16Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap16.set(options.indices);- m.geometry_setIndices16(handle, indexPtr, indexCount);- }- else {- const heap32 = new Uint32Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap32.set(options.indices);- m.geometry_setIndices32(handle, indexPtr, indexCount);- }- }- return handle;- },- /**- * Updates vertices of a dynamic geometry.- * @param handle Geometry handle- * @param vertices New vertex data- * @param offset Offset in floats- */- updateVertices(handle, vertices, offset = 0) {- const m = getModule$1();- const vertexCount = vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(vertices, vertexPtr / 4);- m.geometry_updateVertices(handle, vertexPtr, vertexCount, offset);- },- /**- * Releases a geometry.- * @param handle Geometry handle- */- release(handle) {- if (handle > 0) {- getModule$1().geometry_release(handle);- }- },- /**- * Checks if a geometry handle is valid.- * @param handle Geometry handle- * @returns True if valid- */- isValid(handle) {- if (!module$3 || handle <= 0)- return false;- return module$3.geometry_isValid(handle);- },- // =========================================================================- // Helper Functions- // =========================================================================- /**- * Creates a unit quad geometry (1x1, centered at origin).- * @returns Geometry handle- */- createQuad(width = 1, height = 1) {- const hw = width / 2;- const hh = height / 2;- return Geometry.create({- vertices: new Float32Array([- // x, y, u, v- -hw, -hh, 0, 0,- hw, -hh, 1, 0,- hw, hh, 1, 1,- -hw, hh, 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]),- });- },- /**- * Creates a circle geometry.- * @param radius Circle radius- * @param segments Number of segments- * @returns Geometry handle- */- createCircle(radius = 1, segments = 32) {- const vertices = [];- const indices = [];- vertices.push(0, 0, 0.5, 0.5);- for (let i = 0; i <= segments; i++) {- const angle = (i / segments) * Math.PI * 2;- const x = Math.cos(angle) * radius;- const y = Math.sin(angle) * radius;- const u = (Math.cos(angle) + 1) / 2;- const v = (Math.sin(angle) + 1) / 2;- vertices.push(x, y, u, v);- }- for (let i = 1; i <= segments; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: exports.DataType.Float2 },- { name: 'a_texCoord', type: exports.DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },- /**- * Creates a polygon geometry from vertices.- * @param points Array of {x, y} points- * @returns Geometry handle- */- createPolygon(points) {- if (points.length < 3) {- throw new Error('Polygon must have at least 3 points');- }- let minX = Infinity, minY = Infinity;- let maxX = -Infinity, maxY = -Infinity;- for (const p of points) {- minX = Math.min(minX, p.x);- minY = Math.min(minY, p.y);- maxX = Math.max(maxX, p.x);- maxY = Math.max(maxY, p.y);- }- const vertices = [];- for (const p of points) {- const u = (p.x - minX) / (maxX - minX);- const v = (p.y - minY) / (maxY - minY);- vertices.push(p.x, p.y, u, v);- }- const indices = [];- for (let i = 1; i < points.length - 1; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: exports.DataType.Float2 },- { name: 'a_texCoord', type: exports.DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },-};--/**- * @file postprocess.ts- * @brief Post-processing effects API- * @details Provides full-screen post-processing effects like blur, vignette, etc.- */-// =============================================================================-// Internal State-// =============================================================================-let module$2 = null;-// =============================================================================-// Initialization-// =============================================================================-function initPostProcessAPI(wasmModule) {- module$2 = wasmModule;-}-function shutdownPostProcessAPI() {- if (module$2 && PostProcess.isInitialized()) {- PostProcess.shutdown();- }- module$2 = null;-}-// =============================================================================-// PostProcess API-// =============================================================================-function getModule() {- if (!module$2) {- throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');- }- return module$2;-}-const PostProcess = {- /**- * Initializes the post-processing pipeline.- * @param width Framebuffer width- * @param height Framebuffer height- * @returns True on success- */- init(width, height) {- return getModule().postprocess_init(width, height);- },- /**- * Shuts down the post-processing pipeline.- */- shutdown() {- getModule().postprocess_shutdown();- },- /**- * Resizes the framebuffers.- * @param width New width- * @param height New height- */- resize(width, height) {- getModule().postprocess_resize(width, height);- },- /**- * Adds a post-processing pass.- * @param name Unique name for the pass- * @param shader Shader handle- * @returns Pass index- */- addPass(name, shader) {- return getModule().postprocess_addPass(name, shader);- },- /**- * Removes a pass by name.- * @param name Pass name- */- removePass(name) {- getModule().postprocess_removePass(name);- },- /**- * Enables or disables a pass.- * @param name Pass name- * @param enabled Whether to enable the pass- */- setEnabled(name, enabled) {- getModule().postprocess_setPassEnabled(name, enabled);- },- /**- * Checks if a pass is enabled.- * @param name Pass name- * @returns True if enabled- */- isEnabled(name) {- return getModule().postprocess_isPassEnabled(name);- },- /**- * Sets a float uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Float value- */- setUniform(passName, uniform, value) {- getModule().postprocess_setUniformFloat(passName, uniform, value);- },- /**- * Sets a vec4 uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Vec4 value- */- setUniformVec4(passName, uniform, value) {- getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);- },- /**- * Begins rendering to the post-process pipeline.- * Call this before rendering your scene.- */- begin() {- getModule().postprocess_begin();- },- /**- * Ends and processes all passes.- * Call this after rendering your scene.- */- end() {- getModule().postprocess_end();- },- /**- * Gets the number of passes.- */- getPassCount() {- return getModule().postprocess_getPassCount();- },- /**- * Checks if the pipeline is initialized.- */- isInitialized() {- if (!module$2)- return false;- return module$2.postprocess_isInitialized();- },- /**- * Sets bypass mode to skip FBO rendering entirely.- * When bypassed, begin()/end() become no-ops and scene renders directly to screen.- * Use this when no post-processing passes are needed for maximum performance.- * @param bypass Whether to bypass the pipeline- */- setBypass(bypass) {- getModule().postprocess_setBypass(bypass);- },- /**- * Checks if bypass mode is enabled.- * @returns True if bypassed- */- isBypassed() {- if (!module$2)- return true;- return module$2.postprocess_isBypassed();- },- // =========================================================================- // Built-in Effects- // =========================================================================- /**- * Creates a blur effect shader.- * @returns Shader handle- */- createBlur() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 texelSize = 1.0 / u_resolution;- float offset = u_intensity;-- vec4 color = vec4(0.0);- color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord) * 0.25;- color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;-- fragColor = color;-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a vignette effect shader.- * @returns Shader handle- */- createVignette() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-uniform float u_softness;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- vec2 uv = v_texCoord * 2.0 - 1.0;- float dist = length(uv);- float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);- fragColor = vec4(color.rgb * vignette, color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a grayscale effect shader.- * @returns Shader handle- */- createGrayscale() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));- fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a chromatic aberration effect shader.- * @returns Shader handle- */- createChromaticAberration() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 offset = u_intensity / u_resolution;- float r = texture(u_texture, v_texCoord + offset).r;- float g = texture(u_texture, v_texCoord).g;- float b = texture(u_texture, v_texCoord - offset).b;- float a = texture(u_texture, v_texCoord).a;- fragColor = vec4(r, g, b, a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },-};-// =============================================================================-// Shared Vertex Shader-// =============================================================================-const POSTPROCESS_VERTEX = `#version 300 es-precision highp float;--layout(location = 0) in vec2 a_position;-layout(location = 1) in vec2 a_texCoord;--out vec2 v_texCoord;--void main() {- v_texCoord = a_texCoord;- gl_Position = vec4(a_position, 0.0, 1.0);-}-`;--exports.RenderStage = void 0;-(function (RenderStage) {- RenderStage[RenderStage["Background"] = 0] = "Background";- RenderStage[RenderStage["Opaque"] = 1] = "Opaque";- RenderStage[RenderStage["Transparent"] = 2] = "Transparent";- RenderStage[RenderStage["Overlay"] = 3] = "Overlay";-})(exports.RenderStage || (exports.RenderStage = {}));-let module$1 = null;-let viewProjectionPtr = 0;-function initRendererAPI(wasmModule) {- module$1 = wasmModule;- viewProjectionPtr = module$1._malloc(16 * 4);-}-function shutdownRendererAPI() {- if (module$1 && viewProjectionPtr) {- module$1._free(viewProjectionPtr);- viewProjectionPtr = 0;- }- module$1 = null;-}-const Renderer = {- init(width, height) {- module$1?.renderer_init(width, height);- },- resize(width, height) {- module$1?.renderer_resize(width, height);- },- begin(viewProjection, target) {- if (!module$1 || !viewProjectionPtr)- return;- module$1.HEAPF32.set(viewProjection, viewProjectionPtr / 4);- module$1.renderer_begin(viewProjectionPtr, target ?? 0);- },- end() {- module$1?.renderer_end();- },- submitSprites(registry) {- if (!module$1)- return;- module$1.renderer_submitSprites(registry._cpp);- },- submitSpine(registry) {- if (!module$1)- return;- module$1.renderer_submitSpine(registry._cpp);- },- setStage(stage) {- module$1?.renderer_setStage(stage);- },- createRenderTarget(width, height, flags = 1) {- return module$1?.renderer_createTarget(width, height, flags) ?? 0;- },- releaseRenderTarget(handle) {- module$1?.renderer_releaseTarget(handle);- },- getTargetTexture(handle) {- return module$1?.renderer_getTargetTexture(handle) ?? 0;- },- getTargetDepthTexture(handle) {- return module$1?.renderer_getTargetDepthTexture(handle) ?? 0;- },- setClearColor(r, g, b, a) {- module$1?.renderer_setClearColor?.(r, g, b, a);- },- getStats() {- if (!module$1) {- return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };- }- return {- drawCalls: module$1.renderer_getDrawCalls(),- triangles: module$1.renderer_getTriangles(),- sprites: module$1.renderer_getSprites(),- spine: module$1.renderer_getSpine(),- meshes: module$1.renderer_getMeshes(),- culled: module$1.renderer_getCulled(),- };- },-};--/**- * @file customDraw.ts- * @brief Custom draw callback registration for the render pipeline- */-const callbacks = new Map();-function registerDrawCallback(id, fn) {- callbacks.set(id, fn);-}-function unregisterDrawCallback(id) {- callbacks.delete(id);-}-function clearDrawCallbacks() {- callbacks.clear();-}-function getDrawCallbacks() {- return callbacks;-}--/**- * @file renderPipeline.ts- * @brief Unified render pipeline for runtime and editor- */-class RenderPipeline {- render(params) {- const { registry, viewProjection, width, height, elapsed } = params;- Renderer.resize(width, height);- const usePostProcess = PostProcess.isInitialized()- && PostProcess.getPassCount() > 0- && !PostProcess.isBypassed();- if (usePostProcess) {- PostProcess.resize(width, height);- PostProcess.begin();- }- Renderer.begin(viewProjection);- Renderer.submitSprites(registry);- Renderer.submitSpine(registry);- Renderer.end();- const cbs = getDrawCallbacks();- if (cbs.size > 0) {- Draw.begin(viewProjection);- const failed = [];- for (const [id, fn] of cbs.entries()) {- try {- fn(elapsed);- }- catch (e) {- console.error(`[CustomDraw] callback '${id}' error:`, e);- failed.push(id);- }- }- Draw.end();- for (const id of failed) {- unregisterDrawCallback(id);- }- }- if (usePostProcess) {- PostProcess.end();- }- }-}--/**- * @file app.ts- * @brief Application builder and web platform integration- */-// =============================================================================-// App-// =============================================================================-class App {- constructor() {- this.systems_ = new Map();- this.runner_ = null;- this.running_ = false;- this.lastTime_ = 0;- this.module_ = null;- this.mainLoop = () => {- if (!this.running_) {- return;- }- const now = performance.now();- const deltaMs = now - this.lastTime_;- this.lastTime_ = now;- const delta = deltaMs / 1000;- this.updateTime(delta);- this.runSchedule(exports.Schedule.First);- 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 World();- this.resources_ = new ResourceStorage();- for (const s of Object.values(exports.Schedule)) {- if (typeof s === 'number') {- this.systems_.set(s, []);- }- }- }- static new() {- return new App();- }- // =========================================================================- // Plugins- // =========================================================================- addPlugin(plugin) {- plugin.build(this);- return this;- }- // =========================================================================- // Systems- // =========================================================================- addSystemToSchedule(schedule, system) {- this.systems_.get(schedule).push({ system });- return this;- }- addSystem(system) {- return this.addSystemToSchedule(exports.Schedule.Update, system);- }- addStartupSystem(system) {- return this.addSystemToSchedule(exports.Schedule.Startup, system);- }- // =========================================================================- // C++ Integration- // =========================================================================- connectCpp(cppRegistry, module) {- this.world_.connectCpp(cppRegistry);- if (module) {- this.module_ = module;- }- return this;- }- get wasmModule() {- return this.module_;- }- // =========================================================================- // World Access- // =========================================================================- get world() {- return this.world_;- }- // =========================================================================- // Resource Access- // =========================================================================- insertResource(resource, value) {- this.resources_.insert(resource, value);- return this;- }- getResource(resource) {- return this.resources_.get(resource);- }- hasResource(resource) {- return this.resources_.has(resource);- }- // =========================================================================- // Run- // =========================================================================- run() {- if (this.running_) {- return;- }- this.running_ = true;- this.runner_ = new SystemRunner(this.world_, this.resources_);- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });- this.runSchedule(exports.Schedule.Startup);- this.lastTime_ = performance.now();- this.mainLoop();- }- quit() {- this.running_ = false;- shutdownRendererAPI();- shutdownPostProcessAPI();- shutdownGeometryAPI();- shutdownMaterialAPI();- shutdownDrawAPI();- }- // =========================================================================- // Internal- // =========================================================================- runSchedule(schedule) {- const systems = this.systems_.get(schedule);- if (!systems || !this.runner_) {- return;- }- for (const entry of systems) {- this.runner_.run(entry.system);- }- }- updateTime(delta) {- const time = this.resources_.get(Time);- const newTime = {- delta,- elapsed: time.elapsed + delta,- frameCount: time.frameCount + 1- };- this.resources_.set(Time, newTime);- }-}-function createWebApp(module, options) {- const app = App.new();- const cppRegistry = new module.Registry();- app.connectCpp(cppRegistry, module);- if (options?.glContextHandle) {- module.initRendererWithContext(options.glContextHandle);- }- else {- module.initRenderer();- }- initDrawAPI(module);- initMaterialAPI(module);- initGeometryAPI(module);- initPostProcessAPI(module);- initRendererAPI(module);- const pipeline = new RenderPipeline();- let startTime = performance.now();- const getViewportSize = options?.getViewportSize ?? (() => ({- width: window.innerWidth * (window.devicePixelRatio || 1),- height: window.innerHeight * (window.devicePixelRatio || 1)- }));- const renderSystem = {- _id: Symbol('RenderSystem'),- _name: 'RenderSystem',- _params: [],- _fn: () => {- const { width, height } = getViewportSize();- const vp = computeViewProjection(cppRegistry, width, height);- const elapsed = (performance.now() - startTime) / 1000;- pipeline.render({- registry: { _cpp: cppRegistry },- viewProjection: vp,- width, height, elapsed,- });- }- };- app.addSystemToSchedule(exports.Schedule.Last, renderSystem);- app.addPlugin(textPlugin);- return app;-}-function flushPendingSystems(app) {- if (typeof window === 'undefined')- return;- const pending = window.__esengine_pendingSystems;- if (!pending || pending.length === 0)- return;- for (const entry of pending) {- app.addSystemToSchedule(entry.schedule, entry.system);- }- pending.length = 0;-}-// =============================================================================-// View-Projection Computation-// =============================================================================-const IDENTITY = new Float32Array([- 1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1,-]);-function computeViewProjection(registry, width, height) {- const count = registry.entityCount();- const scanLimit = count + 1000;- for (let e = 0; e < scanLimit; e++) {- if (!registry.valid(e) || !registry.hasCamera(e) || !registry.hasLocalTransform(e)) {- continue;- }- const camera = registry.getCamera(e);- if (!camera.isActive)- continue;- const transform = registry.getLocalTransform(e);- const aspect = width / height;- let projection;- if (camera.projectionType === 1) {- const halfH = camera.orthoSize;- const halfW = halfH * aspect;- projection = ortho(-halfW, halfW, -halfH, halfH, -camera.farPlane, camera.farPlane);- }- else {- projection = perspective(camera.fov * Math.PI / 180, aspect, camera.nearPlane, camera.farPlane);- }- const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);- return multiply(projection, view);- }- return IDENTITY;-}-function ortho(left, right, bottom, top, near, far) {- const m = new Float32Array(16);- const rl = right - left;- const tb = top - bottom;- const fn = far - near;- m[0] = 2 / rl;- m[5] = 2 / tb;- m[10] = -2 / fn;- m[12] = -(right + left) / rl;- m[13] = -(top + bottom) / tb;- m[14] = -(far + near) / fn;- m[15] = 1;- return m;-}-function perspective(fovRad, aspect, near, far) {- const m = new Float32Array(16);- const f = 1.0 / Math.tan(fovRad / 2);- const nf = near - far;- m[0] = f / aspect;- m[5] = f;- m[10] = (far + near) / nf;- m[11] = -1;- m[14] = (2 * far * near) / nf;- return m;-}-function invertTranslation(x, y, z) {- const m = new Float32Array(16);- m[0] = 1;- m[5] = 1;- m[10] = 1;- m[15] = 1;- m[12] = -x;- m[13] = -y;- m[14] = -z;- return m;-}-function multiply(a, b) {- const m = new Float32Array(16);- for (let i = 0; i < 4; i++) {- for (let j = 0; j < 4; j++) {- m[j * 4 + i] =- a[0 * 4 + i] * b[j * 4 + 0] +- a[1 * 4 + i] * b[j * 4 + 1] +- a[2 * 4 + i] * b[j * 4 + 2] +- a[3 * 4 + i] * b[j * 4 + 3];- }- }- return m;-}--/**- * @file MaterialLoader.ts- * @brief Material asset loading and caching- */-// =============================================================================-// MaterialLoader-// =============================================================================-class MaterialLoader {- constructor(shaderLoader, basePath = '') {- this.cache_ = new Map();- this.pending_ = new Map();- this.shaderLoader_ = shaderLoader;- this.basePath_ = basePath;- }- async load(path) {- const cached = this.cache_.get(path);- if (cached) {- return cached;- }- const pending = this.pending_.get(path);- if (pending) {- return pending;- }- const promise = this.loadInternal(path);- this.pending_.set(path, promise);- try {- const result = await promise;- this.cache_.set(path, result);- return result;- }- finally {- this.pending_.delete(path);- }- }- get(path) {- return this.cache_.get(path);- }- has(path) {- return this.cache_.has(path);- }- release(path) {- const loaded = this.cache_.get(path);- if (loaded) {- Material.release(loaded.handle);- this.cache_.delete(path);- }- }- releaseAll() {- for (const loaded of this.cache_.values()) {- Material.release(loaded.handle);- }- this.cache_.clear();- }- async loadInternal(path) {- const fullPath = this.resolvePath(path);- const exists = await platformFileExists(fullPath);- if (!exists) {- throw new Error(`Material file not found: ${fullPath}`);- }- const content = await platformReadTextFile(fullPath);- if (!content) {- throw new Error(`Failed to read material file: ${fullPath}`);- }- const data = JSON.parse(content);- if (data.type !== 'material') {- throw new Error(`Invalid material file type: ${data.type}`);- }- const shaderPath = this.resolveShaderPath(path, data.shader);- const shaderHandle = await this.shaderLoader_.load(shaderPath);- const materialHandle = Material.createFromAsset(data, shaderHandle);- return {- handle: materialHandle,- shaderHandle,- path,- };- }- resolvePath(path) {- if (path.startsWith('/') || path.startsWith('http')) {- return path;- }- return this.basePath_ ? `${this.basePath_}/${path}` : path;- }- resolveShaderPath(materialPath, shaderPath) {- if (shaderPath.startsWith('/') || shaderPath.startsWith('http') || shaderPath.startsWith('assets/')) {- return shaderPath;- }- const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));- return dir ? `${dir}/${shaderPath}` : shaderPath;- }-}--/**- * @file scene.ts- * @brief Scene loading utilities- */-// =============================================================================-// Scene Loader-// =============================================================================-function loadSceneData(world, sceneData) {- const entityMap = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- loadComponent(world, entity, compData);- }- }- // Set parent-child relationships- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- return entityMap;-}-async function loadSceneWithAssets(world, sceneData, options) {- const entityMap = new Map();- const assetServer = options?.assetServer;- const texturePathToUrl = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- }- catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data;- const skeletonPath = data.skeletonPath;- const atlasPath = data.atlasPath;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- loadComponent(world, entity, compData);- }- }- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- if (assetServer && sceneData.textureMetadata) {- for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {- const url = texturePathToUrl.get(texturePath);- if (url && metadata.sliceBorder) {- assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);- }- }- }- return entityMap;-}-function loadComponent(world, entity, compData) {- const data = compData.data;- switch (compData.type) {- case 'LocalTransform':- world.insert(entity, LocalTransform, data);- break;- case 'Sprite':- world.insert(entity, Sprite, data);- break;- case 'Camera':- world.insert(entity, Camera, data);- break;- case 'Canvas':- world.insert(entity, Canvas, data);- break;- case 'Text':- world.insert(entity, Text, data);- break;- case 'SpineAnimation':- world.insert(entity, SpineAnimation, data);- break;- case 'UIRect':- world.insert(entity, UIRect, data);- break;- default: {- const userComp = getUserComponent(compData.type);- if (userComp) {- world.insert(entity, userComp, data);- }- else {- console.warn(`Unknown component type: ${compData.type}`);- }- break;- }- }-}-function updateCameraAspectRatio(world, aspectRatio) {- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera) {- camera.aspectRatio = aspectRatio;- world.insert(entity, Camera, camera);- }- }-}--class AsyncCache {- constructor() {- this.cache_ = new Map();- this.pending_ = new Map();- }- async getOrLoad(key, loader) {- const cached = this.cache_.get(key);- if (cached !== undefined) {- return cached;- }- const pending = this.pending_.get(key);- if (pending) {- return pending;- }- const promise = loader();- this.pending_.set(key, promise);- try {- const result = await promise;- this.cache_.set(key, result);- return result;- }- finally {- this.pending_.delete(key);- }- }- get(key) {- return this.cache_.get(key);- }- has(key) {- return this.cache_.has(key);- }- delete(key) {- return this.cache_.delete(key);- }- clear() {- this.cache_.clear();- }- values() {- return this.cache_.values();- }-}--/**- * @file AssetServer.ts- * @brief Asset loading and caching system- */-// =============================================================================-// AssetServer-// =============================================================================-class AssetServer {- constructor(module) {- this.textureCache_ = new AsyncCache();- this.shaderCache_ = new AsyncCache();- this.jsonCache_ = new AsyncCache();- this.textCache_ = new AsyncCache();- this.binaryCache_ = new AsyncCache();- this.loadedSpines_ = new Set();- this.virtualFSPaths_ = new Set();- this.module_ = module;- this.canvas_ = this.createCanvas(512, 512);- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- const shaderLoader = {- load: (path) => this.loadShader(path),- get: (path) => this.shaderCache_.get(path),- };- this.materialLoader_ = new MaterialLoader(shaderLoader);- }- // =========================================================================- // Texture- // =========================================================================- /**- * Load texture with vertical flip (for Sprite/UI).- * OpenGL UV origin is bottom-left, so standard images need flipping.- */- async loadTexture(source) {- return this.loadTextureWithFlip(source, true);- }- /**- * Load texture without flip (for Spine).- * Spine runtime handles UV coordinates internally.- */- async loadTextureRaw(source) {- return this.loadTextureWithFlip(source, false);- }- getTexture(source) {- return this.textureCache_.get(this.textureCacheKey(source, true));- }- hasTexture(source) {- return this.textureCache_.has(this.textureCacheKey(source, true));- }- releaseTexture(source) {- const rm = this.module_.getResourceManager();- for (const flip of [true, false]) {- const key = this.textureCacheKey(source, flip);- const info = this.textureCache_.get(key);- if (info) {- rm.releaseTexture(info.handle);- this.textureCache_.delete(key);- }- }- }- releaseAll() {- const rm = this.module_.getResourceManager();- for (const info of this.textureCache_.values()) {- rm.releaseTexture(info.handle);- }- this.textureCache_.clear();- this.jsonCache_.clear();- this.textCache_.clear();- this.binaryCache_.clear();- }- setTextureMetadata(handle, border) {- const rm = this.module_.getResourceManager();- rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);- }- setTextureMetadataByPath(source, border) {- const info = this.textureCache_.get(this.textureCacheKey(source, true));- if (info) {- this.setTextureMetadata(info.handle, border);- return true;- }- return false;- }- // =========================================================================- // Spine- // =========================================================================- async loadSpine(skeletonPath, atlasPath, baseUrl) {- const cacheKey = `${skeletonPath}:${atlasPath}`;- if (this.loadedSpines_.has(cacheKey)) {- return { success: true };- }- try {- const atlasUrl = this.resolveUrl(atlasPath, baseUrl);- const atlasResponse = await fetch(atlasUrl);- if (!atlasResponse.ok) {- return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };- }- const atlasContent = await atlasResponse.text();- if (!this.writeToVirtualFS(atlasPath, atlasContent)) {- return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };- }- const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));- const textureNames = this.parseAtlasTextures(atlasContent);- for (const texName of textureNames) {- const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;- const texUrl = this.resolveUrl(texPath, baseUrl);- try {- const info = await this.loadTextureRaw(texUrl);- const rm = this.module_.getResourceManager();- rm.registerTextureWithPath(info.handle, texPath);- }- catch (err) {- console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);- }- }- const skelUrl = this.resolveUrl(skeletonPath, baseUrl);- const skelResponse = await fetch(skelUrl);- if (!skelResponse.ok) {- return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };- }- const isBinary = skeletonPath.endsWith('.skel');- const skelData = isBinary- ? new Uint8Array(await skelResponse.arrayBuffer())- : await skelResponse.text();- if (!this.writeToVirtualFS(skeletonPath, skelData)) {- return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };- }- this.loadedSpines_.add(cacheKey);- return { success: true };- }- catch (err) {- return { success: false, error: String(err) };- }- }- isSpineLoaded(skeletonPath, atlasPath) {- return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);- }- // =========================================================================- // Material & Shader- // =========================================================================- async loadMaterial(path, baseUrl) {- return this.materialLoader_.load(this.resolveUrl(path, baseUrl));- }- getMaterial(path, baseUrl) {- return this.materialLoader_.get(this.resolveUrl(path, baseUrl));- }- hasMaterial(path, baseUrl) {- return this.materialLoader_.has(this.resolveUrl(path, baseUrl));- }- async loadShader(path) {- return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));- }- // =========================================================================- // Generic File Loading- // =========================================================================- async loadJson(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchJson(url);- }- return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));- }- async loadText(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchText(url);- }- return this.textCache_.getOrLoad(url, () => this.fetchText(url));- }- async loadBinary(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchBinary(url);- }- return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));- }- // =========================================================================- // Scene & Batch- // =========================================================================- async loadScene(world, sceneData) {- return loadSceneWithAssets(world, sceneData, { assetServer: this });- }- async loadAll(manifest) {- const bundle = {- textures: new Map(),- materials: new Map(),- spine: new Map(),- json: new Map(),- text: new Map(),- binary: new Map(),- };- const promises = [];- if (manifest.textures) {- for (const path of manifest.textures) {- promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));- }- }- if (manifest.materials) {- for (const path of manifest.materials) {- promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));- }- }- if (manifest.spine) {- for (const desc of manifest.spine) {- const key = `${desc.skeleton}:${desc.atlas}`;- promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {- bundle.spine.set(key, result);- }));- }- }- if (manifest.json) {- for (const path of manifest.json) {- promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));- }- }- if (manifest.text) {- for (const path of manifest.text) {- promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));- }- }- if (manifest.binary) {- for (const path of manifest.binary) {- promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));- }- }- await Promise.all(promises);- return bundle;- }- // =========================================================================- // Private - Texture- // =========================================================================- textureCacheKey(source, flip) {- return `${source}:${flip ? 'f' : 'n'}`;- }- async loadTextureWithFlip(source, flip) {- const cacheKey = this.textureCacheKey(source, flip);- return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));- }- async loadTextureInternal(source, flip) {- const img = await this.loadImage(source);- return this.createTextureFromImage(img, flip);- }- async loadImage(source) {- return new Promise((resolve, reject) => {- const img = new Image();- img.crossOrigin = 'anonymous';- img.onload = async () => {- if (typeof createImageBitmap !== 'undefined') {- try {- const bitmap = await createImageBitmap(img, {- premultiplyAlpha: 'none',- colorSpaceConversion: 'none'- });- resolve(bitmap);- return;- }- catch {- // Fall back to Image element- }- }- resolve(img);- };- img.onerror = () => reject(new Error(`Failed to load image: ${source}`));- img.src = source;- });- }- createTextureFromImage(img, flip) {- const { width, height } = img;- if (this.canvas_.width < width || this.canvas_.height < height) {- this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));- this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));- }- this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);- this.ctx_.save();- if (flip) {- this.ctx_.translate(0, height);- this.ctx_.scale(1, -1);- }- this.ctx_.drawImage(img, 0, 0);- this.ctx_.restore();- const imageData = this.ctx_.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);- const rm = this.module_.getResourceManager();- const ptr = this.module_._malloc(pixels.length);- this.module_.HEAPU8.set(pixels, ptr);- const handle = rm.createTexture(width, height, ptr, pixels.length, 1);- this.module_._free(ptr);- return { handle, width, height };- }- unpremultiplyAlpha(pixels) {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }- // =========================================================================- // Private - Shader- // =========================================================================- async loadShaderInternal(path) {- const exists = await platformFileExists(path);- if (!exists) {- throw new Error(`Shader file not found: ${path}`);- }- const content = await platformReadTextFile(path);- if (!content) {- throw new Error(`Failed to read shader file: ${path}`);- }- const { vertex, fragment } = this.parseEsShader(content);- if (!vertex || !fragment) {- throw new Error(`Invalid shader format: ${path}`);- }- return Material.createShader(vertex, fragment);- }- parseEsShader(content) {- const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);- const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);- return {- vertex: vertexMatch?.[1].trim() ?? null,- fragment: fragmentMatch?.[1].trim() ?? null,- };- }- // =========================================================================- // Private - Generic Fetch- // =========================================================================- async fetchJson(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);- }- return response.json();- }- async fetchText(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch text: ${url} (${response.status})`);- }- return response.text();- }- async fetchBinary(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch binary: ${url} (${response.status})`);- }- return response.arrayBuffer();- }- // =========================================================================- // Private - Virtual FS- // =========================================================================- writeToVirtualFS(virtualPath, data) {- if (this.virtualFSPaths_.has(virtualPath)) {- return true;- }- const fs = this.module_.FS;- if (!fs) {- return false;- }- try {- this.ensureVirtualDir(virtualPath);- fs.writeFile(virtualPath, data);- this.virtualFSPaths_.add(virtualPath);- return true;- }- catch (e) {- console.error(`[AssetServer] Failed to write to virtual FS: ${virtualPath}`, e);- return false;- }- }- ensureVirtualDir(virtualPath) {- const fs = this.module_.FS;- if (!fs)- return;- const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));- if (!dir)- return;- const parts = dir.split('/').filter(p => p);- let currentPath = '';- for (const part of parts) {- currentPath = currentPath ? `${currentPath}/${part}` : part;- try {- const analysis = fs.analyzePath(currentPath);- if (!analysis.exists) {- fs.mkdir(currentPath);- }- }- catch {- try {- fs.mkdir(currentPath);- }- catch {- // Directory might already exist- }- }- }- }- // =========================================================================- // Private - Utilities- // =========================================================================- resolveUrl(path, baseUrl) {- if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {- return path;- }- const base = baseUrl ?? this.baseUrl;- return base ? `${base}/${path}` : `/${path}`;- }- createCanvas(width, height) {- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(width, height)- : document.createElement('canvas');- canvas.width = width;- canvas.height = height;- return canvas;- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- parseAtlasTextures(atlasContent) {- const textures = [];- for (const line of atlasContent.split('\n')) {- const trimmed = line.trim();- if (trimmed && !trimmed.includes(':') &&- (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {- textures.push(trimmed);- }- }- return textures;- }-}--/**- * @file AssetPlugin.ts- * @brief Plugin that provides asset loading capabilities- */-const Assets = defineResource(null, 'Assets');-// =============================================================================-// Asset Plugin-// =============================================================================-class AssetPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('AssetPlugin: No WASM module available');- return;- }- app.insertResource(Assets, new AssetServer(module));- }-}-const assetPlugin = new AssetPlugin();--/**- * @file PreviewPlugin.ts- * @brief Plugin for editor preview functionality- */-// =============================================================================-// PreviewPlugin-// =============================================================================-class PreviewPlugin {- constructor(sceneUrl) {- this.app_ = null;- this.loadPromise_ = null;- this.sceneUrl_ = sceneUrl;- }- build(app) {- this.app_ = app;- if (!app.hasResource(Assets)) {- app.addPlugin(assetPlugin);- }- this.loadPromise_ = this.loadScene();- }- /**- * @brief Wait for scene loading to complete- */- async waitForReady() {- if (this.loadPromise_) {- await this.loadPromise_;- }- }- async loadScene() {- 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();- const assets = this.app_.getResource(Assets);- await assets.loadScene(this.app_.world, sceneData);- this.ensureCamera();- }- catch (err) {- console.error('[PreviewPlugin] Failed to load scene:', err);- }- }- ensureCamera() {- if (!this.app_)- return;- const world = this.app_.world;- let hasActiveCamera = false;- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera.isActive) {- hasActiveCamera = true;- break;- }- }- if (!hasActiveCamera) {- console.warn('[PreviewPlugin] No active camera found, creating default camera');- const cameraEntity = world.spawn();- const transformData = {- position: { x: 0, y: 0, z: 10 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- };- world.insert(cameraEntity, LocalTransform, transformData);- const cameraData = {- isActive: true,- projectionType: 0,- fov: 60,- orthoSize: 540,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- priority: 0,- };- world.insert(cameraEntity, Camera, cameraData);- }- }-}--/**- * @file spine.ts- * @brief Spine animation control API- */-// =============================================================================-// SpineController-// =============================================================================-/**- * Controller for Spine skeletal animations- *- * @example- * ```typescript- * const spine = new SpineController(wasmModule);- *- * // Play animation- * spine.play(entity, 'run', true);- *- * // Queue next animation- * spine.addAnimation(entity, 'idle', true, 0.2);- *- * // Change skin- * spine.setSkin(entity, 'warrior');- *- * // Get bone position for effects- * const pos = spine.getBonePosition(entity, 'weapon');- * if (pos) {- * spawnEffect(pos.x, pos.y);- * }- *- * // Listen for events- * spine.on(entity, 'event', (e) => {- * if (e.eventName === 'footstep') {- * playSound('footstep');- * }- * });- * ```- */-class SpineController {- constructor(wasmModule) {- this.module_ = wasmModule;- this.listeners_ = new Map();- this.setupEventBridge();- }- // =========================================================================- // Animation Control- // =========================================================================- /**- * Plays an animation, replacing any current animation on the track- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop the animation- * @param track Animation track (default 0)- * @returns True if animation was set- */- play(entity, animation, loop = true, track = 0) {- if (!this.module_.spinePlayAnimation)- return false;- return this.module_.spinePlayAnimation(entity, animation, loop, track);- }- /**- * Adds an animation to the queue- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop- * @param delay Delay before starting (seconds)- * @param track Animation track (default 0)- * @returns True if animation was queued- */- addAnimation(entity, animation, loop = true, delay = 0, track = 0) {- if (!this.module_.spineAddAnimation)- return false;- return this.module_.spineAddAnimation(entity, animation, loop, delay, track);- }- /**- * Sets an empty animation to mix out the current animation- * @param entity Target entity- * @param mixDuration Duration of the mix out- * @param track Animation track (default 0)- */- setEmptyAnimation(entity, mixDuration = 0.2, track = 0) {- if (!this.module_.spineSetEmptyAnimation)- return;- this.module_.spineSetEmptyAnimation(entity, mixDuration, track);- }- /**- * Clears all animations on a track- * @param entity Target entity- * @param track Animation track (default 0)- */- clearTrack(entity, track = 0) {- if (!this.module_.spineClearTrack)- return;- this.module_.spineClearTrack(entity, track);- }- /**- * Clears all tracks- * @param entity Target entity- */- clearTracks(entity) {- if (!this.module_.spineClearTracks)- return;- this.module_.spineClearTracks(entity);- }- // =========================================================================- // Skin Control- // =========================================================================- /**- * Sets the current skin- * @param entity Target entity- * @param skinName Skin name- * @returns True if skin was set- */- setSkin(entity, skinName) {- if (!this.module_.spineSetSkin)- return false;- return this.module_.spineSetSkin(entity, skinName);- }- /**- * Gets available skin names- * @param entity Target entity- * @returns Array of skin names- */- getSkins(entity) {- if (!this.module_.spineGetSkins)- return [];- return this.module_.spineGetSkins(entity) || [];- }- // =========================================================================- // Queries- // =========================================================================- /**- * Gets available animation names- * @param entity Target entity- * @returns Array of animation names- */- getAnimations(entity) {- if (!this.module_.spineGetAnimations)- return [];- return this.module_.spineGetAnimations(entity) || [];- }- /**- * Gets the current animation on a track- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Animation name or null- */- getCurrentAnimation(entity, track = 0) {- if (!this.module_.spineGetCurrentAnimation)- return null;- return this.module_.spineGetCurrentAnimation(entity, track);- }- /**- * Gets the duration of an animation- * @param entity Target entity- * @param animation Animation name- * @returns Duration in seconds, or 0 if not found- */- getAnimationDuration(entity, animation) {- if (!this.module_.spineGetAnimationDuration)- return 0;- return this.module_.spineGetAnimationDuration(entity, animation);- }- /**- * Gets detailed track entry info- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Track entry info or null- */- getTrackEntry(entity, track = 0) {- if (!this.module_.spineGetTrackEntry)- return null;- return this.module_.spineGetTrackEntry(entity, track);- }- // =========================================================================- // Bone/Slot Access- // =========================================================================- /**- * Gets world position of a bone- * @param entity Target entity- * @param boneName Bone name- * @returns Position or null if not found- */- getBonePosition(entity, boneName) {- if (!this.module_.spineGetBonePosition)- return null;- const result = this.module_.spineGetBonePosition(entity, boneName);- if (!result)- return null;- return { x: result.x, y: result.y };- }- /**- * Gets world rotation of a bone in degrees- * @param entity Target entity- * @param boneName Bone name- * @returns Rotation in degrees or null- */- getBoneRotation(entity, boneName) {- if (!this.module_.spineGetBoneRotation)- return null;- return this.module_.spineGetBoneRotation(entity, boneName);- }- /**- * Sets the attachment for a slot- * @param entity Target entity- * @param slotName Slot name- * @param attachmentName Attachment name (null to clear)- */- setAttachment(entity, slotName, attachmentName) {- if (!this.module_.spineSetAttachment)- return;- this.module_.spineSetAttachment(entity, slotName, attachmentName || '');- }- // =========================================================================- // Events- // =========================================================================- /**- * Registers an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- on(entity, type, callback) {- if (!this.listeners_.has(entity)) {- this.listeners_.set(entity, new Map());- }- const entityListeners = this.listeners_.get(entity);- if (!entityListeners.has(type)) {- entityListeners.set(type, new Set());- }- entityListeners.get(type).add(callback);- }- /**- * Unregisters an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- off(entity, type, callback) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const typeListeners = entityListeners.get(type);- if (!typeListeners)- return;- typeListeners.delete(callback);- }- /**- * Removes all event listeners for an entity- * @param entity Target entity- */- removeAllListeners(entity) {- this.listeners_.delete(entity);- }- // =========================================================================- // Private- // =========================================================================- setupEventBridge() {- if (typeof window !== 'undefined') {- window.__esengine_spineEvent = (entity, eventData) => {- this.dispatchEvent(entity, eventData);- };- }- }- dispatchEvent(entity, eventData) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const event = {- type: eventData.type,- entity,- track: eventData.track ?? 0,- animation: eventData.animation ?? null,- eventName: eventData.eventName,- intValue: eventData.intValue,- floatValue: eventData.floatValue,- stringValue: eventData.stringValue,- };- const typeListeners = entityListeners.get(event.type);- if (typeListeners) {- typeListeners.forEach(callback => {- try {- callback(event);- }- catch (e) {- console.error('Error in Spine event callback:', e);- }- });- }- }-}-// =============================================================================-// Factory Function-// =============================================================================-/**- * Creates a SpineController instance- * @param wasmModule The ESEngine WASM module- * @returns SpineController instance- */-function createSpineController(wasmModule) {- return new SpineController(wasmModule);-}--const RenderTexture = {- create(options) {- const depth = options.depth ?? true;- const linear = options.filter === 'linear';- const flags = (depth ? 1 : 0) | (linear ? 2 : 0);- const handle = Renderer.createRenderTarget(options.width, options.height, flags);- const textureId = Renderer.getTargetTexture(handle);- return {- _handle: handle,- textureId,- width: options.width,- height: options.height,- };- },- release(rt) {- Renderer.releaseRenderTarget(rt._handle);- },- resize(rt, width, height) {- Renderer.releaseRenderTarget(rt._handle);- return RenderTexture.create({ width, height, depth: true });- },- begin(rt, viewProjection) {- Renderer.begin(viewProjection, rt._handle);- },- end() {- Renderer.end();- },- getDepthTexture(rt) {- return Renderer.getTargetDepthTexture(rt._handle);- },-};--let editorMode = false;-function setEditorMode(active) {- editorMode = active;-}-function isEditor() {- return editorMode;-}-function isRuntime() {- return !editorMode;-}--/**- * @file index.wechat.ts- * @brief ESEngine SDK - WeChat MiniGame entry point- */-// Initialize WeChat platform-initWeChatPlatform();-setPlatform(wechatAdapter);--exports.App = App;-exports.AssetPlugin = AssetPlugin;-exports.AssetServer = AssetServer;-exports.Assets = Assets;-exports.AsyncCache = AsyncCache;-exports.Camera = Camera;-exports.Canvas = Canvas;-exports.Children = Children;-exports.Commands = Commands;-exports.CommandsInstance = CommandsInstance;-exports.Draw = Draw;-exports.EntityCommands = EntityCommands;-exports.Geometry = Geometry;-exports.INVALID_ENTITY = INVALID_ENTITY;-exports.INVALID_TEXTURE = INVALID_TEXTURE;-exports.Input = Input;-exports.LocalTransform = LocalTransform;-exports.Material = Material;-exports.MaterialLoader = MaterialLoader;-exports.Mut = Mut;-exports.Parent = Parent;-exports.PostProcess = PostProcess;-exports.PreviewPlugin = PreviewPlugin;-exports.Query = Query;-exports.QueryInstance = QueryInstance;-exports.RenderPipeline = RenderPipeline;-exports.RenderTexture = RenderTexture;-exports.Renderer = Renderer;-exports.Res = Res;-exports.ResMut = ResMut;-exports.ShaderSources = ShaderSources;-exports.SpineAnimation = SpineAnimation;-exports.SpineController = SpineController;-exports.Sprite = Sprite;-exports.SystemRunner = SystemRunner;-exports.Text = Text;-exports.TextPlugin = TextPlugin;-exports.TextRenderer = TextRenderer;-exports.Time = Time;-exports.UIRect = UIRect;-exports.Velocity = Velocity;-exports.World = World;-exports.WorldTransform = WorldTransform;-exports.addStartupSystem = addStartupSystem;-exports.addSystem = addSystem;-exports.addSystemToSchedule = addSystemToSchedule;-exports.assetPlugin = assetPlugin;-exports.clearDrawCallbacks = clearDrawCallbacks;-exports.clearUserComponents = clearUserComponents;-exports.color = color;-exports.createSpineController = createSpineController;-exports.createWebApp = createWebApp;-exports.defineComponent = defineComponent;-exports.defineResource = defineResource;-exports.defineSystem = defineSystem;-exports.defineTag = defineTag;-exports.flushPendingSystems = flushPendingSystems;-exports.getComponentDefaults = getComponentDefaults;-exports.getPlatform = getPlatform;-exports.getPlatformType = getPlatformType;-exports.getUserComponent = getUserComponent;-exports.initDrawAPI = initDrawAPI;-exports.initGeometryAPI = initGeometryAPI;-exports.initMaterialAPI = initMaterialAPI;-exports.initPostProcessAPI = initPostProcessAPI;-exports.initRendererAPI = initRendererAPI;-exports.isBuiltinComponent = isBuiltinComponent;-exports.isEditor = isEditor;-exports.isPlatformInitialized = isPlatformInitialized;-exports.isRuntime = isRuntime;-exports.isTextureRef = isTextureRef;-exports.isWeChat = isWeChat;-exports.isWeb = isWeb;-exports.loadComponent = loadComponent;-exports.loadSceneData = loadSceneData;-exports.loadSceneWithAssets = loadSceneWithAssets;-exports.platformFetch = platformFetch;-exports.platformFileExists = platformFileExists;-exports.platformInstantiateWasm = platformInstantiateWasm;-exports.platformReadFile = platformReadFile;-exports.platformReadTextFile = platformReadTextFile;-exports.quat = quat;-exports.registerDrawCallback = registerDrawCallback;-exports.registerMaterialCallback = registerMaterialCallback;-exports.setEditorMode = setEditorMode;-exports.shutdownDrawAPI = shutdownDrawAPI;-exports.shutdownGeometryAPI = shutdownGeometryAPI;-exports.shutdownMaterialAPI = shutdownMaterialAPI;-exports.shutdownPostProcessAPI = shutdownPostProcessAPI;-exports.shutdownRendererAPI = shutdownRendererAPI;-exports.textPlugin = textPlugin;-exports.unregisterDrawCallback = unregisterDrawCallback;-exports.updateCameraAspectRatio = updateCameraAspectRatio;-exports.vec2 = vec2;-exports.vec3 = vec3;-exports.vec4 = vec4;-exports.wxFileExists = wxFileExists;-exports.wxFileExistsSync = wxFileExistsSync;-exports.wxGetImagePixels = wxGetImagePixels;-exports.wxLoadImage = wxLoadImage;-exports.wxLoadImagePixels = wxLoadImagePixels;-exports.wxReadFile = wxReadFile;-exports.wxReadTextFile = wxReadTextFile;-exports.wxWriteFile = wxWriteFile;+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function n(e){return t().readTextFile(e)}async function s(e){return t().fileExists(e)}function o(e,t){return new Promise((r,n)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function i(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let a=null;function l(){return a||(a=wx.getFileSystemManager()),a}function c(e){return new Promise((t,r)=>{l().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function u(e,t="utf-8"){return new Promise((r,n)=>{l().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function h(e){return new Promise(t=>{l().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let d=null,p=null;function f(e){return new Promise((t,r)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function _(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return d||(d=wx.createCanvas(),d.width=e,d.height=t,p=d.getContext("2d")),(d.width<e||d.height<t)&&(d.width=Math.max(d.width,e),d.height=Math.max(d.height,t)),{canvas:d,ctx:p}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const o=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(o.data.buffer)}}let m=!1;const x=new class{constructor(){this.name="wechat"}async fetch(e,t){return o(e,t)}async readFile(e){return c(e)}async readTextFile(e){return u(e)}async fileExists(e){return h(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return i(e,t)}},g=4294967295;let y=0;function w(e,t){const r=++y;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function v(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function S(e,t){const r=v(),n=r.get(e);if(n)return n;const s=w(e,t);return r.set(e,s),C(e,t,!1),s}function T(e){return v().get(e)}function C(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function P(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const b=P("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),E=P("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),M=P("Sprite",{texture:g,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),R=P("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),F=P("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),I=P("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),U=P("Parent",{entity:0}),z=P("Children",{entities:[]}),W=P("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),$={LocalTransform:b,WorldTransform:E,Sprite:M,Camera:R,Canvas:F,Velocity:I,Parent:U,Children:z,SpineAnimation:W};let B=0;function k(e,t){const r=++B;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class L{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 D{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new L(this.get(e),t=>this.set(e,t))}}const O=k({delta:0,elapsed:0,frameCount:0},"Time"),G=k({keysDown:new Set,keysPressed:new Set,keysReleased:new Set,mouseX:0,mouseY:0,mouseButtons:new Set},"Input");function N(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class V{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return N(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:n}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),o=[...s,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,l=[];try{for(const e of i){if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data);l=[];let r=!1;for(const t of n)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=s.map(t=>this.world_.get(e,t));for(const e of t)l.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}class H{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let r;return r=A(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class j{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new H(this,null)}entity(e){return new H(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var X;exports.Schedule=void 0,(X=exports.Schedule||(exports.Schedule={}))[X.Startup=0]="Startup",X[X.First=1]="First",X[X.PreUpdate=2]="PreUpdate",X[X.Update=3]="Update",X[X.PostUpdate=4]="PostUpdate",X[X.Last=5]="Last",X[X.FixedPreUpdate=10]="FixedPreUpdate",X[X.FixedUpdate=11]="FixedUpdate",X[X.FixedPostUpdate=12]="FixedPostUpdate";let q=0;function J(e,t,r){const n=++q;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function K(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Y{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof j&&e.flush()}resolveParam(e){switch(e._type){case"query":return new V(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new j(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Q{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return A(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const n={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,n)}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const n=t.create(r);return this.getStorage(t).set(e,n),n}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let n=!0;for(const t of e)if(!this.has(r,t)){n=!1;break}n&&t.push(r)}return t}}var Z,ee,te;exports.TextAlign=void 0,(Z=exports.TextAlign||(exports.TextAlign={}))[Z.Left=0]="Left",Z[Z.Center=1]="Center",Z[Z.Right=2]="Right",exports.TextVerticalAlign=void 0,(ee=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ee.Top=0]="Top",ee[ee.Middle=1]="Middle",ee[ee.Bottom=2]="Bottom",exports.TextOverflow=void 0,(te=exports.TextOverflow||(exports.TextOverflow={}))[te.Visible=0]="Visible",te[te.Clip=1]="Clip",te[te.Ellipsis=2]="Ellipsis";const re=S("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class ne{constructor(e){this.cache=new Map,this.module=e,"undefined"!=typeof OffscreenCanvas?(this.canvas=new OffscreenCanvas(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})):(this.canvas=document.createElement("canvas"),this.canvas.width=512,this.canvas.height=512,this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}))}renderText(e,t){const r=this.ctx,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),p=s?Math.ceil(o):h+2*u,f=s?Math.ceil(i):d+2*u;if(s&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/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 _=Math.round(255*e.color.x),m=Math.round(255*e.color.y),x=Math.round(255*e.color.z),g=e.color.w;r.clearRect(0,0,n.width,n.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${_}, ${m}, ${x}, ${g})`,s&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=l.length*c;let w;if(s)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of 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}r.fillText(t,n,v),v+=c}s&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),T=new Uint8Array(S.data.buffer),C=this.flipVertically(T,p,f),P=this.module.getResourceManager(),A=this.module._malloc(C.length);this.module.HEAPU8.set(C,A);const b=P.createTexture(p,f,A,C.length,1);return this.module._free(A),{textureHandle:b,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const s=this.renderText(t,r);return this.cache.set(e,s),s}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),n=[];for(const e of r){if(!e){n.push("");continue}let r="";for(const s of e){const e=r+s;this.ctx.measureText(e).width>t&&r?(n.push(r),r=s):r=e}r&&n.push(r)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const se=S("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class oe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new ne(t),n=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,J([],()=>{const e=n.getEntitiesWithComponents([re]);for(const t of e){const e=n.get(t,re);if(!e.dirty)continue;n.has(t,M)||n.insert(t,M,{texture:g,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=n.has(t,se)?n.get(t,se):null,o=r.renderForEntity(t,e,s),i=n.get(t,M);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},n.insert(t,M,i),e.dirty=!1}}))}}const ie=new oe;var ae;function le(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(ae=exports.BlendMode||(exports.BlendMode={}))[ae.Normal=0]="Normal",ae[ae.Additive=1]="Additive",ae[ae.Multiply=2]="Multiply",ae[ae.Screen=3]="Screen",ae[ae.PremultipliedAlpha=4]="PremultipliedAlpha";let ce=null,ue=null,he=1;const de=new Map;function pe(e){ce=e,ue=e.getResourceManager(),ve()}function fe(){0!==ge&&ce&&(ce._free(ge),ge=0),de.clear(),he=1,xe=!1,ue=null,ce=null}function _e(){if(!ue)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ue}const me={createShader:(e,t)=>_e().createShader(e,t),releaseShader(e){e>0&&_e().releaseShader(e)},create(e){const t=he++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return de.set(t,r),t},get:e=>de.get(e),setUniform(e,t,r){const n=de.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=de.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=de.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=de.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=de.get(e);r&&(r.depthTest=t)},getShader(e){const t=de.get(e);return t?.shader??0},release(e){de.delete(e)},isValid:e=>de.has(e),createFromAsset(e,t){const r={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)r[t]=n;else if("object"==typeof n&&null!==n){const e=n;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=de.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=he++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return de.set(r,n),r},toAssetData(e,t){const r=de.get(e);if(!r)return null;const n={};for(const[e,t]of r.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:n}},getUniforms(e){const t=de.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let xe=!1,ge=0;const ye=4096;function we(e){const t=(0===ge&&ce&&(ge=ce._malloc(ye)),ge);if(0===t||!ce)return{ptr:0,count:0};let r=0,n=0;const s=ce.HEAPU8,o=ce.HEAPU32,i=ce.HEAPF32;for(const[a,l]of e){if(r+128>ye)break;const e=(new TextEncoder).encode(a),c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,s.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function ve(){if(!ce||xe)return;ce.materialDataProvider=(e,t,r,n,s)=>{const o=de.get(e);if(!o)return ce.HEAPU32[t>>2]=0,ce.HEAPU32[r>>2]=0,ce.HEAPU32[n>>2]=0,void(ce.HEAPU32[s>>2]=0);ce.HEAPU32[t>>2]=o.shader,ce.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=we(o.uniforms);ce.HEAPU32[n>>2]=i,ce.HEAPU32[s>>2]=a},xe=!0}const Se={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"};let Te=null,Ce=0,Pe=0,Ae=0;const be=new Float32Array(256);function Ee(e){Te=e,Ce=Te._malloc(64),Pe=Te._malloc(64),Ae=Te._malloc(1024)}function Me(){Te&&(Ce&&(Te._free(Ce),Ce=0),Pe&&(Te._free(Pe),Pe=0),Ae&&(Te._free(Ae),Ae=0)),Te=null}function Re(){if(!Te)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Te}const Fe={x:1,y:1,z:1,w:1},Ie={begin(e){const t=Re();t.HEAPF32.set(e,Ce/4),t.draw_begin(Ce)},end(){Re().draw_end()},line(e,t,r,n=1){Re().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rect(e,t,r,n=!0){Re().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rectOutline(e,t,r,n=1){Re().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},circle(e,t,r,n=!0,s=32){Re().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},circleOutline(e,t,r,n=1,s=32){Re().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=Fe){Re().draw_texture(e.x,e.y,t.x,t.y,r,n.x,n.y,n.z,n.w)},textureRotated(e,t,r,n,s=Fe){Re().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){Re().draw_setLayer(e)},setDepth(e){Re().draw_setDepth(e)},getDrawCallCount:()=>Te?Te.draw_getDrawCallCount():0,getPrimitiveCount:()=>Te?Te.draw_getPrimitiveCount():0,setBlendMode(e){Re().draw_setBlendMode(e)},setDepthTest(e){Re().draw_setDepthTest(e)},drawMesh(e,t,r){const n=Re();n.HEAPF32.set(r,Pe/4),n.draw_mesh(e,t,Pe)},drawMeshWithMaterial(e,t,r){const n=Re(),s=me.get(t);if(!s)return;if(Ie.setBlendMode(s.blendMode),Ie.setDepthTest(s.depthTest),0===s.uniforms.size)return void Ie.drawMesh(e,s.shader,r);n.HEAPF32.set(r,Pe/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=ze(e);if(!(r<0)){if(le(t))be[o++]=10,be[o++]=r,be[o++]=t.slot??i++,be[o++]=t.textureId;else if("number"==typeof t)be[o++]=1,be[o++]=r,be[o++]=t;else if(Array.isArray(t)){be[o++]=t.length,be[o++]=r;for(let e=0;e<t.length;e++)be[o++]=t[e]}else"w"in t?(be[o++]=4,be[o++]=r,be[o++]=t.x,be[o++]=t.y,be[o++]=t.z,be[o++]=t.w):"z"in t?(be[o++]=3,be[o++]=r,be[o++]=t.x,be[o++]=t.y,be[o++]=t.z):(be[o++]=2,be[o++]=r,be[o++]=t.x,be[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(be.subarray(0,o),Ae/4),n.draw_meshWithUniforms(e,s.shader,Pe,Ae,o)):n.draw_mesh(e,s.shader,Pe)}},Ue={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 ze(e){return Ue[e]??-1}var We;exports.DataType=void 0,(We=exports.DataType||(exports.DataType={}))[We.Float=1]="Float",We[We.Float2=2]="Float2",We[We.Float3=3]="Float3",We[We.Float4=4]="Float4",We[We.Int=5]="Int",We[We.Int2=6]="Int2",We[We.Int3=7]="Int3",We[We.Int4=8]="Int4";let $e=null,Be=0,ke=0,Le=0;function De(e){$e=e,Be=$e._malloc(262144),ke=$e._malloc(65536),Le=$e._malloc(256)}function Oe(){$e&&(Be&&$e._free(Be),ke&&$e._free(ke),Le&&$e._free(Le),Be=0,ke=0,Le=0),$e=null}function Ge(){if(!$e)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return $e}const Ne={create(e){const t=Ge(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Be/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Le,s).set(o),t.geometry_init(r,Be,n,Le,s,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ke,n).set(e.indices),t.geometry_setIndices16(r,ke,n)}else{new Uint32Array(t.HEAPU8.buffer,ke,n).set(e.indices),t.geometry_setIndices32(r,ke,n)}}return r},updateVertices(e,t,r=0){const n=Ge(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,Be/4),n.geometry_updateVertices(e,Be,s,r)},release(e){e>0&&Ge().geometry_release(e)},isValid:e=>!(!$e||e<=0)&&$e.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return Ne.create({vertices:new Float32Array([-r,-n,0,0,r,-n,1,0,r,n,1,1,-r,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,l=(Math.sin(s)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ne.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,n=-1/0,s=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-r)/(s-r);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Ne.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 Ve=null;function He(e){Ve=e}function je(){Ve&&qe.isInitialized()&&qe.shutdown(),Ve=null}function Xe(){if(!Ve)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ve}const qe={init:(e,t)=>Xe().postprocess_init(e,t),shutdown(){Xe().postprocess_shutdown()},resize(e,t){Xe().postprocess_resize(e,t)},addPass:(e,t)=>Xe().postprocess_addPass(e,t),removePass(e){Xe().postprocess_removePass(e)},setEnabled(e,t){Xe().postprocess_setPassEnabled(e,t)},isEnabled:e=>Xe().postprocess_isPassEnabled(e),setUniform(e,t,r){Xe().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Xe().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Xe().postprocess_begin()},end(){Xe().postprocess_end()},getPassCount:()=>Xe().postprocess_getPassCount(),isInitialized:()=>!!Ve&&Ve.postprocess_isInitialized(),setBypass(e){Xe().postprocess_setBypass(e)},isBypassed:()=>!Ve||Ve.postprocess_isBypassed(),createBlur:()=>me.createShader(Je,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>me.createShader(Je,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>me.createShader(Je,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>me.createShader(Je,"#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")},Je="#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 Ke;exports.RenderStage=void 0,(Ke=exports.RenderStage||(exports.RenderStage={}))[Ke.Background=0]="Background",Ke[Ke.Opaque=1]="Opaque",Ke[Ke.Transparent=2]="Transparent",Ke[Ke.Overlay=3]="Overlay";let Ye=null,Qe=0;function Ze(e){Ye=e,Qe=Ye._malloc(64)}function et(){Ye&&Qe&&(Ye._free(Qe),Qe=0),Ye=null}const tt={init(e,t){Ye?.renderer_init(e,t)},resize(e,t){Ye?.renderer_resize(e,t)},begin(e,t){Ye&&Qe&&(Ye.HEAPF32.set(e,Qe/4),Ye.renderer_begin(Qe,t??0))},end(){Ye?.renderer_end()},submitSprites(e){Ye&&Ye.renderer_submitSprites(e._cpp)},submitSpine(e){Ye&&Ye.renderer_submitSpine(e._cpp)},setStage(e){Ye?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>Ye?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){Ye?.renderer_releaseTarget(e)},getTargetTexture:e=>Ye?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ye?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){Ye?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>Ye?{drawCalls:Ye.renderer_getDrawCalls(),triangles:Ye.renderer_getTriangles(),sprites:Ye.renderer_getSprites(),spine:Ye.renderer_getSpine(),meshes:Ye.renderer_getMeshes(),culled:Ye.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}},rt=new Map;function nt(e){rt.delete(e)}class st{render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;tt.resize(n,s);const i=qe.isInitialized()&&qe.getPassCount()>0&&!qe.isBypassed();i&&(qe.resize(n,s),qe.begin()),tt.begin(r),tt.submitSprites(t),tt.submitSpine(t),tt.end();const a=rt;if(a.size>0){Ie.begin(r);const e=[];for(const[t,r]of a.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}Ie.end();for(const t of e)nt(t)}i&&qe.end()}}class ot{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.module_=null,this.mainLoop=()=>{if(!this.running_)return;const e=performance.now(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;this.updateTime(r),this.runSchedule(exports.Schedule.First),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 Q,this.resources_=new D;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ot}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Y(this.world_,this.resources_),this.resources_.insert(O,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=performance.now(),this.mainLoop())}quit(){this.running_=!1,et(),je(),Oe(),fe(),Me()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(O),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(O,r)}}const it=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function at(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,l=n-r,c=o-s;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+r)/l,i[14]=-(o+s)/c,i[15]=1,i}function lt(e,t,r,n){const s=new Float32Array(16),o=1/Math.tan(e/2),i=r-n;return s[0]=o/t,s[5]=o,s[10]=(n+r)/i,s[11]=-1,s[14]=2*n*r/i,s}function ct(e,t,r){const n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n[12]=-e,n[13]=-t,n[14]=-r,n}function ut(e,t){const r=new Float32Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)r[4*s+n]=e[0+n]*t[4*s+0]+e[4+n]*t[4*s+1]+e[8+n]*t[4*s+2]+e[12+n]*t[4*s+3];return r}class ht{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const n=this.loadInternal(e);this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(me.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())me.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await s(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const o=JSON.parse(r);if("material"!==o.type)throw new Error(`Invalid material file type: ${o.type}`);const i=this.resolveShaderPath(e,o.shader),a=await this.shaderLoader_.load(i);return{handle:me.createFromAsset(o,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}async function dt(e,t,r){const n=new Map,s=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();n.set(i.id,t);for(const n of i.components){if("Sprite"===n.type&&s){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await s.loadTexture(n);e.texture=r.handle,o.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===n.type&&s){const e=n.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await s.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}pt(e,t,n)}}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function pt(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,b,n);break;case"Sprite":e.insert(t,M,n);break;case"Camera":e.insert(t,R,n);break;case"Canvas":e.insert(t,F,n);break;case"Text":e.insert(t,re,n);break;case"SpineAnimation":e.insert(t,W,n);break;case"UIRect":e.insert(t,se,n);break;default:{const s=T(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}class ft{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const n=this.pending_.get(e);if(n)return n;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class _t{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.module_=e,this.canvas_=this.createCanvas(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ht(t)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const n=this.textureCacheKey(e,r),s=this.textureCache_.get(n);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const s=this.resolveUrl(t,r),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),l=this.parseAtlasTextures(i);for(const e of l){const t=a?`${a}/${e}`:e,n=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,r),u=await fetch(c);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${c}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(n),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return dt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const n of e.textures)r.push(this.loadTexture(n).then(e=>{t.textures.set(n,e)}));if(e.materials)for(const n of e.materials)r.push(this.loadMaterial(n).then(e=>{t.materials.set(n,e)}));if(e.spine)for(const n of e.spine){const e=`${n.skeleton}:${n.atlas}`;r.push(this.loadSpine(n.skeleton,n.atlas,n.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const n of e.json)r.push(this.loadJson(n).then(e=>{t.json.set(n,e)}));if(e.text)for(const n of e.text)r.push(this.loadText(n).then(e=>{t.text.set(n,e)}));if(e.binary)for(const n of e.binary)r.push(this.loadBinary(n).then(e=>{t.binary.set(n,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}createTextureFromImage(e,t){const{width:r,height:n}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,r,n,t):this.createTextureFallback(e,r,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,n,s){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,n),width:r,height:n}}createTextureFallback(e,t,r,n){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const n=255/r;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){if(!await s(e))throw new Error(`Shader file not found: ${e}`);const t=await n(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(t);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return me.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}async fetchJson(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const n=r.split("/").filter(e=>e);let s="";for(const e of n){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}createCanvas(e,t){const r="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas");return r.width=e,r.height=t,r}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const mt=k(null,"Assets");class xt{build(e){const t=e.wasmModule;t?e.insertResource(mt,new _t(t)):console.warn("AssetPlugin: No WASM module available")}}const gt=new xt;class yt{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,r=!0,n=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,r,n)}addAnimation(e,t,r=!0,n=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,r,n,s)}setEmptyAnimation(e,t=.2,r=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,r)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const r=this.module_.spineGetBonePosition(e,t);return r?{x:r.x,y:r.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,r){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,r||"")}on(e,t,r){this.listeners_.has(e)||this.listeners_.set(e,new Map);const n=this.listeners_.get(e);n.has(t)||n.set(t,new Set),n.get(t).add(r)}off(e,t,r){const n=this.listeners_.get(e);if(!n)return;const s=n.get(t);s&&s.delete(r)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const r=this.listeners_.get(e);if(!r)return;const n={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=r.get(n.type);s&&s.forEach(e=>{try{e(n)}catch(e){console.error("Error in Spine event callback:",e)}})}}const wt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=tt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:tt.getTargetTexture(r),width:e.width,height:e.height}},release(e){tt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(tt.releaseRenderTarget(e._handle),wt.create({width:t,height:r,depth:!0})),begin(e,t){tt.begin(t,e._handle)},end(){tt.end()},getDepthTexture:e=>tt.getTargetDepthTexture(e._handle)};let vt=!1;var St;m||(m=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await o(r,n);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return i(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}),console.log("[ESEngine] WeChat platform initialized")),e=St=x,console.log(`[ESEngine] Platform: ${St.name}`),exports.App=ot,exports.AssetPlugin=xt,exports.AssetServer=_t,exports.Assets=mt,exports.AsyncCache=ft,exports.Camera=R,exports.Canvas=F,exports.Children=z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=j,exports.Draw=Ie,exports.EntityCommands=H,exports.Geometry=Ne,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=g,exports.Input=G,exports.LocalTransform=b,exports.Material=me,exports.MaterialLoader=ht,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=U,exports.PostProcess=qe,exports.PreviewPlugin=class{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(mt)||e.addPlugin(gt),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=this.app_.getResource(mt);await n.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([R]);for(const n of r){if(e.get(n,R).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),r={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(t,b,r);const n={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,R,n)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{N(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)},exports.QueryInstance=V,exports.RenderPipeline=st,exports.RenderTexture=wt,exports.Renderer=tt,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=Se,exports.SpineAnimation=W,exports.SpineController=yt,exports.Sprite=M,exports.SystemRunner=Y,exports.Text=re,exports.TextPlugin=oe,exports.TextRenderer=ne,exports.Time=O,exports.UIRect=se,exports.Velocity=I,exports.World=Q,exports.WorldTransform=E,exports.addStartupSystem=function(e){K().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){K().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){K().push({schedule:e,system:t})},exports.assetPlugin=gt,exports.clearDrawCallbacks=function(){rt.clear()},exports.clearUserComponents=function(){v().clear()},exports.color=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),exports.createSpineController=function(e){return new yt(e)},exports.createWebApp=function(e,t){const r=ot.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ee(e),pe(e),De(e),He(e),Ze(e);const s=new st;let o=performance.now();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=i(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const n=e.getCamera(s);if(!n.isActive)continue;const o=e.getLocalTransform(s),i=t/r;let a;if(1===n.projectionType){const e=n.orthoSize,t=e*i;a=at(-t,t,-e,e,-n.farPlane,n.farPlane)}else a=lt(n.fov*Math.PI/180,i,n.nearPlane,n.farPlane);return ut(a,ct(o.position.x,o.position.y,o.position.z))}return it}(n,e,t),a=(performance.now()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:a})}};return r.addSystemToSchedule(exports.Schedule.Last,a),r.addPlugin(ie),r},exports.defineComponent=S,exports.defineResource=k,exports.defineSystem=J,exports.defineTag=function(e){const t=v(),r=t.get(e);if(r)return r;const n=w(e,{});return t.set(e,n),C(e,{},!0),n},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=$[e];if(t)return{...t._default};const r=T(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=T,exports.initDrawAPI=Ee,exports.initGeometryAPI=De,exports.initMaterialAPI=pe,exports.initPostProcessAPI=He,exports.initRendererAPI=Ze,exports.isBuiltinComponent=A,exports.isEditor=function(){return vt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!vt},exports.isTextureRef=le,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=pt,exports.loadSceneData=function(e,t){const r=new Map;for(const n of t.entities){const t=e.spawn();r.set(n.id,t);for(const r of n.components)pt(e,t,r)}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return r},exports.loadSceneWithAssets=dt,exports.platformFetch=r,exports.platformFileExists=s,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=async function(e){return t().readFile(e)},exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n}),exports.registerDrawCallback=function(e,t){rt.set(e,t)},exports.registerMaterialCallback=ve,exports.setEditorMode=function(e){vt=e},exports.shutdownDrawAPI=Me,exports.shutdownGeometryAPI=Oe,exports.shutdownMaterialAPI=fe,exports.shutdownPostProcessAPI=je,exports.shutdownRendererAPI=et,exports.textPlugin=ie,exports.unregisterDrawCallback=nt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([R]);for(const n of r){const r=e.get(n,R);r&&(r.aspectRatio=t,e.insert(n,R,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),exports.wxFileExists=h,exports.wxFileExistsSync=function(e){const t=l();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=_,exports.wxLoadImage=f,exports.wxLoadImagePixels=async function(e,t=!0){return _(await f(e),t)},exports.wxReadFile=c,exports.wxReadTextFile=u,exports.wxWriteFile=function(e,t){return new Promise((r,n)=>{l().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex ab44e3fc8..fcc6de9c5 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,4285 +1,2 @@-/**- * @file base.ts- * @brief Base platform adapter - no platform-specific code- */-// =============================================================================-// Platform Instance (set by entry point)-// =============================================================================-let currentPlatform = null;-/**- * Set the platform adapter (called by entry point)- */-function setPlatform(adapter) {- currentPlatform = adapter;- console.log(`[ESEngine] Platform: ${adapter.name}`);-}-/**- * Get the current platform adapter- * @throws Error if platform not initialized- */-function getPlatform() {- if (!currentPlatform) {- throw new Error('[ESEngine] Platform not initialized. ' +- 'Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');- }- return currentPlatform;-}-/**- * Check if platform is initialized- */-function isPlatformInitialized() {- return currentPlatform !== null;-}-/**- * Get platform type- */-function getPlatformType() {- return currentPlatform?.name ?? null;-}-/**- * Check if running on WeChat- */-function isWeChat() {- return currentPlatform?.name === 'wechat';-}-/**- * Check if running on Web- */-function isWeb() {- return currentPlatform?.name === 'web';-}-// =============================================================================-// Convenience Functions-// =============================================================================-async function platformFetch(url, options) {- return getPlatform().fetch(url, options);-}-async function platformReadFile(path) {- return getPlatform().readFile(path);-}-async function platformReadTextFile(path) {- return getPlatform().readTextFile(path);-}-async function platformFileExists(path) {- return getPlatform().fileExists(path);-}-async function platformInstantiateWasm(pathOrBuffer, imports) {- return getPlatform().instantiateWasm(pathOrBuffer, imports);-}--/**- * @file fetch.ts- * @brief Fetch polyfill for WeChat MiniGame using wx.request- */-// =============================================================================-// WeChat Fetch Implementation-// =============================================================================-function wxFetch(url, options) {- return new Promise((resolve, reject) => {- const responseType = options?.responseType ?? 'text';- wx.request({- url,- method: (options?.method ?? 'GET'),- data: options?.body,- header: options?.headers,- responseType: responseType === 'arraybuffer' ? 'arraybuffer' : 'text',- timeout: options?.timeout,- success: (res) => {- const ok = res.statusCode >= 200 && res.statusCode < 300;- const headers = {};- if (res.header) {- for (const key of Object.keys(res.header)) {- headers[key.toLowerCase()] = res.header[key];- }- }- resolve({- ok,- status: res.statusCode,- statusText: ok ? 'OK' : 'Error',- headers,- json: () => {- if (typeof res.data === 'string') {- return Promise.resolve(JSON.parse(res.data));- }- return Promise.resolve(res.data);- },- text: () => {- if (typeof res.data === 'string') {- return Promise.resolve(res.data);- }- return Promise.resolve(JSON.stringify(res.data));- },- arrayBuffer: () => {- if (res.data instanceof ArrayBuffer) {- return Promise.resolve(res.data);- }- // Convert string to ArrayBuffer- const encoder = new TextEncoder();- const data = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);- return Promise.resolve(encoder.encode(data).buffer);- },- });- },- fail: (err) => {- reject(new Error(`wx.request failed: ${err.errMsg}`));- },- });- });-}-// =============================================================================-// Global Fetch Polyfill-// =============================================================================-function polyfillFetch() {- if (typeof globalThis.fetch === 'undefined') {- globalThis.fetch = async (input, init) => {- const url = typeof input === 'string' ? input : input.toString();- const options = {- method: init?.method ?? 'GET',- headers: init?.headers,- body: init?.body,- };- const response = await wxFetch(url, options);- // Return a Response-like object- return {- ok: response.ok,- status: response.status,- statusText: response.statusText,- headers: new Headers(response.headers),- json: () => response.json(),- text: () => response.text(),- arrayBuffer: () => response.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: false,- redirected: false,- type: 'basic',- url,- };- };- }-}--/**- * @file wasm.ts- * @brief WebAssembly adapter for WeChat MiniGame using WXWebAssembly- */-// =============================================================================-// WeChat WASM Implementation-// =============================================================================-/**- * Instantiate WASM using WXWebAssembly- * Note: WeChat requires path to be a string (package-relative path), not ArrayBuffer- */-async function wxInstantiateWasm(path, imports) {- if (typeof WXWebAssembly === 'undefined') {- throw new Error('WXWebAssembly is not available. Requires WeChat base library >= 2.13.0');- }- // WeChat requires the path to be a package-relative path string- // e.g., "esengine.wasm" not "/esengine.wasm" or ArrayBuffer- const normalizedPath = path.startsWith('/') ? path.slice(1) : path;- try {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const result = await WXWebAssembly.instantiate(normalizedPath, imports);- return {- // WXWebAssembly.instantiate returns { instance, module } but types are slightly different- instance: result.instance ?? result,- module: result.module,- };- }- catch (err) {- const message = err instanceof Error ? err.message : String(err);- throw new Error(`WXWebAssembly.instantiate failed for "${normalizedPath}": ${message}`);- }-}-// =============================================================================-// Global WebAssembly Polyfill-// =============================================================================-/**- * Polyfill global WebAssembly with WXWebAssembly- * This allows existing code using WebAssembly.instantiate to work on WeChat- */-function polyfillWebAssembly() {- if (typeof WXWebAssembly !== 'undefined' && typeof WebAssembly === 'undefined') {- globalThis.WebAssembly = {- instantiate: async (bufferOrPath, imports) => {- if (typeof bufferOrPath !== 'string') {- throw new Error('WeChat WXWebAssembly requires a file path string, not ArrayBuffer. ' +- 'Use platform adapter instead of direct WebAssembly.instantiate.');- }- return wxInstantiateWasm(bufferOrPath, imports ?? {});- },- 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,- };- }-}--/**- * @file fs.ts- * @brief File system adapter for WeChat MiniGame- */-/// <reference types="minigame-api-typings" />-// =============================================================================-// WeChat File System-// =============================================================================-let fsManager = null;-function getFileSystemManager() {- if (!fsManager) {- fsManager = wx.getFileSystemManager();- }- return fsManager;-}-/**- * Read file as ArrayBuffer (async)- */-function wxReadFile(path) {- return new Promise((resolve, reject) => {- const fs = getFileSystemManager();- fs.readFile({- filePath: path,- success: (res) => {- resolve(res.data);- },- fail: (err) => {- reject(new Error(`Failed to read file "${path}": ${err.errMsg}`));- },- });- });-}-/**- * Read file as string (async)- */-function wxReadTextFile(path, encoding = 'utf-8') {- return new Promise((resolve, reject) => {- const fs = getFileSystemManager();- fs.readFile({- filePath: path,- encoding,- success: (res) => {- resolve(res.data);- },- fail: (err) => {- reject(new Error(`Failed to read file "${path}": ${err.errMsg}`));- },- });- });-}-/**- * Check if file exists- */-function wxFileExists(path) {- return new Promise((resolve) => {- const fs = getFileSystemManager();- fs.access({- path,- success: () => resolve(true),- fail: () => resolve(false),- });- });-}-/**- * Check if file exists (sync)- */-function wxFileExistsSync(path) {- const fs = getFileSystemManager();- try {- fs.accessSync(path);- return true;- }- catch {- return false;- }-}-/**- * Write file- */-function wxWriteFile(path, data) {- return new Promise((resolve, reject) => {- const fs = getFileSystemManager();- fs.writeFile({- filePath: path,- data,- success: () => resolve(),- fail: (err) => {- reject(new Error(`Failed to write file "${path}": ${err.errMsg}`));- },- });- });-}--/**- * @file image.ts- * @brief WeChat MiniGame image loading utilities- */-/// <reference types="minigame-api-typings" />-// =============================================================================-// Canvas Management-// =============================================================================-let offscreenCanvas = null;-let offscreenCtx = null;-function getOffscreenCanvas(width, height) {- if (!offscreenCanvas) {- offscreenCanvas = wx.createCanvas();- offscreenCanvas.width = width;- offscreenCanvas.height = height;- offscreenCtx = offscreenCanvas.getContext('2d');- }- if (offscreenCanvas.width < width || offscreenCanvas.height < height) {- offscreenCanvas.width = Math.max(offscreenCanvas.width, width);- offscreenCanvas.height = Math.max(offscreenCanvas.height, height);- }- return { canvas: offscreenCanvas, ctx: offscreenCtx };-}-// =============================================================================-// Image Loading-// =============================================================================-/**- * Load an image from a file path- * @param path - File path relative to game root- */-function wxLoadImage(path) {- return new Promise((resolve, reject) => {- const img = wx.createImage();- img.onload = () => resolve(img);- img.onerror = (err) => reject(new Error(`Failed to load image: ${path}, ${err}`));- img.src = path;- });-}-/**- * Extract pixel data from an image- * @param img - Loaded image object- * @param flipY - Whether to flip the image vertically (default: true for OpenGL)- */-function wxGetImagePixels(img, flipY = true) {- const { width, height } = img;- const { ctx } = getOffscreenCanvas(width, height);- ctx.clearRect(0, 0, width, height);- ctx.save();- if (flipY) {- ctx.translate(0, height);- ctx.scale(1, -1);- }- ctx.drawImage(img, 0, 0);- ctx.restore();- const imageData = ctx.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- return { width, height, pixels };-}-/**- * Load image and get pixel data in one call- * @param path - File path relative to game root- * @param flipY - Whether to flip the image vertically (default: true for OpenGL)- */-async function wxLoadImagePixels(path, flipY = true) {- const img = await wxLoadImage(path);- return wxGetImagePixels(img, flipY);-}--/**- * @file index.ts- * @brief WeChat MiniGame platform adapter- */-// =============================================================================-// WeChat Platform Adapter-// =============================================================================-class WeChatPlatformAdapter {- constructor() {- this.name = 'wechat';- }- async fetch(url, options) {- return wxFetch(url, options);- }- async readFile(path) {- return wxReadFile(path);- }- async readTextFile(path) {- return wxReadTextFile(path);- }- async fileExists(path) {- return wxFileExists(path);- }- async instantiateWasm(pathOrBuffer, imports) {- if (typeof pathOrBuffer !== 'string') {- throw new Error('WeChat WXWebAssembly requires a file path string, not ArrayBuffer');- }- return wxInstantiateWasm(pathOrBuffer, imports);- }-}-// =============================================================================-// Initialization-// =============================================================================-let initialized = false;-/**- * Initialize WeChat platform polyfills- * Call this at the entry point of your game- */-function initWeChatPlatform() {- if (initialized)- return;- initialized = true;- polyfillFetch();- polyfillWebAssembly();- console.log('[ESEngine] WeChat platform initialized');-}-// =============================================================================-// Export-// =============================================================================-const wechatAdapter = new WeChatPlatformAdapter();--/**- * @file types.ts- * @brief Core type definitions for ESEngine SDK- */-const INVALID_ENTITY = 0;-const INVALID_TEXTURE = 0xFFFFFFFF;-// =============================================================================-// Factory Functions-// =============================================================================-const vec2 = (x = 0, y = 0) => ({ x, y });-const vec3 = (x = 0, y = 0, z = 0) => ({ x, y, z });-const vec4 = (x = 0, y = 0, z = 0, w = 1) => ({ x, y, z, w });-const color = (r = 1, g = 1, b = 1, a = 1) => ({ x: r, y: g, z: b, w: a });-const quat = (w = 1, x = 0, y = 0, z = 0) => ({ w, x, y, z });--/**- * @file component.ts- * @brief Component definition and builtin components- */-let componentCounter = 0;-function createComponentDef(name, defaults) {- const id = ++componentCounter;- return {- _id: Symbol(`Component_${id}_${name}`),- _name: name,- _default: defaults,- _builtin: false,- create(data) {- return { ...defaults, ...data };- }- };-}-function getComponentRegistry() {- if (typeof window === 'undefined')- return new Map();- return (window.__esengine_componentRegistry ?? (window.__esengine_componentRegistry = new Map()));-}-function defineComponent(name, defaults) {- const registry = getComponentRegistry();- const existing = registry.get(name);- if (existing)- return existing;- const def = createComponentDef(name, defaults);- registry.set(name, def);- registerToEditor(name, defaults, false);- return def;-}-function defineTag(name) {- const registry = getComponentRegistry();- const existing = registry.get(name);- if (existing)- return existing;- const def = createComponentDef(name, {});- registry.set(name, def);- registerToEditor(name, {}, true);- return def;-}-function getUserComponent(name) {- return getComponentRegistry().get(name);-}-function clearUserComponents() {- getComponentRegistry().clear();-}-function registerToEditor(name, defaults, isTag) {- if (typeof window !== 'undefined' && window.__esengine_registerComponent) {- window.__esengine_registerComponent(name, defaults, isTag);- }-}-function defineBuiltin(name, defaults) {- return {- _id: Symbol(`Builtin_${name}`),- _name: name,- _cppName: name,- _builtin: true,- _default: defaults- };-}-function isBuiltinComponent(comp) {- return comp._builtin === true;-}-// =============================================================================-// Builtin Component Instances-// =============================================================================-const LocalTransform = defineBuiltin('LocalTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const WorldTransform = defineBuiltin('WorldTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const Sprite = defineBuiltin('Sprite', {- texture: INVALID_TEXTURE,- color: { x: 1, y: 1, z: 1, w: 1 },- size: { x: 32, y: 32 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0-});-const Camera = defineBuiltin('Camera', {- projectionType: 0,- fov: 60,- orthoSize: 5,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- isActive: true,- priority: 0-});-const Canvas = defineBuiltin('Canvas', {- designResolution: { x: 1920, y: 1080 },- pixelsPerUnit: 100,- scaleMode: 0,- matchWidthOrHeight: 0.5,- backgroundColor: { x: 0, y: 0, z: 0, w: 1 }-});-const Velocity = defineBuiltin('Velocity', {- linear: { x: 0, y: 0, z: 0 },- angular: { x: 0, y: 0, z: 0 }-});-const Parent = defineBuiltin('Parent', {- entity: 0-});-const Children = defineBuiltin('Children', {- entities: []-});-const SpineAnimation = defineBuiltin('SpineAnimation', {- skeletonPath: '',- atlasPath: '',- skin: '',- animation: '',- timeScale: 1.0,- loop: true,- playing: true,- flipX: false,- flipY: false,- color: { x: 1, y: 1, z: 1, w: 1 },- layer: 0,- skeletonScale: 1.0,- material: 0-});-// =============================================================================-// Component Defaults Registry-// =============================================================================-const builtinComponents = {- LocalTransform,- WorldTransform,- Sprite,- Camera,- Canvas,- Velocity,- Parent,- Children,- SpineAnimation,-};-function getComponentDefaults(typeName) {- const builtin = builtinComponents[typeName];- if (builtin)- return { ...builtin._default };- const userComp = getUserComponent(typeName);- if (userComp)- return { ...userComp._default };- return null;-}--/**- * @file resource.ts- * @brief Resource system for global singleton data- */-let resourceCounter = 0;-function defineResource(defaultValue, name) {- const id = ++resourceCounter;- return {- _id: Symbol(`Resource_${id}_${name ?? ''}`),- _name: name ?? `Resource_${id}`,- _default: defaultValue- };-}-function Res(resource) {- return { _type: 'res', _resource: resource };-}-function ResMut(resource) {- return { _type: 'res_mut', _resource: resource };-}-// =============================================================================-// Resource Instances (Runtime)-// =============================================================================-class ResMutInstance {- constructor(value, setter) {- this.value_ = value;- this.setter_ = setter;- }- get() {- return this.value_;- }- set(value) {- this.value_ = value;- this.setter_(value);- }- modify(fn) {- fn(this.value_);- this.setter_(this.value_);- }-}-// =============================================================================-// Resource Storage-// =============================================================================-class ResourceStorage {- constructor() {- this.resources_ = new Map();- }- insert(resource, value) {- this.resources_.set(resource._id, value);- }- get(resource) {- if (!this.resources_.has(resource._id)) {- this.resources_.set(resource._id, resource._default);- }- return this.resources_.get(resource._id);- }- set(resource, value) {- this.resources_.set(resource._id, value);- }- has(resource) {- return this.resources_.has(resource._id);- }- remove(resource) {- this.resources_.delete(resource._id);- }- getResMut(resource) {- return new ResMutInstance(this.get(resource), (v) => this.set(resource, v));- }-}-const Time = defineResource({- delta: 0,- elapsed: 0,- frameCount: 0-}, 'Time');-const Input = defineResource({- keysDown: new Set(),- keysPressed: new Set(),- keysReleased: new Set(),- mouseX: 0,- mouseY: 0,- mouseButtons: new Set()-}, 'Input');--/**- * @file query.ts- * @brief Component query system with mutable component support- */-function Mut(component) {- return { _type: 'mut', _component: component };-}-function isMutWrapper(value) {- return typeof value === 'object' && value !== null && value._type === 'mut';-}-function createQueryDescriptor(components, withFilters = [], withoutFilters = []) {- const mutIndices = [];- components.forEach((comp, i) => {- if (isMutWrapper(comp)) {- mutIndices.push(i);- }- });- return {- _type: 'query',- _components: components,- _mutIndices: mutIndices,- _with: withFilters,- _without: withoutFilters- };-}-// =============================================================================-// Query Factory-// =============================================================================-function Query(...components) {- return createQueryDescriptor(components);-}-class QueryInstance {- constructor(world, descriptor) {- this.pendingMutations_ = [];- this.world_ = world;- this.descriptor_ = descriptor;- }- getActualComponent(arg) {- return isMutWrapper(arg) ? arg._component : arg;- }- commitPending() {- for (const mutation of this.pendingMutations_) {- this.world_.insert(mutation.entity, mutation.component, mutation.data);- }- this.pendingMutations_ = [];- }- *[Symbol.iterator]() {- const { _components, _mutIndices, _with, _without } = this.descriptor_;- const actualComponents = _components.map(c => this.getActualComponent(c));- const allRequired = [...actualComponents, ..._with];- const entities = this.world_.getEntitiesWithComponents(allRequired);- let prevEntity = null;- let prevMutData = [];- try {- for (const entity of entities) {- // Commit previous entity's mutations before moving to next- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- prevMutData = [];- let excluded = false;- for (const comp of _without) {- if (this.world_.has(entity, comp)) {- excluded = true;- break;- }- }- if (excluded)- continue;- const components = actualComponents.map(comp => this.world_.get(entity, comp));- // Track mutable components for write-back- for (const idx of _mutIndices) {- prevMutData.push({- component: actualComponents[idx],- data: components[idx]- });- }- prevEntity = entity;- yield [entity, ...components];- }- }- finally {- // Commit last entity's mutations- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- }- }- forEach(callback) {- for (const [entity, ...components] of this) {- callback(entity, ...components);- }- }- single() {- for (const result of this) {- return result;- }- return null;- }- isEmpty() {- return this.single() === null;- }- count() {- let n = 0;- for (const _ of this) {- n++;- }- return n;- }- toArray() {- return [...this];- }-}--/**- * @file commands.ts- * @brief Deferred entity/component operations- */-function Commands() {- return { _type: 'commands' };-}-// =============================================================================-// Entity Commands (Builder for spawning)-// =============================================================================-class EntityCommands {- constructor(commands, entity) {- this.components_ = [];- this.commands_ = commands;- if (entity === null) {- this.entityRef_ = { entity: 0 };- this.isNew_ = true;- }- else {- this.entityRef_ = { entity };- this.isNew_ = false;- }- }- insert(component, data) {- let instance;- if (isBuiltinComponent(component)) {- instance = { ...component._default, ...data };- }- else {- instance = component.create(data);- }- if (this.isNew_) {- this.components_.push({ component, data: instance });- }- else {- this.commands_.queueInsert(this.entityRef_.entity, component, instance);- }- return this;- }- remove(component) {- if (!this.isNew_) {- this.commands_.queueRemove(this.entityRef_.entity, component);- }- return this;- }- id() {- if (this.isNew_ && this.entityRef_.entity === 0) {- this.finalize();- }- return this.entityRef_.entity;- }- finalize() {- if (this.isNew_) {- this.commands_.spawnImmediate(this.components_, this.entityRef_);- this.isNew_ = false;- }- }-}-// =============================================================================-// Commands Instance (Runtime)-// =============================================================================-class CommandsInstance {- constructor(world, resources) {- this.pending_ = [];- this.world_ = world;- this.resources_ = resources;- }- spawn() {- return new EntityCommands(this, null);- }- entity(entity) {- return new EntityCommands(this, entity);- }- despawn(entity) {- this.pending_.push({ type: 'despawn', entity });- return this;- }- insertResource(resource, value) {- this.pending_.push({- type: 'insert_resource',- resource: resource,- value- });- return this;- }- queueInsert(entity, component, data) {- this.pending_.push({ type: 'insert', entity, component, data });- }- queueRemove(entity, component) {- this.pending_.push({ type: 'remove', entity, component });- }- spawnImmediate(components, entityRef) {- const entity = this.world_.spawn();- entityRef.entity = entity;- for (const entry of components) {- this.world_.insert(entity, entry.component, entry.data);- }- }- flush() {- for (const cmd of this.pending_) {- this.executeCommand(cmd);- }- this.pending_ = [];- }- executeCommand(cmd) {- switch (cmd.type) {- case 'spawn': {- const entity = this.world_.spawn();- cmd.entityRef.entity = entity;- for (const entry of cmd.components) {- this.world_.insert(entity, entry.component, entry.data);- }- break;- }- case 'despawn':- this.world_.despawn(cmd.entity);- break;- case 'insert':- this.world_.insert(cmd.entity, cmd.component, cmd.data);- break;- case 'remove':- this.world_.remove(cmd.entity, cmd.component);- break;- case 'insert_resource':- this.resources_.insert(cmd.resource, cmd.value);- break;- }- }-}--/**- * @file system.ts- * @brief System definition and scheduling- */-// =============================================================================-// Schedule Phases-// =============================================================================-var Schedule;-(function (Schedule) {- Schedule[Schedule["Startup"] = 0] = "Startup";- Schedule[Schedule["First"] = 1] = "First";- Schedule[Schedule["PreUpdate"] = 2] = "PreUpdate";- Schedule[Schedule["Update"] = 3] = "Update";- Schedule[Schedule["PostUpdate"] = 4] = "PostUpdate";- Schedule[Schedule["Last"] = 5] = "Last";- Schedule[Schedule["FixedPreUpdate"] = 10] = "FixedPreUpdate";- Schedule[Schedule["FixedUpdate"] = 11] = "FixedUpdate";- Schedule[Schedule["FixedPostUpdate"] = 12] = "FixedPostUpdate";-})(Schedule || (Schedule = {}));-let systemCounter = 0;-function defineSystem(params, fn, options) {- const id = ++systemCounter;- return {- _id: Symbol(`System_${id}_${options?.name ?? ''}`),- _params: params,- _fn: fn,- _name: options?.name ?? `System_${id}`- };-}-// =============================================================================-// Global System Registration-// =============================================================================-function getPendingSystems() {- if (typeof window === 'undefined')- return [];- return (window.__esengine_pendingSystems ?? (window.__esengine_pendingSystems = []));-}-function addSystem(system) {- getPendingSystems().push({ schedule: Schedule.Update, system });-}-function addStartupSystem(system) {- getPendingSystems().push({ schedule: Schedule.Startup, system });-}-function addSystemToSchedule(schedule, system) {- getPendingSystems().push({ schedule, system });-}-// =============================================================================-// System Runner-// =============================================================================-class SystemRunner {- constructor(world, resources) {- this.world_ = world;- this.resources_ = resources;- }- run(system) {- const args = system._params.map(param => this.resolveParam(param));- system._fn(...args);- for (const arg of args) {- if (arg instanceof CommandsInstance) {- arg.flush();- }- }- }- resolveParam(param) {- switch (param._type) {- case 'query':- return new QueryInstance(this.world_, param);- case 'res':- return this.resources_.get(param._resource);- case 'res_mut':- return this.resources_.getResMut(param._resource);- case 'commands':- return new CommandsInstance(this.world_, this.resources_);- default:- throw new Error('Unknown system parameter type');- }- }-}--/**- * @file world.ts- * @brief ECS World with C++ Registry integration- */-// =============================================================================-// World-// =============================================================================-class World {- constructor() {- this.cppRegistry_ = null;- this.entities_ = new Set();- this.tsStorage_ = new Map();- }- connectCpp(cppRegistry) {- this.cppRegistry_ = cppRegistry;- }- get hasCpp() {- return this.cppRegistry_ !== null;- }- // =========================================================================- // Entity Management- // =========================================================================- spawn() {- let entity;- if (this.cppRegistry_) {- entity = this.cppRegistry_.create();- }- else {- entity = (this.entities_.size + 1);- }- this.entities_.add(entity);- return entity;- }- despawn(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.destroy(entity);- }- this.entities_.delete(entity);- for (const storage of this.tsStorage_.values()) {- storage.delete(entity);- }- }- valid(entity) {- if (this.cppRegistry_) {- return this.cppRegistry_.valid(entity);- }- return this.entities_.has(entity);- }- entityCount() {- return this.entities_.size;- }- getAllEntities() {- return Array.from(this.entities_);- }- setParent(child, parent) {- if (this.cppRegistry_) {- this.cppRegistry_.setParent(child, parent);- }- }- removeParent(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.removeParent(entity);- }- }- // =========================================================================- // Component Management- // =========================================================================- insert(entity, component, data) {- if (isBuiltinComponent(component)) {- return this.insertBuiltin(entity, component, data);- }- return this.insertScript(entity, component, data);- }- get(entity, component) {- if (isBuiltinComponent(component)) {- return this.getBuiltin(entity, component);- }- return this.getScript(entity, component);- }- has(entity, component) {- if (isBuiltinComponent(component)) {- return this.hasBuiltin(entity, component);- }- return this.hasScript(entity, component);- }- remove(entity, component) {- if (isBuiltinComponent(component)) {- this.removeBuiltin(entity, component);- }- else {- this.removeScript(entity, component);- }- }- // =========================================================================- // Builtin Component Operations (C++ Registry)- // =========================================================================- insertBuiltin(entity, component, data) {- const merged = { ...component._default, ...data };- if (this.cppRegistry_) {- const adder = `add${component._cppName}`;- const fn = this.cppRegistry_[adder];- fn.call(this.cppRegistry_, entity, merged);- }- return merged;- }- getBuiltin(entity, component) {- if (!this.cppRegistry_) {- throw new Error('C++ Registry not connected');- }- const getter = `get${component._cppName}`;- const fn = this.cppRegistry_[getter];- return fn.call(this.cppRegistry_, entity);- }- hasBuiltin(entity, component) {- if (!this.cppRegistry_) {- return false;- }- const checker = `has${component._cppName}`;- const fn = this.cppRegistry_[checker];- return fn.call(this.cppRegistry_, entity);- }- removeBuiltin(entity, component) {- if (!this.cppRegistry_) {- return;- }- const remover = `remove${component._cppName}`;- const fn = this.cppRegistry_[remover];- fn.call(this.cppRegistry_, entity);- }- // =========================================================================- // Script Component Operations (TypeScript storage)- // =========================================================================- insertScript(entity, component, data) {- const value = component.create(data);- this.getStorage(component).set(entity, value);- return value;- }- getScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- if (!storage) {- throw new Error(`Component not found: ${component._name}`);- }- return storage.get(entity);- }- hasScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- return storage?.has(entity) ?? false;- }- removeScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- storage?.delete(entity);- }- getStorage(component) {- let storage = this.tsStorage_.get(component._id);- if (!storage) {- storage = new Map();- this.tsStorage_.set(component._id, storage);- }- return storage;- }- // =========================================================================- // Query Support- // =========================================================================- getEntitiesWithComponents(components) {- if (components.length === 0) {- return this.getAllEntities();- }- const entities = [];- for (const entity of this.entities_) {- let hasAll = true;- for (const comp of components) {- if (!this.has(entity, comp)) {- hasAll = false;- break;- }- }- if (hasAll) {- entities.push(entity);- }- }- return entities;- }-}--/**- * @file text.ts- * @brief Text component definition for UI text rendering- */-// =============================================================================-// Text Alignment Enums-// =============================================================================-var TextAlign;-(function (TextAlign) {- TextAlign[TextAlign["Left"] = 0] = "Left";- TextAlign[TextAlign["Center"] = 1] = "Center";- TextAlign[TextAlign["Right"] = 2] = "Right";-})(TextAlign || (TextAlign = {}));-var TextVerticalAlign;-(function (TextVerticalAlign) {- TextVerticalAlign[TextVerticalAlign["Top"] = 0] = "Top";- TextVerticalAlign[TextVerticalAlign["Middle"] = 1] = "Middle";- TextVerticalAlign[TextVerticalAlign["Bottom"] = 2] = "Bottom";-})(TextVerticalAlign || (TextVerticalAlign = {}));-var TextOverflow;-(function (TextOverflow) {- TextOverflow[TextOverflow["Visible"] = 0] = "Visible";- TextOverflow[TextOverflow["Clip"] = 1] = "Clip";- TextOverflow[TextOverflow["Ellipsis"] = 2] = "Ellipsis";-})(TextOverflow || (TextOverflow = {}));-// =============================================================================-// Text Component Definition-// =============================================================================-const Text = defineComponent('Text', {- content: '',- fontFamily: 'Arial',- fontSize: 24,- color: { x: 1, y: 1, z: 1, w: 1 },- align: TextAlign.Left,- verticalAlign: TextVerticalAlign.Top,- wordWrap: true,- overflow: TextOverflow.Visible,- lineHeight: 1.2,- dirty: true,-});--/**- * @file TextRenderer.ts- * @brief Renders text to GPU textures using Canvas 2D API- */-// =============================================================================-// Text Renderer-// =============================================================================-class TextRenderer {- constructor(module) {- this.cache = new Map();- this.module = module;- if (typeof OffscreenCanvas !== 'undefined') {- this.canvas = new OffscreenCanvas(512, 512);- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- else {- this.canvas = document.createElement('canvas');- this.canvas.width = 512;- this.canvas.height = 512;- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- }- /**- * Renders text to a texture and returns the handle- */- renderText(text, uiRect) {- const ctx = this.ctx;- const canvas = this.canvas;- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- const hasContainer = uiRect && uiRect.size.x > 0 && uiRect.size.y > 0;- const containerWidth = hasContainer ? uiRect.size.x : 0;- const containerHeight = hasContainer ? uiRect.size.y : 0;- const shouldWrap = text.wordWrap && hasContainer;- let lines = this.wrapText(text.content, shouldWrap ? containerWidth : 0);- const lineHeightPx = Math.ceil(text.fontSize * text.lineHeight);- const padding = Math.ceil(text.fontSize * 0.2);- const measuredWidth = Math.ceil(this.measureWidth(lines));- const measuredHeight = Math.ceil(lines.length * lineHeightPx);- const width = hasContainer ? Math.ceil(containerWidth) : measuredWidth + padding * 2;- const height = hasContainer ? Math.ceil(containerHeight) : measuredHeight + padding * 2;- // Handle overflow ellipsis- if (hasContainer && text.overflow === TextOverflow.Ellipsis && measuredHeight > containerHeight) {- const maxLines = Math.floor(containerHeight / lineHeightPx);- if (maxLines > 0 && lines.length > maxLines) {- lines = lines.slice(0, maxLines);- const lastLine = lines[maxLines - 1];- lines[maxLines - 1] = this.truncateWithEllipsis(lastLine, containerWidth);- }- }- if (canvas.width < width || canvas.height < height) {- const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));- const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));- canvas.width = newWidth;- canvas.height = newHeight;- }- const r = Math.round(text.color.x * 255);- const g = Math.round(text.color.y * 255);- const b = Math.round(text.color.z * 255);- const a = text.color.w;- ctx.clearRect(0, 0, canvas.width, canvas.height);- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- ctx.textAlign = this.mapAlign(text.align);- ctx.textBaseline = 'top';- ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;- // Handle overflow clip- if (hasContainer && text.overflow === TextOverflow.Clip) {- ctx.save();- ctx.beginPath();- ctx.rect(0, 0, width, height);- ctx.clip();- }- const textBlockHeight = lines.length * lineHeightPx;- let startY;- if (hasContainer) {- switch (text.verticalAlign) {- case TextVerticalAlign.Top:- startY = padding;- break;- case TextVerticalAlign.Middle:- startY = (height - textBlockHeight) / 2;- break;- case TextVerticalAlign.Bottom:- startY = height - textBlockHeight - padding;- break;- default: startY = padding;- }- }- else {- startY = padding;- }- let y = startY;- for (const line of lines) {- let x;- switch (text.align) {- case TextAlign.Left:- x = padding;- break;- case TextAlign.Center:- x = width / 2;- break;- case TextAlign.Right:- x = width - padding;- break;- default:- x = padding;- }- ctx.fillText(line, x, y);- y += lineHeightPx;- }- if (hasContainer && text.overflow === TextOverflow.Clip) {- ctx.restore();- }- const imageData = ctx.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- const flipped = this.flipVertically(pixels, width, height);- const rm = this.module.getResourceManager();- const ptr = this.module._malloc(flipped.length);- this.module.HEAPU8.set(flipped, ptr);- const textureHandle = rm.createTexture(width, height, ptr, flipped.length, 1);- this.module._free(ptr);- return { textureHandle, width, height };- }- truncateWithEllipsis(text, maxWidth) {- const ellipsis = '...';- if (this.ctx.measureText(text).width <= maxWidth) {- return text;- }- let truncated = text;- while (truncated.length > 0 && this.ctx.measureText(truncated + ellipsis).width > maxWidth) {- truncated = truncated.slice(0, -1);- }- return truncated + ellipsis;- }- /**- * Renders text for an entity and caches the result- */- renderForEntity(entity, text, uiRect) {- const existing = this.cache.get(entity);- if (existing) {- const rm = this.module.getResourceManager();- rm.releaseTexture(existing.textureHandle);- }- const result = this.renderText(text, uiRect);- this.cache.set(entity, result);- return result;- }- /**- * Gets cached render result for entity- */- getCached(entity) {- return this.cache.get(entity);- }- /**- * Releases texture for entity- */- release(entity) {- const cached = this.cache.get(entity);- if (cached) {- const rm = this.module.getResourceManager();- rm.releaseTexture(cached.textureHandle);- this.cache.delete(entity);- }- }- /**- * Releases all cached textures- */- releaseAll() {- const rm = this.module.getResourceManager();- for (const result of this.cache.values()) {- rm.releaseTexture(result.textureHandle);- }- this.cache.clear();- }- // =========================================================================- // Private Methods- // =========================================================================- wrapText(text, maxWidth) {- if (!text)- return [''];- if (maxWidth <= 0)- return text.split('\n');- const paragraphs = text.split('\n');- const lines = [];- for (const paragraph of paragraphs) {- if (!paragraph) {- lines.push('');- continue;- }- let currentLine = '';- for (const char of paragraph) {- const testLine = currentLine + char;- const metrics = this.ctx.measureText(testLine);- if (metrics.width > maxWidth && currentLine) {- lines.push(currentLine);- currentLine = char;- }- else {- currentLine = testLine;- }- }- if (currentLine) {- lines.push(currentLine);- }- }- return lines.length > 0 ? lines : [''];- }- measureWidth(lines) {- let maxWidth = 0;- for (const line of lines) {- const metrics = this.ctx.measureText(line);- const width = metrics.actualBoundingBoxLeft !== undefined- ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight- : metrics.width;- maxWidth = Math.max(maxWidth, width);- }- return maxWidth;- }- mapAlign(align) {- switch (align) {- case TextAlign.Left:- return 'left';- case TextAlign.Center:- return 'center';- case TextAlign.Right:- return 'right';- }- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- flipVertically(pixels, width, height) {- const rowSize = width * 4;- const flipped = new Uint8Array(pixels.length);- for (let y = 0; y < height; y++) {- const srcOffset = y * rowSize;- const dstOffset = (height - 1 - y) * rowSize;- flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);- }- return flipped;- }-}--/**- * @file UIRect.ts- * @brief UIRect component for UI layout with anchor and pivot- */-// =============================================================================-// UIRect Component Definition-// =============================================================================-const UIRect = defineComponent('UIRect', {- size: { x: 100, y: 100 },- anchor: { x: 0.5, y: 0.5 },- pivot: { x: 0.5, y: 0.5 },-});--/**- * @file TextPlugin.ts- * @brief Plugin that automatically syncs Text components to Sprite textures- */-// =============================================================================-// Text Plugin-// =============================================================================-class TextPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('TextPlugin: No WASM module available');- return;- }- const renderer = new TextRenderer(module);- const world = app.world;- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {- const entities = world.getEntitiesWithComponents([Text]);- for (const entity of entities) {- const text = world.get(entity, Text);- if (!text.dirty)- continue;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- size: { x: 0, y: 0 },- color: { x: 1, y: 1, z: 1, w: 1 },- anchor: { x: 0.5, y: 0.5 },- flip: { x: false, y: false }- });- }- const uiRect = world.has(entity, UIRect)- ? world.get(entity, UIRect)- : null;- const result = renderer.renderForEntity(entity, text, uiRect);- const sprite = world.get(entity, Sprite);- sprite.texture = result.textureHandle;- sprite.size = { x: result.width, y: result.height };- sprite.uvOffset = { x: 0, y: 0 };- sprite.uvScale = { x: 1, y: 1 };- world.insert(entity, Sprite, sprite);- text.dirty = false;- }- }));- }-}-const textPlugin = new TextPlugin();--/**- * @file blend.ts- * @brief Blend mode definitions for rendering- */-var BlendMode;-(function (BlendMode) {- BlendMode[BlendMode["Normal"] = 0] = "Normal";- BlendMode[BlendMode["Additive"] = 1] = "Additive";- BlendMode[BlendMode["Multiply"] = 2] = "Multiply";- BlendMode[BlendMode["Screen"] = 3] = "Screen";- BlendMode[BlendMode["PremultipliedAlpha"] = 4] = "PremultipliedAlpha";-})(BlendMode || (BlendMode = {}));--/**- * @file material.ts- * @brief Material and Shader API for custom rendering- * @details Provides shader creation and material management for custom visual effects.- */-function isTextureRef(v) {- return typeof v === 'object' && v !== null && '__textureRef' in v;-}-// =============================================================================-// Internal State-// =============================================================================-let module$5 = null;-let resourceManager = null;-let nextMaterialId = 1;-const materials = new Map();-// =============================================================================-// Initialization-// =============================================================================-function initMaterialAPI(wasmModule) {- module$5 = wasmModule;- resourceManager = wasmModule.getResourceManager();- registerMaterialCallback();-}-function shutdownMaterialAPI() {- if (uniformBuffer$1 !== 0 && module$5) {- module$5._free(uniformBuffer$1);- uniformBuffer$1 = 0;- }- materials.clear();- nextMaterialId = 1;- materialCallbackRegistered = false;- resourceManager = null;- module$5 = null;-}-// =============================================================================-// Shader API-// =============================================================================-function getResourceManager() {- if (!resourceManager) {- throw new Error('Material API not initialized. Call initMaterialAPI() first.');- }- return resourceManager;-}-const Material = {- /**- * Creates a shader from vertex and fragment source code.- * @param vertexSrc GLSL vertex shader source- * @param fragmentSrc GLSL fragment shader source- * @returns Shader handle, or 0 on failure- */- createShader(vertexSrc, fragmentSrc) {- return getResourceManager().createShader(vertexSrc, fragmentSrc);- },- /**- * Releases a shader.- * @param shader Shader handle to release- */- releaseShader(shader) {- if (shader > 0) {- getResourceManager().releaseShader(shader);- }- },- /**- * Creates a material with a shader and optional settings.- * @param options Material creation options- * @returns Material handle- */- create(options) {- const handle = nextMaterialId++;- const data = {- shader: options.shader,- uniforms: new Map(),- blendMode: options.blendMode ?? BlendMode.Normal,- depthTest: options.depthTest ?? false,- };- if (options.uniforms) {- for (const [key, value] of Object.entries(options.uniforms)) {- data.uniforms.set(key, value);- }- }- materials.set(handle, data);- return handle;- },- /**- * Gets material data by handle.- * @param material Material handle- * @returns Material data or undefined- */- get(material) {- return materials.get(material);- },- /**- * Sets a uniform value on a material.- * @param material Material handle- * @param name Uniform name- * @param value Uniform value- */- setUniform(material, name, value) {- const data = materials.get(material);- if (data) {- data.uniforms.set(name, value);- }- },- /**- * Gets a uniform value from a material.- * @param material Material handle- * @param name Uniform name- * @returns Uniform value or undefined- */- getUniform(material, name) {- const data = materials.get(material);- return data?.uniforms.get(name);- },- /**- * Sets the blend mode for a material.- * @param material Material handle- * @param mode Blend mode- */- setBlendMode(material, mode) {- const data = materials.get(material);- if (data) {- data.blendMode = mode;- }- },- /**- * Gets the blend mode of a material.- * @param material Material handle- * @returns Blend mode- */- getBlendMode(material) {- const data = materials.get(material);- return data?.blendMode ?? BlendMode.Normal;- },- /**- * Sets depth test enabled for a material.- * @param material Material handle- * @param enabled Whether depth test is enabled- */- setDepthTest(material, enabled) {- const data = materials.get(material);- if (data) {- data.depthTest = enabled;- }- },- /**- * Gets the shader handle for a material.- * @param material Material handle- * @returns Shader handle- */- getShader(material) {- const data = materials.get(material);- return data?.shader ?? 0;- },- /**- * Releases a material (does not release the shader).- * @param material Material handle- */- release(material) {- materials.delete(material);- },- /**- * Checks if a material exists.- * @param material Material handle- * @returns True if material exists- */- isValid(material) {- return materials.has(material);- },- /**- * Creates a material from asset data.- * @param data Material asset data (properties object)- * @param shaderHandle Pre-loaded shader handle- * @returns Material handle- */- createFromAsset(data, shaderHandle) {- const uniforms = {};- for (const [key, value] of Object.entries(data.properties)) {- if (typeof value === 'number') {- uniforms[key] = value;- }- else if (typeof value === 'object' && value !== null) {- const obj = value;- if ('w' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };- }- else if ('z' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };- }- else if ('y' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0 };- }- }- }- return this.create({- shader: shaderHandle,- uniforms,- blendMode: data.blendMode ?? BlendMode.Normal,- depthTest: data.depthTest ?? false,- });- },- /**- * Creates a material instance that shares the shader with source.- * @param source Source material handle- * @returns New material handle with copied settings- */- createInstance(source) {- const sourceData = materials.get(source);- if (!sourceData) {- throw new Error(`Invalid source material: ${source}`);- }- const handle = nextMaterialId++;- const data = {- shader: sourceData.shader,- uniforms: new Map(sourceData.uniforms),- blendMode: sourceData.blendMode,- depthTest: sourceData.depthTest,- };- materials.set(handle, data);- return handle;- },- /**- * Exports material to serializable asset data.- * @param material Material handle- * @param shaderPath Shader file path for asset reference- * @returns Material asset data- */- toAssetData(material, shaderPath) {- const data = materials.get(material);- if (!data)- return null;- const properties = {};- for (const [key, value] of data.uniforms) {- properties[key] = value;- }- return {- version: '1.0',- type: 'material',- shader: shaderPath,- blendMode: data.blendMode,- depthTest: data.depthTest,- properties,- };- },- /**- * Gets all uniforms from a material.- * @param material Material handle- * @returns Map of uniform names to values- */- getUniforms(material) {- const data = materials.get(material);- return data ? new Map(data.uniforms) : new Map();- },- tex(textureId, slot) {- return { __textureRef: true, textureId, slot };- },-};-// =============================================================================-// Material Callback Registration-// =============================================================================-let materialCallbackRegistered = false;-let uniformBuffer$1 = 0;-const UNIFORM_BUFFER_SIZE = 4096;-function ensureUniformBuffer() {- if (uniformBuffer$1 === 0 && module$5) {- uniformBuffer$1 = module$5._malloc(UNIFORM_BUFFER_SIZE);- }- return uniformBuffer$1;-}-function serializeUniforms(uniforms) {- const bufferPtr = ensureUniformBuffer();- if (bufferPtr === 0 || !module$5)- return { ptr: 0, count: 0 };- let offset = 0;- let count = 0;- const heap8 = module$5.HEAPU8;- const heap32 = module$5.HEAPU32;- const heapF32 = module$5.HEAPF32;- for (const [name, value] of uniforms) {- if (offset + 128 > UNIFORM_BUFFER_SIZE)- break;- const nameBytes = new TextEncoder().encode(name);- const nameLen = nameBytes.length;- const namePadded = Math.ceil(nameLen / 4) * 4;- heap32[(bufferPtr + offset) >> 2] = nameLen;- offset += 4;- heap8.set(nameBytes, bufferPtr + offset);- offset += namePadded;- let type = 0;- let values = [0, 0, 0, 0];- if (typeof value === 'number') {- type = 0;- values[0] = value;- }- else if (Array.isArray(value)) {- type = Math.min(value.length - 1, 3);- for (let i = 0; i < Math.min(value.length, 4); i++) {- values[i] = value[i];- }- }- else if ('w' in value) {- type = 3;- values = [value.x, value.y, value.z, value.w];- }- else if ('z' in value) {- type = 2;- values = [value.x, value.y, value.z, 0];- }- else if ('y' in value) {- type = 1;- values = [value.x, value.y, 0, 0];- }- heap32[(bufferPtr + offset) >> 2] = type;- offset += 4;- for (let i = 0; i < 4; i++) {- heapF32[(bufferPtr + offset) >> 2] = values[i];- offset += 4;- }- count++;- }- return { ptr: bufferPtr, count };-}-function registerMaterialCallback() {- if (!module$5 || materialCallbackRegistered)- return;- const callback = (materialId, outShaderIdPtr, outBlendModePtr, outUniformBufferPtr, outUniformCountPtr) => {- const data = materials.get(materialId);- if (!data) {- module$5.HEAPU32[outShaderIdPtr >> 2] = 0;- module$5.HEAPU32[outBlendModePtr >> 2] = 0;- module$5.HEAPU32[outUniformBufferPtr >> 2] = 0;- module$5.HEAPU32[outUniformCountPtr >> 2] = 0;- return;- }- module$5.HEAPU32[outShaderIdPtr >> 2] = data.shader;- module$5.HEAPU32[outBlendModePtr >> 2] = data.blendMode;- const { ptr, count } = serializeUniforms(data.uniforms);- module$5.HEAPU32[outUniformBufferPtr >> 2] = ptr;- module$5.HEAPU32[outUniformCountPtr >> 2] = count;- };- module$5.materialDataProvider = callback;- materialCallbackRegistered = true;-}-// =============================================================================-// Built-in Shader Sources-// =============================================================================-const ShaderSources = {- SPRITE_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;-layout(location = 2) in vec2 a_texCoord;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;-out vec2 v_texCoord;--void main() {- v_color = a_color;- v_texCoord = a_texCoord;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- SPRITE_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;-in vec2 v_texCoord;--uniform sampler2D u_texture;--out vec4 fragColor;--void main() {- fragColor = texture(u_texture, v_texCoord) * v_color;-}-`,- COLOR_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;--void main() {- v_color = a_color;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- COLOR_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;--out vec4 fragColor;--void main() {- fragColor = v_color;-}-`,-};--/**- * @file draw.ts- * @brief Immediate mode 2D drawing API- * @details Provides simple drawing primitives (lines, rectangles, circles)- * with automatic batching. All draw commands are cleared each frame.- */-// =============================================================================-// Internal State-// =============================================================================-let module$4 = null;-let viewProjectionPtr$1 = 0;-let transformPtr = 0;-let uniformsPtr = 0;-const UNIFORMS_BUFFER_SIZE = 256;-const uniformBuffer = new Float32Array(UNIFORMS_BUFFER_SIZE);-// =============================================================================-// Initialization-// =============================================================================-function initDrawAPI(wasmModule) {- module$4 = wasmModule;- viewProjectionPtr$1 = module$4._malloc(16 * 4);- transformPtr = module$4._malloc(16 * 4);- uniformsPtr = module$4._malloc(UNIFORMS_BUFFER_SIZE * 4);-}-function shutdownDrawAPI() {- if (module$4) {- if (viewProjectionPtr$1) {- module$4._free(viewProjectionPtr$1);- viewProjectionPtr$1 = 0;- }- if (transformPtr) {- module$4._free(transformPtr);- transformPtr = 0;- }- if (uniformsPtr) {- module$4._free(uniformsPtr);- uniformsPtr = 0;- }- }- module$4 = null;-}-// =============================================================================-// Draw Implementation-// =============================================================================-function getModule$2() {- if (!module$4) {- throw new Error('Draw API not initialized. Call initDrawAPI() first.');- }- return module$4;-}-const WHITE = { x: 1, y: 1, z: 1, w: 1 };-const Draw = {- begin(viewProjection) {- const m = getModule$2();- m.HEAPF32.set(viewProjection, viewProjectionPtr$1 / 4);- m.draw_begin(viewProjectionPtr$1);- },- end() {- getModule$2().draw_end();- },- line(from, to, color, thickness = 1) {- getModule$2().draw_line(from.x, from.y, to.x, to.y, color.x, color.y, color.z, color.w, thickness);- },- rect(position, size, color, filled = true) {- getModule$2().draw_rect(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, filled);- },- rectOutline(position, size, color, thickness = 1) {- getModule$2().draw_rectOutline(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, thickness);- },- circle(center, radius, color, filled = true, segments = 32) {- getModule$2().draw_circle(center.x, center.y, radius, color.x, color.y, color.z, color.w, filled, segments);- },- circleOutline(center, radius, color, thickness = 1, segments = 32) {- getModule$2().draw_circleOutline(center.x, center.y, radius, color.x, color.y, color.z, color.w, thickness, segments);- },- texture(position, size, textureHandle, tint = WHITE) {- getModule$2().draw_texture(position.x, position.y, size.x, size.y, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- textureRotated(position, size, rotation, textureHandle, tint = WHITE) {- getModule$2().draw_textureRotated(position.x, position.y, size.x, size.y, rotation, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- setLayer(layer) {- getModule$2().draw_setLayer(layer);- },- setDepth(depth) {- getModule$2().draw_setDepth(depth);- },- getDrawCallCount() {- if (!module$4)- return 0;- return module$4.draw_getDrawCallCount();- },- getPrimitiveCount() {- if (!module$4)- return 0;- return module$4.draw_getPrimitiveCount();- },- setBlendMode(mode) {- getModule$2().draw_setBlendMode(mode);- },- setDepthTest(enabled) {- getModule$2().draw_setDepthTest(enabled);- },- drawMesh(geometry, shader, transform) {- const m = getModule$2();- m.HEAPF32.set(transform, transformPtr / 4);- m.draw_mesh(geometry, shader, transformPtr);- },- drawMeshWithMaterial(geometry, material, transform) {- const m = getModule$2();- const matData = Material.get(material);- if (!matData)- return;- Draw.setBlendMode(matData.blendMode);- Draw.setDepthTest(matData.depthTest);- if (matData.uniforms.size === 0) {- Draw.drawMesh(geometry, matData.shader, transform);- return;- }- m.HEAPF32.set(transform, transformPtr / 4);- let idx = 0;- let autoTextureSlot = 0;- for (const [name, value] of matData.uniforms) {- const nameId = getUniformNameId(name);- if (nameId < 0)- continue;- if (isTextureRef(value)) {- uniformBuffer[idx++] = 10;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.slot ?? autoTextureSlot++;- uniformBuffer[idx++] = value.textureId;- }- else if (typeof value === 'number') {- uniformBuffer[idx++] = 1;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value;- }- else if (Array.isArray(value)) {- uniformBuffer[idx++] = value.length;- uniformBuffer[idx++] = nameId;- for (let i = 0; i < value.length; i++) {- uniformBuffer[idx++] = value[i];- }- }- else if ('w' in value) {- uniformBuffer[idx++] = 4;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- uniformBuffer[idx++] = value.w;- }- else if ('z' in value) {- uniformBuffer[idx++] = 3;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- }- else {- uniformBuffer[idx++] = 2;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- }- if (idx > UNIFORMS_BUFFER_SIZE - 6) {- console.warn('Uniform buffer overflow, some uniforms will be ignored');- break;- }- }- if (idx === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);- return;- }- m.HEAPF32.set(uniformBuffer.subarray(0, idx), uniformsPtr / 4);- m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);- },-};-const UNIFORM_NAME_MAP = {- '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 getUniformNameId(name) {- return UNIFORM_NAME_MAP[name] ?? -1;-}--/**- * @file geometry.ts- * @brief Geometry API for custom mesh rendering- * @details Provides geometry creation and management for custom shapes,- * particles, trails, and other procedural meshes.- */-var DataType;-(function (DataType) {- DataType[DataType["Float"] = 1] = "Float";- DataType[DataType["Float2"] = 2] = "Float2";- DataType[DataType["Float3"] = 3] = "Float3";- DataType[DataType["Float4"] = 4] = "Float4";- DataType[DataType["Int"] = 5] = "Int";- DataType[DataType["Int2"] = 6] = "Int2";- DataType[DataType["Int3"] = 7] = "Int3";- DataType[DataType["Int4"] = 8] = "Int4";-})(DataType || (DataType = {}));-// =============================================================================-// Internal State-// =============================================================================-let module$3 = null;-let vertexPtr = 0;-let indexPtr = 0;-let layoutPtr = 0;-const VERTEX_BUFFER_SIZE = 64 * 1024;-const INDEX_BUFFER_SIZE = 16 * 1024;-const LAYOUT_BUFFER_SIZE = 64;-// =============================================================================-// Initialization-// =============================================================================-function initGeometryAPI(wasmModule) {- module$3 = wasmModule;- vertexPtr = module$3._malloc(VERTEX_BUFFER_SIZE * 4);- indexPtr = module$3._malloc(INDEX_BUFFER_SIZE * 4);- layoutPtr = module$3._malloc(LAYOUT_BUFFER_SIZE * 4);-}-function shutdownGeometryAPI() {- if (module$3) {- if (vertexPtr)- module$3._free(vertexPtr);- if (indexPtr)- module$3._free(indexPtr);- if (layoutPtr)- module$3._free(layoutPtr);- vertexPtr = 0;- indexPtr = 0;- layoutPtr = 0;- }- module$3 = null;-}-// =============================================================================-// Geometry API-// =============================================================================-function getModule$1() {- if (!module$3) {- throw new Error('Geometry API not initialized. Call initGeometryAPI() first.');- }- return module$3;-}-const Geometry = {- /**- * Creates a new geometry with vertices and optional indices.- * @param options Geometry creation options- * @returns Geometry handle- */- create(options) {- const m = getModule$1();- const handle = m.geometry_create();- if (handle === 0) {- throw new Error('Failed to create geometry');- }- const vertexCount = options.vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(options.vertices, vertexPtr / 4);- const layoutCount = options.layout.length;- const layoutArray = new Int32Array(layoutCount);- for (let i = 0; i < layoutCount; i++) {- layoutArray[i] = options.layout[i].type;- }- const heap32 = new Int32Array(m.HEAPU8.buffer, layoutPtr, layoutCount);- heap32.set(layoutArray);- m.geometry_init(handle, vertexPtr, vertexCount, layoutPtr, layoutCount, options.dynamic ?? false);- if (options.indices) {- const indexCount = options.indices.length;- if (indexCount * 4 > INDEX_BUFFER_SIZE * 4) {- throw new Error(`Index data too large: ${indexCount} indices (max ${INDEX_BUFFER_SIZE})`);- }- if (options.indices instanceof Uint16Array) {- const heap16 = new Uint16Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap16.set(options.indices);- m.geometry_setIndices16(handle, indexPtr, indexCount);- }- else {- const heap32 = new Uint32Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap32.set(options.indices);- m.geometry_setIndices32(handle, indexPtr, indexCount);- }- }- return handle;- },- /**- * Updates vertices of a dynamic geometry.- * @param handle Geometry handle- * @param vertices New vertex data- * @param offset Offset in floats- */- updateVertices(handle, vertices, offset = 0) {- const m = getModule$1();- const vertexCount = vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(vertices, vertexPtr / 4);- m.geometry_updateVertices(handle, vertexPtr, vertexCount, offset);- },- /**- * Releases a geometry.- * @param handle Geometry handle- */- release(handle) {- if (handle > 0) {- getModule$1().geometry_release(handle);- }- },- /**- * Checks if a geometry handle is valid.- * @param handle Geometry handle- * @returns True if valid- */- isValid(handle) {- if (!module$3 || handle <= 0)- return false;- return module$3.geometry_isValid(handle);- },- // =========================================================================- // Helper Functions- // =========================================================================- /**- * Creates a unit quad geometry (1x1, centered at origin).- * @returns Geometry handle- */- createQuad(width = 1, height = 1) {- const hw = width / 2;- const hh = height / 2;- return Geometry.create({- vertices: new Float32Array([- // x, y, u, v- -hw, -hh, 0, 0,- hw, -hh, 1, 0,- hw, hh, 1, 1,- -hw, hh, 0, 1,- ]),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array([0, 1, 2, 2, 3, 0]),- });- },- /**- * Creates a circle geometry.- * @param radius Circle radius- * @param segments Number of segments- * @returns Geometry handle- */- createCircle(radius = 1, segments = 32) {- const vertices = [];- const indices = [];- vertices.push(0, 0, 0.5, 0.5);- for (let i = 0; i <= segments; i++) {- const angle = (i / segments) * Math.PI * 2;- const x = Math.cos(angle) * radius;- const y = Math.sin(angle) * radius;- const u = (Math.cos(angle) + 1) / 2;- const v = (Math.sin(angle) + 1) / 2;- vertices.push(x, y, u, v);- }- for (let i = 1; i <= segments; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },- /**- * Creates a polygon geometry from vertices.- * @param points Array of {x, y} points- * @returns Geometry handle- */- createPolygon(points) {- if (points.length < 3) {- throw new Error('Polygon must have at least 3 points');- }- let minX = Infinity, minY = Infinity;- let maxX = -Infinity, maxY = -Infinity;- for (const p of points) {- minX = Math.min(minX, p.x);- minY = Math.min(minY, p.y);- maxX = Math.max(maxX, p.x);- maxY = Math.max(maxY, p.y);- }- const vertices = [];- for (const p of points) {- const u = (p.x - minX) / (maxX - minX);- const v = (p.y - minY) / (maxY - minY);- vertices.push(p.x, p.y, u, v);- }- const indices = [];- for (let i = 1; i < points.length - 1; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },-};--/**- * @file postprocess.ts- * @brief Post-processing effects API- * @details Provides full-screen post-processing effects like blur, vignette, etc.- */-// =============================================================================-// Internal State-// =============================================================================-let module$2 = null;-// =============================================================================-// Initialization-// =============================================================================-function initPostProcessAPI(wasmModule) {- module$2 = wasmModule;-}-function shutdownPostProcessAPI() {- if (module$2 && PostProcess.isInitialized()) {- PostProcess.shutdown();- }- module$2 = null;-}-// =============================================================================-// PostProcess API-// =============================================================================-function getModule() {- if (!module$2) {- throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');- }- return module$2;-}-const PostProcess = {- /**- * Initializes the post-processing pipeline.- * @param width Framebuffer width- * @param height Framebuffer height- * @returns True on success- */- init(width, height) {- return getModule().postprocess_init(width, height);- },- /**- * Shuts down the post-processing pipeline.- */- shutdown() {- getModule().postprocess_shutdown();- },- /**- * Resizes the framebuffers.- * @param width New width- * @param height New height- */- resize(width, height) {- getModule().postprocess_resize(width, height);- },- /**- * Adds a post-processing pass.- * @param name Unique name for the pass- * @param shader Shader handle- * @returns Pass index- */- addPass(name, shader) {- return getModule().postprocess_addPass(name, shader);- },- /**- * Removes a pass by name.- * @param name Pass name- */- removePass(name) {- getModule().postprocess_removePass(name);- },- /**- * Enables or disables a pass.- * @param name Pass name- * @param enabled Whether to enable the pass- */- setEnabled(name, enabled) {- getModule().postprocess_setPassEnabled(name, enabled);- },- /**- * Checks if a pass is enabled.- * @param name Pass name- * @returns True if enabled- */- isEnabled(name) {- return getModule().postprocess_isPassEnabled(name);- },- /**- * Sets a float uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Float value- */- setUniform(passName, uniform, value) {- getModule().postprocess_setUniformFloat(passName, uniform, value);- },- /**- * Sets a vec4 uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Vec4 value- */- setUniformVec4(passName, uniform, value) {- getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);- },- /**- * Begins rendering to the post-process pipeline.- * Call this before rendering your scene.- */- begin() {- getModule().postprocess_begin();- },- /**- * Ends and processes all passes.- * Call this after rendering your scene.- */- end() {- getModule().postprocess_end();- },- /**- * Gets the number of passes.- */- getPassCount() {- return getModule().postprocess_getPassCount();- },- /**- * Checks if the pipeline is initialized.- */- isInitialized() {- if (!module$2)- return false;- return module$2.postprocess_isInitialized();- },- /**- * Sets bypass mode to skip FBO rendering entirely.- * When bypassed, begin()/end() become no-ops and scene renders directly to screen.- * Use this when no post-processing passes are needed for maximum performance.- * @param bypass Whether to bypass the pipeline- */- setBypass(bypass) {- getModule().postprocess_setBypass(bypass);- },- /**- * Checks if bypass mode is enabled.- * @returns True if bypassed- */- isBypassed() {- if (!module$2)- return true;- return module$2.postprocess_isBypassed();- },- // =========================================================================- // Built-in Effects- // =========================================================================- /**- * Creates a blur effect shader.- * @returns Shader handle- */- createBlur() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 texelSize = 1.0 / u_resolution;- float offset = u_intensity;-- vec4 color = vec4(0.0);- color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord) * 0.25;- color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;-- fragColor = color;-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a vignette effect shader.- * @returns Shader handle- */- createVignette() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-uniform float u_softness;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- vec2 uv = v_texCoord * 2.0 - 1.0;- float dist = length(uv);- float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);- fragColor = vec4(color.rgb * vignette, color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a grayscale effect shader.- * @returns Shader handle- */- createGrayscale() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));- fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a chromatic aberration effect shader.- * @returns Shader handle- */- createChromaticAberration() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 offset = u_intensity / u_resolution;- float r = texture(u_texture, v_texCoord + offset).r;- float g = texture(u_texture, v_texCoord).g;- float b = texture(u_texture, v_texCoord - offset).b;- float a = texture(u_texture, v_texCoord).a;- fragColor = vec4(r, g, b, a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },-};-// =============================================================================-// Shared Vertex Shader-// =============================================================================-const POSTPROCESS_VERTEX = `#version 300 es-precision highp float;--layout(location = 0) in vec2 a_position;-layout(location = 1) in vec2 a_texCoord;--out vec2 v_texCoord;--void main() {- v_texCoord = a_texCoord;- gl_Position = vec4(a_position, 0.0, 1.0);-}-`;--var RenderStage;-(function (RenderStage) {- RenderStage[RenderStage["Background"] = 0] = "Background";- RenderStage[RenderStage["Opaque"] = 1] = "Opaque";- RenderStage[RenderStage["Transparent"] = 2] = "Transparent";- RenderStage[RenderStage["Overlay"] = 3] = "Overlay";-})(RenderStage || (RenderStage = {}));-let module$1 = null;-let viewProjectionPtr = 0;-function initRendererAPI(wasmModule) {- module$1 = wasmModule;- viewProjectionPtr = module$1._malloc(16 * 4);-}-function shutdownRendererAPI() {- if (module$1 && viewProjectionPtr) {- module$1._free(viewProjectionPtr);- viewProjectionPtr = 0;- }- module$1 = null;-}-const Renderer = {- init(width, height) {- module$1?.renderer_init(width, height);- },- resize(width, height) {- module$1?.renderer_resize(width, height);- },- begin(viewProjection, target) {- if (!module$1 || !viewProjectionPtr)- return;- module$1.HEAPF32.set(viewProjection, viewProjectionPtr / 4);- module$1.renderer_begin(viewProjectionPtr, target ?? 0);- },- end() {- module$1?.renderer_end();- },- submitSprites(registry) {- if (!module$1)- return;- module$1.renderer_submitSprites(registry._cpp);- },- submitSpine(registry) {- if (!module$1)- return;- module$1.renderer_submitSpine(registry._cpp);- },- setStage(stage) {- module$1?.renderer_setStage(stage);- },- createRenderTarget(width, height, flags = 1) {- return module$1?.renderer_createTarget(width, height, flags) ?? 0;- },- releaseRenderTarget(handle) {- module$1?.renderer_releaseTarget(handle);- },- getTargetTexture(handle) {- return module$1?.renderer_getTargetTexture(handle) ?? 0;- },- getTargetDepthTexture(handle) {- return module$1?.renderer_getTargetDepthTexture(handle) ?? 0;- },- setClearColor(r, g, b, a) {- module$1?.renderer_setClearColor?.(r, g, b, a);- },- getStats() {- if (!module$1) {- return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };- }- return {- drawCalls: module$1.renderer_getDrawCalls(),- triangles: module$1.renderer_getTriangles(),- sprites: module$1.renderer_getSprites(),- spine: module$1.renderer_getSpine(),- meshes: module$1.renderer_getMeshes(),- culled: module$1.renderer_getCulled(),- };- },-};--/**- * @file customDraw.ts- * @brief Custom draw callback registration for the render pipeline- */-const callbacks = new Map();-function registerDrawCallback(id, fn) {- callbacks.set(id, fn);-}-function unregisterDrawCallback(id) {- callbacks.delete(id);-}-function clearDrawCallbacks() {- callbacks.clear();-}-function getDrawCallbacks() {- return callbacks;-}--/**- * @file renderPipeline.ts- * @brief Unified render pipeline for runtime and editor- */-class RenderPipeline {- render(params) {- const { registry, viewProjection, width, height, elapsed } = params;- Renderer.resize(width, height);- const usePostProcess = PostProcess.isInitialized()- && PostProcess.getPassCount() > 0- && !PostProcess.isBypassed();- if (usePostProcess) {- PostProcess.resize(width, height);- PostProcess.begin();- }- Renderer.begin(viewProjection);- Renderer.submitSprites(registry);- Renderer.submitSpine(registry);- Renderer.end();- const cbs = getDrawCallbacks();- if (cbs.size > 0) {- Draw.begin(viewProjection);- const failed = [];- for (const [id, fn] of cbs.entries()) {- try {- fn(elapsed);- }- catch (e) {- console.error(`[CustomDraw] callback '${id}' error:`, e);- failed.push(id);- }- }- Draw.end();- for (const id of failed) {- unregisterDrawCallback(id);- }- }- if (usePostProcess) {- PostProcess.end();- }- }-}--/**- * @file app.ts- * @brief Application builder and web platform integration- */-// =============================================================================-// App-// =============================================================================-class App {- constructor() {- this.systems_ = new Map();- this.runner_ = null;- this.running_ = false;- this.lastTime_ = 0;- this.module_ = null;- this.mainLoop = () => {- if (!this.running_) {- return;- }- const now = performance.now();- const deltaMs = now - this.lastTime_;- this.lastTime_ = now;- const delta = deltaMs / 1000;- this.updateTime(delta);- this.runSchedule(Schedule.First);- this.runSchedule(Schedule.PreUpdate);- this.runSchedule(Schedule.Update);- this.runSchedule(Schedule.PostUpdate);- this.runSchedule(Schedule.Last);- requestAnimationFrame(this.mainLoop);- };- this.world_ = new World();- this.resources_ = new ResourceStorage();- for (const s of Object.values(Schedule)) {- if (typeof s === 'number') {- this.systems_.set(s, []);- }- }- }- static new() {- return new App();- }- // =========================================================================- // Plugins- // =========================================================================- addPlugin(plugin) {- plugin.build(this);- return this;- }- // =========================================================================- // Systems- // =========================================================================- addSystemToSchedule(schedule, system) {- this.systems_.get(schedule).push({ system });- return this;- }- addSystem(system) {- return this.addSystemToSchedule(Schedule.Update, system);- }- addStartupSystem(system) {- return this.addSystemToSchedule(Schedule.Startup, system);- }- // =========================================================================- // C++ Integration- // =========================================================================- connectCpp(cppRegistry, module) {- this.world_.connectCpp(cppRegistry);- if (module) {- this.module_ = module;- }- return this;- }- get wasmModule() {- return this.module_;- }- // =========================================================================- // World Access- // =========================================================================- get world() {- return this.world_;- }- // =========================================================================- // Resource Access- // =========================================================================- insertResource(resource, value) {- this.resources_.insert(resource, value);- return this;- }- getResource(resource) {- return this.resources_.get(resource);- }- hasResource(resource) {- return this.resources_.has(resource);- }- // =========================================================================- // Run- // =========================================================================- run() {- if (this.running_) {- return;- }- this.running_ = true;- this.runner_ = new SystemRunner(this.world_, this.resources_);- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });- this.runSchedule(Schedule.Startup);- this.lastTime_ = performance.now();- this.mainLoop();- }- quit() {- this.running_ = false;- shutdownRendererAPI();- shutdownPostProcessAPI();- shutdownGeometryAPI();- shutdownMaterialAPI();- shutdownDrawAPI();- }- // =========================================================================- // Internal- // =========================================================================- runSchedule(schedule) {- const systems = this.systems_.get(schedule);- if (!systems || !this.runner_) {- return;- }- for (const entry of systems) {- this.runner_.run(entry.system);- }- }- updateTime(delta) {- const time = this.resources_.get(Time);- const newTime = {- delta,- elapsed: time.elapsed + delta,- frameCount: time.frameCount + 1- };- this.resources_.set(Time, newTime);- }-}-function createWebApp(module, options) {- const app = App.new();- const cppRegistry = new module.Registry();- app.connectCpp(cppRegistry, module);- if (options?.glContextHandle) {- module.initRendererWithContext(options.glContextHandle);- }- else {- module.initRenderer();- }- initDrawAPI(module);- initMaterialAPI(module);- initGeometryAPI(module);- initPostProcessAPI(module);- initRendererAPI(module);- const pipeline = new RenderPipeline();- let startTime = performance.now();- const getViewportSize = options?.getViewportSize ?? (() => ({- width: window.innerWidth * (window.devicePixelRatio || 1),- height: window.innerHeight * (window.devicePixelRatio || 1)- }));- const renderSystem = {- _id: Symbol('RenderSystem'),- _name: 'RenderSystem',- _params: [],- _fn: () => {- const { width, height } = getViewportSize();- const vp = computeViewProjection(cppRegistry, width, height);- const elapsed = (performance.now() - startTime) / 1000;- pipeline.render({- registry: { _cpp: cppRegistry },- viewProjection: vp,- width, height, elapsed,- });- }- };- app.addSystemToSchedule(Schedule.Last, renderSystem);- app.addPlugin(textPlugin);- return app;-}-function flushPendingSystems(app) {- if (typeof window === 'undefined')- return;- const pending = window.__esengine_pendingSystems;- if (!pending || pending.length === 0)- return;- for (const entry of pending) {- app.addSystemToSchedule(entry.schedule, entry.system);- }- pending.length = 0;-}-// =============================================================================-// View-Projection Computation-// =============================================================================-const IDENTITY = new Float32Array([- 1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1,-]);-function computeViewProjection(registry, width, height) {- const count = registry.entityCount();- const scanLimit = count + 1000;- for (let e = 0; e < scanLimit; e++) {- if (!registry.valid(e) || !registry.hasCamera(e) || !registry.hasLocalTransform(e)) {- continue;- }- const camera = registry.getCamera(e);- if (!camera.isActive)- continue;- const transform = registry.getLocalTransform(e);- const aspect = width / height;- let projection;- if (camera.projectionType === 1) {- const halfH = camera.orthoSize;- const halfW = halfH * aspect;- projection = ortho(-halfW, halfW, -halfH, halfH, -camera.farPlane, camera.farPlane);- }- else {- projection = perspective(camera.fov * Math.PI / 180, aspect, camera.nearPlane, camera.farPlane);- }- const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);- return multiply(projection, view);- }- return IDENTITY;-}-function ortho(left, right, bottom, top, near, far) {- const m = new Float32Array(16);- const rl = right - left;- const tb = top - bottom;- const fn = far - near;- m[0] = 2 / rl;- m[5] = 2 / tb;- m[10] = -2 / fn;- m[12] = -(right + left) / rl;- m[13] = -(top + bottom) / tb;- m[14] = -(far + near) / fn;- m[15] = 1;- return m;-}-function perspective(fovRad, aspect, near, far) {- const m = new Float32Array(16);- const f = 1.0 / Math.tan(fovRad / 2);- const nf = near - far;- m[0] = f / aspect;- m[5] = f;- m[10] = (far + near) / nf;- m[11] = -1;- m[14] = (2 * far * near) / nf;- return m;-}-function invertTranslation(x, y, z) {- const m = new Float32Array(16);- m[0] = 1;- m[5] = 1;- m[10] = 1;- m[15] = 1;- m[12] = -x;- m[13] = -y;- m[14] = -z;- return m;-}-function multiply(a, b) {- const m = new Float32Array(16);- for (let i = 0; i < 4; i++) {- for (let j = 0; j < 4; j++) {- m[j * 4 + i] =- a[0 * 4 + i] * b[j * 4 + 0] +- a[1 * 4 + i] * b[j * 4 + 1] +- a[2 * 4 + i] * b[j * 4 + 2] +- a[3 * 4 + i] * b[j * 4 + 3];- }- }- return m;-}--/**- * @file MaterialLoader.ts- * @brief Material asset loading and caching- */-// =============================================================================-// MaterialLoader-// =============================================================================-class MaterialLoader {- constructor(shaderLoader, basePath = '') {- this.cache_ = new Map();- this.pending_ = new Map();- this.shaderLoader_ = shaderLoader;- this.basePath_ = basePath;- }- async load(path) {- const cached = this.cache_.get(path);- if (cached) {- return cached;- }- const pending = this.pending_.get(path);- if (pending) {- return pending;- }- const promise = this.loadInternal(path);- this.pending_.set(path, promise);- try {- const result = await promise;- this.cache_.set(path, result);- return result;- }- finally {- this.pending_.delete(path);- }- }- get(path) {- return this.cache_.get(path);- }- has(path) {- return this.cache_.has(path);- }- release(path) {- const loaded = this.cache_.get(path);- if (loaded) {- Material.release(loaded.handle);- this.cache_.delete(path);- }- }- releaseAll() {- for (const loaded of this.cache_.values()) {- Material.release(loaded.handle);- }- this.cache_.clear();- }- async loadInternal(path) {- const fullPath = this.resolvePath(path);- const exists = await platformFileExists(fullPath);- if (!exists) {- throw new Error(`Material file not found: ${fullPath}`);- }- const content = await platformReadTextFile(fullPath);- if (!content) {- throw new Error(`Failed to read material file: ${fullPath}`);- }- const data = JSON.parse(content);- if (data.type !== 'material') {- throw new Error(`Invalid material file type: ${data.type}`);- }- const shaderPath = this.resolveShaderPath(path, data.shader);- const shaderHandle = await this.shaderLoader_.load(shaderPath);- const materialHandle = Material.createFromAsset(data, shaderHandle);- return {- handle: materialHandle,- shaderHandle,- path,- };- }- resolvePath(path) {- if (path.startsWith('/') || path.startsWith('http')) {- return path;- }- return this.basePath_ ? `${this.basePath_}/${path}` : path;- }- resolveShaderPath(materialPath, shaderPath) {- if (shaderPath.startsWith('/') || shaderPath.startsWith('http') || shaderPath.startsWith('assets/')) {- return shaderPath;- }- const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));- return dir ? `${dir}/${shaderPath}` : shaderPath;- }-}--/**- * @file scene.ts- * @brief Scene loading utilities- */-// =============================================================================-// Scene Loader-// =============================================================================-function loadSceneData(world, sceneData) {- const entityMap = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- loadComponent(world, entity, compData);- }- }- // Set parent-child relationships- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- return entityMap;-}-async function loadSceneWithAssets(world, sceneData, options) {- const entityMap = new Map();- const assetServer = options?.assetServer;- const texturePathToUrl = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- }- catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data;- const skeletonPath = data.skeletonPath;- const atlasPath = data.atlasPath;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- loadComponent(world, entity, compData);- }- }- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- if (assetServer && sceneData.textureMetadata) {- for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {- const url = texturePathToUrl.get(texturePath);- if (url && metadata.sliceBorder) {- assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);- }- }- }- return entityMap;-}-function loadComponent(world, entity, compData) {- const data = compData.data;- switch (compData.type) {- case 'LocalTransform':- world.insert(entity, LocalTransform, data);- break;- case 'Sprite':- world.insert(entity, Sprite, data);- break;- case 'Camera':- world.insert(entity, Camera, data);- break;- case 'Canvas':- world.insert(entity, Canvas, data);- break;- case 'Text':- world.insert(entity, Text, data);- break;- case 'SpineAnimation':- world.insert(entity, SpineAnimation, data);- break;- case 'UIRect':- world.insert(entity, UIRect, data);- break;- default: {- const userComp = getUserComponent(compData.type);- if (userComp) {- world.insert(entity, userComp, data);- }- else {- console.warn(`Unknown component type: ${compData.type}`);- }- break;- }- }-}-function updateCameraAspectRatio(world, aspectRatio) {- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera) {- camera.aspectRatio = aspectRatio;- world.insert(entity, Camera, camera);- }- }-}--class AsyncCache {- constructor() {- this.cache_ = new Map();- this.pending_ = new Map();- }- async getOrLoad(key, loader) {- const cached = this.cache_.get(key);- if (cached !== undefined) {- return cached;- }- const pending = this.pending_.get(key);- if (pending) {- return pending;- }- const promise = loader();- this.pending_.set(key, promise);- try {- const result = await promise;- this.cache_.set(key, result);- return result;- }- finally {- this.pending_.delete(key);- }- }- get(key) {- return this.cache_.get(key);- }- has(key) {- return this.cache_.has(key);- }- delete(key) {- return this.cache_.delete(key);- }- clear() {- this.cache_.clear();- }- values() {- return this.cache_.values();- }-}--/**- * @file AssetServer.ts- * @brief Asset loading and caching system- */-// =============================================================================-// AssetServer-// =============================================================================-class AssetServer {- constructor(module) {- this.textureCache_ = new AsyncCache();- this.shaderCache_ = new AsyncCache();- this.jsonCache_ = new AsyncCache();- this.textCache_ = new AsyncCache();- this.binaryCache_ = new AsyncCache();- this.loadedSpines_ = new Set();- this.virtualFSPaths_ = new Set();- this.module_ = module;- this.canvas_ = this.createCanvas(512, 512);- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- const shaderLoader = {- load: (path) => this.loadShader(path),- get: (path) => this.shaderCache_.get(path),- };- this.materialLoader_ = new MaterialLoader(shaderLoader);- }- // =========================================================================- // Texture- // =========================================================================- /**- * Load texture with vertical flip (for Sprite/UI).- * OpenGL UV origin is bottom-left, so standard images need flipping.- */- async loadTexture(source) {- return this.loadTextureWithFlip(source, true);- }- /**- * Load texture without flip (for Spine).- * Spine runtime handles UV coordinates internally.- */- async loadTextureRaw(source) {- return this.loadTextureWithFlip(source, false);- }- getTexture(source) {- return this.textureCache_.get(this.textureCacheKey(source, true));- }- hasTexture(source) {- return this.textureCache_.has(this.textureCacheKey(source, true));- }- releaseTexture(source) {- const rm = this.module_.getResourceManager();- for (const flip of [true, false]) {- const key = this.textureCacheKey(source, flip);- const info = this.textureCache_.get(key);- if (info) {- rm.releaseTexture(info.handle);- this.textureCache_.delete(key);- }- }- }- releaseAll() {- const rm = this.module_.getResourceManager();- for (const info of this.textureCache_.values()) {- rm.releaseTexture(info.handle);- }- this.textureCache_.clear();- this.jsonCache_.clear();- this.textCache_.clear();- this.binaryCache_.clear();- }- setTextureMetadata(handle, border) {- const rm = this.module_.getResourceManager();- rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);- }- setTextureMetadataByPath(source, border) {- const info = this.textureCache_.get(this.textureCacheKey(source, true));- if (info) {- this.setTextureMetadata(info.handle, border);- return true;- }- return false;- }- // =========================================================================- // Spine- // =========================================================================- async loadSpine(skeletonPath, atlasPath, baseUrl) {- const cacheKey = `${skeletonPath}:${atlasPath}`;- if (this.loadedSpines_.has(cacheKey)) {- return { success: true };- }- try {- const atlasUrl = this.resolveUrl(atlasPath, baseUrl);- const atlasResponse = await fetch(atlasUrl);- if (!atlasResponse.ok) {- return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };- }- const atlasContent = await atlasResponse.text();- if (!this.writeToVirtualFS(atlasPath, atlasContent)) {- return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };- }- const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));- const textureNames = this.parseAtlasTextures(atlasContent);- for (const texName of textureNames) {- const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;- const texUrl = this.resolveUrl(texPath, baseUrl);- try {- const info = await this.loadTextureRaw(texUrl);- const rm = this.module_.getResourceManager();- rm.registerTextureWithPath(info.handle, texPath);- }- catch (err) {- console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);- }- }- const skelUrl = this.resolveUrl(skeletonPath, baseUrl);- const skelResponse = await fetch(skelUrl);- if (!skelResponse.ok) {- return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };- }- const isBinary = skeletonPath.endsWith('.skel');- const skelData = isBinary- ? new Uint8Array(await skelResponse.arrayBuffer())- : await skelResponse.text();- if (!this.writeToVirtualFS(skeletonPath, skelData)) {- return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };- }- this.loadedSpines_.add(cacheKey);- return { success: true };- }- catch (err) {- return { success: false, error: String(err) };- }- }- isSpineLoaded(skeletonPath, atlasPath) {- return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);- }- // =========================================================================- // Material & Shader- // =========================================================================- async loadMaterial(path, baseUrl) {- return this.materialLoader_.load(this.resolveUrl(path, baseUrl));- }- getMaterial(path, baseUrl) {- return this.materialLoader_.get(this.resolveUrl(path, baseUrl));- }- hasMaterial(path, baseUrl) {- return this.materialLoader_.has(this.resolveUrl(path, baseUrl));- }- async loadShader(path) {- return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));- }- // =========================================================================- // Generic File Loading- // =========================================================================- async loadJson(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchJson(url);- }- return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));- }- async loadText(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchText(url);- }- return this.textCache_.getOrLoad(url, () => this.fetchText(url));- }- async loadBinary(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchBinary(url);- }- return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));- }- // =========================================================================- // Scene & Batch- // =========================================================================- async loadScene(world, sceneData) {- return loadSceneWithAssets(world, sceneData, { assetServer: this });- }- async loadAll(manifest) {- const bundle = {- textures: new Map(),- materials: new Map(),- spine: new Map(),- json: new Map(),- text: new Map(),- binary: new Map(),- };- const promises = [];- if (manifest.textures) {- for (const path of manifest.textures) {- promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));- }- }- if (manifest.materials) {- for (const path of manifest.materials) {- promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));- }- }- if (manifest.spine) {- for (const desc of manifest.spine) {- const key = `${desc.skeleton}:${desc.atlas}`;- promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {- bundle.spine.set(key, result);- }));- }- }- if (manifest.json) {- for (const path of manifest.json) {- promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));- }- }- if (manifest.text) {- for (const path of manifest.text) {- promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));- }- }- if (manifest.binary) {- for (const path of manifest.binary) {- promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));- }- }- await Promise.all(promises);- return bundle;- }- // =========================================================================- // Private - Texture- // =========================================================================- textureCacheKey(source, flip) {- return `${source}:${flip ? 'f' : 'n'}`;- }- async loadTextureWithFlip(source, flip) {- const cacheKey = this.textureCacheKey(source, flip);- return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));- }- async loadTextureInternal(source, flip) {- const img = await this.loadImage(source);- return this.createTextureFromImage(img, flip);- }- async loadImage(source) {- return new Promise((resolve, reject) => {- const img = new Image();- img.crossOrigin = 'anonymous';- img.onload = async () => {- if (typeof createImageBitmap !== 'undefined') {- try {- const bitmap = await createImageBitmap(img, {- premultiplyAlpha: 'none',- colorSpaceConversion: 'none'- });- resolve(bitmap);- return;- }- catch {- // Fall back to Image element- }- }- resolve(img);- };- img.onerror = () => reject(new Error(`Failed to load image: ${source}`));- img.src = source;- });- }- createTextureFromImage(img, flip) {- const { width, height } = img;- if (this.canvas_.width < width || this.canvas_.height < height) {- this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));- this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));- }- this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);- this.ctx_.save();- if (flip) {- this.ctx_.translate(0, height);- this.ctx_.scale(1, -1);- }- this.ctx_.drawImage(img, 0, 0);- this.ctx_.restore();- const imageData = this.ctx_.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);- const rm = this.module_.getResourceManager();- const ptr = this.module_._malloc(pixels.length);- this.module_.HEAPU8.set(pixels, ptr);- const handle = rm.createTexture(width, height, ptr, pixels.length, 1);- this.module_._free(ptr);- return { handle, width, height };- }- unpremultiplyAlpha(pixels) {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }- // =========================================================================- // Private - Shader- // =========================================================================- async loadShaderInternal(path) {- const exists = await platformFileExists(path);- if (!exists) {- throw new Error(`Shader file not found: ${path}`);- }- const content = await platformReadTextFile(path);- if (!content) {- throw new Error(`Failed to read shader file: ${path}`);- }- const { vertex, fragment } = this.parseEsShader(content);- if (!vertex || !fragment) {- throw new Error(`Invalid shader format: ${path}`);- }- return Material.createShader(vertex, fragment);- }- parseEsShader(content) {- const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);- const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);- return {- vertex: vertexMatch?.[1].trim() ?? null,- fragment: fragmentMatch?.[1].trim() ?? null,- };- }- // =========================================================================- // Private - Generic Fetch- // =========================================================================- async fetchJson(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);- }- return response.json();- }- async fetchText(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch text: ${url} (${response.status})`);- }- return response.text();- }- async fetchBinary(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch binary: ${url} (${response.status})`);- }- return response.arrayBuffer();- }- // =========================================================================- // Private - Virtual FS- // =========================================================================- writeToVirtualFS(virtualPath, data) {- if (this.virtualFSPaths_.has(virtualPath)) {- return true;- }- const fs = this.module_.FS;- if (!fs) {- return false;- }- try {- this.ensureVirtualDir(virtualPath);- fs.writeFile(virtualPath, data);- this.virtualFSPaths_.add(virtualPath);- return true;- }- catch (e) {- console.error(`[AssetServer] Failed to write to virtual FS: ${virtualPath}`, e);- return false;- }- }- ensureVirtualDir(virtualPath) {- const fs = this.module_.FS;- if (!fs)- return;- const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));- if (!dir)- return;- const parts = dir.split('/').filter(p => p);- let currentPath = '';- for (const part of parts) {- currentPath = currentPath ? `${currentPath}/${part}` : part;- try {- const analysis = fs.analyzePath(currentPath);- if (!analysis.exists) {- fs.mkdir(currentPath);- }- }- catch {- try {- fs.mkdir(currentPath);- }- catch {- // Directory might already exist- }- }- }- }- // =========================================================================- // Private - Utilities- // =========================================================================- resolveUrl(path, baseUrl) {- if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {- return path;- }- const base = baseUrl ?? this.baseUrl;- return base ? `${base}/${path}` : `/${path}`;- }- createCanvas(width, height) {- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(width, height)- : document.createElement('canvas');- canvas.width = width;- canvas.height = height;- return canvas;- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- parseAtlasTextures(atlasContent) {- const textures = [];- for (const line of atlasContent.split('\n')) {- const trimmed = line.trim();- if (trimmed && !trimmed.includes(':') &&- (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {- textures.push(trimmed);- }- }- return textures;- }-}--/**- * @file AssetPlugin.ts- * @brief Plugin that provides asset loading capabilities- */-const Assets = defineResource(null, 'Assets');-// =============================================================================-// Asset Plugin-// =============================================================================-class AssetPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('AssetPlugin: No WASM module available');- return;- }- app.insertResource(Assets, new AssetServer(module));- }-}-const assetPlugin = new AssetPlugin();--/**- * @file PreviewPlugin.ts- * @brief Plugin for editor preview functionality- */-// =============================================================================-// PreviewPlugin-// =============================================================================-class PreviewPlugin {- constructor(sceneUrl) {- this.app_ = null;- this.loadPromise_ = null;- this.sceneUrl_ = sceneUrl;- }- build(app) {- this.app_ = app;- if (!app.hasResource(Assets)) {- app.addPlugin(assetPlugin);- }- this.loadPromise_ = this.loadScene();- }- /**- * @brief Wait for scene loading to complete- */- async waitForReady() {- if (this.loadPromise_) {- await this.loadPromise_;- }- }- async loadScene() {- 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();- const assets = this.app_.getResource(Assets);- await assets.loadScene(this.app_.world, sceneData);- this.ensureCamera();- }- catch (err) {- console.error('[PreviewPlugin] Failed to load scene:', err);- }- }- ensureCamera() {- if (!this.app_)- return;- const world = this.app_.world;- let hasActiveCamera = false;- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera.isActive) {- hasActiveCamera = true;- break;- }- }- if (!hasActiveCamera) {- console.warn('[PreviewPlugin] No active camera found, creating default camera');- const cameraEntity = world.spawn();- const transformData = {- position: { x: 0, y: 0, z: 10 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- };- world.insert(cameraEntity, LocalTransform, transformData);- const cameraData = {- isActive: true,- projectionType: 0,- fov: 60,- orthoSize: 540,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- priority: 0,- };- world.insert(cameraEntity, Camera, cameraData);- }- }-}--/**- * @file spine.ts- * @brief Spine animation control API- */-// =============================================================================-// SpineController-// =============================================================================-/**- * Controller for Spine skeletal animations- *- * @example- * ```typescript- * const spine = new SpineController(wasmModule);- *- * // Play animation- * spine.play(entity, 'run', true);- *- * // Queue next animation- * spine.addAnimation(entity, 'idle', true, 0.2);- *- * // Change skin- * spine.setSkin(entity, 'warrior');- *- * // Get bone position for effects- * const pos = spine.getBonePosition(entity, 'weapon');- * if (pos) {- * spawnEffect(pos.x, pos.y);- * }- *- * // Listen for events- * spine.on(entity, 'event', (e) => {- * if (e.eventName === 'footstep') {- * playSound('footstep');- * }- * });- * ```- */-class SpineController {- constructor(wasmModule) {- this.module_ = wasmModule;- this.listeners_ = new Map();- this.setupEventBridge();- }- // =========================================================================- // Animation Control- // =========================================================================- /**- * Plays an animation, replacing any current animation on the track- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop the animation- * @param track Animation track (default 0)- * @returns True if animation was set- */- play(entity, animation, loop = true, track = 0) {- if (!this.module_.spinePlayAnimation)- return false;- return this.module_.spinePlayAnimation(entity, animation, loop, track);- }- /**- * Adds an animation to the queue- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop- * @param delay Delay before starting (seconds)- * @param track Animation track (default 0)- * @returns True if animation was queued- */- addAnimation(entity, animation, loop = true, delay = 0, track = 0) {- if (!this.module_.spineAddAnimation)- return false;- return this.module_.spineAddAnimation(entity, animation, loop, delay, track);- }- /**- * Sets an empty animation to mix out the current animation- * @param entity Target entity- * @param mixDuration Duration of the mix out- * @param track Animation track (default 0)- */- setEmptyAnimation(entity, mixDuration = 0.2, track = 0) {- if (!this.module_.spineSetEmptyAnimation)- return;- this.module_.spineSetEmptyAnimation(entity, mixDuration, track);- }- /**- * Clears all animations on a track- * @param entity Target entity- * @param track Animation track (default 0)- */- clearTrack(entity, track = 0) {- if (!this.module_.spineClearTrack)- return;- this.module_.spineClearTrack(entity, track);- }- /**- * Clears all tracks- * @param entity Target entity- */- clearTracks(entity) {- if (!this.module_.spineClearTracks)- return;- this.module_.spineClearTracks(entity);- }- // =========================================================================- // Skin Control- // =========================================================================- /**- * Sets the current skin- * @param entity Target entity- * @param skinName Skin name- * @returns True if skin was set- */- setSkin(entity, skinName) {- if (!this.module_.spineSetSkin)- return false;- return this.module_.spineSetSkin(entity, skinName);- }- /**- * Gets available skin names- * @param entity Target entity- * @returns Array of skin names- */- getSkins(entity) {- if (!this.module_.spineGetSkins)- return [];- return this.module_.spineGetSkins(entity) || [];- }- // =========================================================================- // Queries- // =========================================================================- /**- * Gets available animation names- * @param entity Target entity- * @returns Array of animation names- */- getAnimations(entity) {- if (!this.module_.spineGetAnimations)- return [];- return this.module_.spineGetAnimations(entity) || [];- }- /**- * Gets the current animation on a track- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Animation name or null- */- getCurrentAnimation(entity, track = 0) {- if (!this.module_.spineGetCurrentAnimation)- return null;- return this.module_.spineGetCurrentAnimation(entity, track);- }- /**- * Gets the duration of an animation- * @param entity Target entity- * @param animation Animation name- * @returns Duration in seconds, or 0 if not found- */- getAnimationDuration(entity, animation) {- if (!this.module_.spineGetAnimationDuration)- return 0;- return this.module_.spineGetAnimationDuration(entity, animation);- }- /**- * Gets detailed track entry info- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Track entry info or null- */- getTrackEntry(entity, track = 0) {- if (!this.module_.spineGetTrackEntry)- return null;- return this.module_.spineGetTrackEntry(entity, track);- }- // =========================================================================- // Bone/Slot Access- // =========================================================================- /**- * Gets world position of a bone- * @param entity Target entity- * @param boneName Bone name- * @returns Position or null if not found- */- getBonePosition(entity, boneName) {- if (!this.module_.spineGetBonePosition)- return null;- const result = this.module_.spineGetBonePosition(entity, boneName);- if (!result)- return null;- return { x: result.x, y: result.y };- }- /**- * Gets world rotation of a bone in degrees- * @param entity Target entity- * @param boneName Bone name- * @returns Rotation in degrees or null- */- getBoneRotation(entity, boneName) {- if (!this.module_.spineGetBoneRotation)- return null;- return this.module_.spineGetBoneRotation(entity, boneName);- }- /**- * Sets the attachment for a slot- * @param entity Target entity- * @param slotName Slot name- * @param attachmentName Attachment name (null to clear)- */- setAttachment(entity, slotName, attachmentName) {- if (!this.module_.spineSetAttachment)- return;- this.module_.spineSetAttachment(entity, slotName, attachmentName || '');- }- // =========================================================================- // Events- // =========================================================================- /**- * Registers an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- on(entity, type, callback) {- if (!this.listeners_.has(entity)) {- this.listeners_.set(entity, new Map());- }- const entityListeners = this.listeners_.get(entity);- if (!entityListeners.has(type)) {- entityListeners.set(type, new Set());- }- entityListeners.get(type).add(callback);- }- /**- * Unregisters an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- off(entity, type, callback) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const typeListeners = entityListeners.get(type);- if (!typeListeners)- return;- typeListeners.delete(callback);- }- /**- * Removes all event listeners for an entity- * @param entity Target entity- */- removeAllListeners(entity) {- this.listeners_.delete(entity);- }- // =========================================================================- // Private- // =========================================================================- setupEventBridge() {- if (typeof window !== 'undefined') {- window.__esengine_spineEvent = (entity, eventData) => {- this.dispatchEvent(entity, eventData);- };- }- }- dispatchEvent(entity, eventData) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const event = {- type: eventData.type,- entity,- track: eventData.track ?? 0,- animation: eventData.animation ?? null,- eventName: eventData.eventName,- intValue: eventData.intValue,- floatValue: eventData.floatValue,- stringValue: eventData.stringValue,- };- const typeListeners = entityListeners.get(event.type);- if (typeListeners) {- typeListeners.forEach(callback => {- try {- callback(event);- }- catch (e) {- console.error('Error in Spine event callback:', e);- }- });- }- }-}-// =============================================================================-// Factory Function-// =============================================================================-/**- * Creates a SpineController instance- * @param wasmModule The ESEngine WASM module- * @returns SpineController instance- */-function createSpineController(wasmModule) {- return new SpineController(wasmModule);-}--const RenderTexture = {- create(options) {- const depth = options.depth ?? true;- const linear = options.filter === 'linear';- const flags = (depth ? 1 : 0) | (linear ? 2 : 0);- const handle = Renderer.createRenderTarget(options.width, options.height, flags);- const textureId = Renderer.getTargetTexture(handle);- return {- _handle: handle,- textureId,- width: options.width,- height: options.height,- };- },- release(rt) {- Renderer.releaseRenderTarget(rt._handle);- },- resize(rt, width, height) {- Renderer.releaseRenderTarget(rt._handle);- return RenderTexture.create({ width, height, depth: true });- },- begin(rt, viewProjection) {- Renderer.begin(viewProjection, rt._handle);- },- end() {- Renderer.end();- },- getDepthTexture(rt) {- return Renderer.getTargetDepthTexture(rt._handle);- },-};--let editorMode = false;-function setEditorMode(active) {- editorMode = active;-}-function isEditor() {- return editorMode;-}-function isRuntime() {- return !editorMode;-}--/**- * @file index.wechat.ts- * @brief ESEngine SDK - WeChat MiniGame entry point- */-// Initialize WeChat platform-initWeChatPlatform();-setPlatform(wechatAdapter);--export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, wxFileExists, wxFileExistsSync, wxGetImagePixels, wxLoadImage, wxLoadImagePixels, wxReadFile, wxReadTextFile, wxWriteFile };+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function r(){return null!==e}function n(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,r){return t().fetch(e,r)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,r){return t().instantiateWasm(e,r)}function h(e,t){return new Promise((r,n)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function d(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let f=null;function p(){return f||(f=wx.getFileSystemManager()),f}function _(e){return new Promise((t,r)=>{p().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function m(e,t="utf-8"){return new Promise((r,n)=>{p().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function g(e){return new Promise(t=>{p().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function y(e){const t=p();try{return t.accessSync(e),!0}catch{return!1}}function w(e,t){return new Promise((r,n)=>{p().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let x=null,v=null;function S(e){return new Promise((t,r)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return x||(x=wx.createCanvas(),x.width=e,x.height=t,v=x.getContext("2d")),(x.width<e||x.height<t)&&(x.width=Math.max(x.width,e),x.height=Math.max(x.height,t)),{canvas:x,ctx:v}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const i=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(i.data.buffer)}}async function b(e,t=!0){return C(await S(e),t)}let T=!1;const P=new class{constructor(){this.name="wechat"}async fetch(e,t){return h(e,t)}async readFile(e){return _(e)}async readTextFile(e){return m(e)}async fileExists(e){return g(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return d(e,t)}},E=0,A=4294967295,M=(e=0,t=0)=>({x:e,y:t}),R=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),F=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),U=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),z=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let $=0;function W(e,t){const r=++$;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function k(e,t){const r=I(),n=r.get(e);if(n)return n;const s=W(e,t);return r.set(e,s),D(e,t,!1),s}function B(e){const t=I(),r=t.get(e);if(r)return r;const n=W(e,{});return t.set(e,n),D(e,{},!0),n}function L(e){return I().get(e)}function O(){I().clear()}function D(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function G(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function N(e){return!0===e._builtin}const H=G("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),j=G("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=G("Sprite",{texture:A,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),X=G("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),q=G("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=G("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=G("Parent",{entity:0}),Y=G("Children",{entities:[]}),Q=G("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),Z={LocalTransform:H,WorldTransform:j,Sprite:V,Camera:X,Canvas:q,Velocity:J,Parent:K,Children:Y,SpineAnimation:Q};function ee(e){const t=Z[e];if(t)return{...t._default};const r=L(e);return r?{...r._default}:null}let te=0;function re(e,t){const r=++te;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function ne(e){return{_type:"res",_resource:e}}function se(e){return{_type:"res_mut",_resource:e}}class ie{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class oe{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new ie(this.get(e),t=>this.set(e,t))}}const ae=re({delta:0,elapsed:0,frameCount:0},"Time"),ce=re({keysDown:new Set,keysPressed:new Set,keysReleased:new Set,mouseX:0,mouseY:0,mouseButtons:new Set},"Input");function le(e){return{_type:"mut",_component:e}}function ue(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function he(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{ue(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)}class de{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ue(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:n}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...r],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let r=!1;for(const t of n)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function fe(){return{_type:"commands"}}class pe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let r;return r=N(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class _e{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new pe(this,null)}entity(e){return new pe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var me;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(me||(me={}));let ge=0;function ye(e,t,r){const n=++ge;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function we(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function xe(e){we().push({schedule:me.Update,system:e})}function ve(e){we().push({schedule:me.Startup,system:e})}function Se(e,t){we().push({schedule:e,system:t})}class Ce{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof _e&&e.flush()}resolveParam(e){switch(e._type){case"query":return new de(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new _e(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class be{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return N(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return N(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return N(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){N(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const n={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,n)}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const n=t.create(r);return this.getStorage(t).set(e,n),n}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let n=!0;for(const t of e)if(!this.has(r,t)){n=!1;break}n&&t.push(r)}return t}}var Te,Pe,Ee;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Te||(Te={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Pe||(Pe={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ee||(Ee={}));const Ae=k("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Te.Left,verticalAlign:Pe.Top,wordWrap:!0,overflow:Ee.Visible,lineHeight:1.2,dirty:!0});class Me{constructor(e){this.cache=new Map,this.module=e,"undefined"!=typeof OffscreenCanvas?(this.canvas=new OffscreenCanvas(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})):(this.canvas=document.createElement("canvas"),this.canvas.width=512,this.canvas.height=512,this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}))}renderText(e,t){const r=this.ctx,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Ee.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;r.clearRect(0,0,n.width,n.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Ee.Clip&&(r.save(),r.beginPath(),r.rect(0,0,f,p),r.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Pe.Top:x=u;break;case Pe.Middle:x=(p-w)/2;break;case Pe.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case Te.Left:n=u;break;case Te.Center:n=f/2;break;case Te.Right:n=f-u;break;default:n=u}r.fillText(t,n,v),v+=l}s&&e.overflow===Ee.Clip&&r.restore();const S=r.getImageData(0,0,f,p),C=new Uint8Array(S.data.buffer),b=this.flipVertically(C,f,p),T=this.module.getResourceManager(),P=this.module._malloc(b.length);this.module.HEAPU8.set(b,P);const E=T.createTexture(f,p,P,b.length,1);return this.module._free(P),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const s=this.renderText(t,r);return this.cache.set(e,s),s}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),n=[];for(const e of r){if(!e){n.push("");continue}let r="";for(const s of e){const e=r+s;this.ctx.measureText(e).width>t&&r?(n.push(r),r=s):r=e}r&&n.push(r)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case Te.Left:return"left";case Te.Center:return"center";case Te.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const i=t*n,o=(r-1-t)*n;s.set(e.subarray(i,i+n),o)}return s}}const Re=k("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Fe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new Me(t),n=e.world;e.addSystemToSchedule(me.PreUpdate,ye([],()=>{const e=n.getEntitiesWithComponents([Ae]);for(const t of e){const e=n.get(t,Ae);if(!e.dirty)continue;n.has(t,V)||n.insert(t,V,{texture:A,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=n.has(t,Re)?n.get(t,Re):null,i=r.renderForEntity(t,e,s),o=n.get(t,V);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},n.insert(t,V,o),e.dirty=!1}}))}}const Ue=new Fe;var ze;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"}(ze||(ze={}));let We=null,Ie=null,ke=1;const Be=new Map;function Le(e){We=e,Ie=e.getResourceManager(),Xe()}function Oe(){0!==He&&We&&(We._free(He),He=0),Be.clear(),ke=1,Ne=!1,Ie=null,We=null}function De(){if(!Ie)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ie}const Ge={createShader:(e,t)=>De().createShader(e,t),releaseShader(e){e>0&&De().releaseShader(e)},create(e){const t=ke++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ze.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Be.set(t,r),t},get:e=>Be.get(e),setUniform(e,t,r){const n=Be.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Be.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Be.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Be.get(e);return t?.blendMode??ze.Normal},setDepthTest(e,t){const r=Be.get(e);r&&(r.depthTest=t)},getShader(e){const t=Be.get(e);return t?.shader??0},release(e){Be.delete(e)},isValid:e=>Be.has(e),createFromAsset(e,t){const r={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)r[t]=n;else if("object"==typeof n&&null!==n){const e=n;"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??ze.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Be.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=ke++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Be.set(r,n),r},toAssetData(e,t){const r=Be.get(e);if(!r)return null;const n={};for(const[e,t]of r.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:n}},getUniforms(e){const t=Be.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ne=!1,He=0;const je=4096;function Ve(e){const t=(0===He&&We&&(He=We._malloc(je)),He);if(0===t||!We)return{ptr:0,count:0};let r=0,n=0;const s=We.HEAPU8,i=We.HEAPU32,o=We.HEAPF32;for(const[a,c]of e){if(r+128>je)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+r>>2]=l,r+=4,s.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)o[t+r>>2]=d[e],r+=4;n++}return{ptr:t,count:n}}function Xe(){if(!We||Ne)return;We.materialDataProvider=(e,t,r,n,s)=>{const i=Be.get(e);if(!i)return We.HEAPU32[t>>2]=0,We.HEAPU32[r>>2]=0,We.HEAPU32[n>>2]=0,void(We.HEAPU32[s>>2]=0);We.HEAPU32[t>>2]=i.shader,We.HEAPU32[r>>2]=i.blendMode;const{ptr:o,count:a}=Ve(i.uniforms);We.HEAPU32[n>>2]=o,We.HEAPU32[s>>2]=a},Ne=!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"};let Je=null,Ke=0,Ye=0,Qe=0;const Ze=new Float32Array(256);function et(e){Je=e,Ke=Je._malloc(64),Ye=Je._malloc(64),Qe=Je._malloc(1024)}function tt(){Je&&(Ke&&(Je._free(Ke),Ke=0),Ye&&(Je._free(Ye),Ye=0),Qe&&(Je._free(Qe),Qe=0)),Je=null}function rt(){if(!Je)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Je}const nt={x:1,y:1,z:1,w:1},st={begin(e){const t=rt();t.HEAPF32.set(e,Ke/4),t.draw_begin(Ke)},end(){rt().draw_end()},line(e,t,r,n=1){rt().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rect(e,t,r,n=!0){rt().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rectOutline(e,t,r,n=1){rt().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},circle(e,t,r,n=!0,s=32){rt().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},circleOutline(e,t,r,n=1,s=32){rt().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=nt){rt().draw_texture(e.x,e.y,t.x,t.y,r,n.x,n.y,n.z,n.w)},textureRotated(e,t,r,n,s=nt){rt().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){rt().draw_setLayer(e)},setDepth(e){rt().draw_setDepth(e)},getDrawCallCount:()=>Je?Je.draw_getDrawCallCount():0,getPrimitiveCount:()=>Je?Je.draw_getPrimitiveCount():0,setBlendMode(e){rt().draw_setBlendMode(e)},setDepthTest(e){rt().draw_setDepthTest(e)},drawMesh(e,t,r){const n=rt();n.HEAPF32.set(r,Ye/4),n.draw_mesh(e,t,Ye)},drawMeshWithMaterial(e,t,r){const n=rt(),s=Ge.get(t);if(!s)return;if(st.setBlendMode(s.blendMode),st.setDepthTest(s.depthTest),0===s.uniforms.size)return void st.drawMesh(e,s.shader,r);n.HEAPF32.set(r,Ye/4);let i=0,o=0;for(const[e,t]of s.uniforms){const r=ot(e);if(!(r<0)){if($e(t))Ze[i++]=10,Ze[i++]=r,Ze[i++]=t.slot??o++,Ze[i++]=t.textureId;else if("number"==typeof t)Ze[i++]=1,Ze[i++]=r,Ze[i++]=t;else if(Array.isArray(t)){Ze[i++]=t.length,Ze[i++]=r;for(let e=0;e<t.length;e++)Ze[i++]=t[e]}else"w"in t?(Ze[i++]=4,Ze[i++]=r,Ze[i++]=t.x,Ze[i++]=t.y,Ze[i++]=t.z,Ze[i++]=t.w):"z"in t?(Ze[i++]=3,Ze[i++]=r,Ze[i++]=t.x,Ze[i++]=t.y,Ze[i++]=t.z):(Ze[i++]=2,Ze[i++]=r,Ze[i++]=t.x,Ze[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(n.HEAPF32.set(Ze.subarray(0,i),Qe/4),n.draw_meshWithUniforms(e,s.shader,Ye,Qe,i)):n.draw_mesh(e,s.shader,Ye)}},it={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ot(e){return it[e]??-1}var at;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(at||(at={}));let ct=null,lt=0,ut=0,ht=0;function dt(e){ct=e,lt=ct._malloc(262144),ut=ct._malloc(65536),ht=ct._malloc(256)}function ft(){ct&&(lt&&ct._free(lt),ut&&ct._free(ut),ht&&ct._free(ht),lt=0,ut=0,ht=0),ct=null}function pt(){if(!ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ct}const _t={create(e){const t=pt(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,lt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ht,s).set(i),t.geometry_init(r,lt,n,ht,s,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ut,n).set(e.indices),t.geometry_setIndices16(r,ut,n)}else{new Uint32Array(t.HEAPU8.buffer,ut,n).set(e.indices),t.geometry_setIndices32(r,ut,n)}}return r},updateVertices(e,t,r=0){const n=pt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,lt/4),n.geometry_updateVertices(e,lt,s,r)},release(e){e>0&&pt().geometry_release(e)},isValid:e=>!(!ct||e<=0)&&ct.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return _t.create({vertices:new Float32Array([-r,-n,0,0,r,-n,1,0,r,n,1,1,-r,n,0,1]),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;r.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return _t.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,n=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-r)/(s-r);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return _t.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.Float2}],indices:new Uint16Array(o)})}};let mt=null;function gt(e){mt=e}function yt(){mt&&xt.isInitialized()&&xt.shutdown(),mt=null}function wt(){if(!mt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return mt}const xt={init:(e,t)=>wt().postprocess_init(e,t),shutdown(){wt().postprocess_shutdown()},resize(e,t){wt().postprocess_resize(e,t)},addPass:(e,t)=>wt().postprocess_addPass(e,t),removePass(e){wt().postprocess_removePass(e)},setEnabled(e,t){wt().postprocess_setPassEnabled(e,t)},isEnabled:e=>wt().postprocess_isPassEnabled(e),setUniform(e,t,r){wt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){wt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){wt().postprocess_begin()},end(){wt().postprocess_end()},getPassCount:()=>wt().postprocess_getPassCount(),isInitialized:()=>!!mt&&mt.postprocess_isInitialized(),setBypass(e){wt().postprocess_setBypass(e)},isBypassed:()=>!mt||mt.postprocess_isBypassed(),createBlur:()=>Ge.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ge.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ge.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ge.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},vt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var St;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(St||(St={}));let Ct=null,bt=0;function Tt(e){Ct=e,bt=Ct._malloc(64)}function Pt(){Ct&&bt&&(Ct._free(bt),bt=0),Ct=null}const Et={init(e,t){Ct?.renderer_init(e,t)},resize(e,t){Ct?.renderer_resize(e,t)},begin(e,t){Ct&&bt&&(Ct.HEAPF32.set(e,bt/4),Ct.renderer_begin(bt,t??0))},end(){Ct?.renderer_end()},submitSprites(e){Ct&&Ct.renderer_submitSprites(e._cpp)},submitSpine(e){Ct&&Ct.renderer_submitSpine(e._cpp)},setStage(e){Ct?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>Ct?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){Ct?.renderer_releaseTarget(e)},getTargetTexture:e=>Ct?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ct?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){Ct?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>Ct?{drawCalls:Ct.renderer_getDrawCalls(),triangles:Ct.renderer_getTriangles(),sprites:Ct.renderer_getSprites(),spine:Ct.renderer_getSpine(),meshes:Ct.renderer_getMeshes(),culled:Ct.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}},At=new Map;function Mt(e,t){At.set(e,t)}function Rt(e){At.delete(e)}function Ft(){At.clear()}class Ut{render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:i}=e;Et.resize(n,s);const o=xt.isInitialized()&&xt.getPassCount()>0&&!xt.isBypassed();o&&(xt.resize(n,s),xt.begin()),Et.begin(r),Et.submitSprites(t),Et.submitSpine(t),Et.end();const a=At;if(a.size>0){st.begin(r);const e=[];for(const[t,r]of a.entries())try{r(i)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}st.end();for(const t of e)Rt(t)}o&&xt.end()}}class zt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.module_=null,this.mainLoop=()=>{if(!this.running_)return;const e=performance.now(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;this.updateTime(r),this.runSchedule(me.First),this.runSchedule(me.PreUpdate),this.runSchedule(me.Update),this.runSchedule(me.PostUpdate),this.runSchedule(me.Last),requestAnimationFrame(this.mainLoop)},this.world_=new be,this.resources_=new oe;for(const e of Object.values(me))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new zt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(me.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(me.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(ae,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(me.Startup),this.lastTime_=performance.now(),this.mainLoop())}quit(){this.running_=!1,Pt(),yt(),ft(),Oe(),tt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(ae),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(ae,r)}}function $t(e,t){const r=zt.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),et(e),Le(e),dt(e),gt(e),Tt(e);const s=new Ut;let i=performance.now();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const n=e.getCamera(s);if(!n.isActive)continue;const i=e.getLocalTransform(s),o=t/r;let a;if(1===n.projectionType){const e=n.orthoSize,t=e*o;a=kt(-t,t,-e,e,-n.farPlane,n.farPlane)}else a=Bt(n.fov*Math.PI/180,o,n.nearPlane,n.farPlane);return Ot(a,Lt(i.position.x,i.position.y,i.position.z))}return It}(n,e,t),a=(performance.now()-i)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:a})}};return r.addSystemToSchedule(me.Last,a),r.addPlugin(Ue),r}function Wt(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}}const It=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function kt(e,t,r,n,s,i){const o=new Float32Array(16),a=t-e,c=n-r,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+r)/c,o[14]=-(i+s)/l,o[15]=1,o}function Bt(e,t,r,n){const s=new Float32Array(16),i=1/Math.tan(e/2),o=r-n;return s[0]=i/t,s[5]=i,s[10]=(n+r)/o,s[11]=-1,s[14]=2*n*r/o,s}function Lt(e,t,r){const n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n[12]=-e,n[13]=-t,n[14]=-r,n}function Ot(e,t){const r=new Float32Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)r[4*s+n]=e[0+n]*t[4*s+0]+e[4+n]*t[4*s+1]+e[8+n]*t[4*s+2]+e[12+n]*t[4*s+3];return r}class Dt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const n=this.loadInternal(e);this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ge.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ge.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const r=await c(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(r);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const s=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(s);return{handle:Ge.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function Gt(e,t){const r=new Map;for(const n of t.entities){const t=e.spawn();r.set(n.id,t);for(const r of n.components)Ht(e,t,r)}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return r}async function Nt(e,t,r){const n=new Map,s=r?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();n.set(o.id,t);for(const n of o.components){if("Sprite"===n.type&&s){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await s.loadTexture(n);e.texture=r.handle,i.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===n.type&&s){const e=n.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ht(e,t,n)}}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function Ht(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,H,n);break;case"Sprite":e.insert(t,V,n);break;case"Camera":e.insert(t,X,n);break;case"Canvas":e.insert(t,q,n);break;case"Text":e.insert(t,Ae,n);break;case"SpineAnimation":e.insert(t,Q,n);break;case"UIRect":e.insert(t,Re,n);break;default:{const s=L(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function jt(e,t){const r=e.getEntitiesWithComponents([X]);for(const n of r){const r=e.get(n,X);r&&(r.aspectRatio=t,e.insert(n,X,r))}}class Vt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const n=this.pending_.get(e);if(n)return n;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Xt{constructor(e){this.textureCache_=new Vt,this.shaderCache_=new Vt,this.jsonCache_=new Vt,this.textCache_=new Vt,this.binaryCache_=new Vt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=this.createCanvas(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Dt(t)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const n=this.textureCacheKey(e,r),s=this.textureCache_.get(n);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(n))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const s=this.resolveUrl(t,r),i=await fetch(s);if(!i.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const o=await i.text();if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(o);for(const e of c){const t=a?`${a}/${e}`:e,n=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(n),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const n of e.textures)r.push(this.loadTexture(n).then(e=>{t.textures.set(n,e)}));if(e.materials)for(const n of e.materials)r.push(this.loadMaterial(n).then(e=>{t.materials.set(n,e)}));if(e.spine)for(const n of e.spine){const e=`${n.skeleton}:${n.atlas}`;r.push(this.loadSpine(n.skeleton,n.atlas,n.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const n of e.json)r.push(this.loadJson(n).then(e=>{t.json.set(n,e)}));if(e.text)for(const n of e.text)r.push(this.loadText(n).then(e=>{t.text.set(n,e)}));if(e.binary)for(const n of e.binary)r.push(this.loadBinary(n).then(e=>{t.binary.set(n,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}createTextureFromImage(e,t){const{width:r,height:n}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,r,n,t):this.createTextureFallback(e,r,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,n,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,n),width:r,height:n}}createTextureFallback(e,t,r,n){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,r),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,r,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const n=255/r;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:n}=this.parseEsShader(t);if(!r||!n)throw new Error(`Invalid shader format: ${e}`);return Ge.createShader(r,n)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}async fetchJson(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const n=r.split("/").filter(e=>e);let s="";for(const e of n){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}createCanvas(e,t){const r="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas");return r.width=e,r.height=t,r}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const qt=re(null,"Assets");class Jt{build(e){const t=e.wasmModule;t?e.insertResource(qt,new Xt(t)):console.warn("AssetPlugin: No WASM module available")}}const Kt=new Jt;class Yt{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(qt)||e.addPlugin(Kt),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=this.app_.getResource(qt);await r.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([X]);for(const n of r){if(e.get(n,X).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),r={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(t,H,r);const n={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,X,n)}}}class Qt{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,r=!0,n=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,r,n)}addAnimation(e,t,r=!0,n=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,r,n,s)}setEmptyAnimation(e,t=.2,r=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,r)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const r=this.module_.spineGetBonePosition(e,t);return r?{x:r.x,y:r.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,r){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,r||"")}on(e,t,r){this.listeners_.has(e)||this.listeners_.set(e,new Map);const n=this.listeners_.get(e);n.has(t)||n.set(t,new Set),n.get(t).add(r)}off(e,t,r){const n=this.listeners_.get(e);if(!n)return;const s=n.get(t);s&&s.delete(r)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const r=this.listeners_.get(e);if(!r)return;const n={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=r.get(n.type);s&&s.forEach(e=>{try{e(n)}catch(e){console.error("Error in Spine event callback:",e)}})}}function Zt(e){return new Qt(e)}const er={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Et.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Et.getTargetTexture(r),width:e.width,height:e.height}},release(e){Et.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Et.releaseRenderTarget(e._handle),er.create({width:t,height:r,depth:!0})),begin(e,t){Et.begin(t,e._handle)},end(){Et.end()},getDepthTexture:e=>Et.getTargetDepthTexture(e._handle)};let tr=!1;function rr(e){tr=e}function nr(){return tr}function sr(){return!tr}var ir;T||(T=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await h(r,n);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return d(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}),console.log("[ESEngine] WeChat platform initialized")),e=ir=P,console.log(`[ESEngine] Platform: ${ir.name}`);export{zt as App,Jt as AssetPlugin,Xt as AssetServer,qt as Assets,Vt as AsyncCache,ze as BlendMode,X as Camera,q as Canvas,Y as Children,fe as Commands,_e as CommandsInstance,at as DataType,st as Draw,pe as EntityCommands,_t as Geometry,E as INVALID_ENTITY,A as INVALID_TEXTURE,ce as Input,H as LocalTransform,Ge as Material,Dt as MaterialLoader,le as Mut,K as Parent,xt as PostProcess,Yt as PreviewPlugin,he as Query,de as QueryInstance,Ut as RenderPipeline,St as RenderStage,er as RenderTexture,Et as Renderer,ne as Res,se as ResMut,me as Schedule,qe as ShaderSources,Q as SpineAnimation,Qt as SpineController,V as Sprite,Ce as SystemRunner,Ae as Text,Te as TextAlign,Ee as TextOverflow,Fe as TextPlugin,Me as TextRenderer,Pe as TextVerticalAlign,ae as Time,Re as UIRect,J as Velocity,be as World,j as WorldTransform,ve as addStartupSystem,xe as addSystem,Se as addSystemToSchedule,Kt as assetPlugin,Ft as clearDrawCallbacks,O as clearUserComponents,U as color,Zt as createSpineController,$t as createWebApp,k as defineComponent,re as defineResource,ye as defineSystem,B as defineTag,Wt as flushPendingSystems,ee as getComponentDefaults,t as getPlatform,n as getPlatformType,L as getUserComponent,et as initDrawAPI,dt as initGeometryAPI,Le as initMaterialAPI,gt as initPostProcessAPI,Tt as initRendererAPI,N as isBuiltinComponent,nr as isEditor,r as isPlatformInitialized,sr as isRuntime,$e as isTextureRef,s as isWeChat,i as isWeb,Ht as loadComponent,Gt as loadSceneData,Nt as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,z as quat,Mt as registerDrawCallback,Xe as registerMaterialCallback,rr as setEditorMode,tt as shutdownDrawAPI,ft as shutdownGeometryAPI,Oe as shutdownMaterialAPI,yt as shutdownPostProcessAPI,Pt as shutdownRendererAPI,Ue as textPlugin,Rt as unregisterDrawCallback,jt as updateCameraAspectRatio,M as vec2,R as vec3,F as vec4,g as wxFileExists,y as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,b as wxLoadImagePixels,_ as wxReadFile,m as wxReadTextFile,w as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 676716667..6658d0529 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -239,6 +239,7 @@ interface CppRegistry {interface CppResourceManager {createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number): number;createShader(vertSrc: string, fragSrc: string): number;+ registerExternalTexture(glTextureId: number, width: number, height: number): number;releaseTexture(handle: number): void;releaseShader(handle: number): void;setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;@@ -969,6 +970,9 @@ declare class AssetServer {private loadTextureInternal;private loadImage;private createTextureFromImage;+ private getWebGL2Context;+ private createTextureWebGL2;+ private createTextureFallback;private unpremultiplyAlpha;private loadShaderInternal;private parseEsShader;diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex ee9580084..aaa30f339 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,3974 +1,2 @@-/**- * @file base.ts- * @brief Base platform adapter - no platform-specific code- */-// =============================================================================-// Platform Instance (set by entry point)-// =============================================================================-let currentPlatform = null;-/**- * Set the platform adapter (called by entry point)- */-function setPlatform(adapter) {- currentPlatform = adapter;- console.log(`[ESEngine] Platform: ${adapter.name}`);-}-/**- * Get the current platform adapter- * @throws Error if platform not initialized- */-function getPlatform() {- if (!currentPlatform) {- throw new Error('[ESEngine] Platform not initialized. ' +- 'Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');- }- return currentPlatform;-}-/**- * Check if platform is initialized- */-function isPlatformInitialized() {- return currentPlatform !== null;-}-/**- * Get platform type- */-function getPlatformType() {- return currentPlatform?.name ?? null;-}-/**- * Check if running on WeChat- */-function isWeChat() {- return currentPlatform?.name === 'wechat';-}-/**- * Check if running on Web- */-function isWeb() {- return currentPlatform?.name === 'web';-}-// =============================================================================-// Convenience Functions-// =============================================================================-async function platformFetch(url, options) {- return getPlatform().fetch(url, options);-}-async function platformReadFile(path) {- return getPlatform().readFile(path);-}-async function platformReadTextFile(path) {- return getPlatform().readTextFile(path);-}-async function platformFileExists(path) {- return getPlatform().fileExists(path);-}-async function platformInstantiateWasm(pathOrBuffer, imports) {- return getPlatform().instantiateWasm(pathOrBuffer, imports);-}--/**- * @file web.ts- * @brief Web platform adapter implementation- */-// =============================================================================-// Web Platform Adapter-// =============================================================================-class WebPlatformAdapter {- constructor() {- this.name = 'web';- }- async fetch(url, options) {- const response = await globalThis.fetch(url, {- method: options?.method ?? 'GET',- headers: options?.headers,- body: options?.body,- });- const headers = {};- response.headers.forEach((value, key) => {- headers[key] = value;- });- return {- ok: response.ok,- status: response.status,- statusText: response.statusText,- headers,- json: () => response.json(),- text: () => response.text(),- arrayBuffer: () => response.arrayBuffer(),- };- }- async readFile(path) {- const response = await this.fetch(path);- if (!response.ok) {- throw new Error(`Failed to read file: ${path} (${response.status})`);- }- return response.arrayBuffer();- }- async readTextFile(path) {- const response = await this.fetch(path);- if (!response.ok) {- throw new Error(`Failed to read file: ${path} (${response.status})`);- }- return response.text();- }- async fileExists(path) {- try {- const response = await globalThis.fetch(path, { method: 'HEAD' });- return response.ok;- }- catch {- return false;- }- }- async instantiateWasm(pathOrBuffer, imports) {- let buffer;- if (typeof pathOrBuffer === 'string') {- buffer = await this.readFile(pathOrBuffer);- }- else {- buffer = pathOrBuffer;- }- const result = await WebAssembly.instantiate(buffer, imports);- return {- instance: result.instance,- module: result.module,- };- }-}-// =============================================================================-// Export Singleton-// =============================================================================-const webAdapter = new WebPlatformAdapter();--/**- * @file types.ts- * @brief Core type definitions for ESEngine SDK- */-const INVALID_ENTITY = 0;-const INVALID_TEXTURE = 0xFFFFFFFF;-// =============================================================================-// Factory Functions-// =============================================================================-const vec2 = (x = 0, y = 0) => ({ x, y });-const vec3 = (x = 0, y = 0, z = 0) => ({ x, y, z });-const vec4 = (x = 0, y = 0, z = 0, w = 1) => ({ x, y, z, w });-const color = (r = 1, g = 1, b = 1, a = 1) => ({ x: r, y: g, z: b, w: a });-const quat = (w = 1, x = 0, y = 0, z = 0) => ({ w, x, y, z });--/**- * @file component.ts- * @brief Component definition and builtin components- */-let componentCounter = 0;-function createComponentDef(name, defaults) {- const id = ++componentCounter;- return {- _id: Symbol(`Component_${id}_${name}`),- _name: name,- _default: defaults,- _builtin: false,- create(data) {- return { ...defaults, ...data };- }- };-}-function getComponentRegistry() {- if (typeof window === 'undefined')- return new Map();- return (window.__esengine_componentRegistry ?? (window.__esengine_componentRegistry = new Map()));-}-function defineComponent(name, defaults) {- const registry = getComponentRegistry();- const existing = registry.get(name);- if (existing)- return existing;- const def = createComponentDef(name, defaults);- registry.set(name, def);- registerToEditor(name, defaults, false);- return def;-}-function defineTag(name) {- const registry = getComponentRegistry();- const existing = registry.get(name);- if (existing)- return existing;- const def = createComponentDef(name, {});- registry.set(name, def);- registerToEditor(name, {}, true);- return def;-}-function getUserComponent(name) {- return getComponentRegistry().get(name);-}-function clearUserComponents() {- getComponentRegistry().clear();-}-function registerToEditor(name, defaults, isTag) {- if (typeof window !== 'undefined' && window.__esengine_registerComponent) {- window.__esengine_registerComponent(name, defaults, isTag);- }-}-function defineBuiltin(name, defaults) {- return {- _id: Symbol(`Builtin_${name}`),- _name: name,- _cppName: name,- _builtin: true,- _default: defaults- };-}-function isBuiltinComponent(comp) {- return comp._builtin === true;-}-// =============================================================================-// Builtin Component Instances-// =============================================================================-const LocalTransform = defineBuiltin('LocalTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const WorldTransform = defineBuiltin('WorldTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const Sprite = defineBuiltin('Sprite', {- texture: INVALID_TEXTURE,- color: { x: 1, y: 1, z: 1, w: 1 },- size: { x: 32, y: 32 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0-});-const Camera = defineBuiltin('Camera', {- projectionType: 0,- fov: 60,- orthoSize: 5,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- isActive: true,- priority: 0-});-const Canvas = defineBuiltin('Canvas', {- designResolution: { x: 1920, y: 1080 },- pixelsPerUnit: 100,- scaleMode: 0,- matchWidthOrHeight: 0.5,- backgroundColor: { x: 0, y: 0, z: 0, w: 1 }-});-const Velocity = defineBuiltin('Velocity', {- linear: { x: 0, y: 0, z: 0 },- angular: { x: 0, y: 0, z: 0 }-});-const Parent = defineBuiltin('Parent', {- entity: 0-});-const Children = defineBuiltin('Children', {- entities: []-});-const SpineAnimation = defineBuiltin('SpineAnimation', {- skeletonPath: '',- atlasPath: '',- skin: '',- animation: '',- timeScale: 1.0,- loop: true,- playing: true,- flipX: false,- flipY: false,- color: { x: 1, y: 1, z: 1, w: 1 },- layer: 0,- skeletonScale: 1.0,- material: 0-});-// =============================================================================-// Component Defaults Registry-// =============================================================================-const builtinComponents = {- LocalTransform,- WorldTransform,- Sprite,- Camera,- Canvas,- Velocity,- Parent,- Children,- SpineAnimation,-};-function getComponentDefaults(typeName) {- const builtin = builtinComponents[typeName];- if (builtin)- return { ...builtin._default };- const userComp = getUserComponent(typeName);- if (userComp)- return { ...userComp._default };- return null;-}--/**- * @file resource.ts- * @brief Resource system for global singleton data- */-let resourceCounter = 0;-function defineResource(defaultValue, name) {- const id = ++resourceCounter;- return {- _id: Symbol(`Resource_${id}_${name ?? ''}`),- _name: name ?? `Resource_${id}`,- _default: defaultValue- };-}-function Res(resource) {- return { _type: 'res', _resource: resource };-}-function ResMut(resource) {- return { _type: 'res_mut', _resource: resource };-}-// =============================================================================-// Resource Instances (Runtime)-// =============================================================================-class ResMutInstance {- constructor(value, setter) {- this.value_ = value;- this.setter_ = setter;- }- get() {- return this.value_;- }- set(value) {- this.value_ = value;- this.setter_(value);- }- modify(fn) {- fn(this.value_);- this.setter_(this.value_);- }-}-// =============================================================================-// Resource Storage-// =============================================================================-class ResourceStorage {- constructor() {- this.resources_ = new Map();- }- insert(resource, value) {- this.resources_.set(resource._id, value);- }- get(resource) {- if (!this.resources_.has(resource._id)) {- this.resources_.set(resource._id, resource._default);- }- return this.resources_.get(resource._id);- }- set(resource, value) {- this.resources_.set(resource._id, value);- }- has(resource) {- return this.resources_.has(resource._id);- }- remove(resource) {- this.resources_.delete(resource._id);- }- getResMut(resource) {- return new ResMutInstance(this.get(resource), (v) => this.set(resource, v));- }-}-const Time = defineResource({- delta: 0,- elapsed: 0,- frameCount: 0-}, 'Time');-const Input = defineResource({- keysDown: new Set(),- keysPressed: new Set(),- keysReleased: new Set(),- mouseX: 0,- mouseY: 0,- mouseButtons: new Set()-}, 'Input');--/**- * @file query.ts- * @brief Component query system with mutable component support- */-function Mut(component) {- return { _type: 'mut', _component: component };-}-function isMutWrapper(value) {- return typeof value === 'object' && value !== null && value._type === 'mut';-}-function createQueryDescriptor(components, withFilters = [], withoutFilters = []) {- const mutIndices = [];- components.forEach((comp, i) => {- if (isMutWrapper(comp)) {- mutIndices.push(i);- }- });- return {- _type: 'query',- _components: components,- _mutIndices: mutIndices,- _with: withFilters,- _without: withoutFilters- };-}-// =============================================================================-// Query Factory-// =============================================================================-function Query(...components) {- return createQueryDescriptor(components);-}-class QueryInstance {- constructor(world, descriptor) {- this.pendingMutations_ = [];- this.world_ = world;- this.descriptor_ = descriptor;- }- getActualComponent(arg) {- return isMutWrapper(arg) ? arg._component : arg;- }- commitPending() {- for (const mutation of this.pendingMutations_) {- this.world_.insert(mutation.entity, mutation.component, mutation.data);- }- this.pendingMutations_ = [];- }- *[Symbol.iterator]() {- const { _components, _mutIndices, _with, _without } = this.descriptor_;- const actualComponents = _components.map(c => this.getActualComponent(c));- const allRequired = [...actualComponents, ..._with];- const entities = this.world_.getEntitiesWithComponents(allRequired);- let prevEntity = null;- let prevMutData = [];- try {- for (const entity of entities) {- // Commit previous entity's mutations before moving to next- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- prevMutData = [];- let excluded = false;- for (const comp of _without) {- if (this.world_.has(entity, comp)) {- excluded = true;- break;- }- }- if (excluded)- continue;- const components = actualComponents.map(comp => this.world_.get(entity, comp));- // Track mutable components for write-back- for (const idx of _mutIndices) {- prevMutData.push({- component: actualComponents[idx],- data: components[idx]- });- }- prevEntity = entity;- yield [entity, ...components];- }- }- finally {- // Commit last entity's mutations- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- }- }- forEach(callback) {- for (const [entity, ...components] of this) {- callback(entity, ...components);- }- }- single() {- for (const result of this) {- return result;- }- return null;- }- isEmpty() {- return this.single() === null;- }- count() {- let n = 0;- for (const _ of this) {- n++;- }- return n;- }- toArray() {- return [...this];- }-}--/**- * @file commands.ts- * @brief Deferred entity/component operations- */-function Commands() {- return { _type: 'commands' };-}-// =============================================================================-// Entity Commands (Builder for spawning)-// =============================================================================-class EntityCommands {- constructor(commands, entity) {- this.components_ = [];- this.commands_ = commands;- if (entity === null) {- this.entityRef_ = { entity: 0 };- this.isNew_ = true;- }- else {- this.entityRef_ = { entity };- this.isNew_ = false;- }- }- insert(component, data) {- let instance;- if (isBuiltinComponent(component)) {- instance = { ...component._default, ...data };- }- else {- instance = component.create(data);- }- if (this.isNew_) {- this.components_.push({ component, data: instance });- }- else {- this.commands_.queueInsert(this.entityRef_.entity, component, instance);- }- return this;- }- remove(component) {- if (!this.isNew_) {- this.commands_.queueRemove(this.entityRef_.entity, component);- }- return this;- }- id() {- if (this.isNew_ && this.entityRef_.entity === 0) {- this.finalize();- }- return this.entityRef_.entity;- }- finalize() {- if (this.isNew_) {- this.commands_.spawnImmediate(this.components_, this.entityRef_);- this.isNew_ = false;- }- }-}-// =============================================================================-// Commands Instance (Runtime)-// =============================================================================-class CommandsInstance {- constructor(world, resources) {- this.pending_ = [];- this.world_ = world;- this.resources_ = resources;- }- spawn() {- return new EntityCommands(this, null);- }- entity(entity) {- return new EntityCommands(this, entity);- }- despawn(entity) {- this.pending_.push({ type: 'despawn', entity });- return this;- }- insertResource(resource, value) {- this.pending_.push({- type: 'insert_resource',- resource: resource,- value- });- return this;- }- queueInsert(entity, component, data) {- this.pending_.push({ type: 'insert', entity, component, data });- }- queueRemove(entity, component) {- this.pending_.push({ type: 'remove', entity, component });- }- spawnImmediate(components, entityRef) {- const entity = this.world_.spawn();- entityRef.entity = entity;- for (const entry of components) {- this.world_.insert(entity, entry.component, entry.data);- }- }- flush() {- for (const cmd of this.pending_) {- this.executeCommand(cmd);- }- this.pending_ = [];- }- executeCommand(cmd) {- switch (cmd.type) {- case 'spawn': {- const entity = this.world_.spawn();- cmd.entityRef.entity = entity;- for (const entry of cmd.components) {- this.world_.insert(entity, entry.component, entry.data);- }- break;- }- case 'despawn':- this.world_.despawn(cmd.entity);- break;- case 'insert':- this.world_.insert(cmd.entity, cmd.component, cmd.data);- break;- case 'remove':- this.world_.remove(cmd.entity, cmd.component);- break;- case 'insert_resource':- this.resources_.insert(cmd.resource, cmd.value);- break;- }- }-}--/**- * @file system.ts- * @brief System definition and scheduling- */-// =============================================================================-// Schedule Phases-// =============================================================================-var Schedule;-(function (Schedule) {- Schedule[Schedule["Startup"] = 0] = "Startup";- Schedule[Schedule["First"] = 1] = "First";- Schedule[Schedule["PreUpdate"] = 2] = "PreUpdate";- Schedule[Schedule["Update"] = 3] = "Update";- Schedule[Schedule["PostUpdate"] = 4] = "PostUpdate";- Schedule[Schedule["Last"] = 5] = "Last";- Schedule[Schedule["FixedPreUpdate"] = 10] = "FixedPreUpdate";- Schedule[Schedule["FixedUpdate"] = 11] = "FixedUpdate";- Schedule[Schedule["FixedPostUpdate"] = 12] = "FixedPostUpdate";-})(Schedule || (Schedule = {}));-let systemCounter = 0;-function defineSystem(params, fn, options) {- const id = ++systemCounter;- return {- _id: Symbol(`System_${id}_${options?.name ?? ''}`),- _params: params,- _fn: fn,- _name: options?.name ?? `System_${id}`- };-}-// =============================================================================-// Global System Registration-// =============================================================================-function getPendingSystems() {- if (typeof window === 'undefined')- return [];- return (window.__esengine_pendingSystems ?? (window.__esengine_pendingSystems = []));-}-function addSystem(system) {- getPendingSystems().push({ schedule: Schedule.Update, system });-}-function addStartupSystem(system) {- getPendingSystems().push({ schedule: Schedule.Startup, system });-}-function addSystemToSchedule(schedule, system) {- getPendingSystems().push({ schedule, system });-}-// =============================================================================-// System Runner-// =============================================================================-class SystemRunner {- constructor(world, resources) {- this.world_ = world;- this.resources_ = resources;- }- run(system) {- const args = system._params.map(param => this.resolveParam(param));- system._fn(...args);- for (const arg of args) {- if (arg instanceof CommandsInstance) {- arg.flush();- }- }- }- resolveParam(param) {- switch (param._type) {- case 'query':- return new QueryInstance(this.world_, param);- case 'res':- return this.resources_.get(param._resource);- case 'res_mut':- return this.resources_.getResMut(param._resource);- case 'commands':- return new CommandsInstance(this.world_, this.resources_);- default:- throw new Error('Unknown system parameter type');- }- }-}--/**- * @file world.ts- * @brief ECS World with C++ Registry integration- */-// =============================================================================-// World-// =============================================================================-class World {- constructor() {- this.cppRegistry_ = null;- this.entities_ = new Set();- this.tsStorage_ = new Map();- }- connectCpp(cppRegistry) {- this.cppRegistry_ = cppRegistry;- }- get hasCpp() {- return this.cppRegistry_ !== null;- }- // =========================================================================- // Entity Management- // =========================================================================- spawn() {- let entity;- if (this.cppRegistry_) {- entity = this.cppRegistry_.create();- }- else {- entity = (this.entities_.size + 1);- }- this.entities_.add(entity);- return entity;- }- despawn(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.destroy(entity);- }- this.entities_.delete(entity);- for (const storage of this.tsStorage_.values()) {- storage.delete(entity);- }- }- valid(entity) {- if (this.cppRegistry_) {- return this.cppRegistry_.valid(entity);- }- return this.entities_.has(entity);- }- entityCount() {- return this.entities_.size;- }- getAllEntities() {- return Array.from(this.entities_);- }- setParent(child, parent) {- if (this.cppRegistry_) {- this.cppRegistry_.setParent(child, parent);- }- }- removeParent(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.removeParent(entity);- }- }- // =========================================================================- // Component Management- // =========================================================================- insert(entity, component, data) {- if (isBuiltinComponent(component)) {- return this.insertBuiltin(entity, component, data);- }- return this.insertScript(entity, component, data);- }- get(entity, component) {- if (isBuiltinComponent(component)) {- return this.getBuiltin(entity, component);- }- return this.getScript(entity, component);- }- has(entity, component) {- if (isBuiltinComponent(component)) {- return this.hasBuiltin(entity, component);- }- return this.hasScript(entity, component);- }- remove(entity, component) {- if (isBuiltinComponent(component)) {- this.removeBuiltin(entity, component);- }- else {- this.removeScript(entity, component);- }- }- // =========================================================================- // Builtin Component Operations (C++ Registry)- // =========================================================================- insertBuiltin(entity, component, data) {- const merged = { ...component._default, ...data };- if (this.cppRegistry_) {- const adder = `add${component._cppName}`;- const fn = this.cppRegistry_[adder];- fn.call(this.cppRegistry_, entity, merged);- }- return merged;- }- getBuiltin(entity, component) {- if (!this.cppRegistry_) {- throw new Error('C++ Registry not connected');- }- const getter = `get${component._cppName}`;- const fn = this.cppRegistry_[getter];- return fn.call(this.cppRegistry_, entity);- }- hasBuiltin(entity, component) {- if (!this.cppRegistry_) {- return false;- }- const checker = `has${component._cppName}`;- const fn = this.cppRegistry_[checker];- return fn.call(this.cppRegistry_, entity);- }- removeBuiltin(entity, component) {- if (!this.cppRegistry_) {- return;- }- const remover = `remove${component._cppName}`;- const fn = this.cppRegistry_[remover];- fn.call(this.cppRegistry_, entity);- }- // =========================================================================- // Script Component Operations (TypeScript storage)- // =========================================================================- insertScript(entity, component, data) {- const value = component.create(data);- this.getStorage(component).set(entity, value);- return value;- }- getScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- if (!storage) {- throw new Error(`Component not found: ${component._name}`);- }- return storage.get(entity);- }- hasScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- return storage?.has(entity) ?? false;- }- removeScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- storage?.delete(entity);- }- getStorage(component) {- let storage = this.tsStorage_.get(component._id);- if (!storage) {- storage = new Map();- this.tsStorage_.set(component._id, storage);- }- return storage;- }- // =========================================================================- // Query Support- // =========================================================================- getEntitiesWithComponents(components) {- if (components.length === 0) {- return this.getAllEntities();- }- const entities = [];- for (const entity of this.entities_) {- let hasAll = true;- for (const comp of components) {- if (!this.has(entity, comp)) {- hasAll = false;- break;- }- }- if (hasAll) {- entities.push(entity);- }- }- return entities;- }-}--/**- * @file text.ts- * @brief Text component definition for UI text rendering- */-// =============================================================================-// Text Alignment Enums-// =============================================================================-var TextAlign;-(function (TextAlign) {- TextAlign[TextAlign["Left"] = 0] = "Left";- TextAlign[TextAlign["Center"] = 1] = "Center";- TextAlign[TextAlign["Right"] = 2] = "Right";-})(TextAlign || (TextAlign = {}));-var TextVerticalAlign;-(function (TextVerticalAlign) {- TextVerticalAlign[TextVerticalAlign["Top"] = 0] = "Top";- TextVerticalAlign[TextVerticalAlign["Middle"] = 1] = "Middle";- TextVerticalAlign[TextVerticalAlign["Bottom"] = 2] = "Bottom";-})(TextVerticalAlign || (TextVerticalAlign = {}));-var TextOverflow;-(function (TextOverflow) {- TextOverflow[TextOverflow["Visible"] = 0] = "Visible";- TextOverflow[TextOverflow["Clip"] = 1] = "Clip";- TextOverflow[TextOverflow["Ellipsis"] = 2] = "Ellipsis";-})(TextOverflow || (TextOverflow = {}));-// =============================================================================-// Text Component Definition-// =============================================================================-const Text = defineComponent('Text', {- content: '',- fontFamily: 'Arial',- fontSize: 24,- color: { x: 1, y: 1, z: 1, w: 1 },- align: TextAlign.Left,- verticalAlign: TextVerticalAlign.Top,- wordWrap: true,- overflow: TextOverflow.Visible,- lineHeight: 1.2,- dirty: true,-});--/**- * @file TextRenderer.ts- * @brief Renders text to GPU textures using Canvas 2D API- */-// =============================================================================-// Text Renderer-// =============================================================================-class TextRenderer {- constructor(module) {- this.cache = new Map();- this.module = module;- if (typeof OffscreenCanvas !== 'undefined') {- this.canvas = new OffscreenCanvas(512, 512);- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- else {- this.canvas = document.createElement('canvas');- this.canvas.width = 512;- this.canvas.height = 512;- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- }- /**- * Renders text to a texture and returns the handle- */- renderText(text, uiRect) {- const ctx = this.ctx;- const canvas = this.canvas;- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- const hasContainer = uiRect && uiRect.size.x > 0 && uiRect.size.y > 0;- const containerWidth = hasContainer ? uiRect.size.x : 0;- const containerHeight = hasContainer ? uiRect.size.y : 0;- const shouldWrap = text.wordWrap && hasContainer;- let lines = this.wrapText(text.content, shouldWrap ? containerWidth : 0);- const lineHeightPx = Math.ceil(text.fontSize * text.lineHeight);- const padding = Math.ceil(text.fontSize * 0.2);- const measuredWidth = Math.ceil(this.measureWidth(lines));- const measuredHeight = Math.ceil(lines.length * lineHeightPx);- const width = hasContainer ? Math.ceil(containerWidth) : measuredWidth + padding * 2;- const height = hasContainer ? Math.ceil(containerHeight) : measuredHeight + padding * 2;- // Handle overflow ellipsis- if (hasContainer && text.overflow === TextOverflow.Ellipsis && measuredHeight > containerHeight) {- const maxLines = Math.floor(containerHeight / lineHeightPx);- if (maxLines > 0 && lines.length > maxLines) {- lines = lines.slice(0, maxLines);- const lastLine = lines[maxLines - 1];- lines[maxLines - 1] = this.truncateWithEllipsis(lastLine, containerWidth);- }- }- if (canvas.width < width || canvas.height < height) {- const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));- const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));- canvas.width = newWidth;- canvas.height = newHeight;- }- const r = Math.round(text.color.x * 255);- const g = Math.round(text.color.y * 255);- const b = Math.round(text.color.z * 255);- const a = text.color.w;- ctx.clearRect(0, 0, canvas.width, canvas.height);- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- ctx.textAlign = this.mapAlign(text.align);- ctx.textBaseline = 'top';- ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;- // Handle overflow clip- if (hasContainer && text.overflow === TextOverflow.Clip) {- ctx.save();- ctx.beginPath();- ctx.rect(0, 0, width, height);- ctx.clip();- }- const textBlockHeight = lines.length * lineHeightPx;- let startY;- if (hasContainer) {- switch (text.verticalAlign) {- case TextVerticalAlign.Top:- startY = padding;- break;- case TextVerticalAlign.Middle:- startY = (height - textBlockHeight) / 2;- break;- case TextVerticalAlign.Bottom:- startY = height - textBlockHeight - padding;- break;- default: startY = padding;- }- }- else {- startY = padding;- }- let y = startY;- for (const line of lines) {- let x;- switch (text.align) {- case TextAlign.Left:- x = padding;- break;- case TextAlign.Center:- x = width / 2;- break;- case TextAlign.Right:- x = width - padding;- break;- default:- x = padding;- }- ctx.fillText(line, x, y);- y += lineHeightPx;- }- if (hasContainer && text.overflow === TextOverflow.Clip) {- ctx.restore();- }- const imageData = ctx.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- const flipped = this.flipVertically(pixels, width, height);- const rm = this.module.getResourceManager();- const ptr = this.module._malloc(flipped.length);- this.module.HEAPU8.set(flipped, ptr);- const textureHandle = rm.createTexture(width, height, ptr, flipped.length, 1);- this.module._free(ptr);- return { textureHandle, width, height };- }- truncateWithEllipsis(text, maxWidth) {- const ellipsis = '...';- if (this.ctx.measureText(text).width <= maxWidth) {- return text;- }- let truncated = text;- while (truncated.length > 0 && this.ctx.measureText(truncated + ellipsis).width > maxWidth) {- truncated = truncated.slice(0, -1);- }- return truncated + ellipsis;- }- /**- * Renders text for an entity and caches the result- */- renderForEntity(entity, text, uiRect) {- const existing = this.cache.get(entity);- if (existing) {- const rm = this.module.getResourceManager();- rm.releaseTexture(existing.textureHandle);- }- const result = this.renderText(text, uiRect);- this.cache.set(entity, result);- return result;- }- /**- * Gets cached render result for entity- */- getCached(entity) {- return this.cache.get(entity);- }- /**- * Releases texture for entity- */- release(entity) {- const cached = this.cache.get(entity);- if (cached) {- const rm = this.module.getResourceManager();- rm.releaseTexture(cached.textureHandle);- this.cache.delete(entity);- }- }- /**- * Releases all cached textures- */- releaseAll() {- const rm = this.module.getResourceManager();- for (const result of this.cache.values()) {- rm.releaseTexture(result.textureHandle);- }- this.cache.clear();- }- // =========================================================================- // Private Methods- // =========================================================================- wrapText(text, maxWidth) {- if (!text)- return [''];- if (maxWidth <= 0)- return text.split('\n');- const paragraphs = text.split('\n');- const lines = [];- for (const paragraph of paragraphs) {- if (!paragraph) {- lines.push('');- continue;- }- let currentLine = '';- for (const char of paragraph) {- const testLine = currentLine + char;- const metrics = this.ctx.measureText(testLine);- if (metrics.width > maxWidth && currentLine) {- lines.push(currentLine);- currentLine = char;- }- else {- currentLine = testLine;- }- }- if (currentLine) {- lines.push(currentLine);- }- }- return lines.length > 0 ? lines : [''];- }- measureWidth(lines) {- let maxWidth = 0;- for (const line of lines) {- const metrics = this.ctx.measureText(line);- const width = metrics.actualBoundingBoxLeft !== undefined- ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight- : metrics.width;- maxWidth = Math.max(maxWidth, width);- }- return maxWidth;- }- mapAlign(align) {- switch (align) {- case TextAlign.Left:- return 'left';- case TextAlign.Center:- return 'center';- case TextAlign.Right:- return 'right';- }- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- flipVertically(pixels, width, height) {- const rowSize = width * 4;- const flipped = new Uint8Array(pixels.length);- for (let y = 0; y < height; y++) {- const srcOffset = y * rowSize;- const dstOffset = (height - 1 - y) * rowSize;- flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);- }- return flipped;- }-}--/**- * @file UIRect.ts- * @brief UIRect component for UI layout with anchor and pivot- */-// =============================================================================-// UIRect Component Definition-// =============================================================================-const UIRect = defineComponent('UIRect', {- size: { x: 100, y: 100 },- anchor: { x: 0.5, y: 0.5 },- pivot: { x: 0.5, y: 0.5 },-});--/**- * @file TextPlugin.ts- * @brief Plugin that automatically syncs Text components to Sprite textures- */-// =============================================================================-// Text Plugin-// =============================================================================-class TextPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('TextPlugin: No WASM module available');- return;- }- const renderer = new TextRenderer(module);- const world = app.world;- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {- const entities = world.getEntitiesWithComponents([Text]);- for (const entity of entities) {- const text = world.get(entity, Text);- if (!text.dirty)- continue;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- size: { x: 0, y: 0 },- color: { x: 1, y: 1, z: 1, w: 1 },- anchor: { x: 0.5, y: 0.5 },- flip: { x: false, y: false }- });- }- const uiRect = world.has(entity, UIRect)- ? world.get(entity, UIRect)- : null;- const result = renderer.renderForEntity(entity, text, uiRect);- const sprite = world.get(entity, Sprite);- sprite.texture = result.textureHandle;- sprite.size = { x: result.width, y: result.height };- sprite.uvOffset = { x: 0, y: 0 };- sprite.uvScale = { x: 1, y: 1 };- world.insert(entity, Sprite, sprite);- text.dirty = false;- }- }));- }-}-const textPlugin = new TextPlugin();--/**- * @file blend.ts- * @brief Blend mode definitions for rendering- */-var BlendMode;-(function (BlendMode) {- BlendMode[BlendMode["Normal"] = 0] = "Normal";- BlendMode[BlendMode["Additive"] = 1] = "Additive";- BlendMode[BlendMode["Multiply"] = 2] = "Multiply";- BlendMode[BlendMode["Screen"] = 3] = "Screen";- BlendMode[BlendMode["PremultipliedAlpha"] = 4] = "PremultipliedAlpha";-})(BlendMode || (BlendMode = {}));--/**- * @file material.ts- * @brief Material and Shader API for custom rendering- * @details Provides shader creation and material management for custom visual effects.- */-function isTextureRef(v) {- return typeof v === 'object' && v !== null && '__textureRef' in v;-}-// =============================================================================-// Internal State-// =============================================================================-let module$5 = null;-let resourceManager = null;-let nextMaterialId = 1;-const materials = new Map();-// =============================================================================-// Initialization-// =============================================================================-function initMaterialAPI(wasmModule) {- module$5 = wasmModule;- resourceManager = wasmModule.getResourceManager();- registerMaterialCallback();-}-function shutdownMaterialAPI() {- if (uniformBuffer$1 !== 0 && module$5) {- module$5._free(uniformBuffer$1);- uniformBuffer$1 = 0;- }- materials.clear();- nextMaterialId = 1;- materialCallbackRegistered = false;- resourceManager = null;- module$5 = null;-}-// =============================================================================-// Shader API-// =============================================================================-function getResourceManager() {- if (!resourceManager) {- throw new Error('Material API not initialized. Call initMaterialAPI() first.');- }- return resourceManager;-}-const Material = {- /**- * Creates a shader from vertex and fragment source code.- * @param vertexSrc GLSL vertex shader source- * @param fragmentSrc GLSL fragment shader source- * @returns Shader handle, or 0 on failure- */- createShader(vertexSrc, fragmentSrc) {- return getResourceManager().createShader(vertexSrc, fragmentSrc);- },- /**- * Releases a shader.- * @param shader Shader handle to release- */- releaseShader(shader) {- if (shader > 0) {- getResourceManager().releaseShader(shader);- }- },- /**- * Creates a material with a shader and optional settings.- * @param options Material creation options- * @returns Material handle- */- create(options) {- const handle = nextMaterialId++;- const data = {- shader: options.shader,- uniforms: new Map(),- blendMode: options.blendMode ?? BlendMode.Normal,- depthTest: options.depthTest ?? false,- };- if (options.uniforms) {- for (const [key, value] of Object.entries(options.uniforms)) {- data.uniforms.set(key, value);- }- }- materials.set(handle, data);- return handle;- },- /**- * Gets material data by handle.- * @param material Material handle- * @returns Material data or undefined- */- get(material) {- return materials.get(material);- },- /**- * Sets a uniform value on a material.- * @param material Material handle- * @param name Uniform name- * @param value Uniform value- */- setUniform(material, name, value) {- const data = materials.get(material);- if (data) {- data.uniforms.set(name, value);- }- },- /**- * Gets a uniform value from a material.- * @param material Material handle- * @param name Uniform name- * @returns Uniform value or undefined- */- getUniform(material, name) {- const data = materials.get(material);- return data?.uniforms.get(name);- },- /**- * Sets the blend mode for a material.- * @param material Material handle- * @param mode Blend mode- */- setBlendMode(material, mode) {- const data = materials.get(material);- if (data) {- data.blendMode = mode;- }- },- /**- * Gets the blend mode of a material.- * @param material Material handle- * @returns Blend mode- */- getBlendMode(material) {- const data = materials.get(material);- return data?.blendMode ?? BlendMode.Normal;- },- /**- * Sets depth test enabled for a material.- * @param material Material handle- * @param enabled Whether depth test is enabled- */- setDepthTest(material, enabled) {- const data = materials.get(material);- if (data) {- data.depthTest = enabled;- }- },- /**- * Gets the shader handle for a material.- * @param material Material handle- * @returns Shader handle- */- getShader(material) {- const data = materials.get(material);- return data?.shader ?? 0;- },- /**- * Releases a material (does not release the shader).- * @param material Material handle- */- release(material) {- materials.delete(material);- },- /**- * Checks if a material exists.- * @param material Material handle- * @returns True if material exists- */- isValid(material) {- return materials.has(material);- },- /**- * Creates a material from asset data.- * @param data Material asset data (properties object)- * @param shaderHandle Pre-loaded shader handle- * @returns Material handle- */- createFromAsset(data, shaderHandle) {- const uniforms = {};- for (const [key, value] of Object.entries(data.properties)) {- if (typeof value === 'number') {- uniforms[key] = value;- }- else if (typeof value === 'object' && value !== null) {- const obj = value;- if ('w' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };- }- else if ('z' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };- }- else if ('y' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0 };- }- }- }- return this.create({- shader: shaderHandle,- uniforms,- blendMode: data.blendMode ?? BlendMode.Normal,- depthTest: data.depthTest ?? false,- });- },- /**- * Creates a material instance that shares the shader with source.- * @param source Source material handle- * @returns New material handle with copied settings- */- createInstance(source) {- const sourceData = materials.get(source);- if (!sourceData) {- throw new Error(`Invalid source material: ${source}`);- }- const handle = nextMaterialId++;- const data = {- shader: sourceData.shader,- uniforms: new Map(sourceData.uniforms),- blendMode: sourceData.blendMode,- depthTest: sourceData.depthTest,- };- materials.set(handle, data);- return handle;- },- /**- * Exports material to serializable asset data.- * @param material Material handle- * @param shaderPath Shader file path for asset reference- * @returns Material asset data- */- toAssetData(material, shaderPath) {- const data = materials.get(material);- if (!data)- return null;- const properties = {};- for (const [key, value] of data.uniforms) {- properties[key] = value;- }- return {- version: '1.0',- type: 'material',- shader: shaderPath,- blendMode: data.blendMode,- depthTest: data.depthTest,- properties,- };- },- /**- * Gets all uniforms from a material.- * @param material Material handle- * @returns Map of uniform names to values- */- getUniforms(material) {- const data = materials.get(material);- return data ? new Map(data.uniforms) : new Map();- },- tex(textureId, slot) {- return { __textureRef: true, textureId, slot };- },-};-// =============================================================================-// Material Callback Registration-// =============================================================================-let materialCallbackRegistered = false;-let uniformBuffer$1 = 0;-const UNIFORM_BUFFER_SIZE = 4096;-function ensureUniformBuffer() {- if (uniformBuffer$1 === 0 && module$5) {- uniformBuffer$1 = module$5._malloc(UNIFORM_BUFFER_SIZE);- }- return uniformBuffer$1;-}-function serializeUniforms(uniforms) {- const bufferPtr = ensureUniformBuffer();- if (bufferPtr === 0 || !module$5)- return { ptr: 0, count: 0 };- let offset = 0;- let count = 0;- const heap8 = module$5.HEAPU8;- const heap32 = module$5.HEAPU32;- const heapF32 = module$5.HEAPF32;- for (const [name, value] of uniforms) {- if (offset + 128 > UNIFORM_BUFFER_SIZE)- break;- const nameBytes = new TextEncoder().encode(name);- const nameLen = nameBytes.length;- const namePadded = Math.ceil(nameLen / 4) * 4;- heap32[(bufferPtr + offset) >> 2] = nameLen;- offset += 4;- heap8.set(nameBytes, bufferPtr + offset);- offset += namePadded;- let type = 0;- let values = [0, 0, 0, 0];- if (typeof value === 'number') {- type = 0;- values[0] = value;- }- else if (Array.isArray(value)) {- type = Math.min(value.length - 1, 3);- for (let i = 0; i < Math.min(value.length, 4); i++) {- values[i] = value[i];- }- }- else if ('w' in value) {- type = 3;- values = [value.x, value.y, value.z, value.w];- }- else if ('z' in value) {- type = 2;- values = [value.x, value.y, value.z, 0];- }- else if ('y' in value) {- type = 1;- values = [value.x, value.y, 0, 0];- }- heap32[(bufferPtr + offset) >> 2] = type;- offset += 4;- for (let i = 0; i < 4; i++) {- heapF32[(bufferPtr + offset) >> 2] = values[i];- offset += 4;- }- count++;- }- return { ptr: bufferPtr, count };-}-function registerMaterialCallback() {- if (!module$5 || materialCallbackRegistered)- return;- const callback = (materialId, outShaderIdPtr, outBlendModePtr, outUniformBufferPtr, outUniformCountPtr) => {- const data = materials.get(materialId);- if (!data) {- module$5.HEAPU32[outShaderIdPtr >> 2] = 0;- module$5.HEAPU32[outBlendModePtr >> 2] = 0;- module$5.HEAPU32[outUniformBufferPtr >> 2] = 0;- module$5.HEAPU32[outUniformCountPtr >> 2] = 0;- return;- }- module$5.HEAPU32[outShaderIdPtr >> 2] = data.shader;- module$5.HEAPU32[outBlendModePtr >> 2] = data.blendMode;- const { ptr, count } = serializeUniforms(data.uniforms);- module$5.HEAPU32[outUniformBufferPtr >> 2] = ptr;- module$5.HEAPU32[outUniformCountPtr >> 2] = count;- };- module$5.materialDataProvider = callback;- materialCallbackRegistered = true;-}-// =============================================================================-// Built-in Shader Sources-// =============================================================================-const ShaderSources = {- SPRITE_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;-layout(location = 2) in vec2 a_texCoord;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;-out vec2 v_texCoord;--void main() {- v_color = a_color;- v_texCoord = a_texCoord;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- SPRITE_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;-in vec2 v_texCoord;--uniform sampler2D u_texture;--out vec4 fragColor;--void main() {- fragColor = texture(u_texture, v_texCoord) * v_color;-}-`,- COLOR_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;--void main() {- v_color = a_color;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- COLOR_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;--out vec4 fragColor;--void main() {- fragColor = v_color;-}-`,-};--/**- * @file draw.ts- * @brief Immediate mode 2D drawing API- * @details Provides simple drawing primitives (lines, rectangles, circles)- * with automatic batching. All draw commands are cleared each frame.- */-// =============================================================================-// Internal State-// =============================================================================-let module$4 = null;-let viewProjectionPtr$1 = 0;-let transformPtr = 0;-let uniformsPtr = 0;-const UNIFORMS_BUFFER_SIZE = 256;-const uniformBuffer = new Float32Array(UNIFORMS_BUFFER_SIZE);-// =============================================================================-// Initialization-// =============================================================================-function initDrawAPI(wasmModule) {- module$4 = wasmModule;- viewProjectionPtr$1 = module$4._malloc(16 * 4);- transformPtr = module$4._malloc(16 * 4);- uniformsPtr = module$4._malloc(UNIFORMS_BUFFER_SIZE * 4);-}-function shutdownDrawAPI() {- if (module$4) {- if (viewProjectionPtr$1) {- module$4._free(viewProjectionPtr$1);- viewProjectionPtr$1 = 0;- }- if (transformPtr) {- module$4._free(transformPtr);- transformPtr = 0;- }- if (uniformsPtr) {- module$4._free(uniformsPtr);- uniformsPtr = 0;- }- }- module$4 = null;-}-// =============================================================================-// Draw Implementation-// =============================================================================-function getModule$2() {- if (!module$4) {- throw new Error('Draw API not initialized. Call initDrawAPI() first.');- }- return module$4;-}-const WHITE = { x: 1, y: 1, z: 1, w: 1 };-const Draw = {- begin(viewProjection) {- const m = getModule$2();- m.HEAPF32.set(viewProjection, viewProjectionPtr$1 / 4);- m.draw_begin(viewProjectionPtr$1);- },- end() {- getModule$2().draw_end();- },- line(from, to, color, thickness = 1) {- getModule$2().draw_line(from.x, from.y, to.x, to.y, color.x, color.y, color.z, color.w, thickness);- },- rect(position, size, color, filled = true) {- getModule$2().draw_rect(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, filled);- },- rectOutline(position, size, color, thickness = 1) {- getModule$2().draw_rectOutline(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, thickness);- },- circle(center, radius, color, filled = true, segments = 32) {- getModule$2().draw_circle(center.x, center.y, radius, color.x, color.y, color.z, color.w, filled, segments);- },- circleOutline(center, radius, color, thickness = 1, segments = 32) {- getModule$2().draw_circleOutline(center.x, center.y, radius, color.x, color.y, color.z, color.w, thickness, segments);- },- texture(position, size, textureHandle, tint = WHITE) {- getModule$2().draw_texture(position.x, position.y, size.x, size.y, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- textureRotated(position, size, rotation, textureHandle, tint = WHITE) {- getModule$2().draw_textureRotated(position.x, position.y, size.x, size.y, rotation, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- setLayer(layer) {- getModule$2().draw_setLayer(layer);- },- setDepth(depth) {- getModule$2().draw_setDepth(depth);- },- getDrawCallCount() {- if (!module$4)- return 0;- return module$4.draw_getDrawCallCount();- },- getPrimitiveCount() {- if (!module$4)- return 0;- return module$4.draw_getPrimitiveCount();- },- setBlendMode(mode) {- getModule$2().draw_setBlendMode(mode);- },- setDepthTest(enabled) {- getModule$2().draw_setDepthTest(enabled);- },- drawMesh(geometry, shader, transform) {- const m = getModule$2();- m.HEAPF32.set(transform, transformPtr / 4);- m.draw_mesh(geometry, shader, transformPtr);- },- drawMeshWithMaterial(geometry, material, transform) {- const m = getModule$2();- const matData = Material.get(material);- if (!matData)- return;- Draw.setBlendMode(matData.blendMode);- Draw.setDepthTest(matData.depthTest);- if (matData.uniforms.size === 0) {- Draw.drawMesh(geometry, matData.shader, transform);- return;- }- m.HEAPF32.set(transform, transformPtr / 4);- let idx = 0;- let autoTextureSlot = 0;- for (const [name, value] of matData.uniforms) {- const nameId = getUniformNameId(name);- if (nameId < 0)- continue;- if (isTextureRef(value)) {- uniformBuffer[idx++] = 10;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.slot ?? autoTextureSlot++;- uniformBuffer[idx++] = value.textureId;- }- else if (typeof value === 'number') {- uniformBuffer[idx++] = 1;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value;- }- else if (Array.isArray(value)) {- uniformBuffer[idx++] = value.length;- uniformBuffer[idx++] = nameId;- for (let i = 0; i < value.length; i++) {- uniformBuffer[idx++] = value[i];- }- }- else if ('w' in value) {- uniformBuffer[idx++] = 4;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- uniformBuffer[idx++] = value.w;- }- else if ('z' in value) {- uniformBuffer[idx++] = 3;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- }- else {- uniformBuffer[idx++] = 2;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- }- if (idx > UNIFORMS_BUFFER_SIZE - 6) {- console.warn('Uniform buffer overflow, some uniforms will be ignored');- break;- }- }- if (idx === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);- return;- }- m.HEAPF32.set(uniformBuffer.subarray(0, idx), uniformsPtr / 4);- m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);- },-};-const UNIFORM_NAME_MAP = {- '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 getUniformNameId(name) {- return UNIFORM_NAME_MAP[name] ?? -1;-}--/**- * @file geometry.ts- * @brief Geometry API for custom mesh rendering- * @details Provides geometry creation and management for custom shapes,- * particles, trails, and other procedural meshes.- */-var DataType;-(function (DataType) {- DataType[DataType["Float"] = 1] = "Float";- DataType[DataType["Float2"] = 2] = "Float2";- DataType[DataType["Float3"] = 3] = "Float3";- DataType[DataType["Float4"] = 4] = "Float4";- DataType[DataType["Int"] = 5] = "Int";- DataType[DataType["Int2"] = 6] = "Int2";- DataType[DataType["Int3"] = 7] = "Int3";- DataType[DataType["Int4"] = 8] = "Int4";-})(DataType || (DataType = {}));-// =============================================================================-// Internal State-// =============================================================================-let module$3 = null;-let vertexPtr = 0;-let indexPtr = 0;-let layoutPtr = 0;-const VERTEX_BUFFER_SIZE = 64 * 1024;-const INDEX_BUFFER_SIZE = 16 * 1024;-const LAYOUT_BUFFER_SIZE = 64;-// =============================================================================-// Initialization-// =============================================================================-function initGeometryAPI(wasmModule) {- module$3 = wasmModule;- vertexPtr = module$3._malloc(VERTEX_BUFFER_SIZE * 4);- indexPtr = module$3._malloc(INDEX_BUFFER_SIZE * 4);- layoutPtr = module$3._malloc(LAYOUT_BUFFER_SIZE * 4);-}-function shutdownGeometryAPI() {- if (module$3) {- if (vertexPtr)- module$3._free(vertexPtr);- if (indexPtr)- module$3._free(indexPtr);- if (layoutPtr)- module$3._free(layoutPtr);- vertexPtr = 0;- indexPtr = 0;- layoutPtr = 0;- }- module$3 = null;-}-// =============================================================================-// Geometry API-// =============================================================================-function getModule$1() {- if (!module$3) {- throw new Error('Geometry API not initialized. Call initGeometryAPI() first.');- }- return module$3;-}-const Geometry = {- /**- * Creates a new geometry with vertices and optional indices.- * @param options Geometry creation options- * @returns Geometry handle- */- create(options) {- const m = getModule$1();- const handle = m.geometry_create();- if (handle === 0) {- throw new Error('Failed to create geometry');- }- const vertexCount = options.vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(options.vertices, vertexPtr / 4);- const layoutCount = options.layout.length;- const layoutArray = new Int32Array(layoutCount);- for (let i = 0; i < layoutCount; i++) {- layoutArray[i] = options.layout[i].type;- }- const heap32 = new Int32Array(m.HEAPU8.buffer, layoutPtr, layoutCount);- heap32.set(layoutArray);- m.geometry_init(handle, vertexPtr, vertexCount, layoutPtr, layoutCount, options.dynamic ?? false);- if (options.indices) {- const indexCount = options.indices.length;- if (indexCount * 4 > INDEX_BUFFER_SIZE * 4) {- throw new Error(`Index data too large: ${indexCount} indices (max ${INDEX_BUFFER_SIZE})`);- }- if (options.indices instanceof Uint16Array) {- const heap16 = new Uint16Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap16.set(options.indices);- m.geometry_setIndices16(handle, indexPtr, indexCount);- }- else {- const heap32 = new Uint32Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap32.set(options.indices);- m.geometry_setIndices32(handle, indexPtr, indexCount);- }- }- return handle;- },- /**- * Updates vertices of a dynamic geometry.- * @param handle Geometry handle- * @param vertices New vertex data- * @param offset Offset in floats- */- updateVertices(handle, vertices, offset = 0) {- const m = getModule$1();- const vertexCount = vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(vertices, vertexPtr / 4);- m.geometry_updateVertices(handle, vertexPtr, vertexCount, offset);- },- /**- * Releases a geometry.- * @param handle Geometry handle- */- release(handle) {- if (handle > 0) {- getModule$1().geometry_release(handle);- }- },- /**- * Checks if a geometry handle is valid.- * @param handle Geometry handle- * @returns True if valid- */- isValid(handle) {- if (!module$3 || handle <= 0)- return false;- return module$3.geometry_isValid(handle);- },- // =========================================================================- // Helper Functions- // =========================================================================- /**- * Creates a unit quad geometry (1x1, centered at origin).- * @returns Geometry handle- */- createQuad(width = 1, height = 1) {- const hw = width / 2;- const hh = height / 2;- return Geometry.create({- vertices: new Float32Array([- // x, y, u, v- -hw, -hh, 0, 0,- hw, -hh, 1, 0,- hw, hh, 1, 1,- -hw, hh, 0, 1,- ]),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array([0, 1, 2, 2, 3, 0]),- });- },- /**- * Creates a circle geometry.- * @param radius Circle radius- * @param segments Number of segments- * @returns Geometry handle- */- createCircle(radius = 1, segments = 32) {- const vertices = [];- const indices = [];- vertices.push(0, 0, 0.5, 0.5);- for (let i = 0; i <= segments; i++) {- const angle = (i / segments) * Math.PI * 2;- const x = Math.cos(angle) * radius;- const y = Math.sin(angle) * radius;- const u = (Math.cos(angle) + 1) / 2;- const v = (Math.sin(angle) + 1) / 2;- vertices.push(x, y, u, v);- }- for (let i = 1; i <= segments; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },- /**- * Creates a polygon geometry from vertices.- * @param points Array of {x, y} points- * @returns Geometry handle- */- createPolygon(points) {- if (points.length < 3) {- throw new Error('Polygon must have at least 3 points');- }- let minX = Infinity, minY = Infinity;- let maxX = -Infinity, maxY = -Infinity;- for (const p of points) {- minX = Math.min(minX, p.x);- minY = Math.min(minY, p.y);- maxX = Math.max(maxX, p.x);- maxY = Math.max(maxY, p.y);- }- const vertices = [];- for (const p of points) {- const u = (p.x - minX) / (maxX - minX);- const v = (p.y - minY) / (maxY - minY);- vertices.push(p.x, p.y, u, v);- }- const indices = [];- for (let i = 1; i < points.length - 1; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },-};--/**- * @file postprocess.ts- * @brief Post-processing effects API- * @details Provides full-screen post-processing effects like blur, vignette, etc.- */-// =============================================================================-// Internal State-// =============================================================================-let module$2 = null;-// =============================================================================-// Initialization-// =============================================================================-function initPostProcessAPI(wasmModule) {- module$2 = wasmModule;-}-function shutdownPostProcessAPI() {- if (module$2 && PostProcess.isInitialized()) {- PostProcess.shutdown();- }- module$2 = null;-}-// =============================================================================-// PostProcess API-// =============================================================================-function getModule() {- if (!module$2) {- throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');- }- return module$2;-}-const PostProcess = {- /**- * Initializes the post-processing pipeline.- * @param width Framebuffer width- * @param height Framebuffer height- * @returns True on success- */- init(width, height) {- return getModule().postprocess_init(width, height);- },- /**- * Shuts down the post-processing pipeline.- */- shutdown() {- getModule().postprocess_shutdown();- },- /**- * Resizes the framebuffers.- * @param width New width- * @param height New height- */- resize(width, height) {- getModule().postprocess_resize(width, height);- },- /**- * Adds a post-processing pass.- * @param name Unique name for the pass- * @param shader Shader handle- * @returns Pass index- */- addPass(name, shader) {- return getModule().postprocess_addPass(name, shader);- },- /**- * Removes a pass by name.- * @param name Pass name- */- removePass(name) {- getModule().postprocess_removePass(name);- },- /**- * Enables or disables a pass.- * @param name Pass name- * @param enabled Whether to enable the pass- */- setEnabled(name, enabled) {- getModule().postprocess_setPassEnabled(name, enabled);- },- /**- * Checks if a pass is enabled.- * @param name Pass name- * @returns True if enabled- */- isEnabled(name) {- return getModule().postprocess_isPassEnabled(name);- },- /**- * Sets a float uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Float value- */- setUniform(passName, uniform, value) {- getModule().postprocess_setUniformFloat(passName, uniform, value);- },- /**- * Sets a vec4 uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Vec4 value- */- setUniformVec4(passName, uniform, value) {- getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);- },- /**- * Begins rendering to the post-process pipeline.- * Call this before rendering your scene.- */- begin() {- getModule().postprocess_begin();- },- /**- * Ends and processes all passes.- * Call this after rendering your scene.- */- end() {- getModule().postprocess_end();- },- /**- * Gets the number of passes.- */- getPassCount() {- return getModule().postprocess_getPassCount();- },- /**- * Checks if the pipeline is initialized.- */- isInitialized() {- if (!module$2)- return false;- return module$2.postprocess_isInitialized();- },- /**- * Sets bypass mode to skip FBO rendering entirely.- * When bypassed, begin()/end() become no-ops and scene renders directly to screen.- * Use this when no post-processing passes are needed for maximum performance.- * @param bypass Whether to bypass the pipeline- */- setBypass(bypass) {- getModule().postprocess_setBypass(bypass);- },- /**- * Checks if bypass mode is enabled.- * @returns True if bypassed- */- isBypassed() {- if (!module$2)- return true;- return module$2.postprocess_isBypassed();- },- // =========================================================================- // Built-in Effects- // =========================================================================- /**- * Creates a blur effect shader.- * @returns Shader handle- */- createBlur() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 texelSize = 1.0 / u_resolution;- float offset = u_intensity;-- vec4 color = vec4(0.0);- color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord) * 0.25;- color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;-- fragColor = color;-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a vignette effect shader.- * @returns Shader handle- */- createVignette() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-uniform float u_softness;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- vec2 uv = v_texCoord * 2.0 - 1.0;- float dist = length(uv);- float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);- fragColor = vec4(color.rgb * vignette, color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a grayscale effect shader.- * @returns Shader handle- */- createGrayscale() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));- fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a chromatic aberration effect shader.- * @returns Shader handle- */- createChromaticAberration() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 offset = u_intensity / u_resolution;- float r = texture(u_texture, v_texCoord + offset).r;- float g = texture(u_texture, v_texCoord).g;- float b = texture(u_texture, v_texCoord - offset).b;- float a = texture(u_texture, v_texCoord).a;- fragColor = vec4(r, g, b, a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },-};-// =============================================================================-// Shared Vertex Shader-// =============================================================================-const POSTPROCESS_VERTEX = `#version 300 es-precision highp float;--layout(location = 0) in vec2 a_position;-layout(location = 1) in vec2 a_texCoord;--out vec2 v_texCoord;--void main() {- v_texCoord = a_texCoord;- gl_Position = vec4(a_position, 0.0, 1.0);-}-`;--var RenderStage;-(function (RenderStage) {- RenderStage[RenderStage["Background"] = 0] = "Background";- RenderStage[RenderStage["Opaque"] = 1] = "Opaque";- RenderStage[RenderStage["Transparent"] = 2] = "Transparent";- RenderStage[RenderStage["Overlay"] = 3] = "Overlay";-})(RenderStage || (RenderStage = {}));-let module$1 = null;-let viewProjectionPtr = 0;-function initRendererAPI(wasmModule) {- module$1 = wasmModule;- viewProjectionPtr = module$1._malloc(16 * 4);-}-function shutdownRendererAPI() {- if (module$1 && viewProjectionPtr) {- module$1._free(viewProjectionPtr);- viewProjectionPtr = 0;- }- module$1 = null;-}-const Renderer = {- init(width, height) {- module$1?.renderer_init(width, height);- },- resize(width, height) {- module$1?.renderer_resize(width, height);- },- begin(viewProjection, target) {- if (!module$1 || !viewProjectionPtr)- return;- module$1.HEAPF32.set(viewProjection, viewProjectionPtr / 4);- module$1.renderer_begin(viewProjectionPtr, target ?? 0);- },- end() {- module$1?.renderer_end();- },- submitSprites(registry) {- if (!module$1)- return;- module$1.renderer_submitSprites(registry._cpp);- },- submitSpine(registry) {- if (!module$1)- return;- module$1.renderer_submitSpine(registry._cpp);- },- setStage(stage) {- module$1?.renderer_setStage(stage);- },- createRenderTarget(width, height, flags = 1) {- return module$1?.renderer_createTarget(width, height, flags) ?? 0;- },- releaseRenderTarget(handle) {- module$1?.renderer_releaseTarget(handle);- },- getTargetTexture(handle) {- return module$1?.renderer_getTargetTexture(handle) ?? 0;- },- getTargetDepthTexture(handle) {- return module$1?.renderer_getTargetDepthTexture(handle) ?? 0;- },- setClearColor(r, g, b, a) {- module$1?.renderer_setClearColor?.(r, g, b, a);- },- getStats() {- if (!module$1) {- return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };- }- return {- drawCalls: module$1.renderer_getDrawCalls(),- triangles: module$1.renderer_getTriangles(),- sprites: module$1.renderer_getSprites(),- spine: module$1.renderer_getSpine(),- meshes: module$1.renderer_getMeshes(),- culled: module$1.renderer_getCulled(),- };- },-};--/**- * @file customDraw.ts- * @brief Custom draw callback registration for the render pipeline- */-const callbacks = new Map();-function registerDrawCallback(id, fn) {- callbacks.set(id, fn);-}-function unregisterDrawCallback(id) {- callbacks.delete(id);-}-function clearDrawCallbacks() {- callbacks.clear();-}-function getDrawCallbacks() {- return callbacks;-}--/**- * @file renderPipeline.ts- * @brief Unified render pipeline for runtime and editor- */-class RenderPipeline {- render(params) {- const { registry, viewProjection, width, height, elapsed } = params;- Renderer.resize(width, height);- const usePostProcess = PostProcess.isInitialized()- && PostProcess.getPassCount() > 0- && !PostProcess.isBypassed();- if (usePostProcess) {- PostProcess.resize(width, height);- PostProcess.begin();- }- Renderer.begin(viewProjection);- Renderer.submitSprites(registry);- Renderer.submitSpine(registry);- Renderer.end();- const cbs = getDrawCallbacks();- if (cbs.size > 0) {- Draw.begin(viewProjection);- const failed = [];- for (const [id, fn] of cbs.entries()) {- try {- fn(elapsed);- }- catch (e) {- console.error(`[CustomDraw] callback '${id}' error:`, e);- failed.push(id);- }- }- Draw.end();- for (const id of failed) {- unregisterDrawCallback(id);- }- }- if (usePostProcess) {- PostProcess.end();- }- }-}--/**- * @file app.ts- * @brief Application builder and web platform integration- */-// =============================================================================-// App-// =============================================================================-class App {- constructor() {- this.systems_ = new Map();- this.runner_ = null;- this.running_ = false;- this.lastTime_ = 0;- this.module_ = null;- this.mainLoop = () => {- if (!this.running_) {- return;- }- const now = performance.now();- const deltaMs = now - this.lastTime_;- this.lastTime_ = now;- const delta = deltaMs / 1000;- this.updateTime(delta);- this.runSchedule(Schedule.First);- this.runSchedule(Schedule.PreUpdate);- this.runSchedule(Schedule.Update);- this.runSchedule(Schedule.PostUpdate);- this.runSchedule(Schedule.Last);- requestAnimationFrame(this.mainLoop);- };- this.world_ = new World();- this.resources_ = new ResourceStorage();- for (const s of Object.values(Schedule)) {- if (typeof s === 'number') {- this.systems_.set(s, []);- }- }- }- static new() {- return new App();- }- // =========================================================================- // Plugins- // =========================================================================- addPlugin(plugin) {- plugin.build(this);- return this;- }- // =========================================================================- // Systems- // =========================================================================- addSystemToSchedule(schedule, system) {- this.systems_.get(schedule).push({ system });- return this;- }- addSystem(system) {- return this.addSystemToSchedule(Schedule.Update, system);- }- addStartupSystem(system) {- return this.addSystemToSchedule(Schedule.Startup, system);- }- // =========================================================================- // C++ Integration- // =========================================================================- connectCpp(cppRegistry, module) {- this.world_.connectCpp(cppRegistry);- if (module) {- this.module_ = module;- }- return this;- }- get wasmModule() {- return this.module_;- }- // =========================================================================- // World Access- // =========================================================================- get world() {- return this.world_;- }- // =========================================================================- // Resource Access- // =========================================================================- insertResource(resource, value) {- this.resources_.insert(resource, value);- return this;- }- getResource(resource) {- return this.resources_.get(resource);- }- hasResource(resource) {- return this.resources_.has(resource);- }- // =========================================================================- // Run- // =========================================================================- run() {- if (this.running_) {- return;- }- this.running_ = true;- this.runner_ = new SystemRunner(this.world_, this.resources_);- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });- this.runSchedule(Schedule.Startup);- this.lastTime_ = performance.now();- this.mainLoop();- }- quit() {- this.running_ = false;- shutdownRendererAPI();- shutdownPostProcessAPI();- shutdownGeometryAPI();- shutdownMaterialAPI();- shutdownDrawAPI();- }- // =========================================================================- // Internal- // =========================================================================- runSchedule(schedule) {- const systems = this.systems_.get(schedule);- if (!systems || !this.runner_) {- return;- }- for (const entry of systems) {- this.runner_.run(entry.system);- }- }- updateTime(delta) {- const time = this.resources_.get(Time);- const newTime = {- delta,- elapsed: time.elapsed + delta,- frameCount: time.frameCount + 1- };- this.resources_.set(Time, newTime);- }-}-function createWebApp(module, options) {- const app = App.new();- const cppRegistry = new module.Registry();- app.connectCpp(cppRegistry, module);- if (options?.glContextHandle) {- module.initRendererWithContext(options.glContextHandle);- }- else {- module.initRenderer();- }- initDrawAPI(module);- initMaterialAPI(module);- initGeometryAPI(module);- initPostProcessAPI(module);- initRendererAPI(module);- const pipeline = new RenderPipeline();- let startTime = performance.now();- const getViewportSize = options?.getViewportSize ?? (() => ({- width: window.innerWidth * (window.devicePixelRatio || 1),- height: window.innerHeight * (window.devicePixelRatio || 1)- }));- const renderSystem = {- _id: Symbol('RenderSystem'),- _name: 'RenderSystem',- _params: [],- _fn: () => {- const { width, height } = getViewportSize();- const vp = computeViewProjection(cppRegistry, width, height);- const elapsed = (performance.now() - startTime) / 1000;- pipeline.render({- registry: { _cpp: cppRegistry },- viewProjection: vp,- width, height, elapsed,- });- }- };- app.addSystemToSchedule(Schedule.Last, renderSystem);- app.addPlugin(textPlugin);- return app;-}-function flushPendingSystems(app) {- if (typeof window === 'undefined')- return;- const pending = window.__esengine_pendingSystems;- if (!pending || pending.length === 0)- return;- for (const entry of pending) {- app.addSystemToSchedule(entry.schedule, entry.system);- }- pending.length = 0;-}-// =============================================================================-// View-Projection Computation-// =============================================================================-const IDENTITY = new Float32Array([- 1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1,-]);-function computeViewProjection(registry, width, height) {- const count = registry.entityCount();- const scanLimit = count + 1000;- for (let e = 0; e < scanLimit; e++) {- if (!registry.valid(e) || !registry.hasCamera(e) || !registry.hasLocalTransform(e)) {- continue;- }- const camera = registry.getCamera(e);- if (!camera.isActive)- continue;- const transform = registry.getLocalTransform(e);- const aspect = width / height;- let projection;- if (camera.projectionType === 1) {- const halfH = camera.orthoSize;- const halfW = halfH * aspect;- projection = ortho(-halfW, halfW, -halfH, halfH, -camera.farPlane, camera.farPlane);- }- else {- projection = perspective(camera.fov * Math.PI / 180, aspect, camera.nearPlane, camera.farPlane);- }- const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);- return multiply(projection, view);- }- return IDENTITY;-}-function ortho(left, right, bottom, top, near, far) {- const m = new Float32Array(16);- const rl = right - left;- const tb = top - bottom;- const fn = far - near;- m[0] = 2 / rl;- m[5] = 2 / tb;- m[10] = -2 / fn;- m[12] = -(right + left) / rl;- m[13] = -(top + bottom) / tb;- m[14] = -(far + near) / fn;- m[15] = 1;- return m;-}-function perspective(fovRad, aspect, near, far) {- const m = new Float32Array(16);- const f = 1.0 / Math.tan(fovRad / 2);- const nf = near - far;- m[0] = f / aspect;- m[5] = f;- m[10] = (far + near) / nf;- m[11] = -1;- m[14] = (2 * far * near) / nf;- return m;-}-function invertTranslation(x, y, z) {- const m = new Float32Array(16);- m[0] = 1;- m[5] = 1;- m[10] = 1;- m[15] = 1;- m[12] = -x;- m[13] = -y;- m[14] = -z;- return m;-}-function multiply(a, b) {- const m = new Float32Array(16);- for (let i = 0; i < 4; i++) {- for (let j = 0; j < 4; j++) {- m[j * 4 + i] =- a[0 * 4 + i] * b[j * 4 + 0] +- a[1 * 4 + i] * b[j * 4 + 1] +- a[2 * 4 + i] * b[j * 4 + 2] +- a[3 * 4 + i] * b[j * 4 + 3];- }- }- return m;-}--/**- * @file MaterialLoader.ts- * @brief Material asset loading and caching- */-// =============================================================================-// MaterialLoader-// =============================================================================-class MaterialLoader {- constructor(shaderLoader, basePath = '') {- this.cache_ = new Map();- this.pending_ = new Map();- this.shaderLoader_ = shaderLoader;- this.basePath_ = basePath;- }- async load(path) {- const cached = this.cache_.get(path);- if (cached) {- return cached;- }- const pending = this.pending_.get(path);- if (pending) {- return pending;- }- const promise = this.loadInternal(path);- this.pending_.set(path, promise);- try {- const result = await promise;- this.cache_.set(path, result);- return result;- }- finally {- this.pending_.delete(path);- }- }- get(path) {- return this.cache_.get(path);- }- has(path) {- return this.cache_.has(path);- }- release(path) {- const loaded = this.cache_.get(path);- if (loaded) {- Material.release(loaded.handle);- this.cache_.delete(path);- }- }- releaseAll() {- for (const loaded of this.cache_.values()) {- Material.release(loaded.handle);- }- this.cache_.clear();- }- async loadInternal(path) {- const fullPath = this.resolvePath(path);- const exists = await platformFileExists(fullPath);- if (!exists) {- throw new Error(`Material file not found: ${fullPath}`);- }- const content = await platformReadTextFile(fullPath);- if (!content) {- throw new Error(`Failed to read material file: ${fullPath}`);- }- const data = JSON.parse(content);- if (data.type !== 'material') {- throw new Error(`Invalid material file type: ${data.type}`);- }- const shaderPath = this.resolveShaderPath(path, data.shader);- const shaderHandle = await this.shaderLoader_.load(shaderPath);- const materialHandle = Material.createFromAsset(data, shaderHandle);- return {- handle: materialHandle,- shaderHandle,- path,- };- }- resolvePath(path) {- if (path.startsWith('/') || path.startsWith('http')) {- return path;- }- return this.basePath_ ? `${this.basePath_}/${path}` : path;- }- resolveShaderPath(materialPath, shaderPath) {- if (shaderPath.startsWith('/') || shaderPath.startsWith('http') || shaderPath.startsWith('assets/')) {- return shaderPath;- }- const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));- return dir ? `${dir}/${shaderPath}` : shaderPath;- }-}--/**- * @file scene.ts- * @brief Scene loading utilities- */-// =============================================================================-// Scene Loader-// =============================================================================-function loadSceneData(world, sceneData) {- const entityMap = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- loadComponent(world, entity, compData);- }- }- // Set parent-child relationships- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- return entityMap;-}-async function loadSceneWithAssets(world, sceneData, options) {- const entityMap = new Map();- const assetServer = options?.assetServer;- const texturePathToUrl = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- }- catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data;- const skeletonPath = data.skeletonPath;- const atlasPath = data.atlasPath;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- loadComponent(world, entity, compData);- }- }- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- if (assetServer && sceneData.textureMetadata) {- for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {- const url = texturePathToUrl.get(texturePath);- if (url && metadata.sliceBorder) {- assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);- }- }- }- return entityMap;-}-function loadComponent(world, entity, compData) {- const data = compData.data;- switch (compData.type) {- case 'LocalTransform':- world.insert(entity, LocalTransform, data);- break;- case 'Sprite':- world.insert(entity, Sprite, data);- break;- case 'Camera':- world.insert(entity, Camera, data);- break;- case 'Canvas':- world.insert(entity, Canvas, data);- break;- case 'Text':- world.insert(entity, Text, data);- break;- case 'SpineAnimation':- world.insert(entity, SpineAnimation, data);- break;- case 'UIRect':- world.insert(entity, UIRect, data);- break;- default: {- const userComp = getUserComponent(compData.type);- if (userComp) {- world.insert(entity, userComp, data);- }- else {- console.warn(`Unknown component type: ${compData.type}`);- }- break;- }- }-}-function updateCameraAspectRatio(world, aspectRatio) {- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera) {- camera.aspectRatio = aspectRatio;- world.insert(entity, Camera, camera);- }- }-}--class AsyncCache {- constructor() {- this.cache_ = new Map();- this.pending_ = new Map();- }- async getOrLoad(key, loader) {- const cached = this.cache_.get(key);- if (cached !== undefined) {- return cached;- }- const pending = this.pending_.get(key);- if (pending) {- return pending;- }- const promise = loader();- this.pending_.set(key, promise);- try {- const result = await promise;- this.cache_.set(key, result);- return result;- }- finally {- this.pending_.delete(key);- }- }- get(key) {- return this.cache_.get(key);- }- has(key) {- return this.cache_.has(key);- }- delete(key) {- return this.cache_.delete(key);- }- clear() {- this.cache_.clear();- }- values() {- return this.cache_.values();- }-}--/**- * @file AssetServer.ts- * @brief Asset loading and caching system- */-// =============================================================================-// AssetServer-// =============================================================================-class AssetServer {- constructor(module) {- this.textureCache_ = new AsyncCache();- this.shaderCache_ = new AsyncCache();- this.jsonCache_ = new AsyncCache();- this.textCache_ = new AsyncCache();- this.binaryCache_ = new AsyncCache();- this.loadedSpines_ = new Set();- this.virtualFSPaths_ = new Set();- this.module_ = module;- this.canvas_ = this.createCanvas(512, 512);- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- const shaderLoader = {- load: (path) => this.loadShader(path),- get: (path) => this.shaderCache_.get(path),- };- this.materialLoader_ = new MaterialLoader(shaderLoader);- }- // =========================================================================- // Texture- // =========================================================================- /**- * Load texture with vertical flip (for Sprite/UI).- * OpenGL UV origin is bottom-left, so standard images need flipping.- */- async loadTexture(source) {- return this.loadTextureWithFlip(source, true);- }- /**- * Load texture without flip (for Spine).- * Spine runtime handles UV coordinates internally.- */- async loadTextureRaw(source) {- return this.loadTextureWithFlip(source, false);- }- getTexture(source) {- return this.textureCache_.get(this.textureCacheKey(source, true));- }- hasTexture(source) {- return this.textureCache_.has(this.textureCacheKey(source, true));- }- releaseTexture(source) {- const rm = this.module_.getResourceManager();- for (const flip of [true, false]) {- const key = this.textureCacheKey(source, flip);- const info = this.textureCache_.get(key);- if (info) {- rm.releaseTexture(info.handle);- this.textureCache_.delete(key);- }- }- }- releaseAll() {- const rm = this.module_.getResourceManager();- for (const info of this.textureCache_.values()) {- rm.releaseTexture(info.handle);- }- this.textureCache_.clear();- this.jsonCache_.clear();- this.textCache_.clear();- this.binaryCache_.clear();- }- setTextureMetadata(handle, border) {- const rm = this.module_.getResourceManager();- rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);- }- setTextureMetadataByPath(source, border) {- const info = this.textureCache_.get(this.textureCacheKey(source, true));- if (info) {- this.setTextureMetadata(info.handle, border);- return true;- }- return false;- }- // =========================================================================- // Spine- // =========================================================================- async loadSpine(skeletonPath, atlasPath, baseUrl) {- const cacheKey = `${skeletonPath}:${atlasPath}`;- if (this.loadedSpines_.has(cacheKey)) {- return { success: true };- }- try {- const atlasUrl = this.resolveUrl(atlasPath, baseUrl);- const atlasResponse = await fetch(atlasUrl);- if (!atlasResponse.ok) {- return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };- }- const atlasContent = await atlasResponse.text();- if (!this.writeToVirtualFS(atlasPath, atlasContent)) {- return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };- }- const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));- const textureNames = this.parseAtlasTextures(atlasContent);- for (const texName of textureNames) {- const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;- const texUrl = this.resolveUrl(texPath, baseUrl);- try {- const info = await this.loadTextureRaw(texUrl);- const rm = this.module_.getResourceManager();- rm.registerTextureWithPath(info.handle, texPath);- }- catch (err) {- console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);- }- }- const skelUrl = this.resolveUrl(skeletonPath, baseUrl);- const skelResponse = await fetch(skelUrl);- if (!skelResponse.ok) {- return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };- }- const isBinary = skeletonPath.endsWith('.skel');- const skelData = isBinary- ? new Uint8Array(await skelResponse.arrayBuffer())- : await skelResponse.text();- if (!this.writeToVirtualFS(skeletonPath, skelData)) {- return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };- }- this.loadedSpines_.add(cacheKey);- return { success: true };- }- catch (err) {- return { success: false, error: String(err) };- }- }- isSpineLoaded(skeletonPath, atlasPath) {- return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);- }- // =========================================================================- // Material & Shader- // =========================================================================- async loadMaterial(path, baseUrl) {- return this.materialLoader_.load(this.resolveUrl(path, baseUrl));- }- getMaterial(path, baseUrl) {- return this.materialLoader_.get(this.resolveUrl(path, baseUrl));- }- hasMaterial(path, baseUrl) {- return this.materialLoader_.has(this.resolveUrl(path, baseUrl));- }- async loadShader(path) {- return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));- }- // =========================================================================- // Generic File Loading- // =========================================================================- async loadJson(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchJson(url);- }- return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));- }- async loadText(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchText(url);- }- return this.textCache_.getOrLoad(url, () => this.fetchText(url));- }- async loadBinary(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchBinary(url);- }- return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));- }- // =========================================================================- // Scene & Batch- // =========================================================================- async loadScene(world, sceneData) {- return loadSceneWithAssets(world, sceneData, { assetServer: this });- }- async loadAll(manifest) {- const bundle = {- textures: new Map(),- materials: new Map(),- spine: new Map(),- json: new Map(),- text: new Map(),- binary: new Map(),- };- const promises = [];- if (manifest.textures) {- for (const path of manifest.textures) {- promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));- }- }- if (manifest.materials) {- for (const path of manifest.materials) {- promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));- }- }- if (manifest.spine) {- for (const desc of manifest.spine) {- const key = `${desc.skeleton}:${desc.atlas}`;- promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {- bundle.spine.set(key, result);- }));- }- }- if (manifest.json) {- for (const path of manifest.json) {- promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));- }- }- if (manifest.text) {- for (const path of manifest.text) {- promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));- }- }- if (manifest.binary) {- for (const path of manifest.binary) {- promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));- }- }- await Promise.all(promises);- return bundle;- }- // =========================================================================- // Private - Texture- // =========================================================================- textureCacheKey(source, flip) {- return `${source}:${flip ? 'f' : 'n'}`;- }- async loadTextureWithFlip(source, flip) {- const cacheKey = this.textureCacheKey(source, flip);- return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));- }- async loadTextureInternal(source, flip) {- const img = await this.loadImage(source);- return this.createTextureFromImage(img, flip);- }- async loadImage(source) {- return new Promise((resolve, reject) => {- const img = new Image();- img.crossOrigin = 'anonymous';- img.onload = async () => {- if (typeof createImageBitmap !== 'undefined') {- try {- const bitmap = await createImageBitmap(img, {- premultiplyAlpha: 'none',- colorSpaceConversion: 'none'- });- resolve(bitmap);- return;- }- catch {- // Fall back to Image element- }- }- resolve(img);- };- img.onerror = () => reject(new Error(`Failed to load image: ${source}`));- img.src = source;- });- }- createTextureFromImage(img, flip) {- const { width, height } = img;- if (this.canvas_.width < width || this.canvas_.height < height) {- this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));- this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));- }- this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);- this.ctx_.save();- if (flip) {- this.ctx_.translate(0, height);- this.ctx_.scale(1, -1);- }- this.ctx_.drawImage(img, 0, 0);- this.ctx_.restore();- const imageData = this.ctx_.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);- const rm = this.module_.getResourceManager();- const ptr = this.module_._malloc(pixels.length);- this.module_.HEAPU8.set(pixels, ptr);- const handle = rm.createTexture(width, height, ptr, pixels.length, 1);- this.module_._free(ptr);- return { handle, width, height };- }- unpremultiplyAlpha(pixels) {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }- // =========================================================================- // Private - Shader- // =========================================================================- async loadShaderInternal(path) {- const exists = await platformFileExists(path);- if (!exists) {- throw new Error(`Shader file not found: ${path}`);- }- const content = await platformReadTextFile(path);- if (!content) {- throw new Error(`Failed to read shader file: ${path}`);- }- const { vertex, fragment } = this.parseEsShader(content);- if (!vertex || !fragment) {- throw new Error(`Invalid shader format: ${path}`);- }- return Material.createShader(vertex, fragment);- }- parseEsShader(content) {- const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);- const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);- return {- vertex: vertexMatch?.[1].trim() ?? null,- fragment: fragmentMatch?.[1].trim() ?? null,- };- }- // =========================================================================- // Private - Generic Fetch- // =========================================================================- async fetchJson(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);- }- return response.json();- }- async fetchText(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch text: ${url} (${response.status})`);- }- return response.text();- }- async fetchBinary(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch binary: ${url} (${response.status})`);- }- return response.arrayBuffer();- }- // =========================================================================- // Private - Virtual FS- // =========================================================================- writeToVirtualFS(virtualPath, data) {- if (this.virtualFSPaths_.has(virtualPath)) {- return true;- }- const fs = this.module_.FS;- if (!fs) {- return false;- }- try {- this.ensureVirtualDir(virtualPath);- fs.writeFile(virtualPath, data);- this.virtualFSPaths_.add(virtualPath);- return true;- }- catch (e) {- console.error(`[AssetServer] Failed to write to virtual FS: ${virtualPath}`, e);- return false;- }- }- ensureVirtualDir(virtualPath) {- const fs = this.module_.FS;- if (!fs)- return;- const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));- if (!dir)- return;- const parts = dir.split('/').filter(p => p);- let currentPath = '';- for (const part of parts) {- currentPath = currentPath ? `${currentPath}/${part}` : part;- try {- const analysis = fs.analyzePath(currentPath);- if (!analysis.exists) {- fs.mkdir(currentPath);- }- }- catch {- try {- fs.mkdir(currentPath);- }- catch {- // Directory might already exist- }- }- }- }- // =========================================================================- // Private - Utilities- // =========================================================================- resolveUrl(path, baseUrl) {- if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {- return path;- }- const base = baseUrl ?? this.baseUrl;- return base ? `${base}/${path}` : `/${path}`;- }- createCanvas(width, height) {- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(width, height)- : document.createElement('canvas');- canvas.width = width;- canvas.height = height;- return canvas;- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- parseAtlasTextures(atlasContent) {- const textures = [];- for (const line of atlasContent.split('\n')) {- const trimmed = line.trim();- if (trimmed && !trimmed.includes(':') &&- (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {- textures.push(trimmed);- }- }- return textures;- }-}--/**- * @file AssetPlugin.ts- * @brief Plugin that provides asset loading capabilities- */-const Assets = defineResource(null, 'Assets');-// =============================================================================-// Asset Plugin-// =============================================================================-class AssetPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('AssetPlugin: No WASM module available');- return;- }- app.insertResource(Assets, new AssetServer(module));- }-}-const assetPlugin = new AssetPlugin();--/**- * @file PreviewPlugin.ts- * @brief Plugin for editor preview functionality- */-// =============================================================================-// PreviewPlugin-// =============================================================================-class PreviewPlugin {- constructor(sceneUrl) {- this.app_ = null;- this.loadPromise_ = null;- this.sceneUrl_ = sceneUrl;- }- build(app) {- this.app_ = app;- if (!app.hasResource(Assets)) {- app.addPlugin(assetPlugin);- }- this.loadPromise_ = this.loadScene();- }- /**- * @brief Wait for scene loading to complete- */- async waitForReady() {- if (this.loadPromise_) {- await this.loadPromise_;- }- }- async loadScene() {- 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();- const assets = this.app_.getResource(Assets);- await assets.loadScene(this.app_.world, sceneData);- this.ensureCamera();- }- catch (err) {- console.error('[PreviewPlugin] Failed to load scene:', err);- }- }- ensureCamera() {- if (!this.app_)- return;- const world = this.app_.world;- let hasActiveCamera = false;- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera.isActive) {- hasActiveCamera = true;- break;- }- }- if (!hasActiveCamera) {- console.warn('[PreviewPlugin] No active camera found, creating default camera');- const cameraEntity = world.spawn();- const transformData = {- position: { x: 0, y: 0, z: 10 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- };- world.insert(cameraEntity, LocalTransform, transformData);- const cameraData = {- isActive: true,- projectionType: 0,- fov: 60,- orthoSize: 540,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- priority: 0,- };- world.insert(cameraEntity, Camera, cameraData);- }- }-}--/**- * @file spine.ts- * @brief Spine animation control API- */-// =============================================================================-// SpineController-// =============================================================================-/**- * Controller for Spine skeletal animations- *- * @example- * ```typescript- * const spine = new SpineController(wasmModule);- *- * // Play animation- * spine.play(entity, 'run', true);- *- * // Queue next animation- * spine.addAnimation(entity, 'idle', true, 0.2);- *- * // Change skin- * spine.setSkin(entity, 'warrior');- *- * // Get bone position for effects- * const pos = spine.getBonePosition(entity, 'weapon');- * if (pos) {- * spawnEffect(pos.x, pos.y);- * }- *- * // Listen for events- * spine.on(entity, 'event', (e) => {- * if (e.eventName === 'footstep') {- * playSound('footstep');- * }- * });- * ```- */-class SpineController {- constructor(wasmModule) {- this.module_ = wasmModule;- this.listeners_ = new Map();- this.setupEventBridge();- }- // =========================================================================- // Animation Control- // =========================================================================- /**- * Plays an animation, replacing any current animation on the track- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop the animation- * @param track Animation track (default 0)- * @returns True if animation was set- */- play(entity, animation, loop = true, track = 0) {- if (!this.module_.spinePlayAnimation)- return false;- return this.module_.spinePlayAnimation(entity, animation, loop, track);- }- /**- * Adds an animation to the queue- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop- * @param delay Delay before starting (seconds)- * @param track Animation track (default 0)- * @returns True if animation was queued- */- addAnimation(entity, animation, loop = true, delay = 0, track = 0) {- if (!this.module_.spineAddAnimation)- return false;- return this.module_.spineAddAnimation(entity, animation, loop, delay, track);- }- /**- * Sets an empty animation to mix out the current animation- * @param entity Target entity- * @param mixDuration Duration of the mix out- * @param track Animation track (default 0)- */- setEmptyAnimation(entity, mixDuration = 0.2, track = 0) {- if (!this.module_.spineSetEmptyAnimation)- return;- this.module_.spineSetEmptyAnimation(entity, mixDuration, track);- }- /**- * Clears all animations on a track- * @param entity Target entity- * @param track Animation track (default 0)- */- clearTrack(entity, track = 0) {- if (!this.module_.spineClearTrack)- return;- this.module_.spineClearTrack(entity, track);- }- /**- * Clears all tracks- * @param entity Target entity- */- clearTracks(entity) {- if (!this.module_.spineClearTracks)- return;- this.module_.spineClearTracks(entity);- }- // =========================================================================- // Skin Control- // =========================================================================- /**- * Sets the current skin- * @param entity Target entity- * @param skinName Skin name- * @returns True if skin was set- */- setSkin(entity, skinName) {- if (!this.module_.spineSetSkin)- return false;- return this.module_.spineSetSkin(entity, skinName);- }- /**- * Gets available skin names- * @param entity Target entity- * @returns Array of skin names- */- getSkins(entity) {- if (!this.module_.spineGetSkins)- return [];- return this.module_.spineGetSkins(entity) || [];- }- // =========================================================================- // Queries- // =========================================================================- /**- * Gets available animation names- * @param entity Target entity- * @returns Array of animation names- */- getAnimations(entity) {- if (!this.module_.spineGetAnimations)- return [];- return this.module_.spineGetAnimations(entity) || [];- }- /**- * Gets the current animation on a track- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Animation name or null- */- getCurrentAnimation(entity, track = 0) {- if (!this.module_.spineGetCurrentAnimation)- return null;- return this.module_.spineGetCurrentAnimation(entity, track);- }- /**- * Gets the duration of an animation- * @param entity Target entity- * @param animation Animation name- * @returns Duration in seconds, or 0 if not found- */- getAnimationDuration(entity, animation) {- if (!this.module_.spineGetAnimationDuration)- return 0;- return this.module_.spineGetAnimationDuration(entity, animation);- }- /**- * Gets detailed track entry info- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Track entry info or null- */- getTrackEntry(entity, track = 0) {- if (!this.module_.spineGetTrackEntry)- return null;- return this.module_.spineGetTrackEntry(entity, track);- }- // =========================================================================- // Bone/Slot Access- // =========================================================================- /**- * Gets world position of a bone- * @param entity Target entity- * @param boneName Bone name- * @returns Position or null if not found- */- getBonePosition(entity, boneName) {- if (!this.module_.spineGetBonePosition)- return null;- const result = this.module_.spineGetBonePosition(entity, boneName);- if (!result)- return null;- return { x: result.x, y: result.y };- }- /**- * Gets world rotation of a bone in degrees- * @param entity Target entity- * @param boneName Bone name- * @returns Rotation in degrees or null- */- getBoneRotation(entity, boneName) {- if (!this.module_.spineGetBoneRotation)- return null;- return this.module_.spineGetBoneRotation(entity, boneName);- }- /**- * Sets the attachment for a slot- * @param entity Target entity- * @param slotName Slot name- * @param attachmentName Attachment name (null to clear)- */- setAttachment(entity, slotName, attachmentName) {- if (!this.module_.spineSetAttachment)- return;- this.module_.spineSetAttachment(entity, slotName, attachmentName || '');- }- // =========================================================================- // Events- // =========================================================================- /**- * Registers an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- on(entity, type, callback) {- if (!this.listeners_.has(entity)) {- this.listeners_.set(entity, new Map());- }- const entityListeners = this.listeners_.get(entity);- if (!entityListeners.has(type)) {- entityListeners.set(type, new Set());- }- entityListeners.get(type).add(callback);- }- /**- * Unregisters an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- off(entity, type, callback) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const typeListeners = entityListeners.get(type);- if (!typeListeners)- return;- typeListeners.delete(callback);- }- /**- * Removes all event listeners for an entity- * @param entity Target entity- */- removeAllListeners(entity) {- this.listeners_.delete(entity);- }- // =========================================================================- // Private- // =========================================================================- setupEventBridge() {- if (typeof window !== 'undefined') {- window.__esengine_spineEvent = (entity, eventData) => {- this.dispatchEvent(entity, eventData);- };- }- }- dispatchEvent(entity, eventData) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const event = {- type: eventData.type,- entity,- track: eventData.track ?? 0,- animation: eventData.animation ?? null,- eventName: eventData.eventName,- intValue: eventData.intValue,- floatValue: eventData.floatValue,- stringValue: eventData.stringValue,- };- const typeListeners = entityListeners.get(event.type);- if (typeListeners) {- typeListeners.forEach(callback => {- try {- callback(event);- }- catch (e) {- console.error('Error in Spine event callback:', e);- }- });- }- }-}-// =============================================================================-// Factory Function-// =============================================================================-/**- * Creates a SpineController instance- * @param wasmModule The ESEngine WASM module- * @returns SpineController instance- */-function createSpineController(wasmModule) {- return new SpineController(wasmModule);-}--const RenderTexture = {- create(options) {- const depth = options.depth ?? true;- const linear = options.filter === 'linear';- const flags = (depth ? 1 : 0) | (linear ? 2 : 0);- const handle = Renderer.createRenderTarget(options.width, options.height, flags);- const textureId = Renderer.getTargetTexture(handle);- return {- _handle: handle,- textureId,- width: options.width,- height: options.height,- };- },- release(rt) {- Renderer.releaseRenderTarget(rt._handle);- },- resize(rt, width, height) {- Renderer.releaseRenderTarget(rt._handle);- return RenderTexture.create({ width, height, depth: true });- },- begin(rt, viewProjection) {- Renderer.begin(viewProjection, rt._handle);- },- end() {- Renderer.end();- },- getDepthTexture(rt) {- return Renderer.getTargetDepthTexture(rt._handle);- },-};--let editorMode = false;-function setEditorMode(active) {- editorMode = active;-}-function isEditor() {- return editorMode;-}-function isRuntime() {- return !editorMode;-}--/**- * @file index.ts- * @brief ESEngine SDK - Web entry point (auto-initializes Web platform)- */-// Initialize Web platform-setPlatform(webAdapter);--export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}const h=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.module}}},d=0,f=4294967295,_=(e=0,t=0)=>({x:e,y:t}),p=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),m=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),g=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),y=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});let w=0;function x(e,t){const n=++w;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function v(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function S(e,t){const n=v(),r=n.get(e);if(r)return r;const s=x(e,t);return n.set(e,s),b(e,t,!1),s}function C(e){const t=v(),n=t.get(e);if(n)return n;const r=x(e,{});return t.set(e,r),b(e,{},!0),r}function T(e){return v().get(e)}function P(){v().clear()}function b(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function E(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const M=E("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),R=E("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=E("Sprite",{texture:f,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),U=E("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0}),z=E("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:0,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),$=E("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),I=E("Parent",{entity:0}),k=E("Children",{entities:[]}),B=E("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),L={LocalTransform:M,WorldTransform:R,Sprite:F,Camera:U,Canvas:z,Velocity:$,Parent:I,Children:k,SpineAnimation:B};function W(e){const t=L[e];if(t)return{...t._default};const n=T(e);return n?{...n._default}:null}let D=0;function O(e,t){const n=++D;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function H(e){return{_type:"res",_resource:e}}function G(e){return{_type:"res_mut",_resource:e}}class N{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 V{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new N(this.get(e),t=>this.set(e,t))}}const j=O({delta:0,elapsed:0,frameCount:0},"Time"),X=O({keysDown:new Set,keysPressed:new Set,keysReleased:new Set,mouseX:0,mouseY:0,mouseButtons:new Set},"Input");function q(e){return{_type:"mut",_component:e}}function K(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function J(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{K(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class Y{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return K(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}function Q(){return{_type:"commands"}}class Z{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=A(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ee{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new Z(this,null)}entity(e){return new Z(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var te;!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"}(te||(te={}));let ne=0;function re(e,t,n){const r=++ne;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function se(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ie(e){se().push({schedule:te.Update,system:e})}function oe(e){se().push({schedule:te.Startup,system:e})}function ae(e,t){se().push({schedule:e,system:t})}class ce{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof ee&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Y(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ee(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class le{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return A(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,r)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var ue,he,de;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ue||(ue={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(he||(he={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(de||(de={}));const fe=S("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:ue.Left,verticalAlign:he.Top,wordWrap:!0,overflow:de.Visible,lineHeight:1.2,dirty:!0});class _e{constructor(e){this.cache=new Map,this.module=e,"undefined"!=typeof OffscreenCanvas?(this.canvas=new OffscreenCanvas(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})):(this.canvas=document.createElement("canvas"),this.canvas.width=512,this.canvas.height=512,this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}))}renderText(e,t){const n=this.ctx,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,_=s?Math.ceil(o):d+2*u;if(s&&e.overflow===de.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<_){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(_));r.width=e,r.height=t}const p=Math.round(255*e.color.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${p}, ${m}, ${g}, ${y})`,s&&e.overflow===de.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,_),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case he.Top:x=u;break;case he.Middle:x=(_-w)/2;break;case he.Bottom:x=_-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case ue.Left:r=u;break;case ue.Center:r=f/2;break;case ue.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===de.Clip&&n.restore();const S=n.getImageData(0,0,f,_),C=new Uint8Array(S.data.buffer),T=this.flipVertically(C,f,_),P=this.module.getResourceManager(),b=this.module._malloc(T.length);this.module.HEAPU8.set(T,b);const E=P.createTexture(f,_,b,T.length,1);return this.module._free(b),{textureHandle:E,width:f,height:_}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case ue.Left:return"left";case ue.Center:return"center";case ue.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const i=t*r,o=(n-1-t)*r;s.set(e.subarray(i,i+r),o)}return s}}const pe=S("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class me{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new _e(t),r=e.world;e.addSystemToSchedule(te.PreUpdate,re([],()=>{const e=r.getEntitiesWithComponents([fe]);for(const t of e){const e=r.get(t,fe);if(!e.dirty)continue;r.has(t,F)||r.insert(t,F,{texture:f,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,pe)?r.get(t,pe):null,i=n.renderForEntity(t,e,s),o=r.get(t,F);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,F,o),e.dirty=!1}}))}}const ge=new me;var ye;function we(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"}(ye||(ye={}));let xe=null,ve=null,Se=1;const Ce=new Map;function Te(e){xe=e,ve=e.getResourceManager(),Ue()}function Pe(){0!==Me&&xe&&(xe._free(Me),Me=0),Ce.clear(),Se=1,Ae=!1,ve=null,xe=null}function be(){if(!ve)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ve}const Ee={createShader:(e,t)=>be().createShader(e,t),releaseShader(e){e>0&&be().releaseShader(e)},create(e){const t=Se++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ye.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Ce.set(t,n),t},get:e=>Ce.get(e),setUniform(e,t,n){const r=Ce.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Ce.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ce.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ce.get(e);return t?.blendMode??ye.Normal},setDepthTest(e,t){const n=Ce.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ce.get(e);return t?.shader??0},release(e){Ce.delete(e)},isValid:e=>Ce.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??ye.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ce.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Se++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ce.set(n,r),n},toAssetData(e,t){const n=Ce.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=Ce.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ae=!1,Me=0;const Re=4096;function Fe(e){const t=(0===Me&&xe&&(Me=xe._malloc(Re)),Me);if(0===t||!xe)return{ptr:0,count:0};let n=0,r=0;const s=xe.HEAPU8,i=xe.HEAPU32,o=xe.HEAPF32;for(const[a,c]of e){if(n+128>Re)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function Ue(){if(!xe||Ae)return;xe.materialDataProvider=(e,t,n,r,s)=>{const i=Ce.get(e);if(!i)return xe.HEAPU32[t>>2]=0,xe.HEAPU32[n>>2]=0,xe.HEAPU32[r>>2]=0,void(xe.HEAPU32[s>>2]=0);xe.HEAPU32[t>>2]=i.shader,xe.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Fe(i.uniforms);xe.HEAPU32[r>>2]=o,xe.HEAPU32[s>>2]=a},Ae=!0}const ze={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};let $e=null,Ie=0,ke=0,Be=0;const Le=new Float32Array(256);function We(e){$e=e,Ie=$e._malloc(64),ke=$e._malloc(64),Be=$e._malloc(1024)}function De(){$e&&(Ie&&($e._free(Ie),Ie=0),ke&&($e._free(ke),ke=0),Be&&($e._free(Be),Be=0)),$e=null}function Oe(){if(!$e)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return $e}const He={x:1,y:1,z:1,w:1},Ge={begin(e){const t=Oe();t.HEAPF32.set(e,Ie/4),t.draw_begin(Ie)},end(){Oe().draw_end()},line(e,t,n,r=1){Oe().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rect(e,t,n,r=!0){Oe().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rectOutline(e,t,n,r=1){Oe().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},circle(e,t,n,r=!0,s=32){Oe().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},circleOutline(e,t,n,r=1,s=32){Oe().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=He){Oe().draw_texture(e.x,e.y,t.x,t.y,n,r.x,r.y,r.z,r.w)},textureRotated(e,t,n,r,s=He){Oe().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){Oe().draw_setLayer(e)},setDepth(e){Oe().draw_setDepth(e)},getDrawCallCount:()=>$e?$e.draw_getDrawCallCount():0,getPrimitiveCount:()=>$e?$e.draw_getPrimitiveCount():0,setBlendMode(e){Oe().draw_setBlendMode(e)},setDepthTest(e){Oe().draw_setDepthTest(e)},drawMesh(e,t,n){const r=Oe();r.HEAPF32.set(n,ke/4),r.draw_mesh(e,t,ke)},drawMeshWithMaterial(e,t,n){const r=Oe(),s=Ee.get(t);if(!s)return;if(Ge.setBlendMode(s.blendMode),Ge.setDepthTest(s.depthTest),0===s.uniforms.size)return void Ge.drawMesh(e,s.shader,n);r.HEAPF32.set(n,ke/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Ve(e);if(!(n<0)){if(we(t))Le[i++]=10,Le[i++]=n,Le[i++]=t.slot??o++,Le[i++]=t.textureId;else if("number"==typeof t)Le[i++]=1,Le[i++]=n,Le[i++]=t;else if(Array.isArray(t)){Le[i++]=t.length,Le[i++]=n;for(let e=0;e<t.length;e++)Le[i++]=t[e]}else"w"in t?(Le[i++]=4,Le[i++]=n,Le[i++]=t.x,Le[i++]=t.y,Le[i++]=t.z,Le[i++]=t.w):"z"in t?(Le[i++]=3,Le[i++]=n,Le[i++]=t.x,Le[i++]=t.y,Le[i++]=t.z):(Le[i++]=2,Le[i++]=n,Le[i++]=t.x,Le[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(Le.subarray(0,i),Be/4),r.draw_meshWithUniforms(e,s.shader,ke,Be,i)):r.draw_mesh(e,s.shader,ke)}},Ne={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 Ve(e){return Ne[e]??-1}var je;!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"}(je||(je={}));let Xe=null,qe=0,Ke=0,Je=0;function Ye(e){Xe=e,qe=Xe._malloc(262144),Ke=Xe._malloc(65536),Je=Xe._malloc(256)}function Qe(){Xe&&(qe&&Xe._free(qe),Ke&&Xe._free(Ke),Je&&Xe._free(Je),qe=0,Ke=0,Je=0),Xe=null}function Ze(){if(!Xe)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Xe}const et={create(e){const t=Ze(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,qe/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Je,s).set(i),t.geometry_init(n,qe,r,Je,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ke,r).set(e.indices),t.geometry_setIndices16(n,Ke,r)}else{new Uint32Array(t.HEAPU8.buffer,Ke,r).set(e.indices),t.geometry_setIndices32(n,Ke,r)}}return n},updateVertices(e,t,n=0){const r=Ze(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,qe/4),r.geometry_updateVertices(e,qe,s,n)},release(e){e>0&&Ze().geometry_release(e)},isValid:e=>!(!Xe||e<=0)&&Xe.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return et.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:je.Float2},{name:"a_texCoord",type:je.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return et.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:je.Float2},{name:"a_texCoord",type:je.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return et.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:je.Float2},{name:"a_texCoord",type:je.Float2}],indices:new Uint16Array(o)})}};let tt=null;function nt(e){tt=e}function rt(){tt&&it.isInitialized()&&it.shutdown(),tt=null}function st(){if(!tt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return tt}const it={init:(e,t)=>st().postprocess_init(e,t),shutdown(){st().postprocess_shutdown()},resize(e,t){st().postprocess_resize(e,t)},addPass:(e,t)=>st().postprocess_addPass(e,t),removePass(e){st().postprocess_removePass(e)},setEnabled(e,t){st().postprocess_setPassEnabled(e,t)},isEnabled:e=>st().postprocess_isPassEnabled(e),setUniform(e,t,n){st().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){st().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){st().postprocess_begin()},end(){st().postprocess_end()},getPassCount:()=>st().postprocess_getPassCount(),isInitialized:()=>!!tt&&tt.postprocess_isInitialized(),setBypass(e){st().postprocess_setBypass(e)},isBypassed:()=>!tt||tt.postprocess_isBypassed(),createBlur:()=>Ee.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:()=>Ee.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:()=>Ee.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:()=>Ee.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 at;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(at||(at={}));let ct=null,lt=0;function ut(e){ct=e,lt=ct._malloc(64)}function ht(){ct&<&&(ct._free(lt),lt=0),ct=null}const dt={init(e,t){ct?.renderer_init(e,t)},resize(e,t){ct?.renderer_resize(e,t)},begin(e,t){ct&<&&(ct.HEAPF32.set(e,lt/4),ct.renderer_begin(lt,t??0))},end(){ct?.renderer_end()},submitSprites(e){ct&&ct.renderer_submitSprites(e._cpp)},submitSpine(e){ct&&ct.renderer_submitSpine(e._cpp)},setStage(e){ct?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ct?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ct?.renderer_releaseTarget(e)},getTargetTexture:e=>ct?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ct?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){ct?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>ct?{drawCalls:ct.renderer_getDrawCalls(),triangles:ct.renderer_getTriangles(),sprites:ct.renderer_getSprites(),spine:ct.renderer_getSpine(),meshes:ct.renderer_getMeshes(),culled:ct.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}},ft=new Map;function _t(e,t){ft.set(e,t)}function pt(e){ft.delete(e)}function mt(){ft.clear()}class gt{render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;dt.resize(r,s);const o=it.isInitialized()&&it.getPassCount()>0&&!it.isBypassed();o&&(it.resize(r,s),it.begin()),dt.begin(n),dt.submitSprites(t),dt.submitSpine(t),dt.end();const a=ft;if(a.size>0){Ge.begin(n);const e=[];for(const[t,n]of a.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Ge.end();for(const t of e)pt(t)}o&&it.end()}}class yt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.module_=null,this.mainLoop=()=>{if(!this.running_)return;const e=performance.now(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;this.updateTime(n),this.runSchedule(te.First),this.runSchedule(te.PreUpdate),this.runSchedule(te.Update),this.runSchedule(te.PostUpdate),this.runSchedule(te.Last),requestAnimationFrame(this.mainLoop)},this.world_=new le,this.resources_=new V;for(const e of Object.values(te))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new yt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(te.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(te.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get world(){return this.world_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ce(this.world_,this.resources_),this.resources_.insert(j,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(te.Startup),this.lastTime_=performance.now(),this.mainLoop())}quit(){this.running_=!1,ht(),rt(),Qe(),Pe(),De()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(j),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(j,n)}}function wt(e,t){const n=yt.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),We(e),Te(e),Ye(e),nt(e),ut(e);const s=new gt;let i=performance.now();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=o(),n=function(e,t,n){const r=e.entityCount()+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const r=e.getCamera(s);if(!r.isActive)continue;const i=e.getLocalTransform(s),o=t/n;let a;if(1===r.projectionType){const e=r.orthoSize,t=e*o;a=St(-t,t,-e,e,-r.farPlane,r.farPlane)}else a=Ct(r.fov*Math.PI/180,o,r.nearPlane,r.farPlane);return Pt(a,Tt(i.position.x,i.position.y,i.position.z))}return vt}(r,e,t),a=(performance.now()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:n,width:e,height:t,elapsed:a})}};return n.addSystemToSchedule(te.Last,a),n.addPlugin(ge),n}function xt(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const vt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function St(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function Ct(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function Tt(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function Pt(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}class bt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ee.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ee.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:Ee.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Et(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)Mt(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function At(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t);for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Mt(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Mt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,M,r);break;case"Sprite":e.insert(t,F,r);break;case"Camera":e.insert(t,U,r);break;case"Canvas":e.insert(t,z,r);break;case"Text":e.insert(t,fe,r);break;case"SpineAnimation":e.insert(t,B,r);break;case"UIRect":e.insert(t,pe,r);break;default:{const s=T(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Rt(e,t){const n=e.getEntitiesWithComponents([U]);for(const r of n){const n=e.get(r,U);n&&(n.aspectRatio=t,e.insert(r,U,n))}}class Ft{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Ut{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.module_=e,this.canvas_=this.createCanvas(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new bt(t)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await fetch(s);if(!i.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const o=await i.text();if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(o);for(const e of c){const t=a?`${a}/${e}`:e,r=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return At(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const r=255/n;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ee.createShader(n,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}async fetchJson(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await o(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}createCanvas(e,t){const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas");return n.width=e,n.height=t,n}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=O(null,"Assets");class $t{build(e){const t=e.wasmModule;t?e.insertResource(zt,new Ut(t)):console.warn("AssetPlugin: No WASM module available")}}const It=new $t;class kt{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(zt)||e.addPlugin(It),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=this.app_.getResource(zt);await n.loadScene(this.app_.world,t),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([U]);for(const r of n){if(e.get(r,U).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");const t=e.spawn(),n={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(t,M,n);const r={isActive:!0,projectionType:0,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,priority:0};e.insert(t,U,r)}}}class Bt{constructor(e){this.module_=e,this.listeners_=new Map,this.setupEventBridge()}play(e,t,n=!0,r=0){return!!this.module_.spinePlayAnimation&&this.module_.spinePlayAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,s=0){return!!this.module_.spineAddAnimation&&this.module_.spineAddAnimation(e,t,n,r,s)}setEmptyAnimation(e,t=.2,n=0){this.module_.spineSetEmptyAnimation&&this.module_.spineSetEmptyAnimation(e,t,n)}clearTrack(e,t=0){this.module_.spineClearTrack&&this.module_.spineClearTrack(e,t)}clearTracks(e){this.module_.spineClearTracks&&this.module_.spineClearTracks(e)}setSkin(e,t){return!!this.module_.spineSetSkin&&this.module_.spineSetSkin(e,t)}getSkins(e){return this.module_.spineGetSkins&&this.module_.spineGetSkins(e)||[]}getAnimations(e){return this.module_.spineGetAnimations&&this.module_.spineGetAnimations(e)||[]}getCurrentAnimation(e,t=0){return this.module_.spineGetCurrentAnimation?this.module_.spineGetCurrentAnimation(e,t):null}getAnimationDuration(e,t){return this.module_.spineGetAnimationDuration?this.module_.spineGetAnimationDuration(e,t):0}getTrackEntry(e,t=0){return this.module_.spineGetTrackEntry?this.module_.spineGetTrackEntry(e,t):null}getBonePosition(e,t){if(!this.module_.spineGetBonePosition)return null;const n=this.module_.spineGetBonePosition(e,t);return n?{x:n.x,y:n.y}:null}getBoneRotation(e,t){return this.module_.spineGetBoneRotation?this.module_.spineGetBoneRotation(e,t):null}setAttachment(e,t,n){this.module_.spineSetAttachment&&this.module_.spineSetAttachment(e,t,n||"")}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const s=r.get(t);s&&s.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}setupEventBridge(){"undefined"!=typeof window&&(window.__esengine_spineEvent=(e,t)=>{this.dispatchEvent(e,t)})}dispatchEvent(e,t){const n=this.listeners_.get(e);if(!n)return;const r={type:t.type,entity:e,track:t.track??0,animation:t.animation??null,eventName:t.eventName,intValue:t.intValue,floatValue:t.floatValue,stringValue:t.stringValue},s=n.get(r.type);s&&s.forEach(e=>{try{e(r)}catch(e){console.error("Error in Spine event callback:",e)}})}}function Lt(e){return new Bt(e)}const Wt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=dt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:dt.getTargetTexture(n),width:e.width,height:e.height}},release(e){dt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(dt.releaseRenderTarget(e._handle),Wt.create({width:t,height:n,depth:!0})),begin(e,t){dt.begin(t,e._handle)},end(){dt.end()},getDepthTexture:e=>dt.getTargetDepthTexture(e._handle)};let Dt=!1;function Ot(e){Dt=e}function Ht(){return Dt}function Gt(){return!Dt}var Nt;e=Nt=h,console.log(`[ESEngine] Platform: ${Nt.name}`);export{yt as App,$t as AssetPlugin,Ut as AssetServer,zt as Assets,Ft as AsyncCache,ye as BlendMode,U as Camera,z as Canvas,k as Children,Q as Commands,ee as CommandsInstance,je as DataType,Ge as Draw,Z as EntityCommands,et as Geometry,d as INVALID_ENTITY,f as INVALID_TEXTURE,X as Input,M as LocalTransform,Ee as Material,bt as MaterialLoader,q as Mut,I as Parent,it as PostProcess,kt as PreviewPlugin,J as Query,Y as QueryInstance,gt as RenderPipeline,at as RenderStage,Wt as RenderTexture,dt as Renderer,H as Res,G as ResMut,te as Schedule,ze as ShaderSources,B as SpineAnimation,Bt as SpineController,F as Sprite,ce as SystemRunner,fe as Text,ue as TextAlign,de as TextOverflow,me as TextPlugin,_e as TextRenderer,he as TextVerticalAlign,j as Time,pe as UIRect,$ as Velocity,le as World,R as WorldTransform,oe as addStartupSystem,ie as addSystem,ae as addSystemToSchedule,It as assetPlugin,mt as clearDrawCallbacks,P as clearUserComponents,g as color,Lt as createSpineController,wt as createWebApp,S as defineComponent,O as defineResource,re as defineSystem,C as defineTag,xt as flushPendingSystems,W as getComponentDefaults,t as getPlatform,r as getPlatformType,T as getUserComponent,We as initDrawAPI,Ye as initGeometryAPI,Te as initMaterialAPI,nt as initPostProcessAPI,ut as initRendererAPI,A as isBuiltinComponent,Ht as isEditor,n as isPlatformInitialized,Gt as isRuntime,we as isTextureRef,s as isWeChat,i as isWeb,Mt as loadComponent,Et as loadSceneData,At as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,y as quat,_t as registerDrawCallback,Ue as registerMaterialCallback,Ot as setEditorMode,De as shutdownDrawAPI,Qe as shutdownGeometryAPI,Pe as shutdownMaterialAPI,rt as shutdownPostProcessAPI,ht as shutdownRendererAPI,ge as textPlugin,pt as unregisterDrawCallback,Rt as updateCameraAspectRatio,_ as vec2,p as vec3,m as vec4};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.tsindex 97ea39a0f..edb6a99f6 100644--- a/desktop/public/sdk/esm/wasm.d.ts+++ b/desktop/public/sdk/esm/wasm.d.ts@@ -56,6 +56,7 @@ interface CppRegistry {interface CppResourceManager {createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number): number;createShader(vertSrc: string, fragSrc: string): number;+ registerExternalTexture(glTextureId: number, width: number, height: number): number;releaseTexture(handle: number): void;releaseShader(handle: number): void;setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;