Skip to content

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

feat: Add TypeScript ECS framework and scene serialization

esenginefd4cf421b628
diff --git a/assets/templates/.gitignore b/assets/templates/.gitignore
new file mode 100644
index 000000000..ac9813a3a
--- /dev/null
+++ b/assets/templates/.gitignore
@@ -0,0 +1,19 @@
+# Dependencies
+node_modules/
+
+# Build output
+build/
+dist/
+
+# Editor cache
+.esengine/
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
diff --git a/assets/templates/package.json b/assets/templates/package.json
new file mode 100644
index 000000000..df3d4d2da
--- /dev/null
+++ b/assets/templates/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "{{PROJECT_NAME}}",
+ "version": "1.0.0",
+ "type": "module",
+ "scripts": {
+ "build": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/js/main.js --sourcemap",
+ "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/js/main.js --sourcemap --watch",
+ "typecheck": "npx tsc --noEmit"
+ },
+ "dependencies": {
+ "esengine": "file:{{SDK_PATH}}"
+ },
+ "devDependencies": {
+ "esbuild": "^0.20.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/assets/templates/src/components/index.ts b/assets/templates/src/components/index.ts
new file mode 100644
index 000000000..fbc2c1fe8
--- /dev/null
+++ b/assets/templates/src/components/index.ts
@@ -0,0 +1,5 @@
+import { Velocity } from './movement';
+
+export const components = {
+ Velocity,
+};
diff --git a/assets/templates/src/components/movement.ts b/assets/templates/src/components/movement.ts
new file mode 100644
index 000000000..b37629f85
--- /dev/null
+++ b/assets/templates/src/components/movement.ts
@@ -0,0 +1,6 @@
+import { defineComponent, Type } from 'esengine';
+
+export const Velocity = defineComponent({
+ x: Type.f32,
+ y: Type.f32
+}, { x: 0, y: 0 }, 'Velocity');
diff --git a/assets/templates/src/main.ts b/assets/templates/src/main.ts
new file mode 100644
index 000000000..b22e60a40
--- /dev/null
+++ b/assets/templates/src/main.ts
@@ -0,0 +1,27 @@
+import { App } from 'esengine';
+import { components } from './components';
+import { systems } from './systems';
+
+export async function main(Module: any): Promise<void> {
+ const app = App.new();
+
+ const cppRegistry = new Module.Registry();
+ app.connectCpp(cppRegistry, Module.HEAPU8.buffer);
+
+ for (const comp of Object.values(components)) {
+ app.registerComponent(comp);
+ }
+
+ for (const sys of systems) {
+ app.addSystem(sys);
+ }
+
+ const result = await app.loadSceneAsync('assets/scenes/main.esscene');
+ if (result.success) {
+ console.log(`Loaded scene: ${result.sceneName} (${result.entityCount} entities)`);
+ } else {
+ console.error(`Failed to load scene: ${result.error}`);
+ }
+
+ app.run();
+}
diff --git a/assets/templates/src/systems/index.ts b/assets/templates/src/systems/index.ts
new file mode 100644
index 000000000..b025f53db
--- /dev/null
+++ b/assets/templates/src/systems/index.ts
@@ -0,0 +1,5 @@
+import { movementSystem } from './movement';
+
+export const systems = [
+ movementSystem,
+];
diff --git a/assets/templates/src/systems/movement.ts b/assets/templates/src/systems/movement.ts
new file mode 100644
index 000000000..4d7efba8a
--- /dev/null
+++ b/assets/templates/src/systems/movement.ts
@@ -0,0 +1,12 @@
+import { defineSystem, Query, Res, Time, LocalTransform } from 'esengine';
+import { Velocity } from '../components/movement';
+
+export const movementSystem = defineSystem(
+ [Query(LocalTransform, Velocity), Res(Time)],
+ (query, time) => {
+ for (const [entity, transform, vel] of query) {
+ transform.position.x += vel.x * time.delta;
+ transform.position.y += vel.y * time.delta;
+ }
+ }
+);
diff --git a/bindings/tsconfig.json b/assets/templates/tsconfig.json
similarity index 67%
rename from bindings/tsconfig.json
rename to assets/templates/tsconfig.json
index 5ad6b3ace..84d188ba9 100644
--- a/bindings/tsconfig.json
+++ b/assets/templates/tsconfig.json
@@ -5,13 +5,11 @@
"lib": ["ES2020", "DOM"],
"moduleResolution": "node",
"strict": true,
- "noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
- "declaration": true,
- "declarationMap": true
+ "noEmit": true
},
- "include": ["*.ts"],
- "exclude": ["node_modules"]
+ "include": ["src/**/*.ts"],
+ "exclude": ["node_modules", "build"]
}
diff --git a/assets/templates/web/index.html b/assets/templates/web/index.html
new file mode 100644
index 000000000..636164a6e
--- /dev/null
+++ b/assets/templates/web/index.html
@@ -0,0 +1,83 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
+ <title>{{PROJECT_NAME}}</title>
+ <style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ html, body {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background-color: #1a1a1a;
+ }
+ #canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ touch-action: none;
+ }
+ #loading {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ color: #fff;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ font-size: 16px;
+ text-align: center;
+ }
+ #loading.hidden { display: none; }
+ .spinner {
+ width: 40px;
+ height: 40px;
+ margin: 0 auto 16px;
+ border: 3px solid #333;
+ border-top-color: #3b82f6;
+ border-radius: 50%;
+ animation: spin 1s linear infinite;
+ }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ </style>
+</head>
+<body>
+ <div id="loading">
+ <div class="spinner"></div>
+ <div>Loading...</div>
+ </div>
+ <canvas id="canvas"></canvas>
+
+ <script type="module">
+ const v = Date.now();
+ const { default: ESEngineModule } = await import(`./esengine.js?v=${v}`);
+ const { main } = await import(`./scripts/main.js?v=${v}`);
+
+ function resizeCanvas() {
+ const canvas = document.getElementById('canvas');
+ const dpr = window.devicePixelRatio || 1;
+ canvas.width = window.innerWidth * dpr;
+ canvas.height = window.innerHeight * dpr;
+ }
+ window.addEventListener('resize', resizeCanvas);
+ resizeCanvas();
+
+ ESEngineModule({
+ canvas: document.getElementById('canvas'),
+ print: (text) => console.log(text),
+ printErr: (text) => console.error(text)
+ }).then(async (Module) => {
+ console.log('ESEngine loaded');
+ document.getElementById('loading').classList.add('hidden');
+ await main(Module);
+ }).catch((err) => {
+ if (err === 'unwind' || (err.message && err.message.includes('unwind'))) {
+ console.log('App running');
+ return;
+ }
+ console.error('Failed:', err);
+ document.getElementById('loading').innerHTML = '<div style="color:#f87171">Error: ' + err.message + '</div>';
+ });
+ </script>
+</body>
+</html>
diff --git a/bindings/App.ts b/bindings/App.ts
deleted file mode 100644
index e0589f6e1..000000000
--- a/bindings/App.ts
+++ /dev/null
@@ -1,511 +0,0 @@
-/**
- * @file App.ts
- * @brief Type-safe ECS Application wrapper for TypeScript
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-import type {
- ESEngineModule,
- Registry,
- NativeApp,
- EntityVector,
- Entity,
- LocalTransform as ILocalTransform,
- WorldTransform as IWorldTransform,
- Sprite as ISprite,
- Camera as ICamera,
- Canvas as ICanvas,
- Velocity as IVelocity,
- Parent as IParent,
- Children as IChildren
-} from './esengine';
-
-// =============================================================================
-// Component Classes
-// =============================================================================
-
-export class LocalTransform {
- static readonly componentName = 'LocalTransform';
- position = { x: 0, y: 0, z: 0 };
- rotation = { w: 1, x: 0, y: 0, z: 0 };
- scale = { x: 1, y: 1, z: 1 };
-}
-
-export class WorldTransform {
- static readonly componentName = 'WorldTransform';
- matrix: number[] = [];
- position = { x: 0, y: 0, z: 0 };
- rotation = { w: 1, x: 0, y: 0, z: 0 };
- scale = { x: 1, y: 1, z: 1 };
-}
-
-export class Sprite {
- static readonly componentName = 'Sprite';
- texture = 0;
- 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;
-}
-
-export class Camera {
- static readonly componentName = 'Camera';
- projectionType = 0;
- fov = 60;
- orthoSize = 5;
- nearPlane = 0.1;
- farPlane = 1000;
- aspectRatio = 1.77;
- isActive = true;
- priority = 0;
-}
-
-export class Canvas {
- static readonly componentName = 'Canvas';
- designResolution = { x: 1920, y: 1080 };
- pixelsPerUnit = 100;
- scaleMode = 0;
- matchWidthOrHeight = 0.5;
- backgroundColor = { x: 0, y: 0, z: 0, w: 1 };
-}
-
-export class Velocity {
- static readonly componentName = 'Velocity';
- linear = { x: 0, y: 0, z: 0 };
- angular = { x: 0, y: 0, z: 0 };
-}
-
-export class Parent {
- static readonly componentName = 'Parent';
- entity = 0;
-}
-
-export class Children {
- static readonly componentName = 'Children';
- entities: Entity[] = [];
-}
-
-// =============================================================================
-// Component Type Utilities
-// =============================================================================
-
-type ComponentClass<T = unknown> = {
- new(): T;
- readonly componentName: string;
-};
-
-type InstanceOf<T> = T extends ComponentClass<infer I> ? I : never;
-
-type ComponentInstances<T extends ComponentClass[]> = {
- [K in keyof T]: InstanceOf<T[K]>;
-};
-
-// =============================================================================
-// Schedule
-// =============================================================================
-
-export enum Schedule {
- Startup = 0,
- PreUpdate = 1,
- Update = 2,
- PostUpdate = 3,
- PreRender = 4,
- Render = 5,
- PostRender = 6,
-}
-
-// =============================================================================
-// Time
-// =============================================================================
-
-export interface Time {
- readonly delta: number;
- readonly elapsed: number;
- readonly frameCount: number;
-}
-
-// =============================================================================
-// Query
-// =============================================================================
-
-export class Query<T extends ComponentClass[]> {
- private readonly module_: ESEngineModule;
- private readonly registry_: Registry;
- private readonly components_: T;
-
- constructor(module: ESEngineModule, registry: Registry, components: T) {
- this.module_ = module;
- this.registry_ = registry;
- this.components_ = components;
- }
-
- *[Symbol.iterator](): Iterator<[Entity, ...ComponentInstances<T>]> {
- const entities = this.getEntities();
-
- for (const entity of entities) {
- const components = this.components_.map(C =>
- this.getComponent(entity, C.componentName)
- ) as ComponentInstances<T>;
- yield [entity, ...components];
- }
- }
-
- forEach(callback: (entity: Entity, ...components: ComponentInstances<T>) => void): void {
- for (const [entity, ...components] of this) {
- callback(entity, ...components);
- }
- }
-
- single(): [Entity, ...ComponentInstances<T>] | null {
- for (const result of this) {
- return result;
- }
- return null;
- }
-
- isEmpty(): boolean {
- return this.single() === null;
- }
-
- private getEntities(): Entity[] {
- const names = this.components_.map(C => C.componentName).join('');
- const queryName = `query${names}`;
- const queryFn = this.module_[queryName] as
- ((registry: Registry) => EntityVector) | undefined;
-
- if (typeof queryFn === 'function') {
- const entityVector = queryFn(this.registry_);
- const result: Entity[] = [];
- const size = entityVector.size();
- for (let i = 0; i < size; i++) {
- result.push(entityVector.get(i));
- }
- return result;
- }
- return [];
- }
-
- private getComponent(entity: Entity, name: string): unknown {
- const getter = `get${name}`;
- const getterFn = this.registry_[getter] as (entity: Entity) => unknown;
- return getterFn.call(this.registry_, entity);
- }
-}
-
-// =============================================================================
-// Resources
-// =============================================================================
-
-export class Res<T> {
- constructor(private readonly value_: T) {}
-
- get(): T {
- return this.value_;
- }
-}
-
-export class ResMut<T> {
- constructor(private value_: T) {}
-
- get(): T {
- return this.value_;
- }
-
- set(value: T): void {
- this.value_ = value;
- }
-}
-
-// =============================================================================
-// Entity Builder
-// =============================================================================
-
-export class EntityBuilder {
- private readonly registry_: Registry;
- private readonly entity_: Entity;
-
- constructor(registry: Registry) {
- this.registry_ = registry;
- this.entity_ = registry.create();
- }
-
- with<T extends ComponentClass>(Component: T, data: Partial<InstanceOf<T>>): this {
- const name = Component.componentName;
- const defaults = new Component();
- const component = Object.assign({}, defaults, data);
- const adder = `add${name}`;
- const addFn = this.registry_[adder] as (entity: Entity, component: unknown) => void;
- addFn.call(this.registry_, this.entity_, component);
- return this;
- }
-
- id(): Entity {
- return this.entity_;
- }
-}
-
-// =============================================================================
-// Commands
-// =============================================================================
-
-export class Commands {
- private readonly registry_: Registry;
- private readonly pendingDespawns_: Entity[] = [];
-
- constructor(registry: Registry) {
- this.registry_ = registry;
- }
-
- spawn(): EntityBuilder {
- return new EntityBuilder(this.registry_);
- }
-
- despawn(entity: Entity): void {
- this.pendingDespawns_.push(entity);
- }
-
- insert<T extends ComponentClass>(entity: Entity, Component: T, data: Partial<InstanceOf<T>>): void {
- const name = Component.componentName;
- const defaults = new Component();
- const component = Object.assign({}, defaults, data);
- const adder = `add${name}`;
- const addFn = this.registry_[adder] as (entity: Entity, component: unknown) => void;
- addFn.call(this.registry_, entity, component);
- }
-
- remove<T extends ComponentClass>(entity: Entity, Component: T): void {
- const name = Component.componentName;
- const remover = `remove${name}`;
- const removeFn = this.registry_[remover] as (entity: Entity) => void;
- removeFn.call(this.registry_, entity);
- }
-
- has<T extends ComponentClass>(entity: Entity, Component: T): boolean {
- const name = Component.componentName;
- const checker = `has${name}`;
- const hasFn = this.registry_[checker] as (entity: Entity) => boolean;
- return hasFn.call(this.registry_, entity);
- }
-
- get<T extends ComponentClass>(entity: Entity, Component: T): InstanceOf<T> {
- const name = Component.componentName;
- const getter = `get${name}`;
- const getFn = this.registry_[getter] as (entity: Entity) => InstanceOf<T>;
- return getFn.call(this.registry_, entity);
- }
-
- flush(): void {
- for (const entity of this.pendingDespawns_) {
- this.registry_.destroy(entity);
- }
- this.pendingDespawns_.length = 0;
- }
-}
-
-// =============================================================================
-// World
-// =============================================================================
-
-export class World {
- private readonly module_: ESEngineModule;
- private readonly registry_: Registry;
-
- constructor(module: ESEngineModule, registry: Registry) {
- this.module_ = module;
- this.registry_ = registry;
- }
-
- query<T extends ComponentClass[]>(...components: T): Query<T> {
- return new Query(this.module_, this.registry_, components);
- }
-
- spawn(): EntityBuilder {
- return new EntityBuilder(this.registry_);
- }
-
- commands(): Commands {
- return new Commands(this.registry_);
- }
-
- get<T extends ComponentClass>(entity: Entity, Component: T): InstanceOf<T> {
- const name = Component.componentName;
- const getter = `get${name}`;
- const getFn = this.registry_[getter] as (entity: Entity) => InstanceOf<T>;
- return getFn.call(this.registry_, entity);
- }
-
- has<T extends ComponentClass>(entity: Entity, Component: T): boolean {
- const name = Component.componentName;
- const checker = `has${name}`;
- const hasFn = this.registry_[checker] as (entity: Entity) => boolean;
- return hasFn.call(this.registry_, entity);
- }
-}
-
-// =============================================================================
-// System Types
-// =============================================================================
-
-export type SystemFn = (world: World, time: Time) => void;
-
-export abstract class System {
- protected world_!: World;
- protected time_!: Time;
-
- onStart?(): void;
- onUpdate?(): void;
- onDestroy?(): void;
-
- /** @internal */
- _bind(world: World, time: Time): void {
- this.world_ = world;
- this.time_ = time;
- }
-}
-
-export abstract class StartupSystem extends System {
- abstract onStart(): void;
-}
-
-export abstract class UpdateSystem extends System {
- abstract onUpdate(): void;
-}
-
-// =============================================================================
-// App Config
-// =============================================================================
-
-export interface AppConfig {
- title?: string;
- width?: number;
- height?: number;
- vsync?: boolean;
-}
-
-// =============================================================================
-// App
-// =============================================================================
-
-type SystemEntry = SystemFn | System;
-
-export class App {
- private readonly module_: ESEngineModule;
- private readonly cppApp_: NativeApp;
- private readonly systems_ = new Map<Schedule, SystemEntry[]>();
- private readonly systemInstances_: System[] = [];
- private readonly resources_ = new Map<string, unknown>();
-
- constructor(module: ESEngineModule, config?: AppConfig) {
- this.module_ = module;
-
- if (config) {
- // Pass config as plain object - embind value_object accepts JS objects
- const cppConfig = {
- title: config.title ?? 'ESEngine',
- width: config.width ?? 800,
- height: config.height ?? 600,
- vsync: config.vsync ?? true
- };
- this.cppApp_ = module.createAppWithConfig(cppConfig);
- } else {
- this.cppApp_ = module.createApp();
- }
-
- for (let i = 0; i <= Schedule.PostRender; i++) {
- this.systems_.set(i as Schedule, []);
- }
-
- module.setJSSystemsCallback((schedule: number) => {
- this.runSystems(schedule as Schedule);
- });
- }
-
- addSystem(schedule: Schedule, system: SystemFn | System): this {
- const systems = this.systems_.get(schedule);
- if (systems) {
- systems.push(system);
- if (system instanceof System) {
- this.systemInstances_.push(system);
- }
- }
- return this;
- }
-
- addStartupSystem(system: SystemFn | StartupSystem): this {
- return this.addSystem(Schedule.Startup, system);
- }
-
- addUpdateSystem(system: SystemFn | UpdateSystem): this {
- return this.addSystem(Schedule.Update, system);
- }
-
- insertResource<T>(name: string, value: T): this {
- this.resources_.set(name, value);
- return this;
- }
-
- getResource<T>(name: string): T | undefined {
- return this.resources_.get(name) as T | undefined;
- }
-
- run(): void {
- this.cppApp_.run();
- }
-
- quit(): void {
- this.cppApp_.quit();
- }
-
- world(): World {
- return new World(this.module_, this.cppApp_.registry());
- }
-
- time(): Time {
- return this.cppApp_.time();
- }
-
- width(): number {
- return this.cppApp_.width();
- }
-
- height(): number {
- return this.cppApp_.height();
- }
-
- private runSystems(schedule: Schedule): void {
- const systems = this.systems_.get(schedule);
- if (!systems) return;
-
- const world = this.world();
- const time = this.time();
-
- for (const system of systems) {
- if (typeof system === 'function') {
- system(world, time);
- } else {
- system._bind(world, time);
- if (schedule === Schedule.Startup && system.onStart) {
- system.onStart();
- } else if (system.onUpdate) {
- system.onUpdate();
- }
- }
- }
- }
-}
-
-// =============================================================================
-// Factory
-// =============================================================================
-
-export function createApp(module: ESEngineModule, config?: AppConfig): App {
- return new App(module, config);
-}
diff --git a/bindings/esengine.d.ts b/bindings/esengine.d.ts
index 7fbd25bc7..1dc6320ba 100644
--- a/bindings/esengine.d.ts
+++ b/bindings/esengine.d.ts
@@ -31,17 +31,17 @@ export type Mat4 = number[];
// Enums
// =============================================================================
-export const enum ProjectionType {
+export enum ProjectionType {
Perspective = 0,
- Orthographic = 1
+ Orthographic = 1,
}
-export const enum CanvasScaleMode {
+export enum CanvasScaleMode {
FixedWidth = 0,
FixedHeight = 1,
Expand = 2,
Shrink = 3,
- Match = 4
+ Match = 4,
}
// =============================================================================
@@ -49,7 +49,7 @@ export const enum CanvasScaleMode {
// =============================================================================
export interface Camera {
- projectionType: ProjectionType;
+ projectionType: any;
fov: number;
orthoSize: number;
nearPlane: number;
@@ -62,7 +62,7 @@ export interface Camera {
export interface Canvas {
designResolution: UVec2;
pixelsPerUnit: number;
- scaleMode: CanvasScaleMode;
+ scaleMode: any;
matchWidthOrHeight: number;
backgroundColor: Vec4;
}
@@ -72,11 +72,10 @@ export interface Parent {
}
export interface Children {
- entities: Entity[];
}
export interface Sprite {
- texture: number;
+ texture: any;
color: Vec4;
size: Vec2;
uvOffset: Vec2;
@@ -118,109 +117,34 @@ export interface Registry {
getCamera(entity: Entity): Camera;
addCamera(entity: Entity, component: Camera): void;
removeCamera(entity: Entity): void;
-
hasCanvas(entity: Entity): boolean;
getCanvas(entity: Entity): Canvas;
addCanvas(entity: Entity, component: Canvas): void;
removeCanvas(entity: Entity): void;
-
hasParent(entity: Entity): boolean;
getParent(entity: Entity): Parent;
addParent(entity: Entity, component: Parent): void;
removeParent(entity: Entity): void;
-
hasChildren(entity: Entity): boolean;
getChildren(entity: Entity): Children;
addChildren(entity: Entity, component: Children): void;
removeChildren(entity: Entity): void;
-
hasSprite(entity: Entity): boolean;
getSprite(entity: Entity): Sprite;
addSprite(entity: Entity, component: Sprite): void;
removeSprite(entity: Entity): void;
-
hasLocalTransform(entity: Entity): boolean;
getLocalTransform(entity: Entity): LocalTransform;
addLocalTransform(entity: Entity, component: LocalTransform): void;
removeLocalTransform(entity: Entity): void;
-
hasWorldTransform(entity: Entity): boolean;
getWorldTransform(entity: Entity): WorldTransform;
addWorldTransform(entity: Entity, component: WorldTransform): void;
removeWorldTransform(entity: Entity): void;
-
hasVelocity(entity: Entity): boolean;
getVelocity(entity: Entity): Velocity;
addVelocity(entity: Entity, component: Velocity): void;
removeVelocity(entity: Entity): void;
-
- [key: string]: unknown;
-}
-
-// =============================================================================
-// Resource Types
-// =============================================================================
-
-export type ShaderHandle = number;
-export type TextureHandle = number;
-
-export const enum TextureFormat {
- RGB8 = 0,
- RGBA8 = 1
-}
-
-export interface ResourceManager {
- init(): void;
- shutdown(): void;
- createShader(vertSrc: string, fragSrc: string): ShaderHandle;
- createTexture(width: number, height: number, pixelsPtr: number, pixelsLen: number, format: TextureFormat): TextureHandle;
- releaseShader(handle: ShaderHandle): void;
- releaseTexture(handle: TextureHandle): void;
-}
-
-// =============================================================================
-// App Types
-// =============================================================================
-
-export const enum Schedule {
- Startup = 0,
- PreUpdate = 1,
- Update = 2,
- PostUpdate = 3,
- PreRender = 4,
- Render = 5,
- PostRender = 6,
-}
-
-export interface Time {
- delta: number;
- elapsed: number;
- frameCount: number;
-}
-
-export interface AppConfig {
- title: string;
- width: number;
- height: number;
- vsync: boolean;
-}
-
-export interface NativeApp {
- run(): void;
- quit(): void;
- registry(): Registry;
- time(): Time;
- width(): number;
- height(): number;
-}
-
-// =============================================================================
-// Query Types
-// =============================================================================
-
-export interface EntityVector {
- size(): number;
- get(index: number): Entity;
}
// =============================================================================
@@ -228,9 +152,7 @@ export interface EntityVector {
// =============================================================================
export interface ESEngineModule {
- ResourceManager: new () => ResourceManager;
- AppConfig: new () => AppConfig;
-
+ Registry: new () => Registry;
Camera: new () => Camera;
Canvas: new () => Canvas;
Parent: new () => Parent;
@@ -239,26 +161,6 @@ export interface ESEngineModule {
LocalTransform: new () => LocalTransform;
WorldTransform: new () => WorldTransform;
Velocity: new () => Velocity;
-
- Schedule: typeof Schedule;
- TextureFormat: typeof TextureFormat;
- ProjectionType: typeof ProjectionType;
- CanvasScaleMode: typeof CanvasScaleMode;
-
- createApp(): NativeApp;
- createAppWithConfig(config: AppConfig): NativeApp;
- getApp(): NativeApp;
-
- queryLocalTransform(registry: Registry): EntityVector;
- queryLocalTransformSprite(registry: Registry): EntityVector;
-
- HEAPU8: Uint8Array;
- _malloc(size: number): number;
- _free(ptr: number): void;
-
- setJSSystemsCallback(callback: (schedule: number, dt: number) => void): void;
-
- [key: string]: unknown;
}
export default function createModule(): Promise<ESEngineModule>;
diff --git a/bindings/example.ts b/bindings/example.ts
deleted file mode 100644
index e5b4b2012..000000000
--- a/bindings/example.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * @file example.ts
- * @brief Example usage of ESEngine ECS API
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-import createModule from './esengine';
-import {
- App,
- Schedule,
- StartupSystem,
- UpdateSystem,
- LocalTransform,
- Sprite
-} from './App';
-
-// =============================================================================
-// Systems
-// =============================================================================
-
-class SpawnSystem extends StartupSystem {
- onStart(): void {
- this.world_.spawn()
- .with(LocalTransform, {
- position: { x: 400, y: 300, z: 0 }
- })
- .with(Sprite, {
- color: { x: 1, y: 0, z: 0, w: 1 },
- size: { x: 64, y: 64 }
- });
- }
-}
-
-class MovementSystem extends UpdateSystem {
- onUpdate(): void {
- for (const [_, transform] of this.world_.query(LocalTransform)) {
- transform.position.x += Math.sin(this.time_.elapsed * 2) * 50 * this.time_.delta;
- }
- }
-}
-
-class RenderSystem extends UpdateSystem {
- onUpdate(): void {
- for (const [entity, transform, sprite] of this.world_.query(LocalTransform, Sprite)) {
- console.log(`Entity ${entity}: pos=(${transform.position.x.toFixed(1)}, ${transform.position.y.toFixed(1)}), layer=${sprite.layer}`);
- }
- }
-}
-
-async function main(): Promise<void> {
- const module = await createModule();
-
- const app = new App(module, {
- title: 'ECS Example',
- width: 800,
- height: 600
- });
-
- app.addStartupSystem(new SpawnSystem())
- .addUpdateSystem(new MovementSystem())
- .addSystem(Schedule.Render, new RenderSystem());
-
- app.run();
-}
-
-main().catch(console.error);
diff --git a/bindings/package.json b/bindings/package.json
deleted file mode 100644
index 998429da2..000000000
--- a/bindings/package.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "esengine",
- "version": "0.1.0",
- "description": "ESEngine TypeScript SDK and type definitions",
- "main": "App.ts",
- "types": "App.ts",
- "type": "module",
- "exports": {
- ".": {
- "types": "./App.ts",
- "default": "./App.ts"
- },
- "./wasm": {
- "types": "./esengine.d.ts"
- }
- },
- "files": [
- "esengine.d.ts",
- "App.ts",
- "AssetLoader.ts",
- "platform/"
- ],
- "keywords": ["esengine", "game-engine", "webassembly", "ecs"],
- "author": "ESEngine Team",
- "license": "MIT",
- "repository": {
- "type": "git",
- "url": "https://github.com/esengine/esengine.git"
- }
-}
diff --git a/bindings/platform/web/index.html b/bindings/platform/web/index.html
index b2df6585d..31628d776 100644
--- a/bindings/platform/web/index.html
+++ b/bindings/platform/web/index.html
@@ -2,68 +2,44 @@
<html lang="en">
<head>
<meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ESEngine</title>
<style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- html, body {
- width: 100%;
- height: 100%;
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ body {
+ background: #1a1a2e;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-height: 100vh;
overflow: hidden;
- background-color: #1a1a1a;
}
#canvas {
display: block;
- width: 100%;
- height: 100%;
- touch-action: none;
}
#loading {
position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
color: #fff;
- font-family: sans-serif;
- font-size: 18px;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ font-size: 14px;
}
- #loading.hidden { display: none; }
</style>
</head>
<body>
- <div id="loading">Loading ESEngine...</div>
+ <div id="loading">Loading...</div>
<canvas id="canvas"></canvas>
-
- <script type="module">
- // ESEngine ES6 Module Loader
- import ESEngineModule from './hello_triangle.js';
-
- function resizeCanvas() {
- const canvas = document.getElementById('canvas');
- const dpr = window.devicePixelRatio || 1;
- canvas.width = window.innerWidth * dpr;
- canvas.height = window.innerHeight * dpr;
- }
- window.addEventListener('resize', resizeCanvas);
- resizeCanvas();
-
- ESEngineModule({
+ <script>
+ var Module = {
canvas: document.getElementById('canvas'),
- print: (text) => console.log(text),
- printErr: (text) => console.error(text)
- }).then((Module) => {
- console.log('ESEngine module loaded');
- document.getElementById('loading').classList.add('hidden');
- Module._es_app_init();
- }).catch((err) => {
- // "unwind" is expected for Emscripten main loop
- if (err === 'unwind' || (err.message && err.message.includes('unwind'))) {
- console.log('App running');
- return;
+ onRuntimeInitialized: function() {
+ document.getElementById('loading').style.display = 'none';
}
- console.error('Failed:', err);
- document.getElementById('loading').textContent = 'Error: ' + err.message;
- });
+ };
</script>
+ <script src="esengine.js"></script>
</body>
</html>
diff --git a/bindings/platform/wxgame/game.js b/bindings/platform/wxgame/game.js
deleted file mode 100644
index 847979b92..000000000
--- a/bindings/platform/wxgame/game.js
+++ /dev/null
@@ -1,113 +0,0 @@
-// ESEngine WeChat MiniGame Entry Point
-
-import './weapp-adapter.js';
-
-// Get system info
-const systemInfo = wx.getSystemInfoSync();
-const dpr = systemInfo.pixelRatio;
-const width = systemInfo.windowWidth * dpr;
-const height = systemInfo.windowHeight * dpr;
-
-// Create canvas
-const canvas = wx.createCanvas();
-canvas.width = width;
-canvas.height = height;
-
-// Set up WebGL context
-const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
-
-if (!gl) {
- console.error('WebGL not supported');
-}
-
-// Module configuration
-var Module = {
- canvas: canvas,
- gl: gl,
- print: function(text) {
- console.log('[ESEngine]', text);
- },
- printErr: function(text) {
- console.error('[ESEngine]', text);
- },
- onRuntimeInitialized: function() {
- console.log('ESEngine initialized');
- // Initialize engine
- if (Module._es_init) {
- Module._es_init(width, height);
- }
- // Start game loop
- startGameLoop();
- }
-};
-
-// Touch handling
-let touches = new Map();
-
-canvas.addEventListener('touchstart', (e) => {
- for (let touch of e.changedTouches) {
- touches.set(touch.identifier, {
- x: touch.clientX * dpr,
- y: touch.clientY * dpr
- });
- if (Module._es_on_touch) {
- Module._es_on_touch(0, touch.clientX * dpr, touch.clientY * dpr);
- }
- }
-});
-
-canvas.addEventListener('touchmove', (e) => {
- for (let touch of e.changedTouches) {
- touches.set(touch.identifier, {
- x: touch.clientX * dpr,
- y: touch.clientY * dpr
- });
- if (Module._es_on_touch) {
- Module._es_on_touch(1, touch.clientX * dpr, touch.clientY * dpr);
- }
- }
-});
-
-canvas.addEventListener('touchend', (e) => {
- for (let touch of e.changedTouches) {
- if (Module._es_on_touch) {
- Module._es_on_touch(2, touch.clientX * dpr, touch.clientY * dpr);
- }
- touches.delete(touch.identifier);
- }
-});
-
-canvas.addEventListener('touchcancel', (e) => {
- for (let touch of e.changedTouches) {
- if (Module._es_on_touch) {
- Module._es_on_touch(3, touch.clientX * dpr, touch.clientY * dpr);
- }
- touches.delete(touch.identifier);
- }
-});
-
-// Game loop
-let lastTime = Date.now();
-
-function startGameLoop() {
- const loop = () => {
- const now = Date.now();
- const deltaTime = (now - lastTime) / 1000.0;
- lastTime = now;
-
- if (Module._es_update) {
- Module._es_update(deltaTime);
- }
- if (Module._es_render) {
- Module._es_render();
- }
-
- requestAnimationFrame(loop);
- };
-
- requestAnimationFrame(loop);
-}
-
-// Load the WASM module
-// The esengine.js file should be generated by Emscripten
-require('./esengine.js');
diff --git a/bindings/platform/wxgame/game.json b/bindings/platform/wxgame/game.json
deleted file mode 100644
index cd7b3bc5b..000000000
--- a/bindings/platform/wxgame/game.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "deviceOrientation": "portrait",
- "showStatusBar": false,
- "networkTimeout": {
- "request": 10000,
- "connectSocket": 10000,
- "uploadFile": 10000,
- "downloadFile": 10000
- }
-}
diff --git a/bindings/platform/wxgame/weapp-adapter.js b/bindings/platform/wxgame/weapp-adapter.js
deleted file mode 100644
index 4ed9637b0..000000000
--- a/bindings/platform/wxgame/weapp-adapter.js
+++ /dev/null
@@ -1,151 +0,0 @@
-// WeChat MiniGame Adapter
-// Provides browser-like APIs for compatibility with Emscripten
-
-// Canvas polyfill
-if (typeof canvas === 'undefined') {
- var canvas = wx.createCanvas();
-}
-
-// Window object polyfill
-if (typeof window === 'undefined') {
- var window = {
- innerWidth: canvas.width,
- innerHeight: canvas.height,
- devicePixelRatio: wx.getSystemInfoSync().pixelRatio,
- performance: {
- now: function() {
- return Date.now();
- }
- },
- addEventListener: function(type, listener, options) {
- if (type === 'resize') {
- // WeChat doesn't support resize events in the same way
- }
- },
- removeEventListener: function(type, listener, options) {}
- };
-}
-
-// Document polyfill
-if (typeof document === 'undefined') {
- var document = {
- createElement: function(tagName) {
- if (tagName === 'canvas') {
- return wx.createCanvas();
- }
- return {};
- },
- getElementById: function(id) {
- if (id === 'canvas') {
- return canvas;
- }
- return null;
- },
- body: {
- appendChild: function() {}
- },
- addEventListener: function(type, listener, options) {},
- removeEventListener: function(type, listener, options) {}
- };
-}
-
-// Performance polyfill
-if (typeof performance === 'undefined') {
- var performance = {
- now: function() {
- return Date.now();
- }
- };
-}
-
-// Console polyfill (WeChat has console but ensure it exists)
-if (typeof console === 'undefined') {
- var console = {
- log: function() {},
- error: function() {},
- warn: function() {},
- info: function() {}
- };
-}
-
-// XMLHttpRequest polyfill for asset loading
-if (typeof XMLHttpRequest === 'undefined') {
- var XMLHttpRequest = function() {
- this.readyState = 0;
- this.status = 0;
- this.responseText = '';
- this.response = null;
- };
-
- XMLHttpRequest.prototype.open = function(method, url, async) {
- this._method = method;
- this._url = url;
- this._async = async;
- };
-
- XMLHttpRequest.prototype.send = function(data) {
- var self = this;
- var fs = wx.getFileSystemManager();
-
- if (this._method === 'GET') {
- try {
- // Try to read as a local file first
- var content = fs.readFileSync(this._url);
- self.status = 200;
- self.readyState = 4;
- self.response = content;
- self.responseText = typeof content === 'string' ? content : '';
- if (self.onload) self.onload();
- } catch (e) {
- // If local read fails, try network
- wx.request({
- url: this._url,
- method: 'GET',
- responseType: 'arraybuffer',
- success: function(res) {
- self.status = res.statusCode;
- self.readyState = 4;
- self.response = res.data;
- if (self.onload) self.onload();
- },
- fail: function(err) {
- self.status = 0;
- self.readyState = 4;
- if (self.onerror) self.onerror(err);
- }
- });
- }
- }
- };
-
- XMLHttpRequest.prototype.setRequestHeader = function(name, value) {};
-}
-
-// Image polyfill
-if (typeof Image === 'undefined') {
- var Image = function() {
- var img = wx.createImage();
- return img;
- };
-}
-
-// Audio polyfill
-if (typeof Audio === 'undefined') {
- var Audio = function(src) {
- var audio = wx.createInnerAudioContext();
- if (src) {
- audio.src = src;
- }
- return audio;
- };
-}
-
-// Export for module use
-if (typeof module !== 'undefined') {
- module.exports = {
- window: window,
- document: document,
- canvas: canvas,
- performance: performance
- };
-}
diff --git a/scripts/build-editor.bat b/scripts/build-editor.bat
new file mode 100644
index 000000000..d7ab97a13
--- /dev/null
+++ b/scripts/build-editor.bat
@@ -0,0 +1,27 @@
+@echo off
+setlocal
+
+cd /d "%~dp0.."
+
+if not exist build (
+ echo Creating build directory...
+ mkdir build
+ cd build
+ cmake .. -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=Debug
+) else (
+ cd build
+)
+
+echo Building Editor...
+mingw32-make esengine_editor -j%NUMBER_OF_PROCESSORS%
+
+if %ERRORLEVEL% EQU 0 (
+ echo.
+ echo [OK] Editor built successfully!
+ echo Run: bin\esengine_editor.exe
+) else (
+ echo.
+ echo [ERROR] Build failed!
+)
+
+pause
diff --git a/scripts/build-web.bat b/scripts/build-web.bat
new file mode 100644
index 000000000..d8d4086f3
--- /dev/null
+++ b/scripts/build-web.bat
@@ -0,0 +1,27 @@
+@echo off
+setlocal
+
+cd /d "%~dp0.."
+
+if not exist build-web (
+ echo Creating build-web directory...
+ mkdir build-web
+ cd build-web
+ call emcmake cmake .. -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=Release -DES_BUILD_WEB=ON
+) else (
+ cd build-web
+)
+
+echo Building Web SDK...
+call emmake mingw32-make esengine_sdk -j%NUMBER_OF_PROCESSORS%
+
+if %ERRORLEVEL% EQU 0 (
+ echo.
+ echo [OK] Web SDK built successfully!
+ echo Output: build-web/sdk/
+) else (
+ echo.
+ echo [ERROR] Build failed!
+)
+
+pause
diff --git a/scripts/rebuild-web.bat b/scripts/rebuild-web.bat
new file mode 100644
index 000000000..57fd34680
--- /dev/null
+++ b/scripts/rebuild-web.bat
@@ -0,0 +1,27 @@
+@echo off
+setlocal
+
+cd /d "%~dp0.."
+
+echo === Running EHT ===
+python tools/eht.py --verbose
+if %ERRORLEVEL% NEQ 0 (
+ echo [ERROR] EHT failed!
+ pause
+ exit /b 1
+)
+
+echo.
+echo === Building Web SDK ===
+cd build-web
+call emmake mingw32-make esengine_sdk -j%NUMBER_OF_PROCESSORS%
+
+if %ERRORLEVEL% EQU 0 (
+ echo.
+ echo [OK] Build complete!
+) else (
+ echo.
+ echo [ERROR] Build failed!
+)
+
+pause
diff --git a/scripts/run-eht.bat b/scripts/run-eht.bat
new file mode 100644
index 000000000..ac2e0ec4e
--- /dev/null
+++ b/scripts/run-eht.bat
@@ -0,0 +1,4 @@
+@echo off
+cd /d "%~dp0.."
+python tools/eht.py --verbose
+pause
diff --git a/sdk/package-lock.json b/sdk/package-lock.json
index 609f2b111..1f162d4c4 100644
--- a/sdk/package-lock.json
+++ b/sdk/package-lock.json
@@ -867,7 +867,6 @@
"integrity": "sha512-9FwVqlgUHzbXtDg9RCMgodF3Ua4Na6Gau+Sdt9vyCN4RhHfVKX2DCHy3BjMLTDd47ITDhYAnTwGulWTblJSDLg==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@types/estree": "1.0.8"
},
@@ -1088,8 +1087,7 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
- "license": "0BSD",
- "peer": true
+ "license": "0BSD"
},
"node_modules/typescript": {
"version": "5.9.3",
@@ -1097,7 +1095,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
- "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
diff --git a/sdk/package.json b/sdk/package.json
index 8dc322a7d..e5779aa7d 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -1,5 +1,5 @@
{
- "name": "@esengine/sdk",
+ "name": "esengine",
"version": "0.1.0",
"type": "module",
"description": "TypeScript SDK for ESEngine - A lightweight 2D game engine for Web and WeChat MiniGames",
diff --git a/bindings/AssetLoader.ts b/sdk/src/assets/AssetLoader.ts
similarity index 63%
rename from bindings/AssetLoader.ts
rename to sdk/src/assets/AssetLoader.ts
index d671a438f..67c9777ba 100644
--- a/bindings/AssetLoader.ts
+++ b/sdk/src/assets/AssetLoader.ts
@@ -1,6 +1,6 @@
/**
* @file AssetLoader.ts
- * @brief Web platform asset loading utilities
+ * @brief Asset loading utilities for textures, shaders, and data files
*
* @author ESEngine Team
* @date 2026
@@ -9,8 +9,12 @@
* Licensed under the MIT License.
*/
-import type { ESEngineModule, ResourceManager, TextureHandle, ShaderHandle } from './esengine';
-import { TextureFormat } from './esengine';
+import type { ESEngineModule, CppResourceManager, TextureHandle, ShaderHandle } from '../wasm/types';
+import { TextureFormat } from '../wasm/types';
+
+// =============================================================================
+// Types
+// =============================================================================
export interface TextureData {
width: number;
@@ -24,42 +28,38 @@ export interface ShaderData {
fragmentSource: string;
}
+// =============================================================================
+// AssetLoader
+// =============================================================================
+
export class AssetLoader {
private module_: ESEngineModule;
- private resourceManager_: ResourceManager;
+ private resourceManager_: CppResourceManager;
private textureCache_ = new Map<string, TextureHandle>();
private shaderCache_ = new Map<string, ShaderHandle>();
- constructor(module: ESEngineModule, resourceManager: ResourceManager) {
+ constructor(module: ESEngineModule, resourceManager: CppResourceManager) {
this.module_ = module;
this.resourceManager_ = resourceManager;
}
- async loadAndCreateTexture(url: string): Promise<TextureHandle> {
+ // =========================================================================
+ // Texture Loading
+ // =========================================================================
+
+ async loadTexture(url: string): Promise<TextureHandle> {
const cached = this.textureCache_.get(url);
if (cached !== undefined) {
return cached;
}
- const data = await this.loadTexture(url);
- const handle = this.createTextureFromData(data);
+ const data = await this.fetchTexture(url);
+ const handle = this.createTexture(data);
this.textureCache_.set(url, handle);
return handle;
}
- async loadAndCreateShader(url: string): Promise<ShaderHandle> {
- const cached = this.shaderCache_.get(url);
- if (cached !== undefined) {
- return cached;
- }
-
- const data = await this.loadShader(url);
- const handle = this.resourceManager_.createShader(data.vertexSource, data.fragmentSource);
- this.shaderCache_.set(url, handle);
- return handle;
- }
-
- createTextureFromData(data: TextureData): TextureHandle {
+ createTexture(data: TextureData): TextureHandle {
const ptr = this.module_._malloc(data.pixels.length);
this.module_.HEAPU8.set(data.pixels, ptr);
@@ -72,7 +72,7 @@ export class AssetLoader {
return handle;
}
- async loadTexture(url: string): Promise<TextureData> {
+ private async fetchTexture(url: string): Promise<TextureData> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch texture: ${url}`);
@@ -98,41 +98,33 @@ export class AssetLoader {
};
}
- async loadShader(url: string): Promise<ShaderData> {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch shader: ${url}`);
- }
-
- const source = await response.text();
- return this.parseESShader(source);
- }
+ // =========================================================================
+ // Shader Loading
+ // =========================================================================
- async loadText(url: string): Promise<string> {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch: ${url}`);
+ async loadShader(url: string): Promise<ShaderHandle> {
+ const cached = this.shaderCache_.get(url);
+ if (cached !== undefined) {
+ return cached;
}
- return response.text();
- }
- async loadBinary(url: string): Promise<ArrayBuffer> {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch: ${url}`);
- }
- return response.arrayBuffer();
+ const data = await this.fetchShader(url);
+ const handle = this.resourceManager_.createShader(data.vertexSource, data.fragmentSource);
+ this.shaderCache_.set(url, handle);
+ return handle;
}
- async loadJson<T = unknown>(url: string): Promise<T> {
+ private async fetchShader(url: string): Promise<ShaderData> {
const response = await fetch(url);
if (!response.ok) {
- throw new Error(`Failed to fetch: ${url}`);
+ throw new Error(`Failed to fetch shader: ${url}`);
}
- return response.json();
+
+ const source = await response.text();
+ return this.parseShader(source);
}
- private parseESShader(source: string): ShaderData {
+ private parseShader(source: string): ShaderData {
let vertexSource = '';
let fragmentSource = '';
let sharedCode = '';
@@ -184,4 +176,63 @@ export class AssetLoader {
fragmentSource: versionLine + sharedCode + fragmentSource
};
}
+
+ // =========================================================================
+ // Generic Loading
+ // =========================================================================
+
+ async loadText(url: string): Promise<string> {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch: ${url}`);
+ }
+ return response.text();
+ }
+
+ async loadBinary(url: string): Promise<ArrayBuffer> {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch: ${url}`);
+ }
+ return response.arrayBuffer();
+ }
+
+ async loadJson<T = unknown>(url: string): Promise<T> {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch: ${url}`);
+ }
+ return response.json();
+ }
+
+ // =========================================================================
+ // Cache Management
+ // =========================================================================
+
+ releaseTexture(url: string): void {
+ const handle = this.textureCache_.get(url);
+ if (handle !== undefined) {
+ this.resourceManager_.releaseTexture(handle);
+ this.textureCache_.delete(url);
+ }
+ }
+
+ releaseShader(url: string): void {
+ const handle = this.shaderCache_.get(url);
+ if (handle !== undefined) {
+ this.resourceManager_.releaseShader(handle);
+ this.shaderCache_.delete(url);
+ }
+ }
+
+ clearCache(): void {
+ for (const handle of this.textureCache_.values()) {
+ this.resourceManager_.releaseTexture(handle);
+ }
+ for (const handle of this.shaderCache_.values()) {
+ this.resourceManager_.releaseShader(handle);
+ }
+ this.textureCache_.clear();
+ this.shaderCache_.clear();
+ }
}
diff --git a/sdk/src/assets/index.ts b/sdk/src/assets/index.ts
new file mode 100644
index 000000000..f1bc74872
--- /dev/null
+++ b/sdk/src/assets/index.ts
@@ -0,0 +1,12 @@
+/**
+ * @file index.ts
+ * @brief Asset loading module exports
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+export { AssetLoader, type TextureData, type ShaderData } from './AssetLoader';
diff --git a/sdk/src/ecs/Components.ts b/sdk/src/ecs/Components.ts
index e3303af27..c4a896014 100644
--- a/sdk/src/ecs/Components.ts
+++ b/sdk/src/ecs/Components.ts
@@ -133,7 +133,44 @@ export function createStatic(): Static {
return {};
}
-// Component type symbols for type identification
+// =============================================================================
+// Hierarchy Components
+// =============================================================================
+
+import { Entity } from '../core/Types';
+
+/**
+ * Parent component - References the parent entity
+ */
+export interface Parent {
+ entity: Entity;
+}
+
+/**
+ * Create a Parent component
+ */
+export function createParent(entity: Entity): Parent {
+ return { entity };
+}
+
+/**
+ * Children component - List of child entities
+ */
+export interface Children {
+ entities: Entity[];
+}
+
+/**
+ * Create a Children component
+ */
+export function createChildren(entities: Entity[] = []): Children {
+ return { entities: [...entities] };
+}
+
+// =============================================================================
+// Component Type Symbols
+// =============================================================================
+
export const TransformType = Symbol('Transform');
export const VelocityType = Symbol('Velocity');
export const SpriteType = Symbol('Sprite');
@@ -141,3 +178,5 @@ export const NameType = Symbol('Name');
export const ActiveType = Symbol('Active');
export const VisibleType = Symbol('Visible');
export const StaticType = Symbol('Static');
+export const ParentType = Symbol('Parent');
+export const ChildrenType = Symbol('Children');
diff --git a/sdk/src/framework/app.ts b/sdk/src/framework/app.ts
new file mode 100644
index 000000000..15e2d6e35
--- /dev/null
+++ b/sdk/src/framework/app.ts
@@ -0,0 +1,321 @@
+/**
+ * @file app.ts
+ * @brief Application builder with plugin support
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { World, CppRegistry } from './world';
+import { Schedule, SystemOrdering } from './schedule';
+import { SystemDef, SystemRunner, ConditionalSystemDef } from './system';
+import { ResourceDef, ResourceStorage, Time, TimeData } from './resource';
+import { ComponentDef } from './component';
+import { Schema } from './types';
+import { loadScene, ComponentRegistry, SceneLoadResult } from '../scene/SceneLoader';
+
+// =============================================================================
+// Plugin Interface
+// =============================================================================
+
+export interface Plugin {
+ build(app: App): void;
+}
+
+// =============================================================================
+// System Entry
+// =============================================================================
+
+interface SystemEntry {
+ system: SystemDef | ConditionalSystemDef;
+ ordering?: SystemOrdering;
+}
+
+// =============================================================================
+// App Configuration
+// =============================================================================
+
+export interface AppConfig {
+ title?: string;
+ width?: number;
+ height?: number;
+ canvas?: HTMLCanvasElement | string;
+ fixedTimestep?: number;
+}
+
+// =============================================================================
+// App
+// =============================================================================
+
+export class App {
+ private readonly world_: World;
+ private readonly resources_: ResourceStorage;
+ private readonly systems_ = new Map<Schedule, SystemEntry[]>();
+ private readonly plugins_: Plugin[] = [];
+ private readonly componentRegistry_: ComponentRegistry = new Map();
+ private runner_: SystemRunner | null = null;
+
+ private running_ = false;
+ private lastTime_ = 0;
+ private fixedTimestep_ = 1 / 60;
+ private fixedAccumulator_ = 0;
+
+ private config_: AppConfig = {};
+
+ private constructor() {
+ 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(): App {
+ return new App();
+ }
+
+ // =========================================================================
+ // Component Registration
+ // =========================================================================
+
+ /** @brief Register a custom component for scene loading */
+ registerComponent(component: ComponentDef<Schema>): this {
+ this.componentRegistry_.set(component._name, component);
+ return this;
+ }
+
+ /** @brief Get the component registry */
+ get componentRegistry(): ComponentRegistry {
+ return this.componentRegistry_;
+ }
+
+ // =========================================================================
+ // Configuration
+ // =========================================================================
+
+ configure(config: AppConfig): this {
+ this.config_ = { ...this.config_, ...config };
+ if (config.fixedTimestep) {
+ this.fixedTimestep_ = config.fixedTimestep;
+ }
+ return this;
+ }
+
+ // =========================================================================
+ // Plugins
+ // =========================================================================
+
+ addPlugin(plugin: Plugin): this {
+ this.plugins_.push(plugin);
+ plugin.build(this);
+ return this;
+ }
+
+ addPlugins(...plugins: Plugin[]): this {
+ for (const plugin of plugins) {
+ this.addPlugin(plugin);
+ }
+ return this;
+ }
+
+ // =========================================================================
+ // Systems
+ // =========================================================================
+
+ /** @brief Add a system to a specific schedule */
+ addSystemToSchedule(schedule: Schedule, system: SystemDef, ordering?: SystemOrdering): this {
+ const entry: SystemEntry = { system, ordering };
+ this.systems_.get(schedule)!.push(entry);
+ return this;
+ }
+
+ /** @brief Add a system to the Update schedule (convenience) */
+ addSystem(system: SystemDef, ordering?: SystemOrdering): this {
+ return this.addSystemToSchedule(Schedule.Update, system, ordering);
+ }
+
+ /** @brief Add a startup system */
+ addStartupSystem(system: SystemDef): this {
+ return this.addSystemToSchedule(Schedule.Startup, system);
+ }
+
+ /** @brief Add multiple systems to a schedule */
+ addSystems(schedule: Schedule, ...systems: SystemDef[]): this {
+ for (const system of systems) {
+ this.addSystemToSchedule(schedule, system);
+ }
+ return this;
+ }
+
+ // =========================================================================
+ // Scene Loading
+ // =========================================================================
+
+ /** @brief Load a scene from a URL */
+ async loadSceneAsync(url: string): Promise<SceneLoadResult> {
+ return loadScene(this.world_.tsRegistry, url, {
+ componentRegistry: this.componentRegistry_,
+ });
+ }
+
+ /** @brief Load a scene (fire and forget) */
+ loadScene(url: string): this {
+ this.loadSceneAsync(url)
+ .then((result) => {
+ if (result.success) {
+ console.log(`Scene loaded: ${result.sceneName} (${result.entityCount} entities)`);
+ } else {
+ console.error(`Failed to load scene: ${result.error}`);
+ }
+ })
+ .catch((err) => {
+ console.error('Scene loading error:', err);
+ });
+ return this;
+ }
+
+ // =========================================================================
+ // Resources
+ // =========================================================================
+
+ insertResource<T>(resource: ResourceDef<T>, value: T): this {
+ this.resources_.insert(resource, value);
+ return this;
+ }
+
+ initResource<T>(resource: ResourceDef<T>): this {
+ if (!this.resources_.has(resource)) {
+ this.resources_.insert(resource, resource._default);
+ }
+ return this;
+ }
+
+ // =========================================================================
+ // C++ Integration
+ // =========================================================================
+
+ /** @brief Connect to C++ Registry for builtin component access */
+ connectCpp(cppRegistry: CppRegistry, heapBuffer: ArrayBuffer): this {
+ this.world_.connectCpp(cppRegistry, heapBuffer);
+ return this;
+ }
+
+ /** @brief Update HEAP buffer reference (after WASM memory growth) */
+ updateHeapBuffer(heapBuffer: ArrayBuffer): this {
+ this.world_.updateHeapBuffer(heapBuffer);
+ return this;
+ }
+
+ // =========================================================================
+ // World Access
+ // =========================================================================
+
+ get world(): World {
+ return this.world_;
+ }
+
+ // =========================================================================
+ // Run
+ // =========================================================================
+
+ run(): void {
+ if (this.running_) {
+ return;
+ }
+
+ this.running_ = true;
+ this.runner_ = new SystemRunner(this.world_, this.resources_);
+
+ this.initResource(Time);
+
+ this.sortAllSystems();
+
+ this.runSchedule(Schedule.Startup);
+
+ this.lastTime_ = performance.now();
+ this.mainLoop();
+ }
+
+ private mainLoop = (): void => {
+ 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);
+
+ this.fixedAccumulator_ += delta;
+ while (this.fixedAccumulator_ >= this.fixedTimestep_) {
+ this.runSchedule(Schedule.FixedPreUpdate);
+ this.runSchedule(Schedule.FixedUpdate);
+ this.runSchedule(Schedule.FixedPostUpdate);
+ this.fixedAccumulator_ -= this.fixedTimestep_;
+ }
+
+ requestAnimationFrame(this.mainLoop);
+ };
+
+ quit(): void {
+ this.running_ = false;
+ }
+
+ // =========================================================================
+ // Internal
+ // =========================================================================
+
+ private runSchedule(schedule: Schedule): void {
+ const systems = this.systems_.get(schedule);
+ if (!systems || !this.runner_) {
+ return;
+ }
+
+ for (const entry of systems) {
+ const sys = entry.system as ConditionalSystemDef;
+
+ if (sys._condition && !sys._condition()) {
+ continue;
+ }
+
+ this.runner_.run(entry.system);
+ }
+ }
+
+ private updateTime(delta: number): void {
+ const time = this.resources_.get(Time);
+ const newTime: TimeData = {
+ delta,
+ elapsed: time.elapsed + delta,
+ frameCount: time.frameCount + 1
+ };
+ this.resources_.set(Time, newTime);
+ }
+
+ private sortAllSystems(): void {
+ for (const [_, systems] of this.systems_) {
+ this.sortSystems(systems);
+ }
+ }
+
+ private sortSystems(systems: SystemEntry[]): void {
+ // Simple topological sort based on before/after constraints
+ // For now, just maintain insertion order
+ // TODO: Implement proper topological sort
+ }
+}
diff --git a/sdk/src/framework/builtin.ts b/sdk/src/framework/builtin.ts
new file mode 100644
index 000000000..5613370a2
--- /dev/null
+++ b/sdk/src/framework/builtin.ts
@@ -0,0 +1,189 @@
+/**
+ * @file builtin.ts
+ * @brief Built-in component proxies that bridge to C++ Registry
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Entity, Vec2, Vec3, Vec4, Color, Quat } from './types';
+
+// =============================================================================
+// Built-in Component Marker
+// =============================================================================
+
+export interface BuiltinComponentDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _builtin: true;
+ readonly _cppName: string;
+}
+
+function defineBuiltin<T>(name: string): BuiltinComponentDef<T> {
+ return {
+ _id: Symbol(`Builtin_${name}`),
+ _name: name,
+ _builtin: true,
+ _cppName: name
+ };
+}
+
+// =============================================================================
+// Built-in Component Types
+// =============================================================================
+
+export interface LocalTransformData {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+
+export interface WorldTransformData {
+ matrix: number[];
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+
+export interface SpriteData {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+}
+
+export interface CameraData {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+}
+
+export interface CanvasData {
+ designResolution: Vec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+
+export interface VelocityData {
+ linear: Vec3;
+ angular: Vec3;
+}
+
+export interface ParentData {
+ entity: Entity;
+}
+
+export interface ChildrenData {
+ entities: Entity[];
+}
+
+// =============================================================================
+// Built-in Component Definitions
+// =============================================================================
+
+export const LocalTransform = defineBuiltin<LocalTransformData>('LocalTransform');
+export const WorldTransform = defineBuiltin<WorldTransformData>('WorldTransform');
+export const Sprite = defineBuiltin<SpriteData>('Sprite');
+export const Camera = defineBuiltin<CameraData>('Camera');
+export const Canvas = defineBuiltin<CanvasData>('Canvas');
+export const Velocity = defineBuiltin<VelocityData>('Velocity');
+export const Parent = defineBuiltin<ParentData>('Parent');
+export const Children = defineBuiltin<ChildrenData>('Children');
+
+// =============================================================================
+// Type Helpers
+// =============================================================================
+
+export type BuiltinComponent =
+ | typeof LocalTransform
+ | typeof WorldTransform
+ | typeof Sprite
+ | typeof Camera
+ | typeof Canvas
+ | typeof Velocity
+ | typeof Parent
+ | typeof Children;
+
+export type BuiltinComponentData<C extends BuiltinComponentDef<unknown>> =
+ C extends BuiltinComponentDef<infer T> ? T : never;
+
+export function isBuiltinComponent(comp: unknown): comp is BuiltinComponentDef<unknown> {
+ return typeof comp === 'object' && comp !== null && '_builtin' in comp && comp._builtin === true;
+}
+
+// =============================================================================
+// Default Values
+// =============================================================================
+
+export function getBuiltinDefaults<T>(comp: BuiltinComponentDef<T>): T {
+ switch (comp._cppName) {
+ case 'LocalTransform':
+ return {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 }
+ } as T;
+
+ case 'Sprite':
+ return {
+ texture: 0,
+ 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
+ } as T;
+
+ case 'Camera':
+ return {
+ projectionType: 0,
+ fov: 60,
+ orthoSize: 5,
+ nearPlane: 0.1,
+ farPlane: 1000,
+ aspectRatio: 1.77,
+ isActive: true,
+ priority: 0
+ } as T;
+
+ case 'Canvas':
+ return {
+ designResolution: { x: 1920, y: 1080 },
+ pixelsPerUnit: 100,
+ scaleMode: 0,
+ matchWidthOrHeight: 0.5,
+ backgroundColor: { x: 0, y: 0, z: 0, w: 1 }
+ } as T;
+
+ case 'Velocity':
+ return {
+ linear: { x: 0, y: 0, z: 0 },
+ angular: { x: 0, y: 0, z: 0 }
+ } as T;
+
+ case 'Parent':
+ return { entity: 0 } as T;
+
+ case 'Children':
+ return { entities: [] } as T;
+
+ default:
+ return {} as T;
+ }
+}
diff --git a/sdk/src/framework/commands.ts b/sdk/src/framework/commands.ts
new file mode 100644
index 000000000..bd8a69b06
--- /dev/null
+++ b/sdk/src/framework/commands.ts
@@ -0,0 +1,237 @@
+/**
+ * @file commands.ts
+ * @brief Deferred entity/component operations (spawn, despawn, insert, remove)
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Entity } from '../core/Types';
+import { ComponentDef } from './component';
+import { Schema, InferSchema } from './types';
+import { World, AnyComponentDef } from './world';
+import { ResourceDef, ResourceStorage } from './resource';
+import { BuiltinComponentDef, isBuiltinComponent, getBuiltinDefaults } from './builtin';
+
+// =============================================================================
+// Commands Descriptor (for system parameters)
+// =============================================================================
+
+export interface CommandsDescriptor {
+ readonly _type: 'commands';
+}
+
+export function Commands(): CommandsDescriptor {
+ return { _type: 'commands' };
+}
+
+// =============================================================================
+// Command Types
+// =============================================================================
+
+interface SpawnCommand {
+ type: 'spawn';
+ components: Map<symbol, unknown>;
+ entityRef: { entity: Entity };
+}
+
+interface DespawnCommand {
+ type: 'despawn';
+ entity: Entity;
+}
+
+interface InsertCommand {
+ type: 'insert';
+ entity: Entity;
+ component: AnyComponentDef;
+ data: unknown;
+}
+
+interface RemoveCommand {
+ type: 'remove';
+ entity: Entity;
+ component: AnyComponentDef;
+}
+
+interface InsertResourceCommand {
+ type: 'insert_resource';
+ resource: ResourceDef<unknown>;
+ value: unknown;
+}
+
+interface RemoveResourceCommand {
+ type: 'remove_resource';
+ resource: ResourceDef<unknown>;
+}
+
+type Command =
+ | SpawnCommand
+ | DespawnCommand
+ | InsertCommand
+ | RemoveCommand
+ | InsertResourceCommand
+ | RemoveResourceCommand;
+
+// =============================================================================
+// Entity Commands (Builder for spawning)
+// =============================================================================
+
+export class EntityCommands {
+ private readonly commands_: CommandsInstance;
+ private readonly entityRef_: { entity: Entity };
+ private readonly components_ = new Map<symbol, unknown>();
+ private isNew_: boolean;
+
+ constructor(commands: CommandsInstance, entity: Entity | null) {
+ this.commands_ = commands;
+
+ if (entity === null) {
+ this.entityRef_ = { entity: 0 as Entity };
+ this.isNew_ = true;
+ } else {
+ this.entityRef_ = { entity };
+ this.isNew_ = false;
+ }
+ }
+
+ insert<T extends object>(component: AnyComponentDef, data?: Partial<T>): this {
+ let instance: unknown;
+
+ if (isBuiltinComponent(component)) {
+ const defaults = getBuiltinDefaults(component) as object;
+ instance = { ...defaults, ...(data as object) };
+ } else {
+ instance = (component as ComponentDef<Schema>).create(data as never);
+ }
+
+ if (this.isNew_) {
+ this.components_.set(component._id, instance);
+ } else {
+ this.commands_.queueInsert(this.entityRef_.entity, component, instance);
+ }
+
+ return this;
+ }
+
+ remove(component: AnyComponentDef): this {
+ if (!this.isNew_) {
+ this.commands_.queueRemove(this.entityRef_.entity, component);
+ }
+ return this;
+ }
+
+ id(): Entity {
+ if (this.isNew_ && this.entityRef_.entity === 0) {
+ this.finalize();
+ }
+ return this.entityRef_.entity;
+ }
+
+ private finalize(): void {
+ if (this.isNew_) {
+ this.commands_.queueSpawn(this.components_, this.entityRef_);
+ }
+ }
+}
+
+// =============================================================================
+// Commands Instance (Runtime)
+// =============================================================================
+
+export class CommandsInstance {
+ private readonly world_: World;
+ private readonly resources_: ResourceStorage;
+ private pending_: Command[] = [];
+
+ constructor(world: World, resources: ResourceStorage) {
+ this.world_ = world;
+ this.resources_ = resources;
+ }
+
+ spawn(): EntityCommands {
+ return new EntityCommands(this, null);
+ }
+
+ entity(entity: Entity): EntityCommands {
+ return new EntityCommands(this, entity);
+ }
+
+ despawn(entity: Entity): this {
+ this.pending_.push({ type: 'despawn', entity });
+ return this;
+ }
+
+ insertResource<T>(resource: ResourceDef<T>, value: T): this {
+ this.pending_.push({
+ type: 'insert_resource',
+ resource: resource as ResourceDef<unknown>,
+ value
+ });
+ return this;
+ }
+
+ removeResource<T>(resource: ResourceDef<T>): this {
+ this.pending_.push({
+ type: 'remove_resource',
+ resource: resource as ResourceDef<unknown>
+ });
+ return this;
+ }
+
+ queueSpawn(components: Map<symbol, unknown>, entityRef: { entity: Entity }): void {
+ this.pending_.push({ type: 'spawn', components, entityRef });
+ }
+
+ queueInsert(entity: Entity, component: AnyComponentDef, data: unknown): void {
+ this.pending_.push({ type: 'insert', entity, component, data });
+ }
+
+ queueRemove(entity: Entity, component: AnyComponentDef): void {
+ this.pending_.push({ type: 'remove', entity, component });
+ }
+
+ flush(): void {
+ for (const cmd of this.pending_) {
+ this.executeCommand(cmd);
+ }
+ this.pending_ = [];
+ }
+
+ private executeCommand(cmd: Command): void {
+ switch (cmd.type) {
+ case 'spawn': {
+ const entity = this.world_.spawn();
+ cmd.entityRef.entity = entity;
+
+ for (const [compId, data] of cmd.components) {
+ const key = Symbol.for(compId.toString());
+ this.world_.tsRegistry.emplace(entity, key, data);
+ }
+ break;
+ }
+
+ case 'despawn':
+ this.world_.despawn(cmd.entity);
+ break;
+
+ case 'insert':
+ this.world_.insert(cmd.entity, cmd.component, cmd.data as never);
+ break;
+
+ case 'remove':
+ this.world_.remove(cmd.entity, cmd.component);
+ break;
+
+ case 'insert_resource':
+ this.resources_.insert(cmd.resource, cmd.value);
+ break;
+
+ case 'remove_resource':
+ this.resources_.remove(cmd.resource);
+ break;
+ }
+ }
+}
diff --git a/sdk/src/framework/component.ts b/sdk/src/framework/component.ts
new file mode 100644
index 000000000..0ce88bbd2
--- /dev/null
+++ b/sdk/src/framework/component.ts
@@ -0,0 +1,94 @@
+/**
+ * @file component.ts
+ * @brief Component definition API for the ECS framework
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Schema, InferSchema, computeDefaults } from './types';
+import { SchemaLayout, computeSchemaLayout } from './proxy';
+
+// =============================================================================
+// Component Definition
+// =============================================================================
+
+export interface ComponentDef<S extends Schema = Schema> {
+ readonly _id: symbol;
+ readonly _schema: S;
+ readonly _defaults: InferSchema<S>;
+ readonly _name: string;
+ readonly _layout: SchemaLayout;
+ _cppId: number | null;
+
+ create(data?: Partial<InferSchema<S>>): InferSchema<S>;
+}
+
+let componentCounter = 0;
+
+export function defineComponent<S extends Schema>(
+ schema: S,
+ defaults?: Partial<InferSchema<S>>,
+ name?: string
+): ComponentDef<S> {
+ const counter = ++componentCounter;
+ const id = Symbol(`Component_${counter}`);
+ const computedDefaults = computeDefaults(schema, defaults);
+ const componentName = name ?? `Component_${counter}`;
+ const layout = computeSchemaLayout(schema);
+
+ return {
+ _id: id,
+ _schema: schema,
+ _defaults: computedDefaults,
+ _name: componentName,
+ _layout: layout,
+ _cppId: null,
+
+ create(data?: Partial<InferSchema<S>>): InferSchema<S> {
+ if (!data) {
+ return { ...computedDefaults };
+ }
+ return { ...computedDefaults, ...data };
+ }
+ };
+}
+
+// =============================================================================
+// Tag Component (Marker)
+// =============================================================================
+
+export type TagSchema = Record<string, never>;
+
+export function defineTag(name?: string): ComponentDef<TagSchema> {
+ const counter = ++componentCounter;
+ const id = Symbol(`Tag_${counter}`);
+ const tagName = name ?? `Tag_${counter}`;
+
+ return {
+ _id: id,
+ _schema: {} as TagSchema,
+ _defaults: {} as InferSchema<TagSchema>,
+ _name: tagName,
+ _layout: { fields: {}, stride: 0 },
+ _cppId: null,
+
+ create(): InferSchema<TagSchema> {
+ return {};
+ }
+ };
+}
+
+// =============================================================================
+// Component Instance Type Extraction
+// =============================================================================
+
+export type ComponentInstance<C extends ComponentDef<Schema>> =
+ C extends ComponentDef<infer S> ? InferSchema<S> : never;
+
+export type ComponentInstances<C extends readonly ComponentDef<Schema>[]> = {
+ [K in keyof C]: C[K] extends ComponentDef<infer S> ? InferSchema<S> : never;
+};
diff --git a/sdk/src/framework/index.ts b/sdk/src/framework/index.ts
new file mode 100644
index 000000000..0e592e7ac
--- /dev/null
+++ b/sdk/src/framework/index.ts
@@ -0,0 +1,184 @@
+/**
+ * @file index.ts
+ * @brief Public API exports for the ECS framework
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export {
+ Type,
+ Entity,
+ Vec2,
+ Vec3,
+ Vec4,
+ Color,
+ Quat,
+ INVALID_ENTITY,
+ quat,
+ type Schema,
+ type SchemaType,
+ type InferSchema,
+ type InferType,
+} from './types';
+
+// =============================================================================
+// Component
+// =============================================================================
+
+export {
+ defineComponent,
+ defineTag,
+ type ComponentDef,
+ type ComponentInstance,
+ type ComponentInstances,
+} from './component';
+
+// =============================================================================
+// Proxy (Zero-copy WASM memory access)
+// =============================================================================
+
+export {
+ computeSchemaLayout,
+ createComponentProxy,
+ writeComponentData,
+ type FieldLayout,
+ type SchemaLayout,
+} from './proxy';
+
+// =============================================================================
+// Query
+// =============================================================================
+
+export {
+ Query,
+ With,
+ Without,
+ QueryInstance,
+ type QueryDescriptor,
+ type QueryResult,
+} from './query';
+
+// =============================================================================
+// Resource
+// =============================================================================
+
+export {
+ defineResource,
+ Res,
+ ResMut,
+ ResInstance,
+ ResMutInstance,
+ Time,
+ Input,
+ type ResourceDef,
+ type ResDescriptor,
+ type ResMutDescriptor,
+ type TimeData,
+ type InputState,
+} from './resource';
+
+// =============================================================================
+// Commands
+// =============================================================================
+
+export {
+ Commands,
+ CommandsInstance,
+ EntityCommands,
+ type CommandsDescriptor,
+} from './commands';
+
+// =============================================================================
+// System
+// =============================================================================
+
+export {
+ defineSystem,
+ runIf,
+ type SystemDef,
+ type SystemParam,
+ type InferParam,
+ type InferParams,
+} from './system';
+
+// =============================================================================
+// Schedule
+// =============================================================================
+
+export {
+ Schedule,
+ defineSystemSet,
+ type SystemSet,
+ type SystemOrdering,
+} from './schedule';
+
+// =============================================================================
+// World
+// =============================================================================
+
+export { World } from './world';
+
+// =============================================================================
+// App
+// =============================================================================
+
+export {
+ App,
+ type Plugin,
+ type AppConfig,
+} from './app';
+
+// =============================================================================
+// Builtin Components (C++ backed)
+// =============================================================================
+
+export {
+ LocalTransform,
+ WorldTransform,
+ Sprite,
+ Camera,
+ Canvas,
+ Velocity,
+ Parent,
+ Children,
+ isBuiltinComponent,
+ type BuiltinComponentDef,
+ type LocalTransformData,
+ type SpriteData,
+ type CameraData,
+ type CanvasData,
+ type VelocityData,
+} from './builtin';
+
+// =============================================================================
+// Plugins
+// =============================================================================
+
+export {
+ DefaultPlugins,
+ TimePlugin,
+ InputPlugin,
+} from './plugins/default';
+
+export {
+ createWasmPlugin,
+ loadWasmModule,
+ WasmModule,
+ Assets,
+ type WasmPluginOptions,
+ type WasmModuleData,
+} from './plugins/wasm';
+
+// =============================================================================
+// C++ Integration
+// =============================================================================
+
+export type { CppRegistry, AnyComponentDef } from './world';
diff --git a/sdk/src/framework/plugins/default.ts b/sdk/src/framework/plugins/default.ts
new file mode 100644
index 000000000..1bce09f5b
--- /dev/null
+++ b/sdk/src/framework/plugins/default.ts
@@ -0,0 +1,95 @@
+/**
+ * @file default.ts
+ * @brief Default plugins for common functionality (Time, Input)
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { App, Plugin } from '../app';
+import { Time, Input, InputState } from '../resource';
+
+// =============================================================================
+// Time Plugin
+// =============================================================================
+
+export const TimePlugin: Plugin = {
+ build(app: App): void {
+ app.initResource(Time);
+ }
+};
+
+// =============================================================================
+// Input Plugin
+// =============================================================================
+
+export const InputPlugin: Plugin = {
+ build(app: App): void {
+ const inputState: InputState = {
+ keysDown: new Set(),
+ keysPressed: new Set(),
+ keysReleased: new Set(),
+ mouseX: 0,
+ mouseY: 0,
+ mouseButtons: new Set()
+ };
+
+ app.insertResource(Input, inputState);
+
+ if (typeof window !== 'undefined') {
+ setupInputListeners(app, inputState);
+ }
+ }
+};
+
+function setupInputListeners(app: App, state: InputState): void {
+ window.addEventListener('keydown', (e) => {
+ if (!state.keysDown.has(e.code)) {
+ state.keysPressed.add(e.code);
+ }
+ state.keysDown.add(e.code);
+ });
+
+ window.addEventListener('keyup', (e) => {
+ state.keysDown.delete(e.code);
+ state.keysReleased.add(e.code);
+ });
+
+ window.addEventListener('mousemove', (e) => {
+ state.mouseX = e.clientX;
+ state.mouseY = e.clientY;
+ });
+
+ window.addEventListener('mousedown', (e) => {
+ state.mouseButtons.add(e.button);
+ });
+
+ window.addEventListener('mouseup', (e) => {
+ state.mouseButtons.delete(e.button);
+ });
+}
+
+// =============================================================================
+// Frame Cleanup Plugin
+// =============================================================================
+
+export const FrameCleanupPlugin: Plugin = {
+ build(app: App): void {
+ // Clear per-frame input state at the end of each frame
+ // This would need access to the input resource
+ }
+};
+
+// =============================================================================
+// Default Plugins Bundle
+// =============================================================================
+
+export const DefaultPlugins: Plugin = {
+ build(app: App): void {
+ app.addPlugin(TimePlugin);
+ app.addPlugin(InputPlugin);
+ }
+};
diff --git a/sdk/src/framework/plugins/wasm.ts b/sdk/src/framework/plugins/wasm.ts
new file mode 100644
index 000000000..25f5ae446
--- /dev/null
+++ b/sdk/src/framework/plugins/wasm.ts
@@ -0,0 +1,97 @@
+/**
+ * @file wasm.ts
+ * @brief Plugin for connecting to C++ WASM module
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import type { ESEngineModule, CppApp, CppRegistry, CppResourceManager } from '../../wasm/types';
+import { App, Plugin } from '../app';
+import { defineResource, ResourceDef } from '../resource';
+import { AssetLoader } from '../../assets/AssetLoader';
+
+// =============================================================================
+// WASM Resources
+// =============================================================================
+
+export interface WasmModuleData {
+ module: ESEngineModule;
+ cppApp: CppApp;
+ resourceManager: CppResourceManager;
+ assetLoader: AssetLoader;
+}
+
+export const WasmModule = defineResource<WasmModuleData | null>(null, 'WasmModule');
+
+export const Assets = defineResource<AssetLoader | null>(null, 'Assets');
+
+// =============================================================================
+// WASM Plugin Options
+// =============================================================================
+
+export interface WasmPluginOptions {
+ module: ESEngineModule;
+ config?: {
+ title?: string;
+ width?: number;
+ height?: number;
+ vsync?: boolean;
+ };
+}
+
+// =============================================================================
+// WASM Plugin
+// =============================================================================
+
+export function createWasmPlugin(options: WasmPluginOptions): Plugin {
+ return {
+ build(app: App): void {
+ const { module, config } = options;
+
+ let cppApp: CppApp;
+ if (config) {
+ const cppConfig = new module.AppConfig();
+ cppConfig.title = config.title ?? 'ESEngine';
+ cppConfig.width = config.width ?? 800;
+ cppConfig.height = config.height ?? 600;
+ cppConfig.vsync = config.vsync ?? true;
+ cppApp = module.createAppWithConfig(cppConfig);
+ } else {
+ cppApp = module.createApp();
+ }
+
+ const cppRegistry = cppApp.registry();
+ const resourceManager = new module.ResourceManager();
+ resourceManager.init();
+
+ const assetLoader = new AssetLoader(module, resourceManager);
+
+ app.connectCpp(
+ cppRegistry as unknown as import('../world').CppRegistry,
+ module.HEAPU8.buffer as ArrayBuffer
+ );
+
+ app.insertResource(WasmModule, {
+ module,
+ cppApp,
+ resourceManager,
+ assetLoader
+ });
+
+ app.insertResource(Assets, assetLoader);
+ }
+ };
+}
+
+// =============================================================================
+// Helper Functions
+// =============================================================================
+
+export async function loadWasmModule(path: string): Promise<ESEngineModule> {
+ const createModule = (await import(path)).default as () => Promise<ESEngineModule>;
+ return createModule();
+}
diff --git a/sdk/src/framework/proxy.ts b/sdk/src/framework/proxy.ts
new file mode 100644
index 000000000..04035e88d
--- /dev/null
+++ b/sdk/src/framework/proxy.ts
@@ -0,0 +1,248 @@
+/**
+ * @file proxy.ts
+ * @brief Component proxy for zero-copy WASM memory access
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Schema, SchemaType, InferSchema } from './types';
+
+// =============================================================================
+// Type Size Constants
+// =============================================================================
+
+const TYPE_SIZES: Record<string, number> = {
+ f32: 4,
+ f64: 8,
+ i32: 4,
+ u32: 4,
+ bool: 1,
+ Vec2: 8, // 2 * f32
+ Vec3: 12, // 3 * f32
+ Vec4: 16, // 4 * f32
+ Color: 16, // 4 * f32
+ Quat: 16, // 4 * f32
+ Entity: 4, // u32
+ String: 4, // pointer (not fully supported yet)
+};
+
+// =============================================================================
+// Schema Layout
+// =============================================================================
+
+export interface FieldLayout {
+ offset: number;
+ size: number;
+ type: string;
+}
+
+export interface SchemaLayout {
+ fields: Record<string, FieldLayout>;
+ stride: number;
+}
+
+export function computeSchemaLayout<S extends Schema>(schema: S): SchemaLayout {
+ const fields: Record<string, FieldLayout> = {};
+ let offset = 0;
+
+ for (const key in schema) {
+ const type = schema[key] as SchemaType;
+ const tag = type._tag;
+ const size = TYPE_SIZES[tag] ?? 4;
+
+ // Align to natural boundary
+ const alignment = Math.min(size, 4);
+ offset = Math.ceil(offset / alignment) * alignment;
+
+ fields[key] = { offset, size, type: tag };
+ offset += size;
+ }
+
+ // Align stride to 4 bytes
+ const stride = Math.ceil(offset / 4) * 4;
+
+ return { fields, stride };
+}
+
+// =============================================================================
+// Component Proxy
+// =============================================================================
+
+/**
+ * @brief Proxy for direct memory access to component data
+ *
+ * @details Creates property getters/setters that read/write directly
+ * to WASM linear memory without crossing the JS/WASM boundary.
+ */
+export function createComponentProxy<S extends Schema>(
+ layout: SchemaLayout,
+ heapBuffer: ArrayBuffer,
+ byteOffset: number
+): InferSchema<S> {
+ const view = new DataView(heapBuffer, byteOffset, layout.stride);
+ const proxy: Record<string, unknown> = {};
+
+ for (const [key, field] of Object.entries(layout.fields)) {
+ switch (field.type) {
+ case 'f32':
+ Object.defineProperty(proxy, key, {
+ get: () => view.getFloat32(field.offset, true),
+ set: (v: number) => view.setFloat32(field.offset, v, true),
+ enumerable: true,
+ });
+ break;
+
+ case 'f64':
+ Object.defineProperty(proxy, key, {
+ get: () => view.getFloat64(field.offset, true),
+ set: (v: number) => view.setFloat64(field.offset, v, true),
+ enumerable: true,
+ });
+ break;
+
+ case 'i32':
+ Object.defineProperty(proxy, key, {
+ get: () => view.getInt32(field.offset, true),
+ set: (v: number) => view.setInt32(field.offset, v, true),
+ enumerable: true,
+ });
+ break;
+
+ case 'u32':
+ case 'Entity':
+ Object.defineProperty(proxy, key, {
+ get: () => view.getUint32(field.offset, true),
+ set: (v: number) => view.setUint32(field.offset, v, true),
+ enumerable: true,
+ });
+ break;
+
+ case 'bool':
+ Object.defineProperty(proxy, key, {
+ get: () => view.getUint8(field.offset) !== 0,
+ set: (v: boolean) => view.setUint8(field.offset, v ? 1 : 0),
+ enumerable: true,
+ });
+ break;
+
+ case 'Vec2':
+ Object.defineProperty(proxy, key, {
+ get: () => ({
+ x: view.getFloat32(field.offset, true),
+ y: view.getFloat32(field.offset + 4, true),
+ }),
+ set: (v: { x: number; y: number }) => {
+ view.setFloat32(field.offset, v.x, true);
+ view.setFloat32(field.offset + 4, v.y, true);
+ },
+ enumerable: true,
+ });
+ break;
+
+ case 'Vec3':
+ Object.defineProperty(proxy, key, {
+ get: () => ({
+ x: view.getFloat32(field.offset, true),
+ y: view.getFloat32(field.offset + 4, true),
+ z: view.getFloat32(field.offset + 8, true),
+ }),
+ set: (v: { x: number; y: number; z: number }) => {
+ view.setFloat32(field.offset, v.x, true);
+ view.setFloat32(field.offset + 4, v.y, true);
+ view.setFloat32(field.offset + 8, v.z, true);
+ },
+ enumerable: true,
+ });
+ break;
+
+ case 'Vec4':
+ case 'Color':
+ case 'Quat':
+ Object.defineProperty(proxy, key, {
+ get: () => ({
+ x: view.getFloat32(field.offset, true),
+ y: view.getFloat32(field.offset + 4, true),
+ z: view.getFloat32(field.offset + 8, true),
+ w: view.getFloat32(field.offset + 12, true),
+ }),
+ set: (v: { x: number; y: number; z: number; w: number }) => {
+ view.setFloat32(field.offset, v.x, true);
+ view.setFloat32(field.offset + 4, v.y, true);
+ view.setFloat32(field.offset + 8, v.z, true);
+ view.setFloat32(field.offset + 12, v.w, true);
+ },
+ enumerable: true,
+ });
+ break;
+ }
+ }
+
+ return proxy as InferSchema<S>;
+}
+
+// =============================================================================
+// Component Writer
+// =============================================================================
+
+/**
+ * @brief Writes initial component data to WASM memory
+ */
+export function writeComponentData<S extends Schema>(
+ layout: SchemaLayout,
+ heapBuffer: ArrayBuffer,
+ byteOffset: number,
+ data: Partial<InferSchema<S>>
+): void {
+ const view = new DataView(heapBuffer, byteOffset, layout.stride);
+
+ for (const [key, field] of Object.entries(layout.fields)) {
+ const value = (data as Record<string, unknown>)[key];
+ if (value === undefined) continue;
+
+ switch (field.type) {
+ case 'f32':
+ view.setFloat32(field.offset, value as number, true);
+ break;
+ case 'f64':
+ view.setFloat64(field.offset, value as number, true);
+ break;
+ case 'i32':
+ view.setInt32(field.offset, value as number, true);
+ break;
+ case 'u32':
+ case 'Entity':
+ view.setUint32(field.offset, value as number, true);
+ break;
+ case 'bool':
+ view.setUint8(field.offset, (value as boolean) ? 1 : 0);
+ break;
+ case 'Vec2': {
+ const v = value as { x: number; y: number };
+ view.setFloat32(field.offset, v.x, true);
+ view.setFloat32(field.offset + 4, v.y, true);
+ break;
+ }
+ case 'Vec3': {
+ const v = value as { x: number; y: number; z: number };
+ view.setFloat32(field.offset, v.x, true);
+ view.setFloat32(field.offset + 4, v.y, true);
+ view.setFloat32(field.offset + 8, v.z, true);
+ break;
+ }
+ case 'Vec4':
+ case 'Color':
+ case 'Quat': {
+ const v = value as { x: number; y: number; z: number; w: number };
+ view.setFloat32(field.offset, v.x, true);
+ view.setFloat32(field.offset + 4, v.y, true);
+ view.setFloat32(field.offset + 8, v.z, true);
+ view.setFloat32(field.offset + 12, v.w, true);
+ break;
+ }
+ }
+ }
+}
diff --git a/sdk/src/framework/query.ts b/sdk/src/framework/query.ts
new file mode 100644
index 000000000..ee793dd86
--- /dev/null
+++ b/sdk/src/framework/query.ts
@@ -0,0 +1,179 @@
+/**
+ * @file query.ts
+ * @brief Query system supporting both builtin and script components
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Entity } from '../core/Types';
+import { ComponentDef } from './component';
+import { Schema, InferSchema } from './types';
+import { World, AnyComponentDef } from './world';
+import { BuiltinComponentDef } from './builtin';
+
+// =============================================================================
+// Component Data Type Inference
+// =============================================================================
+
+type ComponentData<C> =
+ C extends BuiltinComponentDef<infer T> ? T :
+ C extends ComponentDef<infer S> ? InferSchema<S> :
+ never;
+
+type ComponentsData<C extends readonly AnyComponentDef[]> = {
+ [K in keyof C]: ComponentData<C[K]>;
+};
+
+// =============================================================================
+// Query Descriptor
+// =============================================================================
+
+export interface QueryDescriptor<C extends readonly AnyComponentDef[]> {
+ readonly _type: 'query';
+ readonly _components: C;
+ readonly _with: AnyComponentDef[];
+ readonly _without: AnyComponentDef[];
+
+ with<W extends AnyComponentDef[]>(...components: W): QueryDescriptor<C>;
+ without<W extends AnyComponentDef[]>(...components: W): QueryDescriptor<C>;
+}
+
+function createQueryDescriptor<C extends readonly AnyComponentDef[]>(
+ components: C,
+ withFilters: AnyComponentDef[] = [],
+ withoutFilters: AnyComponentDef[] = []
+): QueryDescriptor<C> {
+ return {
+ _type: 'query',
+ _components: components,
+ _with: withFilters,
+ _without: withoutFilters,
+
+ with<W extends AnyComponentDef[]>(...comps: W): QueryDescriptor<C> {
+ return createQueryDescriptor(
+ components,
+ [...withFilters, ...comps],
+ withoutFilters
+ );
+ },
+
+ without<W extends AnyComponentDef[]>(...comps: W): QueryDescriptor<C> {
+ return createQueryDescriptor(
+ components,
+ withFilters,
+ [...withoutFilters, ...comps]
+ );
+ }
+ };
+}
+
+// =============================================================================
+// Query Factory
+// =============================================================================
+
+export function Query<C extends AnyComponentDef[]>(...components: C): QueryDescriptor<C> {
+ return createQueryDescriptor(components);
+}
+
+// =============================================================================
+// Query Result Type
+// =============================================================================
+
+export type QueryResult<C extends readonly AnyComponentDef[]> = [
+ Entity,
+ ...ComponentsData<C>
+];
+
+// =============================================================================
+// Query Instance
+// =============================================================================
+
+export class QueryInstance<C extends readonly AnyComponentDef[]> implements Iterable<QueryResult<C>> {
+ private readonly world_: World;
+ private readonly descriptor_: QueryDescriptor<C>;
+
+ constructor(world: World, descriptor: QueryDescriptor<C>) {
+ this.world_ = world;
+ this.descriptor_ = descriptor;
+ }
+
+ *[Symbol.iterator](): Iterator<QueryResult<C>> {
+ const { _components, _with, _without } = this.descriptor_;
+
+ const allRequired = [..._components, ..._with];
+ const entities = this.world_.getEntitiesWithComponents(allRequired);
+
+ for (const entity of entities) {
+ let excluded = false;
+ for (const comp of _without) {
+ if (this.world_.has(entity, comp)) {
+ excluded = true;
+ break;
+ }
+ }
+
+ if (excluded) continue;
+
+ const components = _components.map(comp =>
+ this.world_.getComponent(entity, comp)
+ ) as ComponentsData<C>;
+
+ yield [entity, ...components] as QueryResult<C>;
+ }
+ }
+
+ forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void {
+ for (const [entity, ...components] of this) {
+ callback(entity, ...(components as ComponentsData<C>));
+ }
+ }
+
+ single(): QueryResult<C> | null {
+ for (const result of this) {
+ return result;
+ }
+ return null;
+ }
+
+ isEmpty(): boolean {
+ return this.single() === null;
+ }
+
+ count(): number {
+ let n = 0;
+ for (const _ of this) {
+ n++;
+ }
+ return n;
+ }
+
+ toArray(): QueryResult<C>[] {
+ return [...this];
+ }
+}
+
+// =============================================================================
+// Filter Helpers
+// =============================================================================
+
+export interface WithFilter<C extends AnyComponentDef[]> {
+ readonly _filter: 'with';
+ readonly _components: C;
+}
+
+export interface WithoutFilter<C extends AnyComponentDef[]> {
+ readonly _filter: 'without';
+ readonly _components: C;
+}
+
+export function With<C extends AnyComponentDef[]>(...components: C): WithFilter<C> {
+ return { _filter: 'with', _components: components };
+}
+
+export function Without<C extends AnyComponentDef[]>(...components: C): WithoutFilter<C> {
+ return { _filter: 'without', _components: components };
+}
diff --git a/sdk/src/framework/resource.ts b/sdk/src/framework/resource.ts
new file mode 100644
index 000000000..217656647
--- /dev/null
+++ b/sdk/src/framework/resource.ts
@@ -0,0 +1,165 @@
+/**
+ * @file resource.ts
+ * @brief Global resources (singletons) for the ECS framework
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+// =============================================================================
+// Resource Definition
+// =============================================================================
+
+export interface ResourceDef<T> {
+ readonly _id: symbol;
+ readonly _default: T;
+ readonly _name: string;
+}
+
+let resourceCounter = 0;
+
+export function defineResource<T>(defaultValue: T, name?: string): ResourceDef<T> {
+ const id = ++resourceCounter;
+ return {
+ _id: Symbol(`Resource_${id}_${name ?? ''}`),
+ _default: defaultValue,
+ _name: name ?? `Resource_${id}`
+ };
+}
+
+// =============================================================================
+// Resource Descriptors (for system parameters)
+// =============================================================================
+
+export interface ResDescriptor<T> {
+ readonly _type: 'res';
+ readonly _resource: ResourceDef<T>;
+}
+
+export interface ResMutDescriptor<T> {
+ readonly _type: 'res_mut';
+ readonly _resource: ResourceDef<T>;
+}
+
+export function Res<T>(resource: ResourceDef<T>): ResDescriptor<T> {
+ return { _type: 'res', _resource: resource };
+}
+
+export function ResMut<T>(resource: ResourceDef<T>): ResMutDescriptor<T> {
+ return { _type: 'res_mut', _resource: resource };
+}
+
+// =============================================================================
+// Resource Instances (Runtime)
+// =============================================================================
+
+export class ResInstance<T> {
+ constructor(private readonly value_: T) {}
+
+ get(): T {
+ return this.value_;
+ }
+}
+
+export class ResMutInstance<T> {
+ private value_: T;
+ private readonly setter_: (v: T) => void;
+
+ constructor(value: T, setter: (v: T) => void) {
+ this.value_ = value;
+ this.setter_ = setter;
+ }
+
+ get(): T {
+ return this.value_;
+ }
+
+ set(value: T): void {
+ this.value_ = value;
+ this.setter_(value);
+ }
+
+ modify(fn: (value: T) => void): void {
+ fn(this.value_);
+ this.setter_(this.value_);
+ }
+}
+
+// =============================================================================
+// Resource Storage
+// =============================================================================
+
+export class ResourceStorage {
+ private resources_ = new Map<symbol, unknown>();
+
+ insert<T>(resource: ResourceDef<T>, value: T): void {
+ this.resources_.set(resource._id, value);
+ }
+
+ get<T>(resource: ResourceDef<T>): T {
+ if (!this.resources_.has(resource._id)) {
+ this.resources_.set(resource._id, resource._default);
+ }
+ return this.resources_.get(resource._id) as T;
+ }
+
+ set<T>(resource: ResourceDef<T>, value: T): void {
+ this.resources_.set(resource._id, value);
+ }
+
+ has<T>(resource: ResourceDef<T>): boolean {
+ return this.resources_.has(resource._id);
+ }
+
+ remove<T>(resource: ResourceDef<T>): void {
+ this.resources_.delete(resource._id);
+ }
+
+ getRes<T>(resource: ResourceDef<T>): ResInstance<T> {
+ return new ResInstance(this.get(resource));
+ }
+
+ getResMut<T>(resource: ResourceDef<T>): ResMutInstance<T> {
+ return new ResMutInstance(
+ this.get(resource),
+ (v) => this.set(resource, v)
+ );
+ }
+}
+
+// =============================================================================
+// Built-in Resources
+// =============================================================================
+
+export interface TimeData {
+ delta: number;
+ elapsed: number;
+ frameCount: number;
+}
+
+export const Time = defineResource<TimeData>({
+ delta: 0,
+ elapsed: 0,
+ frameCount: 0
+}, 'Time');
+
+export interface InputState {
+ keysDown: Set<string>;
+ keysPressed: Set<string>;
+ keysReleased: Set<string>;
+ mouseX: number;
+ mouseY: number;
+ mouseButtons: Set<number>;
+}
+
+export const Input = defineResource<InputState>({
+ keysDown: new Set(),
+ keysPressed: new Set(),
+ keysReleased: new Set(),
+ mouseX: 0,
+ mouseY: 0,
+ mouseButtons: new Set()
+}, 'Input');
diff --git a/sdk/src/framework/schedule.ts b/sdk/src/framework/schedule.ts
new file mode 100644
index 000000000..aaf22e372
--- /dev/null
+++ b/sdk/src/framework/schedule.ts
@@ -0,0 +1,56 @@
+/**
+ * @file schedule.ts
+ * @brief System scheduling phases for the ECS framework
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+// =============================================================================
+// Schedule Phases
+// =============================================================================
+
+export enum Schedule {
+ Startup = 0,
+
+ First = 1,
+ PreUpdate = 2,
+ Update = 3,
+ PostUpdate = 4,
+ Last = 5,
+
+ FixedPreUpdate = 10,
+ FixedUpdate = 11,
+ FixedPostUpdate = 12,
+}
+
+// =============================================================================
+// System Set
+// =============================================================================
+
+export interface SystemSet {
+ readonly _id: symbol;
+ readonly _name: string;
+}
+
+let systemSetCounter = 0;
+
+export function defineSystemSet(name: string): SystemSet {
+ return {
+ _id: Symbol(`SystemSet_${++systemSetCounter}_${name}`),
+ _name: name
+ };
+}
+
+// =============================================================================
+// System Ordering
+// =============================================================================
+
+export interface SystemOrdering {
+ before?: SystemSet;
+ after?: SystemSet;
+ inSet?: SystemSet;
+}
diff --git a/sdk/src/framework/system.ts b/sdk/src/framework/system.ts
new file mode 100644
index 000000000..7e47419b9
--- /dev/null
+++ b/sdk/src/framework/system.ts
@@ -0,0 +1,130 @@
+/**
+ * @file system.ts
+ * @brief System definition API with parameter injection
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { QueryDescriptor, QueryInstance } from './query';
+import { ResDescriptor, ResMutDescriptor, ResInstance, ResMutInstance, ResourceStorage } from './resource';
+import { CommandsDescriptor, CommandsInstance } from './commands';
+import { World, AnyComponentDef } from './world';
+
+// =============================================================================
+// System Parameter Types
+// =============================================================================
+
+export type SystemParam =
+ | QueryDescriptor<readonly AnyComponentDef[]>
+ | ResDescriptor<unknown>
+ | ResMutDescriptor<unknown>
+ | CommandsDescriptor;
+
+// =============================================================================
+// Parameter Type Inference
+// =============================================================================
+
+export type InferParam<P> =
+ P extends QueryDescriptor<infer C> ? QueryInstance<C> :
+ P extends ResDescriptor<infer T> ? T :
+ P extends ResMutDescriptor<infer T> ? ResMutInstance<T> :
+ P extends CommandsDescriptor ? CommandsInstance :
+ never;
+
+export type InferParams<P extends readonly SystemParam[]> = {
+ [K in keyof P]: InferParam<P[K]>;
+};
+
+// =============================================================================
+// System Definition
+// =============================================================================
+
+export interface SystemDef {
+ readonly _id: symbol;
+ readonly _params: readonly SystemParam[];
+ readonly _fn: (...args: unknown[]) => void;
+ readonly _name: string;
+}
+
+let systemCounter = 0;
+
+export function defineSystem<P extends readonly SystemParam[]>(
+ params: [...P],
+ fn: (...args: InferParams<P>) => void,
+ options?: { name?: string }
+): SystemDef {
+ const id = ++systemCounter;
+
+ return {
+ _id: Symbol(`System_${id}_${options?.name ?? ''}`),
+ _params: params,
+ _fn: fn as (...args: unknown[]) => void,
+ _name: options?.name ?? `System_${id}`
+ };
+}
+
+// =============================================================================
+// System Runner
+// =============================================================================
+
+export class SystemRunner {
+ private readonly world_: World;
+ private readonly resources_: ResourceStorage;
+
+ constructor(world: World, resources: ResourceStorage) {
+ this.world_ = world;
+ this.resources_ = resources;
+ }
+
+ run(system: SystemDef): void {
+ const args = system._params.map(param => this.resolveParam(param));
+
+ system._fn(...args);
+
+ for (const arg of args) {
+ if (arg instanceof CommandsInstance) {
+ arg.flush();
+ }
+ }
+ }
+
+ private resolveParam(param: SystemParam): unknown {
+ 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`);
+ }
+ }
+}
+
+// =============================================================================
+// System Condition
+// =============================================================================
+
+export type SystemCondition = () => boolean;
+
+export interface ConditionalSystemDef extends SystemDef {
+ readonly _condition?: SystemCondition;
+}
+
+export function runIf(condition: SystemCondition, system: SystemDef): ConditionalSystemDef {
+ return {
+ ...system,
+ _condition: condition
+ };
+}
diff --git a/sdk/src/framework/types.ts b/sdk/src/framework/types.ts
new file mode 100644
index 000000000..7fb1ffa4b
--- /dev/null
+++ b/sdk/src/framework/types.ts
@@ -0,0 +1,142 @@
+/**
+ * @file types.ts
+ * @brief Type system for component schema definitions
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Entity, Vec2, Vec3, Vec4, Color, INVALID_ENTITY } from '../core/Types';
+
+export { Entity, Vec2, Vec3, Vec4, Color, INVALID_ENTITY };
+
+// =============================================================================
+// Quaternion
+// =============================================================================
+
+export interface Quat {
+ x: number;
+ y: number;
+ z: number;
+ w: number;
+}
+
+export function quat(x: number = 0, y: number = 0, z: number = 0, w: number = 1): Quat {
+ return { x, y, z, w };
+}
+
+// =============================================================================
+// Type Markers
+// =============================================================================
+
+type TypeTag =
+ | 'f32' | 'f64' | 'i32' | 'u32' | 'bool'
+ | 'Vec2' | 'Vec3' | 'Vec4' | 'Color' | 'Quat'
+ | 'Entity' | 'String';
+
+interface TypeMarker<T extends TypeTag> {
+ readonly _tag: T;
+}
+
+// =============================================================================
+// Type Constants
+// =============================================================================
+
+export const Type = {
+ f32: { _tag: 'f32' } as TypeMarker<'f32'>,
+ f64: { _tag: 'f64' } as TypeMarker<'f64'>,
+ i32: { _tag: 'i32' } as TypeMarker<'i32'>,
+ u32: { _tag: 'u32' } as TypeMarker<'u32'>,
+ bool: { _tag: 'bool' } as TypeMarker<'bool'>,
+ Vec2: { _tag: 'Vec2' } as TypeMarker<'Vec2'>,
+ Vec3: { _tag: 'Vec3' } as TypeMarker<'Vec3'>,
+ Vec4: { _tag: 'Vec4' } as TypeMarker<'Vec4'>,
+ Color: { _tag: 'Color' } as TypeMarker<'Color'>,
+ Quat: { _tag: 'Quat' } as TypeMarker<'Quat'>,
+ Entity: { _tag: 'Entity' } as TypeMarker<'Entity'>,
+ String: { _tag: 'String' } as TypeMarker<'String'>,
+} as const;
+
+// =============================================================================
+// Schema Types
+// =============================================================================
+
+export type SchemaType = TypeMarker<TypeTag>;
+
+export type Schema = Record<string, SchemaType>;
+
+// =============================================================================
+// Type Inference
+// =============================================================================
+
+export type InferType<T extends SchemaType> =
+ T extends TypeMarker<'f32'> ? number :
+ T extends TypeMarker<'f64'> ? number :
+ T extends TypeMarker<'i32'> ? number :
+ T extends TypeMarker<'u32'> ? number :
+ T extends TypeMarker<'bool'> ? boolean :
+ T extends TypeMarker<'Vec2'> ? Vec2 :
+ T extends TypeMarker<'Vec3'> ? Vec3 :
+ T extends TypeMarker<'Vec4'> ? Vec4 :
+ T extends TypeMarker<'Color'> ? Color :
+ T extends TypeMarker<'Quat'> ? Quat :
+ T extends TypeMarker<'Entity'> ? Entity :
+ T extends TypeMarker<'String'> ? string :
+ never;
+
+export type InferSchema<S extends Schema> = {
+ [K in keyof S]: InferType<S[K]>;
+};
+
+// =============================================================================
+// Default Values
+// =============================================================================
+
+export function getDefaultValue(type: SchemaType): unknown {
+ switch (type._tag) {
+ case 'f32':
+ case 'f64':
+ case 'i32':
+ case 'u32':
+ return 0;
+ case 'bool':
+ return false;
+ case 'Vec2':
+ return { x: 0, y: 0 };
+ case 'Vec3':
+ return { x: 0, y: 0, z: 0 };
+ case 'Vec4':
+ return { x: 0, y: 0, z: 0, w: 0 };
+ case 'Color':
+ return { r: 1, g: 1, b: 1, a: 1 };
+ case 'Quat':
+ return { x: 0, y: 0, z: 0, w: 1 };
+ case 'Entity':
+ return INVALID_ENTITY;
+ case 'String':
+ return '';
+ default:
+ return undefined;
+ }
+}
+
+export function computeDefaults<S extends Schema>(
+ schema: S,
+ overrides?: Partial<InferSchema<S>>
+): InferSchema<S> {
+ const result = {} as InferSchema<S>;
+
+ for (const key in schema) {
+ const override = overrides?.[key as keyof typeof overrides];
+ if (override !== undefined) {
+ (result as Record<string, unknown>)[key] = override;
+ } else {
+ (result as Record<string, unknown>)[key] = getDefaultValue(schema[key]);
+ }
+ }
+
+ return result;
+}
diff --git a/sdk/src/framework/world.ts b/sdk/src/framework/world.ts
new file mode 100644
index 000000000..61711db71
--- /dev/null
+++ b/sdk/src/framework/world.ts
@@ -0,0 +1,397 @@
+/**
+ * @file world.ts
+ * @brief ECS World with dual Registry support (C++ builtin + TS script)
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Entity } from '../core/Types';
+import { Registry } from '../ecs/Registry';
+import { ComponentDef } from './component';
+import { Schema, InferSchema } from './types';
+import { BuiltinComponentDef, isBuiltinComponent, getBuiltinDefaults } from './builtin';
+import { createComponentProxy, writeComponentData } from './proxy';
+
+// =============================================================================
+// C++ Registry Interface
+// =============================================================================
+
+export interface CppRegistry {
+ create(): Entity;
+ destroy(entity: Entity): void;
+ valid(entity: Entity): boolean;
+
+ addLocalTransform(entity: Entity, data: unknown): void;
+ getLocalTransform(entity: Entity): unknown;
+ hasLocalTransform(entity: Entity): boolean;
+ removeLocalTransform(entity: Entity): void;
+
+ addSprite(entity: Entity, data: unknown): void;
+ getSprite(entity: Entity): unknown;
+ hasSprite(entity: Entity): boolean;
+ removeSprite(entity: Entity): void;
+
+ addCamera(entity: Entity, data: unknown): void;
+ getCamera(entity: Entity): unknown;
+ hasCamera(entity: Entity): boolean;
+ removeCamera(entity: Entity): void;
+
+ addCanvas(entity: Entity, data: unknown): void;
+ getCanvas(entity: Entity): unknown;
+ hasCanvas(entity: Entity): boolean;
+ removeCanvas(entity: Entity): void;
+
+ addVelocity(entity: Entity, data: unknown): void;
+ getVelocity(entity: Entity): unknown;
+ hasVelocity(entity: Entity): boolean;
+ removeVelocity(entity: Entity): void;
+
+ // Schema Components (Script-defined, direct memory access)
+ registerSchemaPool(name: string, stride: number): number;
+ getSchemaPoolId(name: string): number;
+ addSchemaComponent(poolId: number, entity: Entity): number;
+ hasSchemaComponent(poolId: number, entity: Entity): boolean;
+ getSchemaComponentOffset(poolId: number, entity: Entity): number;
+ removeSchemaComponent(poolId: number, entity: Entity): void;
+ getSchemaPoolBasePtr(poolId: number): number;
+ getSchemaPoolStride(poolId: number): number;
+ querySchema(poolId: number): Entity[];
+
+ [key: string]: unknown;
+}
+
+// =============================================================================
+// Any Component Type
+// =============================================================================
+
+export type AnyComponentDef = ComponentDef<Schema> | BuiltinComponentDef<unknown>;
+
+// =============================================================================
+// World
+// =============================================================================
+
+export class World {
+ private tsRegistry_: Registry;
+ private cppRegistry_: CppRegistry | null = null;
+ private heapBuffer_: ArrayBuffer | null = null;
+ private componentKeys_ = new Map<symbol, symbol>();
+ private entities_ = new Set<Entity>();
+
+ constructor() {
+ this.tsRegistry_ = new Registry();
+ }
+
+ /** @brief Connect to C++ Registry (called by App) */
+ connectCpp(cppRegistry: CppRegistry, heapBuffer: ArrayBuffer): void {
+ this.cppRegistry_ = cppRegistry;
+ this.heapBuffer_ = heapBuffer;
+ }
+
+ /** @brief Check if C++ Registry is connected */
+ get hasCpp(): boolean {
+ return this.cppRegistry_ !== null;
+ }
+
+ /** @brief Update HEAP buffer reference (needed after WASM memory growth) */
+ updateHeapBuffer(heapBuffer: ArrayBuffer): void {
+ this.heapBuffer_ = heapBuffer;
+ }
+
+ // =========================================================================
+ // Entity Management
+ // =========================================================================
+
+ spawn(): Entity {
+ let entity: Entity;
+
+ if (this.cppRegistry_) {
+ entity = this.cppRegistry_.create();
+ } else {
+ entity = this.tsRegistry_.create();
+ }
+
+ this.entities_.add(entity);
+ return entity;
+ }
+
+ despawn(entity: Entity): void {
+ if (this.cppRegistry_) {
+ this.cppRegistry_.destroy(entity);
+ } else {
+ this.tsRegistry_.destroy(entity);
+ }
+ this.entities_.delete(entity);
+ }
+
+ valid(entity: Entity): boolean {
+ if (this.cppRegistry_) {
+ return this.cppRegistry_.valid(entity);
+ }
+ return this.tsRegistry_.valid(entity);
+ }
+
+ entityCount(): number {
+ return this.entities_.size;
+ }
+
+ getAllEntities(): Entity[] {
+ return Array.from(this.entities_);
+ }
+
+ // =========================================================================
+ // Component Management - Generic
+ // =========================================================================
+
+ insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown {
+ if (isBuiltinComponent(component)) {
+ return this.insertBuiltin(entity, component, data);
+ }
+ return this.insertScript(entity, component as ComponentDef<Schema>, data as never);
+ }
+
+ remove(entity: Entity, component: AnyComponentDef): void {
+ if (isBuiltinComponent(component)) {
+ this.removeBuiltin(entity, component);
+ } else {
+ this.removeScript(entity, component as ComponentDef<Schema>);
+ }
+ }
+
+ get(entity: Entity, component: AnyComponentDef): unknown {
+ if (isBuiltinComponent(component)) {
+ return this.getBuiltin(entity, component);
+ }
+ return this.getScript(entity, component as ComponentDef<Schema>);
+ }
+
+ tryGet(entity: Entity, component: AnyComponentDef): unknown | undefined {
+ if (!this.has(entity, component)) {
+ return undefined;
+ }
+ return this.get(entity, component);
+ }
+
+ has(entity: Entity, component: AnyComponentDef): boolean {
+ if (isBuiltinComponent(component)) {
+ return this.hasBuiltin(entity, component);
+ }
+ return this.hasScript(entity, component as ComponentDef<Schema>);
+ }
+
+ // =========================================================================
+ // Built-in Component Operations (C++ Registry)
+ // =========================================================================
+
+ private insertBuiltin(entity: Entity, component: BuiltinComponentDef<unknown>, data?: unknown): unknown {
+ const defaults = getBuiltinDefaults(component) as object;
+ const merged = { ...defaults, ...(data as object) };
+
+ if (this.cppRegistry_) {
+ const adder = `add${component._cppName}` as keyof CppRegistry;
+ const fn = this.cppRegistry_[adder] as (e: Entity, d: unknown) => void;
+ fn.call(this.cppRegistry_, entity, merged);
+ }
+
+ return merged;
+ }
+
+ private getBuiltin<T>(entity: Entity, component: BuiltinComponentDef<T>): T {
+ if (!this.cppRegistry_) {
+ throw new Error('C++ Registry not connected');
+ }
+
+ const getter = `get${component._cppName}` as keyof CppRegistry;
+ const fn = this.cppRegistry_[getter] as (e: Entity) => T;
+ return fn.call(this.cppRegistry_, entity);
+ }
+
+ private hasBuiltin(entity: Entity, component: BuiltinComponentDef<unknown>): boolean {
+ if (!this.cppRegistry_) {
+ return false;
+ }
+
+ const checker = `has${component._cppName}` as keyof CppRegistry;
+ const fn = this.cppRegistry_[checker] as (e: Entity) => boolean;
+ return fn.call(this.cppRegistry_, entity);
+ }
+
+ private removeBuiltin(entity: Entity, component: BuiltinComponentDef<unknown>): void {
+ if (!this.cppRegistry_) {
+ return;
+ }
+
+ const remover = `remove${component._cppName}` as keyof CppRegistry;
+ const fn = this.cppRegistry_[remover] as (e: Entity) => void;
+ fn.call(this.cppRegistry_, entity);
+ }
+
+ // =========================================================================
+ // Script Component Operations (Schema-based with direct memory access)
+ // =========================================================================
+
+ private insertScript<S extends Schema>(
+ entity: Entity,
+ component: ComponentDef<S>,
+ data?: Partial<InferSchema<S>>
+ ): InferSchema<S> {
+ const initialData = component.create(data);
+
+ if (this.cppRegistry_ && this.heapBuffer_) {
+ const poolId = this.ensureCppRegistered(component);
+ const byteOffset = this.cppRegistry_.addSchemaComponent(poolId, entity);
+ const basePtr = this.cppRegistry_.getSchemaPoolBasePtr(poolId);
+
+ writeComponentData(
+ component._layout,
+ this.heapBuffer_,
+ basePtr + byteOffset,
+ initialData
+ );
+
+ return createComponentProxy<S>(
+ component._layout,
+ this.heapBuffer_,
+ basePtr + byteOffset
+ );
+ } else {
+ const key = this.getOrCreateKey(component);
+ this.tsRegistry_.emplace(entity, key, initialData);
+ return initialData;
+ }
+ }
+
+ private getScript<S extends Schema>(entity: Entity, component: ComponentDef<S>): InferSchema<S> {
+ if (this.cppRegistry_ && this.heapBuffer_ && component._cppId !== null) {
+ const byteOffset = this.cppRegistry_.getSchemaComponentOffset(component._cppId, entity);
+ const basePtr = this.cppRegistry_.getSchemaPoolBasePtr(component._cppId);
+
+ return createComponentProxy<S>(
+ component._layout,
+ this.heapBuffer_,
+ basePtr + byteOffset
+ );
+ }
+
+ const key = this.componentKeys_.get(component._id);
+ if (!key) {
+ throw new Error(`Component not registered: ${component._name}`);
+ }
+ return this.tsRegistry_.get<InferSchema<S>>(entity, key);
+ }
+
+ private hasScript<S extends Schema>(entity: Entity, component: ComponentDef<S>): boolean {
+ if (this.cppRegistry_ && component._cppId !== null) {
+ return this.cppRegistry_.hasSchemaComponent(component._cppId, entity);
+ }
+
+ const key = this.componentKeys_.get(component._id);
+ if (!key) {
+ return false;
+ }
+ return this.tsRegistry_.has(entity, key);
+ }
+
+ private removeScript<S extends Schema>(entity: Entity, component: ComponentDef<S>): void {
+ if (this.cppRegistry_ && component._cppId !== null) {
+ this.cppRegistry_.removeSchemaComponent(component._cppId, entity);
+ return;
+ }
+
+ const key = this.componentKeys_.get(component._id);
+ if (key) {
+ this.tsRegistry_.remove(entity, key);
+ }
+ }
+
+ private ensureCppRegistered<S extends Schema>(component: ComponentDef<S>): number {
+ if (component._cppId === null) {
+ const id = this.cppRegistry_!.registerSchemaPool(
+ component._name,
+ component._layout.stride
+ );
+ component._cppId = id;
+ return id;
+ }
+ return component._cppId;
+ }
+
+ private getOrCreateKey<S extends Schema>(component: ComponentDef<S>): symbol {
+ let key = this.componentKeys_.get(component._id);
+ if (!key) {
+ key = Symbol(component._name);
+ this.componentKeys_.set(component._id, key);
+ }
+ return key;
+ }
+
+ // =========================================================================
+ // Query Support
+ // =========================================================================
+
+ getEntitiesWithComponents(components: AnyComponentDef[]): Entity[] {
+ if (components.length === 0) {
+ return this.getAllEntities();
+ }
+
+ // Optimize: if all components are script components with C++ IDs,
+ // use C++ querySchema for the first component and filter
+ if (this.cppRegistry_ && components.length > 0) {
+ const firstComp = components[0];
+ if (!isBuiltinComponent(firstComp)) {
+ const scriptComp = firstComp as ComponentDef<Schema>;
+ if (scriptComp._cppId !== null) {
+ const baseEntities = this.cppRegistry_.querySchema(scriptComp._cppId);
+ if (components.length === 1) {
+ return baseEntities;
+ }
+
+ return baseEntities.filter((entity: Entity) => {
+ for (let i = 1; i < components.length; i++) {
+ if (!this.has(entity, components[i])) {
+ return false;
+ }
+ }
+ return true;
+ });
+ }
+ }
+ }
+
+ const entities: Entity[] = [];
+
+ 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;
+ }
+
+ getComponent(entity: Entity, component: AnyComponentDef): unknown {
+ return this.get(entity, component);
+ }
+
+ // =========================================================================
+ // Internal Access
+ // =========================================================================
+
+ get tsRegistry(): Registry {
+ return this.tsRegistry_;
+ }
+
+ get cppRegistry(): CppRegistry | null {
+ return this.cppRegistry_;
+ }
+}
diff --git a/sdk/src/index.ts b/sdk/src/index.ts
index 28543a4a9..0de28e5aa 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -1,9 +1,18 @@
/**
- * ESEngine TypeScript SDK
+ * @file index.ts
+ * @brief ESEngine TypeScript SDK public API exports
*
- * A lightweight 2D game engine for Web and WeChat MiniGames.
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
*/
+// =============================================================================
+// Core
+// =============================================================================
+
// Core types and utilities
export {
Entity,
@@ -46,7 +55,10 @@ export {
withFloat32Array,
} from './core/WasmBridge';
-// ECS - Entity
+// =============================================================================
+// ECS
+// =============================================================================
+
export {
generateEntityId,
recycleEntityId,
@@ -54,10 +66,8 @@ export {
resetEntityIds,
} from './ecs/Entity';
-// ECS - Registry
export { Registry } from './ecs/Registry';
-// ECS - Components
export {
Transform,
Velocity,
@@ -66,6 +76,8 @@ export {
Active,
Visible,
Static,
+ Parent,
+ Children,
createTransform,
createVelocity,
createSprite,
@@ -73,6 +85,8 @@ export {
createActive,
createVisible,
createStatic,
+ createParent,
+ createChildren,
TransformType,
VelocityType,
SpriteType,
@@ -80,15 +94,18 @@ export {
ActiveType,
VisibleType,
StaticType,
+ ParentType,
+ ChildrenType,
} from './ecs/Components';
-// ECS - View
export { View, View2, View3, View4 } from './ecs/View';
-// ECS - System
export { System, SystemGroup } from './ecs/System';
-// Math utilities
+// =============================================================================
+// Math
+// =============================================================================
+
export {
PI,
TWO_PI,
@@ -104,10 +121,12 @@ export {
Mat4Math,
} from './math/Math';
-// Input
+// =============================================================================
+// Platform
+// =============================================================================
+
export { Input } from './input/Input';
-// Platform
export {
Platform,
PlatformCapabilities,
@@ -119,5 +138,46 @@ export {
export { WebPlatform } from './platform/WebPlatform';
export { WxPlatform } from './platform/WxPlatform';
+// =============================================================================
// Renderer
+// =============================================================================
+
export { Renderer, RendererMode, DrawQuadOptions } from './renderer/Renderer';
+
+// =============================================================================
+// Scene
+// =============================================================================
+
+export {
+ loadScene,
+ loadSceneFromData,
+ SceneData,
+ EntityData,
+ ComponentsData,
+ ScriptComponentData,
+ TextureLoader,
+ ComponentRegistry,
+ SceneLoaderOptions,
+ SceneLoadResult,
+ SCENE_FORMAT_VERSION,
+} from './scene/SceneLoader';
+
+// =============================================================================
+// Assets & WASM
+// =============================================================================
+
+export { AssetLoader, type TextureData, type ShaderData } from './assets';
+
+export type {
+ CppRegistry,
+ CppApp,
+ CppResourceManager,
+ TextureHandle,
+ ShaderHandle,
+} from './wasm';
+
+// =============================================================================
+// Framework
+// =============================================================================
+
+export * from './framework';
diff --git a/sdk/src/scene/SceneLoader.ts b/sdk/src/scene/SceneLoader.ts
new file mode 100644
index 000000000..1ed937304
--- /dev/null
+++ b/sdk/src/scene/SceneLoader.ts
@@ -0,0 +1,314 @@
+/**
+ * @file SceneLoader.ts
+ * @brief Scene loading utilities for .esscene JSON files
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+import { Entity } from '../core/Types';
+import { Registry } from '../ecs/Registry';
+import {
+ Transform,
+ Sprite,
+ Name,
+ Parent,
+ Children,
+ createTransform,
+ createSprite,
+ createName,
+ createParent,
+ createChildren,
+ TransformType,
+ SpriteType,
+ NameType,
+ ActiveType,
+ VisibleType,
+ StaticType,
+ ParentType,
+ ChildrenType,
+ createActive,
+ createVisible,
+ createStatic,
+} from '../ecs/Components';
+import { ComponentDef } from '../framework/component';
+import { Schema } from '../framework/types';
+
+// =============================================================================
+// Constants
+// =============================================================================
+
+export const SCENE_FORMAT_VERSION = 1;
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface SceneData {
+ version: number;
+ name: string;
+ entities: EntityData[];
+ scripts?: ScriptComponentData[];
+}
+
+/**
+ * Script component definition in scene file
+ */
+export interface ScriptComponentData {
+ name: string;
+ schema: Record<string, string>;
+}
+
+/**
+ * Entity data in scene file
+ */
+export interface EntityData {
+ uuid: number;
+ name: string;
+ components: ComponentsData;
+}
+
+/**
+ * Components data structure
+ */
+export interface ComponentsData {
+ LocalTransform?: {
+ position: [number, number, number];
+ rotation: [number, number, number, number]; // quaternion [w, x, y, z]
+ scale: [number, number, number];
+ };
+ Parent?: {
+ uuid: number;
+ };
+ Sprite?: {
+ texture: number;
+ texturePath?: string;
+ color: [number, number, number, number];
+ size: [number, number];
+ uvOffset: [number, number];
+ uvScale: [number, number];
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ };
+ Camera?: {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ };
+ Canvas?: {
+ designResolution: [number, number];
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: [number, number, number, number];
+ };
+ tags?: string[];
+ scripts?: Array<{
+ name: string;
+ fields: Record<string, unknown>;
+ }>;
+}
+
+export type TextureLoader = (path: string) => Promise<number>;
+
+/**
+ * Component registry for custom script components
+ */
+export type ComponentRegistry = Map<string, ComponentDef<Schema>>;
+
+export interface SceneLoaderOptions {
+ textureLoader?: TextureLoader;
+ componentRegistry?: ComponentRegistry;
+}
+
+export interface SceneLoadResult {
+ success: boolean;
+ sceneName: string;
+ entityCount: number;
+ entities: Entity[];
+ error?: string;
+}
+
+// =============================================================================
+// Functions
+// =============================================================================
+
+export async function loadScene(
+ registry: Registry,
+ url: string,
+ options: SceneLoaderOptions = {}
+): Promise<SceneLoadResult> {
+ try {
+ const response = await fetch(url);
+ if (!response.ok) {
+ return {
+ success: false,
+ sceneName: '',
+ entityCount: 0,
+ entities: [],
+ error: `Failed to fetch scene: ${response.status} ${response.statusText}`,
+ };
+ }
+
+ const sceneData: SceneData = await response.json();
+ return await loadSceneFromData(registry, sceneData, options);
+ } catch (error) {
+ return {
+ success: false,
+ sceneName: '',
+ entityCount: 0,
+ entities: [],
+ error: `Failed to load scene: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+}
+
+export async function loadSceneFromData(
+ registry: Registry,
+ sceneData: SceneData,
+ options: SceneLoaderOptions = {}
+): Promise<SceneLoadResult> {
+ const { textureLoader, componentRegistry } = options;
+
+ // Check version
+ if (sceneData.version > SCENE_FORMAT_VERSION) {
+ return {
+ success: false,
+ sceneName: sceneData.name,
+ entityCount: 0,
+ entities: [],
+ error: `Scene version ${sceneData.version} is newer than supported version ${SCENE_FORMAT_VERSION}`,
+ };
+ }
+
+ // Clear existing entities
+ registry.clear();
+
+ // Maps for resolving references
+ const uuidToEntity = new Map<number, Entity>();
+ const entities: Entity[] = [];
+
+ // First pass: create all entities
+ for (const entityData of sceneData.entities) {
+ const entity = registry.create();
+ uuidToEntity.set(entityData.uuid, entity);
+ entities.push(entity);
+
+ // Add Name component
+ registry.emplace(entity, NameType, createName(entityData.name));
+
+ // Add components
+ const components = entityData.components;
+
+ // LocalTransform
+ if (components.LocalTransform) {
+ const t = components.LocalTransform;
+ registry.emplace(
+ entity,
+ TransformType,
+ createTransform(
+ { x: t.position[0], y: t.position[1], z: t.position[2] },
+ { x: 0, y: 0, z: 0 }, // Convert quaternion to euler if needed
+ { x: t.scale[0], y: t.scale[1], z: t.scale[2] }
+ )
+ );
+ }
+
+ // Sprite
+ if (components.Sprite) {
+ const s = components.Sprite;
+ let textureId = 0;
+
+ // Try to load texture if path is provided
+ if (s.texturePath && textureLoader) {
+ try {
+ textureId = await textureLoader(s.texturePath);
+ } catch (e) {
+ console.warn(`Failed to load texture: ${s.texturePath}`, e);
+ }
+ }
+
+ registry.emplace(
+ entity,
+ SpriteType,
+ createSprite(textureId, {
+ color: { r: s.color[0], g: s.color[1], b: s.color[2], a: s.color[3] },
+ size: { x: s.size[0], y: s.size[1] },
+ uvOffset: { x: s.uvOffset[0], y: s.uvOffset[1] },
+ uvScale: { x: s.uvScale[0], y: s.uvScale[1] },
+ layer: s.layer,
+ })
+ );
+ }
+
+ // Tags
+ if (components.tags) {
+ for (const tag of components.tags) {
+ switch (tag) {
+ case 'Active':
+ registry.emplace(entity, ActiveType, createActive());
+ break;
+ case 'Visible':
+ registry.emplace(entity, VisibleType, createVisible());
+ break;
+ case 'Static':
+ registry.emplace(entity, StaticType, createStatic());
+ break;
+ }
+ }
+ }
+
+ // Custom script components
+ if (components.scripts && componentRegistry) {
+ for (const scriptData of components.scripts) {
+ const componentDef = componentRegistry.get(scriptData.name);
+ if (componentDef) {
+ const instance = componentDef.create(scriptData.fields as never);
+ const key = Symbol.for(`Script_${scriptData.name}`);
+ registry.emplace(entity, key, instance);
+ } else {
+ console.warn(`Unknown script component: ${scriptData.name}`);
+ }
+ }
+ }
+ }
+
+ // Second pass: resolve parent/children relationships
+ for (const entityData of sceneData.entities) {
+ const entity = uuidToEntity.get(entityData.uuid);
+ if (!entity) continue;
+
+ const parentData = entityData.components.Parent;
+ if (parentData && parentData.uuid !== 0) {
+ const parentEntity = uuidToEntity.get(parentData.uuid);
+ if (parentEntity !== undefined) {
+ // Add Parent component to child
+ registry.emplace(entity, ParentType, createParent(parentEntity));
+
+ // Add/update Children component on parent
+ const existingChildren = registry.tryGet<Children>(parentEntity, ChildrenType);
+ if (existingChildren) {
+ existingChildren.entities.push(entity);
+ } else {
+ registry.emplace(parentEntity, ChildrenType, createChildren([entity]));
+ }
+ }
+ }
+ }
+
+ return {
+ success: true,
+ sceneName: sceneData.name,
+ entityCount: entities.length,
+ entities,
+ };
+}
diff --git a/sdk/src/scene/index.ts b/sdk/src/scene/index.ts
new file mode 100644
index 000000000..46000cb52
--- /dev/null
+++ b/sdk/src/scene/index.ts
@@ -0,0 +1,22 @@
+/**
+ * @file index.ts
+ * @brief Scene module exports
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+export {
+ loadScene,
+ loadSceneFromData,
+ SceneData,
+ EntityData,
+ ComponentsData,
+ TextureLoader,
+ SceneLoaderOptions,
+ SceneLoadResult,
+ SCENE_FORMAT_VERSION,
+} from './SceneLoader';
diff --git a/sdk/src/wasm/index.ts b/sdk/src/wasm/index.ts
new file mode 100644
index 000000000..4f6c50932
--- /dev/null
+++ b/sdk/src/wasm/index.ts
@@ -0,0 +1,12 @@
+/**
+ * @file index.ts
+ * @brief WASM module types and utilities
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+export * from './types';
diff --git a/sdk/src/wasm/types.ts b/sdk/src/wasm/types.ts
new file mode 100644
index 000000000..6f13dd194
--- /dev/null
+++ b/sdk/src/wasm/types.ts
@@ -0,0 +1,274 @@
+/**
+ * @file types.ts
+ * @brief ESEngine C++ Module Type Definitions
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+// =============================================================================
+// Core Types
+// =============================================================================
+
+export type Entity = number;
+
+// =============================================================================
+// Math Types
+// =============================================================================
+
+export interface Vec2 { x: number; y: number; }
+export interface Vec3 { x: number; y: number; z: number; }
+export interface Vec4 { x: number; y: number; z: number; w: number; }
+export interface UVec2 { x: number; y: number; }
+export interface Quat { w: number; x: number; y: number; z: number; }
+export type Mat4 = number[];
+
+// =============================================================================
+// Enums
+// =============================================================================
+
+export const enum ProjectionType {
+ Perspective = 0,
+ Orthographic = 1
+}
+
+export const enum CanvasScaleMode {
+ FixedWidth = 0,
+ FixedHeight = 1,
+ Expand = 2,
+ Shrink = 3,
+ Match = 4
+}
+
+export const enum TextureFormat {
+ RGB8 = 0,
+ RGBA8 = 1
+}
+
+export const enum CppSchedule {
+ Startup = 0,
+ PreUpdate = 1,
+ Update = 2,
+ PostUpdate = 3,
+ PreRender = 4,
+ Render = 5,
+ PostRender = 6,
+}
+
+// =============================================================================
+// Components
+// =============================================================================
+
+export interface CppCamera {
+ projectionType: ProjectionType;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+}
+
+export interface CppCanvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: CanvasScaleMode;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+
+export interface CppParent {
+ entity: number;
+}
+
+export interface CppChildren {
+ entities: Entity[];
+}
+
+export interface CppSprite {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+}
+
+export interface CppLocalTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+
+export interface CppWorldTransform {
+ matrix: Mat4;
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+
+export interface CppVelocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+
+// =============================================================================
+// Registry
+// =============================================================================
+
+export interface CppRegistry {
+ create(): Entity;
+ destroy(entity: Entity): void;
+ valid(entity: Entity): boolean;
+ entityCount(): number;
+
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): CppCamera;
+ addCamera(entity: Entity, component: CppCamera): void;
+ removeCamera(entity: Entity): void;
+
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): CppCanvas;
+ addCanvas(entity: Entity, component: CppCanvas): void;
+ removeCanvas(entity: Entity): void;
+
+ hasParent(entity: Entity): boolean;
+ getParent(entity: Entity): CppParent;
+ addParent(entity: Entity, component: CppParent): void;
+ removeParent(entity: Entity): void;
+
+ hasChildren(entity: Entity): boolean;
+ getChildren(entity: Entity): CppChildren;
+ addChildren(entity: Entity, component: CppChildren): void;
+ removeChildren(entity: Entity): void;
+
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): CppSprite;
+ addSprite(entity: Entity, component: CppSprite): void;
+ removeSprite(entity: Entity): void;
+
+ hasLocalTransform(entity: Entity): boolean;
+ getLocalTransform(entity: Entity): CppLocalTransform;
+ addLocalTransform(entity: Entity, component: CppLocalTransform): void;
+ removeLocalTransform(entity: Entity): void;
+
+ hasWorldTransform(entity: Entity): boolean;
+ getWorldTransform(entity: Entity): CppWorldTransform;
+ addWorldTransform(entity: Entity, component: CppWorldTransform): void;
+ removeWorldTransform(entity: Entity): void;
+
+ hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): CppVelocity;
+ addVelocity(entity: Entity, component: CppVelocity): void;
+ removeVelocity(entity: Entity): void;
+
+ // Schema Components (Script-defined, direct memory access)
+ registerSchemaPool(name: string, stride: number): number;
+ getSchemaPoolId(name: string): number;
+ addSchemaComponent(poolId: number, entity: Entity): number;
+ hasSchemaComponent(poolId: number, entity: Entity): boolean;
+ getSchemaComponentOffset(poolId: number, entity: Entity): number;
+ removeSchemaComponent(poolId: number, entity: Entity): void;
+ getSchemaPoolBasePtr(poolId: number): number;
+ getSchemaPoolStride(poolId: number): number;
+ querySchema(poolId: number): Entity[];
+
+ [key: string]: unknown;
+}
+
+// =============================================================================
+// Resources
+// =============================================================================
+
+export type ShaderHandle = number;
+export type TextureHandle = number;
+
+export interface CppResourceManager {
+ init(): void;
+ shutdown(): void;
+ createShader(vertSrc: string, fragSrc: string): ShaderHandle;
+ createTexture(width: number, height: number, pixelsPtr: number, pixelsLen: number, format: TextureFormat): TextureHandle;
+ releaseShader(handle: ShaderHandle): void;
+ releaseTexture(handle: TextureHandle): void;
+}
+
+// =============================================================================
+// App
+// =============================================================================
+
+export interface CppTime {
+ delta: number;
+ elapsed: number;
+ frameCount: number;
+}
+
+export interface CppAppConfig {
+ title: string;
+ width: number;
+ height: number;
+ vsync: boolean;
+}
+
+export interface CppApp {
+ run(): void;
+ quit(): void;
+ registry(): CppRegistry;
+ time(): CppTime;
+ width(): number;
+ height(): number;
+}
+
+// =============================================================================
+// Query
+// =============================================================================
+
+export interface EntityVector {
+ size(): number;
+ get(index: number): Entity;
+}
+
+// =============================================================================
+// Module
+// =============================================================================
+
+export interface ESEngineModule {
+ ResourceManager: new () => CppResourceManager;
+ AppConfig: new () => CppAppConfig;
+
+ Camera: new () => CppCamera;
+ Canvas: new () => CppCanvas;
+ Parent: new () => CppParent;
+ Children: new () => CppChildren;
+ Sprite: new () => CppSprite;
+ LocalTransform: new () => CppLocalTransform;
+ WorldTransform: new () => CppWorldTransform;
+ Velocity: new () => CppVelocity;
+
+ Schedule: typeof CppSchedule;
+ TextureFormat: typeof TextureFormat;
+ ProjectionType: typeof ProjectionType;
+ CanvasScaleMode: typeof CanvasScaleMode;
+
+ createApp(): CppApp;
+ createAppWithConfig(config: CppAppConfig): CppApp;
+ getApp(): CppApp;
+
+ queryLocalTransform(registry: CppRegistry): EntityVector;
+ queryLocalTransformSprite(registry: CppRegistry): EntityVector;
+
+ HEAPU8: Uint8Array;
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+
+ setJSSystemsCallback(callback: (schedule: number, dt: number) => void): void;
+
+ [key: string]: unknown;
+}
+
+export type CreateModuleFn = () => Promise<ESEngineModule>;
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 8a0d877c8..fa6e8debc 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -15,11 +15,6 @@
#include <emscripten/bind.h>
#include "../ecs/Registry.hpp"
#include "../math/Math.hpp"
-#include "../resource/ResourceManager.hpp"
-#include "../renderer/Texture.hpp"
-#include "../renderer/Shader.hpp"
-#include "../app/App.hpp"
-#include "../app/Schedule.hpp"
#include "../ecs/components/Camera.hpp"
#include "../ecs/components/Canvas.hpp"
@@ -32,23 +27,6 @@ using namespace emscripten;
using namespace esengine;
using namespace esengine::ecs;
-// =============================================================================
-// Enums
-// =============================================================================
-
-EMSCRIPTEN_BINDINGS(esengine_enums) {
- enum_<esengine::ecs::ProjectionType>("ProjectionType")
- .value("Perspective", esengine::ecs::ProjectionType::Perspective)
- .value("Orthographic", esengine::ecs::ProjectionType::Orthographic);
-
- enum_<esengine::ecs::CanvasScaleMode>("CanvasScaleMode")
- .value("FixedWidth", esengine::ecs::CanvasScaleMode::FixedWidth)
- .value("FixedHeight", esengine::ecs::CanvasScaleMode::FixedHeight)
- .value("Expand", esengine::ecs::CanvasScaleMode::Expand)
- .value("Shrink", esengine::ecs::CanvasScaleMode::Shrink)
- .value("Match", esengine::ecs::CanvasScaleMode::Match);
-}
-
// =============================================================================
// Math Types
// =============================================================================
@@ -80,6 +58,24 @@ EMSCRIPTEN_BINDINGS(esengine_math) {
.field("z", &glm::quat::z);
}
+// =============================================================================
+// Enums
+// =============================================================================
+
+EMSCRIPTEN_BINDINGS(esengine_enums) {
+ enum_<esengine::ecs::ProjectionType>("ProjectionType")
+ .value("Perspective", esengine::ecs::ProjectionType::Perspective)
+ .value("Orthographic", esengine::ecs::ProjectionType::Orthographic);
+
+ enum_<esengine::ecs::CanvasScaleMode>("CanvasScaleMode")
+ .value("FixedWidth", esengine::ecs::CanvasScaleMode::FixedWidth)
+ .value("FixedHeight", esengine::ecs::CanvasScaleMode::FixedHeight)
+ .value("Expand", esengine::ecs::CanvasScaleMode::Expand)
+ .value("Shrink", esengine::ecs::CanvasScaleMode::Shrink)
+ .value("Match", esengine::ecs::CanvasScaleMode::Match);
+
+}
+
// =============================================================================
// Components
// =============================================================================
@@ -145,6 +141,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
EMSCRIPTEN_BINDINGS(esengine_registry) {
class_<Registry>("Registry")
+ .constructor<>()
.function("create", optional_override([](Registry& r) {
return static_cast<u32>(r.create());
}))
@@ -271,123 +268,4 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
;
}
-// =============================================================================
-// Resource Manager
-// =============================================================================
-
-EMSCRIPTEN_BINDINGS(esengine_resources) {
- using namespace esengine::resource;
-
- class_<ResourceManager>("ResourceManager")
- .constructor<>()
- .function("init", &ResourceManager::init)
- .function("shutdown", &ResourceManager::shutdown)
- .function("createShader", optional_override([](ResourceManager& rm,
- const std::string& vertSrc, const std::string& fragSrc) -> u32 {
- return rm.createShader(vertSrc, fragSrc).id();
- }))
- .function("createTexture", optional_override([](ResourceManager& rm,
- u32 width, u32 height, uintptr_t pixelsPtr, usize pixelsLen, int format) -> u32 {
- const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);
- ConstSpan<u8> span(pixels, pixelsLen);
- return rm.createTexture(width, height, span,
- static_cast<TextureFormat>(format)).id();
- }))
- .function("releaseShader", optional_override([](ResourceManager& rm, u32 handle) {
- rm.releaseShader(ShaderHandle(handle));
- }))
- .function("releaseTexture", optional_override([](ResourceManager& rm, u32 handle) {
- rm.releaseTexture(TextureHandle(handle));
- }));
-
- enum_<TextureFormat>("TextureFormat")
- .value("RGB8", TextureFormat::RGB8)
- .value("RGBA8", TextureFormat::RGBA8);
-}
-
-// =============================================================================
-// App
-// =============================================================================
-
-EMSCRIPTEN_BINDINGS(esengine_app) {
- enum_<Schedule>("Schedule")
- .value("Startup", Schedule::Startup)
- .value("PreUpdate", Schedule::PreUpdate)
- .value("Update", Schedule::Update)
- .value("PostUpdate", Schedule::PostUpdate)
- .value("PreRender", Schedule::PreRender)
- .value("Render", Schedule::Render)
- .value("PostRender", Schedule::PostRender);
-
- value_object<Time>("Time")
- .field("delta", &Time::delta)
- .field("elapsed", &Time::elapsed)
- .field("frameCount", &Time::frameCount);
-
- value_object<AppConfig>("AppConfig")
- .field("title", &AppConfig::title)
- .field("width", &AppConfig::width)
- .field("height", &AppConfig::height)
- .field("vsync", &AppConfig::vsync);
-
- class_<App>("App")
- .function("run", &App::run)
- .function("quit", &App::quit)
- .function("registry", optional_override([](App& app) -> Registry* {
- return &app.registry();
- }), allow_raw_pointers())
- .function("time", &App::time)
- .function("width", &App::width)
- .function("height", &App::height);
-
- function("createApp", optional_override([]() -> App* {
- static App app;
- return &app;
- }), allow_raw_pointers());
-
- function("createAppWithConfig", optional_override([](const AppConfig& config) -> App* {
- static App app(config);
- return &app;
- }), allow_raw_pointers());
-
- function("getApp", optional_override([]() -> App* {
- return &App::get();
- }), allow_raw_pointers());
-
- function("setJSSystemsCallback", optional_override([](emscripten::val callback) {
- static emscripten::val storedCallback = emscripten::val::undefined();
- storedCallback = callback;
- App::setJSSystemsCallback(&storedCallback);
- }));
-}
-
-// =============================================================================
-// View Iterator for Query
-// =============================================================================
-
-EMSCRIPTEN_BINDINGS(esengine_query) {
- class_<std::vector<u32>>("EntityVector")
- .constructor<>()
- .function("size", &std::vector<u32>::size)
- .function("get", optional_override([](const std::vector<u32>& v, usize i) {
- return v[i];
- }));
-
- function("queryLocalTransformSprite", optional_override([](Registry& reg) {
- std::vector<u32> entities;
- reg.each<LocalTransform, Sprite>([&entities](Entity e, LocalTransform&, Sprite&) {
- entities.push_back(static_cast<u32>(e));
- });
- return entities;
- }));
-
- function("queryLocalTransform", optional_override([](Registry& reg) {
- std::vector<u32> entities;
- reg.each<LocalTransform>([&entities](Entity e, LocalTransform&) {
- entities.push_back(static_cast<u32>(e));
- });
- return entities;
- }));
-}
-
#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/ecs/DynamicComponent.hpp b/src/esengine/ecs/DynamicComponent.hpp
new file mode 100644
index 000000000..bb5dce870
--- /dev/null
+++ b/src/esengine/ecs/DynamicComponent.hpp
@@ -0,0 +1,321 @@
+/**
+ * @file DynamicComponent.hpp
+ * @brief Dynamic component storage for script-defined components
+ * @details Provides type-erased component storage that allows TypeScript
+ * to define and use custom components without C++ compile-time types.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../core/Types.hpp"
+#include "Entity.hpp"
+#include "SparseSet.hpp"
+
+#include <any>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#ifdef ES_PLATFORM_WEB
+#include <emscripten/val.h>
+#endif
+
+namespace esengine::ecs {
+
+// =============================================================================
+// DynamicValue
+// =============================================================================
+
+#ifdef ES_PLATFORM_WEB
+using DynamicValue = emscripten::val;
+#else
+using DynamicValue = std::any;
+#endif
+
+// =============================================================================
+// DynamicComponentPool
+// =============================================================================
+
+/**
+ * @brief Storage for a single dynamic component type
+ *
+ * @details Uses SparseSet-like storage to efficiently store script-defined
+ * component data. On Web platform, stores emscripten::val directly
+ * to minimize JS/C++ boundary crossing overhead.
+ */
+class DynamicComponentPool {
+public:
+ DynamicComponentPool() = default;
+ ~DynamicComponentPool() = default;
+
+ DynamicComponentPool(const DynamicComponentPool&) = delete;
+ DynamicComponentPool& operator=(const DynamicComponentPool&) = delete;
+ DynamicComponentPool(DynamicComponentPool&&) noexcept = default;
+ DynamicComponentPool& operator=(DynamicComponentPool&&) noexcept = default;
+
+ // =========================================================================
+ // Lookup Operations
+ // =========================================================================
+
+ /** @brief Checks if entity has this component */
+ bool contains(Entity entity) const {
+ return entity < sparse_.size() &&
+ sparse_[entity] < dense_.size() &&
+ dense_[sparse_[entity]] == entity;
+ }
+
+ /** @brief Gets component data (must exist) */
+ DynamicValue& get(Entity entity) {
+ ES_ASSERT(contains(entity), "Entity does not have component");
+ return values_[sparse_[entity]];
+ }
+
+ /** @brief Gets component data (const) */
+ const DynamicValue& get(Entity entity) const {
+ ES_ASSERT(contains(entity), "Entity does not have component");
+ return values_[sparse_[entity]];
+ }
+
+ /** @brief Tries to get component data (returns nullptr if not found) */
+ DynamicValue* tryGet(Entity entity) {
+ if (!contains(entity)) return nullptr;
+ return &values_[sparse_[entity]];
+ }
+
+ // =========================================================================
+ // Modification Operations
+ // =========================================================================
+
+ /** @brief Adds component data to entity */
+ void emplace(Entity entity, DynamicValue value) {
+ ES_ASSERT(!contains(entity), "Entity already has component");
+
+ if (entity >= sparse_.size()) {
+ sparse_.resize(entity + 1, INVALID_ENTITY);
+ }
+
+ sparse_[entity] = static_cast<Entity>(dense_.size());
+ dense_.push_back(entity);
+ values_.push_back(std::move(value));
+ }
+
+ /** @brief Adds or replaces component data */
+ void emplaceOrReplace(Entity entity, DynamicValue value) {
+ if (contains(entity)) {
+ values_[sparse_[entity]] = std::move(value);
+ } else {
+ emplace(entity, std::move(value));
+ }
+ }
+
+ /** @brief Removes component from entity */
+ void remove(Entity entity) {
+ if (!contains(entity)) return;
+
+ const auto last = dense_.back();
+ const auto index = sparse_[entity];
+
+ dense_[index] = last;
+ values_[index] = std::move(values_.back());
+ sparse_[last] = index;
+
+ dense_.pop_back();
+ values_.pop_back();
+ sparse_[entity] = INVALID_ENTITY;
+ }
+
+ // =========================================================================
+ // Container Operations
+ // =========================================================================
+
+ usize size() const { return dense_.size(); }
+ bool empty() const { return dense_.empty(); }
+
+ void clear() {
+ sparse_.clear();
+ dense_.clear();
+ values_.clear();
+ }
+
+ const std::vector<Entity>& entities() const { return dense_; }
+
+private:
+ std::vector<Entity> sparse_;
+ std::vector<Entity> dense_;
+ std::vector<DynamicValue> values_;
+};
+
+// =============================================================================
+// DynamicComponentRegistry
+// =============================================================================
+
+/**
+ * @brief Manages all dynamic component pools
+ *
+ * @details Provides a central registry for script-defined components,
+ * allowing TypeScript to create and manage components by name
+ * without requiring C++ type definitions.
+ */
+class DynamicComponentRegistry {
+public:
+ DynamicComponentRegistry() = default;
+ ~DynamicComponentRegistry() = default;
+
+ // =========================================================================
+ // Component Type Registration
+ // =========================================================================
+
+ /**
+ * @brief Registers a new dynamic component type
+ * @param name Unique name for the component type
+ * @return Component type ID for fast lookup
+ */
+ u32 registerComponent(const std::string& name) {
+ auto it = nameToId_.find(name);
+ if (it != nameToId_.end()) {
+ return it->second;
+ }
+
+ u32 id = static_cast<u32>(pools_.size());
+ pools_.emplace_back();
+ nameToId_[name] = id;
+ idToName_[id] = name;
+ return id;
+ }
+
+ /** @brief Gets component ID by name (returns UINT32_MAX if not found) */
+ u32 getComponentId(const std::string& name) const {
+ auto it = nameToId_.find(name);
+ return it != nameToId_.end() ? it->second : UINT32_MAX;
+ }
+
+ /** @brief Gets component name by ID */
+ const std::string& getComponentName(u32 id) const {
+ static const std::string empty;
+ auto it = idToName_.find(id);
+ return it != idToName_.end() ? it->second : empty;
+ }
+
+ /** @brief Checks if component type is registered */
+ bool isRegistered(const std::string& name) const {
+ return nameToId_.find(name) != nameToId_.end();
+ }
+
+ // =========================================================================
+ // Component Operations (by ID)
+ // =========================================================================
+
+ bool has(Entity entity, u32 componentId) const {
+ if (componentId >= pools_.size()) return false;
+ return pools_[componentId].contains(entity);
+ }
+
+ DynamicValue& get(Entity entity, u32 componentId) {
+ ES_ASSERT(componentId < pools_.size(), "Invalid component ID");
+ return pools_[componentId].get(entity);
+ }
+
+ const DynamicValue& get(Entity entity, u32 componentId) const {
+ ES_ASSERT(componentId < pools_.size(), "Invalid component ID");
+ return pools_[componentId].get(entity);
+ }
+
+ void add(Entity entity, u32 componentId, DynamicValue value) {
+ ES_ASSERT(componentId < pools_.size(), "Invalid component ID");
+ pools_[componentId].emplaceOrReplace(entity, std::move(value));
+ }
+
+ void remove(Entity entity, u32 componentId) {
+ if (componentId < pools_.size()) {
+ pools_[componentId].remove(entity);
+ }
+ }
+
+ // =========================================================================
+ // Component Operations (by name)
+ // =========================================================================
+
+ bool hasByName(Entity entity, const std::string& name) const {
+ u32 id = getComponentId(name);
+ return id != UINT32_MAX && has(entity, id);
+ }
+
+ DynamicValue* getByName(Entity entity, const std::string& name) {
+ u32 id = getComponentId(name);
+ if (id == UINT32_MAX) return nullptr;
+ return pools_[id].tryGet(entity);
+ }
+
+ void addByName(Entity entity, const std::string& name, DynamicValue value) {
+ u32 id = registerComponent(name);
+ pools_[id].emplaceOrReplace(entity, std::move(value));
+ }
+
+ void removeByName(Entity entity, const std::string& name) {
+ u32 id = getComponentId(name);
+ if (id != UINT32_MAX) {
+ pools_[id].remove(entity);
+ }
+ }
+
+ // =========================================================================
+ // Entity Operations
+ // =========================================================================
+
+ /** @brief Removes all dynamic components from entity */
+ void removeAll(Entity entity) {
+ for (auto& pool : pools_) {
+ pool.remove(entity);
+ }
+ }
+
+ // =========================================================================
+ // Query Operations
+ // =========================================================================
+
+ /** @brief Gets all entities with a specific dynamic component */
+ const std::vector<Entity>& entitiesWith(u32 componentId) const {
+ static const std::vector<Entity> empty;
+ if (componentId >= pools_.size()) return empty;
+ return pools_[componentId].entities();
+ }
+
+ /** @brief Gets pool for direct access */
+ DynamicComponentPool* getPool(u32 componentId) {
+ if (componentId >= pools_.size()) return nullptr;
+ return &pools_[componentId];
+ }
+
+ const DynamicComponentPool* getPool(u32 componentId) const {
+ if (componentId >= pools_.size()) return nullptr;
+ return &pools_[componentId];
+ }
+
+ // =========================================================================
+ // Utility
+ // =========================================================================
+
+ void clear() {
+ for (auto& pool : pools_) {
+ pool.clear();
+ }
+ }
+
+ usize componentTypeCount() const { return pools_.size(); }
+
+private:
+ std::vector<DynamicComponentPool> pools_;
+ std::unordered_map<std::string, u32> nameToId_;
+ std::unordered_map<u32, std::string> idToName_;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index b270db85f..f662bc3f9 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -21,6 +21,7 @@
#include "../core/Log.hpp"
#include "../core/Types.hpp"
#include "Entity.hpp"
+#include "SchemaComponent.hpp"
#include "SparseSet.hpp"
#include "View.hpp"
@@ -123,11 +124,14 @@ public:
void destroy(Entity entity) {
if (!valid(entity)) return;
- // Remove all components from this entity
+ // Remove all static components from this entity
for (auto& [typeId, pool] : pools_) {
pool->remove(entity);
}
+ // Remove all schema components from this entity
+ schemaRegistry_.removeAll(entity);
+
entityValid_[entity] = false;
recycled_.push(entity);
@@ -417,6 +421,60 @@ public:
}
}
+ // =========================================================================
+ // Schema Component Management (Script-defined, direct memory access)
+ // =========================================================================
+
+ /** @brief Registers a schema component pool */
+ u32 registerSchemaPool(const std::string& name, u32 stride) {
+ return schemaRegistry_.registerPool(name, stride);
+ }
+
+ /** @brief Gets schema pool ID by name */
+ u32 getSchemaPoolId(const std::string& name) const {
+ return schemaRegistry_.getPoolId(name);
+ }
+
+ /** @brief Adds schema component to entity, returns byte offset */
+ u32 addSchemaComponent(u32 poolId, Entity entity) {
+ ES_ASSERT(valid(entity), "Invalid entity");
+ return schemaRegistry_.addComponent(poolId, entity);
+ }
+
+ /** @brief Checks if entity has schema component */
+ bool hasSchemaComponent(u32 poolId, Entity entity) const {
+ return schemaRegistry_.hasComponent(poolId, entity);
+ }
+
+ /** @brief Gets byte offset of entity's schema component */
+ u32 getSchemaComponentOffset(u32 poolId, Entity entity) const {
+ return schemaRegistry_.getComponentOffset(poolId, entity);
+ }
+
+ /** @brief Removes schema component from entity */
+ void removeSchemaComponent(u32 poolId, Entity entity) {
+ schemaRegistry_.removeComponent(poolId, entity);
+ }
+
+ /** @brief Gets base pointer for schema pool (for JS direct access) */
+ uintptr_t getSchemaPoolBasePtr(u32 poolId) const {
+ return schemaRegistry_.getPoolBasePtr(poolId);
+ }
+
+ /** @brief Gets stride for schema pool */
+ u32 getSchemaPoolStride(u32 poolId) const {
+ return schemaRegistry_.getPoolStride(poolId);
+ }
+
+ /** @brief Gets entities with schema component */
+ const std::vector<Entity>& getSchemaEntities(u32 poolId) const {
+ return schemaRegistry_.getEntities(poolId);
+ }
+
+ /** @brief Gets the schema registry */
+ SchemaRegistry& schemaRegistry() { return schemaRegistry_; }
+ const SchemaRegistry& schemaRegistry() const { return schemaRegistry_; }
+
private:
// =========================================================================
// Private Helpers
@@ -474,6 +532,9 @@ private:
/** @brief Type-erased component pools indexed by TypeId */
std::unordered_map<TypeId, Unique<SparseSetBase>> pools_;
+
+ /** @brief Schema component registry for script-defined components */
+ SchemaRegistry schemaRegistry_;
};
} // namespace esengine::ecs
diff --git a/src/esengine/ecs/SchemaComponent.hpp b/src/esengine/ecs/SchemaComponent.hpp
new file mode 100644
index 000000000..4177be962
--- /dev/null
+++ b/src/esengine/ecs/SchemaComponent.hpp
@@ -0,0 +1,305 @@
+/**
+ * @file SchemaComponent.hpp
+ * @brief Schema-based component storage with direct memory access
+ * @details Provides zero-copy component access from TypeScript by storing
+ * component data in WASM linear memory with a defined layout.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../core/Types.hpp"
+#include "Entity.hpp"
+
+#include <cstring>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace esengine::ecs {
+
+// =============================================================================
+// SchemaComponentPool
+// =============================================================================
+
+/**
+ * @brief Component pool with fixed-stride memory layout for direct JS access
+ *
+ * @details Stores component data in a contiguous memory block that can be
+ * directly accessed from TypeScript via WASM HEAP. Each component
+ * occupies exactly `stride` bytes.
+ *
+ * Memory layout:
+ * ┌────────────┬────────────┬────────────┬─────┐
+ * │ Component0 │ Component1 │ Component2 │ ... │
+ * └────────────┴────────────┴────────────┴─────┘
+ * │<- stride ->│
+ */
+class SchemaComponentPool {
+public:
+ explicit SchemaComponentPool(u32 stride, u32 initialCapacity = 64)
+ : stride_(stride) {
+ data_.reserve(initialCapacity * stride);
+ }
+
+ ~SchemaComponentPool() = default;
+
+ SchemaComponentPool(const SchemaComponentPool&) = delete;
+ SchemaComponentPool& operator=(const SchemaComponentPool&) = delete;
+ SchemaComponentPool(SchemaComponentPool&&) noexcept = default;
+ SchemaComponentPool& operator=(SchemaComponentPool&&) noexcept = default;
+
+ // =========================================================================
+ // Component Operations
+ // =========================================================================
+
+ /**
+ * @brief Adds a component to an entity
+ * @param entity The entity to add component to
+ * @return Byte offset of the component data in the pool
+ */
+ u32 add(Entity entity) {
+ if (contains(entity)) {
+ return getOffset(entity);
+ }
+
+ if (entity >= sparse_.size()) {
+ sparse_.resize(entity + 1, INVALID_ENTITY);
+ }
+
+ u32 index = static_cast<u32>(dense_.size());
+ sparse_[entity] = index;
+ dense_.push_back(entity);
+
+ // Allocate space for component data (zero-initialized)
+ usize oldSize = data_.size();
+ data_.resize(oldSize + stride_, 0);
+
+ return static_cast<u32>(oldSize);
+ }
+
+ /**
+ * @brief Gets the byte offset of an entity's component data
+ * @param entity The entity
+ * @return Byte offset in the data buffer
+ */
+ u32 getOffset(Entity entity) const {
+ ES_ASSERT(contains(entity), "Entity does not have component");
+ return sparse_[entity] * stride_;
+ }
+
+ /**
+ * @brief Checks if entity has this component
+ */
+ bool contains(Entity entity) const {
+ return entity < sparse_.size() &&
+ sparse_[entity] < dense_.size() &&
+ dense_[sparse_[entity]] == entity;
+ }
+
+ /**
+ * @brief Removes component from entity
+ */
+ void remove(Entity entity) {
+ if (!contains(entity)) return;
+
+ u32 index = sparse_[entity];
+ Entity lastEntity = dense_.back();
+ u32 lastIndex = static_cast<u32>(dense_.size() - 1);
+
+ // Swap data
+ if (index != lastIndex) {
+ u8* dstPtr = data_.data() + index * stride_;
+ u8* srcPtr = data_.data() + lastIndex * stride_;
+ std::memcpy(dstPtr, srcPtr, stride_);
+
+ dense_[index] = lastEntity;
+ sparse_[lastEntity] = index;
+ }
+
+ dense_.pop_back();
+ data_.resize(data_.size() - stride_);
+ sparse_[entity] = INVALID_ENTITY;
+ }
+
+ // =========================================================================
+ // Memory Access
+ // =========================================================================
+
+ /** @brief Gets base pointer for direct memory access from JS */
+ uintptr_t basePtr() const {
+ return reinterpret_cast<uintptr_t>(data_.data());
+ }
+
+ /** @brief Gets the stride (bytes per component) */
+ u32 stride() const { return stride_; }
+
+ /** @brief Gets number of components */
+ usize size() const { return dense_.size(); }
+
+ /** @brief Gets entity at dense index */
+ Entity entityAt(usize index) const { return dense_[index]; }
+
+ /** @brief Gets all entities */
+ const std::vector<Entity>& entities() const { return dense_; }
+
+ /** @brief Clears all components */
+ void clear() {
+ sparse_.clear();
+ dense_.clear();
+ data_.clear();
+ }
+
+ /**
+ * @brief Gets raw pointer to component data (for C++ access)
+ * @param entity The entity
+ * @return Pointer to component data
+ */
+ u8* getData(Entity entity) {
+ return data_.data() + getOffset(entity);
+ }
+
+ const u8* getData(Entity entity) const {
+ return data_.data() + getOffset(entity);
+ }
+
+private:
+ u32 stride_; ///< Bytes per component
+ std::vector<u8> data_; ///< Contiguous component data
+ std::vector<u32> sparse_; ///< Entity -> dense index
+ std::vector<Entity> dense_; ///< Dense entity array
+};
+
+// =============================================================================
+// SchemaRegistry
+// =============================================================================
+
+/**
+ * @brief Registry for schema-based component pools
+ */
+class SchemaRegistry {
+public:
+ SchemaRegistry() = default;
+ ~SchemaRegistry() = default;
+
+ // =========================================================================
+ // Pool Management
+ // =========================================================================
+
+ /**
+ * @brief Registers a new component type
+ * @param name Component type name
+ * @param stride Bytes per component
+ * @return Pool ID for fast access
+ */
+ u32 registerPool(const std::string& name, u32 stride) {
+ auto it = nameToId_.find(name);
+ if (it != nameToId_.end()) {
+ return it->second;
+ }
+
+ u32 id = static_cast<u32>(pools_.size());
+ pools_.push_back(makeUnique<SchemaComponentPool>(stride));
+ nameToId_[name] = id;
+ idToName_[id] = name;
+ return id;
+ }
+
+ /** @brief Gets pool ID by name */
+ u32 getPoolId(const std::string& name) const {
+ auto it = nameToId_.find(name);
+ return it != nameToId_.end() ? it->second : UINT32_MAX;
+ }
+
+ /** @brief Gets pool by ID */
+ SchemaComponentPool* getPool(u32 id) {
+ return id < pools_.size() ? pools_[id].get() : nullptr;
+ }
+
+ const SchemaComponentPool* getPool(u32 id) const {
+ return id < pools_.size() ? pools_[id].get() : nullptr;
+ }
+
+ // =========================================================================
+ // Component Operations
+ // =========================================================================
+
+ /**
+ * @brief Adds component to entity
+ * @return Byte offset in pool's data buffer
+ */
+ u32 addComponent(u32 poolId, Entity entity) {
+ ES_ASSERT(poolId < pools_.size(), "Invalid pool ID");
+ return pools_[poolId]->add(entity);
+ }
+
+ bool hasComponent(u32 poolId, Entity entity) const {
+ if (poolId >= pools_.size()) return false;
+ return pools_[poolId]->contains(entity);
+ }
+
+ u32 getComponentOffset(u32 poolId, Entity entity) const {
+ ES_ASSERT(poolId < pools_.size(), "Invalid pool ID");
+ return pools_[poolId]->getOffset(entity);
+ }
+
+ void removeComponent(u32 poolId, Entity entity) {
+ if (poolId < pools_.size()) {
+ pools_[poolId]->remove(entity);
+ }
+ }
+
+ /** @brief Gets base pointer for a pool */
+ uintptr_t getPoolBasePtr(u32 poolId) const {
+ if (poolId >= pools_.size()) return 0;
+ return pools_[poolId]->basePtr();
+ }
+
+ /** @brief Gets stride for a pool */
+ u32 getPoolStride(u32 poolId) const {
+ if (poolId >= pools_.size()) return 0;
+ return pools_[poolId]->stride();
+ }
+
+ /** @brief Gets entities with component */
+ const std::vector<Entity>& getEntities(u32 poolId) const {
+ static const std::vector<Entity> empty;
+ if (poolId >= pools_.size()) return empty;
+ return pools_[poolId]->entities();
+ }
+
+ // =========================================================================
+ // Entity Cleanup
+ // =========================================================================
+
+ /** @brief Removes all components from an entity */
+ void removeAll(Entity entity) {
+ for (auto& pool : pools_) {
+ pool->remove(entity);
+ }
+ }
+
+ /** @brief Clears all pools */
+ void clear() {
+ for (auto& pool : pools_) {
+ pool->clear();
+ }
+ }
+
+ usize poolCount() const { return pools_.size(); }
+
+private:
+ std::vector<Unique<SchemaComponentPool>> pools_;
+ std::unordered_map<std::string, u32> nameToId_;
+ std::unordered_map<u32, std::string> idToName_;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/Camera.hpp b/src/esengine/ecs/components/Camera.hpp
index aa41709dc..c99ae8ec1 100644
--- a/src/esengine/ecs/components/Camera.hpp
+++ b/src/esengine/ecs/components/Camera.hpp
@@ -27,9 +27,10 @@ namespace esengine::ecs {
/**
* @brief Camera projection type
*/
+ES_ENUM()
enum class ProjectionType : u8 {
- Perspective, ///< 3D perspective projection
- Orthographic ///< 2D orthographic projection
+ Perspective,
+ Orthographic
};
// =============================================================================
diff --git a/src/esengine/ecs/components/Canvas.hpp b/src/esengine/ecs/components/Canvas.hpp
index 82b433065..a09116d78 100644
--- a/src/esengine/ecs/components/Canvas.hpp
+++ b/src/esengine/ecs/components/Canvas.hpp
@@ -29,12 +29,13 @@ namespace esengine::ecs {
/**
* @brief Canvas scaling mode for different screen resolutions
*/
+ES_ENUM()
enum class CanvasScaleMode : u8 {
- FixedWidth, ///< Keep design width, adjust height
- FixedHeight, ///< Keep design height, adjust width
- Expand, ///< Expand to fill screen (may show more content)
- Shrink, ///< Shrink to fit screen (may show less content)
- Match ///< Match width/height by a blend factor
+ FixedWidth,
+ FixedHeight,
+ Expand,
+ Shrink,
+ Match
};
// =============================================================================
diff --git a/src/esengine/ecs/components/Common.hpp b/src/esengine/ecs/components/Common.hpp
index f6ae99164..79709f999 100644
--- a/src/esengine/ecs/components/Common.hpp
+++ b/src/esengine/ecs/components/Common.hpp
@@ -18,6 +18,9 @@
#include "../../core/Types.hpp"
#include <string>
+#include <unordered_map>
+#include <variant>
+#include <vector>
namespace esengine::ecs {
@@ -126,6 +129,73 @@ struct UUID {
bool operator!=(const UUID& other) const { return value != other.value; }
};
+// =============================================================================
+// Script Components
+// =============================================================================
+
+/** @brief Value type for script component fields */
+using ScriptFieldValue = std::variant<
+ f32,
+ i32,
+ bool,
+ std::string,
+ glm::vec2,
+ glm::vec3,
+ glm::vec4,
+ u32 // Entity reference
+>;
+
+/**
+ * @brief Instance of a script component attached to an entity
+ */
+struct ScriptInstance {
+ std::string componentName;
+ std::unordered_map<std::string, ScriptFieldValue> values;
+};
+
+/**
+ * @brief Component storing all script instances for an entity
+ */
+struct Scripts {
+ std::vector<ScriptInstance> instances;
+
+ /** @brief Check if entity has a specific script component */
+ bool has(const std::string& name) const {
+ for (const auto& inst : instances) {
+ if (inst.componentName == name) return true;
+ }
+ return false;
+ }
+
+ /** @brief Get script instance by name (nullptr if not found) */
+ ScriptInstance* get(const std::string& name) {
+ for (auto& inst : instances) {
+ if (inst.componentName == name) return &inst;
+ }
+ return nullptr;
+ }
+
+ const ScriptInstance* get(const std::string& name) const {
+ for (const auto& inst : instances) {
+ if (inst.componentName == name) return &inst;
+ }
+ return nullptr;
+ }
+
+ /** @brief Add a script instance */
+ void add(ScriptInstance&& instance) {
+ instances.push_back(std::move(instance));
+ }
+
+ /** @brief Remove script instance by name */
+ void remove(const std::string& name) {
+ instances.erase(
+ std::remove_if(instances.begin(), instances.end(),
+ [&name](const ScriptInstance& inst) { return inst.componentName == name; }),
+ instances.end());
+ }
+};
+
} // namespace esengine::ecs
// =============================================================================
diff --git a/src/esengine/editor/CMakeLists.txt b/src/esengine/editor/CMakeLists.txt
index 6a31489f6..4aba0fb4e 100644
--- a/src/esengine/editor/CMakeLists.txt
+++ b/src/esengine/editor/CMakeLists.txt
@@ -50,6 +50,12 @@ set(EDITOR_SOURCES
# Preview
preview/WebPreviewServer.cpp
preview/WebExporter.cpp
+
+ # Scene
+ scene/SceneSerializer.cpp
+
+ # Script
+ script/ScriptComponentRegistry.cpp
)
set(EDITOR_HEADERS
@@ -115,6 +121,12 @@ set(EDITOR_HEADERS
# Preview
preview/WebPreviewServer.hpp
preview/WebExporter.hpp
+
+ # Scene
+ scene/SceneSerializer.hpp
+
+ # Script
+ script/ScriptComponentRegistry.hpp
)
# Create editor executable
@@ -142,6 +154,7 @@ if(WIN32)
set_target_properties(esengine_editor PROPERTIES
WIN32_EXECUTABLE OFF
)
+ target_link_libraries(esengine_editor PRIVATE ws2_32)
endif()
# Copy assets or resources if needed (future)
diff --git a/src/esengine/editor/EditorApplication.cpp b/src/esengine/editor/EditorApplication.cpp
index 812948d04..fabf999b1 100644
--- a/src/esengine/editor/EditorApplication.cpp
+++ b/src/esengine/editor/EditorApplication.cpp
@@ -39,6 +39,7 @@
#include "widgets/EditorToolbar.hpp"
#include "../platform/FileDialog.hpp"
#include "preview/WebExporter.hpp"
+#include "scene/SceneSerializer.hpp"
#include <filesystem>
@@ -195,7 +196,6 @@ void EditorApplication::onUpdate(f32 deltaTime) {
if (frameTime_ >= FPS_UPDATE_INTERVAL) {
fps_ = static_cast<f32>(frameCount_) / static_cast<f32>(frameTime_);
- ES_LOG_TRACE("FPS: {:.1f}", fps_);
frameTime_ = 0.0;
frameCount_ = 0;
}
@@ -275,6 +275,42 @@ void EditorApplication::onKey(KeyCode key, bool pressed) {
handleRedo();
break;
+ case KeyCode::S:
+ if (mode_ == EditorMode::Editor && projectManager_->hasOpenProject()) {
+ if (shiftPressed_) {
+ // Ctrl+Shift+S: Save As
+ std::string scenesDir = ensureScenesDirectory();
+ std::string path = FileDialog::saveFile("Save Scene As",
+ {{"ESEngine Scene", "esscene"}}, scenesDir, "Untitled");
+ if (!path.empty()) {
+ saveSceneAs(path);
+ }
+ } else {
+ // Ctrl+S: Save
+ saveCurrentScene();
+ }
+ }
+ break;
+
+ case KeyCode::O:
+ if (mode_ == EditorMode::Editor && projectManager_->hasOpenProject()) {
+ // Ctrl+O: Open Scene
+ std::string scenesDir = ensureScenesDirectory();
+ std::string path = FileDialog::openFile("Open Scene",
+ {{"ESEngine Scene", "esscene"}}, scenesDir);
+ if (!path.empty()) {
+ loadScene(path);
+ }
+ }
+ break;
+
+ case KeyCode::N:
+ if (mode_ == EditorMode::Editor) {
+ // Ctrl+N: New Scene
+ newScene();
+ }
+ break;
+
default:
break;
}
@@ -362,8 +398,13 @@ void EditorApplication::setupEventListeners() {
eventConnections_.add(
dispatcher_.sink<ProjectOpened>().connect(
- [](const ProjectOpened& e) {
+ [this](const ProjectOpened& e) {
ES_LOG_INFO("Project opened: {} ({})", e.name, e.path);
+ // Scan TypeScript source for script component definitions
+ std::string projectDir = std::filesystem::path(e.path).parent_path().string();
+ if (scriptComponentRegistry_.scanProject(projectDir)) {
+ ES_LOG_INFO("Discovered {} script components", scriptComponentRegistry_.componentCount());
+ }
}));
eventConnections_.add(
@@ -404,10 +445,11 @@ void EditorApplication::setupEditorLayout() {
ES_LOG_INFO("setupEditorLayout: Creating HierarchyPanel...");
auto hierarchyPanel = makeUnique<HierarchyPanel>(registry_, selection_);
hierarchyPanel->setMinSize(glm::vec2(280.0f, 200.0f));
+ hierarchyPanel_ = hierarchyPanel.get();
dockArea_->addPanel(std::move(hierarchyPanel), ui::DockDropZone::Left, nullptr, 0.22f);
ES_LOG_INFO("setupEditorLayout: Creating InspectorPanel...");
- auto inspectorPanel = makeUnique<InspectorPanel>(registry_, selection_, commandHistory_);
+ auto inspectorPanel = makeUnique<InspectorPanel>(registry_, selection_, commandHistory_, &scriptComponentRegistry_);
inspectorPanel->setMinSize(glm::vec2(250.0f, 200.0f));
dockArea_->addPanel(std::move(inspectorPanel), ui::DockDropZone::Right, nullptr, 0.25f);
@@ -417,6 +459,14 @@ void EditorApplication::setupEditorLayout() {
auto assetBrowserPanel = makeUnique<AssetBrowserPanel>(assetDatabase_, thumbnailGenerator_);
assetBrowserPanel->setMinSize(glm::vec2(300.0f, 200.0f));
+ // Connect double-click handler for scene files
+ eventConnections_.add(sink(assetBrowserPanel->onAssetDoubleClicked).connect([this](const std::string& path) {
+ // Check if it's a scene file
+ if (path.size() > 8 && path.substr(path.size() - 8) == ".esscene") {
+ loadScene(path);
+ }
+ }));
+
editorRoot_->setAssetsDrawerContent(std::move(assetBrowserPanel));
ES_LOG_INFO("setupEditorLayout: Creating OutputLogPanel for drawer...");
@@ -453,25 +503,46 @@ void EditorApplication::setupEditorLayout() {
return;
}
+ // Export current scene for web preview
+ std::string projectPath = projectManager_->getCurrentProject().rootDirectory;
+ std::string mainScenePath = projectPath + "/assets/scenes/main.esscene";
+ std::filesystem::create_directories(std::filesystem::path(mainScenePath).parent_path());
+ if (!SceneSerializer::saveScene(getEditorRegistry(), mainScenePath, "main",
+ &getResourceManager(), projectPath)) {
+ ES_LOG_ERROR("Failed to export scene for web preview");
+ return;
+ }
+ ES_LOG_INFO("Exported scene for web preview: {}", mainScenePath);
+
+ if (WebExporter::isExporting()) {
+ ES_LOG_WARN("Export already in progress, please wait...");
+ return;
+ }
+
ES_LOG_INFO("Building and exporting project for web preview...");
- std::string projectPath = projectManager_->getCurrentProject().rootDirectory;
- bool success = WebExporter::exportProject(
+ WebExporter::exportProjectAsync(
projectPath,
sdkPath,
webBuildDir,
- [](const std::string& status, f32 progress) {
- ES_LOG_INFO("[{:.0f}%] {}", progress * 100.0f, status);
+ [toolbar, webBuildDir](bool success) {
+ if (!success) {
+ ES_LOG_ERROR("Failed to export web build");
+ return;
+ }
+ ES_LOG_INFO("Export complete, starting web preview...");
+ toolbar->startWebPreview(webBuildDir);
}
);
+ }
+ }));
- if (!success) {
- ES_LOG_ERROR("Failed to export web build");
- return;
- }
+ eventConnections_.add(sink(toolbar->onSave).connect([this]() {
+ saveCurrentScene();
+ }));
- toolbar->startWebPreview(webBuildDir);
- }
+ eventConnections_.add(sink(toolbar->onNewScene).connect([this]() {
+ newScene();
}));
uiContext_->setRoot(std::move(editorRoot));
@@ -546,6 +617,32 @@ void EditorApplication::createDemoScene() {
ES_LOG_INFO("Demo scene created with {} entities", registry_.entityCount());
}
+void EditorApplication::createEmptyScene() {
+ SceneSerializer::clearScene(getEditorRegistry());
+
+ Entity canvasEntity = registry_.create();
+ registry_.emplace<ecs::Name>(canvasEntity, "Canvas");
+ auto& canvas = registry_.emplace<ecs::Canvas>(canvasEntity);
+ canvas.designResolution = glm::uvec2(1920, 1080);
+ canvas.pixelsPerUnit = 100.0f;
+ canvas.scaleMode = ecs::CanvasScaleMode::FixedHeight;
+ canvas.backgroundColor = glm::vec4(0.1f, 0.1f, 0.15f, 1.0f);
+
+ Entity camera = registry_.create();
+ registry_.emplace<ecs::Name>(camera, "Main Camera");
+ registry_.emplace<ecs::LocalTransform>(camera, glm::vec3(0.0f, 0.0f, 10.0f));
+ auto& cam = registry_.emplace<ecs::Camera>(camera);
+ cam.isActive = true;
+ cam.priority = 0;
+ cam.projectionType = ecs::ProjectionType::Orthographic;
+ cam.orthoSize = canvas.getOrthoSize();
+
+ currentScenePath_.clear();
+ sceneDirty_ = false;
+
+ ES_LOG_INFO("Created empty scene with Canvas and Camera");
+}
+
// =============================================================================
// Mode Switching
// =============================================================================
@@ -643,7 +740,7 @@ void EditorApplication::showEditor() {
mode_ = EditorMode::Editor;
- createDemoScene();
+ createEmptyScene();
setupEditorLayout();
@@ -691,6 +788,14 @@ void EditorApplication::dockAssetBrowser() {
if (!dockedAssetBrowser_) {
auto assetBrowserPanel = makeUnique<AssetBrowserPanel>(assetDatabase_, thumbnailGenerator_);
assetBrowserPanel->setMinSize(glm::vec2(300.0f, 200.0f));
+
+ // Connect double-click handler for scene files
+ eventConnections_.add(sink(assetBrowserPanel->onAssetDoubleClicked).connect([this](const std::string& path) {
+ if (path.size() > 8 && path.substr(path.size() - 8) == ".esscene") {
+ loadScene(path);
+ }
+ }));
+
dockedAssetBrowser_ = assetBrowserPanel.get();
dockArea_->addPanel(std::move(assetBrowserPanel), ui::DockDropZone::Bottom, nullptr, 0.25f);
}
@@ -735,5 +840,111 @@ std::string EditorApplication::findWebSDKPath() {
return "";
}
+std::string EditorApplication::ensureScenesDirectory() {
+ namespace fs = std::filesystem;
+
+ if (!projectManager_->hasOpenProject()) {
+ return "";
+ }
+
+ std::string projectPath = projectManager_->getCurrentProject().rootDirectory;
+ fs::path scenesDir = fs::path(projectPath) / "assets" / "scenes";
+
+ if (!fs::exists(scenesDir)) {
+ try {
+ fs::create_directories(scenesDir);
+ ES_LOG_INFO("Created scenes directory: {}", scenesDir.string());
+ } catch (const std::exception& e) {
+ ES_LOG_ERROR("Failed to create scenes directory: {}", e.what());
+ return projectPath + "/assets";
+ }
+ }
+
+ return scenesDir.string();
+}
+
+// =============================================================================
+// Scene Management
+// =============================================================================
+
+void EditorApplication::newScene() {
+ ES_LOG_INFO("Creating new scene");
+
+ // Clear current scene
+ SceneSerializer::clearScene(getEditorRegistry());
+
+ // Reset scene state
+ currentScenePath_.clear();
+ sceneDirty_ = false;
+
+ // Clear selection
+ selection_.clear();
+
+ // Create default entities for new scene
+ createDemoScene();
+
+ // Refresh hierarchy panel
+ if (hierarchyPanel_) {
+ hierarchyPanel_->refresh();
+ }
+}
+
+bool EditorApplication::saveCurrentScene() {
+ if (currentScenePath_.empty()) {
+ // Need to use Save As dialog
+ std::string scenesDir = ensureScenesDirectory();
+ if (scenesDir.empty()) {
+ ES_LOG_ERROR("No project open, cannot save scene");
+ return false;
+ }
+
+ std::string path = FileDialog::saveFile("Save Scene",
+ {{"ESEngine Scene", "esscene"}}, scenesDir, "Untitled");
+ if (path.empty()) {
+ return false;
+ }
+ return saveSceneAs(path);
+ }
+
+ return saveSceneAs(currentScenePath_);
+}
+
+bool EditorApplication::saveSceneAs(const std::string& path) {
+ std::string sceneName = SceneSerializer::getSceneName(path);
+ std::string projectPath = projectManager_->hasOpenProject()
+ ? projectManager_->getCurrentProject().rootDirectory
+ : "";
+
+ if (SceneSerializer::saveScene(getEditorRegistry(), path, sceneName,
+ &getResourceManager(), projectPath)) {
+ currentScenePath_ = path;
+ sceneDirty_ = false;
+ ES_LOG_INFO("Scene saved: {}", path);
+ return true;
+ }
+
+ ES_LOG_ERROR("Failed to save scene: {}", path);
+ return false;
+}
+
+bool EditorApplication::loadScene(const std::string& path) {
+ if (SceneSerializer::loadScene(getEditorRegistry(), path)) {
+ currentScenePath_ = path;
+ sceneDirty_ = false;
+ selection_.clear();
+
+ // Refresh hierarchy panel to show loaded entities
+ if (hierarchyPanel_) {
+ hierarchyPanel_->refresh();
+ }
+
+ ES_LOG_INFO("Scene loaded: {}", path);
+ return true;
+ }
+
+ ES_LOG_ERROR("Failed to load scene: {}", path);
+ return false;
+}
+
} // namespace editor
} // namespace esengine
diff --git a/src/esengine/editor/EditorApplication.hpp b/src/esengine/editor/EditorApplication.hpp
index 02d17fe69..9fdb59937 100644
--- a/src/esengine/editor/EditorApplication.hpp
+++ b/src/esengine/editor/EditorApplication.hpp
@@ -28,6 +28,7 @@
#include "ThumbnailGenerator.hpp"
#include "DragDropManager.hpp"
#include "project/ProjectManager.hpp"
+#include "script/ScriptComponentRegistry.hpp"
namespace esengine {
namespace editor {
@@ -38,6 +39,7 @@ class EditorRootContainer;
class AssetBrowserPanel;
class GameViewPanel;
class SceneViewPanel;
+class HierarchyPanel;
// =============================================================================
// Editor Mode
@@ -142,6 +144,12 @@ public:
*/
ProjectManager& getProjectManager() { return *projectManager_; }
+ /**
+ * @brief Get the script component registry
+ * @return Reference to the script component registry
+ */
+ ScriptComponentRegistry& getScriptComponentRegistry() { return scriptComponentRegistry_; }
+
/**
* @brief Get current editor mode
* @return Current editor mode (Launcher or Editor)
@@ -158,6 +166,52 @@ public:
*/
void showEditor();
+ // =========================================================================
+ // Scene Management
+ // =========================================================================
+
+ /**
+ * @brief Create a new empty scene
+ */
+ void newScene();
+
+ /**
+ * @brief Save the current scene
+ * @return true if save succeeded
+ */
+ bool saveCurrentScene();
+
+ /**
+ * @brief Save the current scene to a new path
+ * @param path Path to save to
+ * @return true if save succeeded
+ */
+ bool saveSceneAs(const std::string& path);
+
+ /**
+ * @brief Load a scene from file
+ * @param path Path to .esscene file
+ * @return true if load succeeded
+ */
+ bool loadScene(const std::string& path);
+
+ /**
+ * @brief Get current scene path
+ * @return Path to current scene file, empty if unsaved
+ */
+ const std::string& getCurrentScenePath() const { return currentScenePath_; }
+
+ /**
+ * @brief Check if scene has unsaved changes
+ * @return true if scene is dirty
+ */
+ bool isSceneDirty() const { return sceneDirty_; }
+
+ /**
+ * @brief Mark scene as dirty (has unsaved changes)
+ */
+ void markSceneDirty() { sceneDirty_ = true; }
+
protected:
// =========================================================================
// Application Lifecycle Overrides
@@ -237,6 +291,11 @@ private:
*/
void createDemoScene();
+ /**
+ * @brief Create a minimal empty scene with Canvas and Camera
+ */
+ void createEmptyScene();
+
/**
* @brief Setup project launcher UI
*/
@@ -263,6 +322,12 @@ private:
*/
std::string findWebSDKPath();
+ /**
+ * @brief Ensure scenes directory exists and return its path
+ * @return Path to scenes directory
+ */
+ std::string ensureScenesDirectory();
+
// =========================================================================
// Constants
// =========================================================================
@@ -281,11 +346,13 @@ private:
ThumbnailGenerator thumbnailGenerator_; ///< Thumbnail generator
DragDropManager dragDropManager_; ///< Drag-drop manager
Unique<ProjectManager> projectManager_; ///< Project manager
+ ScriptComponentRegistry scriptComponentRegistry_; ///< Script component registry
Unique<ui::UIContext> uiContext_; ///< UI system context
ui::DockArea* dockArea_ = nullptr; ///< Main docking area (owned by UIContext)
EditorRootContainer* editorRoot_ = nullptr; ///< Editor root container
GameViewPanel* gameViewPanel_ = nullptr; ///< Game view panel
SceneViewPanel* sceneViewPanel_ = nullptr; ///< Scene view panel
+ HierarchyPanel* hierarchyPanel_ = nullptr; ///< Hierarchy panel
AssetBrowserPanel* dockedAssetBrowser_ = nullptr; ///< Docked asset browser (if any)
ProjectLauncherPanel* launcherPanel_ = nullptr; ///< Launcher panel (owned by UIContext)
NewProjectDialog* newProjectDialog_ = nullptr; ///< New project dialog
@@ -304,6 +371,13 @@ private:
bool altPressed_ = false; ///< Alt key state
bool pendingShowEditor_ = false; ///< Deferred mode switch flag
+ // =========================================================================
+ // Scene State
+ // =========================================================================
+
+ std::string currentScenePath_; ///< Path to current scene file
+ bool sceneDirty_ = false; ///< Whether scene has unsaved changes
+
// =========================================================================
// Event Connections
// =========================================================================
diff --git a/src/esengine/editor/panels/AssetBrowserPanel.cpp b/src/esengine/editor/panels/AssetBrowserPanel.cpp
index ef0f68ef6..b1be79f32 100644
--- a/src/esengine/editor/panels/AssetBrowserPanel.cpp
+++ b/src/esengine/editor/panels/AssetBrowserPanel.cpp
@@ -607,11 +607,11 @@ void AssetBrowserPanel::createScene() {
#endif
std::string baseName = "New Scene";
- std::string scenePath = currentPath_ + "/" + baseName + ".scene";
+ std::string scenePath = currentPath_ + "/" + baseName + ".esscene";
i32 counter = 1;
while (FileSystem::fileExists(scenePath)) {
- scenePath = currentPath_ + "/" + baseName + " " + std::to_string(counter) + ".scene";
+ scenePath = currentPath_ + "/" + baseName + " " + std::to_string(counter) + ".esscene";
++counter;
}
diff --git a/src/esengine/editor/panels/HierarchyPanel.cpp b/src/esengine/editor/panels/HierarchyPanel.cpp
index 76111ee56..6b18b0a5b 100644
--- a/src/esengine/editor/panels/HierarchyPanel.cpp
+++ b/src/esengine/editor/panels/HierarchyPanel.cpp
@@ -312,7 +312,7 @@ bool HierarchyPanel::onKeyDown(const ui::KeyEvent& event) {
// =============================================================================
void HierarchyPanel::refresh() {
- needsRebuild_ = true;
+ rebuildTree();
}
void HierarchyPanel::setShowOrphans(bool showOrphans) {
@@ -357,6 +357,13 @@ void HierarchyPanel::rebuildTree() {
allEntities.push_back(entity);
});
+ // Sort entities by name for consistent ordering
+ std::sort(allEntities.begin(), allEntities.end(), [this](Entity a, Entity b) {
+ std::string nameA = getEntityDisplayName(a);
+ std::string nameB = getEntityDisplayName(b);
+ return nameA < nameB;
+ });
+
ES_LOG_DEBUG("HierarchyPanel::rebuildTree: Found {} entities", allEntities.size());
// Convert search filter to lowercase for case-insensitive search
@@ -417,19 +424,27 @@ ui::TreeNodeId HierarchyPanel::addEntityToTree(Entity entity, ui::TreeNodeId par
// Add children if entity has Children component
if (registry_.has<ecs::Children>(entity)) {
const auto& children = registry_.get<ecs::Children>(entity);
+
+ // Sort children by name for consistent ordering
+ std::vector<Entity> sortedChildren;
for (Entity childEntity : children.entities) {
- // Verify child is valid
- if (!registry_.valid(childEntity)) {
+ if (registry_.valid(childEntity)) {
+ sortedChildren.push_back(childEntity);
+ } else {
ES_LOG_WARN("HierarchyPanel: Invalid child entity {} for parent {}",
childEntity, entity);
- continue;
}
+ }
+ std::sort(sortedChildren.begin(), sortedChildren.end(), [this](Entity a, Entity b) {
+ return getEntityDisplayName(a) < getEntityDisplayName(b);
+ });
+ for (Entity childEntity : sortedChildren) {
addEntityToTree(childEntity, nodeId);
}
// Expand node if it has children
- if (!children.empty()) {
+ if (!sortedChildren.empty()) {
treeView_->setNodeExpanded(nodeId, true);
}
}
diff --git a/src/esengine/editor/panels/InspectorPanel.cpp b/src/esengine/editor/panels/InspectorPanel.cpp
index 83ccdfde9..131af31dc 100644
--- a/src/esengine/editor/panels/InspectorPanel.cpp
+++ b/src/esengine/editor/panels/InspectorPanel.cpp
@@ -34,11 +34,13 @@ namespace esengine::editor {
InspectorPanel::InspectorPanel(ecs::Registry& registry,
EntitySelection& selection,
- CommandHistory& history)
+ CommandHistory& history,
+ ScriptComponentRegistry* scriptRegistry)
: DockPanel(ui::WidgetId("inspector_panel"), "Inspector"),
registry_(registry),
selection_(selection),
- history_(history) {
+ history_(history),
+ scriptRegistry_(scriptRegistry) {
setPanelType("Inspector");
setClosable(false);
@@ -431,6 +433,12 @@ void InspectorPanel::rebuildInspector() {
componentCount++;
}
+ // Script components
+ if (registry_.has<ecs::Scripts>(currentEntity_)) {
+ addScriptComponentEditors(currentEntity_);
+ componentCount += static_cast<i32>(registry_.get<ecs::Scripts>(currentEntity_).instances.size());
+ }
+
if (componentCountLabel_) {
std::string countText = std::to_string(componentCount) +
(componentCount == 1 ? " component" : " components");
@@ -1008,4 +1016,233 @@ void InspectorPanel::addTagsEditor(Entity entity) {
widgets.content->addChild(std::move(staticEditor));
}
+void InspectorPanel::addScriptComponentEditors(Entity entity) {
+ if (!registry_.has<ecs::Scripts>(entity)) return;
+
+ auto& scripts = registry_.get<ecs::Scripts>(entity);
+
+ for (auto& instance : scripts.instances) {
+ // Get field definitions from registry if available
+ const ScriptComponentDef* def = nullptr;
+ if (scriptRegistry_) {
+ def = scriptRegistry_->getComponent(instance.componentName);
+ }
+
+ auto widgets = createComponentSection(instance.componentName, ui::icons::Code);
+
+ for (auto& [fieldName, fieldValue] : instance.values) {
+ ScriptFieldType fieldType = ScriptFieldType::F32; // Default
+
+ // Try to get type from definition
+ if (def) {
+ for (const auto& field : def->fields) {
+ if (field.name == fieldName) {
+ fieldType = field.type;
+ break;
+ }
+ }
+ }
+
+ // Create appropriate editor based on field type
+ std::string fieldId = widgets.content->getId().path + "_" + fieldName;
+
+ switch (fieldType) {
+ case ScriptFieldType::F32: {
+ auto editor = makeUnique<FloatEditor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<f32>(fieldValue)) {
+ editor->setValue(std::get<f32>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<f32>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::I32: {
+ auto editor = makeUnique<IntEditor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<i32>(fieldValue)) {
+ editor->setValue(std::get<i32>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<i32>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::Bool: {
+ auto editor = makeUnique<BoolEditor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<bool>(fieldValue)) {
+ editor->setValue(std::get<bool>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<bool>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::String: {
+ auto editor = makeUnique<StringEditor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<std::string>(fieldValue)) {
+ editor->setValue(std::get<std::string>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<std::string>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::Vec2: {
+ auto editor = makeUnique<Vector2Editor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<glm::vec2>(fieldValue)) {
+ editor->setValue(std::get<glm::vec2>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<glm::vec2>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::Vec3: {
+ auto editor = makeUnique<Vector3Editor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<glm::vec3>(fieldValue)) {
+ editor->setValue(std::get<glm::vec3>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<glm::vec3>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::Vec4:
+ case ScriptFieldType::Color: {
+ auto editor = makeUnique<ColorEditor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName);
+ if (std::holds_alternative<glm::vec4>(fieldValue)) {
+ editor->setValue(std::get<glm::vec4>(fieldValue));
+ }
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = std::any_cast<glm::vec4>(value);
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+
+ case ScriptFieldType::Entity: {
+ auto editor = makeUnique<IntEditor>(ui::WidgetId(fieldId), fieldName);
+ editor->setLabel(fieldName + " (Entity)");
+ if (std::holds_alternative<u32>(fieldValue)) {
+ editor->setValue(static_cast<i32>(std::get<u32>(fieldValue)));
+ }
+ editor->setRange(0, 1000000);
+ editor->setCommandHistory(&history_);
+
+ editorConnections_.add(sink(editor->onValueChanged).connect(
+ [this, entity, compName = instance.componentName, fieldName](const std::any& value) {
+ if (!registry_.valid(entity) || !registry_.has<ecs::Scripts>(entity)) return;
+ auto& s = registry_.get<ecs::Scripts>(entity);
+ if (auto* inst = s.get(compName)) {
+ try {
+ inst->values[fieldName] = static_cast<u32>(std::any_cast<i32>(value));
+ } catch (const std::bad_any_cast&) {}
+ }
+ }
+ ));
+
+ widgets.content->addChild(std::move(editor));
+ break;
+ }
+ }
+ }
+ }
+}
+
} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/InspectorPanel.hpp b/src/esengine/editor/panels/InspectorPanel.hpp
index 6091647d1..de5a1b418 100644
--- a/src/esengine/editor/panels/InspectorPanel.hpp
+++ b/src/esengine/editor/panels/InspectorPanel.hpp
@@ -33,6 +33,7 @@
#include "../property/editors/ColorEditor.hpp"
#include "../property/editors/EnumEditor.hpp"
#include "../../events/Connection.hpp"
+#include "../script/ScriptComponentRegistry.hpp"
#include <unordered_set>
#include <unordered_map>
@@ -62,10 +63,12 @@ public:
* @param registry Entity registry
* @param selection Entity selection manager
* @param history Command history for undo/redo
+ * @param scriptRegistry Script component registry (optional)
*/
InspectorPanel(ecs::Registry& registry,
EntitySelection& selection,
- CommandHistory& history);
+ CommandHistory& history,
+ ScriptComponentRegistry* scriptRegistry = nullptr);
~InspectorPanel() override;
@@ -108,10 +111,12 @@ private:
void addCameraEditor(Entity entity);
void addSpriteEditor(Entity entity);
void addTagsEditor(Entity entity);
+ void addScriptComponentEditors(Entity entity);
ecs::Registry& registry_;
EntitySelection& selection_;
CommandHistory& history_;
+ ScriptComponentRegistry* scriptRegistry_ = nullptr;
ui::Panel* rootPanel_ = nullptr;
ui::Panel* headerPanel_ = nullptr;
diff --git a/src/esengine/editor/preview/WebExporter.cpp b/src/esengine/editor/preview/WebExporter.cpp
index e7313e963..b4bfafbc5 100644
--- a/src/esengine/editor/preview/WebExporter.cpp
+++ b/src/esengine/editor/preview/WebExporter.cpp
@@ -11,16 +11,48 @@
#include "WebExporter.hpp"
#include "../../core/Log.hpp"
+#include "../../platform/FileSystem.hpp"
+#include "../../platform/PathResolver.hpp"
#include <cstdlib>
#include <filesystem>
#include <fstream>
-#include <sstream>
namespace fs = std::filesystem;
namespace esengine::editor {
+std::atomic<bool> WebExporter::exporting_{false};
+std::future<bool> WebExporter::exportFuture_;
+
+bool WebExporter::isExporting() {
+ return exporting_.load();
+}
+
+void WebExporter::exportProjectAsync(
+ const std::string& projectPath,
+ const std::string& sdkPath,
+ const std::string& outputPath,
+ CompletionCallback onComplete
+) {
+ if (exporting_.load()) {
+ ES_LOG_WARN("Export already in progress");
+ if (onComplete) onComplete(false);
+ return;
+ }
+
+ exporting_.store(true);
+
+ exportFuture_ = std::async(std::launch::async,
+ [projectPath, sdkPath, outputPath, onComplete]() {
+ bool result = exportProject(projectPath, sdkPath, outputPath, nullptr);
+ exporting_.store(false);
+ if (onComplete) onComplete(result);
+ return result;
+ }
+ );
+}
+
bool WebExporter::exportProject(
const std::string& projectPath,
const std::string& sdkPath,
@@ -146,15 +178,8 @@ bool WebExporter::compileTypeScript(const std::string& projectPath, ProgressCall
fs::create_directories(buildDir);
}
- // Check if already compiled and up to date
- if (fs::exists(mainJs)) {
- auto srcTime = fs::last_write_time(mainTs);
- auto jsTime = fs::last_write_time(mainJs);
- if (jsTime >= srcTime) {
- ES_LOG_DEBUG("TypeScript already compiled and up to date");
- return true;
- }
- }
+ // Always recompile for web preview to ensure latest SDK changes are included
+ // (SDK files in node_modules/esengine may have been updated)
// Run esbuild to bundle and compile
ES_LOG_INFO("Bundling TypeScript with esbuild...");
@@ -259,100 +284,26 @@ bool WebExporter::copyAssets(const std::string& projectPath, const std::string&
}
bool WebExporter::generateIndexHtml(const std::string& outputPath, const std::string& projectName) {
- std::ostringstream html;
- html << R"(<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
- <title>)" << projectName << R"(</title>
- <style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- html, body {
- width: 100%;
- height: 100%;
- overflow: hidden;
- background-color: #1a1a1a;
- }
- #canvas {
- display: block;
- width: 100%;
- height: 100%;
- touch-action: none;
- }
- #loading {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- color: #fff;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- font-size: 16px;
- text-align: center;
- }
- #loading.hidden { display: none; }
- .spinner {
- width: 40px;
- height: 40px;
- margin: 0 auto 16px;
- border: 3px solid #333;
- border-top-color: #3b82f6;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- }
- @keyframes spin { to { transform: rotate(360deg); } }
- </style>
-</head>
-<body>
- <div id="loading">
- <div class="spinner"></div>
- <div>Loading...</div>
- </div>
- <canvas id="canvas"></canvas>
-
- <script type="module">
- import ESEngineModule from './esengine.js';
- import { main } from './scripts/main.js';
-
- function resizeCanvas() {
- const canvas = document.getElementById('canvas');
- const dpr = window.devicePixelRatio || 1;
- canvas.width = window.innerWidth * dpr;
- canvas.height = window.innerHeight * dpr;
- }
- window.addEventListener('resize', resizeCanvas);
- resizeCanvas();
-
- ESEngineModule({
- canvas: document.getElementById('canvas'),
- print: (text) => console.log(text),
- printErr: (text) => console.error(text)
- }).then((Module) => {
- console.log('ESEngine loaded');
- document.getElementById('loading').classList.add('hidden');
- main(Module);
- }).catch((err) => {
- if (err === 'unwind' || (err.message && err.message.includes('unwind'))) {
- console.log('App running');
- return;
- }
- console.error('Failed:', err);
- document.getElementById('loading').innerHTML = '<div style="color:#f87171">Error: ' + err.message + '</div>';
- });
- </script>
-</body>
-</html>
-)";
-
- fs::path indexPath = fs::path(outputPath) / "index.html";
- std::ofstream file(indexPath);
- if (!file) {
- ES_LOG_ERROR("Failed to create index.html");
+ std::string templatePath = PathResolver::editorPath("assets/templates/web/index.html");
+ std::string content = FileSystem::readTextFile(templatePath);
+
+ if (content.empty()) {
+ ES_LOG_ERROR("Failed to read index.html template from {}", templatePath);
return false;
}
- file << html.str();
- file.close();
+ std::string placeholder = "{{PROJECT_NAME}}";
+ size_t pos = 0;
+ while ((pos = content.find(placeholder, pos)) != std::string::npos) {
+ content.replace(pos, placeholder.length(), projectName);
+ pos += projectName.length();
+ }
+
+ std::string indexPath = outputPath + "/index.html";
+ if (!FileSystem::writeTextFile(indexPath, content)) {
+ ES_LOG_ERROR("Failed to write index.html");
+ return false;
+ }
ES_LOG_DEBUG("Generated index.html");
return true;
diff --git a/src/esengine/editor/preview/WebExporter.hpp b/src/esengine/editor/preview/WebExporter.hpp
index ea1a3d223..c341f9f9a 100644
--- a/src/esengine/editor/preview/WebExporter.hpp
+++ b/src/esengine/editor/preview/WebExporter.hpp
@@ -13,6 +13,8 @@
#include "../../core/Types.hpp"
#include <string>
#include <functional>
+#include <future>
+#include <atomic>
namespace esengine::editor {
@@ -22,14 +24,10 @@ namespace esengine::editor {
class WebExporter {
public:
using ProgressCallback = std::function<void(const std::string& status, f32 progress)>;
+ using CompletionCallback = std::function<void(bool success)>;
/**
- * @brief Export project to web format
- * @param projectPath Root directory of the game project
- * @param sdkPath Path to the prebuilt web SDK (build-web/sdk)
- * @param outputPath Output directory (usually project/build/web)
- * @param callback Optional progress callback
- * @return true if export succeeded
+ * @brief Export project to web format (blocking)
*/
static bool exportProject(
const std::string& projectPath,
@@ -38,7 +36,23 @@ public:
ProgressCallback callback = nullptr
);
+ /**
+ * @brief Export project to web format (async, non-blocking)
+ */
+ static void exportProjectAsync(
+ const std::string& projectPath,
+ const std::string& sdkPath,
+ const std::string& outputPath,
+ CompletionCallback onComplete
+ );
+
+ /** @brief Check if async export is running */
+ static bool isExporting();
+
private:
+ static std::atomic<bool> exporting_;
+ static std::future<bool> exportFuture_;
+
static bool ensureDependencies(const std::string& projectPath, ProgressCallback& callback);
static bool compileTypeScript(const std::string& projectPath, ProgressCallback& callback);
static bool copySDKFiles(const std::string& sdkPath, const std::string& outputPath, ProgressCallback& callback);
diff --git a/src/esengine/editor/preview/WebPreviewServer.cpp b/src/esengine/editor/preview/WebPreviewServer.cpp
index e9357f599..588cf3304 100644
--- a/src/esengine/editor/preview/WebPreviewServer.cpp
+++ b/src/esengine/editor/preview/WebPreviewServer.cpp
@@ -17,11 +17,15 @@
#ifdef ES_PLATFORM_WINDOWS
#include <shellapi.h>
+#include <ws2tcpip.h>
#else
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <cstdlib>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
#endif
namespace esengine {
@@ -51,11 +55,25 @@ bool WebPreviewServer::start(const std::string& directory, u16 port) {
}
directory_ = directory;
- port_ = port;
+
+ constexpr int MAX_PORT_ATTEMPTS = 10;
+ u16 selectedPort = port;
+ for (int i = 0; i < MAX_PORT_ATTEMPTS; ++i) {
+ if (isPortAvailable(selectedPort)) {
+ break;
+ }
+ ES_LOG_WARN("Port {} is in use, trying {}", selectedPort, selectedPort + 1);
+ ++selectedPort;
+ if (i == MAX_PORT_ATTEMPTS - 1) {
+ ES_LOG_ERROR("Could not find available port after {} attempts", MAX_PORT_ATTEMPTS);
+ return false;
+ }
+ }
+ port_ = selectedPort;
#ifdef ES_PLATFORM_WINDOWS
std::stringstream cmd;
- cmd << "python -m http.server " << port << " --directory \"" << directory << "\"";
+ cmd << "python -m http.server " << port_ << " --directory \"" << directory << "\"";
STARTUPINFOA si = {};
si.cb = sizeof(si);
@@ -91,7 +109,7 @@ bool WebPreviewServer::start(const std::string& directory, u16 port) {
}
if (pid_ == 0) {
- std::string portStr = std::to_string(port);
+ std::string portStr = std::to_string(port_);
execlp("python3", "python3", "-m", "http.server", portStr.c_str(),
"--directory", directory.c_str(), nullptr);
execlp("python", "python", "-m", "http.server", portStr.c_str(),
@@ -150,5 +168,46 @@ void WebPreviewServer::openInBrowser(const std::string& url) {
#endif
}
+bool WebPreviewServer::isPortAvailable(u16 port) {
+#ifdef ES_PLATFORM_WINDOWS
+ WSADATA wsaData;
+ if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
+ return false;
+ }
+
+ SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (sock == INVALID_SOCKET) {
+ WSACleanup();
+ return false;
+ }
+
+ sockaddr_in addr = {};
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ addr.sin_port = htons(port);
+
+ int result = bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
+ closesocket(sock);
+ WSACleanup();
+
+ return result == 0;
+#else
+ int sock = socket(AF_INET, SOCK_STREAM, 0);
+ if (sock < 0) {
+ return false;
+ }
+
+ sockaddr_in addr = {};
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ addr.sin_port = htons(port);
+
+ int result = bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
+ close(sock);
+
+ return result == 0;
+#endif
+}
+
} // namespace editor
} // namespace esengine
diff --git a/src/esengine/editor/preview/WebPreviewServer.hpp b/src/esengine/editor/preview/WebPreviewServer.hpp
index 22decf62c..b68c049cc 100644
--- a/src/esengine/editor/preview/WebPreviewServer.hpp
+++ b/src/esengine/editor/preview/WebPreviewServer.hpp
@@ -15,6 +15,7 @@
#ifdef ES_PLATFORM_WINDOWS
#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
#include <windows.h>
#endif
@@ -36,6 +37,7 @@ public:
std::string getUrl() const;
static void openInBrowser(const std::string& url);
+ static bool isPortAvailable(u16 port);
private:
bool running_ = false;
diff --git a/src/esengine/editor/project/ProjectManager.cpp b/src/esengine/editor/project/ProjectManager.cpp
index e1d7d0877..22947035d 100644
--- a/src/esengine/editor/project/ProjectManager.cpp
+++ b/src/esengine/editor/project/ProjectManager.cpp
@@ -20,6 +20,8 @@
#include <algorithm>
#include <chrono>
+#include <filesystem>
+#include <unordered_map>
namespace esengine::editor {
@@ -238,138 +240,80 @@ const RecentProjectsManager& ProjectManager::getRecentProjects() const {
void ProjectManager::createDirectoryStructure(const std::string& rootDir) {
const std::vector<std::string> directories = {
- "/src", // User source code
- "/assets", // Resources only
+ "/src",
+ "/src/components",
+ "/src/systems",
+ "/assets",
"/assets/scenes",
"/assets/textures",
"/assets/audio",
"/assets/fonts",
"/assets/prefabs",
"/assets/shaders",
- "/build", // Build output (should be gitignored)
- "/.esengine" // Editor cache (should be gitignored)
+ "/build",
+ "/.esengine"
};
for (const auto& dir : directories) {
FileSystem::createDirectory(rootDir + dir);
}
- createProjectFiles(rootDir);
- createGitignore(rootDir);
+ copyTemplates(rootDir);
}
-void ProjectManager::createProjectFiles(const std::string& rootDir) {
- std::string sdkDir = PathResolver::editorPath("bindings");
- // Convert backslashes to forward slashes for JSON/npm compatibility
+void ProjectManager::copyTemplates(const std::string& rootDir) {
+ std::string templateDir = PathResolver::editorPath("assets/templates");
+ std::string sdkDir = PathResolver::editorPath("sdk");
std::replace(sdkDir.begin(), sdkDir.end(), '\\', '/');
- // Generate package.json in project root
- std::string packageJson = R"({
- "name": ")" + current_project_.name + R"(",
- "version": "1.0.0",
- "type": "module",
- "scripts": {
- "build": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/js/main.js --sourcemap",
- "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/js/main.js --sourcemap --watch",
- "typecheck": "npx tsc --noEmit"
- },
- "dependencies": {
- "esengine": "file:)" + sdkDir + R"("
- },
- "devDependencies": {
- "esbuild": "^0.20.0",
- "typescript": "^5.0.0"
- }
-}
-)";
- FileSystem::writeTextFile(rootDir + "/package.json", packageJson);
- ES_LOG_DEBUG("Created package.json");
-
- // Generate tsconfig.json in project root (for type checking and IDE support)
- std::string tsconfig = R"({
- "compilerOptions": {
- "target": "ES2020",
- "module": "ESNext",
- "lib": ["ES2020", "DOM"],
- "moduleResolution": "node",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "noEmit": true
- },
- "include": ["src/**/*.ts"],
- "exclude": ["node_modules", "build"]
+ std::unordered_map<std::string, std::string> vars = {
+ {"{{PROJECT_NAME}}", current_project_.name},
+ {"{{SDK_PATH}}", sdkDir}
+ };
+
+ copyTemplateDirectory(templateDir, rootDir, vars);
}
-)";
- FileSystem::writeTextFile(rootDir + "/tsconfig.json", tsconfig);
- ES_LOG_DEBUG("Created tsconfig.json");
-
- // Create main.ts in src/ directory
- std::string mainScript = R"(/**
- * @file main.ts
- * @brief Game entry point
- */
-import { App, StartupSystem, LocalTransform, Sprite } from 'esengine';
-
-class SetupSystem extends StartupSystem {
- onStart(): void {
- // Create a simple sprite entity
- this.world_.spawn()
- .with(LocalTransform, {
- position: { x: 400, y: 300, z: 0 }
- })
- .with(Sprite, {
- color: { x: 1, y: 1, z: 1, w: 1 },
- size: { x: 64, y: 64 }
- });
-
- console.log('Game started!');
+void ProjectManager::copyTemplateFile(const std::string& src, const std::string& dst,
+ const std::unordered_map<std::string, std::string>& vars) {
+ std::string content = FileSystem::readTextFile(src);
+ if (content.empty()) {
+ ES_LOG_WARN("Template file empty or not found: {}", src);
+ return;
}
-}
-/**
- * Game entry point - called by the engine after WASM is loaded
- */
-export function main(module: any): void {
- const app = new App(module, {
- title: ')" + current_project_.name + R"(',
- width: 800,
- height: 600
- });
+ for (const auto& [key, value] : vars) {
+ usize pos = 0;
+ while ((pos = content.find(key, pos)) != std::string::npos) {
+ content.replace(pos, key.length(), value);
+ pos += value.length();
+ }
+ }
- app.addStartupSystem(new SetupSystem());
- app.run();
-}
-)";
- FileSystem::writeTextFile(rootDir + "/src/main.ts", mainScript);
- ES_LOG_DEBUG("Created src/main.ts");
+ FileSystem::writeTextFile(dst, content);
+ ES_LOG_DEBUG("Created {}", dst);
}
-void ProjectManager::createGitignore(const std::string& rootDir) {
- std::string gitignore = R"(# Dependencies
-node_modules/
-
-# Build output
-build/
-dist/
-
-# Editor cache
-.esengine/
-
-# IDE
-.vscode/
-.idea/
-*.swp
-*.swo
-
-# OS
-.DS_Store
-Thumbs.db
-)";
- FileSystem::writeTextFile(rootDir + "/.gitignore", gitignore);
- ES_LOG_DEBUG("Created .gitignore");
+void ProjectManager::copyTemplateDirectory(const std::string& srcDir, const std::string& dstDir,
+ const std::unordered_map<std::string, std::string>& vars) {
+ namespace fs = std::filesystem;
+
+ if (!fs::exists(srcDir)) {
+ ES_LOG_ERROR("Template directory not found: {}", srcDir);
+ return;
+ }
+
+ for (const auto& entry : fs::recursive_directory_iterator(srcDir)) {
+ std::string relativePath = fs::relative(entry.path(), srcDir).string();
+ std::string dstPath = dstDir + "/" + relativePath;
+ std::replace(dstPath.begin(), dstPath.end(), '\\', '/');
+
+ if (entry.is_directory()) {
+ FileSystem::createDirectory(dstPath);
+ } else if (entry.is_regular_file()) {
+ copyTemplateFile(entry.path().string(), dstPath, vars);
+ }
+ }
}
void ProjectManager::updatePathResolver(const std::string& rootDir) {
@@ -417,47 +361,28 @@ void ProjectManager::checkAndSyncDependencies() {
std::string nodeModulesPath = rootDir + "/node_modules";
std::string esengineModulePath = nodeModulesPath + "/esengine";
- // Check if package.json exists
if (!FileSystem::fileExists(packageJsonPath)) {
- ES_LOG_INFO("No package.json found, creating project files...");
- createProjectFiles(rootDir);
+ ES_LOG_INFO("No package.json found, copying templates...");
+ copyTemplates(rootDir);
return;
}
- // Check if node_modules/esengine exists
if (!FileSystem::directoryExists(esengineModulePath)) {
ES_LOG_WARN("Dependencies not installed. Please run 'npm install' in {}", rootDir);
}
- // Update package.json with current SDK path (in case engine location changed)
- std::string sdkDir = PathResolver::editorPath("bindings");
- // Convert backslashes to forward slashes for JSON/npm compatibility
+ std::string sdkDir = PathResolver::editorPath("sdk");
std::replace(sdkDir.begin(), sdkDir.end(), '\\', '/');
std::string currentPackageJson = FileSystem::readTextFile(packageJsonPath);
- // Check if SDK path needs updating
if (currentPackageJson.find(sdkDir) == std::string::npos) {
ES_LOG_INFO("Updating package.json with current SDK path...");
-
- std::string packageJson = R"({
- "name": ")" + current_project_.name + R"(",
- "version": "1.0.0",
- "type": "module",
- "scripts": {
- "build": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/js/main.js --sourcemap",
- "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/js/main.js --sourcemap --watch",
- "typecheck": "npx tsc --noEmit"
- },
- "dependencies": {
- "esengine": "file:)" + sdkDir + R"("
- },
- "devDependencies": {
- "esbuild": "^0.20.0",
- "typescript": "^5.0.0"
- }
-}
-)";
- FileSystem::writeTextFile(packageJsonPath, packageJson);
+ std::string templatePath = PathResolver::editorPath("assets/templates/package.json");
+ std::unordered_map<std::string, std::string> vars = {
+ {"{{PROJECT_NAME}}", current_project_.name},
+ {"{{SDK_PATH}}", sdkDir}
+ };
+ copyTemplateFile(templatePath, packageJsonPath, vars);
ES_LOG_INFO("package.json updated. Please run 'npm install' to update dependencies.");
}
}
diff --git a/src/esengine/editor/project/ProjectManager.hpp b/src/esengine/editor/project/ProjectManager.hpp
index 6781766ff..dbfa72260 100644
--- a/src/esengine/editor/project/ProjectManager.hpp
+++ b/src/esengine/editor/project/ProjectManager.hpp
@@ -18,6 +18,9 @@
#include "RecentProjectsManager.hpp"
#include "../../core/Types.hpp"
+#include <string>
+#include <unordered_map>
+
namespace esengine {
class Dispatcher;
}
@@ -81,9 +84,12 @@ public:
private:
void createDirectoryStructure(const std::string& rootDir);
- void createProjectFiles(const std::string& rootDir);
- void createGitignore(const std::string& rootDir);
+ void copyTemplates(const std::string& rootDir);
void checkAndSyncDependencies();
+ void copyTemplateFile(const std::string& src, const std::string& dst,
+ const std::unordered_map<std::string, std::string>& vars);
+ void copyTemplateDirectory(const std::string& srcDir, const std::string& dstDir,
+ const std::unordered_map<std::string, std::string>& vars);
void updatePathResolver(const std::string& rootDir);
void initializeAssetDatabase(const std::string& rootDir);
void fireProjectOpenedEvent();
diff --git a/src/esengine/editor/scene/SceneSerializer.cpp b/src/esengine/editor/scene/SceneSerializer.cpp
new file mode 100644
index 000000000..acbd64e40
--- /dev/null
+++ b/src/esengine/editor/scene/SceneSerializer.cpp
@@ -0,0 +1,863 @@
+/**
+ * @file SceneSerializer.cpp
+ * @brief Scene serialization implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "SceneSerializer.hpp"
+#include "../../core/Log.hpp"
+#include "../../ecs/Component.hpp"
+#include "../../ecs/components/Canvas.hpp"
+
+#include <filesystem>
+#include <fstream>
+#include <random>
+#include <sstream>
+#include <unordered_map>
+
+namespace fs = std::filesystem;
+
+namespace esengine::editor {
+
+// =============================================================================
+// Helper Functions
+// =============================================================================
+
+namespace {
+
+std::string escapeJsonString(const std::string& str) {
+ std::string result;
+ result.reserve(str.size() + 16);
+ for (char c : str) {
+ switch (c) {
+ case '"': result += "\\\""; break;
+ case '\\': result += "\\\\"; break;
+ case '\n': result += "\\n"; break;
+ case '\r': result += "\\r"; break;
+ case '\t': result += "\\t"; break;
+ default: result += c; break;
+ }
+ }
+ return result;
+}
+
+std::string unescapeJsonString(const std::string& str) {
+ std::string result;
+ result.reserve(str.size());
+ for (usize i = 0; i < str.size(); ++i) {
+ if (str[i] == '\\' && i + 1 < str.size()) {
+ switch (str[i + 1]) {
+ case '"': result += '"'; ++i; break;
+ case '\\': result += '\\'; ++i; break;
+ case 'n': result += '\n'; ++i; break;
+ case 'r': result += '\r'; ++i; break;
+ case 't': result += '\t'; ++i; break;
+ default: result += str[i]; break;
+ }
+ } else {
+ result += str[i];
+ }
+ }
+ return result;
+}
+
+u64 generateUUID() {
+ static std::random_device rd;
+ static std::mt19937_64 gen(rd());
+ static std::uniform_int_distribution<u64> dis;
+ return dis(gen);
+}
+
+std::string extractString(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return "";
+
+ usize valueStart = json.find("\"", keyPos + searchKey.size());
+ if (valueStart == std::string::npos) return "";
+
+ usize valueEnd = valueStart + 1;
+ while (valueEnd < json.size()) {
+ if (json[valueEnd] == '"' && json[valueEnd - 1] != '\\') break;
+ ++valueEnd;
+ }
+ if (valueEnd >= json.size()) return "";
+
+ return unescapeJsonString(json.substr(valueStart + 1, valueEnd - valueStart - 1));
+}
+
+u64 extractUInt(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return 0;
+
+ usize valueStart = keyPos + searchKey.size();
+ while (valueStart < json.size() && !std::isdigit(json[valueStart]) && json[valueStart] != '-') {
+ ++valueStart;
+ }
+ if (valueStart >= json.size()) return 0;
+
+ try {
+ return std::stoull(json.substr(valueStart));
+ } catch (...) {
+ return 0;
+ }
+}
+
+i32 extractInt(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return 0;
+
+ usize valueStart = keyPos + searchKey.size();
+ while (valueStart < json.size() && !std::isdigit(json[valueStart]) && json[valueStart] != '-') {
+ ++valueStart;
+ }
+ if (valueStart >= json.size()) return 0;
+
+ try {
+ return std::stoi(json.substr(valueStart));
+ } catch (...) {
+ return 0;
+ }
+}
+
+f32 extractFloat(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return 0.0f;
+
+ usize valueStart = keyPos + searchKey.size();
+ while (valueStart < json.size() && !std::isdigit(json[valueStart]) &&
+ json[valueStart] != '-' && json[valueStart] != '.') {
+ ++valueStart;
+ }
+ if (valueStart >= json.size()) return 0.0f;
+
+ try {
+ return std::stof(json.substr(valueStart));
+ } catch (...) {
+ return 0.0f;
+ }
+}
+
+bool extractBool(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return false;
+
+ usize truePos = json.find("true", keyPos);
+ usize falsePos = json.find("false", keyPos);
+ usize nextKey = json.find("\"", keyPos + searchKey.size() + 1);
+
+ if (truePos != std::string::npos && (truePos < falsePos || falsePos == std::string::npos)) {
+ if (nextKey == std::string::npos || truePos < nextKey) {
+ return true;
+ }
+ }
+ return false;
+}
+
+glm::vec2 extractVec2(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return glm::vec2(0.0f);
+
+ usize arrayStart = json.find("[", keyPos);
+ usize arrayEnd = json.find("]", arrayStart);
+ if (arrayStart == std::string::npos || arrayEnd == std::string::npos) return glm::vec2(0.0f);
+
+ std::string content = json.substr(arrayStart + 1, arrayEnd - arrayStart - 1);
+ glm::vec2 result(0.0f);
+
+ try {
+ usize pos = 0;
+ result.x = std::stof(content.substr(pos));
+ pos = content.find(",", pos);
+ if (pos != std::string::npos) {
+ result.y = std::stof(content.substr(pos + 1));
+ }
+ } catch (...) {}
+
+ return result;
+}
+
+glm::vec3 extractVec3(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return glm::vec3(0.0f);
+
+ usize arrayStart = json.find("[", keyPos);
+ usize arrayEnd = json.find("]", arrayStart);
+ if (arrayStart == std::string::npos || arrayEnd == std::string::npos) return glm::vec3(0.0f);
+
+ std::string content = json.substr(arrayStart + 1, arrayEnd - arrayStart - 1);
+ glm::vec3 result(0.0f);
+
+ try {
+ usize pos = 0;
+ result.x = std::stof(content.substr(pos));
+ pos = content.find(",", pos);
+ if (pos != std::string::npos) {
+ result.y = std::stof(content.substr(pos + 1));
+ pos = content.find(",", pos + 1);
+ if (pos != std::string::npos) {
+ result.z = std::stof(content.substr(pos + 1));
+ }
+ }
+ } catch (...) {}
+
+ return result;
+}
+
+glm::vec4 extractVec4(const std::string& json, usize startPos, const std::string& key) {
+ std::string searchKey = "\"" + key + "\":";
+ usize keyPos = json.find(searchKey, startPos);
+ if (keyPos == std::string::npos) return glm::vec4(0.0f);
+
+ usize arrayStart = json.find("[", keyPos);
+ usize arrayEnd = json.find("]", arrayStart);
+ if (arrayStart == std::string::npos || arrayEnd == std::string::npos) return glm::vec4(0.0f);
+
+ std::string content = json.substr(arrayStart + 1, arrayEnd - arrayStart - 1);
+ glm::vec4 result(0.0f);
+
+ try {
+ usize pos = 0;
+ result.x = std::stof(content.substr(pos));
+ pos = content.find(",", pos);
+ if (pos != std::string::npos) {
+ result.y = std::stof(content.substr(pos + 1));
+ pos = content.find(",", pos + 1);
+ if (pos != std::string::npos) {
+ result.z = std::stof(content.substr(pos + 1));
+ pos = content.find(",", pos + 1);
+ if (pos != std::string::npos) {
+ result.w = std::stof(content.substr(pos + 1));
+ }
+ }
+ }
+ } catch (...) {}
+
+ return result;
+}
+
+glm::quat extractQuat(const std::string& json, usize startPos, const std::string& key) {
+ glm::vec4 v = extractVec4(json, startPos, key);
+ return glm::quat(v.x, v.y, v.z, v.w); // w, x, y, z order
+}
+
+std::string serializeVec2(const glm::vec2& v) {
+ std::ostringstream ss;
+ ss << "[" << v.x << ", " << v.y << "]";
+ return ss.str();
+}
+
+std::string serializeVec3(const glm::vec3& v) {
+ std::ostringstream ss;
+ ss << "[" << v.x << ", " << v.y << ", " << v.z << "]";
+ return ss.str();
+}
+
+std::string serializeVec4(const glm::vec4& v) {
+ std::ostringstream ss;
+ ss << "[" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << "]";
+ return ss.str();
+}
+
+std::string serializeQuat(const glm::quat& q) {
+ std::ostringstream ss;
+ ss << "[" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << "]";
+ return ss.str();
+}
+
+} // namespace
+
+// =============================================================================
+// Scene Serialization
+// =============================================================================
+
+bool SceneSerializer::saveScene(
+ const ecs::Registry& registry,
+ const std::string& filePath,
+ const std::string& sceneName,
+ const resource::ResourceManager* resourceManager,
+ const std::string& projectPath
+) {
+ ES_LOG_INFO("Saving scene to: {}", filePath);
+
+ std::ostringstream ss;
+ ss << "{\n";
+ ss << " \"version\": " << SCENE_FORMAT_VERSION << ",\n";
+ ss << " \"name\": \"" << escapeJsonString(sceneName) << "\",\n";
+ ss << " \"entities\": [\n";
+
+ bool firstEntity = true;
+ std::unordered_map<Entity, u64> entityToUUID;
+
+ // First pass: assign UUIDs to all entities
+ registry.forEachEntity([&](Entity entity) {
+ if (registry.has<ecs::UUID>(entity)) {
+ entityToUUID[entity] = registry.get<ecs::UUID>(entity).value;
+ } else {
+ entityToUUID[entity] = generateUUID();
+ }
+ });
+
+ // Second pass: serialize entities
+ registry.forEachEntity([&](Entity entity) {
+ if (!firstEntity) {
+ ss << ",\n";
+ }
+ firstEntity = false;
+
+ u64 uuid = entityToUUID[entity];
+
+ ss << " {\n";
+ ss << " \"uuid\": " << uuid << ",\n";
+
+ // Name
+ if (registry.has<ecs::Name>(entity)) {
+ const auto& name = registry.get<ecs::Name>(entity);
+ ss << " \"name\": \"" << escapeJsonString(name.value) << "\",\n";
+ } else {
+ ss << " \"name\": \"Entity\",\n";
+ }
+
+ ss << " \"components\": {\n";
+ bool firstComponent = true;
+
+ // LocalTransform
+ if (registry.has<ecs::LocalTransform>(entity)) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ const auto& t = registry.get<ecs::LocalTransform>(entity);
+ ss << " \"LocalTransform\": {\n";
+ ss << " \"position\": " << serializeVec3(t.position) << ",\n";
+ ss << " \"rotation\": " << serializeQuat(t.rotation) << ",\n";
+ ss << " \"scale\": " << serializeVec3(t.scale) << "\n";
+ ss << " }";
+ }
+
+ // Parent
+ if (registry.has<ecs::Parent>(entity)) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ const auto& p = registry.get<ecs::Parent>(entity);
+ u64 parentUUID = 0;
+ if (p.entity != INVALID_ENTITY && entityToUUID.count(p.entity)) {
+ parentUUID = entityToUUID[p.entity];
+ }
+ ss << " \"Parent\": {\n";
+ ss << " \"uuid\": " << parentUUID << "\n";
+ ss << " }";
+ }
+
+ // Sprite
+ if (registry.has<ecs::Sprite>(entity)) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ const auto& s = registry.get<ecs::Sprite>(entity);
+ ss << " \"Sprite\": {\n";
+ ss << " \"texture\": " << s.texture.id() << ",\n";
+
+ // Store texture path if available (for web preview)
+ if (resourceManager && s.texture.isValid()) {
+ std::string texPath = resourceManager->getTexturePath(s.texture);
+ // Make path relative to project's assets folder
+ if (!texPath.empty() && !projectPath.empty()) {
+ fs::path texturePath(texPath);
+ fs::path assetsPath = fs::path(projectPath) / "assets";
+ if (texturePath.string().find(assetsPath.string()) == 0) {
+ texPath = "assets" + texturePath.string().substr(assetsPath.string().size());
+ // Normalize path separators
+ std::replace(texPath.begin(), texPath.end(), '\\', '/');
+ }
+ }
+ ss << " \"texturePath\": \"" << escapeJsonString(texPath) << "\",\n";
+ }
+
+ ss << " \"color\": " << serializeVec4(s.color) << ",\n";
+ ss << " \"size\": " << serializeVec2(s.size) << ",\n";
+ ss << " \"uvOffset\": " << serializeVec2(s.uvOffset) << ",\n";
+ ss << " \"uvScale\": " << serializeVec2(s.uvScale) << ",\n";
+ ss << " \"layer\": " << s.layer << ",\n";
+ ss << " \"flipX\": " << (s.flipX ? "true" : "false") << ",\n";
+ ss << " \"flipY\": " << (s.flipY ? "true" : "false") << "\n";
+ ss << " }";
+ }
+
+ // Camera
+ if (registry.has<ecs::Camera>(entity)) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ const auto& c = registry.get<ecs::Camera>(entity);
+ ss << " \"Camera\": {\n";
+ ss << " \"projectionType\": " << static_cast<int>(c.projectionType) << ",\n";
+ ss << " \"fov\": " << c.fov << ",\n";
+ ss << " \"orthoSize\": " << c.orthoSize << ",\n";
+ ss << " \"nearPlane\": " << c.nearPlane << ",\n";
+ ss << " \"farPlane\": " << c.farPlane << ",\n";
+ ss << " \"aspectRatio\": " << c.aspectRatio << ",\n";
+ ss << " \"isActive\": " << (c.isActive ? "true" : "false") << ",\n";
+ ss << " \"priority\": " << c.priority << "\n";
+ ss << " }";
+ }
+
+ // Canvas
+ if (registry.has<ecs::Canvas>(entity)) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ const auto& c = registry.get<ecs::Canvas>(entity);
+ ss << " \"Canvas\": {\n";
+ ss << " \"designResolution\": [" << c.designResolution.x << ", " << c.designResolution.y << "],\n";
+ ss << " \"pixelsPerUnit\": " << c.pixelsPerUnit << ",\n";
+ ss << " \"scaleMode\": " << static_cast<int>(c.scaleMode) << ",\n";
+ ss << " \"matchWidthOrHeight\": " << c.matchWidthOrHeight << ",\n";
+ ss << " \"backgroundColor\": " << serializeVec4(c.backgroundColor) << "\n";
+ ss << " }";
+ }
+
+ // Tags
+ std::vector<std::string> tags;
+ if (registry.has<ecs::Active>(entity)) tags.push_back("Active");
+ if (registry.has<ecs::Visible>(entity)) tags.push_back("Visible");
+ if (registry.has<ecs::Static>(entity)) tags.push_back("Static");
+ if (registry.has<ecs::Folder>(entity)) tags.push_back("Folder");
+ if (registry.has<ecs::MainEntity>(entity)) tags.push_back("MainEntity");
+
+ if (!tags.empty()) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ ss << " \"tags\": [";
+ for (usize i = 0; i < tags.size(); ++i) {
+ if (i > 0) ss << ", ";
+ ss << "\"" << tags[i] << "\"";
+ }
+ ss << "]";
+ }
+
+ // Scripts
+ if (registry.has<ecs::Scripts>(entity)) {
+ const auto& scripts = registry.get<ecs::Scripts>(entity);
+ if (!scripts.instances.empty()) {
+ if (!firstComponent) ss << ",\n";
+ firstComponent = false;
+ ss << " \"scripts\": [\n";
+ bool firstScript = true;
+ for (const auto& inst : scripts.instances) {
+ if (!firstScript) ss << ",\n";
+ firstScript = false;
+ ss << " {\n";
+ ss << " \"name\": \"" << escapeJsonString(inst.componentName) << "\",\n";
+ ss << " \"fields\": {\n";
+ bool firstField = true;
+ for (const auto& [fieldName, fieldValue] : inst.values) {
+ if (!firstField) ss << ",\n";
+ firstField = false;
+ ss << " \"" << escapeJsonString(fieldName) << "\": ";
+ std::visit([&ss](auto&& arg) {
+ using T = std::decay_t<decltype(arg)>;
+ if constexpr (std::is_same_v<T, f32>) {
+ ss << arg;
+ } else if constexpr (std::is_same_v<T, i32>) {
+ ss << arg;
+ } else if constexpr (std::is_same_v<T, bool>) {
+ ss << (arg ? "true" : "false");
+ } else if constexpr (std::is_same_v<T, std::string>) {
+ ss << "\"" << escapeJsonString(arg) << "\"";
+ } else if constexpr (std::is_same_v<T, glm::vec2>) {
+ ss << "[" << arg.x << ", " << arg.y << "]";
+ } else if constexpr (std::is_same_v<T, glm::vec3>) {
+ ss << "[" << arg.x << ", " << arg.y << ", " << arg.z << "]";
+ } else if constexpr (std::is_same_v<T, glm::vec4>) {
+ ss << "[" << arg.x << ", " << arg.y << ", " << arg.z << ", " << arg.w << "]";
+ } else if constexpr (std::is_same_v<T, u32>) {
+ ss << arg;
+ }
+ }, fieldValue);
+ }
+ ss << "\n }\n";
+ ss << " }";
+ }
+ ss << "\n ]";
+ }
+ }
+
+ ss << "\n }\n";
+ ss << " }";
+ });
+
+ ss << "\n ]\n";
+ ss << "}\n";
+
+ // Write to file
+ try {
+ fs::path path(filePath);
+ fs::create_directories(path.parent_path());
+
+ std::ofstream file(filePath);
+ if (!file) {
+ ES_LOG_ERROR("Failed to open file for writing: {}", filePath);
+ return false;
+ }
+ file << ss.str();
+ file.close();
+
+ ES_LOG_INFO("Scene saved successfully");
+ return true;
+ } catch (const std::exception& e) {
+ ES_LOG_ERROR("Failed to save scene: {}", e.what());
+ return false;
+ }
+}
+
+bool SceneSerializer::loadScene(
+ ecs::Registry& registry,
+ const std::string& filePath
+) {
+ ES_LOG_INFO("Loading scene from: {}", filePath);
+
+ // Read file
+ std::ifstream file(filePath);
+ if (!file) {
+ ES_LOG_ERROR("Failed to open scene file: {}", filePath);
+ return false;
+ }
+
+ std::stringstream buffer;
+ buffer << file.rdbuf();
+ std::string json = buffer.str();
+ file.close();
+
+ if (json.empty()) {
+ ES_LOG_ERROR("Scene file is empty");
+ return false;
+ }
+
+ // Check version
+ u32 version = static_cast<u32>(extractUInt(json, 0, "version"));
+ if (version == 0 || version > SCENE_FORMAT_VERSION) {
+ ES_LOG_ERROR("Unsupported scene format version: {}", version);
+ return false;
+ }
+
+ // Clear existing entities
+ clearScene(registry);
+
+ // Parse entities
+ std::unordered_map<u64, Entity> uuidToEntity;
+ std::vector<std::pair<Entity, u64>> parentRelations;
+
+ usize entityStart = 0;
+ while ((entityStart = json.find("{", entityStart)) != std::string::npos) {
+ // Skip the root object and "entities" array opening
+ if (entityStart < json.find("\"entities\"")) {
+ entityStart++;
+ continue;
+ }
+
+ // Find entity block
+ usize uuidPos = json.find("\"uuid\":", entityStart);
+ if (uuidPos == std::string::npos) break;
+ if (uuidPos > entityStart + 100) { // Not this entity block
+ entityStart++;
+ continue;
+ }
+
+ // Find end of entity block
+ usize depth = 1;
+ usize blockEnd = entityStart + 1;
+ while (depth > 0 && blockEnd < json.size()) {
+ if (json[blockEnd] == '{') depth++;
+ else if (json[blockEnd] == '}') depth--;
+ blockEnd++;
+ }
+
+ std::string entityJson = json.substr(entityStart, blockEnd - entityStart);
+
+ // Extract UUID
+ u64 uuid = extractUInt(entityJson, 0, "uuid");
+ if (uuid == 0) {
+ entityStart = blockEnd;
+ continue;
+ }
+
+ // Create entity
+ Entity entity = registry.create();
+ uuidToEntity[uuid] = entity;
+
+ // Add UUID component
+ registry.emplace<ecs::UUID>(entity, uuid);
+
+ // Name
+ std::string name = extractString(entityJson, 0, "name");
+ if (!name.empty()) {
+ registry.emplace<ecs::Name>(entity, name);
+ }
+
+ // Find components block
+ usize componentsPos = entityJson.find("\"components\":");
+ if (componentsPos != std::string::npos) {
+ // LocalTransform
+ usize transformPos = entityJson.find("\"LocalTransform\":", componentsPos);
+ if (transformPos != std::string::npos) {
+ ecs::LocalTransform t;
+ t.position = extractVec3(entityJson, transformPos, "position");
+ t.rotation = extractQuat(entityJson, transformPos, "rotation");
+ t.scale = extractVec3(entityJson, transformPos, "scale");
+ if (t.scale.x == 0.0f) t.scale.x = 1.0f;
+ if (t.scale.y == 0.0f) t.scale.y = 1.0f;
+ if (t.scale.z == 0.0f) t.scale.z = 1.0f;
+ registry.emplace<ecs::LocalTransform>(entity, t);
+ }
+
+ // Parent (defer resolution)
+ usize parentPos = entityJson.find("\"Parent\":", componentsPos);
+ if (parentPos != std::string::npos) {
+ u64 parentUUID = extractUInt(entityJson, parentPos, "uuid");
+ if (parentUUID != 0) {
+ parentRelations.push_back({entity, parentUUID});
+ }
+ }
+
+ // Sprite
+ usize spritePos = entityJson.find("\"Sprite\":", componentsPos);
+ if (spritePos != std::string::npos) {
+ ecs::Sprite s;
+ s.texture = resource::TextureHandle(static_cast<u32>(extractUInt(entityJson, spritePos, "texture")));
+ s.color = extractVec4(entityJson, spritePos, "color");
+ if (s.color.w == 0.0f) s.color = glm::vec4(1.0f);
+ s.size = extractVec2(entityJson, spritePos, "size");
+ if (s.size.x == 0.0f) s.size.x = 1.0f;
+ if (s.size.y == 0.0f) s.size.y = 1.0f;
+ s.uvOffset = extractVec2(entityJson, spritePos, "uvOffset");
+ s.uvScale = extractVec2(entityJson, spritePos, "uvScale");
+ if (s.uvScale.x == 0.0f) s.uvScale.x = 1.0f;
+ if (s.uvScale.y == 0.0f) s.uvScale.y = 1.0f;
+ s.layer = extractInt(entityJson, spritePos, "layer");
+ s.flipX = extractBool(entityJson, spritePos, "flipX");
+ s.flipY = extractBool(entityJson, spritePos, "flipY");
+ registry.emplace<ecs::Sprite>(entity, s);
+ }
+
+ // Camera
+ usize cameraPos = entityJson.find("\"Camera\":", componentsPos);
+ if (cameraPos != std::string::npos) {
+ ecs::Camera c;
+ c.projectionType = static_cast<ecs::ProjectionType>(extractInt(entityJson, cameraPos, "projectionType"));
+ c.fov = extractFloat(entityJson, cameraPos, "fov");
+ if (c.fov == 0.0f) c.fov = 60.0f;
+ c.orthoSize = extractFloat(entityJson, cameraPos, "orthoSize");
+ if (c.orthoSize == 0.0f) c.orthoSize = 5.0f;
+ c.nearPlane = extractFloat(entityJson, cameraPos, "nearPlane");
+ if (c.nearPlane == 0.0f) c.nearPlane = 0.1f;
+ c.farPlane = extractFloat(entityJson, cameraPos, "farPlane");
+ if (c.farPlane == 0.0f) c.farPlane = 1000.0f;
+ c.aspectRatio = extractFloat(entityJson, cameraPos, "aspectRatio");
+ c.isActive = extractBool(entityJson, cameraPos, "isActive");
+ c.priority = extractInt(entityJson, cameraPos, "priority");
+ registry.emplace<ecs::Camera>(entity, c);
+ }
+
+ // Canvas
+ usize canvasPos = entityJson.find("\"Canvas\":", componentsPos);
+ if (canvasPos != std::string::npos) {
+ ecs::Canvas c;
+ glm::vec2 res = extractVec2(entityJson, canvasPos, "designResolution");
+ c.designResolution = glm::uvec2(static_cast<u32>(res.x), static_cast<u32>(res.y));
+ if (c.designResolution.x == 0) c.designResolution.x = 1920;
+ if (c.designResolution.y == 0) c.designResolution.y = 1080;
+ c.pixelsPerUnit = static_cast<u32>(extractUInt(entityJson, canvasPos, "pixelsPerUnit"));
+ if (c.pixelsPerUnit == 0) c.pixelsPerUnit = 100;
+ c.scaleMode = static_cast<ecs::CanvasScaleMode>(extractInt(entityJson, canvasPos, "scaleMode"));
+ c.matchWidthOrHeight = extractFloat(entityJson, canvasPos, "matchWidthOrHeight");
+ c.backgroundColor = extractVec4(entityJson, canvasPos, "backgroundColor");
+ registry.emplace<ecs::Canvas>(entity, c);
+ }
+
+ // Tags
+ usize tagsPos = entityJson.find("\"tags\":", componentsPos);
+ if (tagsPos != std::string::npos) {
+ if (entityJson.find("\"Active\"", tagsPos) != std::string::npos) {
+ registry.emplace<ecs::Active>(entity);
+ }
+ if (entityJson.find("\"Visible\"", tagsPos) != std::string::npos) {
+ registry.emplace<ecs::Visible>(entity);
+ }
+ if (entityJson.find("\"Static\"", tagsPos) != std::string::npos) {
+ registry.emplace<ecs::Static>(entity);
+ }
+ if (entityJson.find("\"Folder\"", tagsPos) != std::string::npos) {
+ registry.emplace<ecs::Folder>(entity);
+ }
+ if (entityJson.find("\"MainEntity\"", tagsPos) != std::string::npos) {
+ registry.emplace<ecs::MainEntity>(entity);
+ }
+ }
+
+ // Scripts
+ usize scriptsPos = entityJson.find("\"scripts\":", componentsPos);
+ if (scriptsPos != std::string::npos) {
+ usize scriptsArrayStart = entityJson.find("[", scriptsPos);
+ usize scriptsArrayEnd = scriptsArrayStart;
+ if (scriptsArrayStart != std::string::npos) {
+ int depth = 1;
+ scriptsArrayEnd = scriptsArrayStart + 1;
+ while (scriptsArrayEnd < entityJson.size() && depth > 0) {
+ if (entityJson[scriptsArrayEnd] == '[') depth++;
+ else if (entityJson[scriptsArrayEnd] == ']') depth--;
+ scriptsArrayEnd++;
+ }
+ }
+
+ ecs::Scripts scriptsComp;
+ usize scriptObjStart = scriptsArrayStart;
+ while ((scriptObjStart = entityJson.find("{", scriptObjStart + 1)) != std::string::npos &&
+ scriptObjStart < scriptsArrayEnd) {
+ usize scriptObjEnd = scriptObjStart + 1;
+ int objDepth = 1;
+ while (scriptObjEnd < entityJson.size() && objDepth > 0) {
+ if (entityJson[scriptObjEnd] == '{') objDepth++;
+ else if (entityJson[scriptObjEnd] == '}') objDepth--;
+ scriptObjEnd++;
+ }
+
+ std::string scriptObjJson = entityJson.substr(scriptObjStart, scriptObjEnd - scriptObjStart);
+ std::string scriptName = extractString(scriptObjJson, 0, "name");
+
+ if (!scriptName.empty()) {
+ ecs::ScriptInstance inst;
+ inst.componentName = scriptName;
+
+ usize fieldsPos = scriptObjJson.find("\"fields\":");
+ if (fieldsPos != std::string::npos) {
+ usize fieldsObjStart = scriptObjJson.find("{", fieldsPos);
+ if (fieldsObjStart != std::string::npos) {
+ usize fieldsObjEnd = fieldsObjStart + 1;
+ int fieldsDepth = 1;
+ while (fieldsObjEnd < scriptObjJson.size() && fieldsDepth > 0) {
+ if (scriptObjJson[fieldsObjEnd] == '{') fieldsDepth++;
+ else if (scriptObjJson[fieldsObjEnd] == '}') fieldsDepth--;
+ fieldsObjEnd++;
+ }
+
+ std::string fieldsJson = scriptObjJson.substr(fieldsObjStart, fieldsObjEnd - fieldsObjStart);
+
+ // Parse fields - simplified parsing
+ usize fieldKeyPos = 0;
+ while ((fieldKeyPos = fieldsJson.find("\"", fieldKeyPos + 1)) != std::string::npos) {
+ usize fieldKeyEnd = fieldsJson.find("\"", fieldKeyPos + 1);
+ if (fieldKeyEnd == std::string::npos) break;
+
+ std::string fieldKey = fieldsJson.substr(fieldKeyPos + 1, fieldKeyEnd - fieldKeyPos - 1);
+ if (fieldKey.empty()) break;
+
+ usize colonPos = fieldsJson.find(":", fieldKeyEnd);
+ if (colonPos == std::string::npos) break;
+
+ usize valueStart = colonPos + 1;
+ while (valueStart < fieldsJson.size() && std::isspace(fieldsJson[valueStart])) valueStart++;
+ if (valueStart >= fieldsJson.size()) break;
+
+ // Determine value type and parse
+ if (fieldsJson[valueStart] == '"') {
+ // String value
+ std::string val = extractString(fieldsJson, fieldKeyPos, fieldKey);
+ inst.values[fieldKey] = val;
+ } else if (fieldsJson[valueStart] == '[') {
+ // Array (vec2/vec3/vec4)
+ glm::vec4 vec = extractVec4(fieldsJson, fieldKeyPos, fieldKey);
+ usize arrEnd = fieldsJson.find("]", valueStart);
+ std::string arrContent = fieldsJson.substr(valueStart + 1, arrEnd - valueStart - 1);
+ int commaCount = 0;
+ for (char c : arrContent) if (c == ',') commaCount++;
+ if (commaCount == 1) {
+ inst.values[fieldKey] = glm::vec2(vec.x, vec.y);
+ } else if (commaCount == 2) {
+ inst.values[fieldKey] = glm::vec3(vec.x, vec.y, vec.z);
+ } else {
+ inst.values[fieldKey] = vec;
+ }
+ } else if (fieldsJson.substr(valueStart, 4) == "true") {
+ inst.values[fieldKey] = true;
+ } else if (fieldsJson.substr(valueStart, 5) == "false") {
+ inst.values[fieldKey] = false;
+ } else if (fieldsJson[valueStart] == '-' || std::isdigit(fieldsJson[valueStart])) {
+ // Number (f32 or i32)
+ std::string numStr;
+ usize numEnd = valueStart;
+ while (numEnd < fieldsJson.size() &&
+ (std::isdigit(fieldsJson[numEnd]) || fieldsJson[numEnd] == '.' ||
+ fieldsJson[numEnd] == '-' || fieldsJson[numEnd] == 'e' || fieldsJson[numEnd] == 'E')) {
+ numEnd++;
+ }
+ numStr = fieldsJson.substr(valueStart, numEnd - valueStart);
+ if (numStr.find('.') != std::string::npos || numStr.find('e') != std::string::npos) {
+ try { inst.values[fieldKey] = std::stof(numStr); } catch (...) {}
+ } else {
+ try { inst.values[fieldKey] = std::stoi(numStr); } catch (...) {}
+ }
+ }
+
+ fieldKeyPos = fieldsJson.find(",", valueStart);
+ if (fieldKeyPos == std::string::npos) break;
+ }
+ }
+ }
+
+ scriptsComp.instances.push_back(std::move(inst));
+ }
+
+ scriptObjStart = scriptObjEnd;
+ }
+
+ if (!scriptsComp.instances.empty()) {
+ registry.emplace<ecs::Scripts>(entity, std::move(scriptsComp));
+ }
+ }
+ }
+
+ entityStart = blockEnd;
+ }
+
+ // Resolve parent relationships
+ for (const auto& [entity, parentUUID] : parentRelations) {
+ auto it = uuidToEntity.find(parentUUID);
+ if (it != uuidToEntity.end()) {
+ Entity parentEntity = it->second;
+ registry.emplace<ecs::Parent>(entity, parentEntity);
+
+ // Add to parent's children
+ if (!registry.has<ecs::Children>(parentEntity)) {
+ registry.emplace<ecs::Children>(parentEntity);
+ }
+ registry.get<ecs::Children>(parentEntity).entities.push_back(entity);
+ }
+ }
+
+ ES_LOG_INFO("Scene loaded successfully ({} entities)", uuidToEntity.size());
+ return true;
+}
+
+void SceneSerializer::clearScene(ecs::Registry& registry) {
+ std::vector<Entity> toDestroy;
+ registry.forEachEntity([&](Entity entity) {
+ toDestroy.push_back(entity);
+ });
+ for (Entity entity : toDestroy) {
+ registry.destroy(entity);
+ }
+}
+
+std::string SceneSerializer::getSceneName(const std::string& filePath) {
+ fs::path path(filePath);
+ return path.stem().string();
+}
+
+} // namespace esengine::editor
diff --git a/src/esengine/editor/scene/SceneSerializer.hpp b/src/esengine/editor/scene/SceneSerializer.hpp
new file mode 100644
index 000000000..87b02ff1d
--- /dev/null
+++ b/src/esengine/editor/scene/SceneSerializer.hpp
@@ -0,0 +1,82 @@
+/**
+ * @file SceneSerializer.hpp
+ * @brief Scene serialization to/from JSON files
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../../core/Types.hpp"
+#include "../../ecs/Registry.hpp"
+#include "../../resource/ResourceManager.hpp"
+
+#include <string>
+
+namespace esengine::editor {
+
+// =============================================================================
+// Scene Format Version
+// =============================================================================
+
+constexpr u32 SCENE_FORMAT_VERSION = 1;
+
+// =============================================================================
+// SceneSerializer
+// =============================================================================
+
+/**
+ * @brief Serializes scene data to/from JSON files
+ */
+class SceneSerializer {
+public:
+ /**
+ * @brief Saves all entities in the registry to a JSON file
+ * @param registry The registry containing entities to save
+ * @param filePath Path to the output .esscene file
+ * @param sceneName Name of the scene
+ * @param resourceManager Resource manager for looking up texture paths (optional)
+ * @param projectPath Project root path for making paths relative (optional)
+ * @return true if save succeeded
+ */
+ [[nodiscard]] static bool saveScene(
+ const ecs::Registry& registry,
+ const std::string& filePath,
+ const std::string& sceneName = "Untitled",
+ const resource::ResourceManager* resourceManager = nullptr,
+ const std::string& projectPath = ""
+ );
+
+ /**
+ * @brief Loads entities from a JSON file into the registry
+ * @param registry The registry to populate (will be cleared first)
+ * @param filePath Path to the .esscene file
+ * @return true if load succeeded
+ */
+ [[nodiscard]] static bool loadScene(
+ ecs::Registry& registry,
+ const std::string& filePath
+ );
+
+ /**
+ * @brief Clears all entities from the registry
+ * @param registry The registry to clear
+ */
+ static void clearScene(ecs::Registry& registry);
+
+ /**
+ * @brief Gets the scene name from a file path
+ * @param filePath Full path to .esscene file
+ * @return Scene name extracted from filename
+ */
+ [[nodiscard]] static std::string getSceneName(const std::string& filePath);
+};
+
+} // namespace esengine::editor
diff --git a/src/esengine/editor/script/ScriptComponentRegistry.cpp b/src/esengine/editor/script/ScriptComponentRegistry.cpp
new file mode 100644
index 000000000..195bbf21e
--- /dev/null
+++ b/src/esengine/editor/script/ScriptComponentRegistry.cpp
@@ -0,0 +1,461 @@
+/**
+ * @file ScriptComponentRegistry.cpp
+ * @brief Script component registry implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "ScriptComponentRegistry.hpp"
+#include "../../core/Log.hpp"
+#include "../../platform/FileSystem.hpp"
+
+#include <filesystem>
+#include <regex>
+#include <sstream>
+
+namespace fs = std::filesystem;
+
+namespace esengine::editor {
+
+// =============================================================================
+// Type Mappings
+// =============================================================================
+
+namespace {
+
+const std::unordered_map<std::string, ScriptFieldType> TYPE_MAP = {
+ {"Type.f32", ScriptFieldType::F32},
+ {"Type.i32", ScriptFieldType::I32},
+ {"Type.bool", ScriptFieldType::Bool},
+ {"Type.string", ScriptFieldType::String},
+ {"Type.String", ScriptFieldType::String},
+ {"Type.Vec2", ScriptFieldType::Vec2},
+ {"Type.Vec3", ScriptFieldType::Vec3},
+ {"Type.Vec4", ScriptFieldType::Vec4},
+ {"Type.Color", ScriptFieldType::Color},
+ {"Type.Entity", ScriptFieldType::Entity},
+};
+
+ScriptFieldValue getDefaultValue(ScriptFieldType type) {
+ switch (type) {
+ case ScriptFieldType::F32: return 0.0f;
+ case ScriptFieldType::I32: return 0;
+ case ScriptFieldType::Bool: return false;
+ case ScriptFieldType::String: return std::string{};
+ case ScriptFieldType::Vec2: return glm::vec2(0.0f);
+ case ScriptFieldType::Vec3: return glm::vec3(0.0f);
+ case ScriptFieldType::Vec4:
+ case ScriptFieldType::Color: return glm::vec4(1.0f);
+ case ScriptFieldType::Entity: return static_cast<u32>(0);
+ }
+ return 0.0f;
+}
+
+std::string trim(const std::string& str) {
+ usize start = str.find_first_not_of(" \t\n\r");
+ if (start == std::string::npos) return "";
+ usize end = str.find_last_not_of(" \t\n\r");
+ return str.substr(start, end - start + 1);
+}
+
+} // namespace
+
+// =============================================================================
+// ScriptComponentRegistry Implementation
+// =============================================================================
+
+bool ScriptComponentRegistry::scanProject(const std::string& projectPath) {
+ projectPath_ = projectPath;
+ return rescan();
+}
+
+bool ScriptComponentRegistry::rescan() {
+ if (projectPath_.empty()) {
+ return false;
+ }
+
+ components_.clear();
+ nameToIndex_.clear();
+
+ std::string srcDir = projectPath_ + "/src";
+ if (!fs::exists(srcDir)) {
+ ES_LOG_DEBUG("No src directory found at {}", srcDir);
+ return true;
+ }
+
+ auto tsFiles = findTypeScriptFiles(srcDir);
+ ES_LOG_DEBUG("Found {} TypeScript files in {}", tsFiles.size(), srcDir);
+
+ for (const auto& file : tsFiles) {
+ parseFile(file);
+ }
+
+ ES_LOG_INFO("Discovered {} script components from TypeScript source", components_.size());
+ return true;
+}
+
+std::vector<std::string> ScriptComponentRegistry::findTypeScriptFiles(const std::string& dir) {
+ std::vector<std::string> files;
+
+ try {
+ for (const auto& entry : fs::recursive_directory_iterator(dir)) {
+ if (entry.is_regular_file()) {
+ std::string ext = entry.path().extension().string();
+ if (ext == ".ts" || ext == ".tsx") {
+ // Skip node_modules and build directories
+ std::string pathStr = entry.path().string();
+ if (pathStr.find("node_modules") == std::string::npos &&
+ pathStr.find("/build/") == std::string::npos &&
+ pathStr.find("\\build\\") == std::string::npos) {
+ files.push_back(pathStr);
+ }
+ }
+ }
+ }
+ } catch (const std::exception& e) {
+ ES_LOG_WARN("Error scanning directory {}: {}", dir, e.what());
+ }
+
+ return files;
+}
+
+usize ScriptComponentRegistry::parseFile(const std::string& filePath) {
+ std::string source = FileSystem::readTextFile(filePath);
+ if (source.empty()) {
+ return 0;
+ }
+
+ usize found = 0;
+ usize pos = 0;
+
+ // Find all defineComponent calls
+ while ((pos = source.find("defineComponent", pos)) != std::string::npos) {
+ // Make sure it's not part of a larger identifier
+ if (pos > 0) {
+ char prev = source[pos - 1];
+ if (std::isalnum(prev) || prev == '_') {
+ pos++;
+ continue;
+ }
+ }
+
+ ScriptComponentDef def;
+ def.sourceFile = filePath;
+
+ if (parseDefineComponent(source, pos, def)) {
+ if (!def.name.empty() && !def.fields.empty()) {
+ // Check for duplicates
+ if (nameToIndex_.find(def.name) == nameToIndex_.end()) {
+ nameToIndex_[def.name] = components_.size();
+ components_.push_back(std::move(def));
+ found++;
+ } else {
+ ES_LOG_WARN("Duplicate component '{}' in {}", def.name, filePath);
+ }
+ }
+ }
+
+ pos++;
+ }
+
+ if (found > 0) {
+ std::string relPath = fs::relative(filePath, projectPath_).string();
+ ES_LOG_DEBUG(" {}: {} component(s)", relPath, found);
+ }
+
+ return found;
+}
+
+usize ScriptComponentRegistry::findMatchingBrace(const std::string& source, usize openPos, char open, char close) {
+ if (openPos >= source.size() || source[openPos] != open) {
+ return std::string::npos;
+ }
+
+ int depth = 1;
+ usize pos = openPos + 1;
+ bool inString = false;
+ char stringChar = 0;
+
+ while (pos < source.size() && depth > 0) {
+ char c = source[pos];
+
+ // Handle string literals
+ if (!inString && (c == '"' || c == '\'' || c == '`')) {
+ inString = true;
+ stringChar = c;
+ } else if (inString && c == stringChar && (pos == 0 || source[pos - 1] != '\\')) {
+ inString = false;
+ } else if (!inString) {
+ if (c == open) depth++;
+ else if (c == close) depth--;
+ }
+
+ pos++;
+ }
+
+ return depth == 0 ? pos : std::string::npos;
+}
+
+bool ScriptComponentRegistry::parseDefineComponent(const std::string& source, usize pos, ScriptComponentDef& outDef) {
+ // Skip "defineComponent"
+ pos += 15;
+
+ // Skip whitespace
+ while (pos < source.size() && std::isspace(source[pos])) pos++;
+
+ // Expect (
+ if (pos >= source.size() || source[pos] != '(') return false;
+ pos++;
+
+ // Skip whitespace
+ while (pos < source.size() && std::isspace(source[pos])) pos++;
+
+ // Expect { for schema
+ if (pos >= source.size() || source[pos] != '{') return false;
+
+ usize schemaStart = pos;
+ usize schemaEnd = findMatchingBrace(source, schemaStart, '{', '}');
+ if (schemaEnd == std::string::npos) return false;
+
+ // Parse schema
+ if (!parseSchema(source, schemaStart + 1, schemaEnd - 1, outDef.fields)) {
+ return false;
+ }
+
+ pos = schemaEnd;
+
+ // Skip whitespace and comma
+ while (pos < source.size() && (std::isspace(source[pos]) || source[pos] == ',')) pos++;
+
+ // Check for defaults object or name string
+ if (pos < source.size() && source[pos] == '{') {
+ usize defaultsStart = pos;
+ usize defaultsEnd = findMatchingBrace(source, defaultsStart, '{', '}');
+ if (defaultsEnd != std::string::npos) {
+ parseDefaults(source, defaultsStart + 1, defaultsEnd - 1, outDef.fields);
+ pos = defaultsEnd;
+ }
+ }
+
+ // Skip whitespace and comma
+ while (pos < source.size() && (std::isspace(source[pos]) || source[pos] == ',')) pos++;
+
+ // Look for component name as string argument
+ if (pos < source.size() && (source[pos] == '\'' || source[pos] == '"')) {
+ char quote = source[pos];
+ usize nameStart = pos + 1;
+ usize nameEnd = source.find(quote, nameStart);
+ if (nameEnd != std::string::npos) {
+ outDef.name = source.substr(nameStart, nameEnd - nameStart);
+ }
+ }
+
+ // If no explicit name, try to find variable name: const Foo = defineComponent(...)
+ if (outDef.name.empty()) {
+ // Search backwards for "const NAME = " or "export const NAME = "
+ usize searchStart = source.rfind("const ", pos > 100 ? pos - 100 : 0);
+ if (searchStart != std::string::npos && searchStart < pos) {
+ usize nameStart = searchStart + 6;
+ while (nameStart < pos && std::isspace(source[nameStart])) nameStart++;
+
+ usize nameEnd = nameStart;
+ while (nameEnd < pos && (std::isalnum(source[nameEnd]) || source[nameEnd] == '_')) nameEnd++;
+
+ if (nameEnd > nameStart) {
+ std::string varName = source.substr(nameStart, nameEnd - nameStart);
+ // Verify this is followed by " = defineComponent"
+ usize afterName = nameEnd;
+ while (afterName < pos && std::isspace(source[afterName])) afterName++;
+ if (afterName < pos && source[afterName] == '=') {
+ outDef.name = varName;
+ }
+ }
+ }
+ }
+
+ return !outDef.name.empty();
+}
+
+bool ScriptComponentRegistry::parseSchema(const std::string& source, usize start, usize end,
+ std::vector<ScriptFieldDef>& outFields) {
+ std::string content = source.substr(start, end - start);
+
+ // Match patterns like "fieldName: Type.xxx" or "fieldName : Type.xxx"
+ std::regex fieldRegex(R"((\w+)\s*:\s*(Type\.\w+))");
+ std::smatch match;
+ std::string::const_iterator searchStart = content.cbegin();
+
+ while (std::regex_search(searchStart, content.cend(), match, fieldRegex)) {
+ std::string fieldName = match[1].str();
+ std::string typeStr = match[2].str();
+
+ auto it = TYPE_MAP.find(typeStr);
+ if (it != TYPE_MAP.end()) {
+ ScriptFieldDef field;
+ field.name = fieldName;
+ field.type = it->second;
+ field.defaultValue = getDefaultValue(it->second);
+ outFields.push_back(std::move(field));
+ } else {
+ ES_LOG_WARN("Unknown type '{}' for field '{}'", typeStr, fieldName);
+ }
+
+ searchStart = match.suffix().first;
+ }
+
+ return !outFields.empty();
+}
+
+void ScriptComponentRegistry::parseDefaults(const std::string& source, usize start, usize end,
+ std::vector<ScriptFieldDef>& fields) {
+ std::string content = source.substr(start, end - start);
+
+ for (auto& field : fields) {
+ // Look for "fieldName: value" pattern
+ std::regex valueRegex(field.name + R"(\s*:\s*([^,}]+))");
+ std::smatch match;
+
+ if (std::regex_search(content, match, valueRegex)) {
+ std::string valueStr = trim(match[1].str());
+
+ switch (field.type) {
+ case ScriptFieldType::F32:
+ try { field.defaultValue = std::stof(valueStr); } catch (...) {}
+ break;
+ case ScriptFieldType::I32:
+ try { field.defaultValue = std::stoi(valueStr); } catch (...) {}
+ break;
+ case ScriptFieldType::Bool:
+ field.defaultValue = (valueStr == "true");
+ break;
+ case ScriptFieldType::String:
+ if ((valueStr.front() == '\'' || valueStr.front() == '"') &&
+ valueStr.size() >= 2) {
+ field.defaultValue = valueStr.substr(1, valueStr.size() - 2);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+}
+
+const ScriptComponentDef* ScriptComponentRegistry::getComponent(const std::string& name) const {
+ auto it = nameToIndex_.find(name);
+ if (it == nameToIndex_.end()) return nullptr;
+ return &components_[it->second];
+}
+
+bool ScriptComponentRegistry::hasComponent(const std::string& name) const {
+ return nameToIndex_.count(name) > 0;
+}
+
+std::optional<ScriptComponentInstance> ScriptComponentRegistry::createInstance(const std::string& name) const {
+ const auto* def = getComponent(name);
+ if (!def) return std::nullopt;
+
+ ScriptComponentInstance instance;
+ instance.componentName = name;
+
+ for (const auto& field : def->fields) {
+ instance.values[field.name] = field.defaultValue;
+ }
+
+ return instance;
+}
+
+std::string ScriptComponentRegistry::fieldTypeToString(ScriptFieldType type) {
+ switch (type) {
+ case ScriptFieldType::F32: return "f32";
+ case ScriptFieldType::I32: return "i32";
+ case ScriptFieldType::Bool: return "bool";
+ case ScriptFieldType::String: return "string";
+ case ScriptFieldType::Vec2: return "Vec2";
+ case ScriptFieldType::Vec3: return "Vec3";
+ case ScriptFieldType::Vec4: return "Vec4";
+ case ScriptFieldType::Color: return "Color";
+ case ScriptFieldType::Entity: return "Entity";
+ }
+ return "f32";
+}
+
+ScriptFieldType ScriptComponentRegistry::stringToFieldType(const std::string& str) {
+ if (str == "f32") return ScriptFieldType::F32;
+ if (str == "i32") return ScriptFieldType::I32;
+ if (str == "bool") return ScriptFieldType::Bool;
+ if (str == "string") return ScriptFieldType::String;
+ if (str == "Vec2") return ScriptFieldType::Vec2;
+ if (str == "Vec3") return ScriptFieldType::Vec3;
+ if (str == "Vec4") return ScriptFieldType::Vec4;
+ if (str == "Color") return ScriptFieldType::Color;
+ if (str == "Entity") return ScriptFieldType::Entity;
+ return ScriptFieldType::F32;
+}
+
+std::string ScriptComponentRegistry::serializeValue(const ScriptFieldValue& value, ScriptFieldType type) {
+ std::ostringstream ss;
+ switch (type) {
+ case ScriptFieldType::F32:
+ ss << std::get<f32>(value);
+ break;
+ case ScriptFieldType::I32:
+ ss << std::get<i32>(value);
+ break;
+ case ScriptFieldType::Bool:
+ ss << (std::get<bool>(value) ? "true" : "false");
+ break;
+ case ScriptFieldType::String:
+ ss << "\"" << std::get<std::string>(value) << "\"";
+ break;
+ case ScriptFieldType::Vec2: {
+ auto v = std::get<glm::vec2>(value);
+ ss << "[" << v.x << ", " << v.y << "]";
+ break;
+ }
+ case ScriptFieldType::Vec3: {
+ auto v = std::get<glm::vec3>(value);
+ ss << "[" << v.x << ", " << v.y << ", " << v.z << "]";
+ break;
+ }
+ case ScriptFieldType::Vec4:
+ case ScriptFieldType::Color: {
+ auto v = std::get<glm::vec4>(value);
+ ss << "[" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << "]";
+ break;
+ }
+ case ScriptFieldType::Entity:
+ ss << std::get<u32>(value);
+ break;
+ }
+ return ss.str();
+}
+
+ScriptFieldValue ScriptComponentRegistry::parseValue(const std::string& json, ScriptFieldType type) {
+ switch (type) {
+ case ScriptFieldType::F32:
+ try { return std::stof(json); } catch (...) { return 0.0f; }
+ case ScriptFieldType::I32:
+ try { return std::stoi(json); } catch (...) { return 0; }
+ case ScriptFieldType::Bool:
+ return json.find("true") != std::string::npos;
+ case ScriptFieldType::String:
+ return json;
+ case ScriptFieldType::Vec2:
+ return glm::vec2(0.0f);
+ case ScriptFieldType::Vec3:
+ return glm::vec3(0.0f);
+ case ScriptFieldType::Vec4:
+ case ScriptFieldType::Color:
+ return glm::vec4(1.0f);
+ case ScriptFieldType::Entity:
+ try { return static_cast<u32>(std::stoul(json)); } catch (...) { return 0u; }
+ }
+ return 0.0f;
+}
+
+} // namespace esengine::editor
diff --git a/src/esengine/editor/script/ScriptComponentRegistry.hpp b/src/esengine/editor/script/ScriptComponentRegistry.hpp
new file mode 100644
index 000000000..6c870d258
--- /dev/null
+++ b/src/esengine/editor/script/ScriptComponentRegistry.hpp
@@ -0,0 +1,192 @@
+/**
+ * @file ScriptComponentRegistry.hpp
+ * @brief Registry for script-defined components
+ * @details Parses TypeScript source files to discover defineComponent calls.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../../core/Types.hpp"
+
+#include <glm/glm.hpp>
+#include <optional>
+#include <string>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+namespace esengine::editor {
+
+// =============================================================================
+// Field Types
+// =============================================================================
+
+enum class ScriptFieldType : u8 {
+ F32,
+ I32,
+ Bool,
+ String,
+ Vec2,
+ Vec3,
+ Vec4,
+ Color,
+ Entity
+};
+
+// =============================================================================
+// Field Value
+// =============================================================================
+
+using ScriptFieldValue = std::variant<
+ f32,
+ i32,
+ bool,
+ std::string,
+ glm::vec2,
+ glm::vec3,
+ glm::vec4,
+ u32 // Entity
+>;
+
+// =============================================================================
+// Script Field Definition
+// =============================================================================
+
+struct ScriptFieldDef {
+ std::string name;
+ ScriptFieldType type;
+ ScriptFieldValue defaultValue;
+};
+
+// =============================================================================
+// Script Component Definition
+// =============================================================================
+
+struct ScriptComponentDef {
+ std::string name;
+ std::string sourceFile; ///< Source file where component is defined
+ std::vector<ScriptFieldDef> fields;
+};
+
+// =============================================================================
+// Script Component Instance
+// =============================================================================
+
+struct ScriptComponentInstance {
+ std::string componentName;
+ std::unordered_map<std::string, ScriptFieldValue> values;
+};
+
+// =============================================================================
+// ScriptComponentRegistry
+// =============================================================================
+
+/**
+ * @brief Registry for script-defined components
+ * @details Scans TypeScript source files and parses defineComponent calls
+ * to discover custom component definitions.
+ */
+class ScriptComponentRegistry {
+public:
+ ScriptComponentRegistry() = default;
+ ~ScriptComponentRegistry() = default;
+
+ // =========================================================================
+ // Scanning
+ // =========================================================================
+
+ /**
+ * @brief Scan project source directory for component definitions
+ * @param projectPath Path to project root
+ * @return True if scanning succeeded
+ */
+ bool scanProject(const std::string& projectPath);
+
+ /**
+ * @brief Rescan the project source files
+ */
+ bool rescan();
+
+ /**
+ * @brief Parse a single TypeScript file for component definitions
+ * @param filePath Path to the .ts file
+ * @return Number of components found
+ */
+ usize parseFile(const std::string& filePath);
+
+ // =========================================================================
+ // Query
+ // =========================================================================
+
+ /** @brief Get all registered component definitions */
+ const std::vector<ScriptComponentDef>& getComponents() const { return components_; }
+
+ /** @brief Get component definition by name */
+ const ScriptComponentDef* getComponent(const std::string& name) const;
+
+ /** @brief Check if a component is registered */
+ bool hasComponent(const std::string& name) const;
+
+ /** @brief Get number of registered components */
+ usize componentCount() const { return components_.size(); }
+
+ // =========================================================================
+ // Instance Creation
+ // =========================================================================
+
+ /**
+ * @brief Create a component instance with default values
+ * @param name Component name
+ * @return Instance with default values, or nullopt if not found
+ */
+ std::optional<ScriptComponentInstance> createInstance(const std::string& name) const;
+
+ // =========================================================================
+ // Serialization Helpers
+ // =========================================================================
+
+ /** @brief Convert field type to string */
+ static std::string fieldTypeToString(ScriptFieldType type);
+
+ /** @brief Parse field type from string */
+ static ScriptFieldType stringToFieldType(const std::string& str);
+
+ /** @brief Serialize field value to JSON string */
+ static std::string serializeValue(const ScriptFieldValue& value, ScriptFieldType type);
+
+ /** @brief Parse field value from JSON string */
+ static ScriptFieldValue parseValue(const std::string& json, ScriptFieldType type);
+
+private:
+ std::string projectPath_;
+ std::vector<ScriptComponentDef> components_;
+ std::unordered_map<std::string, usize> nameToIndex_;
+
+ /** @brief Find all .ts files in directory recursively */
+ std::vector<std::string> findTypeScriptFiles(const std::string& dir);
+
+ /** @brief Parse defineComponent call from source code */
+ bool parseDefineComponent(const std::string& source, usize pos, ScriptComponentDef& outDef);
+
+ /** @brief Parse schema object { field: Type.xxx, ... } */
+ bool parseSchema(const std::string& source, usize start, usize end,
+ std::vector<ScriptFieldDef>& outFields);
+
+ /** @brief Parse defaults object { field: value, ... } */
+ void parseDefaults(const std::string& source, usize start, usize end,
+ std::vector<ScriptFieldDef>& fields);
+
+ /** @brief Find matching brace/bracket */
+ usize findMatchingBrace(const std::string& source, usize openPos, char open, char close);
+};
+
+} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/EditorToolbar.cpp b/src/esengine/editor/widgets/EditorToolbar.cpp
index e8fe94763..34b550d6a 100644
--- a/src/esengine/editor/widgets/EditorToolbar.cpp
+++ b/src/esengine/editor/widgets/EditorToolbar.cpp
@@ -121,9 +121,16 @@ void EditorToolbar::render(ui::UIBatchRenderer& renderer) {
constexpr glm::vec4 previewingBg{0.180f, 0.545f, 0.341f, 1.0f};
+ // Left side: scene management
+ drawButton(newSceneButton_, icons::FilePlus, false, buttonBg);
+ drawButton(saveButton_, icons::Save, false, buttonBg);
+
+ // Center: play controls
drawButton(playButton_, icons::Play, playing, playingBg);
drawButton(pauseButton_, icons::Pause, paused, pausedBg);
drawButton(stopButton_, icons::Square, false, buttonBg);
+
+ // Right side: web preview
drawButton(webPreviewButton_, icons::Globe, previewing, previewingBg);
}
@@ -134,6 +141,16 @@ void EditorToolbar::render(ui::UIBatchRenderer& renderer) {
bool EditorToolbar::onMouseDown(const ui::MouseButtonEvent& event) {
if (event.button != ui::MouseButton::Left) return false;
+ if (newSceneButton_.bounds.contains(event.x, event.y)) {
+ onNewScene.publish();
+ return true;
+ }
+
+ if (saveButton_.bounds.contains(event.x, event.y)) {
+ onSave.publish();
+ return true;
+ }
+
if (playButton_.bounds.contains(event.x, event.y)) {
if (state_ == PlayState::Paused) {
play();
@@ -166,6 +183,8 @@ bool EditorToolbar::onMouseDown(const ui::MouseButtonEvent& event) {
}
bool EditorToolbar::onMouseMove(const ui::MouseMoveEvent& event) {
+ newSceneButton_.hovered = newSceneButton_.bounds.contains(event.x, event.y);
+ saveButton_.hovered = saveButton_.bounds.contains(event.x, event.y);
playButton_.hovered = playButton_.bounds.contains(event.x, event.y);
pauseButton_.hovered = pauseButton_.bounds.contains(event.x, event.y);
stopButton_.hovered = stopButton_.bounds.contains(event.x, event.y);
@@ -185,14 +204,21 @@ void EditorToolbar::updateButtonBounds() {
constexpr f32 groupWidth = buttonSize * 3 + buttonGap * 2;
constexpr f32 padding = 8.0f;
- f32 centerX = bounds.x + bounds.width * 0.5f;
- f32 startX = centerX - groupWidth * 0.5f;
f32 centerY = bounds.y + (bounds.height - buttonSize) * 0.5f;
+ // Left side: scene management buttons
+ f32 leftX = bounds.x + padding;
+ newSceneButton_.bounds = ui::Rect{leftX, centerY, buttonSize, buttonSize};
+ saveButton_.bounds = ui::Rect{leftX + buttonSize + buttonGap, centerY, buttonSize, buttonSize};
+
+ // Center: play controls
+ f32 centerX = bounds.x + bounds.width * 0.5f;
+ f32 startX = centerX - groupWidth * 0.5f;
playButton_.bounds = ui::Rect{startX, centerY, buttonSize, buttonSize};
pauseButton_.bounds = ui::Rect{startX + buttonSize + buttonGap, centerY, buttonSize, buttonSize};
stopButton_.bounds = ui::Rect{startX + (buttonSize + buttonGap) * 2, centerY, buttonSize, buttonSize};
+ // Right side: web preview
f32 rightX = bounds.x + bounds.width - padding - buttonSize;
webPreviewButton_.bounds = ui::Rect{rightX, centerY, buttonSize, buttonSize};
}
diff --git a/src/esengine/editor/widgets/EditorToolbar.hpp b/src/esengine/editor/widgets/EditorToolbar.hpp
index f27dea008..45cf13e03 100644
--- a/src/esengine/editor/widgets/EditorToolbar.hpp
+++ b/src/esengine/editor/widgets/EditorToolbar.hpp
@@ -58,6 +58,8 @@ public:
Signal<void()> onPause;
Signal<void()> onStop;
Signal<void()> onWebPreview;
+ Signal<void()> onSave;
+ Signal<void()> onNewScene;
void startWebPreview(const std::string& directory);
void stopWebPreview();
@@ -78,6 +80,8 @@ private:
bool hovered = false;
};
+ ButtonState newSceneButton_;
+ ButtonState saveButton_;
ButtonState playButton_;
ButtonState pauseButton_;
ButtonState stopButton_;
diff --git a/src/esengine/platform/FileDialog.cpp b/src/esengine/platform/FileDialog.cpp
index 136176935..3d6957b49 100644
--- a/src/esengine/platform/FileDialog.cpp
+++ b/src/esengine/platform/FileDialog.cpp
@@ -17,126 +17,280 @@
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
-#include <commdlg.h>
+#include <shobjidl.h>
#include <shlobj.h>
#endif
namespace esengine {
// =============================================================================
-// Windows Implementation
+// Windows Implementation - Modern COM API
// =============================================================================
#ifdef ES_PLATFORM_WINDOWS
+namespace {
+
+// Convert UTF-8 to wide string
+std::wstring toWideString(const std::string& str) {
+ if (str.empty()) return L"";
+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
+ std::wstring result(size - 1, 0);
+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &result[0], size);
+ return result;
+}
+
+// Convert wide string to UTF-8
+std::string toUtf8String(const std::wstring& wstr) {
+ if (wstr.empty()) return "";
+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
+ std::string result(size - 1, 0);
+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &result[0], size, nullptr, nullptr);
+ return result;
+}
+
+} // namespace
+
std::string FileDialog::openFile(const std::string& title,
const std::vector<FileFilter>& filters,
const std::string& defaultPath) {
- char filename[MAX_PATH] = {0};
+ // Initialize COM
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+ bool comInitialized = SUCCEEDED(hr) || hr == S_FALSE;
+ if (!comInitialized) {
+ ES_LOG_ERROR("Failed to initialize COM for file dialog");
+ return "";
+ }
+
+ std::string result;
+ IFileOpenDialog* pDialog = nullptr;
+
+ hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_ALL,
+ IID_IFileOpenDialog, reinterpret_cast<void**>(&pDialog));
+ if (FAILED(hr) || !pDialog) {
+ ES_LOG_ERROR("Failed to create file open dialog");
+ CoUninitialize();
+ return "";
+ }
+
+ // Set title
+ std::wstring wTitle = toWideString(title);
+ pDialog->SetTitle(wTitle.c_str());
+
+ // Set file type filters
+ if (!filters.empty()) {
+ std::vector<COMDLG_FILTERSPEC> specs;
+ std::vector<std::wstring> names, patterns;
- std::string filterStr;
- if (filters.empty()) {
- filterStr = "All Files\0*.*\0";
- } else {
for (const auto& filter : filters) {
- filterStr += filter.name;
- filterStr.push_back('\0');
- filterStr += filter.pattern;
- filterStr.push_back('\0');
+ names.push_back(toWideString(filter.name));
+ std::string pattern = filter.pattern;
+ if (!pattern.empty() && pattern[0] != '*') {
+ pattern = "*." + pattern;
+ }
+ patterns.push_back(toWideString(pattern));
}
- }
- filterStr.push_back('\0');
- OPENFILENAMEA ofn = {};
- ofn.lStructSize = sizeof(ofn);
- ofn.hwndOwner = nullptr;
- ofn.lpstrFilter = filterStr.c_str();
- ofn.lpstrFile = filename;
- ofn.nMaxFile = MAX_PATH;
- ofn.lpstrTitle = title.c_str();
- ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
+ for (size_t i = 0; i < filters.size(); ++i) {
+ specs.push_back({names[i].c_str(), patterns[i].c_str()});
+ }
+
+ pDialog->SetFileTypes(static_cast<UINT>(specs.size()), specs.data());
+ pDialog->SetFileTypeIndex(1);
+ }
+ // Set default folder
if (!defaultPath.empty()) {
- ofn.lpstrInitialDir = defaultPath.c_str();
+ IShellItem* pFolder = nullptr;
+ std::wstring wPath = toWideString(defaultPath);
+ hr = SHCreateItemFromParsingName(wPath.c_str(), nullptr, IID_IShellItem,
+ reinterpret_cast<void**>(&pFolder));
+ if (SUCCEEDED(hr) && pFolder) {
+ pDialog->SetFolder(pFolder);
+ pFolder->Release();
+ }
}
- if (GetOpenFileNameA(&ofn)) {
- return std::string(filename);
+ // Show dialog
+ hr = pDialog->Show(nullptr);
+ if (SUCCEEDED(hr)) {
+ IShellItem* pItem = nullptr;
+ hr = pDialog->GetResult(&pItem);
+ if (SUCCEEDED(hr) && pItem) {
+ PWSTR pszPath = nullptr;
+ hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
+ if (SUCCEEDED(hr) && pszPath) {
+ result = toUtf8String(pszPath);
+ CoTaskMemFree(pszPath);
+ }
+ pItem->Release();
+ }
}
- return "";
+ pDialog->Release();
+ CoUninitialize();
+
+ return result;
}
std::string FileDialog::saveFile(const std::string& title,
const std::vector<FileFilter>& filters,
const std::string& defaultPath,
const std::string& defaultName) {
- char filename[MAX_PATH] = {0};
+ // Initialize COM
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+ bool comInitialized = SUCCEEDED(hr) || hr == S_FALSE;
+ if (!comInitialized) {
+ ES_LOG_ERROR("Failed to initialize COM for file dialog");
+ return "";
+ }
- if (!defaultName.empty()) {
- strncpy_s(filename, defaultName.c_str(), MAX_PATH - 1);
+ std::string result;
+ IFileSaveDialog* pDialog = nullptr;
+
+ hr = CoCreateInstance(CLSID_FileSaveDialog, nullptr, CLSCTX_ALL,
+ IID_IFileSaveDialog, reinterpret_cast<void**>(&pDialog));
+ if (FAILED(hr) || !pDialog) {
+ ES_LOG_ERROR("Failed to create file save dialog");
+ CoUninitialize();
+ return "";
}
- std::string filterStr;
- if (filters.empty()) {
- filterStr = "All Files\0*.*\0";
- } else {
+ // Set title
+ std::wstring wTitle = toWideString(title);
+ pDialog->SetTitle(wTitle.c_str());
+
+ // Set file type filters
+ std::string defaultExtension;
+ if (!filters.empty()) {
+ std::vector<COMDLG_FILTERSPEC> specs;
+ std::vector<std::wstring> names, patterns;
+
for (const auto& filter : filters) {
- filterStr += filter.name;
- filterStr.push_back('\0');
- filterStr += filter.pattern;
- filterStr.push_back('\0');
+ names.push_back(toWideString(filter.name));
+ std::string pattern = filter.pattern;
+ if (!pattern.empty() && pattern[0] != '*') {
+ defaultExtension = pattern;
+ pattern = "*." + pattern;
+ }
+ patterns.push_back(toWideString(pattern));
+ }
+
+ for (size_t i = 0; i < filters.size(); ++i) {
+ specs.push_back({names[i].c_str(), patterns[i].c_str()});
+ }
+
+ pDialog->SetFileTypes(static_cast<UINT>(specs.size()), specs.data());
+ pDialog->SetFileTypeIndex(1);
+
+ if (!defaultExtension.empty()) {
+ std::wstring wExt = toWideString(defaultExtension);
+ pDialog->SetDefaultExtension(wExt.c_str());
}
}
- filterStr.push_back('\0');
- OPENFILENAMEA ofn = {};
- ofn.lStructSize = sizeof(ofn);
- ofn.hwndOwner = nullptr;
- ofn.lpstrFilter = filterStr.c_str();
- ofn.lpstrFile = filename;
- ofn.nMaxFile = MAX_PATH;
- ofn.lpstrTitle = title.c_str();
- ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
+ // Set default filename
+ if (!defaultName.empty()) {
+ std::wstring wName = toWideString(defaultName);
+ pDialog->SetFileName(wName.c_str());
+ }
+ // Set default folder
if (!defaultPath.empty()) {
- ofn.lpstrInitialDir = defaultPath.c_str();
+ IShellItem* pFolder = nullptr;
+ std::wstring wPath = toWideString(defaultPath);
+ hr = SHCreateItemFromParsingName(wPath.c_str(), nullptr, IID_IShellItem,
+ reinterpret_cast<void**>(&pFolder));
+ if (SUCCEEDED(hr) && pFolder) {
+ pDialog->SetFolder(pFolder);
+ pFolder->Release();
+ }
}
- if (GetSaveFileNameA(&ofn)) {
- return std::string(filename);
+ // Show dialog
+ hr = pDialog->Show(nullptr);
+ if (SUCCEEDED(hr)) {
+ IShellItem* pItem = nullptr;
+ hr = pDialog->GetResult(&pItem);
+ if (SUCCEEDED(hr) && pItem) {
+ PWSTR pszPath = nullptr;
+ hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
+ if (SUCCEEDED(hr) && pszPath) {
+ result = toUtf8String(pszPath);
+ CoTaskMemFree(pszPath);
+ }
+ pItem->Release();
+ }
}
- return "";
-}
+ pDialog->Release();
+ CoUninitialize();
-static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM /*lParam*/, LPARAM lpData) {
- if (uMsg == BFFM_INITIALIZED && lpData != 0) {
- SendMessageA(hwnd, BFFM_SETSELECTION, TRUE, lpData);
- }
- return 0;
+ return result;
}
std::string FileDialog::selectFolder(const std::string& title,
const std::string& defaultPath) {
- char path[MAX_PATH] = {0};
-
- BROWSEINFOA bi = {};
- bi.lpszTitle = title.c_str();
- bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
- bi.lpfn = BrowseCallbackProc;
- bi.lParam = reinterpret_cast<LPARAM>(defaultPath.empty() ? nullptr : defaultPath.c_str());
-
- LPITEMIDLIST pidl = SHBrowseForFolderA(&bi);
- if (pidl != nullptr) {
- if (SHGetPathFromIDListA(pidl, path)) {
- CoTaskMemFree(pidl);
- return std::string(path);
+ // Initialize COM
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+ bool comInitialized = SUCCEEDED(hr) || hr == S_FALSE;
+ if (!comInitialized) {
+ ES_LOG_ERROR("Failed to initialize COM for folder dialog");
+ return "";
+ }
+
+ std::string result;
+ IFileOpenDialog* pDialog = nullptr;
+
+ hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_ALL,
+ IID_IFileOpenDialog, reinterpret_cast<void**>(&pDialog));
+ if (FAILED(hr) || !pDialog) {
+ ES_LOG_ERROR("Failed to create folder dialog");
+ CoUninitialize();
+ return "";
+ }
+
+ // Set options to pick folders
+ DWORD options;
+ pDialog->GetOptions(&options);
+ pDialog->SetOptions(options | FOS_PICKFOLDERS);
+
+ // Set title
+ std::wstring wTitle = toWideString(title);
+ pDialog->SetTitle(wTitle.c_str());
+
+ // Set default folder
+ if (!defaultPath.empty()) {
+ IShellItem* pFolder = nullptr;
+ std::wstring wPath = toWideString(defaultPath);
+ hr = SHCreateItemFromParsingName(wPath.c_str(), nullptr, IID_IShellItem,
+ reinterpret_cast<void**>(&pFolder));
+ if (SUCCEEDED(hr) && pFolder) {
+ pDialog->SetFolder(pFolder);
+ pFolder->Release();
}
- CoTaskMemFree(pidl);
}
- return "";
+ // Show dialog
+ hr = pDialog->Show(nullptr);
+ if (SUCCEEDED(hr)) {
+ IShellItem* pItem = nullptr;
+ hr = pDialog->GetResult(&pItem);
+ if (SUCCEEDED(hr) && pItem) {
+ PWSTR pszPath = nullptr;
+ hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
+ if (SUCCEEDED(hr) && pszPath) {
+ result = toUtf8String(pszPath);
+ CoTaskMemFree(pszPath);
+ }
+ pItem->Release();
+ }
+ }
+
+ pDialog->Release();
+ CoUninitialize();
+
+ return result;
}
// =============================================================================
diff --git a/src/esengine/platform/Platform.hpp b/src/esengine/platform/Platform.hpp
index 01998d691..c386c4c69 100644
--- a/src/esengine/platform/Platform.hpp
+++ b/src/esengine/platform/Platform.hpp
@@ -83,6 +83,8 @@ enum class KeyCode : u32 {
A = 65, ///< A key
C = 67, ///< C key
D = 68, ///< D key
+ N = 78, ///< N key
+ O = 79, ///< O key
S = 83, ///< S key
V = 86, ///< V key
W = 87, ///< W key
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 110da4251..0ca662ed1 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -202,6 +202,10 @@ void ResourceManager::releaseTexture(TextureHandle handle) {
}
}
+const std::string& ResourceManager::getTexturePath(TextureHandle handle) const {
+ return textures_.getPath(handle);
+}
+
TextureHandle ResourceManager::loadTextureByGUID(const std::string& guid, const std::string& path) {
auto it = guidToTexture_.find(guid);
if (it != guidToTexture_.end() && it->second.isValid()) {
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index fbc54a5d3..ef6a81c76 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -210,6 +210,13 @@ public:
*/
void releaseTexture(TextureHandle handle);
+ /**
+ * @brief Gets the cached path for a texture
+ * @param handle The texture handle
+ * @return The path used to load the texture, or empty if not found
+ */
+ const std::string& getTexturePath(TextureHandle handle) const;
+
/**
* @brief Loads a texture by GUID (with caching)
* @param guid Asset GUID from AssetDatabase
diff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hpp
index 255d771cc..44d39c021 100644
--- a/src/esengine/resource/ResourcePool.hpp
+++ b/src/esengine/resource/ResourcePool.hpp
@@ -217,6 +217,19 @@ public:
return entries_[handle.id()].refCount;
}
+ /**
+ * @brief Gets the cached path for a resource
+ * @param handle The resource handle
+ * @return The path, or empty string if not found
+ */
+ const std::string& getPath(Handle<T> handle) const {
+ static const std::string empty;
+ if (!handle.isValid() || handle.id() >= entries_.size()) {
+ return empty;
+ }
+ return entries_[handle.id()].path;
+ }
+
private:
std::vector<Entry> entries_;
std::vector<u32> freeList_;