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.

refactor: Simplify SDK architecture and update docs to TypeScript

esengine18b7dce8c817
diff --git a/CMakeLists.txt b/CMakeLists.txt
index fd8f29081..478589456 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -5,31 +5,10 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
-# Build options
option(ES_BUILD_WEB "Build for Web/Emscripten" OFF)
option(ES_BUILD_WXGAME "Build for WeChat MiniGame" OFF)
option(ES_BUILD_TESTS "Build tests" ON)
-option(ES_BUILD_EDITOR "Build editor (native only)" OFF)
-option(ES_BUILD_MODULAR "Build modular WASM (Web only, dynamic linking)" OFF)
-# Feature options (modular compilation)
-option(ES_FEATURE_SDF_FONT "Enable SDF font rendering (requires FreeType)" OFF)
-option(ES_FEATURE_BITMAP_FONT "Enable bitmap font rendering (lightweight)" OFF)
-
-# Auto-configure font features based on build target
-if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
- # Web/Mini-game: Force disable SDF font to reduce package size
- set(ES_FEATURE_SDF_FONT OFF CACHE BOOL "" FORCE)
- message(STATUS "Web build: SDF font disabled, using SystemFont")
-elseif(ES_BUILD_EDITOR)
- # Editor: Enable SDF font by default for better quality
- if(NOT DEFINED CACHE{ES_FEATURE_SDF_FONT} OR NOT ES_FEATURE_SDF_FONT)
- set(ES_FEATURE_SDF_FONT ON CACHE BOOL "" FORCE)
- message(STATUS "Editor build: SDF font enabled")
- endif()
-endif()
-
-# Include custom CMake modules
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(ESEngineConfig)
@@ -37,15 +16,12 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
include(Emscripten)
endif()
-# Modular build configuration (dynamic linking for Web)
-if(ES_BUILD_MODULAR AND ES_BUILD_WEB)
- include(ModularBuild)
-endif()
-
-# Third party libraries
add_subdirectory(third_party)
-# ESEngine library
+# =============================================================================
+# ESEngine Library
+# =============================================================================
+
set(ESENGINE_SOURCES
src/esengine/core/Application.cpp
src/esengine/core/Engine.cpp
@@ -66,49 +42,15 @@ set(ESENGINE_SOURCES
src/esengine/renderer/stb_image_impl.cpp
src/esengine/platform/input/Input.cpp
src/esengine/platform/PathResolver.cpp
- # UI System
- src/esengine/ui/UIContext.cpp
- src/esengine/ui/rendering/UIBatchRenderer.cpp
- src/esengine/ui/layout/StackLayout.cpp
- src/esengine/ui/layout/WrapLayout.cpp
- src/esengine/ui/widgets/Widget.cpp
- src/esengine/ui/widgets/Panel.cpp
- src/esengine/ui/widgets/Label.cpp
- src/esengine/ui/widgets/Button.cpp
- src/esengine/ui/widgets/ScrollView.cpp
- src/esengine/ui/widgets/TreeView.cpp
- src/esengine/ui/widgets/TextField.cpp
- src/esengine/ui/widgets/Checkbox.cpp
- src/esengine/ui/widgets/Slider.cpp
- src/esengine/ui/widgets/ContextMenu.cpp
- src/esengine/ui/widgets/Dropdown.cpp
- src/esengine/ui/widgets/DropdownPopup.cpp
- src/esengine/ui/widgets/ClickablePanel.cpp
- # Text utilities
- src/esengine/ui/text/TextMeasureHelper.cpp
)
-# Font sources (conditional)
-if(ES_FEATURE_SDF_FONT)
- list(APPEND ESENGINE_SOURCES
- src/esengine/ui/font/SDFFont.cpp
- src/esengine/ui/font/MSDFFont.cpp
- )
-endif()
-
-if(ES_FEATURE_BITMAP_FONT)
- list(APPEND ESENGINE_SOURCES src/esengine/ui/font/BitmapFont.cpp)
-endif()
-
-# SystemFont is always available (uses OS native APIs)
-list(APPEND ESENGINE_SOURCES src/esengine/ui/font/SystemFont.cpp)
-
set(ESENGINE_HEADERS
src/esengine/ESEngine.hpp
src/esengine/core/Types.hpp
src/esengine/core/Application.hpp
src/esengine/core/Engine.hpp
src/esengine/core/Log.hpp
+ src/esengine/core/Reflection.hpp
src/esengine/ecs/Entity.hpp
src/esengine/ecs/Component.hpp
src/esengine/ecs/System.hpp
@@ -116,7 +58,6 @@ set(ESENGINE_HEADERS
src/esengine/ecs/SparseSet.hpp
src/esengine/ecs/View.hpp
src/esengine/ecs/TransformSystem.hpp
- # ECS Components (split for modularity)
src/esengine/ecs/components/Transform.hpp
src/esengine/ecs/components/Hierarchy.hpp
src/esengine/ecs/components/Sprite.hpp
@@ -135,63 +76,20 @@ set(ESENGINE_HEADERS
src/esengine/renderer/Texture.hpp
src/esengine/renderer/Framebuffer.hpp
src/esengine/renderer/RenderCommand.hpp
+ src/esengine/renderer/RenderPipeline.hpp
src/esengine/platform/Platform.hpp
+ src/esengine/platform/FileSystem.hpp
src/esengine/platform/input/Input.hpp
- # Event system
src/esengine/events/Events.hpp
src/esengine/events/Connection.hpp
src/esengine/events/Signal.hpp
src/esengine/events/Sink.hpp
src/esengine/events/Dispatcher.hpp
- # UI System
- src/esengine/ui/UIContext.hpp
- src/esengine/ui/core/Types.hpp
- src/esengine/ui/core/Theme.hpp
- src/esengine/ui/events/UIEvent.hpp
- src/esengine/ui/layout/SizeValue.hpp
- src/esengine/ui/layout/Layout.hpp
- src/esengine/ui/layout/StackLayout.hpp
- src/esengine/ui/rendering/UIBatchRenderer.hpp
- src/esengine/ui/icons/Icons.hpp
- src/esengine/ui/widgets/Widget.hpp
- src/esengine/ui/widgets/Panel.hpp
- src/esengine/ui/widgets/Label.hpp
- src/esengine/ui/widgets/Button.hpp
- src/esengine/ui/widgets/ScrollView.hpp
- src/esengine/ui/widgets/TreeView.hpp
- src/esengine/ui/widgets/TextField.hpp
- src/esengine/ui/widgets/Checkbox.hpp
- src/esengine/ui/widgets/Slider.hpp
- src/esengine/ui/widgets/ContextMenu.hpp
- src/esengine/ui/widgets/Dropdown.hpp
- src/esengine/ui/widgets/DropdownPopup.hpp
- src/esengine/ui/widgets/ClickablePanel.hpp
- # Text utilities
- src/esengine/ui/text/TextMeasureHelper.hpp
)
-# Font headers (conditional)
-if(ES_FEATURE_SDF_FONT)
- list(APPEND ESENGINE_HEADERS
- src/esengine/ui/font/SDFFont.hpp
- src/esengine/ui/font/MSDFFont.hpp
- )
-endif()
-
-if(ES_FEATURE_BITMAP_FONT)
- list(APPEND ESENGINE_HEADERS src/esengine/ui/font/BitmapFont.hpp)
-endif()
-
-list(APPEND ESENGINE_HEADERS
- src/esengine/ui/font/IFont.hpp
- src/esengine/ui/font/SystemFont.hpp
-)
-
-# Generated binding file paths (defined early for use in source lists)
set(GENERATED_WEB_BINDINGS "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/bindings/WebBindings.generated.cpp")
set(GENERATED_TS_DEFINITIONS "${CMAKE_CURRENT_SOURCE_DIR}/bindings/esengine.d.ts")
-# Platform-specific sources
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
list(APPEND ESENGINE_SOURCES
src/esengine/platform/web/WebPlatform.cpp
@@ -199,38 +97,21 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
${GENERATED_WEB_BINDINGS}
)
else()
- # Native platform (GLFW + OpenGL)
list(APPEND ESENGINE_SOURCES
src/esengine/platform/native/NativePlatform.cpp
src/esengine/platform/native/NativeFileSystem.cpp
src/esengine/platform/FileDialog.cpp
- src/esengine/scripting/ScriptContext.cpp
- src/esengine/scripting/ScriptValue.cpp
- src/esengine/ecs/systems/ScriptSystem.cpp
)
list(APPEND ESENGINE_HEADERS
src/esengine/platform/native/NativePlatform.hpp
- src/esengine/scripting/ScriptContext.hpp
- src/esengine/scripting/ScriptValue.hpp
- src/esengine/scripting/bindings/ECSBindings.hpp
- src/esengine/ecs/systems/ScriptSystem.hpp
- src/esengine/ecs/components/Script.hpp
+ src/esengine/platform/FileDialog.hpp
)
-
endif()
-# Platform-independent headers
-list(APPEND ESENGINE_HEADERS
- src/esengine/platform/FileSystem.hpp
- src/esengine/platform/FileDialog.hpp
- src/esengine/core/Reflection.hpp
-)
-
# =============================================================================
-# EHT - ESEngine Header Tool (Binding Generation)
+# EHT - ESEngine Header Tool
# =============================================================================
-# Find Python3 for EHT
find_package(Python3 COMPONENTS Interpreter)
if(Python3_FOUND)
@@ -238,43 +119,31 @@ if(Python3_FOUND)
"${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/ecs/components/*.hpp"
)
- # Custom command to run EHT
add_custom_command(
- OUTPUT
- ${GENERATED_WEB_BINDINGS}
- ${GENERATED_TS_DEFINITIONS}
+ OUTPUT ${GENERATED_WEB_BINDINGS} ${GENERATED_TS_DEFINITIONS}
COMMAND ${Python3_EXECUTABLE}
"${CMAKE_CURRENT_SOURCE_DIR}/tools/eht.py"
--input "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/ecs/components"
--output "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/bindings"
--ts-output "${CMAKE_CURRENT_SOURCE_DIR}/bindings"
- DEPENDS
- ${COMPONENT_HEADERS}
- "${CMAKE_CURRENT_SOURCE_DIR}/tools/eht.py"
+ DEPENDS ${COMPONENT_HEADERS} "${CMAKE_CURRENT_SOURCE_DIR}/tools/eht.py"
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
- COMMENT "Running EHT (ESEngine Header Tool)..."
+ COMMENT "Running EHT..."
VERBATIM
)
- # Create custom target for EHT
- add_custom_target(eht
- DEPENDS
- ${GENERATED_WEB_BINDINGS}
- ${GENERATED_TS_DEFINITIONS}
- )
-
- message(STATUS "EHT (ESEngine Header Tool): ENABLED")
+ add_custom_target(eht DEPENDS ${GENERATED_WEB_BINDINGS} ${GENERATED_TS_DEFINITIONS})
+ message(STATUS "EHT: ENABLED")
else()
message(WARNING "Python3 not found - EHT DISABLED")
- message(WARNING "Using pre-existing binding files (may be outdated)")
endif()
add_library(esengine STATIC ${ESENGINE_SOURCES} ${ESENGINE_HEADERS})
-# Add dependency on EHT if Python is available
-if(Python3_FOUND)
- add_dependencies(esengine eht)
-endif()
+# EHT disabled - WebBindings.generated.cpp manually maintained
+# if(Python3_FOUND)
+# add_dependencies(esengine eht)
+# endif()
target_include_directories(esengine
PUBLIC
@@ -287,63 +156,32 @@ target_include_directories(esengine
${CMAKE_CURRENT_SOURCE_DIR}/third_party/stb
)
-# Add QuickJS include path only for native platform (SYSTEM to prevent version file issues)
-if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
- target_include_directories(esengine SYSTEM PRIVATE ${QUICKJS_INCLUDE_DIR})
-endif()
-
-# Core dependencies
target_link_libraries(esengine PUBLIC glm)
-# FreeType dependency (only needed for SDF fonts)
-if(ES_FEATURE_SDF_FONT)
- target_link_libraries(esengine PUBLIC freetype msdfgen-core msdfgen-ext)
- target_include_directories(esengine PUBLIC
- ${CMAKE_SOURCE_DIR}/third_party/freetype/include
- ${CMAKE_SOURCE_DIR}/third_party/msdfgen
- )
- target_compile_definitions(esengine PUBLIC ES_FEATURE_SDF_FONT=1)
-endif()
-
-if(ES_FEATURE_BITMAP_FONT)
- target_compile_definitions(esengine PUBLIC ES_FEATURE_BITMAP_FONT=1)
-endif()
-
-# Platform-specific settings
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
- # Emscripten-specific settings (link flags are in cmake/Emscripten.cmake)
target_compile_definitions(esengine PUBLIC ES_PLATFORM_WEB)
if(ES_BUILD_WXGAME)
target_compile_definitions(esengine PUBLIC ES_PLATFORM_WXGAME)
endif()
else()
- # Native platform - link GLFW, GLAD, OpenGL, QuickJS
find_package(OpenGL REQUIRED)
- target_compile_definitions(esengine PUBLIC ES_PLATFORM_NATIVE)
- # Development mode: use source directory for editor assets
- target_compile_definitions(esengine PUBLIC ES_SOURCE_DIR="${CMAKE_SOURCE_DIR}")
- target_link_libraries(esengine PUBLIC glfw glad OpenGL::GL quickjs)
- target_include_directories(esengine PUBLIC
- ${CMAKE_SOURCE_DIR}/third_party/glad/include
- )
+ target_compile_definitions(esengine PUBLIC ES_PLATFORM_NATIVE ES_SOURCE_DIR="${CMAKE_SOURCE_DIR}")
+ target_link_libraries(esengine PUBLIC glfw glad OpenGL::GL)
+ target_include_directories(esengine PUBLIC ${CMAKE_SOURCE_DIR}/third_party/glad/include)
if(WIN32)
target_compile_definitions(esengine PUBLIC ES_PLATFORM_WINDOWS)
endif()
endif()
-# Strict compiler warnings
esengine_set_strict_warnings(esengine)
# =============================================================================
-# Web SDK Library
+# Web SDK
# =============================================================================
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
add_executable(esengine_sdk src/esengine/bindings/WebSDKEntry.cpp)
- # Use --whole-archive to force link entire engine (prevent dead code elimination)
- target_link_libraries(esengine_sdk PRIVATE
- -Wl,--whole-archive esengine -Wl,--no-whole-archive
- )
+ target_link_libraries(esengine_sdk PRIVATE -Wl,--whole-archive esengine -Wl,--no-whole-archive)
es_apply_sdk_settings(esengine_sdk)
set_target_properties(esengine_sdk PROPERTIES
@@ -355,22 +193,14 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
COMMAND ${CMAKE_COMMAND} -E copy
"${CMAKE_SOURCE_DIR}/bindings/esengine.d.ts"
"${CMAKE_BINARY_DIR}/sdk/esengine.d.ts"
- COMMENT "Copying TypeScript definitions to SDK output"
)
endif()
-# Tests
if(ES_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
-# Editor (native platform only)
-if(ES_BUILD_EDITOR AND NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
- add_subdirectory(src/esengine/editor)
-endif()
-
-# Install rules
install(TARGETS esengine
EXPORT ESEngineTargets
LIBRARY DESTINATION lib
@@ -378,12 +208,4 @@ install(TARGETS esengine
RUNTIME DESTINATION bin
)
-install(DIRECTORY src/esengine/
- DESTINATION include/esengine
- FILES_MATCHING PATTERN "*.hpp"
-)
-
-install(DIRECTORY include/esengine/
- DESTINATION include/esengine
- FILES_MATCHING PATTERN "*.hpp"
-)
+install(DIRECTORY src/esengine/ DESTINATION include/esengine FILES_MATCHING PATTERN "*.hpp")
diff --git a/README.md b/README.md
index 84a979bbc..052c2a204 100644
--- a/README.md
+++ b/README.md
@@ -49,59 +49,57 @@ emcmake cmake -B build_web -DES_BUILD_WEB=ON && cmake --build build_web
emcmake cmake -B build_wxgame -DES_BUILD_WXGAME=ON && cmake --build build_wxgame
```
-### Quick Example (C++)
+### Quick Start
-```cpp
-#include <esengine/ESEngine.hpp>
-
-class MyGame : public esengine::Application {
-protected:
- void onInit() override { /* Initialize */ }
- void onUpdate(float dt) override { /* Update logic */ }
- void onRender() override { /* Render frame */ }
-};
-
-ES_MAIN(MyGame)
-```
-
-### TypeScript SDK
-
-The TypeScript SDK provides a high-level API for building games with ESEngine in the browser.
+The TypeScript SDK provides an ECS-style API for building games with ESEngine.
```bash
cd sdk && npm install && npm run build
```
```typescript
-import { Application, Renderer, Input, KeyCode } from '@esengine/sdk';
-
-class MyGame extends Application {
- protected onInit(): void {
- console.log('Game initialized!');
- }
-
- protected onUpdate(dt: number): void {
- if (Input.isKeyDown(KeyCode.Space)) {
- // Handle input
- }
- }
-
- protected onRender(): void {
- Renderer.clear();
- Renderer.drawQuad({ x: 100, y: 100 }, { x: 50, y: 50 }, { r: 1, g: 0, b: 0, a: 1 });
- }
+import {
+ App, createWebApp, defineSystem, Schedule,
+ Commands, Query, Res, Time,
+ LocalTransform, Sprite, Camera,
+ type ESEngineModule
+} from 'esengine';
+
+export async function main(Module: ESEngineModule): Promise<void> {
+ const app = createWebApp(Module);
+
+ // Startup system - runs once
+ app.addSystemToSchedule(Schedule.Startup, defineSystem(
+ [Commands()],
+ (cmds) => {
+ // Create camera
+ cmds.spawn()
+ .insert(Camera, { projectionType: 1, orthoSize: 400, isActive: true })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 10 } });
+
+ // Create sprite
+ cmds.spawn()
+ .insert(Sprite, { color: { x: 1, y: 0.5, z: 0.2, w: 1 }, size: { x: 100, y: 100 } })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } });
+ }
+ ));
+
+ // Update system - runs every frame
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(LocalTransform, Sprite)],
+ (time, query) => {
+ for (const [entity, transform, sprite] of query) {
+ transform.position.x = Math.sin(time.elapsed) * 100;
+ transform.position.y = Math.cos(time.elapsed) * 100;
+ }
+ }
+ ));
+
+ app.run();
}
-
-const game = new MyGame({
- width: 800,
- height: 600,
- canvas: 'canvas',
- wasmPath: './esengine.js', // Use C++ WASM backend
-});
-game.run();
```
-See [sdk/examples/hello-game](sdk/examples/hello-game/) for a complete example.
+See [sdk/examples/playground](sdk/examples/playground/) for a complete example.
## Documentation
diff --git a/assets/.esengine/assets.db b/assets/.esengine/assets.db
deleted file mode 100644
index a99d83377..000000000
--- a/assets/.esengine/assets.db
+++ /dev/null
@@ -1,851 +0,0 @@
-{
- "version": "1.0",
- "assets": [
- {
- "guid": "a9993ed8-9802-fb1c-f5e4-15864011fa2c",
- "path": "F:\\microes\\assets\\textures\\test.png",
- "name": "test.png",
- "type": 2,
- "fileSize": 6,
- "lastModified": 1769488062,
- "isDirectory": false
- },
- {
- "guid": "458ea613-0ce1-0325-3f9c-9f6937eafacf",
- "path": "assets\\prefabs\\Player.prefab",
- "name": "Player.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "6837963f-192a-0bcb-80e2-1cb45a8e35e7",
- "path": "assets\\scripts\\PlayerController.js",
- "name": "PlayerController.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "0f5a7d56-b021-7cfe-9ffd-b6deba57b565",
- "path": "assets\\textures\\ui_panel.png",
- "name": "ui_panel.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "0926ee8f-8eef-58fa-8d75-0ac49a8bf2b1",
- "path": "F:\\microes\\assets\\scenes",
- "name": "scenes",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "bbbdbf23-cecf-5053-0ebe-f3daf5b9e103",
- "path": "assets\\prefabs\\Explosion.prefab",
- "name": "Explosion.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "ab8960b7-4b05-8029-7577-571c44b9c394",
- "path": "F:\\microes\\assets\\fonts",
- "name": "fonts",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769653161,
- "isDirectory": true
- },
- {
- "guid": "83dd6048-d8fa-b62a-47d1-6f17771c459f",
- "path": "F:\\microes\\assets\\scripts",
- "name": "scripts",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "f543cca8-b481-a8be-8507-770c03c75eab",
- "path": "assets\\scenes",
- "name": "scenes",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "44626f54-604d-ae12-0f2e-2087f068acbf",
- "path": "F:\\microes\\assets\\prefabs\\Enemy.prefab",
- "name": "Enemy.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "a638dc81-b60d-567f-6820-13f4e9998407",
- "path": "assets\\.esengine\\assets.db",
- "name": "assets.db",
- "type": 0,
- "fileSize": 2186,
- "lastModified": 1769502460,
- "isDirectory": false
- },
- {
- "guid": "cf70754c-26ba-346d-c01d-ff9fc29a6e9e",
- "path": "assets\\.esengine",
- "name": ".esengine",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769495857,
- "isDirectory": true
- },
- {
- "guid": "e19fb621-dd86-3c0c-6b10-142a848c6a14",
- "path": "assets\\audio\\sfx_jump.wav",
- "name": "sfx_jump.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "e11483d8-2203-6eff-1b7e-0932b819f1c9",
- "path": "assets\\audio\\sfx_attack.wav",
- "name": "sfx_attack.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "0e48ebc1-25c8-2588-29aa-fb40564e2355",
- "path": "assets\\scenes\\MainMenu.scene",
- "name": "MainMenu.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "6650f3d3-a906-b4a9-1873-b75759499bf8",
- "path": "F:\\microes\\assets\\audio\\sfx_jump.wav",
- "name": "sfx_jump.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "0dd456da-eb9c-cdac-c429-b918b2f78b00",
- "path": "F:\\microes\\assets\\shaders\\particle.glsl",
- "name": "particle.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "86ed9e0d-442c-a047-9b51-09011c881685",
- "path": "assets\\audio",
- "name": "audio",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": true
- },
- {
- "guid": "602e5d05-e6b5-3cbe-a3a4-857b4290f255",
- "path": "assets\\scripts\\CameraFollow.js",
- "name": "CameraFollow.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "ca89cb26-11ee-a95a-940a-4d952d33b936",
- "path": "F:\\microes\\assets\\scenes\\MainMenu.scene",
- "name": "MainMenu.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "83d5664f-9f0b-4687-73b2-b854c5e6d5cf",
- "path": "assets\\fonts",
- "name": "fonts",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769501795,
- "isDirectory": true
- },
- {
- "guid": "d0e72f1c-981f-5995-dade-848b8b18813e",
- "path": "assets\\textures\\background.png",
- "name": "background.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "a19bf5bf-7a78-8cbd-00c8-8f38cf141628",
- "path": "F:\\microes\\assets\\fonts\\msyh.ttc",
- "name": "msyh.ttc",
- "type": 0,
- "fileSize": 19704352,
- "lastModified": 1769511857,
- "isDirectory": false
- },
- {
- "guid": "c771ea16-ad7f-3333-df52-9426cff8a384",
- "path": "assets\\textures\\ui_button.png",
- "name": "ui_button.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "7d86b8df-60d3-330a-ae99-ae597a929a9b",
- "path": "assets\\textures\\player.png",
- "name": "player.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "ca417dff-fe94-4361-ec9b-16504f048514",
- "path": "F:\\microes\\assets\\prefabs\\Bullet.prefab",
- "name": "Bullet.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "2402078f-7772-c860-8bce-dfdb1fc37788",
- "path": "F:\\microes\\assets\\audio\\bgm_main.mp3",
- "name": "bgm_main.mp3",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "99c227eb-f8d3-d0e8-843b-ceb126687e8b",
- "path": "F:\\microes\\assets\\audio",
- "name": "audio",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "1c90475d-0d57-c627-f004-15d52bee4319",
- "path": "F:\\microes\\assets\\shaders\\water.glsl",
- "name": "water.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "ce69c963-c0ea-0fb2-c96c-bf1afc0e0802",
- "path": "assets\\shaders\\postprocess.glsl",
- "name": "postprocess.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "08964537-6809-2c47-8997-7bbf1c75029f",
- "path": "assets\\scripts",
- "name": "scripts",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "8af759e0-a053-8e8c-1e34-48843f734d2f",
- "path": "assets\\textures\\enemy.png",
- "name": "enemy.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "ed1cf9a5-9d96-50d7-e385-82c605f70a63",
- "path": "F:\\microes\\assets\\prefabs\\Explosion.prefab",
- "name": "Explosion.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "e0220f45-6261-175f-883b-ba80783788f2",
- "path": "assets\\textures",
- "name": "textures",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": true
- },
- {
- "guid": "57c85655-8b7d-e5b6-d5a6-80eb2b0b49d3",
- "path": "assets\\scripts\\Inventory.js",
- "name": "Inventory.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "bca66dcd-f892-9c43-f176-62ac939c4de4",
- "path": "F:\\microes\\assets\\audio\\sfx_attack.wav",
- "name": "sfx_attack.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "bbb48cfb-31bf-8e65-6d26-fa4156d4b29c",
- "path": "F:\\microes\\assets\\shaders\\grid.esshader",
- "name": "grid.esshader",
- "type": 0,
- "fileSize": 318,
- "lastModified": 1769701529,
- "isDirectory": false
- },
- {
- "guid": "c71b2168-6faf-8d98-2ce8-4175ecfc98f2",
- "path": "assets\\prefabs\\Bullet.prefab",
- "name": "Bullet.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "6a7bd38a-6b72-be37-a497-9628dafb35e1",
- "path": "F:\\microes\\assets\\.esengine\\assets.db",
- "name": "assets.db",
- "type": 0,
- "fileSize": 24088,
- "lastModified": 1769823748,
- "isDirectory": false
- },
- {
- "guid": "08719359-3487-beb2-0d62-f54a2a8634c4",
- "path": "assets\\shaders",
- "name": "shaders",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "ce792685-9959-2c9f-d909-597cab98305a",
- "path": "F:\\microes\\assets\\fonts\\lucide_new.ttf",
- "name": "lucide_new.ttf",
- "type": 8,
- "fileSize": 793848,
- "lastModified": 1769653162,
- "isDirectory": false
- },
- {
- "guid": "d44064b6-5cd8-29c4-8dc3-e6f0b71c6ad1",
- "path": "F:\\microes\\assets\\textures\\ui_panel.png",
- "name": "ui_panel.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "02f457d5-e200-7f62-6850-7612ed829a63",
- "path": "assets\\scenes\\BossRoom.scene",
- "name": "BossRoom.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "b162bd84-eee3-1b79-807c-c64d2c64cb2b",
- "path": "F:\\microes\\assets\\scripts\\PlayerController.js",
- "name": "PlayerController.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "38633421-fb34-4766-58e7-b4ba7c8b5ee3",
- "path": "assets\\audio\\sfx_explosion.wav",
- "name": "sfx_explosion.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "539c3218-76fb-bed8-1442-3c43ae5be464",
- "path": "F:\\microes\\assets\\textures\\tileset.png",
- "name": "tileset.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "fb6e1999-a210-5293-9dc9-f648e6e8fc1f",
- "path": "assets\\shaders\\sprite.glsl",
- "name": "sprite.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "44aa95ad-d460-37e0-041f-c6a4449f8b17",
- "path": "assets\\textures\\test.png",
- "name": "test.png",
- "type": 2,
- "fileSize": 6,
- "lastModified": 1769488063,
- "isDirectory": false
- },
- {
- "guid": "b9c53311-d99a-e00b-9ba2-358e123efa4e",
- "path": "assets\\scripts\\GameManager.js",
- "name": "GameManager.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "4f4e6a0b-08fb-1c62-5a27-830f643cacff",
- "path": "F:\\microes\\assets\\prefabs",
- "name": "prefabs",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "3cc64ba4-5416-2768-7eff-dbba531179c4",
- "path": "assets\\textures\\particle.png",
- "name": "particle.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "02f1f294-5a7f-d28b-7095-a04518207f9c",
- "path": "F:\\microes\\assets\\scripts\\GameManager.js",
- "name": "GameManager.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "e704f3d4-170b-fecb-d4f9-4534e5056d78",
- "path": "assets\\shaders\\particle.glsl",
- "name": "particle.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "78390dfc-f548-9908-8279-6b3064ea26b3",
- "path": "F:\\microes\\assets\\textures",
- "name": "textures",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": true
- },
- {
- "guid": "986b148c-b4ea-cf89-2e04-37dc26624976",
- "path": "F:\\microes\\assets\\textures\\particle.png",
- "name": "particle.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "234c30b6-359c-51c1-a526-a970984ad90a",
- "path": "F:\\microes\\assets\\textures\\enemy.png",
- "name": "enemy.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "4b48ff38-aeb0-7a1b-38ec-03ad938736e9",
- "path": "F:\\microes\\assets\\shaders\\sprite.glsl",
- "name": "sprite.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "a424334b-4399-6ab1-440c-7da10d865e15",
- "path": "assets\\scripts\\UIManager.js",
- "name": "UIManager.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "32dd883f-81c7-59a9-8229-5920e8152da1",
- "path": "assets\\prefabs",
- "name": "prefabs",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": true
- },
- {
- "guid": "53cf7de5-ae26-2632-e022-e9108f6bbc2c",
- "path": "F:\\microes\\assets\\audio\\sfx_coin.wav",
- "name": "sfx_coin.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "e1d87090-38ce-2d60-5bdd-1f928fdaf88a",
- "path": "assets\\scenes\\Level1.scene",
- "name": "Level1.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "ff5ba3b5-d524-f202-72ae-a40add555353",
- "path": "assets\\scenes\\Level2.scene",
- "name": "Level2.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "9db35f84-665c-e687-86b1-cc78a3934216",
- "path": "assets\\test.txt",
- "name": "test.txt",
- "type": 0,
- "fileSize": 5,
- "lastModified": 1769488062,
- "isDirectory": false
- },
- {
- "guid": "cc395f8f-d6f9-a23d-db3b-7253b437aa8a",
- "path": "F:\\microes\\assets\\.esengine",
- "name": ".esengine",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769753978,
- "isDirectory": true
- },
- {
- "guid": "f23cff38-7fcd-d864-b487-6ca733c33582",
- "path": "F:\\microes\\assets\\scripts\\EnemyAI.js",
- "name": "EnemyAI.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "a6dd418b-dd75-0249-f26e-bb1b4cc294c8",
- "path": "F:\\microes\\assets\\shaders\\postprocess.glsl",
- "name": "postprocess.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "835ed25e-a75f-3a42-0953-d9af26b1cc87",
- "path": "F:\\microes\\assets\\test.txt",
- "name": "test.txt",
- "type": 0,
- "fileSize": 5,
- "lastModified": 1769488063,
- "isDirectory": false
- },
- {
- "guid": "06d02285-6f13-7665-e142-87cc08b9f6b8",
- "path": "assets\\fonts\\lucide.ttf",
- "name": "lucide.ttf",
- "type": 8,
- "fileSize": 793848,
- "lastModified": 1769501796,
- "isDirectory": false
- },
- {
- "guid": "d6dbbbb3-87ce-a096-8027-f7b9d7129e6f",
- "path": "assets\\scripts\\EnemyAI.js",
- "name": "EnemyAI.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "8283ad01-d8a2-48ae-c4e7-c1f8f0de7955",
- "path": "F:\\microes\\assets\\scripts\\UIManager.js",
- "name": "UIManager.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "04f5ced8-9d11-fa20-d612-06f12e563341",
- "path": "assets\\prefabs\\Coin.prefab",
- "name": "Coin.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "182aa6a4-c774-8473-5238-49e1d28f1c5d",
- "path": "assets\\prefabs\\Enemy.prefab",
- "name": "Enemy.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "3750f28c-b12f-4245-2036-9c552be15aea",
- "path": "F:\\microes\\assets\\fonts\\lucide.ttf",
- "name": "lucide.ttf",
- "type": 8,
- "fileSize": 793848,
- "lastModified": 1769501796,
- "isDirectory": false
- },
- {
- "guid": "30c0a678-ec31-5c3c-f60c-2b982d208861",
- "path": "F:\\microes\\assets\\textures\\background.png",
- "name": "background.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "f928d327-1c23-3d66-2009-d4d3daea8e31",
- "path": "F:\\microes\\assets\\textures\\skybox.png",
- "name": "skybox.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "6f4b1d08-8b77-b7eb-629d-c2ea4efba441",
- "path": "F:\\microes\\assets\\prefabs\\Coin.prefab",
- "name": "Coin.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "88f4512c-08fc-7521-0720-aa75e35defbc",
- "path": "assets\\audio\\bgm_main.mp3",
- "name": "bgm_main.mp3",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "9d4aa6d5-4f32-3634-e6fa-2c79467a2a9c",
- "path": "F:\\microes\\assets\\shaders",
- "name": "shaders",
- "type": 1,
- "fileSize": 0,
- "lastModified": 1769703321,
- "isDirectory": true
- },
- {
- "guid": "abf642da-9512-d0bd-e306-e1bce616320c",
- "path": "F:\\microes\\assets\\scenes\\Level2.scene",
- "name": "Level2.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "7fe2a865-bb30-1847-62e3-d289b5616a3a",
- "path": "F:\\microes\\assets\\scenes\\BossRoom.scene",
- "name": "BossRoom.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "9d69bbdf-276b-8f14-cc66-10e8dfcdb283",
- "path": "F:\\microes\\assets\\scripts\\CameraFollow.js",
- "name": "CameraFollow.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "0b354ef8-0528-35e8-b628-bed14b4960db",
- "path": "F:\\microes\\assets\\audio\\bgm_battle.mp3",
- "name": "bgm_battle.mp3",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "d11c2d62-5870-5040-3e1a-bf5bc046b98a",
- "path": "F:\\microes\\assets\\textures\\ui_button.png",
- "name": "ui_button.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "c6908b3b-7d16-8e81-5c2d-c65c46fee0d4",
- "path": "assets\\audio\\bgm_battle.mp3",
- "name": "bgm_battle.mp3",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "73405f12-7a43-8434-140c-748f9448be34",
- "path": "F:\\microes\\assets\\shaders\\axis.esshader",
- "name": "axis.esshader",
- "type": 0,
- "fileSize": 392,
- "lastModified": 1769701535,
- "isDirectory": false
- },
- {
- "guid": "6e88b347-db2d-b526-87c6-301569094b15",
- "path": "F:\\microes\\assets\\audio\\sfx_explosion.wav",
- "name": "sfx_explosion.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "c6113f63-03d0-811d-550a-8f26f331233d",
- "path": "assets\\textures\\tileset.png",
- "name": "tileset.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "90db01ce-eadb-5131-35ee-a55e9f60bb4d",
- "path": "assets\\shaders\\water.glsl",
- "name": "water.glsl",
- "type": 5,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "b55ead52-b974-950b-26a3-a227e2ac41e9",
- "path": "assets\\audio\\sfx_coin.wav",
- "name": "sfx_coin.wav",
- "type": 3,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "49fa3441-7d74-bf79-c116-717b849b78ce",
- "path": "F:\\microes\\assets\\prefabs\\Player.prefab",
- "name": "Player.prefab",
- "type": 7,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "d3d9a556-8861-fbc2-504a-151ef73f41de",
- "path": "F:\\microes\\assets\\textures\\player.png",
- "name": "player.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "f29a2ee0-016a-f018-436a-9c11731f251a",
- "path": "F:\\microes\\assets\\scripts\\Inventory.js",
- "name": "Inventory.js",
- "type": 4,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- },
- {
- "guid": "22bdfe10-0ff6-620f-56ec-26a8142aec33",
- "path": "assets\\textures\\skybox.png",
- "name": "skybox.png",
- "type": 2,
- "fileSize": 0,
- "lastModified": 1769503001,
- "isDirectory": false
- },
- {
- "guid": "090ed68c-0dbe-382c-e163-5ad3bc22abad",
- "path": "F:\\microes\\assets\\scenes\\Level1.scene",
- "name": "Level1.scene",
- "type": 6,
- "fileSize": 0,
- "lastModified": 1769503002,
- "isDirectory": false
- }
- ]
-}
diff --git a/assets/audio/bgm_battle.mp3 b/assets/audio/bgm_battle.mp3
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/audio/bgm_main.mp3 b/assets/audio/bgm_main.mp3
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/audio/sfx_attack.wav b/assets/audio/sfx_attack.wav
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/audio/sfx_coin.wav b/assets/audio/sfx_coin.wav
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/audio/sfx_explosion.wav b/assets/audio/sfx_explosion.wav
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/audio/sfx_jump.wav b/assets/audio/sfx_jump.wav
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/fonts/lucide.ttf b/assets/fonts/lucide.ttf
deleted file mode 100644
index 72c0bf60b..000000000
Binary files a/assets/fonts/lucide.ttf and /dev/null differ
diff --git a/assets/fonts/lucide_new.ttf b/assets/fonts/lucide_new.ttf
deleted file mode 100644
index 72c0bf60b..000000000
Binary files a/assets/fonts/lucide_new.ttf and /dev/null differ
diff --git a/assets/fonts/msyh.ttc b/assets/fonts/msyh.ttc
deleted file mode 100644
index ea174b27d..000000000
Binary files a/assets/fonts/msyh.ttc and /dev/null differ
diff --git a/assets/prefabs/Bullet.prefab b/assets/prefabs/Bullet.prefab
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/prefabs/Coin.prefab b/assets/prefabs/Coin.prefab
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/prefabs/Enemy.prefab b/assets/prefabs/Enemy.prefab
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/prefabs/Explosion.prefab b/assets/prefabs/Explosion.prefab
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/prefabs/Player.prefab b/assets/prefabs/Player.prefab
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scenes/BossRoom.scene b/assets/scenes/BossRoom.scene
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scenes/Level1.scene b/assets/scenes/Level1.scene
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scenes/Level2.scene b/assets/scenes/Level2.scene
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scenes/MainMenu.scene b/assets/scenes/MainMenu.scene
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scripts/CameraFollow.js b/assets/scripts/CameraFollow.js
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scripts/EnemyAI.js b/assets/scripts/EnemyAI.js
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scripts/GameManager.js b/assets/scripts/GameManager.js
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scripts/Inventory.js b/assets/scripts/Inventory.js
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scripts/PlayerController.js b/assets/scripts/PlayerController.js
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/scripts/UIManager.js b/assets/scripts/UIManager.js
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/shaders/particle.glsl b/assets/shaders/particle.glsl
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/shaders/postprocess.glsl b/assets/shaders/postprocess.glsl
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/shaders/sprite.glsl b/assets/shaders/sprite.glsl
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/shaders/water.glsl b/assets/shaders/water.glsl
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/templates/src/components/index.ts b/assets/templates/src/components/index.ts
deleted file mode 100644
index fbc2c1fe8..000000000
--- a/assets/templates/src/components/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { Velocity } from './movement';
-
-export const components = {
- Velocity,
-};
diff --git a/assets/templates/src/components/movement.ts b/assets/templates/src/components/movement.ts
deleted file mode 100644
index b37629f85..000000000
--- a/assets/templates/src/components/movement.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-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
deleted file mode 100644
index b22e60a40..000000000
--- a/assets/templates/src/main.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-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
deleted file mode 100644
index b025f53db..000000000
--- a/assets/templates/src/systems/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { movementSystem } from './movement';
-
-export const systems = [
- movementSystem,
-];
diff --git a/assets/templates/src/systems/movement.ts b/assets/templates/src/systems/movement.ts
deleted file mode 100644
index 4d7efba8a..000000000
--- a/assets/templates/src/systems/movement.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-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/assets/test.txt b/assets/test.txt
deleted file mode 100644
index 9daeafb98..000000000
--- a/assets/test.txt
+++ /dev/null
@@ -1 +0,0 @@
-test
diff --git a/assets/textures/background.png b/assets/textures/background.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/enemy.png b/assets/textures/enemy.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/particle.png b/assets/textures/particle.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/player.png b/assets/textures/player.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/skybox.png b/assets/textures/skybox.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/test.png b/assets/textures/test.png
deleted file mode 100644
index 180cf8328..000000000
--- a/assets/textures/test.png
+++ /dev/null
@@ -1 +0,0 @@
-test2
diff --git a/assets/textures/tileset.png b/assets/textures/tileset.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/ui_button.png b/assets/textures/ui_button.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/assets/textures/ui_panel.png b/assets/textures/ui_panel.png
deleted file mode 100644
index e69de29bb..000000000
diff --git a/bindings/platform/web/index.html b/bindings/platform/web/index.html
deleted file mode 100644
index 31628d776..000000000
--- a/bindings/platform/web/index.html
+++ /dev/null
@@ -1,45 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>ESEngine</title>
- <style>
- * {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
- body {
- background: #1a1a2e;
- display: flex;
- justify-content: center;
- align-items: center;
- min-height: 100vh;
- overflow: hidden;
- }
- #canvas {
- display: block;
- }
- #loading {
- position: absolute;
- color: #fff;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- font-size: 14px;
- }
- </style>
-</head>
-<body>
- <div id="loading">Loading...</div>
- <canvas id="canvas"></canvas>
- <script>
- var Module = {
- canvas: document.getElementById('canvas'),
- onRuntimeInitialized: function() {
- document.getElementById('loading').style.display = 'none';
- }
- };
- </script>
- <script src="esengine.js"></script>
-</body>
-</html>
diff --git a/build-modular/CPackConfig.cmake b/build-modular/CPackConfig.cmake
deleted file mode 100644
index d469c0162..000000000
--- a/build-modular/CPackConfig.cmake
+++ /dev/null
@@ -1,79 +0,0 @@
-# This file will be configured to contain variables for CPack. These variables
-# should be set in the CMake list file of the project before CPack module is
-# included. The list of available CPACK_xxx variables and their associated
-# documentation may be obtained using
-# cpack --help-variable-list
-#
-# Some variables are common to all generators (e.g. CPACK_PACKAGE_NAME)
-# and some are specific to a generator
-# (e.g. CPACK_NSIS_EXTRA_INSTALL_COMMANDS). The generator specific variables
-# usually begin with CPACK_<GENNAME>_xxxx.
-
-
-set(CPACK_BUILD_SOURCE_DIRS "F:/microes;F:/microes/build-modular")
-set(CPACK_CMAKE_GENERATOR "MinGW Makefiles")
-set(CPACK_COMPONENTS_ALL "Unspecified;headers;pkgconfig")
-set(CPACK_COMPONENT_HEADERS_DEPENDS "libraries")
-set(CPACK_COMPONENT_HEADERS_DESCRIPTION "C/C++ header files for use with FreeType")
-set(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "C/C++ Headers")
-set(CPACK_COMPONENT_HEADERS_GROUP "Development")
-set(CPACK_COMPONENT_LIBRARIES_DESCRIPTION "Library used to build programs which use FreeType")
-set(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "Libraries")
-set(CPACK_COMPONENT_LIBRARIES_GROUP "Development")
-set(CPACK_COMPONENT_UNSPECIFIED_HIDDEN "TRUE")
-set(CPACK_COMPONENT_UNSPECIFIED_REQUIRED "TRUE")
-set(CPACK_DEFAULT_PACKAGE_DESCRIPTION_FILE "C:/msys64/mingw64/share/cmake/Templates/CPack.GenericDescription.txt")
-set(CPACK_DEFAULT_PACKAGE_DESCRIPTION_SUMMARY "ESEngine built using CMake")
-set(CPACK_DMG_SLA_USE_RESOURCE_FILE_LICENSE "ON")
-set(CPACK_GENERATOR "TGZ")
-set(CPACK_INNOSETUP_ARCHITECTURE "x86")
-set(CPACK_INSTALL_CMAKE_PROJECTS "F:/microes/build-modular;ESEngine;ALL;/")
-set(CPACK_INSTALL_PREFIX "F:/emsdk/upstream/emscripten/cache/sysroot")
-set(CPACK_MODULE_PATH "F:/emsdk/upstream/emscripten/cmake/Modules;F:/emsdk/upstream/emscripten/cmake/Modules;F:/microes/cmake;F:/microes/third_party/freetype/builds/cmake")
-set(CPACK_NSIS_DISPLAY_NAME "ESEngine 2.13.3")
-set(CPACK_NSIS_INSTALLER_ICON_CODE "")
-set(CPACK_NSIS_INSTALLER_MUI_ICON_CODE "")
-set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES")
-set(CPACK_NSIS_PACKAGE_NAME "ESEngine 2.13.3")
-set(CPACK_NSIS_UNINSTALL_NAME "Uninstall")
-set(CPACK_OBJCOPY_EXECUTABLE "C:/msys64/mingw64/bin/objcopy.exe")
-set(CPACK_OBJDUMP_EXECUTABLE "C:/msys64/mingw64/bin/objdump.exe")
-set(CPACK_OUTPUT_CONFIG_FILE "F:/microes/build-modular/CPackConfig.cmake")
-set(CPACK_PACKAGE_DEFAULT_LOCATION "/")
-set(CPACK_PACKAGE_DESCRIPTION_FILE "F:/microes/third_party/freetype/README")
-set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "The FreeType font rendering library.")
-set(CPACK_PACKAGE_FILE_NAME "ESEngine-2.13.3-Emscripten")
-set(CPACK_PACKAGE_INSTALL_DIRECTORY "ESEngine 2.13.3")
-set(CPACK_PACKAGE_INSTALL_REGISTRY_KEY "ESEngine 2.13.3")
-set(CPACK_PACKAGE_NAME "ESEngine")
-set(CPACK_PACKAGE_RELOCATABLE "true")
-set(CPACK_PACKAGE_VENDOR "Humanity")
-set(CPACK_PACKAGE_VERSION "2.13.3")
-set(CPACK_PACKAGE_VERSION_MAJOR "2")
-set(CPACK_PACKAGE_VERSION_MINOR "13")
-set(CPACK_PACKAGE_VERSION_PATCH "3")
-set(CPACK_READELF_EXECUTABLE "C:/msys64/mingw64/bin/readelf.exe")
-set(CPACK_RESOURCE_FILE_LICENSE "F:/microes/third_party/freetype/LICENSE.TXT")
-set(CPACK_RESOURCE_FILE_README "C:/msys64/mingw64/share/cmake/Templates/CPack.GenericDescription.txt")
-set(CPACK_RESOURCE_FILE_WELCOME "C:/msys64/mingw64/share/cmake/Templates/CPack.GenericWelcome.txt")
-set(CPACK_SET_DESTDIR "OFF")
-set(CPACK_SOURCE_GENERATOR "TBZ2;TGZ;TXZ;TZ")
-set(CPACK_SOURCE_OUTPUT_CONFIG_FILE "F:/microes/build-modular/CPackSourceConfig.cmake")
-set(CPACK_SOURCE_RPM "OFF")
-set(CPACK_SOURCE_TBZ2 "ON")
-set(CPACK_SOURCE_TGZ "ON")
-set(CPACK_SOURCE_TXZ "ON")
-set(CPACK_SOURCE_TZ "ON")
-set(CPACK_SOURCE_ZIP "OFF")
-set(CPACK_SYSTEM_NAME "Emscripten")
-set(CPACK_THREADS "1")
-set(CPACK_TOPLEVEL_TAG "Emscripten")
-set(CPACK_WIX_SIZEOF_VOID_P "4")
-
-if(NOT CPACK_PROPERTIES_FILE)
- set(CPACK_PROPERTIES_FILE "F:/microes/build-modular/CPackProperties.cmake")
-endif()
-
-if(EXISTS ${CPACK_PROPERTIES_FILE})
- include(${CPACK_PROPERTIES_FILE})
-endif()
diff --git a/build-modular/CPackSourceConfig.cmake b/build-modular/CPackSourceConfig.cmake
deleted file mode 100644
index 299fa1c6c..000000000
--- a/build-modular/CPackSourceConfig.cmake
+++ /dev/null
@@ -1,87 +0,0 @@
-# This file will be configured to contain variables for CPack. These variables
-# should be set in the CMake list file of the project before CPack module is
-# included. The list of available CPACK_xxx variables and their associated
-# documentation may be obtained using
-# cpack --help-variable-list
-#
-# Some variables are common to all generators (e.g. CPACK_PACKAGE_NAME)
-# and some are specific to a generator
-# (e.g. CPACK_NSIS_EXTRA_INSTALL_COMMANDS). The generator specific variables
-# usually begin with CPACK_<GENNAME>_xxxx.
-
-
-set(CPACK_BUILD_SOURCE_DIRS "F:/microes;F:/microes/build-modular")
-set(CPACK_CMAKE_GENERATOR "MinGW Makefiles")
-set(CPACK_COMPONENTS_ALL "Unspecified;headers;pkgconfig")
-set(CPACK_COMPONENT_HEADERS_DEPENDS "libraries")
-set(CPACK_COMPONENT_HEADERS_DESCRIPTION "C/C++ header files for use with FreeType")
-set(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "C/C++ Headers")
-set(CPACK_COMPONENT_HEADERS_GROUP "Development")
-set(CPACK_COMPONENT_LIBRARIES_DESCRIPTION "Library used to build programs which use FreeType")
-set(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "Libraries")
-set(CPACK_COMPONENT_LIBRARIES_GROUP "Development")
-set(CPACK_COMPONENT_UNSPECIFIED_HIDDEN "TRUE")
-set(CPACK_COMPONENT_UNSPECIFIED_REQUIRED "TRUE")
-set(CPACK_DEFAULT_PACKAGE_DESCRIPTION_FILE "C:/msys64/mingw64/share/cmake/Templates/CPack.GenericDescription.txt")
-set(CPACK_DEFAULT_PACKAGE_DESCRIPTION_SUMMARY "ESEngine built using CMake")
-set(CPACK_DMG_SLA_USE_RESOURCE_FILE_LICENSE "ON")
-set(CPACK_GENERATOR "TBZ2;TGZ;TXZ;TZ")
-set(CPACK_IGNORE_FILES "/CVS/;/\\.svn/;/\\.bzr/;/\\.hg/;/\\.git/;\\.swp\$;\\.#;/#")
-set(CPACK_INNOSETUP_ARCHITECTURE "x86")
-set(CPACK_INSTALLED_DIRECTORIES "F:/microes;/")
-set(CPACK_INSTALL_CMAKE_PROJECTS "")
-set(CPACK_INSTALL_PREFIX "F:/emsdk/upstream/emscripten/cache/sysroot")
-set(CPACK_MODULE_PATH "F:/emsdk/upstream/emscripten/cmake/Modules;F:/emsdk/upstream/emscripten/cmake/Modules;F:/microes/cmake;F:/microes/third_party/freetype/builds/cmake")
-set(CPACK_NSIS_DISPLAY_NAME "ESEngine 2.13.3")
-set(CPACK_NSIS_INSTALLER_ICON_CODE "")
-set(CPACK_NSIS_INSTALLER_MUI_ICON_CODE "")
-set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES")
-set(CPACK_NSIS_PACKAGE_NAME "ESEngine 2.13.3")
-set(CPACK_NSIS_UNINSTALL_NAME "Uninstall")
-set(CPACK_OBJCOPY_EXECUTABLE "C:/msys64/mingw64/bin/objcopy.exe")
-set(CPACK_OBJDUMP_EXECUTABLE "C:/msys64/mingw64/bin/objdump.exe")
-set(CPACK_OUTPUT_CONFIG_FILE "F:/microes/build-modular/CPackConfig.cmake")
-set(CPACK_PACKAGE_DEFAULT_LOCATION "/")
-set(CPACK_PACKAGE_DESCRIPTION_FILE "F:/microes/third_party/freetype/README")
-set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "The FreeType font rendering library.")
-set(CPACK_PACKAGE_FILE_NAME "ESEngine-2.13.3-Source")
-set(CPACK_PACKAGE_INSTALL_DIRECTORY "ESEngine 2.13.3")
-set(CPACK_PACKAGE_INSTALL_REGISTRY_KEY "ESEngine 2.13.3")
-set(CPACK_PACKAGE_NAME "ESEngine")
-set(CPACK_PACKAGE_RELOCATABLE "true")
-set(CPACK_PACKAGE_VENDOR "Humanity")
-set(CPACK_PACKAGE_VERSION "2.13.3")
-set(CPACK_PACKAGE_VERSION_MAJOR "2")
-set(CPACK_PACKAGE_VERSION_MINOR "13")
-set(CPACK_PACKAGE_VERSION_PATCH "3")
-set(CPACK_READELF_EXECUTABLE "C:/msys64/mingw64/bin/readelf.exe")
-set(CPACK_RESOURCE_FILE_LICENSE "F:/microes/third_party/freetype/LICENSE.TXT")
-set(CPACK_RESOURCE_FILE_README "C:/msys64/mingw64/share/cmake/Templates/CPack.GenericDescription.txt")
-set(CPACK_RESOURCE_FILE_WELCOME "C:/msys64/mingw64/share/cmake/Templates/CPack.GenericWelcome.txt")
-set(CPACK_RPM_PACKAGE_SOURCES "ON")
-set(CPACK_SET_DESTDIR "OFF")
-set(CPACK_SOURCE_GENERATOR "TBZ2;TGZ;TXZ;TZ")
-set(CPACK_SOURCE_IGNORE_FILES "/CVS/;/\\.svn/;/\\.bzr/;/\\.hg/;/\\.git/;\\.swp\$;\\.#;/#")
-set(CPACK_SOURCE_INSTALLED_DIRECTORIES "F:/microes;/")
-set(CPACK_SOURCE_OUTPUT_CONFIG_FILE "F:/microes/build-modular/CPackSourceConfig.cmake")
-set(CPACK_SOURCE_PACKAGE_FILE_NAME "ESEngine-2.13.3-Source")
-set(CPACK_SOURCE_RPM "OFF")
-set(CPACK_SOURCE_TBZ2 "ON")
-set(CPACK_SOURCE_TGZ "ON")
-set(CPACK_SOURCE_TOPLEVEL_TAG "Emscripten-Source")
-set(CPACK_SOURCE_TXZ "ON")
-set(CPACK_SOURCE_TZ "ON")
-set(CPACK_SOURCE_ZIP "OFF")
-set(CPACK_STRIP_FILES "")
-set(CPACK_SYSTEM_NAME "Emscripten")
-set(CPACK_THREADS "1")
-set(CPACK_TOPLEVEL_TAG "Emscripten-Source")
-set(CPACK_WIX_SIZEOF_VOID_P "4")
-
-if(NOT CPACK_PROPERTIES_FILE)
- set(CPACK_PROPERTIES_FILE "F:/microes/build-modular/CPackProperties.cmake")
-endif()
-
-if(EXISTS ${CPACK_PROPERTIES_FILE})
- include(${CPACK_PROPERTIES_FILE})
-endif()
diff --git a/build-modular/third_party/freetype/freetype-config-version.cmake b/build-modular/third_party/freetype/freetype-config-version.cmake
deleted file mode 100644
index 13c66894a..000000000
--- a/build-modular/third_party/freetype/freetype-config-version.cmake
+++ /dev/null
@@ -1,65 +0,0 @@
-# This is a basic version file for the Config-mode of find_package().
-# It is used by write_basic_package_version_file() as input file for configure_file()
-# to create a version-file which can be installed along a config.cmake file.
-#
-# The created file sets PACKAGE_VERSION_EXACT if the current version string and
-# the requested version string are exactly the same and it sets
-# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version,
-# but only if the requested major version is the same as the current one.
-# The variable CVF_VERSION must be set before calling configure_file().
-
-
-set(PACKAGE_VERSION "2.13.3")
-
-if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
-else()
-
- if("2.13.3" MATCHES "^([0-9]+)\\.")
- set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}")
- if(NOT CVF_VERSION_MAJOR VERSION_EQUAL 0)
- string(REGEX REPLACE "^0+" "" CVF_VERSION_MAJOR "${CVF_VERSION_MAJOR}")
- endif()
- else()
- set(CVF_VERSION_MAJOR "2.13.3")
- endif()
-
- if(PACKAGE_FIND_VERSION_RANGE)
- # both endpoints of the range must have the expected major version
- math (EXPR CVF_VERSION_MAJOR_NEXT "${CVF_VERSION_MAJOR} + 1")
- if (NOT PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
- OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX_MAJOR STREQUAL CVF_VERSION_MAJOR)
- OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX VERSION_LESS_EQUAL CVF_VERSION_MAJOR_NEXT)))
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
- elseif(PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
- AND ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS_EQUAL PACKAGE_FIND_VERSION_MAX)
- OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MAX)))
- set(PACKAGE_VERSION_COMPATIBLE TRUE)
- else()
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
- endif()
- else()
- if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR)
- set(PACKAGE_VERSION_COMPATIBLE TRUE)
- else()
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
- endif()
-
- if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
- set(PACKAGE_VERSION_EXACT TRUE)
- endif()
- endif()
-endif()
-
-
-# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
-if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "4" STREQUAL "")
- return()
-endif()
-
-# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
-if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "4")
- math(EXPR installedBits "4 * 8")
- set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
- set(PACKAGE_VERSION_UNSUITABLE TRUE)
-endif()
diff --git a/build-modular/third_party/freetype/freetype2.pc b/build-modular/third_party/freetype/freetype2.pc
deleted file mode 100644
index bf4502b54..000000000
--- a/build-modular/third_party/freetype/freetype2.pc
+++ /dev/null
@@ -1,14 +0,0 @@
-prefix=F:/emsdk/upstream/emscripten/cache/sysroot
-exec_prefix=${prefix}
-libdir=${prefix}/lib
-includedir=${prefix}/include
-
-Name: FreeType 2
-URL: https://freetype.org
-Description: A free, high-quality, and portable font engine.
-Version: 26.2.20
-Requires:
-Requires.private:
-Libs: -L${libdir} -lfreetype
-Libs.private:
-Cflags: -I${includedir}/freetype2
diff --git a/build-modular/third_party/freetype/include/freetype/config/ftconfig.h b/build-modular/third_party/freetype/include/freetype/config/ftconfig.h
deleted file mode 100644
index ef58b2f88..000000000
--- a/build-modular/third_party/freetype/include/freetype/config/ftconfig.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************************
- *
- * ftconfig.h.in
- *
- * UNIX-specific configuration file (specification only).
- *
- * Copyright (C) 1996-2024 by
- * David Turner, Robert Wilhelm, and Werner Lemberg.
- *
- * This file is part of the FreeType project, and may only be used,
- * modified, and distributed under the terms of the FreeType project
- * license, LICENSE.TXT. By continuing to use, modify, or distribute
- * this file you indicate that you have read the license and
- * understand and accept it fully.
- *
- */
-
-
- /**************************************************************************
- *
- * This header file contains a number of macro definitions that are used by
- * the rest of the engine. Most of the macros here are automatically
- * determined at compile time, and you should not need to change it to port
- * FreeType, except to compile the library with a non-ANSI compiler.
- *
- * Note however that if some specific modifications are needed, we advise
- * you to place a modified copy in your build directory.
- *
- * The build directory is usually `builds/<system>`, and contains
- * system-specific files that are always included first when building the
- * library.
- *
- */
-
-#ifndef FTCONFIG_H_
-#define FTCONFIG_H_
-
-#include <ft2build.h>
-#include FT_CONFIG_OPTIONS_H
-#include FT_CONFIG_STANDARD_LIBRARY_H
-
-#define HAVE_UNISTD_H 1
-#define HAVE_FCNTL_H 1
-
-#include <freetype/config/integer-types.h>
-#include <freetype/config/public-macros.h>
-#include <freetype/config/mac-support.h>
-
-#endif /* FTCONFIG_H_ */
-
-
-/* END */
diff --git a/build-modular/third_party/freetype/include/freetype/config/ftoption.h b/build-modular/third_party/freetype/include/freetype/config/ftoption.h
deleted file mode 100644
index eb4e32d80..000000000
--- a/build-modular/third_party/freetype/include/freetype/config/ftoption.h
+++ /dev/null
@@ -1,1030 +0,0 @@
-/****************************************************************************
- *
- * ftoption.h
- *
- * User-selectable configuration macros (specification only).
- *
- * Copyright (C) 1996-2024 by
- * David Turner, Robert Wilhelm, and Werner Lemberg.
- *
- * This file is part of the FreeType project, and may only be used,
- * modified, and distributed under the terms of the FreeType project
- * license, LICENSE.TXT. By continuing to use, modify, or distribute
- * this file you indicate that you have read the license and
- * understand and accept it fully.
- *
- */
-
-
-#ifndef FTOPTION_H_
-#define FTOPTION_H_
-
-
-#include <ft2build.h>
-
-
-FT_BEGIN_HEADER
-
- /**************************************************************************
- *
- * USER-SELECTABLE CONFIGURATION MACROS
- *
- * This file contains the default configuration macro definitions for a
- * standard build of the FreeType library. There are three ways to use
- * this file to build project-specific versions of the library:
- *
- * - You can modify this file by hand, but this is not recommended in
- * cases where you would like to build several versions of the library
- * from a single source directory.
- *
- * - You can put a copy of this file in your build directory, more
- * precisely in `$BUILD/freetype/config/ftoption.h`, where `$BUILD` is
- * the name of a directory that is included _before_ the FreeType include
- * path during compilation.
- *
- * The default FreeType Makefiles use the build directory
- * `builds/<system>` by default, but you can easily change that for your
- * own projects.
- *
- * - Copy the file <ft2build.h> to `$BUILD/ft2build.h` and modify it
- * slightly to pre-define the macro `FT_CONFIG_OPTIONS_H` used to locate
- * this file during the build. For example,
- *
- * ```
- * #define FT_CONFIG_OPTIONS_H <myftoptions.h>
- * #include <freetype/config/ftheader.h>
- * ```
- *
- * will use `$BUILD/myftoptions.h` instead of this file for macro
- * definitions.
- *
- * Note also that you can similarly pre-define the macro
- * `FT_CONFIG_MODULES_H` used to locate the file listing of the modules
- * that are statically linked to the library at compile time. By
- * default, this file is `<freetype/config/ftmodule.h>`.
- *
- * We highly recommend using the third method whenever possible.
- *
- */
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** G E N E R A L F R E E T Y P E 2 C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
-
- /*#************************************************************************
- *
- * If you enable this configuration option, FreeType recognizes an
- * environment variable called `FREETYPE_PROPERTIES`, which can be used to
- * control the various font drivers and modules. The controllable
- * properties are listed in the section @properties.
- *
- * You have to undefine this configuration option on platforms that lack
- * the concept of environment variables (and thus don't have the `getenv`
- * function), for example Windows CE.
- *
- * `FREETYPE_PROPERTIES` has the following syntax form (broken here into
- * multiple lines for better readability).
- *
- * ```
- * <optional whitespace>
- * <module-name1> ':'
- * <property-name1> '=' <property-value1>
- * <whitespace>
- * <module-name2> ':'
- * <property-name2> '=' <property-value2>
- * ...
- * ```
- *
- * Example:
- *
- * ```
- * FREETYPE_PROPERTIES=truetype:interpreter-version=35 \
- * cff:no-stem-darkening=1
- * ```
- *
- */
-#define FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES
-
-
- /**************************************************************************
- *
- * Uncomment the line below if you want to activate LCD rendering
- * technology similar to ClearType in this build of the library. This
- * technology triples the resolution in the direction color subpixels. To
- * mitigate color fringes inherent to this technology, you also need to
- * explicitly set up LCD filtering.
- *
- * When this macro is not defined, FreeType offers alternative LCD
- * rendering technology that produces excellent output.
- */
-/* #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING */
-
-
- /**************************************************************************
- *
- * Many compilers provide a non-ANSI 64-bit data type that can be used by
- * FreeType to speed up some computations. However, this will create some
- * problems when compiling the library in strict ANSI mode.
- *
- * For this reason, the use of 64-bit integers is normally disabled when
- * the `__STDC__` macro is defined. You can however disable this by
- * defining the macro `FT_CONFIG_OPTION_FORCE_INT64` here.
- *
- * For most compilers, this will only create compilation warnings when
- * building the library.
- *
- * ObNote: The compiler-specific 64-bit integers are detected in the
- * file `ftconfig.h` either statically or through the `configure`
- * script on supported platforms.
- */
-#undef FT_CONFIG_OPTION_FORCE_INT64
-
-
- /**************************************************************************
- *
- * If this macro is defined, do not try to use an assembler version of
- * performance-critical functions (e.g., @FT_MulFix). You should only do
- * that to verify that the assembler function works properly, or to execute
- * benchmark tests of the various implementations.
- */
-/* #define FT_CONFIG_OPTION_NO_ASSEMBLER */
-
-
- /**************************************************************************
- *
- * If this macro is defined, try to use an inlined assembler version of the
- * @FT_MulFix function, which is a 'hotspot' when loading and hinting
- * glyphs, and which should be executed as fast as possible.
- *
- * Note that if your compiler or CPU is not supported, this will default to
- * the standard and portable implementation found in `ftcalc.c`.
- */
-#define FT_CONFIG_OPTION_INLINE_MULFIX
-
-
- /**************************************************************************
- *
- * LZW-compressed file support.
- *
- * FreeType now handles font files that have been compressed with the
- * `compress` program. This is mostly used to parse many of the PCF
- * files that come with various X11 distributions. The implementation
- * uses NetBSD's `zopen` to partially uncompress the file on the fly (see
- * `src/lzw/ftgzip.c`).
- *
- * Define this macro if you want to enable this 'feature'.
- */
-#define FT_CONFIG_OPTION_USE_LZW
-
-
- /**************************************************************************
- *
- * Gzip-compressed file support.
- *
- * FreeType now handles font files that have been compressed with the
- * `gzip` program. This is mostly used to parse many of the PCF files
- * that come with XFree86. The implementation uses 'zlib' to partially
- * uncompress the file on the fly (see `src/gzip/ftgzip.c`).
- *
- * Define this macro if you want to enable this 'feature'. See also the
- * macro `FT_CONFIG_OPTION_SYSTEM_ZLIB` below.
- */
-#define FT_CONFIG_OPTION_USE_ZLIB
-
-
- /**************************************************************************
- *
- * ZLib library selection
- *
- * This macro is only used when `FT_CONFIG_OPTION_USE_ZLIB` is defined.
- * It allows FreeType's 'ftgzip' component to link to the system's
- * installation of the ZLib library. This is useful on systems like
- * Unix or VMS where it generally is already available.
- *
- * If you let it undefined, the component will use its own copy of the
- * zlib sources instead. These have been modified to be included
- * directly within the component and **not** export external function
- * names. This allows you to link any program with FreeType _and_ ZLib
- * without linking conflicts.
- *
- * Do not `#undef` this macro here since the build system might define
- * it for certain configurations only.
- *
- * If you use a build system like cmake or the `configure` script,
- * options set by those programs have precedence, overwriting the value
- * here with the configured one.
- *
- * If you use the GNU make build system directly (that is, without the
- * `configure` script) and you define this macro, you also have to pass
- * `SYSTEM_ZLIB=yes` as an argument to make.
- */
-/* #define FT_CONFIG_OPTION_SYSTEM_ZLIB */
-
-
- /**************************************************************************
- *
- * Bzip2-compressed file support.
- *
- * FreeType now handles font files that have been compressed with the
- * `bzip2` program. This is mostly used to parse many of the PCF files
- * that come with XFree86. The implementation uses `libbz2` to partially
- * uncompress the file on the fly (see `src/bzip2/ftbzip2.c`). Contrary
- * to gzip, bzip2 currently is not included and need to use the system
- * available bzip2 implementation.
- *
- * Define this macro if you want to enable this 'feature'.
- *
- * If you use a build system like cmake or the `configure` script,
- * options set by those programs have precedence, overwriting the value
- * here with the configured one.
- */
-/* #define FT_CONFIG_OPTION_USE_BZIP2 */
-
-
- /**************************************************************************
- *
- * Define to disable the use of file stream functions and types, `FILE`,
- * `fopen`, etc. Enables the use of smaller system libraries on embedded
- * systems that have multiple system libraries, some with or without file
- * stream support, in the cases where file stream support is not necessary
- * such as memory loading of font files.
- */
-/* #define FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */
-
-
- /**************************************************************************
- *
- * PNG bitmap support.
- *
- * FreeType now handles loading color bitmap glyphs in the PNG format.
- * This requires help from the external libpng library. Uncompressed
- * color bitmaps do not need any external libraries and will be supported
- * regardless of this configuration.
- *
- * Define this macro if you want to enable this 'feature'.
- *
- * If you use a build system like cmake or the `configure` script,
- * options set by those programs have precedence, overwriting the value
- * here with the configured one.
- */
-/* #define FT_CONFIG_OPTION_USE_PNG */
-
-
- /**************************************************************************
- *
- * HarfBuzz support.
- *
- * FreeType uses the HarfBuzz library to improve auto-hinting of OpenType
- * fonts. If available, many glyphs not directly addressable by a font's
- * character map will be hinted also.
- *
- * Define this macro if you want to enable this 'feature'.
- *
- * If you use a build system like cmake or the `configure` script,
- * options set by those programs have precedence, overwriting the value
- * here with the configured one.
- */
-/* #define FT_CONFIG_OPTION_USE_HARFBUZZ */
-
-
- /**************************************************************************
- *
- * Brotli support.
- *
- * FreeType uses the Brotli library to provide support for decompressing
- * WOFF2 streams.
- *
- * Define this macro if you want to enable this 'feature'.
- *
- * If you use a build system like cmake or the `configure` script,
- * options set by those programs have precedence, overwriting the value
- * here with the configured one.
- */
-/* #define FT_CONFIG_OPTION_USE_BROTLI */
-
-
- /**************************************************************************
- *
- * Glyph Postscript Names handling
- *
- * By default, FreeType 2 is compiled with the 'psnames' module. This
- * module is in charge of converting a glyph name string into a Unicode
- * value, or return a Macintosh standard glyph name for the use with the
- * TrueType 'post' table.
- *
- * Undefine this macro if you do not want 'psnames' compiled in your
- * build of FreeType. This has the following effects:
- *
- * - The TrueType driver will provide its own set of glyph names, if you
- * build it to support postscript names in the TrueType 'post' table,
- * but will not synthesize a missing Unicode charmap.
- *
- * - The Type~1 driver will not be able to synthesize a Unicode charmap
- * out of the glyphs found in the fonts.
- *
- * You would normally undefine this configuration macro when building a
- * version of FreeType that doesn't contain a Type~1 or CFF driver.
- */
-#define FT_CONFIG_OPTION_POSTSCRIPT_NAMES
-
-
- /**************************************************************************
- *
- * Postscript Names to Unicode Values support
- *
- * By default, FreeType~2 is built with the 'psnames' module compiled in.
- * Among other things, the module is used to convert a glyph name into a
- * Unicode value. This is especially useful in order to synthesize on
- * the fly a Unicode charmap from the CFF/Type~1 driver through a big
- * table named the 'Adobe Glyph List' (AGL).
- *
- * Undefine this macro if you do not want the Adobe Glyph List compiled
- * in your 'psnames' module. The Type~1 driver will not be able to
- * synthesize a Unicode charmap out of the glyphs found in the fonts.
- */
-#define FT_CONFIG_OPTION_ADOBE_GLYPH_LIST
-
-
- /**************************************************************************
- *
- * Support for Mac fonts
- *
- * Define this macro if you want support for outline fonts in Mac format
- * (mac dfont, mac resource, macbinary containing a mac resource) on
- * non-Mac platforms.
- *
- * Note that the 'FOND' resource isn't checked.
- */
-#define FT_CONFIG_OPTION_MAC_FONTS
-
-
- /**************************************************************************
- *
- * Guessing methods to access embedded resource forks
- *
- * Enable extra Mac fonts support on non-Mac platforms (e.g., GNU/Linux).
- *
- * Resource forks which include fonts data are stored sometimes in
- * locations which users or developers don't expected. In some cases,
- * resource forks start with some offset from the head of a file. In
- * other cases, the actual resource fork is stored in file different from
- * what the user specifies. If this option is activated, FreeType tries
- * to guess whether such offsets or different file names must be used.
- *
- * Note that normal, direct access of resource forks is controlled via
- * the `FT_CONFIG_OPTION_MAC_FONTS` option.
- */
-#ifdef FT_CONFIG_OPTION_MAC_FONTS
-#define FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK
-#endif
-
-
- /**************************************************************************
- *
- * Allow the use of `FT_Incremental_Interface` to load typefaces that
- * contain no glyph data, but supply it via a callback function. This is
- * required by clients supporting document formats which supply font data
- * incrementally as the document is parsed, such as the Ghostscript
- * interpreter for the PostScript language.
- */
-#define FT_CONFIG_OPTION_INCREMENTAL
-
-
- /**************************************************************************
- *
- * The size in bytes of the render pool used by the scan-line converter to
- * do all of its work.
- */
-#define FT_RENDER_POOL_SIZE 16384L
-
-
- /**************************************************************************
- *
- * FT_MAX_MODULES
- *
- * The maximum number of modules that can be registered in a single
- * FreeType library object. 32~is the default.
- */
-#define FT_MAX_MODULES 32
-
-
- /**************************************************************************
- *
- * Debug level
- *
- * FreeType can be compiled in debug or trace mode. In debug mode,
- * errors are reported through the 'ftdebug' component. In trace mode,
- * additional messages are sent to the standard output during execution.
- *
- * Define `FT_DEBUG_LEVEL_ERROR` to build the library in debug mode.
- * Define `FT_DEBUG_LEVEL_TRACE` to build it in trace mode.
- *
- * Don't define any of these macros to compile in 'release' mode!
- *
- * Do not `#undef` these macros here since the build system might define
- * them for certain configurations only.
- */
-/* #define FT_DEBUG_LEVEL_ERROR */
-/* #define FT_DEBUG_LEVEL_TRACE */
-
-
- /**************************************************************************
- *
- * Logging
- *
- * Compiling FreeType in debug or trace mode makes FreeType write error
- * and trace log messages to `stderr`. Enabling this macro
- * automatically forces the `FT_DEBUG_LEVEL_ERROR` and
- * `FT_DEBUG_LEVEL_TRACE` macros and allows FreeType to write error and
- * trace log messages to a file instead of `stderr`. For writing logs
- * to a file, FreeType uses an the external `dlg` library (the source
- * code is in `src/dlg`).
- *
- * This option needs a C99 compiler.
- */
-/* #define FT_DEBUG_LOGGING */
-
-
- /**************************************************************************
- *
- * Autofitter debugging
- *
- * If `FT_DEBUG_AUTOFIT` is defined, FreeType provides some means to
- * control the autofitter behaviour for debugging purposes with global
- * boolean variables (consequently, you should **never** enable this
- * while compiling in 'release' mode):
- *
- * ```
- * af_debug_disable_horz_hints_
- * af_debug_disable_vert_hints_
- * af_debug_disable_blue_hints_
- * ```
- *
- * Additionally, the following functions provide dumps of various
- * internal autofit structures to stdout (using `printf`):
- *
- * ```
- * af_glyph_hints_dump_points
- * af_glyph_hints_dump_segments
- * af_glyph_hints_dump_edges
- * af_glyph_hints_get_num_segments
- * af_glyph_hints_get_segment_offset
- * ```
- *
- * As an argument, they use another global variable:
- *
- * ```
- * af_debug_hints_
- * ```
- *
- * Please have a look at the `ftgrid` demo program to see how those
- * variables and macros should be used.
- *
- * Do not `#undef` these macros here since the build system might define
- * them for certain configurations only.
- */
-/* #define FT_DEBUG_AUTOFIT */
-
-
- /**************************************************************************
- *
- * Memory Debugging
- *
- * FreeType now comes with an integrated memory debugger that is capable
- * of detecting simple errors like memory leaks or double deletes. To
- * compile it within your build of the library, you should define
- * `FT_DEBUG_MEMORY` here.
- *
- * Note that the memory debugger is only activated at runtime when when
- * the _environment_ variable `FT2_DEBUG_MEMORY` is defined also!
- *
- * Do not `#undef` this macro here since the build system might define it
- * for certain configurations only.
- */
-/* #define FT_DEBUG_MEMORY */
-
-
- /**************************************************************************
- *
- * Module errors
- *
- * If this macro is set (which is _not_ the default), the higher byte of
- * an error code gives the module in which the error has occurred, while
- * the lower byte is the real error code.
- *
- * Setting this macro makes sense for debugging purposes only, since it
- * would break source compatibility of certain programs that use
- * FreeType~2.
- *
- * More details can be found in the files `ftmoderr.h` and `fterrors.h`.
- */
-#undef FT_CONFIG_OPTION_USE_MODULE_ERRORS
-
-
- /**************************************************************************
- *
- * OpenType SVG Glyph Support
- *
- * Setting this macro enables support for OpenType SVG glyphs. By
- * default, FreeType can only fetch SVG documents. However, it can also
- * render them if external rendering hook functions are plugged in at
- * runtime.
- *
- * More details on the hooks can be found in file `otsvg.h`.
- */
-#define FT_CONFIG_OPTION_SVG
-
-
- /**************************************************************************
- *
- * Error Strings
- *
- * If this macro is set, `FT_Error_String` will return meaningful
- * descriptions. This is not enabled by default to reduce the overall
- * size of FreeType.
- *
- * More details can be found in the file `fterrors.h`.
- */
-/* #define FT_CONFIG_OPTION_ERROR_STRINGS */
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** S F N T D R I V E R C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_EMBEDDED_BITMAPS` if you want to support
- * embedded bitmaps in all formats using the 'sfnt' module (namely
- * TrueType~& OpenType).
- */
-#define TT_CONFIG_OPTION_EMBEDDED_BITMAPS
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_COLOR_LAYERS` if you want to support colored
- * outlines (from the 'COLR'/'CPAL' tables) in all formats using the 'sfnt'
- * module (namely TrueType~& OpenType).
- */
-#define TT_CONFIG_OPTION_COLOR_LAYERS
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_POSTSCRIPT_NAMES` if you want to be able to
- * load and enumerate Postscript names of glyphs in a TrueType or OpenType
- * file.
- *
- * Note that if you do not compile the 'psnames' module by undefining the
- * above `FT_CONFIG_OPTION_POSTSCRIPT_NAMES` macro, the 'sfnt' module will
- * contain additional code to read the PostScript name table from a font.
- *
- * (By default, the module uses 'psnames' to extract glyph names.)
- */
-#define TT_CONFIG_OPTION_POSTSCRIPT_NAMES
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_SFNT_NAMES` if your applications need to access
- * the internal name table in a SFNT-based format like TrueType or
- * OpenType. The name table contains various strings used to describe the
- * font, like family name, copyright, version, etc. It does not contain
- * any glyph name though.
- *
- * Accessing SFNT names is done through the functions declared in
- * `ftsnames.h`.
- */
-#define TT_CONFIG_OPTION_SFNT_NAMES
-
-
- /**************************************************************************
- *
- * TrueType CMap support
- *
- * Here you can fine-tune which TrueType CMap table format shall be
- * supported.
- */
-#define TT_CONFIG_CMAP_FORMAT_0
-#define TT_CONFIG_CMAP_FORMAT_2
-#define TT_CONFIG_CMAP_FORMAT_4
-#define TT_CONFIG_CMAP_FORMAT_6
-#define TT_CONFIG_CMAP_FORMAT_8
-#define TT_CONFIG_CMAP_FORMAT_10
-#define TT_CONFIG_CMAP_FORMAT_12
-#define TT_CONFIG_CMAP_FORMAT_13
-#define TT_CONFIG_CMAP_FORMAT_14
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** T R U E T Y P E D R I V E R C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_BYTECODE_INTERPRETER` if you want to compile a
- * bytecode interpreter in the TrueType driver.
- *
- * By undefining this, you will only compile the code necessary to load
- * TrueType glyphs without hinting.
- *
- * Do not `#undef` this macro here, since the build system might define it
- * for certain configurations only.
- */
-#define TT_CONFIG_OPTION_BYTECODE_INTERPRETER
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_SUBPIXEL_HINTING` if you want to compile
- * subpixel hinting support into the TrueType driver. This modifies the
- * TrueType hinting mechanism when anything but `FT_RENDER_MODE_MONO` is
- * requested.
- *
- * In particular, it modifies the bytecode interpreter to interpret (or
- * not) instructions in a certain way so that all TrueType fonts look like
- * they do in a Windows ClearType (DirectWrite) environment. See [1] for a
- * technical overview on what this means. See `ttinterp.h` for more
- * details on this option.
- *
- * The new default mode focuses on applying a minimal set of rules to all
- * fonts indiscriminately so that modern and web fonts render well while
- * legacy fonts render okay. The corresponding interpreter version is v40.
- * The so-called Infinality mode (v38) is no longer available in FreeType.
- *
- * By undefining these, you get rendering behavior like on Windows without
- * ClearType, i.e., Windows XP without ClearType enabled and Win9x
- * (interpreter version v35). Or not, depending on how much hinting blood
- * and testing tears the font designer put into a given font. If you
- * define one or both subpixel hinting options, you can switch between
- * between v35 and the ones you define (using `FT_Property_Set`).
- *
- * This option requires `TT_CONFIG_OPTION_BYTECODE_INTERPRETER` to be
- * defined.
- *
- * [1]
- * https://www.microsoft.com/typography/cleartype/truetypecleartype.aspx
- */
-#define TT_CONFIG_OPTION_SUBPIXEL_HINTING
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED` to compile the
- * TrueType glyph loader to use Apple's definition of how to handle
- * component offsets in composite glyphs.
- *
- * Apple and MS disagree on the default behavior of component offsets in
- * composites. Apple says that they should be scaled by the scaling
- * factors in the transformation matrix (roughly, it's more complex) while
- * MS says they should not. OpenType defines two bits in the composite
- * flags array which can be used to disambiguate, but old fonts will not
- * have them.
- *
- * https://www.microsoft.com/typography/otspec/glyf.htm
- * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
- */
-#undef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_GX_VAR_SUPPORT` if you want to include support
- * for Apple's distortable font technology ('fvar', 'gvar', 'cvar', and
- * 'avar' tables). Tagged 'Font Variations', this is now part of OpenType
- * also. This has many similarities to Type~1 Multiple Masters support.
- */
-#define TT_CONFIG_OPTION_GX_VAR_SUPPORT
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_NO_BORING_EXPANSION` if you want to exclude
- * support for 'boring' OpenType specification expansions.
- *
- * https://github.com/harfbuzz/boring-expansion-spec
- *
- * Right now, the following features are covered:
- *
- * - 'avar' version 2.0
- *
- * Most likely, this is a temporary configuration option to be removed in
- * the near future, since it is assumed that eventually those features are
- * added to the OpenType standard.
- */
-/* #define TT_CONFIG_OPTION_NO_BORING_EXPANSION */
-
-
- /**************************************************************************
- *
- * Define `TT_CONFIG_OPTION_BDF` if you want to include support for an
- * embedded 'BDF~' table within SFNT-based bitmap formats.
- */
-#define TT_CONFIG_OPTION_BDF
-
-
- /**************************************************************************
- *
- * Option `TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES` controls the maximum
- * number of bytecode instructions executed for a single run of the
- * bytecode interpreter, needed to prevent infinite loops. You don't want
- * to change this except for very special situations (e.g., making a
- * library fuzzer spend less time to handle broken fonts).
- *
- * It is not expected that this value is ever modified by a configuring
- * script; instead, it gets surrounded with `#ifndef ... #endif` so that
- * the value can be set as a preprocessor option on the compiler's command
- * line.
- */
-#ifndef TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES
-#define TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES 1000000L
-#endif
-
-
- /**************************************************************************
- *
- * Option `TT_CONFIG_OPTION_GPOS_KERNING` enables a basic GPOS kerning
- * implementation (for TrueType fonts only). With this defined, FreeType
- * is able to get kerning pair data from the GPOS 'kern' feature as well as
- * legacy 'kern' tables; without this defined, FreeType will only be able
- * to use legacy 'kern' tables.
- *
- * Note that FreeType does not support more advanced GPOS layout features;
- * even the 'kern' feature implemented here doesn't handle more
- * sophisticated kerning variants. Use a higher-level library like
- * HarfBuzz instead for that.
- */
-/* #define TT_CONFIG_OPTION_GPOS_KERNING */
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** T Y P E 1 D R I V E R C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
-
- /**************************************************************************
- *
- * `T1_MAX_DICT_DEPTH` is the maximum depth of nest dictionaries and arrays
- * in the Type~1 stream (see `t1load.c`). A minimum of~4 is required.
- */
-#define T1_MAX_DICT_DEPTH 5
-
-
- /**************************************************************************
- *
- * `T1_MAX_SUBRS_CALLS` details the maximum number of nested sub-routine
- * calls during glyph loading.
- */
-#define T1_MAX_SUBRS_CALLS 16
-
-
- /**************************************************************************
- *
- * `T1_MAX_CHARSTRING_OPERANDS` is the charstring stack's capacity. A
- * minimum of~16 is required.
- *
- * The Chinese font 'MingTiEG-Medium' (covering the CNS 11643 character
- * set) needs 256.
- */
-#define T1_MAX_CHARSTRINGS_OPERANDS 256
-
-
- /**************************************************************************
- *
- * Define this configuration macro if you want to prevent the compilation
- * of the 't1afm' module, which is in charge of reading Type~1 AFM files
- * into an existing face. Note that if set, the Type~1 driver will be
- * unable to produce kerning distances.
- */
-#undef T1_CONFIG_OPTION_NO_AFM
-
-
- /**************************************************************************
- *
- * Define this configuration macro if you want to prevent the compilation
- * of the Multiple Masters font support in the Type~1 driver.
- */
-#undef T1_CONFIG_OPTION_NO_MM_SUPPORT
-
-
- /**************************************************************************
- *
- * `T1_CONFIG_OPTION_OLD_ENGINE` controls whether the pre-Adobe Type~1
- * engine gets compiled into FreeType. If defined, it is possible to
- * switch between the two engines using the `hinting-engine` property of
- * the 'type1' driver module.
- */
-/* #define T1_CONFIG_OPTION_OLD_ENGINE */
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** C F F D R I V E R C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
-
- /**************************************************************************
- *
- * Using `CFF_CONFIG_OPTION_DARKENING_PARAMETER_{X,Y}{1,2,3,4}` it is
- * possible to set up the default values of the four control points that
- * define the stem darkening behaviour of the (new) CFF engine. For more
- * details please read the documentation of the `darkening-parameters`
- * property (file `ftdriver.h`), which allows the control at run-time.
- *
- * Do **not** undefine these macros!
- */
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 500
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 400
-
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 1000
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 275
-
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 1667
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 275
-
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 2333
-#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 0
-
-
- /**************************************************************************
- *
- * `CFF_CONFIG_OPTION_OLD_ENGINE` controls whether the pre-Adobe CFF engine
- * gets compiled into FreeType. If defined, it is possible to switch
- * between the two engines using the `hinting-engine` property of the 'cff'
- * driver module.
- */
-/* #define CFF_CONFIG_OPTION_OLD_ENGINE */
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** P C F D R I V E R C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
-
- /**************************************************************************
- *
- * There are many PCF fonts just called 'Fixed' which look completely
- * different, and which have nothing to do with each other. When selecting
- * 'Fixed' in KDE or Gnome one gets results that appear rather random, the
- * style changes often if one changes the size and one cannot select some
- * fonts at all. This option makes the 'pcf' module prepend the foundry
- * name (plus a space) to the family name.
- *
- * We also check whether we have 'wide' characters; all put together, we
- * get family names like 'Sony Fixed' or 'Misc Fixed Wide'.
- *
- * If this option is activated, it can be controlled with the
- * `no-long-family-names` property of the 'pcf' driver module.
- */
-/* #define PCF_CONFIG_OPTION_LONG_FAMILY_NAMES */
-
-
- /*************************************************************************/
- /*************************************************************************/
- /**** ****/
- /**** A U T O F I T M O D U L E C O N F I G U R A T I O N ****/
- /**** ****/
- /*************************************************************************/
- /*************************************************************************/
-
-
- /**************************************************************************
- *
- * Compile 'autofit' module with CJK (Chinese, Japanese, Korean) script
- * support.
- */
-#define AF_CONFIG_OPTION_CJK
-
-
- /**************************************************************************
- *
- * Compile 'autofit' module with fallback Indic script support, covering
- * some scripts that the 'latin' submodule of the 'autofit' module doesn't
- * (yet) handle. Currently, this needs option `AF_CONFIG_OPTION_CJK`.
- */
-#ifdef AF_CONFIG_OPTION_CJK
-#define AF_CONFIG_OPTION_INDIC
-#endif
-
-
- /**************************************************************************
- *
- * Use TrueType-like size metrics for 'light' auto-hinting.
- *
- * It is strongly recommended to avoid this option, which exists only to
- * help some legacy applications retain its appearance and behaviour with
- * respect to auto-hinted TrueType fonts.
- *
- * The very reason this option exists at all are GNU/Linux distributions
- * like Fedora that did not un-patch the following change (which was
- * present in FreeType between versions 2.4.6 and 2.7.1, inclusive).
- *
- * ```
- * 2011-07-16 Steven Chu <[email protected]>
- *
- * [truetype] Fix metrics on size request for scalable fonts.
- * ```
- *
- * This problematic commit is now reverted (more or less).
- */
-/* #define AF_CONFIG_OPTION_TT_SIZE_METRICS */
-
- /* */
-
-
- /*
- * This macro is obsolete. Support has been removed in FreeType version
- * 2.5.
- */
-/* #define FT_CONFIG_OPTION_OLD_INTERNALS */
-
-
- /*
- * The next two macros are defined if native TrueType hinting is
- * requested by the definitions above. Don't change this.
- */
-#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
-#define TT_USE_BYTECODE_INTERPRETER
-#ifdef TT_CONFIG_OPTION_SUBPIXEL_HINTING
-#define TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL
-#endif
-#endif
-
-
- /*
- * The TT_SUPPORT_COLRV1 macro is defined to indicate to clients that this
- * version of FreeType has support for 'COLR' v1 API. This definition is
- * useful to FreeType clients that want to build in support for 'COLR' v1
- * depending on a tip-of-tree checkout before it is officially released in
- * FreeType, and while the feature cannot yet be tested against using
- * version macros. Don't change this macro. This may be removed once the
- * feature is in a FreeType release version and version macros can be used
- * to test for availability.
- */
-#ifdef TT_CONFIG_OPTION_COLOR_LAYERS
-#define TT_SUPPORT_COLRV1
-#endif
-
-
- /*
- * Check CFF darkening parameters. The checks are the same as in function
- * `cff_property_set` in file `cffdrivr.c`.
- */
-#if CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 < 0 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 < 0 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 < 0 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 < 0 || \
- \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 < 0 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 < 0 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 < 0 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 < 0 || \
- \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 > \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 > \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 > \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 || \
- \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 > 500 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 > 500 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 > 500 || \
- CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 > 500
-#error "Invalid CFF darkening parameters!"
-#endif
-
-
-FT_END_HEADER
-
-#endif /* FTOPTION_H_ */
-
-
-/* END */
diff --git a/cmake/ESEngineConfig.cmake b/cmake/ESEngineConfig.cmake
index a61539f1c..f99ecbbc5 100644
--- a/cmake/ESEngineConfig.cmake
+++ b/cmake/ESEngineConfig.cmake
@@ -105,7 +105,6 @@ message(STATUS "ESEngine Configuration:")
message(STATUS " Build Type: ${CMAKE_BUILD_TYPE}")
message(STATUS " Web Build: ${ES_BUILD_WEB}")
message(STATUS " WxGame Build: ${ES_BUILD_WXGAME}")
-message(STATUS " Build Examples: ${ES_BUILD_EXAMPLES}")
message(STATUS " Build Tests: ${ES_BUILD_TESTS}")
if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
message(STATUS " Scripting Enabled: YES (QuickJS)")
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmake
index 9b69e5cb7..eb53c0cf0 100644
--- a/cmake/Emscripten.cmake
+++ b/cmake/Emscripten.cmake
@@ -150,7 +150,7 @@ endfunction()
# SDK-specific link flags (library only, no app entry)
set(ES_EMSCRIPTEN_SDK_LINK_FLAGS
--bind
- --emit-tsd esengine.d.ts
+ # --emit-tsd esengine.d.ts # Temporarily disabled due to binding mismatch
-sWASM=1
-sUSE_WEBGL2=1
-sFULL_ES3=1
@@ -159,7 +159,7 @@ set(ES_EMSCRIPTEN_SDK_LINK_FLAGS
-sEXPORT_ES6=1
-sMODULARIZE=1
"-sEXPORT_NAME='ESEngineModule'"
- "-sEXPORTED_FUNCTIONS=['_malloc','_free','_es_sdk_init','_es_sdk_version']"
+ "-sEXPORTED_FUNCTIONS=['_malloc','_free']"
"-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32']"
-O3
--closure=1
@@ -176,7 +176,7 @@ set(ES_EMSCRIPTEN_SINGLE_FILE_FLAGS
-sNO_EXIT_RUNTIME=1
-sMODULARIZE=1
"-sEXPORT_NAME='ESEngineModule'"
- "-sEXPORTED_FUNCTIONS=['_malloc','_free','_es_sdk_init','_es_sdk_version']"
+ "-sEXPORTED_FUNCTIONS=['_malloc','_free']"
"-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32']"
-O3
-flto
diff --git a/cmake/QuickJSMinGW.cmake b/cmake/QuickJSMinGW.cmake
deleted file mode 100644
index e6a66cd88..000000000
--- a/cmake/QuickJSMinGW.cmake
+++ /dev/null
@@ -1,37 +0,0 @@
-# =============================================================================
-# QuickJS Build Configuration Helper
-# =============================================================================
-# QuickJS requires GCC/MinGW on Windows, cannot compile with MSVC
-
-if(WIN32 AND MSVC)
- message(FATAL_ERROR "
-========================================================================
-QuickJS requires MinGW-w64 (GCC) on Windows, cannot use MSVC.
-
-Please choose one of the following options:
-
-Option 1 (Recommended): Use MinGW-w64 for the entire project
- 1. Install MSYS2: https://www.msys2.org/
- 2. In MSYS2 terminal: pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-cmake
- 3. Use MSYS2 MinGW terminal to build:
- cmake -B build -G \"MinGW Makefiles\"
- cmake --build build
-
-Option 2: Use MSYS2 UCRT64 environment (Modern Windows API)
- 1. Install MSYS2
- 2. In MSYS2 terminal: pacman -S mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake
- 3. Use UCRT64 terminal to build
-
-Option 3: Mixed toolchain (Advanced)
- Use ExternalProject to build QuickJS with MinGW separately
- (Not currently implemented)
-
-For now, please rebuild using MinGW-w64 instead of MSVC.
-========================================================================
-")
-endif()
-
-# GCC/MinGW-specific settings for QuickJS
-if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
- message(STATUS "QuickJS: Using GCC/MinGW compiler")
-endif()
diff --git a/docs/astro/src/content/docs/getting-started/installation.mdx b/docs/astro/src/content/docs/getting-started/installation.mdx
index 383ecd53a..72ab2b0ab 100644
--- a/docs/astro/src/content/docs/getting-started/installation.mdx
+++ b/docs/astro/src/content/docs/getting-started/installation.mdx
@@ -3,22 +3,86 @@ title: Installation
description: Set up your development environment for ESEngine
---
-import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';
+import { Tabs, TabItem, Steps, Aside } from '@astrojs/starlight/components';
This guide will help you set up your development environment for building games with ESEngine.
-## Prerequisites
+## Quick Start (SDK Only)
-Before you begin, ensure you have the following installed:
+For most users, just install the TypeScript SDK:
+
+```bash
+npm install esengine
+```
+
+You'll also need the WASM files. Download them from the [releases page](https://github.com/esengine/microes/releases) or build them yourself (see below).
+
+<Aside type="tip">
+ If you're just getting started, skip to [Quick Start](/microes/getting-started/quick-start/) after installing the SDK.
+</Aside>
+
+## Project Setup
+
+<Steps>
+
+1. **Create your project**
+
+ ```bash
+ mkdir my-game
+ cd my-game
+ npm init -y
+ ```
+
+2. **Install dependencies**
+
+ ```bash
+ npm install esengine
+ npm install -D esbuild typescript
+ ```
+
+3. **Create tsconfig.json**
+
+ ```json
+ {
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true
+ },
+ "include": ["src"]
+ }
+ ```
+
+4. **Add build scripts to package.json**
+
+ ```json
+ {
+ "type": "module",
+ "scripts": {
+ "build": "esbuild src/main.ts --bundle --format=esm --outfile=build/main.js",
+ "dev": "esbuild src/main.ts --bundle --format=esm --outfile=build/main.js --watch"
+ }
+ }
+ ```
+
+</Steps>
+
+## Building WASM (Advanced)
+
+If you need to build the C++ WASM backend yourself:
+
+### Prerequisites
| Tool | Version | Purpose |
|------|---------|---------|
| CMake | 3.16+ | Build system |
| C++ Compiler | C++17 support | GCC 8+, Clang 7+, MSVC 2019+ |
| Emscripten | 3.1+ | WebAssembly compilation |
-| Git | Any | Clone the repository |
+| Node.js | 18+ | SDK build |
-## Installing Emscripten
+### Installing Emscripten
<Tabs>
<TabItem label="Linux/macOS">
@@ -58,7 +122,7 @@ emcc --version
# emcc (Emscripten gcc/clang-like replacement) 3.x.x
```
-## Getting ESEngine
+### Building
<Steps>
@@ -66,62 +130,37 @@ emcc --version
```bash
git clone https://github.com/esengine/microes.git
- cd esengine
+ cd microes
```
-2. **Initialize submodules** (if any)
+2. **Build WASM**
```bash
- git submodule update --init --recursive
+ # Web build
+ emcmake cmake -B build_web -DES_BUILD_WEB=ON
+ cmake --build build_web
+
+ # WeChat MiniGame build
+ emcmake cmake -B build_wxgame -DES_BUILD_WXGAME=ON
+ cmake --build build_wxgame
```
-3. **Verify the structure**
+3. **Build SDK**
- ```
- esengine/
- ├── src/esengine/ # Engine source
- ├── include/ # Public headers
- ├── third_party/ # Dependencies (GLM)
- ├── examples/ # Example projects
- └── CMakeLists.txt # Build configuration
+ ```bash
+ cd sdk
+ npm install
+ npm run build
```
</Steps>
-## Building
-
-### Native Build (for testing)
-
-```bash
-cmake -B build -DCMAKE_BUILD_TYPE=Debug
-cmake --build build
-```
-
-### Web Build
-
-```bash
-# Ensure Emscripten is activated
-source /path/to/emsdk/emsdk_env.sh # Linux/macOS
-# or: .\emsdk_env.bat # Windows
-
-emcmake cmake -B build_web -DES_BUILD_WEB=ON
-cmake --build build_web
-```
-
-### WeChat MiniGame Build
-
-```bash
-emcmake cmake -B build_wxgame -DES_BUILD_WXGAME=ON
-cmake --build build_wxgame
-```
-
-## CMake Options
+### CMake Options
| Option | Default | Description |
|--------|---------|-------------|
| `ES_BUILD_WEB` | OFF | Build for web browsers |
| `ES_BUILD_WXGAME` | OFF | Build for WeChat MiniGames |
-| `ES_BUILD_EXAMPLES` | ON | Build example projects |
| `ES_BUILD_TESTS` | OFF | Build unit tests |
## IDE Setup
@@ -129,21 +168,12 @@ cmake --build build_wxgame
### Visual Studio Code
Recommended extensions:
+- ESLint
+- TypeScript
+
+For C++ development:
- C/C++ (Microsoft)
- CMake Tools
-- clangd (for better intellisense)
-
-`.vscode/settings.json`:
-```json
-{
- "cmake.configureArgs": ["-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
- "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"
-}
-```
-
-### CLion
-
-CLion works out of the box with CMake projects. Open the `esengine` folder and it will auto-detect the CMakeLists.txt.
## Next Steps
diff --git a/docs/astro/src/content/docs/getting-started/introduction.mdx b/docs/astro/src/content/docs/getting-started/introduction.mdx
index 6723d03d6..8f2c04a0b 100644
--- a/docs/astro/src/content/docs/getting-started/introduction.mdx
+++ b/docs/astro/src/content/docs/getting-started/introduction.mdx
@@ -3,25 +3,38 @@ title: Introduction
description: Learn what ESEngine is and why you might want to use it
---
-ESEngine is a lightweight, modern C++17 game engine designed specifically for **WebAssembly** deployment. It provides everything you need to build 2D games that run in web browsers and WeChat MiniGames.
+ESEngine is a lightweight 2D game engine with a **TypeScript SDK** powered by a **C++/WebAssembly** backend. Build games that run in web browsers and WeChat MiniGames with excellent performance.
## Why ESEngine?
-### Designed for the Web
+### TypeScript-First Development
-Unlike traditional game engines ported to WebAssembly, ESEngine was built from the ground up with web constraints in mind:
+Write your game logic in TypeScript with a modern, type-safe ECS API:
-- **Small binary size** - Optimized for fast initial load times
-- **No filesystem dependencies** - Works with browser storage APIs
-- **Touch-first input** - Mobile and desktop input unified
+```typescript
+import { createWebApp, defineSystem, Schedule, Commands, Query, Res, Time, LocalTransform, Sprite } from 'esengine';
+
+const app = createWebApp(Module);
-### Modern C++ Architecture
+app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(LocalTransform, Sprite)],
+ (time, query) => {
+ for (const [entity, transform, sprite] of query) {
+ transform.position.x = Math.sin(time.elapsed) * 100;
+ }
+ }
+));
+
+app.run();
+```
-ESEngine uses modern C++17 features and patterns:
+### High Performance C++ Backend
-- **Entity-Component-System (ECS)** - Data-oriented design inspired by [EnTT](https://github.com/skypjack/entt)
-- **RAII everywhere** - Automatic resource management
-- **Type-safe APIs** - Compile-time checks catch errors early
+The rendering and core ECS are implemented in C++ and compiled to WebAssembly:
+
+- **Small binary size** - Optimized for fast initial load times
+- **Native performance** - C++ rendering pipeline
+- **Type-safe bridge** - TypeScript types match C++ components
### WeChat MiniGame Support
@@ -38,31 +51,27 @@ ESEngine is ideal for:
- 2D games targeting web browsers
- WeChat MiniGames
- Projects requiring small download sizes
-- Developers comfortable with C++
+- TypeScript developers wanting ECS architecture
ESEngine may not be the best choice for:
-- 3D games (basic 3D support only)
+- 3D games (2D only)
- Desktop-only games (use a native engine)
-- Rapid prototyping (consider Unity/Godot)
## Architecture Overview
```
┌─────────────────────────────────────────────────────┐
-│ Application │
-│ (Your game code - inherits from Application) │
-├─────────────────────────────────────────────────────┤
-│ ECS │
-│ Registry │ Entity │ Component │ System │ View │
+│ Your Game (TypeScript) │
+│ Systems │ Components │ Queries │ Resources │
├─────────────────────────────────────────────────────┤
-│ Renderer │
-│ Shader │ Texture │ Buffer │ RenderCommand │
+│ ESEngine SDK │
+│ App │ World │ Commands │ defineSystem │
├─────────────────────────────────────────────────────┤
-│ Platform │
-│ Input │ Window │ FileSystem │ Timer │
+│ C++ WASM Backend │
+│ Registry │ Renderer │ Input │ ResourceManager │
├─────────────────────────────────────────────────────┤
-│ Emscripten / WebGL │
+│ Emscripten / WebGL │
└─────────────────────────────────────────────────────┘
```
diff --git a/docs/astro/src/content/docs/getting-started/quick-start.mdx b/docs/astro/src/content/docs/getting-started/quick-start.mdx
index 6985e0536..e2595082b 100644
--- a/docs/astro/src/content/docs/getting-started/quick-start.mdx
+++ b/docs/astro/src/content/docs/getting-started/quick-start.mdx
@@ -11,163 +11,186 @@ Let's create a simple game that displays a moving sprite. This will introduce yo
<Steps>
-1. **Create your game directory**
+1. **Create your project directory**
```bash
mkdir my-game
cd my-game
+ npm init -y
```
-2. **Create CMakeLists.txt**
+2. **Install dependencies**
- ```cmake
- cmake_minimum_required(VERSION 3.16)
- project(MyGame)
+ ```bash
+ npm install esengine
+ npm install -D esbuild typescript
+ ```
- # Find ESEngine (adjust path as needed)
- add_subdirectory(../esengine esengine)
+3. **Create src/main.ts**
+
+ ```typescript
+ import {
+ type ESEngineModule,
+ createWebApp,
+ defineSystem,
+ Schedule,
+ Commands,
+ Query,
+ Res,
+ Time,
+ LocalTransform,
+ Sprite,
+ Camera
+ } from 'esengine';
+
+ export async function main(Module: ESEngineModule): Promise<void> {
+ const app = createWebApp(Module);
+
+ // Startup system - runs once at the beginning
+ app.addSystemToSchedule(Schedule.Startup, defineSystem(
+ [Commands()],
+ (cmds) => {
+ // Create camera
+ cmds.spawn()
+ .insert(Camera, {
+ projectionType: 1,
+ orthoSize: 400,
+ isActive: true
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 10 }
+ });
+
+ // Create a sprite
+ cmds.spawn()
+ .insert(Sprite, {
+ color: { x: 1, y: 0.5, z: 0.2, w: 1 },
+ size: { x: 100, y: 100 }
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 0 }
+ });
+ }
+ ));
+
+ // Update system - runs every frame
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(LocalTransform, Sprite)],
+ (time, query) => {
+ for (const [entity, transform, sprite] of query) {
+ // Move sprite in a circle
+ transform.position.x = Math.sin(time.elapsed) * 100;
+ transform.position.y = Math.cos(time.elapsed) * 100;
+ }
+ }
+ ));
- # Create executable
- add_executable(MyGame src/main.cpp)
- target_link_libraries(MyGame PRIVATE esengine)
+ app.run();
+ }
```
-3. **Create src/main.cpp**
-
- ```cpp
- #include <esengine/ESEngine.hpp>
-
- using namespace esengine;
- using namespace esengine::ecs;
-
- // Components
- struct Position {
- float x, y;
- };
-
- struct Velocity {
- float vx, vy;
- };
-
- class MyGame : public Application {
- public:
- MyGame() : Application({.title = "My First Game", .width = 800, .height = 600}) {}
-
- protected:
- void onInit() override {
- // Create a player entity
- Entity player = getRegistry().create();
- getRegistry().emplace<Position>(player, 400.0f, 300.0f);
- getRegistry().emplace<Velocity>(player, 100.0f, 50.0f);
- }
-
- void onUpdate(float dt) override {
- // Update all entities with Position and Velocity
- auto view = getRegistry().view<Position, Velocity>();
- for (auto [entity, pos, vel] : view.each()) {
- pos.x += vel.vx * dt;
- pos.y += vel.vy * dt;
-
- // Bounce off edges
- if (pos.x < 0 || pos.x > 800) vel.vx *= -1;
- if (pos.y < 0 || pos.y > 600) vel.vy *= -1;
- }
- }
+4. **Add build script to package.json**
- void onRender() override {
- // Draw entities (simplified - actual rendering uses Renderer API)
- auto view = getRegistry().view<Position>();
- for (auto [entity, pos] : view.each()) {
- // renderer.drawRect(pos.x - 25, pos.y - 25, 50, 50, Color::Red);
- }
- }
- };
+ ```json
+ {
+ "scripts": {
+ "build": "esbuild src/main.ts --bundle --format=esm --outfile=build/main.js"
+ }
+ }
+ ```
- ES_MAIN(MyGame)
+5. **Build your game**
+
+ ```bash
+ npm run build
```
</Steps>
-## Build and Run
+<Aside type="tip">
+ You also need the ESEngine WASM files. See [Installation](/microes/getting-started/installation/) for how to build them.
+</Aside>
-### Native (for quick testing)
+## Understanding the Code
-```bash
-cmake -B build
-cmake --build build
-./build/MyGame
-```
+### App and Systems
-### Web
+ESEngine uses a system-based architecture. Systems are functions that run at specific points in the game loop:
-```bash
-emcmake cmake -B build_web -DES_BUILD_WEB=ON
-cmake --build build_web
+```typescript
+// Create the app with WASM module
+const app = createWebApp(Module);
-# Serve the output
-npx serve build_web
-# Open http://localhost:3000/MyGame.html
+// Add a system to a schedule
+app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [/* parameters */],
+ (/* injected params */) => {
+ // Game logic here
+ }
+));
+
+// Start the game loop
+app.run();
```
-<Aside type="tip">
- Use native builds for fast iteration during development, then test on web periodically.
-</Aside>
+### Schedule Types
-## Understanding the Code
+| Schedule | When it runs |
+|----------|--------------|
+| `Startup` | Once at the beginning |
+| `Update` | Every frame |
+| `PostUpdate` | After Update, every frame |
+| `FixedUpdate` | At fixed time intervals |
-### Application Lifecycle
+### System Parameters
-```
-┌─────────────┐
-│ Constructor │
-└──────┬──────┘
- ▼
-┌─────────────┐
-│ onInit() │ ← Load assets, create entities
-└──────┬──────┘
- ▼
-┌─────────────┐
-│ Main Loop │ ◄─────────────────┐
-│ ┌────────┐ │ │
-│ │onUpdate│ │ ← Game logic │
-│ └────────┘ │ │
-│ ┌────────┐ │ │
-│ │onRender│ │ ← Draw frame │
-│ └────────┘ │ │
-└──────┬──────┘ │
- │ (running) │
- └──────────────────────────┘
- │ (quit)
- ▼
-┌─────────────┐
-│ onShutdown()│ ← Cleanup
-└─────────────┘
+Systems declare what data they need, and it gets injected automatically:
+
+```typescript
+defineSystem(
+ [Commands(), Res(Time), Query(LocalTransform, Sprite)],
+ (cmds, time, query) => {
+ // cmds: spawn/despawn entities
+ // time: elapsed time, delta time
+ // query: iterate entities with components
+ }
+)
```
-### ECS Basics
+### Components
-ESEngine uses an Entity-Component-System architecture:
+Components are data attached to entities. ESEngine provides builtin components:
-- **Entity**: A unique identifier (just a number)
-- **Component**: Plain data structs attached to entities
-- **System**: Logic that operates on entities with specific components
+| Component | Description |
+|-----------|-------------|
+| `LocalTransform` | Position, rotation, scale |
+| `Sprite` | 2D sprite rendering |
+| `Camera` | Camera settings |
+| `Velocity` | Movement velocity |
-```cpp
-// Create entity
-Entity e = registry.create();
+### Creating Entities
-// Add components
-registry.emplace<Position>(e, 0.0f, 0.0f);
-registry.emplace<Velocity>(e, 1.0f, 0.0f);
+Use `Commands` to spawn entities and attach components:
-// Query and iterate
-for (auto [entity, pos, vel] : registry.view<Position, Velocity>().each()) {
- pos.x += vel.vx * dt;
+```typescript
+cmds.spawn()
+ .insert(Sprite, { color: { x: 1, y: 0, z: 0, w: 1 } })
+ .insert(LocalTransform, { position: { x: 100, y: 100, z: 0 } })
+ .id(); // Returns the entity ID
+```
+
+### Querying Entities
+
+Use `Query` to iterate entities with specific components:
+
+```typescript
+for (const [entity, transform, sprite] of query) {
+ transform.position.x += 1;
}
```
## Next Steps
- [Learn ECS in depth](/microes/guides/ecs/)
-- [Add sprites and textures](/microes/guides/rendering/)
- [Handle input](/microes/guides/input/)
+- [Add sprites and textures](/microes/guides/rendering/)
diff --git a/docs/astro/src/content/docs/guides/ecs.mdx b/docs/astro/src/content/docs/guides/ecs.mdx
index e477d3102..5b7fb67dd 100644
--- a/docs/astro/src/content/docs/guides/ecs.mdx
+++ b/docs/astro/src/content/docs/guides/ecs.mdx
@@ -14,7 +14,7 @@ ECS separates **identity** (Entity), **data** (Component), and **behavior** (Sys
| Concept | Description | Example |
|---------|-------------|---------|
| **Entity** | A unique identifier | Player, Enemy, Bullet |
-| **Component** | Plain data struct | Position, Velocity, Health |
+| **Component** | Plain data struct | LocalTransform, Sprite, Velocity |
| **System** | Logic operating on components | MovementSystem, RenderSystem |
<Aside type="tip">
@@ -25,175 +25,231 @@ ECS separates **identity** (Entity), **data** (Component), and **behavior** (Sys
An entity is just a number (ID). It has no data or behavior on its own.
-```cpp
-#include <esengine/ESEngine.hpp>
-using namespace esengine::ecs;
+```typescript
+import { Commands, type Entity } from 'esengine';
-Registry registry;
+// In a system with Commands:
+defineSystem([Commands()], (cmds) => {
+ // Create a new entity
+ const player: Entity = cmds.spawn().id();
-// Create single entity
-Entity player = registry.create();
+ // Despawn an entity
+ cmds.despawn(player);
+});
+```
-// Create multiple entities
-std::vector<Entity> enemies = registry.create(100);
+## Components
-// Check if valid
-if (registry.valid(player)) {
- // Entity exists
-}
+Components are data attached to entities. ESEngine provides builtin components backed by C++:
-// Destroy entity (removes all components)
-registry.destroy(player);
+### Builtin Components
+
+```typescript
+import { LocalTransform, Sprite, Camera, Velocity, Parent, Children } from 'esengine';
+
+// LocalTransform - position, rotation, scale
+cmds.spawn().insert(LocalTransform, {
+ position: { x: 100, y: 200, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+});
+
+// Sprite - 2D rendering
+cmds.spawn().insert(Sprite, {
+ texture: 0,
+ color: { x: 1, y: 1, z: 1, w: 1 },
+ size: { x: 64, y: 64 }
+});
+
+// Camera - view settings
+cmds.spawn().insert(Camera, {
+ projectionType: 1, // Orthographic
+ orthoSize: 400,
+ isActive: true
+});
+
+// Velocity - movement
+cmds.spawn().insert(Velocity, {
+ linear: { x: 100, y: 0, z: 0 },
+ angular: { x: 0, y: 0, z: 0 }
+});
```
-## Components
+### Custom Components
-Components are plain structs containing only data. No methods, no inheritance.
+You can define your own components for game-specific data:
-```cpp
-// Good: Simple data structs
-struct Position {
- float x, y;
-};
+```typescript
+import { defineComponent, defineTag } from 'esengine';
-struct Velocity {
- float vx, vy;
-};
+// Data component with default values
+const Health = defineComponent('Health', {
+ current: 100,
+ max: 100
+});
-struct Health {
- int current;
- int max;
-};
+// Tag component (no data, just for filtering)
+const Player = defineTag('Player');
+const Enemy = defineTag('Enemy');
-struct Tag {}; // Empty tags are valid
+// Usage
+cmds.spawn()
+ .insert(Player)
+ .insert(Health, { current: 100, max: 100 });
```
<Aside type="caution">
- Avoid putting logic in components. Keep them as pure data containers.
+ Custom components are stored in TypeScript only. Builtin components are synced with the C++ backend for rendering.
</Aside>
### Adding Components
-```cpp
-Entity player = registry.create();
-
-// emplace - construct in-place
-registry.emplace<Position>(player, 100.0f, 200.0f);
-registry.emplace<Health>(player, 100, 100);
+```typescript
+// spawn() returns EntityCommands for chaining
+const entity = cmds.spawn()
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Sprite, { size: { x: 50, y: 50 } })
+ .insert(Health, { current: 100, max: 100 })
+ .id();
+
+// Add to existing entity
+cmds.entity(entity)
+ .insert(Velocity, { linear: { x: 10, y: 0, z: 0 } });
+```
-// emplaceOrReplace - add or overwrite
-registry.emplaceOrReplace<Position>(player, 0.0f, 0.0f);
+### Removing Components
-// getOrEmplace - get existing or create new
-auto& vel = registry.getOrEmplace<Velocity>(player, 0.0f, 0.0f);
+```typescript
+cmds.entity(entity).remove(Velocity);
```
-### Accessing Components
+## Systems
-```cpp
-// get - must exist (asserts otherwise)
-Position& pos = registry.get<Position>(player);
+Systems contain game logic. They declare what data they need via parameters.
-// tryGet - returns nullptr if missing
-Health* health = registry.tryGet<Health>(player);
-if (health) {
- health->current -= 10;
-}
+### Defining Systems
-// Check existence
-if (registry.has<Position>(player)) { ... }
-if (registry.hasAll<Position, Velocity>(player)) { ... }
-if (registry.hasAny<Enemy, Boss>(player)) { ... }
-```
+```typescript
+import { defineSystem, Schedule, Commands, Query, Res, Time } from 'esengine';
-### Removing Components
+const movementSystem = defineSystem(
+ [Res(Time), Query(LocalTransform, Velocity)],
+ (time, query) => {
+ for (const [entity, transform, velocity] of query) {
+ transform.position.x += velocity.linear.x * time.delta;
+ transform.position.y += velocity.linear.y * time.delta;
+ }
+ }
+);
-```cpp
-registry.remove<Velocity>(player); // No-op if missing
+// Add to app
+app.addSystemToSchedule(Schedule.Update, movementSystem);
```
-## Views (Queries)
+### System Parameters
-Views let you iterate over entities that have specific components.
+| Parameter | Description | Usage |
+|-----------|-------------|-------|
+| `Commands()` | Spawn/despawn entities | `cmds.spawn()` |
+| `Query(...)` | Query entities with components | `for (const [e, ...] of query)` |
+| `Res(T)` | Read-only resource | `time.elapsed` |
+| `ResMut(T)` | Mutable resource | `state.score += 1` |
-### Single Component View
+### Schedule Types
-```cpp
-// Iterate entities with Position
-for (Entity entity : registry.view<Position>()) {
- Position& pos = registry.get<Position>(entity);
- pos.x += 1.0f;
-}
-```
+```typescript
+import { Schedule } from 'esengine';
-### Multi-Component View
+// Startup - runs once at beginning
+app.addSystemToSchedule(Schedule.Startup, setupSystem);
-```cpp
-// Iterate entities with both Position AND Velocity
-auto view = registry.view<Position, Velocity>();
+// Update - runs every frame
+app.addSystemToSchedule(Schedule.Update, gameLogicSystem);
-// Method 1: Structured bindings (recommended)
-for (auto [entity, pos, vel] : view.each()) {
- pos.x += vel.vx * dt;
- pos.y += vel.vy * dt;
-}
+// PostUpdate - after Update
+app.addSystemToSchedule(Schedule.PostUpdate, cleanupSystem);
-// Method 2: Manual get
-for (Entity entity : view) {
- auto& pos = view.get<Position>(entity);
- auto& vel = view.get<Velocity>(entity);
- pos.x += vel.vx * dt;
-}
+// FixedUpdate - fixed timestep (physics)
+app.addSystemToSchedule(Schedule.FixedUpdate, physicsSystem);
```
-### Using `each()` with Callbacks
+## Queries
-```cpp
-registry.each<Position, Velocity>([dt](Entity e, Position& p, Velocity& v) {
- p.x += v.vx * dt;
- p.y += v.vy * dt;
-});
+Queries let you iterate over entities that have specific components.
+
+### Basic Query
+
+```typescript
+defineSystem(
+ [Query(LocalTransform, Sprite)],
+ (query) => {
+ // Iterate all entities with both LocalTransform AND Sprite
+ for (const [entity, transform, sprite] of query) {
+ transform.position.x += 1;
+ }
+ }
+);
```
-## Systems
+### Query Methods
-Systems contain the game logic. They typically query components and update them.
+```typescript
+defineSystem(
+ [Query(LocalTransform, Sprite)],
+ (query) => {
+ // Iterate with for-of
+ for (const [entity, transform, sprite] of query) { ... }
-### Basic Pattern
+ // Iterate with forEach
+ query.forEach((entity, transform, sprite) => { ... });
-```cpp
-class MovementSystem {
-public:
- void update(Registry& registry, float dt) {
- for (auto [e, pos, vel] : registry.view<Position, Velocity>().each()) {
- pos.x += vel.vx * dt;
- pos.y += vel.vy * dt;
- }
- }
-};
+ // Get single entity (errors if 0 or >1)
+ const [entity, transform, sprite] = query.single();
-class CollisionSystem {
-public:
- void update(Registry& registry) {
- auto view = registry.view<Position, Collider>();
- // Check collisions between entities...
+ // Get count
+ const count = query.count();
}
-};
+);
```
-### In Your Application
+## Resources
-```cpp
-class MyGame : public Application {
- MovementSystem movementSystem;
- CollisionSystem collisionSystem;
+Resources are global singletons, not attached to entities.
-protected:
- void onUpdate(float dt) override {
- movementSystem.update(getRegistry(), dt);
- collisionSystem.update(getRegistry());
+### Builtin Resources
+
+```typescript
+import { Res, Time, Input } from 'esengine';
+
+defineSystem(
+ [Res(Time)],
+ (time) => {
+ console.log(`Elapsed: ${time.elapsed}s`);
+ console.log(`Delta: ${time.delta}s`);
}
-};
+);
+```
+
+### Custom Resources
+
+```typescript
+import { defineResource, Res, ResMut } from 'esengine';
+
+const GameState = defineResource({
+ score: 0,
+ level: 1,
+ paused: false
+});
+
+// Read-only access
+defineSystem([Res(GameState)], (state) => {
+ console.log(`Score: ${state.score}`);
+});
+
+// Mutable access
+defineSystem([ResMut(GameState)], (state) => {
+ state.value.score += 10;
+});
```
## Best Practices
@@ -201,30 +257,62 @@ protected:
### Do
- Keep components small and focused
-- Use empty structs as tags (`struct Player {};`)
+- Use tags for filtering entities (`const Player = defineTag('Player')`)
- Prefer composition over complex components
-- Cache views if iterating frequently in the same frame
+- Use separate systems for different concerns
### Don't
-- Put methods in components
-- Store pointers to components (they may relocate)
-- Create deep component hierarchies
-- Use components for things that don't need identity
-
-## Performance Tips
-
-1. **Component Order**: Put frequently accessed components together
-2. **View Caching**: Store views if reusing within a frame
-3. **Sorting**: Use `registry.sort<T>()` for better cache locality
-4. **Batch Creation**: Use `registry.create(count)` for many entities
+- Put methods in components (use systems instead)
+- Store references to other entities directly (use entity IDs)
+- Create deeply nested component data
+- Modify components from multiple systems without care
+
+## Example: Complete Game Loop
+
+```typescript
+import {
+ createWebApp, defineSystem, defineComponent, defineTag,
+ Schedule, Commands, Query, Res, Time,
+ LocalTransform, Sprite, Camera
+} from 'esengine';
+
+// Custom components
+const Velocity = defineComponent('Velocity', { x: 0, y: 0 });
+const Player = defineTag('Player');
+
+export async function main(Module) {
+ const app = createWebApp(Module);
+
+ // Setup
+ app.addSystemToSchedule(Schedule.Startup, defineSystem(
+ [Commands()],
+ (cmds) => {
+ // Camera
+ cmds.spawn()
+ .insert(Camera, { projectionType: 1, orthoSize: 400, isActive: true })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 10 } });
+
+ // Player
+ cmds.spawn()
+ .insert(Player)
+ .insert(Sprite, { size: { x: 50, y: 50 } })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Velocity, { x: 100, y: 50 });
+ }
+ ));
+
+ // Movement
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(LocalTransform, Velocity)],
+ (time, query) => {
+ for (const [entity, transform, velocity] of query) {
+ transform.position.x += velocity.x * time.delta;
+ transform.position.y += velocity.y * time.delta;
+ }
+ }
+ ));
-```cpp
-// Good: Batch create
-auto entities = registry.create(1000);
-for (Entity e : entities) {
- registry.emplace<Position>(e, 0.0f, 0.0f);
+ app.run();
}
-
-// Avoid: Create one by one in hot path
```
diff --git a/docs/astro/src/content/docs/guides/input.mdx b/docs/astro/src/content/docs/guides/input.mdx
index 7f0ca56cf..f95fa2924 100644
--- a/docs/astro/src/content/docs/guides/input.mdx
+++ b/docs/astro/src/content/docs/guides/input.mdx
@@ -3,247 +3,156 @@ title: Input Handling
description: Keyboard, mouse, and touch input in ESEngine
---
-import { Aside, Tabs, TabItem } from '@astrojs/starlight/components';
-
-ESEngine provides a unified input system that works across desktop browsers and mobile devices.
-
-## Input Model
-
-ESEngine uses two input patterns:
-
-1. **Event callbacks** - For discrete events (key press, touch start)
-2. **Polling** - For continuous checks (is key held down?)
-
-## Keyboard Input
-
-### Event-Based
-
-Override callbacks in your Application:
-
-```cpp
-class MyGame : public Application {
-protected:
- void onKey(KeyCode key, bool pressed) override {
- if (key == KeyCode::Space && pressed) {
- player.jump();
- }
-
- if (key == KeyCode::Escape && pressed) {
- quit();
+import { Aside } from '@astrojs/starlight/components';
+
+ESEngine provides input handling through the `Input` resource.
+
+## Using Input in Systems
+
+Access input state through the `Res(Input)` system parameter:
+
+```typescript
+import { defineSystem, Res, Input, Query, LocalTransform } from 'esengine';
+
+defineSystem(
+ [Res(Input), Query(LocalTransform)],
+ (input, query) => {
+ for (const [entity, transform] of query) {
+ // Move based on input
+ if (input.isKeyDown('KeyW')) {
+ transform.position.y -= 5;
+ }
+ if (input.isKeyDown('KeyS')) {
+ transform.position.y += 5;
+ }
+ if (input.isKeyDown('KeyA')) {
+ transform.position.x -= 5;
+ }
+ if (input.isKeyDown('KeyD')) {
+ transform.position.x += 5;
+ }
}
}
-};
+);
```
-### Polling
+## Keyboard Input
-Check key state anytime:
+### Key State
-```cpp
-void onUpdate(float dt) override {
- auto& input = getPlatform().getInput();
+```typescript
+// Check if key is currently held down
+if (input.isKeyDown('Space')) {
+ player.jump();
+}
- if (input.isKeyDown(KeyCode::W)) {
- player.y -= speed * dt;
- }
- if (input.isKeyDown(KeyCode::S)) {
- player.y += speed * dt;
- }
- if (input.isKeyDown(KeyCode::A)) {
- player.x -= speed * dt;
- }
- if (input.isKeyDown(KeyCode::D)) {
- player.x += speed * dt;
- }
+// Check if key was just pressed this frame
+if (input.isKeyPressed('Space')) {
+ player.startJump();
+}
+
+// Check if key was just released this frame
+if (input.isKeyReleased('Space')) {
+ player.endJump();
}
```
### Key Codes
-```cpp
+Use standard DOM key codes:
+
+```typescript
// Letters
-KeyCode::A, KeyCode::B, ... KeyCode::Z
+'KeyA', 'KeyB', ... 'KeyZ'
// Numbers
-KeyCode::Num0, KeyCode::Num1, ... KeyCode::Num9
+'Digit0', 'Digit1', ... 'Digit9'
-// Special
-KeyCode::Space, KeyCode::Enter, KeyCode::Escape
-KeyCode::Shift, KeyCode::Ctrl, KeyCode::Alt
+// Special keys
+'Space', 'Enter', 'Escape', 'Tab'
+'ShiftLeft', 'ShiftRight', 'ControlLeft', 'ControlRight'
-// Arrows
-KeyCode::Left, KeyCode::Right, KeyCode::Up, KeyCode::Down
+// Arrow keys
+'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'
// Function keys
-KeyCode::F1, KeyCode::F2, ... KeyCode::F12
+'F1', 'F2', ... 'F12'
```
## Mouse Input
-### Event-Based
+```typescript
+// Get mouse position
+const mousePos = input.getMousePosition();
+console.log(`Mouse at: ${mousePos.x}, ${mousePos.y}`);
-Mouse events come through the touch callbacks (unified input):
-
-```cpp
-void onTouch(TouchType type, const TouchPoint& point) override {
- if (type == TouchType::Down) {
- // Mouse button pressed or touch started
- handleClick(point.x, point.y);
- }
+// Check mouse buttons
+if (input.isMouseButtonDown(0)) { // Left button
+ shoot(mousePos.x, mousePos.y);
}
-```
-
-### Polling
-
-```cpp
-void onUpdate(float dt) override {
- auto& input = getPlatform().getInput();
-
- glm::vec2 mousePos = input.getMousePosition();
-
- if (input.isMouseButtonDown(MouseButton::Left)) {
- shoot(mousePos.x, mousePos.y);
- }
+if (input.isMouseButtonDown(2)) { // Right button
+ openContextMenu();
}
```
## Touch Input
-Touch input is essential for mobile and WeChat MiniGames.
-
-### Touch Events
-
-```cpp
-void onTouch(TouchType type, const TouchPoint& point) override {
- switch (type) {
- case TouchType::Down:
- // Finger touched screen
- onTouchStart(point);
- break;
-
- case TouchType::Move:
- // Finger moved
- onTouchMove(point);
- break;
-
- case TouchType::Up:
- // Finger lifted
- onTouchEnd(point);
- break;
+Touch input is unified with mouse input for cross-platform support:
- case TouchType::Cancel:
- // Touch interrupted (e.g., phone call)
- onTouchCancel(point);
- break;
- }
+```typescript
+// Works for both mouse click and touch
+if (input.isMouseButtonDown(0)) {
+ const pos = input.getMousePosition();
+ handleTap(pos.x, pos.y);
}
```
-### TouchPoint Structure
-
-```cpp
-struct TouchPoint {
- int id; // Unique touch identifier (for multi-touch)
- float x; // X position in viewport coordinates
- float y; // Y position in viewport coordinates
-};
-```
-
-### Multi-Touch
-
-```cpp
-class MyGame : public Application {
- std::unordered_map<int, glm::vec2> activeTouches;
-
-protected:
- void onTouch(TouchType type, const TouchPoint& point) override {
- switch (type) {
- case TouchType::Down:
- activeTouches[point.id] = {point.x, point.y};
- break;
-
- case TouchType::Move:
- activeTouches[point.id] = {point.x, point.y};
- break;
-
- case TouchType::Up:
- case TouchType::Cancel:
- activeTouches.erase(point.id);
- break;
- }
-
- // Pinch zoom detection
- if (activeTouches.size() == 2) {
- auto it = activeTouches.begin();
- glm::vec2 p1 = it->second; ++it;
- glm::vec2 p2 = it->second;
- float distance = glm::length(p2 - p1);
- handlePinch(distance);
- }
- }
-};
-```
-
-## Virtual Joystick
-
-Common pattern for mobile games:
-
-```cpp
-class VirtualJoystick {
-public:
- glm::vec2 center;
- float radius = 50.0f;
- bool active = false;
- glm::vec2 direction = {0, 0};
-
- void onTouchDown(float x, float y) {
- center = {x, y};
- active = true;
- direction = {0, 0};
- }
-
- void onTouchMove(float x, float y) {
- if (!active) return;
-
- glm::vec2 delta = {x - center.x, y - center.y};
- float length = glm::length(delta);
+<Aside type="tip">
+ Design your input handling to work with both mouse and touch. The Input resource provides a unified interface.
+</Aside>
- if (length > 0) {
- direction = delta / std::max(length, radius);
+## Example: Player Movement
+
+```typescript
+import {
+ defineSystem, defineComponent, Schedule,
+ Res, Input, Time, Query, LocalTransform
+} from 'esengine';
+
+const Player = defineTag('Player');
+const MoveSpeed = defineComponent('MoveSpeed', { value: 200 });
+
+// Movement system
+app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Input), Res(Time), Query(LocalTransform, MoveSpeed, Player)],
+ (input, time, query) => {
+ for (const [entity, transform, speed] of query) {
+ const velocity = { x: 0, y: 0 };
+
+ if (input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp')) {
+ velocity.y = -1;
+ }
+ if (input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown')) {
+ velocity.y = 1;
+ }
+ if (input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft')) {
+ velocity.x = -1;
+ }
+ if (input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight')) {
+ velocity.x = 1;
+ }
+
+ // Normalize diagonal movement
+ const len = Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
+ if (len > 0) {
+ velocity.x /= len;
+ velocity.y /= len;
+ }
+
+ // Apply movement
+ transform.position.x += velocity.x * speed.value * time.delta;
+ transform.position.y += velocity.y * speed.value * time.delta;
}
}
-
- void onTouchUp() {
- active = false;
- direction = {0, 0};
- }
-};
-
-// Usage
-VirtualJoystick joystick;
-
-void onUpdate(float dt) override {
- player.x += joystick.direction.x * speed * dt;
- player.y += joystick.direction.y * speed * dt;
-}
+));
```
-
-## Input Best Practices
-
-<Tabs>
- <TabItem label="Do">
- - Use events for discrete actions (jump, shoot)
- - Use polling for continuous input (movement)
- - Handle `TouchType::Cancel` for mobile
- - Test on real mobile devices
- </TabItem>
- <TabItem label="Don't">
- - Don't assume mouse is always available
- - Don't ignore touch input for "desktop" games
- - Don't store raw pointers to touch points
- </TabItem>
-</Tabs>
-
-<Aside type="tip">
- The web and WeChat both support both touch and mouse. Design your input handling to support both seamlessly.
-</Aside>
diff --git a/docs/astro/src/content/docs/guides/project-structure.mdx b/docs/astro/src/content/docs/guides/project-structure.mdx
index 69ebc7de9..9323e4873 100644
--- a/docs/astro/src/content/docs/guides/project-structure.mdx
+++ b/docs/astro/src/content/docs/guides/project-structure.mdx
@@ -1,159 +1,201 @@
---
title: Project Structure
-description: Understanding the ESEngine codebase organization
+description: How to organize your ESEngine game project
---
-This guide explains how the ESEngine codebase is organized and where to find specific functionality.
+This guide explains how to structure your ESEngine game project and the SDK architecture.
-## Directory Layout
+## Game Project Structure
+
+A typical ESEngine game project:
```
-esengine/
-├── include/esengine/ # Public API headers
-│ └── ESEngine.hpp # Main include file
-│
-├── src/esengine/ # Engine implementation
-│ ├── core/ # Core systems
-│ │ ├── Application.hpp # Base application class
-│ │ ├── Engine.hpp # Engine singleton
-│ │ ├── Log.hpp # Logging utilities
-│ │ └── Types.hpp # Common type aliases
-│ │
-│ ├── ecs/ # Entity-Component-System
-│ │ ├── Entity.hpp # Entity type definition
-│ │ ├── Component.hpp # Component traits
-│ │ ├── Registry.hpp # Main ECS container
-│ │ ├── SparseSet.hpp # Component storage
-│ │ ├── View.hpp # Query iterators
-│ │ └── System.hpp # System base class
-│ │
-│ ├── math/ # Mathematics
-│ │ └── Math.hpp # GLM wrapper and utilities
-│ │
-│ ├── renderer/ # Graphics
-│ │ ├── Renderer.hpp # High-level render API
-│ │ ├── RenderCommand.hpp
-│ │ ├── Shader.hpp # Shader program
-│ │ ├── Texture.hpp # Texture loading
-│ │ └── Buffer.hpp # Vertex/Index buffers
-│ │
-│ ├── platform/ # Platform abstraction
-│ │ ├── Platform.hpp # Platform interface
-│ │ └── input/
-│ │ └── Input.hpp # Input handling
-│ │
-│ └── ESEngine.hpp # Internal aggregation header
-│
-├── third_party/ # External dependencies
-│ └── glm/ # OpenGL Mathematics
-│
-├── examples/ # Example projects
-├── tests/ # Unit tests
-├── bindings/ # JS bindings
-└── docs/ # Documentation
+my-game/
+├── src/
+│ ├── main.ts # Entry point
+│ ├── systems/ # Game systems
+│ │ ├── movement.ts
+│ │ ├── collision.ts
+│ │ └── input.ts
+│ └── components/ # Custom components
+│ ├── player.ts
+│ └── enemy.ts
+├── assets/ # Game assets
+│ ├── sprites/
+│ └── audio/
+├── build/ # Build output
+│ ├── main.js
+│ ├── esengine.js # WASM loader
+│ └── esengine.wasm # WASM binary
+├── index.html # HTML entry
+├── package.json
+└── tsconfig.json
```
-## Module Overview
+## Entry Point
-### Core (`src/esengine/core/`)
+Your `src/main.ts` exports a `main` function that receives the WASM module:
-Foundation types and the application framework.
+```typescript
+import { createWebApp, defineSystem, Schedule, ... } from 'esengine';
+import type { ESEngineModule } from 'esengine';
-| File | Purpose |
-|------|---------|
-| `Application.hpp` | Base class for games, manages lifecycle |
-| `Engine.hpp` | Global engine state and subsystems |
-| `Log.hpp` | Logging macros (`ES_LOG_INFO`, etc.) |
-| `Types.hpp` | Typedefs (`u32`, `f32`, `Unique<T>`) |
+// Import your systems
+import { movementSystem } from './systems/movement';
+import { inputSystem } from './systems/input';
-### ECS (`src/esengine/ecs/`)
+export async function main(Module: ESEngineModule): Promise<void> {
+ const app = createWebApp(Module);
-The Entity-Component-System implementation.
+ // Add systems
+ app.addSystemToSchedule(Schedule.Startup, setupSystem);
+ app.addSystemToSchedule(Schedule.Update, inputSystem);
+ app.addSystemToSchedule(Schedule.Update, movementSystem);
-| File | Purpose |
-|------|---------|
-| `Entity.hpp` | Entity ID type and utilities |
-| `Registry.hpp` | Central container for entities/components |
-| `SparseSet.hpp` | O(1) component storage |
-| `View.hpp` | Query interface for iteration |
-| `System.hpp` | Base class for game systems |
+ app.run();
+}
+```
-### Renderer (`src/esengine/renderer/`)
+## Organizing Systems
-WebGL-based rendering pipeline.
+Create separate files for each system:
-| File | Purpose |
-|------|---------|
-| `Renderer.hpp` | High-level drawing API |
-| `Shader.hpp` | GLSL shader compilation |
-| `Texture.hpp` | Image loading and binding |
-| `Buffer.hpp` | GPU buffer management |
+```typescript
+// src/systems/movement.ts
+import { defineSystem, Res, Time, Query, LocalTransform, Velocity } from 'esengine';
-### Platform (`src/esengine/platform/`)
+export const movementSystem = defineSystem(
+ [Res(Time), Query(LocalTransform, Velocity)],
+ (time, query) => {
+ for (const [entity, transform, velocity] of query) {
+ transform.position.x += velocity.linear.x * time.delta;
+ transform.position.y += velocity.linear.y * time.delta;
+ }
+ }
+);
+```
-OS and browser abstraction layer.
+## Organizing Components
-| File | Purpose |
-|------|---------|
-| `Platform.hpp` | Window, context, timing |
-| `input/Input.hpp` | Keyboard, mouse, touch |
+Define custom components in separate files:
-## Include Conventions
+```typescript
+// src/components/player.ts
+import { defineComponent, defineTag } from 'esengine';
-### For Game Code
+export const Player = defineTag('Player');
-Include only the public header:
+export const Health = defineComponent('Health', {
+ current: 100,
+ max: 100
+});
-```cpp
-#include <esengine/ESEngine.hpp>
+export const MoveSpeed = defineComponent('MoveSpeed', {
+ value: 200
+});
```
-This gives you access to all public APIs.
+## HTML Setup
+
+Your `index.html` loads the WASM and your game:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>My Game</title>
+ <style>
+ body { margin: 0; overflow: hidden; }
+ canvas { display: block; }
+ </style>
+</head>
+<body>
+ <canvas id="canvas"></canvas>
+ <script type="module">
+ import ESEngineModule from './build/esengine.js';
+ import { main } from './build/main.js';
+
+ ESEngineModule().then(Module => {
+ main(Module);
+ });
+ </script>
+</body>
+</html>
+```
-### For Engine Development
+## SDK Architecture
-Include specific internal headers:
+The ESEngine SDK is organized as a single-entry package:
-```cpp
-#include "core/Application.hpp"
-#include "ecs/Registry.hpp"
+```
+esengine/
+├── dist/
+│ ├── index.js # Main entry
+│ ├── index.d.ts # TypeScript types
+│ ├── wasm.js # WASM types export
+│ └── wasm.d.ts
+└── src/
+ ├── index.ts # Public exports
+ ├── types.ts # Entity, Vec2, Vec3, etc.
+ ├── component.ts # Components
+ ├── resource.ts # Resources
+ ├── query.ts # Query system
+ ├── commands.ts # Commands
+ ├── system.ts # System definitions
+ ├── world.ts # World management
+ ├── app.ts # App and createWebApp
+ └── wasm.ts # WASM interface types
```
-## Namespace Organization
+### Import from Single Entry
-```cpp
-namespace esengine {
- // Core classes
- class Application;
- class Platform;
+```typescript
+// All imports from 'esengine'
+import {
+ // App
+ App, createWebApp,
- namespace ecs {
- // ECS types
- class Registry;
- using Entity = uint32_t;
- }
+ // ECS
+ defineSystem, Schedule,
+ Commands, Query,
+ defineComponent, defineTag,
- namespace math {
- // Math utilities (mostly GLM re-exports)
- }
-}
+ // Resources
+ Res, ResMut, defineResource, Time, Input,
+
+ // Builtin Components
+ LocalTransform, Sprite, Camera, Velocity,
+
+ // Types
+ type Entity, vec2, vec3, vec4, quat
+} from 'esengine';
```
-## Adding New Features
+## Best Practices
-### Adding a Component
+### File Organization
-1. Define in your game code (components are just structs):
- ```cpp
- struct Health {
- int current;
- int max;
- };
- ```
+- Keep systems small and focused (one concern per system)
+- Group related components together
+- Use barrel exports (`index.ts`) for cleaner imports
+
+### Code Structure
+
+```typescript
+// src/systems/index.ts
+export { movementSystem } from './movement';
+export { inputSystem } from './input';
+export { collisionSystem } from './collision';
+
+// src/main.ts
+import { movementSystem, inputSystem, collisionSystem } from './systems';
+```
-### Adding an Engine System
+### Separation of Concerns
-1. Create header in appropriate module
-2. Include in `ESEngine.hpp` if public
-3. Add to `CMakeLists.txt` if new files
-4. Document with Doxygen comments
+| Layer | Responsibility |
+|-------|----------------|
+| Components | Data only, no logic |
+| Systems | Game logic, operates on components |
+| Resources | Global state (time, input, game state) |
+| App | Wiring systems together |
diff --git a/docs/astro/src/content/docs/guides/rendering.mdx b/docs/astro/src/content/docs/guides/rendering.mdx
index e3ee3ad4a..f6cc605cc 100644
--- a/docs/astro/src/content/docs/guides/rendering.mdx
+++ b/docs/astro/src/content/docs/guides/rendering.mdx
@@ -1,248 +1,230 @@
---
title: Rendering
-description: Drawing sprites, shapes, and text with ESEngine
+description: Drawing sprites and managing the camera in ESEngine
---
import { Aside } from '@astrojs/starlight/components';
-ESEngine provides a WebGL-based rendering system optimized for 2D games. This guide covers the rendering APIs.
-
-## Render Loop
-
-Rendering happens in the `onRender()` callback:
-
-```cpp
-class MyGame : public Application {
-protected:
- void onRender() override {
- auto& renderer = getRenderer();
-
- renderer.clear(Color::Black);
-
- // Draw your game...
-
- renderer.present();
+ESEngine uses a component-based rendering system. Add rendering components to entities and the engine handles drawing automatically.
+
+## Sprites
+
+The `Sprite` component makes an entity visible:
+
+```typescript
+import { Commands, Sprite, LocalTransform } from 'esengine';
+
+defineSystem([Commands()], (cmds) => {
+ cmds.spawn()
+ .insert(Sprite, {
+ texture: 0, // Texture ID
+ color: { x: 1, y: 1, z: 1, w: 1 }, // RGBA (white)
+ size: { x: 64, y: 64 }, // Width, height
+ uvOffset: { x: 0, y: 0 }, // Texture offset
+ uvScale: { x: 1, y: 1 }, // Texture scale
+ layer: 0, // Render order
+ flipX: false,
+ flipY: false
+ })
+ .insert(LocalTransform, {
+ position: { x: 100, y: 100, z: 0 }
+ });
+});
+```
+
+### Sprite Properties
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `texture` | number | Texture resource ID |
+| `color` | Vec4 | Tint color (RGBA, 0-1) |
+| `size` | Vec2 | Sprite dimensions in pixels |
+| `uvOffset` | Vec2 | Texture coordinate offset |
+| `uvScale` | Vec2 | Texture coordinate scale |
+| `layer` | number | Render order (higher = on top) |
+| `flipX` | boolean | Flip horizontally |
+| `flipY` | boolean | Flip vertically |
+
+### Colored Rectangle
+
+For simple colored rectangles without textures:
+
+```typescript
+cmds.spawn()
+ .insert(Sprite, {
+ texture: 0, // No texture
+ color: { x: 1, y: 0, z: 0, w: 1 }, // Red
+ size: { x: 50, y: 50 }
+ })
+ .insert(LocalTransform, {
+ position: { x: 200, y: 200, z: 0 }
+ });
+```
+
+## Camera
+
+A `Camera` component is required to see anything. Create one in your startup system:
+
+```typescript
+cmds.spawn()
+ .insert(Camera, {
+ projectionType: 1, // 0 = Perspective, 1 = Orthographic
+ fov: 60, // Field of view (perspective only)
+ orthoSize: 400, // Half-height in world units (ortho only)
+ nearPlane: 0.1,
+ farPlane: 1000,
+ aspectRatio: 1, // Usually set automatically
+ isActive: true, // Only one camera should be active
+ priority: 0 // Higher priority camera wins
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 10 } // Camera position
+ });
+```
+
+### Orthographic Camera
+
+Best for 2D games. The `orthoSize` determines how much of the world is visible:
+
+```typescript
+// Camera showing 800x600 world units
+cmds.spawn()
+ .insert(Camera, {
+ projectionType: 1,
+ orthoSize: 300, // Half of 600
+ isActive: true
+ })
+ .insert(LocalTransform, {
+ position: { x: 400, y: 300, z: 10 } // Center of 800x600 world
+ });
+```
+
+### Moving the Camera
+
+Query and modify the camera's transform:
+
+```typescript
+defineSystem(
+ [Res(Input), Query(LocalTransform, Camera)],
+ (input, query) => {
+ for (const [entity, transform, camera] of query) {
+ // Pan camera with arrow keys
+ if (input.isKeyDown('ArrowLeft')) {
+ transform.position.x -= 5;
+ }
+ if (input.isKeyDown('ArrowRight')) {
+ transform.position.x += 5;
+ }
+ }
}
-};
-```
-
-## Coordinate System
-
-ESEngine uses a standard 2D coordinate system:
-
-```
-(0,0) ───────────► X (width)
- │
- │
- │
- ▼
- Y (height)
-```
-
-<Aside>
- Origin is top-left. Y increases downward. This matches most 2D game engines and web conventions.
-</Aside>
-
-## Drawing Primitives
-
-### Rectangles
-
-```cpp
-// Filled rectangle
-renderer.fillRect(x, y, width, height, Color::Red);
-
-// Outlined rectangle
-renderer.drawRect(x, y, width, height, Color::White, lineWidth);
-```
-
-### Lines
-
-```cpp
-renderer.drawLine(x1, y1, x2, y2, Color::Green, lineWidth);
-```
-
-### Circles
-
-```cpp
-renderer.fillCircle(centerX, centerY, radius, Color::Blue);
-renderer.drawCircle(centerX, centerY, radius, Color::White, lineWidth);
-```
-
-## Textures
-
-### Loading
-
-```cpp
-Texture texture;
-
-void onInit() override {
- texture = Texture::load("assets/player.png");
- // Or from memory:
- // texture = Texture::loadFromMemory(data, size);
-}
-```
-
-### Drawing
-
-```cpp
-// Draw at position
-renderer.drawTexture(texture, x, y);
-
-// Draw with size
-renderer.drawTexture(texture, x, y, width, height);
-
-// Draw region (sprite sheet)
-Rect srcRect = {0, 0, 32, 32}; // Source rectangle in texture
-Rect dstRect = {x, y, 64, 64}; // Destination on screen
-renderer.drawTexture(texture, srcRect, dstRect);
-```
-
-### Sprite Sheets
-
-```cpp
-struct SpriteSheet {
- Texture texture;
- int tileWidth;
- int tileHeight;
- int columns;
-
- Rect getTileRect(int index) {
- int col = index % columns;
- int row = index / columns;
- return {col * tileWidth, row * tileHeight, tileWidth, tileHeight};
+);
+```
+
+## Transform
+
+Every visible entity needs a `LocalTransform`:
+
+```typescript
+cmds.spawn()
+ .insert(LocalTransform, {
+ position: { x: 100, y: 200, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 }, // Quaternion
+ scale: { x: 1, y: 1, z: 1 }
+ })
+ .insert(Sprite, { ... });
+```
+
+### Rotation
+
+Rotation uses quaternions. For 2D rotation around Z-axis:
+
+```typescript
+// Rotate sprite over time
+defineSystem(
+ [Res(Time), Query(LocalTransform, Sprite)],
+ (time, query) => {
+ for (const [entity, transform, sprite] of query) {
+ const angle = time.elapsed; // Radians
+ const halfAngle = angle / 2;
+ transform.rotation = {
+ w: Math.cos(halfAngle),
+ x: 0,
+ y: 0,
+ z: Math.sin(halfAngle)
+ };
+ }
}
-};
-
-// Usage
-SpriteSheet sheet = {texture, 32, 32, 8};
-Rect src = sheet.getTileRect(5); // Get 6th tile
-renderer.drawTexture(sheet.texture, src, dstRect);
-```
-
-## Colors
-
-```cpp
-// Predefined colors
-Color::Black, Color::White, Color::Red, Color::Green, Color::Blue
-
-// Custom colors (RGBA, 0-255)
-Color custom = {128, 64, 255, 255};
-
-// With alpha
-Color semiTransparent = {255, 0, 0, 128}; // 50% red
-```
-
-## Transformations
-
-### Translation, Rotation, Scale
-
-```cpp
-renderer.pushTransform();
-
-renderer.translate(100, 100);
-renderer.rotate(glm::radians(45.0f)); // Rotate 45 degrees
-renderer.scale(2.0f, 2.0f); // Double size
-
-renderer.drawTexture(texture, 0, 0); // Draws at transformed position
-
-renderer.popTransform();
+);
```
-### Camera
-
-```cpp
-class Camera {
-public:
- float x = 0, y = 0;
- float zoom = 1.0f;
-
- void apply(Renderer& renderer) {
- renderer.translate(-x, -y);
- renderer.scale(zoom, zoom);
- }
-};
-
-// In onRender:
-renderer.pushTransform();
-camera.apply(renderer);
-
-// Draw world objects...
+### Scale
-renderer.popTransform();
+```typescript
+// Double size
+transform.scale = { x: 2, y: 2, z: 1 };
-// Draw UI (not affected by camera)
-renderer.drawText("Score: 100", 10, 10);
+// Flip horizontally
+transform.scale = { x: -1, y: 1, z: 1 };
```
-## Render Targets
+## Render Order
-Render to an off-screen texture:
+Sprites are drawn in order by:
-```cpp
-RenderTarget target;
+1. **Z position** - Lower Z draws first (behind)
+2. **Layer** - Higher layer draws on top
-void onInit() override {
- target = RenderTarget::create(256, 256);
-}
+```typescript
+// Background (behind everything)
+cmds.spawn()
+ .insert(Sprite, { layer: 0, ... })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: -10 } });
-void onRender() override {
- // Render to target
- renderer.setTarget(target);
- renderer.clear(Color::Transparent);
- renderer.fillCircle(128, 128, 64, Color::Red);
+// Player (middle)
+cmds.spawn()
+ .insert(Sprite, { layer: 1, ... })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 0 } });
- // Render to screen
- renderer.setTarget(nullptr);
- renderer.clear(Color::Black);
- renderer.drawTexture(target.getTexture(), 0, 0);
-}
+// UI (on top)
+cmds.spawn()
+ .insert(Sprite, { layer: 10, ... })
+ .insert(LocalTransform, { position: { x: 0, y: 0, z: 10 } });
```
-## Blending
+## Example: Animated Sprite
-```cpp
-// Set blend mode
-renderer.setBlendMode(BlendMode::Alpha); // Default
-renderer.setBlendMode(BlendMode::Additive); // For glow effects
-renderer.setBlendMode(BlendMode::Multiply); // For shadows
-```
-
-## Batching
-
-ESEngine automatically batches draw calls when possible. For best performance:
-
-1. Draw same texture consecutively
-2. Minimize blend mode changes
-3. Minimize transform changes
+```typescript
+import {
+ defineSystem, defineComponent, Schedule,
+ Res, Time, Query, LocalTransform, Sprite
+} from 'esengine';
-```cpp
-// Good: All same texture
-for (auto& enemy : enemies) {
- renderer.drawTexture(enemyTexture, enemy.x, enemy.y);
-}
+const Animation = defineComponent('Animation', {
+ frames: 4,
+ currentFrame: 0,
+ frameTime: 0.1,
+ elapsed: 0
+});
-// Avoid: Alternating textures
-for (int i = 0; i < 100; i++) {
- renderer.drawTexture(textureA, ...); // Breaks batch
- renderer.drawTexture(textureB, ...); // Breaks batch
-}
-```
-
-## Shaders
+// Animation system
+app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(Sprite, Animation)],
+ (time, query) => {
+ for (const [entity, sprite, anim] of query) {
+ anim.elapsed += time.delta;
-For advanced effects, use custom shaders:
+ if (anim.elapsed >= anim.frameTime) {
+ anim.elapsed = 0;
+ anim.currentFrame = (anim.currentFrame + 1) % anim.frames;
-```cpp
-Shader shader = Shader::load("assets/custom.vert", "assets/custom.frag");
-
-void onRender() override {
- renderer.setShader(shader);
- shader.setUniform("u_time", getTime());
- renderer.drawTexture(texture, 0, 0);
- renderer.setShader(nullptr); // Reset to default
-}
+ // Update UV offset for sprite sheet
+ sprite.uvOffset.x = anim.currentFrame / anim.frames;
+ }
+ }
+ }
+));
```
-<Aside type="caution">
- Custom shaders must be GLSL ES 2.0/3.0 compatible for WebGL.
+<Aside type="tip">
+ The C++ backend handles all WebGL rendering. You just set component data and the engine draws everything automatically each frame.
</Aside>
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
deleted file mode 100644
index 4e353ed6f..000000000
--- a/examples/CMakeLists.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-# ESEngine Examples
-
-# Hello Triangle Example
-add_executable(hello_triangle hello_triangle/main.cpp)
-target_link_libraries(hello_triangle PRIVATE esengine)
-
-if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
- es_apply_emscripten_settings(hello_triangle)
-
- # Copy HTML file
- configure_file(
- ${CMAKE_CURRENT_SOURCE_DIR}/../bindings/platform/web/index.html
- ${CMAKE_BINARY_DIR}/bin/hello_triangle.html
- COPYONLY
- )
-endif()
diff --git a/examples/hello_triangle/main.cpp b/examples/hello_triangle/main.cpp
deleted file mode 100644
index 6f79851e5..000000000
--- a/examples/hello_triangle/main.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-#include <esengine/ESEngine.hpp>
-#include <esengine/ui/UIContext.hpp>
-#include <esengine/ui/rendering/UIBatchRenderer.hpp>
-#include <esengine/ui/font/SystemFont.hpp>
-#include <esengine/events/Dispatcher.hpp>
-
-using namespace esengine;
-using namespace esengine::ecs;
-
-class HelloTriangleApp : public Application {
-public:
- HelloTriangleApp() : Application(createConfig()) {}
-
-private:
- static ApplicationConfig createConfig() {
- ApplicationConfig config;
- config.title = "ESEngine - SystemFont Demo";
- config.width = 800;
- config.height = 600;
- return config;
- }
-
-protected:
- void onInit() override {
- ES_LOG_INFO("SystemFont Demo initialized!");
-
- uiContext_ = makeUnique<ui::UIContext>(getRenderContext(), dispatcher_);
- uiContext_->init();
- uiContext_->setViewport(getWidth(), getHeight());
-
- font_ = ui::SystemFont::create("Microsoft YaHei", 32.0f);
- if (!font_) {
- font_ = ui::SystemFont::create("Arial", 32.0f);
- }
-
- if (font_) {
- ES_LOG_INFO("Created SystemFont: {}", font_->getFontFamily());
- font_->preloadASCII();
- font_->preloadChars("你好世界中文测试游戏引擎");
- } else {
- ES_LOG_ERROR("Failed to create SystemFont!");
- }
-
- auto& registry = getRegistry();
- Entity entity = registry.create();
- registry.emplace<LocalTransform>(entity, glm::vec3(400.0f, 300.0f, 0.0f));
- registry.emplace<Name>(entity, "Demo");
-
- ES_LOG_INFO("Press ESC to exit");
- }
-
- void onUpdate(f32 deltaTime) override {
- (void)deltaTime;
- if (getInput().isKeyPressed(KeyCode::Escape)) {
- quit();
- }
- }
-
- void onRender() override {
- if (!uiContext_ || !font_) return;
-
- auto& uiRenderer = uiContext_->getRenderer();
-
- glm::mat4 projection = glm::ortho(
- 0.0f, static_cast<f32>(getWidth()),
- static_cast<f32>(getHeight()), 0.0f,
- -1.0f, 1.0f
- );
-
- uiRenderer.begin(projection);
-
- uiRenderer.drawText(
- "ESEngine SystemFont",
- {50.0f, 50.0f},
- *font_,
- 32.0f,
- {1.0f, 1.0f, 1.0f, 1.0f}
- );
-
- uiRenderer.drawText(
- "Hello World! 你好世界!",
- {50.0f, 100.0f},
- *font_,
- 28.0f,
- {0.0f, 1.0f, 0.8f, 1.0f}
- );
-
- uiRenderer.drawText(
- "中文测试 Chinese Test",
- {50.0f, 150.0f},
- *font_,
- 24.0f,
- {1.0f, 1.0f, 0.0f, 1.0f}
- );
-
- uiRenderer.drawText(
- "Small 14px text",
- {50.0f, 200.0f},
- *font_,
- 14.0f,
- {0.8f, 0.8f, 1.0f, 1.0f}
- );
-
- uiRenderer.drawText(
- "Large 48px",
- {50.0f, 230.0f},
- *font_,
- 48.0f,
- {1.0f, 0.6f, 0.6f, 1.0f}
- );
-
- uiRenderer.drawText(
- "游戏引擎 Game Engine",
- {50.0f, 300.0f},
- *font_,
- 32.0f,
- {0.5f, 1.0f, 0.5f, 1.0f}
- );
-
- uiRenderer.end();
- }
-
- void onShutdown() override {
- font_.reset();
- uiContext_.reset();
- ES_LOG_INFO("SystemFont Demo shutdown");
- }
-
-private:
- Dispatcher dispatcher_;
- Unique<ui::UIContext> uiContext_;
- Unique<ui::SystemFont> font_;
-};
-
-#ifndef ES_PLATFORM_WEB
-int main() {
- HelloTriangleApp app;
- app.run();
- return 0;
-}
-#else
-ES_MAIN(HelloTriangleApp)
-#endif
diff --git a/scripts/build-web-test.bat b/scripts/build-web-test.bat
new file mode 100644
index 000000000..5195c32fb
--- /dev/null
+++ b/scripts/build-web-test.bat
@@ -0,0 +1,28 @@
+@echo off
+setlocal
+
+cd /d "%~dp0\.."
+
+set BUILD_DIR=build-web
+set TEST_DIR=sdk\examples\playground\build
+
+cd "%BUILD_DIR%"
+
+call emmake make -j4
+if errorlevel 1 goto :error
+
+cd ..
+copy /Y "%BUILD_DIR%\sdk\esengine.js" "%TEST_DIR%\"
+copy /Y "%BUILD_DIR%\sdk\esengine.wasm" "%TEST_DIR%\"
+
+echo.
+echo Build and copy complete!
+goto :end
+
+:error
+echo Build failed!
+pause
+exit /b 1
+
+:end
+pause
diff --git a/scripts/build-web.bat b/scripts/build-web.bat
index d8d4086f3..e5ca825dc 100644
--- a/scripts/build-web.bat
+++ b/scripts/build-web.bat
@@ -1,27 +1,29 @@
@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!
-)
+cd /d "%~dp0\.."
+set BUILD_DIR=build-web
+
+if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
+cd "%BUILD_DIR%"
+
+call emcmake cmake .. -DES_BUILD_WEB=ON -DES_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release
+if errorlevel 1 goto :error
+
+call emmake make -j4
+if errorlevel 1 goto :error
+
+echo.
+echo Build complete: %BUILD_DIR%\sdk\
+dir sdk\
+goto :end
+
+:error
+echo Build failed!
+pause
+exit /b 1
+
+:end
+endlocal
pause
diff --git a/bindings/esengine.d.ts b/sdk/esengine.d.ts
similarity index 75%
rename from bindings/esengine.d.ts
rename to sdk/esengine.d.ts
index 1dc6320ba..faf1069a1 100644
--- a/bindings/esengine.d.ts
+++ b/sdk/esengine.d.ts
@@ -1,25 +1,15 @@
/**
* @file esengine.d.ts
* @brief ESEngine TypeScript Definitions
- * @details Generated by EHT (ESEngine Header Tool) - DO NOT EDIT
- *
- * @author ESEngine Team
- * @date 2026
+ * @details Generated by EHT - DO NOT EDIT
*
* @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; }
@@ -27,9 +17,7 @@ export interface UVec2 { x: number; y: number; }
export interface Quat { w: number; x: number; y: number; z: number; }
export type Mat4 = number[];
-// =============================================================================
// Enums
-// =============================================================================
export enum ProjectionType {
Perspective = 0,
@@ -44,12 +32,10 @@ export enum CanvasScaleMode {
Match = 4,
}
-// =============================================================================
// Components
-// =============================================================================
export interface Camera {
- projectionType: any;
+ projectionType: number;
fov: number;
orthoSize: number;
nearPlane: number;
@@ -62,7 +48,7 @@ export interface Camera {
export interface Canvas {
designResolution: UVec2;
pixelsPerUnit: number;
- scaleMode: any;
+ scaleMode: number;
matchWidthOrHeight: number;
backgroundColor: Vec4;
}
@@ -75,7 +61,7 @@ export interface Children {
}
export interface Sprite {
- texture: any;
+ texture: number;
color: Vec4;
size: Vec2;
uvOffset: Vec2;
@@ -92,7 +78,6 @@ export interface LocalTransform {
}
export interface WorldTransform {
- matrix: Mat4;
position: Vec3;
rotation: Quat;
scale: Vec3;
@@ -103,10 +88,7 @@ export interface Velocity {
angular: Vec3;
}
-// =============================================================================
// Registry
-// =============================================================================
-
export interface Registry {
create(): Entity;
destroy(entity: Entity): void;
@@ -147,10 +129,7 @@ export interface Registry {
removeVelocity(entity: Entity): void;
}
-// =============================================================================
// Module
-// =============================================================================
-
export interface ESEngineModule {
Registry: new () => Registry;
Camera: new () => Camera;
diff --git a/sdk/examples/hello-game/index.html b/sdk/examples/hello-game/index.html
deleted file mode 100644
index 90a728478..000000000
--- a/sdk/examples/hello-game/index.html
+++ /dev/null
@@ -1,69 +0,0 @@
-<!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>Hello ESEngine</title>
- <style>
- * {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
-
- html, body {
- width: 100%;
- height: 100%;
- overflow: hidden;
- background: #1a1a2e;
- }
-
- body {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- }
-
- h1 {
- color: #e94560;
- margin-bottom: 20px;
- font-size: 24px;
- }
-
- #game-canvas {
- border: 2px solid #e94560;
- border-radius: 4px;
- background: #16213e;
- touch-action: none;
- }
-
- .instructions {
- color: #a8a8a8;
- margin-top: 20px;
- font-size: 14px;
- text-align: center;
- }
-
- .instructions kbd {
- background: #2a2a4e;
- padding: 2px 8px;
- border-radius: 4px;
- color: #e94560;
- }
- </style>
-</head>
-<body>
- <h1>ESEngine TypeScript SDK Demo</h1>
- <canvas id="canvas" width="800" height="600"></canvas>
- <div class="instructions">
- <p>Use <kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> or <kbd>↑</kbd><kbd>←</kbd><kbd>↓</kbd><kbd>→</kbd> to move</p>
- <p>Touch/click to move towards that position</p>
- <p>Press <kbd>ESC</kbd> to quit</p>
- </div>
-
- <!-- For development, use the bundled SDK -->
- <script type="module" src="./index.js"></script>
-</body>
-</html>
diff --git a/sdk/examples/hello-game/index.ts b/sdk/examples/hello-game/index.ts
deleted file mode 100644
index 3e13d8d32..000000000
--- a/sdk/examples/hello-game/index.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-/**
- * ESEngine SDK - Hello Game Example
- *
- * A simple example demonstrating the TypeScript SDK usage.
- */
-
-import {
- Application,
- Registry,
- Transform,
- Sprite,
- Velocity,
- TransformType,
- SpriteType,
- VelocityType,
- createTransform,
- createSprite,
- createVelocity,
- Renderer,
- Input,
- KeyCode,
- TouchType,
- TouchPoint,
- color,
- vec2,
-} from '../../src/index';
-
-/**
- * A simple game with a moving player square.
- */
-class HelloGame extends Application {
- private player: number = 0;
- private speed: number = 200;
-
- protected onInit(): void {
- console.log('HelloGame initialized!');
-
- const registry = this.getRegistry();
-
- // Create player entity
- this.player = registry.create();
-
- // Add Transform component
- registry.emplace(
- this.player,
- TransformType,
- createTransform({ x: this.getWidth() / 2, y: this.getHeight() / 2 })
- );
-
- // Add Sprite component
- registry.emplace(
- this.player,
- SpriteType,
- createSprite(0, { color: { r: 1, g: 0.3, b: 0.3, a: 1 }, size: { x: 50, y: 50 } })
- );
-
- // Add Velocity component
- registry.emplace(this.player, VelocityType, createVelocity());
-
- // Create some background entities
- for (let i = 0; i < 5; i++) {
- const entity = registry.create();
- registry.emplace(
- entity,
- TransformType,
- createTransform({
- x: Math.random() * this.getWidth(),
- y: Math.random() * this.getHeight(),
- })
- );
- registry.emplace(
- entity,
- SpriteType,
- createSprite(0, {
- color: {
- r: Math.random() * 0.5 + 0.5,
- g: Math.random() * 0.5 + 0.5,
- b: Math.random() * 0.5 + 0.5,
- a: 0.8,
- },
- size: { x: 30 + Math.random() * 20, y: 30 + Math.random() * 20 },
- })
- );
- }
-
- // Set clear color
- Renderer.setClearColor(color(0.1, 0.1, 0.15, 1));
- }
-
- protected onUpdate(dt: number): void {
- const registry = this.getRegistry();
-
- // Handle input
- const velocity = registry.get<Velocity>(this.player, VelocityType);
-
- // Reset velocity
- velocity.linear.x = 0;
- velocity.linear.y = 0;
-
- // Keyboard input
- if (Input.isKeyDown(KeyCode.W) || Input.isKeyDown(KeyCode.Up)) {
- velocity.linear.y = -this.speed;
- }
- if (Input.isKeyDown(KeyCode.S) || Input.isKeyDown(KeyCode.Down)) {
- velocity.linear.y = this.speed;
- }
- if (Input.isKeyDown(KeyCode.A) || Input.isKeyDown(KeyCode.Left)) {
- velocity.linear.x = -this.speed;
- }
- if (Input.isKeyDown(KeyCode.D) || Input.isKeyDown(KeyCode.Right)) {
- velocity.linear.x = this.speed;
- }
-
- // Touch input - move towards touch position
- if (Input.isTouchDown()) {
- const touchPos = Input.getTouchPosition();
- const transform = registry.get<Transform>(this.player, TransformType);
-
- const dx = touchPos.x - transform.position.x;
- const dy = touchPos.y - transform.position.y;
- const dist = Math.sqrt(dx * dx + dy * dy);
-
- if (dist > 10) {
- velocity.linear.x = (dx / dist) * this.speed;
- velocity.linear.y = (dy / dist) * this.speed;
- }
- }
-
- // Quit on Escape
- if (Input.isKeyPressed(KeyCode.Escape)) {
- this.quit();
- }
-
- // Update positions based on velocity
- registry.view2<Transform, Velocity>(TransformType, VelocityType).each(
- (entity, transform, vel) => {
- transform.position.x += vel.linear.x * dt;
- transform.position.y += vel.linear.y * dt;
-
- // Keep player on screen
- if (entity === this.player) {
- transform.position.x = Math.max(
- 25,
- Math.min(this.getWidth() - 25, transform.position.x)
- );
- transform.position.y = Math.max(
- 25,
- Math.min(this.getHeight() - 25, transform.position.y)
- );
- }
- }
- );
- }
-
- protected onRender(): void {
- const registry = this.getRegistry();
-
- // Clear screen
- Renderer.clear();
-
- // Set up orthographic projection
- const projection = Renderer.createOrtho2D(
- this.getWidth() * this.getPlatform().getDevicePixelRatio(),
- this.getHeight() * this.getPlatform().getDevicePixelRatio()
- );
- Renderer.beginScene(projection);
-
- // Render all sprites
- registry.view2<Transform, Sprite>(TransformType, SpriteType).each(
- (entity, transform, sprite) => {
- const pos = vec2(
- transform.position.x * this.getPlatform().getDevicePixelRatio(),
- transform.position.y * this.getPlatform().getDevicePixelRatio()
- );
- const size = vec2(
- sprite.size.x * this.getPlatform().getDevicePixelRatio(),
- sprite.size.y * this.getPlatform().getDevicePixelRatio()
- );
-
- // Center the quad
- Renderer.drawQuad(
- { x: pos.x - size.x / 2, y: pos.y - size.y / 2 },
- size,
- sprite.color
- );
- }
- );
-
- Renderer.endScene();
- }
-
- protected onTouch(type: TouchType, point: TouchPoint): void {
- if (type === TouchType.Begin) {
- console.log(`Touch started at (${point.x}, ${point.y})`);
- }
- }
-
- protected onKey(key: KeyCode, pressed: boolean): void {
- if (pressed) {
- console.log(`Key pressed: ${key}`);
- }
- }
-
- protected onShutdown(): void {
- console.log('HelloGame shutdown');
- }
-}
-
-// Start the game with C++ WASM renderer
-const game = new HelloGame({
- title: 'Hello ESEngine',
- width: 800,
- height: 600,
- canvas: 'canvas', // Must match C++ selector "#canvas"
- wasmPath: './esengine.js',
-});
-
-game.run();
diff --git a/sdk/examples/hello-game/rollup.config.js b/sdk/examples/hello-game/rollup.config.js
deleted file mode 100644
index 5708f4aeb..000000000
--- a/sdk/examples/hello-game/rollup.config.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import typescript from '@rollup/plugin-typescript';
-
-export default {
- input: 'index.ts',
- output: {
- file: 'index.js',
- format: 'esm',
- sourcemap: true,
- },
- plugins: [
- typescript({
- tsconfig: './tsconfig.json',
- declaration: false,
- }),
- ],
-};
diff --git a/sdk/examples/playground/package-lock.json b/sdk/examples/playground/package-lock.json
new file mode 100644
index 000000000..a4307c6ac
--- /dev/null
+++ b/sdk/examples/playground/package-lock.json
@@ -0,0 +1,494 @@
+{
+ "name": "test-project",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "test-project",
+ "version": "1.0.0",
+ "dependencies": {
+ "esengine": "file:../.."
+ },
+ "devDependencies": {
+ "esbuild": "^0.20.0",
+ "typescript": "^5.0.0"
+ }
+ },
+ "../..": {
+ "name": "esengine",
+ "version": "0.2.0",
+ "license": "MIT",
+ "devDependencies": {
+ "@rollup/plugin-typescript": "^11.1.5",
+ "rimraf": "^5.0.5",
+ "rollup": "^4.9.0",
+ "rollup-plugin-dts": "^6.1.0",
+ "tslib": "^2.6.2",
+ "typescript": "^5.3.0"
+ }
+ },
+ "../sdk": {
+ "name": "esengine",
+ "version": "0.2.0",
+ "extraneous": true,
+ "license": "MIT",
+ "devDependencies": {
+ "@rollup/plugin-typescript": "^11.1.5",
+ "rimraf": "^5.0.5",
+ "rollup": "^4.9.0",
+ "rollup-plugin-dts": "^6.1.0",
+ "tslib": "^2.6.2",
+ "typescript": "^5.3.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz",
+ "integrity": "sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.20.2.tgz",
+ "integrity": "sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.20.2.tgz",
+ "integrity": "sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.20.2.tgz",
+ "integrity": "sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.20.2.tgz",
+ "integrity": "sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.20.2.tgz",
+ "integrity": "sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.2.tgz",
+ "integrity": "sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.20.2.tgz",
+ "integrity": "sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.20.2.tgz",
+ "integrity": "sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.20.2.tgz",
+ "integrity": "sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.20.2.tgz",
+ "integrity": "sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.20.2.tgz",
+ "integrity": "sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.20.2.tgz",
+ "integrity": "sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.20.2.tgz",
+ "integrity": "sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.20.2.tgz",
+ "integrity": "sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.20.2.tgz",
+ "integrity": "sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.20.2.tgz",
+ "integrity": "sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.20.2.tgz",
+ "integrity": "sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.20.2.tgz",
+ "integrity": "sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.20.2.tgz",
+ "integrity": "sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.20.2.tgz",
+ "integrity": "sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.20.2.tgz",
+ "integrity": "sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.20.2.tgz",
+ "integrity": "sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.2.tgz",
+ "integrity": "sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.20.2",
+ "@esbuild/android-arm": "0.20.2",
+ "@esbuild/android-arm64": "0.20.2",
+ "@esbuild/android-x64": "0.20.2",
+ "@esbuild/darwin-arm64": "0.20.2",
+ "@esbuild/darwin-x64": "0.20.2",
+ "@esbuild/freebsd-arm64": "0.20.2",
+ "@esbuild/freebsd-x64": "0.20.2",
+ "@esbuild/linux-arm": "0.20.2",
+ "@esbuild/linux-arm64": "0.20.2",
+ "@esbuild/linux-ia32": "0.20.2",
+ "@esbuild/linux-loong64": "0.20.2",
+ "@esbuild/linux-mips64el": "0.20.2",
+ "@esbuild/linux-ppc64": "0.20.2",
+ "@esbuild/linux-riscv64": "0.20.2",
+ "@esbuild/linux-s390x": "0.20.2",
+ "@esbuild/linux-x64": "0.20.2",
+ "@esbuild/netbsd-x64": "0.20.2",
+ "@esbuild/openbsd-x64": "0.20.2",
+ "@esbuild/sunos-x64": "0.20.2",
+ "@esbuild/win32-arm64": "0.20.2",
+ "@esbuild/win32-ia32": "0.20.2",
+ "@esbuild/win32-x64": "0.20.2"
+ }
+ },
+ "node_modules/esengine": {
+ "resolved": "../..",
+ "link": true
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ }
+ }
+}
diff --git a/sdk/examples/playground/package.json b/sdk/examples/playground/package.json
new file mode 100644
index 000000000..f5103939e
--- /dev/null
+++ b/sdk/examples/playground/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "test-project",
+ "version": "1.0.0",
+ "type": "module",
+ "scripts": {
+ "build": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap",
+ "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap --watch"
+ },
+ "dependencies": {
+ "esengine": "file:../.."
+ },
+ "devDependencies": {
+ "esbuild": "^0.20.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/sdk/examples/playground/src/main.ts b/sdk/examples/playground/src/main.ts
new file mode 100644
index 000000000..a006d95bb
--- /dev/null
+++ b/sdk/examples/playground/src/main.ts
@@ -0,0 +1,97 @@
+/**
+ * ESEngine Project Entry Point
+ *
+ * This file is the main entry point for your game logic.
+ * Press F5 in the editor to run, or use Web Preview for browser testing.
+ */
+import {
+ type ESEngineModule,
+ App,
+ createWebApp,
+ defineSystem,
+ Schedule,
+ Commands,
+ LocalTransform,
+ Sprite,
+ Camera,
+ Canvas,
+ Res,
+ Time,
+ Query,
+ type Entity
+} from 'esengine';
+
+// =============================================================================
+// Main Entry Point
+// =============================================================================
+
+export async function main(Module: ESEngineModule): Promise<void> {
+ console.log('ESEngine starting...');
+
+ // Create the app with WASM module (handles renderer init + render loop)
+ const app = createWebApp(Module);
+
+ // Add startup system - runs once at beginning
+ app.addSystemToSchedule(Schedule.Startup, defineSystem(
+ [Commands()],
+ (cmds) => {
+ console.log('Startup: Creating entities...');
+
+ // Create camera
+ const camera = cmds.spawn()
+ .insert(Camera, {
+ projectionType: 1, // Orthographic
+ fov: 60,
+ orthoSize: 400,
+ nearPlane: 0.1,
+ farPlane: 1000,
+ aspectRatio: 1,
+ isActive: true,
+ priority: 0
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 10 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+ })
+ .id();
+
+ // Create a test sprite
+ const sprite = cmds.spawn()
+ .insert(Sprite, {
+ texture: 0,
+ color: { x: 1, y: 0.5, z: 0.2, w: 1 },
+ size: { x: 100, y: 100 },
+ uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 },
+ layer: 0,
+ flipX: false,
+ flipY: false
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+ })
+ .id();
+
+ console.log(`Created camera: ${camera}, sprite: ${sprite}`);
+ }
+ ));
+
+ // Add update system - runs every frame
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(LocalTransform, Sprite)],
+ (time, query) => {
+ for (const [entity, transform, sprite] of query) {
+ // Move the sprite in a circle
+ transform.position.x = Math.sin(time.elapsed) * 100;
+ transform.position.y = Math.cos(time.elapsed) * 100;
+ }
+ }
+ ));
+
+ // Start the game loop
+ console.log('Starting game loop...');
+ app.run();
+}
diff --git a/assets/templates/tsconfig.json b/sdk/examples/playground/tsconfig.json
similarity index 100%
rename from assets/templates/tsconfig.json
rename to sdk/examples/playground/tsconfig.json
diff --git a/sdk/package.json b/sdk/package.json
index e5779aa7d..a60e4f672 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -1,11 +1,29 @@
{
"name": "esengine",
- "version": "0.1.0",
+ "version": "0.2.0",
"type": "module",
- "description": "TypeScript SDK for ESEngine - A lightweight 2D game engine for Web and WeChat MiniGames",
- "main": "dist/esengine.cjs.js",
- "module": "dist/esengine.esm.js",
- "types": "dist/index.d.ts",
+ "description": "Modular TypeScript SDK for ESEngine - A lightweight 2D game engine for Web and WeChat MiniGames",
+ "sideEffects": false,
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.js",
+ "types": "./dist/index.d.ts"
+ },
+ "./wasm": {
+ "import": "./dist/wasm.js",
+ "types": "./dist/wasm.d.ts"
+ },
+ "./scene": {
+ "import": "./dist/scene/index.js",
+ "types": "./dist/scene/index.d.ts"
+ },
+ "./assets": {
+ "import": "./dist/assets/index.js",
+ "types": "./dist/assets/index.d.ts"
+ }
+ },
"files": [
"dist"
],
@@ -20,7 +38,8 @@
"ecs",
"webgl",
"wechat-minigame",
- "typescript"
+ "typescript",
+ "modular"
],
"author": "ESEngine Team",
"license": "MIT",
@@ -32,7 +51,6 @@
"tslib": "^2.6.2",
"typescript": "^5.3.0"
},
- "peerDependencies": {},
"repository": {
"type": "git",
"url": "https://github.com/esengine/esengine.git"
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index 9d96a413f..f47a4f8a8 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -1,46 +1,39 @@
import typescript from '@rollup/plugin-typescript';
import dts from 'rollup-plugin-dts';
-const input = 'src/index.ts';
+const modules = {
+ 'index': 'src/index.ts',
+ 'wasm': 'src/wasm.ts',
+ // TODO: Fix imports in scene and assets modules
+ // 'scene/index': 'src/scene/index.ts',
+ // 'assets/index': 'src/assets/index.ts',
+};
-export default [
- // ESM build
- {
+const esmBuilds = Object.entries(modules).map(([name, input]) => ({
input,
output: {
- file: 'dist/esengine.esm.js',
- format: 'esm',
- sourcemap: true,
+ file: `dist/${name}.js`,
+ format: 'esm',
+ sourcemap: true,
},
plugins: [
- typescript({
- tsconfig: './tsconfig.json',
- declaration: false,
- }),
+ typescript({
+ tsconfig: './tsconfig.json',
+ declaration: false,
+ }),
],
- },
- // CommonJS build
- {
- input,
- output: {
- file: 'dist/esengine.cjs.js',
- format: 'cjs',
- sourcemap: true,
+ treeshake: {
+ moduleSideEffects: false,
},
- plugins: [
- typescript({
- tsconfig: './tsconfig.json',
- declaration: false,
- }),
- ],
- },
- // Type declarations
- {
+}));
+
+const dtsBuilds = Object.entries(modules).map(([name, input]) => ({
input,
output: {
- file: 'dist/index.d.ts',
- format: 'esm',
+ file: `dist/${name}.d.ts`,
+ format: 'esm',
},
plugins: [dts()],
- },
-];
+}));
+
+export default [...esmBuilds, ...dtsBuilds];
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
new file mode 100644
index 000000000..aaf1b3572
--- /dev/null
+++ b/sdk/src/app.ts
@@ -0,0 +1,215 @@
+/**
+ * @file app.ts
+ * @brief Application builder and web platform integration
+ */
+
+import { World } from './world';
+import { Schedule, SystemDef, SystemRunner } from './system';
+import { ResourceStorage, Time, TimeData } from './resource';
+import type { ESEngineModule, CppRegistry } from './wasm';
+
+// =============================================================================
+// Plugin Interface
+// =============================================================================
+
+export interface Plugin {
+ build(app: App): void;
+}
+
+// =============================================================================
+// System Entry
+// =============================================================================
+
+interface SystemEntry {
+ system: SystemDef;
+}
+
+// =============================================================================
+// App
+// =============================================================================
+
+export class App {
+ private readonly world_: World;
+ private readonly resources_: ResourceStorage;
+ private readonly systems_ = new Map<Schedule, SystemEntry[]>();
+ private runner_: SystemRunner | null = null;
+
+ private running_ = false;
+ private lastTime_ = 0;
+
+ private module_: ESEngineModule | null = null;
+
+ 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();
+ }
+
+ // =========================================================================
+ // Plugins
+ // =========================================================================
+
+ addPlugin(plugin: Plugin): this {
+ plugin.build(this);
+ return this;
+ }
+
+ // =========================================================================
+ // Systems
+ // =========================================================================
+
+ addSystemToSchedule(schedule: Schedule, system: SystemDef): this {
+ this.systems_.get(schedule)!.push({ system });
+ return this;
+ }
+
+ addSystem(system: SystemDef): this {
+ return this.addSystemToSchedule(Schedule.Update, system);
+ }
+
+ addStartupSystem(system: SystemDef): this {
+ return this.addSystemToSchedule(Schedule.Startup, system);
+ }
+
+ // =========================================================================
+ // C++ Integration
+ // =========================================================================
+
+ connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this {
+ this.world_.connectCpp(cppRegistry);
+
+ if (module) {
+ this.module_ = module;
+ }
+
+ return this;
+ }
+
+ get wasmModule(): ESEngineModule | null {
+ return this.module_;
+ }
+
+ // =========================================================================
+ // 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.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
+
+ 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);
+
+ 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) {
+ 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);
+ }
+}
+
+// =============================================================================
+// Web App Factory
+// =============================================================================
+
+export interface WebAppOptions {
+ getViewportSize?: () => { width: number; height: number };
+}
+
+export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {
+ const app = App.new();
+ const cppRegistry = new module.Registry() as unknown as CppRegistry;
+
+ app.connectCpp(cppRegistry, module);
+
+ module.initRenderer();
+
+ const getViewportSize = options?.getViewportSize ?? (() => ({
+ width: window.innerWidth * (window.devicePixelRatio || 1),
+ height: window.innerHeight * (window.devicePixelRatio || 1)
+ }));
+
+ const renderSystem: SystemDef = {
+ _id: Symbol('RenderSystem'),
+ _name: 'RenderSystem',
+ _params: [],
+ _fn: () => {
+ const { width, height } = getViewportSize();
+ module.renderFrame(cppRegistry, width, height);
+ }
+ };
+
+ app.addSystemToSchedule(Schedule.Last, renderSystem);
+
+ return app;
+}
diff --git a/sdk/src/assets/AssetLoader.ts b/sdk/src/assets/AssetLoader.ts
deleted file mode 100644
index 67c9777ba..000000000
--- a/sdk/src/assets/AssetLoader.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-/**
- * @file AssetLoader.ts
- * @brief Asset loading utilities for textures, shaders, and data files
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-import type { ESEngineModule, CppResourceManager, TextureHandle, ShaderHandle } from '../wasm/types';
-import { TextureFormat } from '../wasm/types';
-
-// =============================================================================
-// Types
-// =============================================================================
-
-export interface TextureData {
- width: number;
- height: number;
- pixels: Uint8Array;
- format: 'RGBA8' | 'RGB8';
-}
-
-export interface ShaderData {
- vertexSource: string;
- fragmentSource: string;
-}
-
-// =============================================================================
-// AssetLoader
-// =============================================================================
-
-export class AssetLoader {
- private module_: ESEngineModule;
- private resourceManager_: CppResourceManager;
- private textureCache_ = new Map<string, TextureHandle>();
- private shaderCache_ = new Map<string, ShaderHandle>();
-
- constructor(module: ESEngineModule, resourceManager: CppResourceManager) {
- this.module_ = module;
- this.resourceManager_ = resourceManager;
- }
-
- // =========================================================================
- // Texture Loading
- // =========================================================================
-
- async loadTexture(url: string): Promise<TextureHandle> {
- const cached = this.textureCache_.get(url);
- if (cached !== undefined) {
- return cached;
- }
-
- const data = await this.fetchTexture(url);
- const handle = this.createTexture(data);
- this.textureCache_.set(url, handle);
- return handle;
- }
-
- createTexture(data: TextureData): TextureHandle {
- const ptr = this.module_._malloc(data.pixels.length);
- this.module_.HEAPU8.set(data.pixels, ptr);
-
- const format = data.format === 'RGBA8' ? TextureFormat.RGBA8 : TextureFormat.RGB8;
- const handle = this.resourceManager_.createTexture(
- data.width, data.height, ptr, data.pixels.length, format
- );
-
- this.module_._free(ptr);
- return handle;
- }
-
- private async fetchTexture(url: string): Promise<TextureData> {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch texture: ${url}`);
- }
-
- const blob = await response.blob();
- const bitmap = await createImageBitmap(blob, { premultiplyAlpha: 'none' });
-
- const canvas = document.createElement('canvas');
- canvas.width = bitmap.width;
- canvas.height = bitmap.height;
-
- const ctx = canvas.getContext('2d')!;
- ctx.drawImage(bitmap, 0, 0);
-
- const imageData = ctx.getImageData(0, 0, bitmap.width, bitmap.height);
-
- return {
- width: bitmap.width,
- height: bitmap.height,
- pixels: new Uint8Array(imageData.data.buffer),
- format: 'RGBA8'
- };
- }
-
- // =========================================================================
- // Shader Loading
- // =========================================================================
-
- async loadShader(url: string): Promise<ShaderHandle> {
- const cached = this.shaderCache_.get(url);
- if (cached !== undefined) {
- return cached;
- }
-
- const data = await this.fetchShader(url);
- const handle = this.resourceManager_.createShader(data.vertexSource, data.fragmentSource);
- this.shaderCache_.set(url, handle);
- return handle;
- }
-
- private async fetchShader(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.parseShader(source);
- }
-
- private parseShader(source: string): ShaderData {
- let vertexSource = '';
- let fragmentSource = '';
- let sharedCode = '';
- let version = '';
-
- const lines = source.split('\n');
- let state: 'global' | 'vertex' | 'fragment' = 'global';
- let currentSection: string[] = [];
-
- for (const line of lines) {
- const trimmed = line.trim();
-
- if (trimmed.startsWith('#pragma')) {
- const parts = trimmed.substring(7).trim().split(/\s+/);
- const directive = parts[0];
-
- if (directive === 'version') {
- version = parts[1] || '';
- } else if (directive === 'vertex') {
- state = 'vertex';
- currentSection = [];
- } else if (directive === 'fragment') {
- state = 'fragment';
- currentSection = [];
- } else if (directive === 'end') {
- if (state === 'vertex') {
- vertexSource = currentSection.join('\n');
- } else if (state === 'fragment') {
- fragmentSource = currentSection.join('\n');
- }
- state = 'global';
- }
- continue;
- }
-
- if (state === 'global') {
- if (trimmed && !trimmed.startsWith('//')) {
- sharedCode += line + '\n';
- }
- } else {
- currentSection.push(line);
- }
- }
-
- const versionLine = version ? `#version ${version}\n` : '';
-
- return {
- vertexSource: versionLine + sharedCode + vertexSource,
- 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
deleted file mode 100644
index f1bc74872..000000000
--- a/sdk/src/assets/index.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * @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/framework/commands.ts b/sdk/src/commands.ts
similarity index 73%
rename from sdk/src/framework/commands.ts
rename to sdk/src/commands.ts
index bd8a69b06..8e1e6963a 100644
--- a/sdk/src/framework/commands.ts
+++ b/sdk/src/commands.ts
@@ -1,20 +1,12 @@
/**
* @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.
+ * @brief Deferred entity/component operations
*/
-import { Entity } from '../core/Types';
-import { ComponentDef } from './component';
-import { Schema, InferSchema } from './types';
-import { World, AnyComponentDef } from './world';
+import { Entity } from './types';
+import { AnyComponentDef, ComponentDef, isBuiltinComponent } from './component';
+import type { World } from './world';
import { ResourceDef, ResourceStorage } from './resource';
-import { BuiltinComponentDef, isBuiltinComponent, getBuiltinDefaults } from './builtin';
// =============================================================================
// Commands Descriptor (for system parameters)
@@ -32,9 +24,14 @@ export function Commands(): CommandsDescriptor {
// Command Types
// =============================================================================
+interface SpawnComponentEntry {
+ component: AnyComponentDef;
+ data: unknown;
+}
+
interface SpawnCommand {
type: 'spawn';
- components: Map<symbol, unknown>;
+ components: SpawnComponentEntry[];
entityRef: { entity: Entity };
}
@@ -62,18 +59,12 @@ interface InsertResourceCommand {
value: unknown;
}
-interface RemoveResourceCommand {
- type: 'remove_resource';
- resource: ResourceDef<unknown>;
-}
-
type Command =
| SpawnCommand
| DespawnCommand
| InsertCommand
| RemoveCommand
- | InsertResourceCommand
- | RemoveResourceCommand;
+ | InsertResourceCommand;
// =============================================================================
// Entity Commands (Builder for spawning)
@@ -82,7 +73,7 @@ type Command =
export class EntityCommands {
private readonly commands_: CommandsInstance;
private readonly entityRef_: { entity: Entity };
- private readonly components_ = new Map<symbol, unknown>();
+ private readonly components_: SpawnComponentEntry[] = [];
private isNew_: boolean;
constructor(commands: CommandsInstance, entity: Entity | null) {
@@ -101,14 +92,13 @@ export class EntityCommands {
let instance: unknown;
if (isBuiltinComponent(component)) {
- const defaults = getBuiltinDefaults(component) as object;
- instance = { ...defaults, ...(data as object) };
+ instance = { ...component._default, ...(data as object) };
} else {
- instance = (component as ComponentDef<Schema>).create(data as never);
+ instance = (component as ComponentDef<T>).create(data);
}
if (this.isNew_) {
- this.components_.set(component._id, instance);
+ this.components_.push({ component, data: instance });
} else {
this.commands_.queueInsert(this.entityRef_.entity, component, instance);
}
@@ -132,7 +122,8 @@ export class EntityCommands {
private finalize(): void {
if (this.isNew_) {
- this.commands_.queueSpawn(this.components_, this.entityRef_);
+ this.commands_.spawnImmediate(this.components_, this.entityRef_);
+ this.isNew_ = false;
}
}
}
@@ -173,18 +164,6 @@ export class CommandsInstance {
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 });
}
@@ -193,6 +172,15 @@ export class CommandsInstance {
this.pending_.push({ type: 'remove', entity, component });
}
+ spawnImmediate(components: SpawnComponentEntry[], entityRef: { entity: Entity }): void {
+ const entity = this.world_.spawn();
+ entityRef.entity = entity;
+
+ for (const entry of components) {
+ this.world_.insert(entity, entry.component, entry.data);
+ }
+ }
+
flush(): void {
for (const cmd of this.pending_) {
this.executeCommand(cmd);
@@ -205,10 +193,8 @@ export class CommandsInstance {
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);
+ for (const entry of cmd.components) {
+ this.world_.insert(entity, entry.component, entry.data);
}
break;
}
@@ -218,7 +204,7 @@ export class CommandsInstance {
break;
case 'insert':
- this.world_.insert(cmd.entity, cmd.component, cmd.data as never);
+ this.world_.insert(cmd.entity, cmd.component, cmd.data);
break;
case 'remove':
@@ -228,10 +214,6 @@ export class CommandsInstance {
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/component.ts b/sdk/src/component.ts
new file mode 100644
index 000000000..a3ed16ef9
--- /dev/null
+++ b/sdk/src/component.ts
@@ -0,0 +1,199 @@
+/**
+ * @file component.ts
+ * @brief Component definition and builtin components
+ */
+
+import { Entity, Vec2, Vec3, Vec4, Quat } from './types';
+
+// =============================================================================
+// Component Definition
+// =============================================================================
+
+export interface ComponentDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _default: T;
+ readonly _builtin: false;
+ create(data?: Partial<T>): T;
+}
+
+let componentCounter = 0;
+
+export function defineComponent<T extends object>(
+ name: string,
+ defaults: T
+): ComponentDef<T> {
+ const id = ++componentCounter;
+ return {
+ _id: Symbol(`Component_${id}_${name}`),
+ _name: name,
+ _default: defaults,
+ _builtin: false,
+ create(data?: Partial<T>): T {
+ return { ...defaults, ...data };
+ }
+ };
+}
+
+export function defineTag(name: string): ComponentDef<{}> {
+ return defineComponent(name, {});
+}
+
+// =============================================================================
+// Builtin Component Definition (C++ backed)
+// =============================================================================
+
+export interface BuiltinComponentDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _cppName: string;
+ readonly _builtin: true;
+ readonly _default: T;
+}
+
+function defineBuiltin<T>(name: string, defaults: T): BuiltinComponentDef<T> {
+ return {
+ _id: Symbol(`Builtin_${name}`),
+ _name: name,
+ _cppName: name,
+ _builtin: true,
+ _default: defaults
+ };
+}
+
+// =============================================================================
+// Component Type Union
+// =============================================================================
+
+export type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
+
+export function isBuiltinComponent(comp: AnyComponentDef): comp is BuiltinComponentDef<any> {
+ return comp._builtin === true;
+}
+
+// =============================================================================
+// Builtin Component Types
+// =============================================================================
+
+export interface LocalTransformData {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+
+export interface WorldTransformData {
+ 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[];
+}
+
+// =============================================================================
+// Builtin Component Instances
+// =============================================================================
+
+export const LocalTransform = defineBuiltin<LocalTransformData>('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 const WorldTransform = defineBuiltin<WorldTransformData>('WorldTransform', {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+});
+
+export const Sprite = defineBuiltin<SpriteData>('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 const Camera = defineBuiltin<CameraData>('Camera', {
+ projectionType: 0,
+ fov: 60,
+ orthoSize: 5,
+ nearPlane: 0.1,
+ farPlane: 1000,
+ aspectRatio: 1.77,
+ isActive: true,
+ priority: 0
+});
+
+export const Canvas = defineBuiltin<CanvasData>('Canvas', {
+ designResolution: { x: 1920, y: 1080 },
+ pixelsPerUnit: 100,
+ scaleMode: 0,
+ matchWidthOrHeight: 0.5,
+ backgroundColor: { x: 0, y: 0, z: 0, w: 1 }
+});
+
+export const Velocity = defineBuiltin<VelocityData>('Velocity', {
+ linear: { x: 0, y: 0, z: 0 },
+ angular: { x: 0, y: 0, z: 0 }
+});
+
+export const Parent = defineBuiltin<ParentData>('Parent', {
+ entity: 0 as Entity
+});
+
+export const Children = defineBuiltin<ChildrenData>('Children', {
+ entities: []
+});
+
+// =============================================================================
+// Type Helpers
+// =============================================================================
+
+export type ComponentData<C> =
+ C extends BuiltinComponentDef<infer T> ? T :
+ C extends ComponentDef<infer T> ? T :
+ never;
diff --git a/sdk/src/core/Application.ts b/sdk/src/core/Application.ts
deleted file mode 100644
index 9f6cafa4b..000000000
--- a/sdk/src/core/Application.ts
+++ /dev/null
@@ -1,372 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Application Base Class
- *
- * Provides the main entry point and lifecycle management for games.
- */
-
-import {
- ApplicationConfig,
- TouchType,
- TouchPoint,
- KeyCode,
- RendererBackend,
-} from './Types';
-import { loadWasmModule, isWasmLoaded, WasmLoadOptions } from './WasmBridge';
-import { Registry } from '../ecs/Registry';
-import { SystemGroup } from '../ecs/System';
-import { Input } from '../input/Input';
-import { Platform, PlatformConfig } from '../platform/Platform';
-import { Renderer, RendererMode } from '../renderer/Renderer';
-
-/**
- * Application - Base class for games.
- * Extend this class and override lifecycle methods to create your game.
- */
-export abstract class Application {
- private static instance: Application | null = null;
-
- protected config: Required<ApplicationConfig>;
- protected platform: Platform;
- protected registry: Registry;
- protected systems: SystemGroup;
- protected running: boolean = false;
- protected deltaTime: number = 0;
- protected animationFrameId: number = 0;
- protected rendererMode: RendererMode = RendererMode.Native;
-
- constructor(config: ApplicationConfig = {}) {
- if (Application.instance) {
- throw new Error('Only one Application instance can exist');
- }
- Application.instance = this;
-
- // Determine renderer backend
- const hasWasm = !!config.wasmPath;
- const requestedBackend = config.renderer ?? (hasWasm ? RendererBackend.Wasm : RendererBackend.Native);
-
- // Warn if Wasm requested but no path provided
- if (requestedBackend === RendererBackend.Wasm && !hasWasm) {
- console.warn(
- '[ESEngine] Wasm backend requested but wasmPath not provided. ' +
- 'Falling back to Native. Provide wasmPath for C++ rendering.'
- );
- }
-
- // Apply default configuration
- this.config = {
- title: config.title ?? 'ESEngine Application',
- width: config.width ?? 800,
- height: config.height ?? 600,
- canvas: config.canvas ?? undefined as unknown as HTMLCanvasElement,
- vsync: config.vsync ?? true,
- wasmPath: config.wasmPath ?? '',
- renderer: requestedBackend,
- };
-
- // Initialize systems
- this.registry = new Registry();
- this.systems = new SystemGroup();
-
- // Create platform
- this.platform = Platform.create();
- }
-
- /**
- * Get the singleton application instance.
- */
- static get(): Application {
- if (!Application.instance) {
- throw new Error('No Application instance exists');
- }
- return Application.instance;
- }
-
- /**
- * Start the application main loop.
- * This is an async method that loads WASM if configured.
- */
- async run(): Promise<void> {
- if (this.running) return;
-
- // For WASM mode, we need to set up canvas first, then load WASM
- // because Emscripten needs the canvas to create WebGL context
- let canvas: HTMLCanvasElement | null = null;
-
- // Get or create canvas element
- if (this.config.canvas) {
- if (typeof this.config.canvas === 'string') {
- canvas = document.getElementById(this.config.canvas) as HTMLCanvasElement;
- } else {
- canvas = this.config.canvas;
- }
- }
-
- if (!canvas && typeof document !== 'undefined') {
- canvas = document.createElement('canvas');
- canvas.id = 'esengine-canvas';
- document.body.appendChild(canvas);
- }
-
- // Set canvas size
- if (canvas) {
- const dpr = window.devicePixelRatio ?? 1;
- canvas.width = this.config.width * dpr;
- canvas.height = this.config.height * dpr;
- canvas.style.width = `${this.config.width}px`;
- canvas.style.height = `${this.config.height}px`;
- }
-
- // Load WASM module if configured for Wasm backend
- if (this.config.renderer === RendererBackend.Wasm && this.config.wasmPath) {
- try {
- console.log('[ESEngine] Loading WASM module...');
- const wasmOptions: WasmLoadOptions | undefined = canvas ? {
- canvas,
- width: this.config.width,
- height: this.config.height,
- } : undefined;
- await loadWasmModule(this.config.wasmPath, wasmOptions);
- this.rendererMode = RendererMode.Wasm;
- console.log('[ESEngine] WASM module loaded, using C++ renderer');
- } catch (error) {
- console.error('[ESEngine] Failed to load WASM module:', error);
- console.warn('[ESEngine] Falling back to Native renderer');
- this.rendererMode = RendererMode.Native;
- }
- } else {
- this.rendererMode = RendererMode.Native;
- if (this.config.renderer === RendererBackend.Wasm) {
- console.warn('[ESEngine] Using Native renderer (no wasmPath configured)');
- }
- }
-
- // Initialize platform (skip GL context creation if using WASM)
- const isWasmMode = this.rendererMode === RendererMode.Wasm;
- const platformConfig: PlatformConfig = {
- width: this.config.width,
- height: this.config.height,
- canvas: canvas ?? this.config.canvas,
- skipGLContext: isWasmMode, // Don't create GL context - C++ owns it
- };
-
- if (!this.platform.initialize(platformConfig)) {
- console.error('Failed to initialize platform');
- return;
- }
-
- // Initialize input
- Input.init();
-
- // Set up platform callbacks
- this.platform.setTouchCallback((type, point) => {
- Input.onTouchEvent(type, point);
- this.onTouch(type, point);
- });
-
- this.platform.setKeyCallback((key, pressed) => {
- Input.onKeyEvent(key, pressed);
- this.onKey(key, pressed);
- });
-
- this.platform.setResizeCallback((width, height) => {
- this.config.width = width;
- this.config.height = height;
- this.onResize(width, height);
- });
-
- // Initialize renderer with appropriate mode
- if (isWasmMode) {
- // WASM mode: C++ handles WebGL, no TypeScript GL context needed
- Renderer.init(null, this.rendererMode);
- } else {
- // Native mode: TypeScript handles WebGL
- const gl = this.platform.getGL();
- if (gl) {
- Renderer.init(gl, this.rendererMode);
- Renderer.setViewport(
- 0,
- 0,
- this.config.width * this.platform.getDevicePixelRatio(),
- this.config.height * this.platform.getDevicePixelRatio()
- );
- }
- }
-
- // Initialize systems
- this.systems.init(this.registry);
-
- // Call user initialization
- this.onInit();
-
- // Start game loop
- this.running = true;
- this.gameLoop();
- }
-
- /**
- * Request the application to quit.
- */
- quit(): void {
- this.running = false;
- }
-
- /**
- * Get the platform instance.
- */
- getPlatform(): Platform {
- return this.platform;
- }
-
- /**
- * Get the ECS registry.
- */
- getRegistry(): Registry {
- return this.registry;
- }
-
- /**
- * Get the system group.
- */
- getSystems(): SystemGroup {
- return this.systems;
- }
-
- /**
- * Get the window width.
- */
- getWidth(): number {
- return this.config.width;
- }
-
- /**
- * Get the window height.
- */
- getHeight(): number {
- return this.config.height;
- }
-
- /**
- * Get the time since last frame.
- */
- getDeltaTime(): number {
- return this.deltaTime;
- }
-
- /**
- * Check if the application is running.
- */
- isRunning(): boolean {
- return this.running;
- }
-
- /**
- * Check if using WASM renderer.
- */
- isUsingWasm(): boolean {
- return this.rendererMode === RendererMode.Wasm && isWasmLoaded();
- }
-
- // ========== Lifecycle Methods (Override in subclass) ==========
-
- /**
- * Called once when the application initializes.
- */
- protected onInit(): void {}
-
- /**
- * Called every frame to update game logic.
- */
- protected onUpdate(deltaTime: number): void {}
-
- /**
- * Called every frame to render the game.
- */
- protected onRender(): void {}
-
- /**
- * Called when the application shuts down.
- */
- protected onShutdown(): void {}
-
- /**
- * Called when a touch event occurs.
- */
- protected onTouch(type: TouchType, point: TouchPoint): void {}
-
- /**
- * Called when a key event occurs.
- */
- protected onKey(key: KeyCode, pressed: boolean): void {}
-
- /**
- * Called when the window is resized.
- */
- protected onResize(width: number, height: number): void {}
-
- // ========== Private Methods ==========
-
- private gameLoop = (): void => {
- if (!this.running) {
- this.shutdown();
- return;
- }
-
- // Poll events and update timing
- this.platform.pollEvents();
- this.deltaTime = this.platform.getDeltaTime();
-
- // Update input state
- Input.update();
-
- // Begin frame
- Renderer.beginFrame();
-
- // Update systems
- this.systems.update(this.registry, this.deltaTime);
-
- // Update game
- this.onUpdate(this.deltaTime);
-
- // Render game
- this.onRender();
-
- // End frame
- Renderer.endFrame();
-
- // Swap buffers
- this.platform.swapBuffers();
-
- // Request next frame
- if (typeof requestAnimationFrame !== 'undefined') {
- this.animationFrameId = requestAnimationFrame(this.gameLoop);
- } else {
- // Fallback for environments without requestAnimationFrame
- setTimeout(this.gameLoop, 16);
- }
- };
-
- private shutdown(): void {
- // Cancel animation frame
- if (this.animationFrameId) {
- cancelAnimationFrame(this.animationFrameId);
- }
-
- // Call user shutdown
- this.onShutdown();
-
- // Shutdown systems
- this.systems.shutdown(this.registry);
-
- // Shutdown renderer
- Renderer.shutdown();
-
- // Shutdown input
- Input.shutdown();
-
- // Shutdown platform
- this.platform.shutdown();
-
- // Clear singleton
- Application.instance = null;
- }
-}
diff --git a/sdk/src/core/Types.ts b/sdk/src/core/Types.ts
deleted file mode 100644
index bad3e041a..000000000
--- a/sdk/src/core/Types.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Core Type Definitions
- *
- * Provides fundamental types used throughout the engine.
- */
-
-// Entity type - unique identifier for game objects
-export type Entity = number;
-
-// Invalid entity constant
-export const INVALID_ENTITY: Entity = 0xffffffff;
-
-// Component type identifier
-export type ComponentType = number;
-
-// 2D Vector
-export interface Vec2 {
- x: number;
- y: number;
-}
-
-// 3D Vector
-export interface Vec3 {
- x: number;
- y: number;
- z: number;
-}
-
-// 4D Vector
-export interface Vec4 {
- x: number;
- y: number;
- z: number;
- w: number;
-}
-
-// RGBA Color (0-1 range)
-export interface Color {
- r: number;
- g: number;
- b: number;
- a: number;
-}
-
-// Matrix 4x4 (column-major, compatible with WebGL)
-export type Mat4 = Float32Array;
-
-// Touch event types
-export enum TouchType {
- Begin = 0,
- Move = 1,
- End = 2,
- Cancel = 3,
-}
-
-// Touch point data
-export interface TouchPoint {
- id: number;
- x: number;
- y: number;
-}
-
-// Keyboard key codes
-export enum KeyCode {
- Unknown = 0,
-
- // Special keys
- Backspace = 8,
- Tab = 9,
- Enter = 13,
- Shift = 16,
- Control = 17,
- Alt = 18,
- Escape = 27,
- Space = 32,
-
- // Arrow keys
- Left = 37,
- Up = 38,
- Right = 39,
- Down = 40,
-
- // Number keys
- Digit0 = 48,
- Digit1 = 49,
- Digit2 = 50,
- Digit3 = 51,
- Digit4 = 52,
- Digit5 = 53,
- Digit6 = 54,
- Digit7 = 55,
- Digit8 = 56,
- Digit9 = 57,
-
- // Letter keys
- A = 65,
- B = 66,
- C = 67,
- D = 68,
- E = 69,
- F = 70,
- G = 71,
- H = 72,
- I = 73,
- J = 74,
- K = 75,
- L = 76,
- M = 77,
- N = 78,
- O = 79,
- P = 80,
- Q = 81,
- R = 82,
- S = 83,
- T = 84,
- U = 85,
- V = 86,
- W = 87,
- X = 88,
- Y = 89,
- Z = 90,
-}
-
-// Renderer mode
-export enum RendererBackend {
- /** Use C++ WASM backend (recommended for production) */
- Wasm = 'wasm',
- /** Use pure TypeScript/WebGL (fallback, no WASM required) */
- Native = 'native',
-}
-
-// Application configuration
-export interface ApplicationConfig {
- title?: string;
- width?: number;
- height?: number;
- canvas?: HTMLCanvasElement | string;
- vsync?: boolean;
- /** Path to WASM module (e.g., 'esengine.js'). Required for Wasm backend. */
- wasmPath?: string;
- /** Renderer backend. Defaults to Wasm if wasmPath is provided, otherwise Native. */
- renderer?: RendererBackend;
-}
-
-// Renderer statistics
-export interface RendererStats {
- drawCalls: number;
- triangleCount: number;
- vertexCount: number;
-}
-
-// Utility functions for creating vectors and colors
-export function vec2(x: number = 0, y: number = 0): Vec2 {
- return { x, y };
-}
-
-export function vec3(x: number = 0, y: number = 0, z: number = 0): Vec3 {
- return { x, y, z };
-}
-
-export function vec4(
- x: number = 0,
- y: number = 0,
- z: number = 0,
- w: number = 0
-): Vec4 {
- return { x, y, z, w };
-}
-
-export function color(
- r: number = 1,
- g: number = 1,
- b: number = 1,
- a: number = 1
-): Color {
- return { r, g, b, a };
-}
-
-// Create identity matrix
-export function mat4Identity(): Mat4 {
- const m = new Float32Array(16);
- m[0] = 1;
- m[5] = 1;
- m[10] = 1;
- m[15] = 1;
- return m;
-}
-
-// Create orthographic projection matrix
-export function mat4Ortho(
- left: number,
- right: number,
- bottom: number,
- top: number,
- near: number,
- far: number
-): Mat4 {
- const m = new Float32Array(16);
- const lr = 1 / (left - right);
- const bt = 1 / (bottom - top);
- const nf = 1 / (near - far);
-
- m[0] = -2 * lr;
- m[5] = -2 * bt;
- m[10] = 2 * nf;
- m[12] = (left + right) * lr;
- m[13] = (top + bottom) * bt;
- m[14] = (far + near) * nf;
- m[15] = 1;
-
- return m;
-}
diff --git a/sdk/src/core/WasmBridge.ts b/sdk/src/core/WasmBridge.ts
deleted file mode 100644
index c1158ca7f..000000000
--- a/sdk/src/core/WasmBridge.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-/**
- * ESEngine TypeScript SDK - WASM Bridge
- *
- * Provides interface for interacting with the C++ WASM module.
- */
-
-/**
- * ESEngine WASM Module interface.
- * Defines the functions exported from the C++ code.
- */
-export interface ESEngineModule {
- // Memory management
- HEAPF32: Float32Array;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- _malloc(size: number): number;
- _free(ptr: number): void;
-
- // Core lifecycle
- _es_init(width: number, height: number): void;
- _es_update(deltaTime: number): void;
- _es_render(): void;
- _es_shutdown(): void;
-
- // Input handling
- _es_on_touch(type: number, x: number, y: number): void;
- _es_on_key?(keyCode: number, pressed: number): void;
-
- // Renderer
- _es_renderer_clear?(r: number, g: number, b: number, a: number): void;
- _es_renderer_begin_scene?(vpMatrixPtr: number): void;
- _es_renderer_end_scene?(): void;
- _es_renderer_draw_quad?(
- x: number,
- y: number,
- w: number,
- h: number,
- r: number,
- g: number,
- b: number,
- a: number
- ): void;
- _es_renderer_draw_quad_textured?(
- x: number,
- y: number,
- w: number,
- h: number,
- texId: number,
- r: number,
- g: number,
- b: number,
- a: number
- ): void;
-
- // Emscripten canvas/context
- canvas?: HTMLCanvasElement;
-
- // Runtime methods
- ccall(
- name: string,
- returnType: string | null,
- argTypes: string[],
- args: unknown[]
- ): unknown;
- cwrap(
- name: string,
- returnType: string | null,
- argTypes: string[]
- ): (...args: unknown[]) => unknown;
-}
-
-/**
- * WASM load options.
- */
-export interface WasmLoadOptions {
- canvas: HTMLCanvasElement;
- width: number;
- height: number;
-}
-
-/**
- * Global reference to the loaded WASM module.
- */
-let wasmModule: ESEngineModule | null = null;
-
-/**
- * Check if WASM module is loaded.
- */
-export function isWasmLoaded(): boolean {
- return wasmModule !== null;
-}
-
-/**
- * Get the loaded WASM module.
- * Throws if module is not loaded.
- */
-export function getWasmModule(): ESEngineModule {
- if (!wasmModule) {
- throw new Error('WASM module not loaded. Call loadWasmModule first.');
- }
- return wasmModule;
-}
-
-/**
- * Set the WASM module reference.
- * Called when the module is loaded externally.
- */
-export function setWasmModule(module: ESEngineModule): void {
- wasmModule = module;
-}
-
-/**
- * Load the WASM module from the specified path.
- *
- * @param wasmPath Path to the .js loader file (e.g., 'esengine.js')
- * @param options Canvas and dimensions for WebGL context
- * @returns Promise that resolves to the loaded module
- */
-export async function loadWasmModule(
- wasmPath: string,
- options?: WasmLoadOptions
-): Promise<ESEngineModule> {
- if (wasmModule) {
- return wasmModule;
- }
-
- return new Promise((resolve, reject) => {
- // Create Module configuration
- // Emscripten will add exports like _malloc, _free to this object
- const moduleConfig: Partial<ESEngineModule> & Record<string, unknown> = {
- // Pass canvas element to Emscripten so it can create WebGL context
- canvas: options?.canvas,
- locateFile: (path: string) => {
- // Handle .wasm file location
- if (path.endsWith('.wasm')) {
- const basePath = wasmPath.substring(0, wasmPath.lastIndexOf('/') + 1);
- return basePath + path;
- }
- return path;
- },
- print: (text: string) => console.log('[ESEngine C++]', text),
- printErr: (text: string) => console.error('[ESEngine C++]', text),
- };
-
- // onRuntimeInitialized is called after all exports are attached to moduleConfig
- moduleConfig.onRuntimeInitialized = () => {
- // moduleConfig now has _malloc, _free, etc. attached by Emscripten
- wasmModule = moduleConfig as ESEngineModule;
-
- // Initialize C++ renderer if options provided
- if (options && wasmModule._es_init) {
- wasmModule._es_init(options.width, options.height);
- }
-
- resolve(wasmModule);
- };
-
- // Set global Module before loading script
- (window as unknown as { Module: unknown }).Module = moduleConfig;
-
- // Load the WASM loader script
- const script = document.createElement('script');
- script.src = wasmPath;
- script.onerror = () => reject(new Error(`Failed to load WASM module: ${wasmPath}`));
- document.head.appendChild(script);
- });
-}
-
-/**
- * Initialize C++ renderer (call after WASM is loaded).
- */
-export function initWasmRenderer(width: number, height: number): void {
- const module = getWasmModule();
- if (module._es_init) {
- module._es_init(width, height);
- }
-}
-
-/**
- * Allocate memory in WASM heap and copy a Float32Array.
- */
-export function allocFloat32Array(data: Float32Array): number {
- const module = getWasmModule();
- const ptr = module._malloc(data.length * 4);
- module.HEAPF32.set(data, ptr >> 2);
- return ptr;
-}
-
-/**
- * Allocate memory in WASM heap and copy a Uint8Array.
- */
-export function allocUint8Array(data: Uint8Array): number {
- const module = getWasmModule();
- const ptr = module._malloc(data.length);
- module.HEAPU8.set(data, ptr);
- return ptr;
-}
-
-/**
- * Free previously allocated WASM memory.
- */
-export function freePtr(ptr: number): void {
- if (ptr && wasmModule) {
- wasmModule._free(ptr);
- }
-}
-
-/**
- * Execute a callback with a temporary Float32Array allocation.
- */
-export function withFloat32Array<T>(
- data: Float32Array,
- callback: (ptr: number) => T
-): T {
- const ptr = allocFloat32Array(data);
- try {
- return callback(ptr);
- } finally {
- freePtr(ptr);
- }
-}
diff --git a/sdk/src/ecs/Components.ts b/sdk/src/ecs/Components.ts
deleted file mode 100644
index c4a896014..000000000
--- a/sdk/src/ecs/Components.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Built-in Components
- *
- * Provides standard component types for common game functionality.
- */
-
-import { Vec2, Vec3, Color, color, vec3 } from '../core/Types';
-
-/**
- * Transform component - Position, rotation, and scale in world space.
- */
-export interface Transform {
- position: Vec3;
- rotation: Vec3; // Euler angles in radians
- scale: Vec3;
-}
-
-/**
- * Create a new Transform with default values.
- */
-export function createTransform(
- position: Partial<Vec3> = {},
- rotation: Partial<Vec3> = {},
- scale: Partial<Vec3> = {}
-): Transform {
- return {
- position: { x: position.x ?? 0, y: position.y ?? 0, z: position.z ?? 0 },
- rotation: { x: rotation.x ?? 0, y: rotation.y ?? 0, z: rotation.z ?? 0 },
- scale: { x: scale.x ?? 1, y: scale.y ?? 1, z: scale.z ?? 1 },
- };
-}
-
-/**
- * Velocity component - Linear and angular velocity.
- */
-export interface Velocity {
- linear: Vec3; // Units per second
- angular: Vec3; // Radians per second
-}
-
-/**
- * Create a new Velocity with default values.
- */
-export function createVelocity(
- linear: Partial<Vec3> = {},
- angular: Partial<Vec3> = {}
-): Velocity {
- return {
- linear: { x: linear.x ?? 0, y: linear.y ?? 0, z: linear.z ?? 0 },
- angular: { x: angular.x ?? 0, y: angular.y ?? 0, z: angular.z ?? 0 },
- };
-}
-
-/**
- * Sprite component - Visual representation for 2D rendering.
- */
-export interface Sprite {
- textureId: number;
- color: Color;
- size: Vec2;
- uvOffset: Vec2;
- uvScale: Vec2;
- layer: number;
-}
-
-/**
- * Create a new Sprite with default values.
- */
-export function createSprite(
- textureId: number = 0,
- options: {
- color?: Partial<Color>;
- size?: Partial<Vec2>;
- uvOffset?: Partial<Vec2>;
- uvScale?: Partial<Vec2>;
- layer?: number;
- } = {}
-): Sprite {
- return {
- textureId,
- color: {
- r: options.color?.r ?? 1,
- g: options.color?.g ?? 1,
- b: options.color?.b ?? 1,
- a: options.color?.a ?? 1,
- },
- size: { x: options.size?.x ?? 1, y: options.size?.y ?? 1 },
- uvOffset: { x: options.uvOffset?.x ?? 0, y: options.uvOffset?.y ?? 0 },
- uvScale: { x: options.uvScale?.x ?? 1, y: options.uvScale?.y ?? 1 },
- layer: options.layer ?? 0,
- };
-}
-
-/**
- * Name component - Human-readable identifier.
- */
-export interface Name {
- value: string;
-}
-
-/**
- * Create a new Name component.
- */
-export function createName(value: string): Name {
- return { value };
-}
-
-/**
- * Tag components - Empty marker components for filtering.
- */
-export interface Active {}
-export interface Visible {}
-export interface Static {}
-
-/**
- * Create an Active tag.
- */
-export function createActive(): Active {
- return {};
-}
-
-/**
- * Create a Visible tag.
- */
-export function createVisible(): Visible {
- return {};
-}
-
-/**
- * Create a Static tag.
- */
-export function createStatic(): Static {
- return {};
-}
-
-// =============================================================================
-// 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');
-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/ecs/Entity.ts b/sdk/src/ecs/Entity.ts
deleted file mode 100644
index 8406ab97d..000000000
--- a/sdk/src/ecs/Entity.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Entity Management
- *
- * Provides entity creation and validation utilities.
- */
-
-import { Entity, INVALID_ENTITY } from '../core/Types';
-
-// Entity ID generation
-let nextEntityId: Entity = 0;
-const recycledIds: Entity[] = [];
-
-/**
- * Generate a new entity ID.
- * Reuses recycled IDs when available.
- */
-export function generateEntityId(): Entity {
- if (recycledIds.length > 0) {
- return recycledIds.pop()!;
- }
- return nextEntityId++;
-}
-
-/**
- * Recycle an entity ID for reuse.
- */
-export function recycleEntityId(entity: Entity): void {
- recycledIds.push(entity);
-}
-
-/**
- * Check if an entity ID is valid (not INVALID_ENTITY).
- */
-export function isValidEntity(entity: Entity): boolean {
- return entity !== INVALID_ENTITY;
-}
-
-/**
- * Reset entity ID generation (for testing).
- */
-export function resetEntityIds(): void {
- nextEntityId = 0;
- recycledIds.length = 0;
-}
diff --git a/sdk/src/ecs/Registry.ts b/sdk/src/ecs/Registry.ts
deleted file mode 100644
index 0bcee1f05..000000000
--- a/sdk/src/ecs/Registry.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-/**
- * ESEngine TypeScript SDK - ECS Registry
- *
- * Central registry for managing entities and components.
- * Uses sparse set storage for efficient component access.
- */
-
-import { Entity, INVALID_ENTITY } from '../core/Types';
-import { generateEntityId, recycleEntityId, isValidEntity } from './Entity';
-import { View, View2, View3, View4 } from './View';
-
-// Component pool type
-type ComponentPool<T> = Map<Entity, T>;
-
-// Component type identifier
-type ComponentKey = symbol | string;
-
-/**
- * Registry - Central manager for entities and components.
- */
-export class Registry {
- private entities: Set<Entity> = new Set();
- private componentPools: Map<ComponentKey, ComponentPool<unknown>> = new Map();
- private entityComponents: Map<Entity, Set<ComponentKey>> = new Map();
-
- /**
- * Create a new entity.
- */
- create(): Entity {
- const entity = generateEntityId();
- this.entities.add(entity);
- this.entityComponents.set(entity, new Set());
- return entity;
- }
-
- /**
- * Create multiple entities at once.
- */
- createMany(count: number): Entity[] {
- const entities: Entity[] = [];
- for (let i = 0; i < count; i++) {
- entities.push(this.create());
- }
- return entities;
- }
-
- /**
- * Destroy an entity and all its components.
- */
- destroy(entity: Entity): void {
- if (!this.valid(entity)) return;
-
- // Remove all components
- const components = this.entityComponents.get(entity);
- if (components) {
- for (const key of components) {
- const pool = this.componentPools.get(key);
- if (pool) {
- pool.delete(entity);
- }
- }
- }
-
- // Remove entity
- this.entities.delete(entity);
- this.entityComponents.delete(entity);
- recycleEntityId(entity);
- }
-
- /**
- * Check if an entity is valid (exists in the registry).
- */
- valid(entity: Entity): boolean {
- return isValidEntity(entity) && this.entities.has(entity);
- }
-
- /**
- * Get the number of entities in the registry.
- */
- entityCount(): number {
- return this.entities.size;
- }
-
- /**
- * Add a component to an entity.
- *
- * @param entity The entity to add the component to
- * @param key The component type identifier (symbol or string)
- * @param component The component data
- * @returns The component that was added
- */
- emplace<T>(entity: Entity, key: ComponentKey, component: T): T {
- if (!this.valid(entity)) {
- throw new Error(`Cannot add component to invalid entity: ${entity}`);
- }
-
- let pool = this.componentPools.get(key) as ComponentPool<T> | undefined;
- if (!pool) {
- pool = new Map<Entity, T>();
- this.componentPools.set(key, pool as ComponentPool<unknown>);
- }
-
- pool.set(entity, component);
- this.entityComponents.get(entity)!.add(key);
-
- return component;
- }
-
- /**
- * Add or replace a component on an entity.
- */
- emplaceOrReplace<T>(entity: Entity, key: ComponentKey, component: T): T {
- return this.emplace(entity, key, component);
- }
-
- /**
- * Remove a component from an entity.
- */
- remove(entity: Entity, key: ComponentKey): void {
- if (!this.valid(entity)) return;
-
- const pool = this.componentPools.get(key);
- if (pool) {
- pool.delete(entity);
- }
-
- const components = this.entityComponents.get(entity);
- if (components) {
- components.delete(key);
- }
- }
-
- /**
- * Get a component from an entity.
- * Throws if the entity doesn't have the component.
- */
- get<T>(entity: Entity, key: ComponentKey): T {
- const component = this.tryGet<T>(entity, key);
- if (component === undefined) {
- throw new Error(
- `Entity ${entity} does not have component: ${String(key)}`
- );
- }
- return component;
- }
-
- /**
- * Try to get a component from an entity.
- * Returns undefined if the entity doesn't have the component.
- */
- tryGet<T>(entity: Entity, key: ComponentKey): T | undefined {
- if (!this.valid(entity)) return undefined;
-
- const pool = this.componentPools.get(key) as ComponentPool<T> | undefined;
- if (!pool) return undefined;
-
- return pool.get(entity);
- }
-
- /**
- * Get a component or add it if it doesn't exist.
- */
- getOrEmplace<T>(
- entity: Entity,
- key: ComponentKey,
- defaultComponent: T
- ): T {
- const existing = this.tryGet<T>(entity, key);
- if (existing !== undefined) {
- return existing;
- }
- return this.emplace(entity, key, defaultComponent);
- }
-
- /**
- * Check if an entity has a component.
- */
- has(entity: Entity, key: ComponentKey): boolean {
- if (!this.valid(entity)) return false;
-
- const pool = this.componentPools.get(key);
- return pool !== undefined && pool.has(entity);
- }
-
- /**
- * Check if an entity has all of the specified components.
- */
- hasAll(entity: Entity, ...keys: ComponentKey[]): boolean {
- return keys.every((key) => this.has(entity, key));
- }
-
- /**
- * Check if an entity has any of the specified components.
- */
- hasAny(entity: Entity, ...keys: ComponentKey[]): boolean {
- return keys.some((key) => this.has(entity, key));
- }
-
- /**
- * Create a view for entities with a single component.
- */
- view<T>(key: ComponentKey): View<T> {
- const pool = this.getOrCreatePool<T>(key);
- const entities = new Set<Entity>();
-
- for (const entity of this.entities) {
- if (pool.has(entity)) {
- entities.add(entity);
- }
- }
-
- return new View(pool, entities);
- }
-
- /**
- * Create a view for entities with two components.
- */
- view2<T1, T2>(key1: ComponentKey, key2: ComponentKey): View2<T1, T2> {
- const pool1 = this.getOrCreatePool<T1>(key1);
- const pool2 = this.getOrCreatePool<T2>(key2);
- const entities = new Set<Entity>();
-
- for (const entity of this.entities) {
- if (pool1.has(entity) && pool2.has(entity)) {
- entities.add(entity);
- }
- }
-
- return new View2(pool1, pool2, entities);
- }
-
- /**
- * Create a view for entities with three components.
- */
- view3<T1, T2, T3>(
- key1: ComponentKey,
- key2: ComponentKey,
- key3: ComponentKey
- ): View3<T1, T2, T3> {
- const pool1 = this.getOrCreatePool<T1>(key1);
- const pool2 = this.getOrCreatePool<T2>(key2);
- const pool3 = this.getOrCreatePool<T3>(key3);
- const entities = new Set<Entity>();
-
- for (const entity of this.entities) {
- if (pool1.has(entity) && pool2.has(entity) && pool3.has(entity)) {
- entities.add(entity);
- }
- }
-
- return new View3(pool1, pool2, pool3, entities);
- }
-
- /**
- * Create a view for entities with four components.
- */
- view4<T1, T2, T3, T4>(
- key1: ComponentKey,
- key2: ComponentKey,
- key3: ComponentKey,
- key4: ComponentKey
- ): View4<T1, T2, T3, T4> {
- const pool1 = this.getOrCreatePool<T1>(key1);
- const pool2 = this.getOrCreatePool<T2>(key2);
- const pool3 = this.getOrCreatePool<T3>(key3);
- const pool4 = this.getOrCreatePool<T4>(key4);
- const entities = new Set<Entity>();
-
- for (const entity of this.entities) {
- if (
- pool1.has(entity) &&
- pool2.has(entity) &&
- pool3.has(entity) &&
- pool4.has(entity)
- ) {
- entities.add(entity);
- }
- }
-
- return new View4(pool1, pool2, pool3, pool4, entities);
- }
-
- /**
- * Execute a callback for each entity with the specified component.
- */
- each<T>(key: ComponentKey, callback: (entity: Entity, component: T) => void): void {
- this.view<T>(key).each(callback);
- }
-
- /**
- * Clear all entities and components.
- */
- clear(): void {
- this.entities.clear();
- this.componentPools.clear();
- this.entityComponents.clear();
- }
-
- /**
- * Get all entities in the registry.
- */
- getAllEntities(): Entity[] {
- return Array.from(this.entities);
- }
-
- private getOrCreatePool<T>(key: ComponentKey): ComponentPool<T> {
- let pool = this.componentPools.get(key) as ComponentPool<T> | undefined;
- if (!pool) {
- pool = new Map<Entity, T>();
- this.componentPools.set(key, pool as ComponentPool<unknown>);
- }
- return pool;
- }
-}
diff --git a/sdk/src/ecs/System.ts b/sdk/src/ecs/System.ts
deleted file mode 100644
index d46f9688c..000000000
--- a/sdk/src/ecs/System.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-/**
- * ESEngine TypeScript SDK - System Management
- *
- * Provides base classes for game systems and system groups.
- */
-
-import { Registry } from './Registry';
-
-/**
- * System base class - Override to create game systems.
- */
-export abstract class System {
- private enabled: boolean = true;
- private priority: number = 0;
-
- /**
- * Called when the system is initialized.
- */
- init(registry: Registry): void {}
-
- /**
- * Called every frame to update game state.
- */
- abstract update(registry: Registry, deltaTime: number): void;
-
- /**
- * Called when the system is shut down.
- */
- shutdown(registry: Registry): void {}
-
- /**
- * Enable or disable the system.
- */
- setEnabled(enabled: boolean): void {
- this.enabled = enabled;
- }
-
- /**
- * Check if the system is enabled.
- */
- isEnabled(): boolean {
- return this.enabled;
- }
-
- /**
- * Set the system priority (higher = runs first).
- */
- setPriority(priority: number): void {
- this.priority = priority;
- }
-
- /**
- * Get the system priority.
- */
- getPriority(): number {
- return this.priority;
- }
-}
-
-/**
- * SystemGroup - Manages a collection of systems.
- */
-export class SystemGroup {
- private systems: System[] = [];
- private initialized: boolean = false;
-
- /**
- * Add a system to the group.
- */
- addSystem(system: System): void {
- this.systems.push(system);
- this.sortSystems();
- }
-
- /**
- * Create and add a system to the group.
- */
- createSystem<T extends System>(
- SystemClass: new (...args: unknown[]) => T,
- ...args: unknown[]
- ): T {
- const system = new SystemClass(...args);
- this.addSystem(system);
- return system;
- }
-
- /**
- * Remove a system from the group.
- */
- removeSystem(system: System): boolean {
- const index = this.systems.indexOf(system);
- if (index !== -1) {
- this.systems.splice(index, 1);
- return true;
- }
- return false;
- }
-
- /**
- * Initialize all systems in the group.
- */
- init(registry: Registry): void {
- if (this.initialized) return;
-
- for (const system of this.systems) {
- system.init(registry);
- }
- this.initialized = true;
- }
-
- /**
- * Update all enabled systems in the group.
- */
- update(registry: Registry, deltaTime: number): void {
- for (const system of this.systems) {
- if (system.isEnabled()) {
- system.update(registry, deltaTime);
- }
- }
- }
-
- /**
- * Shut down all systems in the group.
- */
- shutdown(registry: Registry): void {
- if (!this.initialized) return;
-
- // Shutdown in reverse order
- for (let i = this.systems.length - 1; i >= 0; i--) {
- this.systems[i].shutdown(registry);
- }
- this.initialized = false;
- }
-
- /**
- * Get all systems in the group.
- */
- getSystems(): readonly System[] {
- return this.systems;
- }
-
- /**
- * Get the number of systems in the group.
- */
- getSystemCount(): number {
- return this.systems.length;
- }
-
- private sortSystems(): void {
- this.systems.sort((a, b) => b.getPriority() - a.getPriority());
- }
-}
diff --git a/sdk/src/ecs/View.ts b/sdk/src/ecs/View.ts
deleted file mode 100644
index 323de71c3..000000000
--- a/sdk/src/ecs/View.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Component View
- *
- * Provides efficient querying and iteration over entities with specific components.
- */
-
-import { Entity } from '../core/Types';
-
-// Component storage type
-type ComponentPool<T> = Map<Entity, T>;
-
-/**
- * View for querying entities with a single component type.
- */
-export class View<T> {
- private pool: ComponentPool<T>;
- private entities: Set<Entity>;
-
- constructor(pool: ComponentPool<T>, entities: Set<Entity>) {
- this.pool = pool;
- this.entities = entities;
- }
-
- /**
- * Iterate over all entities in the view.
- */
- *[Symbol.iterator](): Iterator<[Entity, T]> {
- for (const entity of this.entities) {
- const component = this.pool.get(entity);
- if (component !== undefined) {
- yield [entity, component];
- }
- }
- }
-
- /**
- * Execute a callback for each entity in the view.
- */
- each(callback: (entity: Entity, component: T) => void): void {
- for (const [entity, component] of this) {
- callback(entity, component);
- }
- }
-
- /**
- * Check if the view is empty.
- */
- empty(): boolean {
- return this.entities.size === 0;
- }
-
- /**
- * Get the number of entities in the view (hint, may be inaccurate).
- */
- sizeHint(): number {
- return this.entities.size;
- }
-
- /**
- * Get component for a specific entity.
- */
- get(entity: Entity): T | undefined {
- return this.pool.get(entity);
- }
-}
-
-/**
- * View for querying entities with two component types.
- */
-export class View2<T1, T2> {
- private pool1: ComponentPool<T1>;
- private pool2: ComponentPool<T2>;
- private entities: Set<Entity>;
-
- constructor(
- pool1: ComponentPool<T1>,
- pool2: ComponentPool<T2>,
- entities: Set<Entity>
- ) {
- this.pool1 = pool1;
- this.pool2 = pool2;
- this.entities = entities;
- }
-
- /**
- * Iterate over all entities in the view.
- */
- *[Symbol.iterator](): Iterator<[Entity, T1, T2]> {
- for (const entity of this.entities) {
- const c1 = this.pool1.get(entity);
- const c2 = this.pool2.get(entity);
- if (c1 !== undefined && c2 !== undefined) {
- yield [entity, c1, c2];
- }
- }
- }
-
- /**
- * Execute a callback for each entity in the view.
- */
- each(callback: (entity: Entity, c1: T1, c2: T2) => void): void {
- for (const [entity, c1, c2] of this) {
- callback(entity, c1, c2);
- }
- }
-
- /**
- * Check if the view is empty.
- */
- empty(): boolean {
- return this.sizeHint() === 0;
- }
-
- /**
- * Get the number of entities in the view (hint, may be inaccurate).
- */
- sizeHint(): number {
- // Return the minimum of both pools
- let count = 0;
- for (const entity of this.entities) {
- if (this.pool1.has(entity) && this.pool2.has(entity)) {
- count++;
- }
- }
- return count;
- }
-}
-
-/**
- * View for querying entities with three component types.
- */
-export class View3<T1, T2, T3> {
- private pool1: ComponentPool<T1>;
- private pool2: ComponentPool<T2>;
- private pool3: ComponentPool<T3>;
- private entities: Set<Entity>;
-
- constructor(
- pool1: ComponentPool<T1>,
- pool2: ComponentPool<T2>,
- pool3: ComponentPool<T3>,
- entities: Set<Entity>
- ) {
- this.pool1 = pool1;
- this.pool2 = pool2;
- this.pool3 = pool3;
- this.entities = entities;
- }
-
- /**
- * Iterate over all entities in the view.
- */
- *[Symbol.iterator](): Iterator<[Entity, T1, T2, T3]> {
- for (const entity of this.entities) {
- const c1 = this.pool1.get(entity);
- const c2 = this.pool2.get(entity);
- const c3 = this.pool3.get(entity);
- if (c1 !== undefined && c2 !== undefined && c3 !== undefined) {
- yield [entity, c1, c2, c3];
- }
- }
- }
-
- /**
- * Execute a callback for each entity in the view.
- */
- each(callback: (entity: Entity, c1: T1, c2: T2, c3: T3) => void): void {
- for (const [entity, c1, c2, c3] of this) {
- callback(entity, c1, c2, c3);
- }
- }
-
- /**
- * Check if the view is empty.
- */
- empty(): boolean {
- return this.sizeHint() === 0;
- }
-
- /**
- * Get the number of entities in the view (hint, may be inaccurate).
- */
- sizeHint(): number {
- let count = 0;
- for (const entity of this.entities) {
- if (
- this.pool1.has(entity) &&
- this.pool2.has(entity) &&
- this.pool3.has(entity)
- ) {
- count++;
- }
- }
- return count;
- }
-}
-
-/**
- * View for querying entities with four component types.
- */
-export class View4<T1, T2, T3, T4> {
- private pool1: ComponentPool<T1>;
- private pool2: ComponentPool<T2>;
- private pool3: ComponentPool<T3>;
- private pool4: ComponentPool<T4>;
- private entities: Set<Entity>;
-
- constructor(
- pool1: ComponentPool<T1>,
- pool2: ComponentPool<T2>,
- pool3: ComponentPool<T3>,
- pool4: ComponentPool<T4>,
- entities: Set<Entity>
- ) {
- this.pool1 = pool1;
- this.pool2 = pool2;
- this.pool3 = pool3;
- this.pool4 = pool4;
- this.entities = entities;
- }
-
- /**
- * Iterate over all entities in the view.
- */
- *[Symbol.iterator](): Iterator<[Entity, T1, T2, T3, T4]> {
- for (const entity of this.entities) {
- const c1 = this.pool1.get(entity);
- const c2 = this.pool2.get(entity);
- const c3 = this.pool3.get(entity);
- const c4 = this.pool4.get(entity);
- if (
- c1 !== undefined &&
- c2 !== undefined &&
- c3 !== undefined &&
- c4 !== undefined
- ) {
- yield [entity, c1, c2, c3, c4];
- }
- }
- }
-
- /**
- * Execute a callback for each entity in the view.
- */
- each(callback: (entity: Entity, c1: T1, c2: T2, c3: T3, c4: T4) => void): void {
- for (const [entity, c1, c2, c3, c4] of this) {
- callback(entity, c1, c2, c3, c4);
- }
- }
-
- /**
- * Check if the view is empty.
- */
- empty(): boolean {
- return this.sizeHint() === 0;
- }
-
- /**
- * Get the number of entities in the view (hint, may be inaccurate).
- */
- sizeHint(): number {
- let count = 0;
- for (const entity of this.entities) {
- if (
- this.pool1.has(entity) &&
- this.pool2.has(entity) &&
- this.pool3.has(entity) &&
- this.pool4.has(entity)
- ) {
- count++;
- }
- }
- return count;
- }
-}
diff --git a/sdk/src/framework/app.ts b/sdk/src/framework/app.ts
deleted file mode 100644
index 15e2d6e35..000000000
--- a/sdk/src/framework/app.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 5613370a2..000000000
--- a/sdk/src/framework/builtin.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * @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/component.ts b/sdk/src/framework/component.ts
deleted file mode 100644
index 0ce88bbd2..000000000
--- a/sdk/src/framework/component.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 0e592e7ac..000000000
--- a/sdk/src/framework/index.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 1bce09f5b..000000000
--- a/sdk/src/framework/plugins/default.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 25f5ae446..000000000
--- a/sdk/src/framework/plugins/wasm.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 04035e88d..000000000
--- a/sdk/src/framework/proxy.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-/**
- * @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/schedule.ts b/sdk/src/framework/schedule.ts
deleted file mode 100644
index aaf22e372..000000000
--- a/sdk/src/framework/schedule.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * @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/types.ts b/sdk/src/framework/types.ts
deleted file mode 100644
index 7fb1ffa4b..000000000
--- a/sdk/src/framework/types.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 61711db71..000000000
--- a/sdk/src/framework/world.ts
+++ /dev/null
@@ -1,397 +0,0 @@
-/**
- * @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 0de28e5aa..de3bc5fb4 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -1,183 +1,134 @@
/**
* @file index.ts
- * @brief ESEngine TypeScript SDK public API exports
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
+ * @brief ESEngine SDK - Main entry point
*/
// =============================================================================
-// Core
+// Types
// =============================================================================
-// Core types and utilities
export {
- Entity,
- INVALID_ENTITY,
- ComponentType,
- Vec2,
- Vec3,
- Vec4,
- Color,
- Mat4,
- TouchType,
- TouchPoint,
- KeyCode,
- ApplicationConfig,
- RendererStats,
- RendererBackend,
- vec2,
- vec3,
- vec4,
- color,
- mat4Identity,
- mat4Ortho,
-} from './core/Types';
-
-// Application
-export { Application } from './core/Application';
-
-// WASM Bridge
-export {
- ESEngineModule,
- WasmLoadOptions,
- isWasmLoaded,
- getWasmModule,
- setWasmModule,
- loadWasmModule,
- initWasmRenderer,
- allocFloat32Array,
- allocUint8Array,
- freePtr,
- withFloat32Array,
-} from './core/WasmBridge';
+ type Entity,
+ INVALID_ENTITY,
+ type Vec2,
+ type Vec3,
+ type Vec4,
+ type Color,
+ type Quat,
+ vec2,
+ vec3,
+ vec4,
+ color,
+ quat,
+} from './types';
// =============================================================================
-// ECS
+// Components
// =============================================================================
export {
- generateEntityId,
- recycleEntityId,
- isValidEntity,
- resetEntityIds,
-} from './ecs/Entity';
-
-export { Registry } from './ecs/Registry';
-
-export {
- Transform,
- Velocity,
- Sprite,
- Name,
- Active,
- Visible,
- Static,
- Parent,
- Children,
- createTransform,
- createVelocity,
- createSprite,
- createName,
- createActive,
- createVisible,
- createStatic,
- createParent,
- createChildren,
- TransformType,
- VelocityType,
- SpriteType,
- NameType,
- ActiveType,
- VisibleType,
- StaticType,
- ParentType,
- ChildrenType,
-} from './ecs/Components';
-
-export { View, View2, View3, View4 } from './ecs/View';
-
-export { System, SystemGroup } from './ecs/System';
-
-// =============================================================================
-// Math
+ defineComponent,
+ defineTag,
+ isBuiltinComponent,
+ type ComponentDef,
+ type BuiltinComponentDef,
+ type AnyComponentDef,
+ type ComponentData,
+ LocalTransform,
+ WorldTransform,
+ Sprite,
+ Camera,
+ Canvas,
+ Velocity,
+ Parent,
+ Children,
+ type LocalTransformData,
+ type WorldTransformData,
+ type SpriteData,
+ type CameraData,
+ type CanvasData,
+ type VelocityData,
+ type ParentData,
+ type ChildrenData,
+} from './component';
+
+// =============================================================================
+// Resources
// =============================================================================
export {
- PI,
- TWO_PI,
- HALF_PI,
- DEG_TO_RAD,
- RAD_TO_DEG,
- clamp,
- lerp,
- toRadians,
- toDegrees,
- Vec2Math,
- Vec3Math,
- Mat4Math,
-} from './math/Math';
+ defineResource,
+ Res,
+ ResMut,
+ Time,
+ Input,
+ type ResourceDef,
+ type ResDescriptor,
+ type ResMutDescriptor,
+ type ResMutInstance,
+ type TimeData,
+ type InputState,
+} from './resource';
// =============================================================================
-// Platform
+// Query
// =============================================================================
-export { Input } from './input/Input';
-
export {
- Platform,
- PlatformCapabilities,
- PlatformConfig,
- TouchCallback,
- KeyCallback,
- ResizeCallback,
-} from './platform/Platform';
-export { WebPlatform } from './platform/WebPlatform';
-export { WxPlatform } from './platform/WxPlatform';
+ Query,
+ QueryInstance,
+ type QueryDescriptor,
+ type QueryResult,
+} from './query';
// =============================================================================
-// Renderer
+// Commands
// =============================================================================
-export { Renderer, RendererMode, DrawQuadOptions } from './renderer/Renderer';
+export {
+ Commands,
+ CommandsInstance,
+ EntityCommands,
+ type CommandsDescriptor,
+} from './commands';
// =============================================================================
-// Scene
+// System
// =============================================================================
export {
- loadScene,
- loadSceneFromData,
- SceneData,
- EntityData,
- ComponentsData,
- ScriptComponentData,
- TextureLoader,
- ComponentRegistry,
- SceneLoaderOptions,
- SceneLoadResult,
- SCENE_FORMAT_VERSION,
-} from './scene/SceneLoader';
+ Schedule,
+ defineSystem,
+ SystemRunner,
+ type SystemDef,
+ type SystemParam,
+ type InferParam,
+ type InferParams,
+} from './system';
// =============================================================================
-// Assets & WASM
+// World
// =============================================================================
-export { AssetLoader, type TextureData, type ShaderData } from './assets';
+export { World } from './world';
-export type {
- CppRegistry,
- CppApp,
- CppResourceManager,
- TextureHandle,
- ShaderHandle,
-} from './wasm';
+// =============================================================================
+// App
+// =============================================================================
+
+export {
+ App,
+ createWebApp,
+ type Plugin,
+ type WebAppOptions,
+} from './app';
// =============================================================================
-// Framework
+// WASM Types
// =============================================================================
-export * from './framework';
+export type {
+ ESEngineModule,
+ CppRegistry,
+ CppResourceManager,
+} from './wasm';
diff --git a/sdk/src/input/Input.ts b/sdk/src/input/Input.ts
deleted file mode 100644
index ba7dc5e6b..000000000
--- a/sdk/src/input/Input.ts
+++ /dev/null
@@ -1,294 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Input Management
- *
- * Provides unified input handling for touch and keyboard.
- */
-
-import { Vec2, KeyCode, TouchType, TouchPoint, vec2 } from '../core/Types';
-
-// Touch state
-interface TouchState {
- id: number;
- position: Vec2;
- startPosition: Vec2;
- isDown: boolean;
- justPressed: boolean;
- justReleased: boolean;
-}
-
-// Key state
-interface KeyState {
- isDown: boolean;
- justPressed: boolean;
- justReleased: boolean;
-}
-
-/**
- * Input - Static class for input management.
- */
-export class Input {
- private static touches: Map<number, TouchState> = new Map();
- private static keys: Map<KeyCode, KeyState> = new Map();
- private static mousePosition: Vec2 = { x: 0, y: 0 };
- private static mouseButtons: Map<number, KeyState> = new Map();
- private static initialized: boolean = false;
-
- /**
- * Initialize the input system.
- */
- static init(): void {
- if (this.initialized) return;
- this.touches.clear();
- this.keys.clear();
- this.mouseButtons.clear();
- this.initialized = true;
- }
-
- /**
- * Shut down the input system.
- */
- static shutdown(): void {
- this.touches.clear();
- this.keys.clear();
- this.mouseButtons.clear();
- this.initialized = false;
- }
-
- /**
- * Update input state. Call once per frame after processing events.
- */
- static update(): void {
- // Reset "just" states for touches
- for (const touch of this.touches.values()) {
- touch.justPressed = false;
- touch.justReleased = false;
- }
-
- // Remove released touches
- for (const [id, touch] of this.touches) {
- if (!touch.isDown && !touch.justReleased) {
- this.touches.delete(id);
- }
- }
-
- // Reset "just" states for keys
- for (const key of this.keys.values()) {
- key.justPressed = false;
- key.justReleased = false;
- }
-
- // Reset "just" states for mouse buttons
- for (const button of this.mouseButtons.values()) {
- button.justPressed = false;
- button.justReleased = false;
- }
- }
-
- // ========== Touch Input ==========
-
- /**
- * Handle touch event from platform.
- */
- static onTouchEvent(type: TouchType, point: TouchPoint): void {
- let touch = this.touches.get(point.id);
-
- switch (type) {
- case TouchType.Begin:
- touch = {
- id: point.id,
- position: { x: point.x, y: point.y },
- startPosition: { x: point.x, y: point.y },
- isDown: true,
- justPressed: true,
- justReleased: false,
- };
- this.touches.set(point.id, touch);
- break;
-
- case TouchType.Move:
- if (touch) {
- touch.position = { x: point.x, y: point.y };
- }
- break;
-
- case TouchType.End:
- case TouchType.Cancel:
- if (touch) {
- touch.position = { x: point.x, y: point.y };
- touch.isDown = false;
- touch.justReleased = true;
- }
- break;
- }
- }
-
- /**
- * Check if a touch is currently down.
- */
- static isTouchDown(index: number = 0): boolean {
- const touch = this.getTouchByIndex(index);
- return touch !== undefined && touch.isDown;
- }
-
- /**
- * Check if a touch just started this frame.
- */
- static isTouchPressed(index: number = 0): boolean {
- const touch = this.getTouchByIndex(index);
- return touch !== undefined && touch.justPressed;
- }
-
- /**
- * Check if a touch just ended this frame.
- */
- static isTouchReleased(index: number = 0): boolean {
- const touch = this.getTouchByIndex(index);
- return touch !== undefined && touch.justReleased;
- }
-
- /**
- * Get the current touch position.
- */
- static getTouchPosition(index: number = 0): Vec2 {
- const touch = this.getTouchByIndex(index);
- return touch ? { ...touch.position } : { x: 0, y: 0 };
- }
-
- /**
- * Get the touch delta from start position.
- */
- static getTouchDelta(index: number = 0): Vec2 {
- const touch = this.getTouchByIndex(index);
- if (!touch) return { x: 0, y: 0 };
- return {
- x: touch.position.x - touch.startPosition.x,
- y: touch.position.y - touch.startPosition.y,
- };
- }
-
- /**
- * Get the number of active touches.
- */
- static getTouchCount(): number {
- let count = 0;
- for (const touch of this.touches.values()) {
- if (touch.isDown) count++;
- }
- return count;
- }
-
- private static getTouchByIndex(index: number): TouchState | undefined {
- let i = 0;
- for (const touch of this.touches.values()) {
- if (i === index) return touch;
- i++;
- }
- return undefined;
- }
-
- // ========== Keyboard Input ==========
-
- /**
- * Handle key event from platform.
- */
- static onKeyEvent(key: KeyCode, pressed: boolean): void {
- let state = this.keys.get(key);
-
- if (!state) {
- state = { isDown: false, justPressed: false, justReleased: false };
- this.keys.set(key, state);
- }
-
- if (pressed && !state.isDown) {
- state.isDown = true;
- state.justPressed = true;
- } else if (!pressed && state.isDown) {
- state.isDown = false;
- state.justReleased = true;
- }
- }
-
- /**
- * Check if a key is currently down.
- */
- static isKeyDown(key: KeyCode): boolean {
- const state = this.keys.get(key);
- return state !== undefined && state.isDown;
- }
-
- /**
- * Check if a key was just pressed this frame.
- */
- static isKeyPressed(key: KeyCode): boolean {
- const state = this.keys.get(key);
- return state !== undefined && state.justPressed;
- }
-
- /**
- * Check if a key was just released this frame.
- */
- static isKeyReleased(key: KeyCode): boolean {
- const state = this.keys.get(key);
- return state !== undefined && state.justReleased;
- }
-
- // ========== Mouse Input ==========
-
- /**
- * Handle mouse move event from platform.
- */
- static onMouseMove(x: number, y: number): void {
- this.mousePosition = { x, y };
- }
-
- /**
- * Handle mouse button event from platform.
- */
- static onMouseButton(button: number, pressed: boolean): void {
- let state = this.mouseButtons.get(button);
-
- if (!state) {
- state = { isDown: false, justPressed: false, justReleased: false };
- this.mouseButtons.set(button, state);
- }
-
- if (pressed && !state.isDown) {
- state.isDown = true;
- state.justPressed = true;
- } else if (!pressed && state.isDown) {
- state.isDown = false;
- state.justReleased = true;
- }
- }
-
- /**
- * Get the current mouse position.
- */
- static getMousePosition(): Vec2 {
- return { ...this.mousePosition };
- }
-
- /**
- * Check if a mouse button is currently down.
- */
- static isMouseButtonDown(button: number = 0): boolean {
- const state = this.mouseButtons.get(button);
- return state !== undefined && state.isDown;
- }
-
- /**
- * Check if a mouse button was just pressed.
- */
- static isMouseButtonPressed(button: number = 0): boolean {
- const state = this.mouseButtons.get(button);
- return state !== undefined && state.justPressed;
- }
-
- /**
- * Check if a mouse button was just released.
- */
- static isMouseButtonReleased(button: number = 0): boolean {
- const state = this.mouseButtons.get(button);
- return state !== undefined && state.justReleased;
- }
-}
diff --git a/sdk/src/math/Math.ts b/sdk/src/math/Math.ts
deleted file mode 100644
index 9dbd1869a..000000000
--- a/sdk/src/math/Math.ts
+++ /dev/null
@@ -1,312 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Math Utilities
- *
- * Provides common math operations for game development.
- */
-
-import { Vec2, Vec3, Vec4, Mat4, mat4Identity } from '../core/Types';
-
-// Constants
-export const PI = Math.PI;
-export const TWO_PI = Math.PI * 2;
-export const HALF_PI = Math.PI / 2;
-export const DEG_TO_RAD = Math.PI / 180;
-export const RAD_TO_DEG = 180 / Math.PI;
-
-/**
- * Clamp a value between min and max.
- */
-export function clamp(value: number, min: number, max: number): number {
- return Math.min(Math.max(value, min), max);
-}
-
-/**
- * Linear interpolation between two values.
- */
-export function lerp(a: number, b: number, t: number): number {
- return a + (b - a) * t;
-}
-
-/**
- * Convert degrees to radians.
- */
-export function toRadians(degrees: number): number {
- return degrees * DEG_TO_RAD;
-}
-
-/**
- * Convert radians to degrees.
- */
-export function toDegrees(radians: number): number {
- return radians * RAD_TO_DEG;
-}
-
-// ========== Vec2 Operations ==========
-
-export namespace Vec2Math {
- export function add(a: Vec2, b: Vec2): Vec2 {
- return { x: a.x + b.x, y: a.y + b.y };
- }
-
- export function sub(a: Vec2, b: Vec2): Vec2 {
- return { x: a.x - b.x, y: a.y - b.y };
- }
-
- export function mul(v: Vec2, scalar: number): Vec2 {
- return { x: v.x * scalar, y: v.y * scalar };
- }
-
- export function div(v: Vec2, scalar: number): Vec2 {
- return { x: v.x / scalar, y: v.y / scalar };
- }
-
- export function dot(a: Vec2, b: Vec2): number {
- return a.x * b.x + a.y * b.y;
- }
-
- export function length(v: Vec2): number {
- return Math.sqrt(v.x * v.x + v.y * v.y);
- }
-
- export function lengthSquared(v: Vec2): number {
- return v.x * v.x + v.y * v.y;
- }
-
- export function normalize(v: Vec2): Vec2 {
- const len = length(v);
- if (len === 0) return { x: 0, y: 0 };
- return { x: v.x / len, y: v.y / len };
- }
-
- export function distance(a: Vec2, b: Vec2): number {
- return length(sub(b, a));
- }
-
- export function lerp(a: Vec2, b: Vec2, t: number): Vec2 {
- return {
- x: a.x + (b.x - a.x) * t,
- y: a.y + (b.y - a.y) * t,
- };
- }
-}
-
-// ========== Vec3 Operations ==========
-
-export namespace Vec3Math {
- export function add(a: Vec3, b: Vec3): Vec3 {
- return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };
- }
-
- export function sub(a: Vec3, b: Vec3): Vec3 {
- return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };
- }
-
- export function mul(v: Vec3, scalar: number): Vec3 {
- return { x: v.x * scalar, y: v.y * scalar, z: v.z * scalar };
- }
-
- export function div(v: Vec3, scalar: number): Vec3 {
- return { x: v.x / scalar, y: v.y / scalar, z: v.z / scalar };
- }
-
- export function dot(a: Vec3, b: Vec3): number {
- return a.x * b.x + a.y * b.y + a.z * b.z;
- }
-
- export function cross(a: Vec3, b: Vec3): Vec3 {
- return {
- x: a.y * b.z - a.z * b.y,
- y: a.z * b.x - a.x * b.z,
- z: a.x * b.y - a.y * b.x,
- };
- }
-
- export function length(v: Vec3): number {
- return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
- }
-
- export function lengthSquared(v: Vec3): number {
- return v.x * v.x + v.y * v.y + v.z * v.z;
- }
-
- export function normalize(v: Vec3): Vec3 {
- const len = length(v);
- if (len === 0) return { x: 0, y: 0, z: 0 };
- return { x: v.x / len, y: v.y / len, z: v.z / len };
- }
-
- export function distance(a: Vec3, b: Vec3): number {
- return length(sub(b, a));
- }
-
- export function lerp(a: Vec3, b: Vec3, t: number): Vec3 {
- return {
- x: a.x + (b.x - a.x) * t,
- y: a.y + (b.y - a.y) * t,
- z: a.z + (b.z - a.z) * t,
- };
- }
-}
-
-// ========== Mat4 Operations ==========
-
-export namespace Mat4Math {
- /**
- * Multiply two 4x4 matrices.
- */
- export function multiply(a: Mat4, b: Mat4): Mat4 {
- const result = new Float32Array(16);
-
- for (let i = 0; i < 4; i++) {
- for (let j = 0; j < 4; j++) {
- result[i * 4 + j] =
- a[i * 4 + 0] * b[0 * 4 + j] +
- a[i * 4 + 1] * b[1 * 4 + j] +
- a[i * 4 + 2] * b[2 * 4 + j] +
- a[i * 4 + 3] * b[3 * 4 + j];
- }
- }
-
- return result;
- }
-
- /**
- * Create a translation matrix.
- */
- export function translate(x: number, y: number, z: number): Mat4 {
- const m = mat4Identity();
- m[12] = x;
- m[13] = y;
- m[14] = z;
- return m;
- }
-
- /**
- * Create a scale matrix.
- */
- export function scale(x: number, y: number, z: number): Mat4 {
- const m = new Float32Array(16);
- m[0] = x;
- m[5] = y;
- m[10] = z;
- m[15] = 1;
- return m;
- }
-
- /**
- * Create a rotation matrix around the Z axis.
- */
- export function rotateZ(angle: number): Mat4 {
- const m = mat4Identity();
- const c = Math.cos(angle);
- const s = Math.sin(angle);
- m[0] = c;
- m[1] = s;
- m[4] = -s;
- m[5] = c;
- return m;
- }
-
- /**
- * Create a rotation matrix around the X axis.
- */
- export function rotateX(angle: number): Mat4 {
- const m = mat4Identity();
- const c = Math.cos(angle);
- const s = Math.sin(angle);
- m[5] = c;
- m[6] = s;
- m[9] = -s;
- m[10] = c;
- return m;
- }
-
- /**
- * Create a rotation matrix around the Y axis.
- */
- export function rotateY(angle: number): Mat4 {
- const m = mat4Identity();
- const c = Math.cos(angle);
- const s = Math.sin(angle);
- m[0] = c;
- m[2] = -s;
- m[8] = s;
- m[10] = c;
- return m;
- }
-
- /**
- * Create an orthographic projection matrix.
- */
- export function ortho(
- left: number,
- right: number,
- bottom: number,
- top: number,
- near: number,
- far: number
- ): Mat4 {
- const m = new Float32Array(16);
- const lr = 1 / (left - right);
- const bt = 1 / (bottom - top);
- const nf = 1 / (near - far);
-
- m[0] = -2 * lr;
- m[5] = -2 * bt;
- m[10] = 2 * nf;
- m[12] = (left + right) * lr;
- m[13] = (top + bottom) * bt;
- m[14] = (far + near) * nf;
- m[15] = 1;
-
- return m;
- }
-
- /**
- * Create a perspective projection matrix.
- */
- export function perspective(
- fov: number,
- aspect: number,
- near: number,
- far: number
- ): Mat4 {
- const m = new Float32Array(16);
- const f = 1.0 / Math.tan(fov / 2);
- const nf = 1 / (near - far);
-
- m[0] = f / aspect;
- m[5] = f;
- m[10] = (far + near) * nf;
- m[11] = -1;
- m[14] = 2 * far * near * nf;
-
- return m;
- }
-
- /**
- * Create a look-at view matrix.
- */
- export function lookAt(eye: Vec3, target: Vec3, up: Vec3): Mat4 {
- const z = Vec3Math.normalize(Vec3Math.sub(eye, target));
- const x = Vec3Math.normalize(Vec3Math.cross(up, z));
- const y = Vec3Math.cross(z, x);
-
- const m = new Float32Array(16);
- m[0] = x.x;
- m[1] = y.x;
- m[2] = z.x;
- m[4] = x.y;
- m[5] = y.y;
- m[6] = z.y;
- m[8] = x.z;
- m[9] = y.z;
- m[10] = z.z;
- m[12] = -Vec3Math.dot(x, eye);
- m[13] = -Vec3Math.dot(y, eye);
- m[14] = -Vec3Math.dot(z, eye);
- m[15] = 1;
-
- return m;
- }
-}
diff --git a/sdk/src/platform/Platform.ts b/sdk/src/platform/Platform.ts
deleted file mode 100644
index d9f13d24f..000000000
--- a/sdk/src/platform/Platform.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Platform Abstraction
- *
- * Defines the interface for platform-specific implementations.
- */
-
-import { TouchType, TouchPoint, KeyCode } from '../core/Types';
-
-/**
- * Platform capabilities.
- */
-export interface PlatformCapabilities {
- hasTouch: boolean;
- hasKeyboard: boolean;
- hasMouse: boolean;
- hasWebGL2: boolean;
-}
-
-/**
- * Platform configuration.
- */
-export interface PlatformConfig {
- width: number;
- height: number;
- canvas?: HTMLCanvasElement | string;
- devicePixelRatio?: number;
- /** Skip WebGL context creation (used when WASM creates the context) */
- skipGLContext?: boolean;
-}
-
-/**
- * Touch event callback type.
- */
-export type TouchCallback = (type: TouchType, point: TouchPoint) => void;
-
-/**
- * Key event callback type.
- */
-export type KeyCallback = (key: KeyCode, pressed: boolean) => void;
-
-/**
- * Resize event callback type.
- */
-export type ResizeCallback = (width: number, height: number) => void;
-
-/**
- * Platform - Abstract interface for platform implementations.
- */
-export abstract class Platform {
- protected touchCallback: TouchCallback | null = null;
- protected keyCallback: KeyCallback | null = null;
- protected resizeCallback: ResizeCallback | null = null;
-
- /**
- * Initialize the platform.
- */
- abstract initialize(config: PlatformConfig): boolean;
-
- /**
- * Shut down the platform.
- */
- abstract shutdown(): void;
-
- /**
- * Poll for input events.
- */
- abstract pollEvents(): void;
-
- /**
- * Swap display buffers (for double buffering).
- */
- abstract swapBuffers(): void;
-
- /**
- * Get the current time in seconds.
- */
- abstract getTime(): number;
-
- /**
- * Get the time since last frame in seconds.
- */
- abstract getDeltaTime(): number;
-
- /**
- * Get the window width in pixels.
- */
- abstract getWindowWidth(): number;
-
- /**
- * Get the window height in pixels.
- */
- abstract getWindowHeight(): number;
-
- /**
- * Get the aspect ratio (width / height).
- */
- getAspectRatio(): number {
- const height = this.getWindowHeight();
- return height > 0 ? this.getWindowWidth() / height : 1;
- }
-
- /**
- * Get the device pixel ratio.
- */
- abstract getDevicePixelRatio(): number;
-
- /**
- * Check if the platform is still running.
- */
- abstract isRunning(): boolean;
-
- /**
- * Request the platform to quit.
- */
- abstract requestQuit(): void;
-
- /**
- * Get the WebGL rendering context.
- */
- abstract getGL(): WebGLRenderingContext | WebGL2RenderingContext | null;
-
- /**
- * Get the canvas element.
- */
- abstract getCanvas(): HTMLCanvasElement | null;
-
- /**
- * Get platform capabilities.
- */
- abstract getCapabilities(): PlatformCapabilities;
-
- /**
- * Set the touch event callback.
- */
- setTouchCallback(callback: TouchCallback | null): void {
- this.touchCallback = callback;
- }
-
- /**
- * Set the key event callback.
- */
- setKeyCallback(callback: KeyCallback | null): void {
- this.keyCallback = callback;
- }
-
- /**
- * Set the resize event callback.
- */
- setResizeCallback(callback: ResizeCallback | null): void {
- this.resizeCallback = callback;
- }
-
- private static platformFactory: (() => Platform) | null = null;
-
- /**
- * Register a platform factory function.
- * This is called by platform implementations to register themselves.
- */
- static registerFactory(factory: () => Platform): void {
- Platform.platformFactory = factory;
- }
-
- /**
- * Create the appropriate platform for the current environment.
- * The platform must be registered first via registerFactory.
- */
- static create(): Platform {
- if (Platform.platformFactory) {
- return Platform.platformFactory();
- }
-
- // Auto-detect and throw helpful error
- if (typeof wx !== 'undefined' && typeof wx.createCanvas === 'function') {
- throw new Error('WeChat MiniGame detected. Import WxPlatform and register it.');
- } else if (typeof window !== 'undefined' && typeof document !== 'undefined') {
- throw new Error('Web browser detected. Import WebPlatform and register it.');
- } else {
- throw new Error('Unsupported platform');
- }
- }
-}
-
-// Type declaration for WeChat MiniGame API (minimal)
-declare const wx: {
- createCanvas: () => HTMLCanvasElement;
- getSystemInfoSync: () => {
- windowWidth: number;
- windowHeight: number;
- pixelRatio: number;
- };
-} | undefined;
diff --git a/sdk/src/platform/WebPlatform.ts b/sdk/src/platform/WebPlatform.ts
deleted file mode 100644
index 2e5e69419..000000000
--- a/sdk/src/platform/WebPlatform.ts
+++ /dev/null
@@ -1,284 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Web Platform Implementation
- *
- * Platform implementation for standard web browsers.
- */
-
-import { TouchType, TouchPoint, KeyCode } from '../core/Types';
-import { Platform, PlatformConfig, PlatformCapabilities } from './Platform';
-
-/**
- * WebPlatform - Web browser platform implementation.
- */
-export class WebPlatform extends Platform {
- private canvas: HTMLCanvasElement | null = null;
- private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
- private running: boolean = false;
- private width: number = 0;
- private height: number = 0;
- private dpr: number = 1;
- private startTime: number = 0;
- private lastTime: number = 0;
- private deltaTime: number = 0;
- private capabilities: PlatformCapabilities;
-
- constructor() {
- super();
- this.capabilities = {
- hasTouch: false,
- hasKeyboard: true,
- hasMouse: true,
- hasWebGL2: false,
- };
- }
-
- initialize(config: PlatformConfig): boolean {
- // Get or create canvas
- if (config.canvas) {
- if (typeof config.canvas === 'string') {
- this.canvas = document.getElementById(config.canvas) as HTMLCanvasElement;
- if (!this.canvas) {
- console.error(`Canvas element not found: ${config.canvas}`);
- return false;
- }
- } else {
- this.canvas = config.canvas;
- }
- } else {
- this.canvas = document.createElement('canvas');
- document.body.appendChild(this.canvas);
- }
-
- // Set up dimensions
- this.dpr = config.devicePixelRatio ?? window.devicePixelRatio ?? 1;
- this.width = config.width;
- this.height = config.height;
- this.canvas.width = this.width * this.dpr;
- this.canvas.height = this.height * this.dpr;
- this.canvas.style.width = `${this.width}px`;
- this.canvas.style.height = `${this.height}px`;
-
- // Get WebGL context (skip if WASM creates it)
- if (!config.skipGLContext) {
- this.gl = this.canvas.getContext('webgl2') as WebGL2RenderingContext;
- if (this.gl) {
- this.capabilities.hasWebGL2 = true;
- } else {
- this.gl = this.canvas.getContext('webgl') as WebGLRenderingContext;
- if (!this.gl) {
- console.error('WebGL not supported');
- return false;
- }
- }
- } else {
- // When using WASM, the C++ code creates and manages the WebGL context
- this.capabilities.hasWebGL2 = true; // WASM uses WebGL2
- }
-
- // Check touch support
- this.capabilities.hasTouch = 'ontouchstart' in window;
-
- // Set up event listeners
- this.setupEventListeners();
-
- // Initialize timing
- this.startTime = performance.now() / 1000;
- this.lastTime = this.startTime;
- this.running = true;
-
- return true;
- }
-
- shutdown(): void {
- this.removeEventListeners();
- this.running = false;
- this.gl = null;
- this.canvas = null;
- }
-
- pollEvents(): void {
- // Events are handled asynchronously via callbacks
- const now = performance.now() / 1000;
- this.deltaTime = now - this.lastTime;
- this.lastTime = now;
- }
-
- swapBuffers(): void {
- // WebGL automatically swaps buffers
- }
-
- getTime(): number {
- return performance.now() / 1000 - this.startTime;
- }
-
- getDeltaTime(): number {
- return this.deltaTime;
- }
-
- getWindowWidth(): number {
- return this.width;
- }
-
- getWindowHeight(): number {
- return this.height;
- }
-
- getDevicePixelRatio(): number {
- return this.dpr;
- }
-
- isRunning(): boolean {
- return this.running;
- }
-
- requestQuit(): void {
- this.running = false;
- }
-
- getGL(): WebGLRenderingContext | WebGL2RenderingContext | null {
- return this.gl;
- }
-
- getCanvas(): HTMLCanvasElement | null {
- return this.canvas;
- }
-
- getCapabilities(): PlatformCapabilities {
- return { ...this.capabilities };
- }
-
- private setupEventListeners(): void {
- if (!this.canvas) return;
-
- // Touch events
- this.canvas.addEventListener('touchstart', this.handleTouchStart);
- this.canvas.addEventListener('touchmove', this.handleTouchMove);
- this.canvas.addEventListener('touchend', this.handleTouchEnd);
- this.canvas.addEventListener('touchcancel', this.handleTouchCancel);
-
- // Mouse events (emulate touch)
- this.canvas.addEventListener('mousedown', this.handleMouseDown);
- this.canvas.addEventListener('mousemove', this.handleMouseMove);
- this.canvas.addEventListener('mouseup', this.handleMouseUp);
-
- // Keyboard events
- window.addEventListener('keydown', this.handleKeyDown);
- window.addEventListener('keyup', this.handleKeyUp);
-
- // Resize event
- window.addEventListener('resize', this.handleResize);
- }
-
- private removeEventListeners(): void {
- if (!this.canvas) return;
-
- this.canvas.removeEventListener('touchstart', this.handleTouchStart);
- this.canvas.removeEventListener('touchmove', this.handleTouchMove);
- this.canvas.removeEventListener('touchend', this.handleTouchEnd);
- this.canvas.removeEventListener('touchcancel', this.handleTouchCancel);
- this.canvas.removeEventListener('mousedown', this.handleMouseDown);
- this.canvas.removeEventListener('mousemove', this.handleMouseMove);
- this.canvas.removeEventListener('mouseup', this.handleMouseUp);
-
- window.removeEventListener('keydown', this.handleKeyDown);
- window.removeEventListener('keyup', this.handleKeyUp);
- window.removeEventListener('resize', this.handleResize);
- }
-
- private getCanvasPosition(clientX: number, clientY: number): { x: number; y: number } {
- if (!this.canvas) return { x: 0, y: 0 };
- const rect = this.canvas.getBoundingClientRect();
- // Return logical coordinates (CSS pixels), not physical pixels
- // Game logic should use logical coords, only convert to physical in rendering
- return {
- x: clientX - rect.left,
- y: clientY - rect.top,
- };
- }
-
- private handleTouchStart = (e: TouchEvent): void => {
- e.preventDefault();
- for (let i = 0; i < e.changedTouches.length; i++) {
- const touch = e.changedTouches[i];
- const pos = this.getCanvasPosition(touch.clientX, touch.clientY);
- const point: TouchPoint = { id: touch.identifier, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.Begin, point);
- }
- };
-
- private handleTouchMove = (e: TouchEvent): void => {
- e.preventDefault();
- for (let i = 0; i < e.changedTouches.length; i++) {
- const touch = e.changedTouches[i];
- const pos = this.getCanvasPosition(touch.clientX, touch.clientY);
- const point: TouchPoint = { id: touch.identifier, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.Move, point);
- }
- };
-
- private handleTouchEnd = (e: TouchEvent): void => {
- e.preventDefault();
- for (let i = 0; i < e.changedTouches.length; i++) {
- const touch = e.changedTouches[i];
- const pos = this.getCanvasPosition(touch.clientX, touch.clientY);
- const point: TouchPoint = { id: touch.identifier, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.End, point);
- }
- };
-
- private handleTouchCancel = (e: TouchEvent): void => {
- e.preventDefault();
- for (let i = 0; i < e.changedTouches.length; i++) {
- const touch = e.changedTouches[i];
- const pos = this.getCanvasPosition(touch.clientX, touch.clientY);
- const point: TouchPoint = { id: touch.identifier, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.Cancel, point);
- }
- };
-
- private handleMouseDown = (e: MouseEvent): void => {
- const pos = this.getCanvasPosition(e.clientX, e.clientY);
- const point: TouchPoint = { id: 0, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.Begin, point);
- };
-
- private handleMouseMove = (e: MouseEvent): void => {
- const pos = this.getCanvasPosition(e.clientX, e.clientY);
- const point: TouchPoint = { id: 0, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.Move, point);
- };
-
- private handleMouseUp = (e: MouseEvent): void => {
- const pos = this.getCanvasPosition(e.clientX, e.clientY);
- const point: TouchPoint = { id: 0, x: pos.x, y: pos.y };
- this.touchCallback?.(TouchType.End, point);
- };
-
- private handleKeyDown = (e: KeyboardEvent): void => {
- const keyCode = this.mapKeyCode(e.keyCode);
- this.keyCallback?.(keyCode, true);
- };
-
- private handleKeyUp = (e: KeyboardEvent): void => {
- const keyCode = this.mapKeyCode(e.keyCode);
- this.keyCallback?.(keyCode, false);
- };
-
- private handleResize = (): void => {
- this.resizeCallback?.(window.innerWidth, window.innerHeight);
- };
-
- private mapKeyCode(code: number): KeyCode {
- // Most key codes map directly
- if (code in KeyCode) {
- return code as KeyCode;
- }
- return KeyCode.Unknown;
- }
-}
-
-// Auto-register WebPlatform when imported in browser environment
-// Check is done after class definition to ensure WebPlatform is available
-if (typeof window !== 'undefined' && typeof document !== 'undefined') {
- Platform.registerFactory(() => new WebPlatform());
-}
diff --git a/sdk/src/platform/WxPlatform.ts b/sdk/src/platform/WxPlatform.ts
deleted file mode 100644
index f427ae1f0..000000000
--- a/sdk/src/platform/WxPlatform.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-/**
- * ESEngine TypeScript SDK - WeChat MiniGame Platform Implementation
- *
- * Platform implementation for WeChat MiniGame environment.
- */
-
-import { TouchType, TouchPoint } from '../core/Types';
-import { Platform, PlatformConfig, PlatformCapabilities } from './Platform';
-
-// WeChat MiniGame API types
-declare const wx: {
- createCanvas: () => HTMLCanvasElement;
- getSystemInfoSync: () => {
- windowWidth: number;
- windowHeight: number;
- pixelRatio: number;
- platform: string;
- brand: string;
- model: string;
- };
- onTouchStart: (callback: (res: WxTouchEvent) => void) => void;
- onTouchMove: (callback: (res: WxTouchEvent) => void) => void;
- onTouchEnd: (callback: (res: WxTouchEvent) => void) => void;
- onTouchCancel: (callback: (res: WxTouchEvent) => void) => void;
- offTouchStart: (callback: (res: WxTouchEvent) => void) => void;
- offTouchMove: (callback: (res: WxTouchEvent) => void) => void;
- offTouchEnd: (callback: (res: WxTouchEvent) => void) => void;
- offTouchCancel: (callback: (res: WxTouchEvent) => void) => void;
-};
-
-interface WxTouch {
- identifier: number;
- clientX: number;
- clientY: number;
-}
-
-interface WxTouchEvent {
- touches: WxTouch[];
- changedTouches: WxTouch[];
- timeStamp: number;
-}
-
-/**
- * WxPlatform - WeChat MiniGame platform implementation.
- */
-export class WxPlatform extends Platform {
- private canvas: HTMLCanvasElement | null = null;
- private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
- private running: boolean = false;
- private width: number = 0;
- private height: number = 0;
- private dpr: number = 1;
- private startTime: number = 0;
- private lastTime: number = 0;
- private deltaTime: number = 0;
- private capabilities: PlatformCapabilities;
-
- constructor() {
- super();
- this.capabilities = {
- hasTouch: true,
- hasKeyboard: false,
- hasMouse: false,
- hasWebGL2: false,
- };
- }
-
- initialize(config: PlatformConfig): boolean {
- // Get system info
- const systemInfo = wx.getSystemInfoSync();
- this.dpr = config.devicePixelRatio ?? systemInfo.pixelRatio;
-
- // Create canvas
- this.canvas = wx.createCanvas();
-
- // Set up dimensions
- this.width = config.width || systemInfo.windowWidth;
- this.height = config.height || systemInfo.windowHeight;
- this.canvas.width = this.width * this.dpr;
- this.canvas.height = this.height * this.dpr;
-
- // Get WebGL context
- this.gl = this.canvas.getContext('webgl2') as WebGL2RenderingContext;
- if (this.gl) {
- this.capabilities.hasWebGL2 = true;
- } else {
- this.gl = this.canvas.getContext('webgl') as WebGLRenderingContext;
- if (!this.gl) {
- console.error('WebGL not supported');
- return false;
- }
- }
-
- // Set up event listeners
- this.setupEventListeners();
-
- // Initialize timing
- this.startTime = Date.now() / 1000;
- this.lastTime = this.startTime;
- this.running = true;
-
- return true;
- }
-
- shutdown(): void {
- this.removeEventListeners();
- this.running = false;
- this.gl = null;
- this.canvas = null;
- }
-
- pollEvents(): void {
- const now = Date.now() / 1000;
- this.deltaTime = now - this.lastTime;
- this.lastTime = now;
- }
-
- swapBuffers(): void {
- // WeChat handles buffer swapping
- }
-
- getTime(): number {
- return Date.now() / 1000 - this.startTime;
- }
-
- getDeltaTime(): number {
- return this.deltaTime;
- }
-
- getWindowWidth(): number {
- return this.width;
- }
-
- getWindowHeight(): number {
- return this.height;
- }
-
- getDevicePixelRatio(): number {
- return this.dpr;
- }
-
- isRunning(): boolean {
- return this.running;
- }
-
- requestQuit(): void {
- this.running = false;
- }
-
- getGL(): WebGLRenderingContext | WebGL2RenderingContext | null {
- return this.gl;
- }
-
- getCanvas(): HTMLCanvasElement | null {
- return this.canvas;
- }
-
- getCapabilities(): PlatformCapabilities {
- return { ...this.capabilities };
- }
-
- private setupEventListeners(): void {
- wx.onTouchStart(this.handleTouchStart);
- wx.onTouchMove(this.handleTouchMove);
- wx.onTouchEnd(this.handleTouchEnd);
- wx.onTouchCancel(this.handleTouchCancel);
- }
-
- private removeEventListeners(): void {
- wx.offTouchStart(this.handleTouchStart);
- wx.offTouchMove(this.handleTouchMove);
- wx.offTouchEnd(this.handleTouchEnd);
- wx.offTouchCancel(this.handleTouchCancel);
- }
-
- private handleTouchStart = (e: WxTouchEvent): void => {
- for (const touch of e.changedTouches) {
- const point: TouchPoint = {
- id: touch.identifier,
- x: touch.clientX * this.dpr,
- y: touch.clientY * this.dpr,
- };
- this.touchCallback?.(TouchType.Begin, point);
- }
- };
-
- private handleTouchMove = (e: WxTouchEvent): void => {
- for (const touch of e.changedTouches) {
- const point: TouchPoint = {
- id: touch.identifier,
- x: touch.clientX * this.dpr,
- y: touch.clientY * this.dpr,
- };
- this.touchCallback?.(TouchType.Move, point);
- }
- };
-
- private handleTouchEnd = (e: WxTouchEvent): void => {
- for (const touch of e.changedTouches) {
- const point: TouchPoint = {
- id: touch.identifier,
- x: touch.clientX * this.dpr,
- y: touch.clientY * this.dpr,
- };
- this.touchCallback?.(TouchType.End, point);
- }
- };
-
- private handleTouchCancel = (e: WxTouchEvent): void => {
- for (const touch of e.changedTouches) {
- const point: TouchPoint = {
- id: touch.identifier,
- x: touch.clientX * this.dpr,
- y: touch.clientY * this.dpr,
- };
- this.touchCallback?.(TouchType.Cancel, point);
- }
- };
-}
-
-// Auto-register WxPlatform when imported in WeChat MiniGame environment
-// Check is done after class definition to ensure WxPlatform is available
-try {
- if (typeof wx !== 'undefined' && typeof wx.createCanvas === 'function') {
- Platform.registerFactory(() => new WxPlatform());
- }
-} catch {
- // Ignore errors in environments where wx is not available
-}
diff --git a/sdk/src/framework/query.ts b/sdk/src/query.ts
similarity index 59%
rename from sdk/src/framework/query.ts
rename to sdk/src/query.ts
index ee793dd86..7aa27ea17 100644
--- a/sdk/src/framework/query.ts
+++ b/sdk/src/query.ts
@@ -1,32 +1,11 @@
/**
* @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.
+ * @brief Component query system
*/
-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]>;
-};
+import { Entity } from './types';
+import { AnyComponentDef, ComponentData } from './component';
+import type { World } from './world';
// =============================================================================
// Query Descriptor
@@ -37,9 +16,6 @@ export interface QueryDescriptor<C extends readonly AnyComponentDef[]> {
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[]>(
@@ -51,23 +27,7 @@ function createQueryDescriptor<C extends readonly AnyComponentDef[]>(
_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]
- );
- }
+ _without: withoutFilters
};
}
@@ -83,13 +43,17 @@ export function Query<C extends AnyComponentDef[]>(...components: C): QueryDescr
// Query Result Type
// =============================================================================
+type ComponentsData<C extends readonly AnyComponentDef[]> = {
+ [K in keyof C]: ComponentData<C[K]>;
+};
+
export type QueryResult<C extends readonly AnyComponentDef[]> = [
Entity,
...ComponentsData<C>
];
// =============================================================================
-// Query Instance
+// Query Instance (Runtime)
// =============================================================================
export class QueryInstance<C extends readonly AnyComponentDef[]> implements Iterable<QueryResult<C>> {
@@ -119,7 +83,7 @@ export class QueryInstance<C extends readonly AnyComponentDef[]> implements Iter
if (excluded) continue;
const components = _components.map(comp =>
- this.world_.getComponent(entity, comp)
+ this.world_.get(entity, comp)
) as ComponentsData<C>;
yield [entity, ...components] as QueryResult<C>;
@@ -155,25 +119,3 @@ export class QueryInstance<C extends readonly AnyComponentDef[]> implements Iter
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/renderer/Renderer.ts b/sdk/src/renderer/Renderer.ts
deleted file mode 100644
index 196c883da..000000000
--- a/sdk/src/renderer/Renderer.ts
+++ /dev/null
@@ -1,471 +0,0 @@
-/**
- * ESEngine TypeScript SDK - Renderer
- *
- * Provides rendering functionality using either native WebGL or WASM backend.
- */
-
-import { Vec2, Vec3, Color, Mat4, RendererStats, mat4Identity, mat4Ortho } from '../core/Types';
-import { isWasmLoaded, getWasmModule, withFloat32Array } from '../core/WasmBridge';
-
-/**
- * Renderer mode - determines which backend to use.
- */
-export enum RendererMode {
- /** Use native WebGL (TypeScript implementation) */
- Native = 'native',
- /** Use WASM backend (C++ implementation) */
- Wasm = 'wasm',
-}
-
-/**
- * Quad drawing options.
- */
-export interface DrawQuadOptions {
- position: Vec2 | Vec3;
- size: Vec2;
- color?: Color;
- textureId?: number;
- rotation?: number;
-}
-
-/**
- * Renderer - Static class for 2D rendering.
- */
-export class Renderer {
- private static gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
- private static mode: RendererMode = RendererMode.Native;
- private static initialized: boolean = false;
- private static viewProjection: Mat4 = mat4Identity();
- private static clearColor: Color = { r: 0, g: 0, b: 0, a: 1 };
- private static stats: RendererStats = { drawCalls: 0, triangleCount: 0, vertexCount: 0 };
-
- // Native rendering resources
- private static quadShader: WebGLProgram | null = null;
- private static quadVAO: WebGLVertexArrayObject | null = null;
- private static quadVBO: WebGLBuffer | null = null;
- private static quadIBO: WebGLBuffer | null = null;
-
- /**
- * Initialize the renderer.
- * @param gl WebGL context (null for WASM mode where C++ owns the context)
- * @param mode Renderer mode
- */
- static init(gl: WebGLRenderingContext | WebGL2RenderingContext | null, mode: RendererMode = RendererMode.Native): void {
- if (this.initialized) return;
-
- this.gl = gl;
- this.mode = mode;
-
- if (mode === RendererMode.Native && gl) {
- this.initNative();
- }
-
- this.initialized = true;
- }
-
- /**
- * Shut down the renderer.
- */
- static shutdown(): void {
- if (!this.initialized) return;
-
- if (this.mode === RendererMode.Native) {
- this.shutdownNative();
- }
-
- this.gl = null;
- this.initialized = false;
- }
-
- /**
- * Begin a new frame.
- */
- static beginFrame(): void {
- this.resetStats();
- }
-
- /**
- * End the current frame.
- */
- static endFrame(): void {
- // Flush any pending operations
- }
-
- /**
- * Set the viewport.
- */
- static setViewport(x: number, y: number, width: number, height: number): void {
- if (!this.gl) return;
- this.gl.viewport(x, y, width, height);
- }
-
- /**
- * Set the clear color.
- */
- static setClearColor(color: Color): void {
- this.clearColor = { ...color };
- if (this.gl) {
- this.gl.clearColor(color.r, color.g, color.b, color.a);
- }
- }
-
- /**
- * Clear the screen.
- */
- static clear(): void {
- if (!this.gl) return;
-
- if (this.mode === RendererMode.Wasm && isWasmLoaded()) {
- const module = getWasmModule();
- if (module._es_renderer_clear) {
- module._es_renderer_clear(
- this.clearColor.r,
- this.clearColor.g,
- this.clearColor.b,
- this.clearColor.a
- );
- return;
- }
- }
-
- this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
- }
-
- /**
- * Begin a scene with the given view-projection matrix.
- */
- static beginScene(viewProjection: Mat4): void {
- this.viewProjection = viewProjection;
-
- if (this.mode === RendererMode.Wasm && isWasmLoaded()) {
- const module = getWasmModule();
- if (module._es_renderer_begin_scene) {
- withFloat32Array(viewProjection, (ptr) => {
- module._es_renderer_begin_scene!(ptr);
- });
- return;
- }
- }
-
- // Native mode - set shader uniform
- if (this.quadShader && this.gl) {
- this.gl.useProgram(this.quadShader);
- const loc = this.gl.getUniformLocation(this.quadShader, 'u_ViewProjection');
- this.gl.uniformMatrix4fv(loc, false, viewProjection);
- }
- }
-
- /**
- * End the current scene.
- */
- static endScene(): void {
- if (this.mode === RendererMode.Wasm && isWasmLoaded()) {
- const module = getWasmModule();
- if (module._es_renderer_end_scene) {
- module._es_renderer_end_scene();
- }
- }
- }
-
- /**
- * Draw a colored quad.
- */
- static drawQuad(position: Vec2 | Vec3, size: Vec2, color: Color): void {
- const x = position.x;
- const y = position.y;
- const z = 'z' in position ? position.z : 0;
-
- if (this.mode === RendererMode.Wasm && isWasmLoaded()) {
- const module = getWasmModule();
- if (module._es_renderer_draw_quad) {
- module._es_renderer_draw_quad(
- x, y, size.x, size.y,
- color.r, color.g, color.b, color.a
- );
- this.stats.drawCalls++;
- this.stats.triangleCount += 2;
- this.stats.vertexCount += 4;
- return;
- }
- }
-
- // Native drawing
- this.drawQuadNative(x, y, z, size.x, size.y, color, -1);
- }
-
- /**
- * Draw a textured quad.
- */
- static drawTexturedQuad(
- position: Vec2 | Vec3,
- size: Vec2,
- textureId: number,
- tintColor: Color = { r: 1, g: 1, b: 1, a: 1 }
- ): void {
- const x = position.x;
- const y = position.y;
- const z = 'z' in position ? position.z : 0;
-
- if (this.mode === RendererMode.Wasm && isWasmLoaded()) {
- const module = getWasmModule();
- if (module._es_renderer_draw_quad_textured) {
- module._es_renderer_draw_quad_textured(
- x, y, size.x, size.y, textureId,
- tintColor.r, tintColor.g, tintColor.b, tintColor.a
- );
- this.stats.drawCalls++;
- this.stats.triangleCount += 2;
- this.stats.vertexCount += 4;
- return;
- }
- }
-
- // Native drawing
- this.drawQuadNative(x, y, z, size.x, size.y, tintColor, textureId);
- }
-
- /**
- * Get renderer statistics.
- */
- static getStats(): RendererStats {
- return { ...this.stats };
- }
-
- /**
- * Reset renderer statistics.
- */
- static resetStats(): void {
- this.stats = { drawCalls: 0, triangleCount: 0, vertexCount: 0 };
- }
-
- /**
- * Create an orthographic projection for 2D rendering.
- */
- static createOrtho2D(width: number, height: number): Mat4 {
- return mat4Ortho(0, width, height, 0, -1, 1);
- }
-
- // ========== Native WebGL Implementation ==========
-
- private static initNative(): void {
- const gl = this.gl;
- if (!gl) return;
-
- // Create shader program
- this.quadShader = this.createShaderProgram(QUAD_VERTEX_SHADER, QUAD_FRAGMENT_SHADER);
-
- // Create quad geometry
- const vertices = new Float32Array([
- // Position (x, y) // UV
- 0.0, 0.0, 0.0, 0.0,
- 1.0, 0.0, 1.0, 0.0,
- 1.0, 1.0, 1.0, 1.0,
- 0.0, 1.0, 0.0, 1.0,
- ]);
-
- const indices = new Uint16Array([0, 1, 2, 2, 3, 0]);
-
- // Check for WebGL2
- const gl2 = gl as WebGL2RenderingContext;
- if (typeof gl2.createVertexArray === 'function') {
- this.quadVAO = gl2.createVertexArray();
- gl2.bindVertexArray(this.quadVAO);
- }
-
- // Create VBO
- this.quadVBO = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVBO);
- gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
-
- // Create IBO
- this.quadIBO = gl.createBuffer();
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.quadIBO);
- gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
-
- // Set up vertex attributes
- const stride = 4 * 4; // 4 floats * 4 bytes
- gl.enableVertexAttribArray(0);
- gl.vertexAttribPointer(0, 2, gl.FLOAT, false, stride, 0);
- gl.enableVertexAttribArray(1);
- gl.vertexAttribPointer(1, 2, gl.FLOAT, false, stride, 2 * 4);
-
- if (typeof gl2.bindVertexArray === 'function') {
- gl2.bindVertexArray(null);
- }
-
- // Enable blending
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
- }
-
- private static shutdownNative(): void {
- const gl = this.gl;
- if (!gl) return;
-
- if (this.quadShader) {
- gl.deleteProgram(this.quadShader);
- this.quadShader = null;
- }
-
- if (this.quadVBO) {
- gl.deleteBuffer(this.quadVBO);
- this.quadVBO = null;
- }
-
- if (this.quadIBO) {
- gl.deleteBuffer(this.quadIBO);
- this.quadIBO = null;
- }
-
- const gl2 = gl as WebGL2RenderingContext;
- if (this.quadVAO && typeof gl2.deleteVertexArray === 'function') {
- gl2.deleteVertexArray(this.quadVAO);
- this.quadVAO = null;
- }
- }
-
- private static drawQuadNative(
- x: number,
- y: number,
- z: number,
- w: number,
- h: number,
- color: Color,
- textureId: number
- ): void {
- const gl = this.gl;
- if (!gl || !this.quadShader) return;
-
- gl.useProgram(this.quadShader);
-
- // Set uniforms
- const uTransform = gl.getUniformLocation(this.quadShader, 'u_Transform');
- const uColor = gl.getUniformLocation(this.quadShader, 'u_Color');
- const uUseTexture = gl.getUniformLocation(this.quadShader, 'u_UseTexture');
-
- // Simple transform: translate and scale
- const transform = new Float32Array([
- w, 0, 0, 0,
- 0, h, 0, 0,
- 0, 0, 1, 0,
- x, y, z, 1,
- ]);
-
- gl.uniformMatrix4fv(uTransform, false, transform);
- gl.uniform4f(uColor, color.r, color.g, color.b, color.a);
- gl.uniform1i(uUseTexture, textureId >= 0 ? 1 : 0);
-
- // Bind texture if needed
- if (textureId >= 0) {
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, textureId as unknown as WebGLTexture);
- const uTexture = gl.getUniformLocation(this.quadShader, 'u_Texture');
- gl.uniform1i(uTexture, 0);
- }
-
- // Draw
- const gl2 = gl as WebGL2RenderingContext;
- if (this.quadVAO && typeof gl2.bindVertexArray === 'function') {
- gl2.bindVertexArray(this.quadVAO);
- } else {
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVBO);
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.quadIBO);
- gl.enableVertexAttribArray(0);
- gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(1);
- gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 16, 8);
- }
-
- gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
-
- if (typeof gl2.bindVertexArray === 'function') {
- gl2.bindVertexArray(null);
- }
-
- this.stats.drawCalls++;
- this.stats.triangleCount += 2;
- this.stats.vertexCount += 4;
- }
-
- private static createShaderProgram(vertexSource: string, fragmentSource: string): WebGLProgram | null {
- const gl = this.gl;
- if (!gl) return null;
-
- const vertexShader = this.compileShader(gl.VERTEX_SHADER, vertexSource);
- const fragmentShader = this.compileShader(gl.FRAGMENT_SHADER, fragmentSource);
-
- if (!vertexShader || !fragmentShader) return null;
-
- const program = gl.createProgram();
- if (!program) return null;
-
- gl.attachShader(program, vertexShader);
- gl.attachShader(program, fragmentShader);
- gl.linkProgram(program);
-
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- console.error('Shader program link error:', gl.getProgramInfoLog(program));
- gl.deleteProgram(program);
- return null;
- }
-
- gl.deleteShader(vertexShader);
- gl.deleteShader(fragmentShader);
-
- return program;
- }
-
- private static compileShader(type: number, source: string): WebGLShader | null {
- const gl = this.gl;
- if (!gl) return null;
-
- const shader = gl.createShader(type);
- if (!shader) return null;
-
- gl.shaderSource(shader, source);
- gl.compileShader(shader);
-
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
- console.error('Shader compile error:', gl.getShaderInfoLog(shader));
- gl.deleteShader(shader);
- return null;
- }
-
- return shader;
- }
-}
-
-// ========== Shader Sources ==========
-
-const QUAD_VERTEX_SHADER = `
-attribute vec2 a_Position;
-attribute vec2 a_TexCoord;
-
-uniform mat4 u_ViewProjection;
-uniform mat4 u_Transform;
-
-varying vec2 v_TexCoord;
-
-void main() {
- v_TexCoord = a_TexCoord;
- gl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 0.0, 1.0);
-}
-`;
-
-const QUAD_FRAGMENT_SHADER = `
-precision mediump float;
-
-varying vec2 v_TexCoord;
-
-uniform vec4 u_Color;
-uniform sampler2D u_Texture;
-uniform int u_UseTexture;
-
-void main() {
- if (u_UseTexture == 1) {
- gl_FragColor = texture2D(u_Texture, v_TexCoord) * u_Color;
- } else {
- gl_FragColor = u_Color;
- }
-}
-`;
diff --git a/sdk/src/framework/resource.ts b/sdk/src/resource.ts
similarity index 87%
rename from sdk/src/framework/resource.ts
rename to sdk/src/resource.ts
index 217656647..ef7cbf428 100644
--- a/sdk/src/framework/resource.ts
+++ b/sdk/src/resource.ts
@@ -1,12 +1,6 @@
/**
* @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.
+ * @brief Resource system for global singleton data
*/
// =============================================================================
@@ -15,8 +9,8 @@
export interface ResourceDef<T> {
readonly _id: symbol;
- readonly _default: T;
readonly _name: string;
+ readonly _default: T;
}
let resourceCounter = 0;
@@ -25,8 +19,8 @@ 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}`
+ _name: name ?? `Resource_${id}`,
+ _default: defaultValue
};
}
@@ -56,14 +50,6 @@ export function ResMut<T>(resource: ResourceDef<T>): ResMutDescriptor<T> {
// 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;
@@ -118,10 +104,6 @@ export class ResourceStorage {
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),
@@ -131,7 +113,7 @@ export class ResourceStorage {
}
// =============================================================================
-// Built-in Resources
+// Builtin Resources
// =============================================================================
export interface TimeData {
diff --git a/sdk/src/scene/SceneLoader.ts b/sdk/src/scene/SceneLoader.ts
deleted file mode 100644
index 1ed937304..000000000
--- a/sdk/src/scene/SceneLoader.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 46000cb52..000000000
--- a/sdk/src/scene/index.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * @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/framework/system.ts b/sdk/src/system.ts
similarity index 81%
rename from sdk/src/framework/system.ts
rename to sdk/src/system.ts
index 7e47419b9..2252d4617 100644
--- a/sdk/src/framework/system.ts
+++ b/sdk/src/system.ts
@@ -1,18 +1,29 @@
/**
* @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.
+ * @brief System definition and scheduling
*/
+import { AnyComponentDef } from './component';
import { QueryDescriptor, QueryInstance } from './query';
-import { ResDescriptor, ResMutDescriptor, ResInstance, ResMutInstance, ResourceStorage } from './resource';
+import { ResDescriptor, ResMutDescriptor, ResMutInstance, ResourceStorage } from './resource';
import { CommandsDescriptor, CommandsInstance } from './commands';
-import { World, AnyComponentDef } from './world';
+import type { World } from './world';
+
+// =============================================================================
+// Schedule Phases
+// =============================================================================
+
+export enum Schedule {
+ Startup = 0,
+ First = 1,
+ PreUpdate = 2,
+ Update = 3,
+ PostUpdate = 4,
+ Last = 5,
+ FixedPreUpdate = 10,
+ FixedUpdate = 11,
+ FixedPostUpdate = 12,
+}
// =============================================================================
// System Parameter Types
@@ -107,24 +118,7 @@ export class SystemRunner {
return new CommandsInstance(this.world_, this.resources_);
default:
- throw new Error(`Unknown system parameter type`);
+ 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/types.ts b/sdk/src/types.ts
new file mode 100644
index 000000000..0f0760504
--- /dev/null
+++ b/sdk/src/types.ts
@@ -0,0 +1,52 @@
+/**
+ * @file types.ts
+ * @brief Core type definitions for ESEngine SDK
+ */
+
+// =============================================================================
+// Entity
+// =============================================================================
+
+export type Entity = number;
+export const INVALID_ENTITY = 0 as Entity;
+
+// =============================================================================
+// 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 Quat {
+ w: number;
+ x: number;
+ y: number;
+ z: number;
+}
+
+export type Color = Vec4;
+
+// =============================================================================
+// Factory Functions
+// =============================================================================
+
+export const vec2 = (x = 0, y = 0): Vec2 => ({ x, y });
+export const vec3 = (x = 0, y = 0, z = 0): Vec3 => ({ x, y, z });
+export const vec4 = (x = 0, y = 0, z = 0, w = 1): Vec4 => ({ x, y, z, w });
+export const color = (r = 1, g = 1, b = 1, a = 1): Color => ({ x: r, y: g, z: b, w: a });
+export const quat = (w = 1, x = 0, y = 0, z = 0): Quat => ({ w, x, y, z });
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
new file mode 100644
index 000000000..11d4b8020
--- /dev/null
+++ b/sdk/src/wasm.ts
@@ -0,0 +1,86 @@
+/**
+ * @file wasm.ts
+ * @brief WASM module type definitions
+ */
+
+import { Entity } from './types';
+
+// =============================================================================
+// 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;
+
+ addWorldTransform(entity: Entity, data: unknown): void;
+ getWorldTransform(entity: Entity): unknown;
+ hasWorldTransform(entity: Entity): boolean;
+ removeWorldTransform(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;
+
+ addParent(entity: Entity, data: unknown): void;
+ getParent(entity: Entity): unknown;
+ hasParent(entity: Entity): boolean;
+ removeParent(entity: Entity): void;
+
+ addChildren(entity: Entity, data: unknown): void;
+ getChildren(entity: Entity): unknown;
+ hasChildren(entity: Entity): boolean;
+ removeChildren(entity: Entity): void;
+
+ [key: string]: unknown;
+}
+
+// =============================================================================
+// C++ Resource Manager
+// =============================================================================
+
+export interface CppResourceManager {
+ createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number): number;
+ createShader(vertSrc: string, fragSrc: string): number;
+ releaseTexture(handle: number): void;
+ releaseShader(handle: number): void;
+}
+
+// =============================================================================
+// WASM Module Interface
+// =============================================================================
+
+export interface ESEngineModule {
+ Registry: new () => CppRegistry;
+ HEAPU8: Uint8Array;
+
+ initRenderer(): void;
+ shutdownRenderer(): void;
+ renderFrame(registry: CppRegistry, width: number, height: number): void;
+ getResourceManager(): CppResourceManager;
+
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+}
diff --git a/sdk/src/wasm/index.ts b/sdk/src/wasm/index.ts
deleted file mode 100644
index 4f6c50932..000000000
--- a/sdk/src/wasm/index.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 6f13dd194..000000000
--- a/sdk/src/wasm/types.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-/**
- * @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/sdk/src/world.ts b/sdk/src/world.ts
new file mode 100644
index 000000000..ecd8ef98a
--- /dev/null
+++ b/sdk/src/world.ts
@@ -0,0 +1,212 @@
+/**
+ * @file world.ts
+ * @brief ECS World with C++ Registry integration
+ */
+
+import { Entity } from './types';
+import { AnyComponentDef, ComponentDef, BuiltinComponentDef, isBuiltinComponent } from './component';
+import type { CppRegistry } from './wasm';
+
+// =============================================================================
+// World
+// =============================================================================
+
+export class World {
+ private cppRegistry_: CppRegistry | null = null;
+ private entities_ = new Set<Entity>();
+ private tsStorage_ = new Map<symbol, Map<Entity, unknown>>();
+
+ connectCpp(cppRegistry: CppRegistry): void {
+ this.cppRegistry_ = cppRegistry;
+ }
+
+ get hasCpp(): boolean {
+ return this.cppRegistry_ !== null;
+ }
+
+ // =========================================================================
+ // Entity Management
+ // =========================================================================
+
+ spawn(): Entity {
+ let entity: Entity;
+
+ if (this.cppRegistry_) {
+ entity = this.cppRegistry_.create();
+ } else {
+ entity = (this.entities_.size + 1) as Entity;
+ }
+
+ this.entities_.add(entity);
+ return entity;
+ }
+
+ despawn(entity: Entity): void {
+ if (this.cppRegistry_) {
+ this.cppRegistry_.destroy(entity);
+ }
+ this.entities_.delete(entity);
+
+ for (const storage of this.tsStorage_.values()) {
+ storage.delete(entity);
+ }
+ }
+
+ valid(entity: Entity): boolean {
+ if (this.cppRegistry_) {
+ return this.cppRegistry_.valid(entity);
+ }
+ return this.entities_.has(entity);
+ }
+
+ entityCount(): number {
+ return this.entities_.size;
+ }
+
+ getAllEntities(): Entity[] {
+ return Array.from(this.entities_);
+ }
+
+ // =========================================================================
+ // Component Management
+ // =========================================================================
+
+ insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown {
+ if (isBuiltinComponent(component)) {
+ return this.insertBuiltin(entity, component, data);
+ }
+ return this.insertScript(entity, component as ComponentDef<any>, data);
+ }
+
+ get(entity: Entity, component: AnyComponentDef): unknown {
+ if (isBuiltinComponent(component)) {
+ return this.getBuiltin(entity, component);
+ }
+ return this.getScript(entity, component as ComponentDef<any>);
+ }
+
+ has(entity: Entity, component: AnyComponentDef): boolean {
+ if (isBuiltinComponent(component)) {
+ return this.hasBuiltin(entity, component);
+ }
+ return this.hasScript(entity, component as ComponentDef<any>);
+ }
+
+ remove(entity: Entity, component: AnyComponentDef): void {
+ if (isBuiltinComponent(component)) {
+ this.removeBuiltin(entity, component);
+ } else {
+ this.removeScript(entity, component as ComponentDef<any>);
+ }
+ }
+
+ // =========================================================================
+ // Builtin Component Operations (C++ Registry)
+ // =========================================================================
+
+ private insertBuiltin(entity: Entity, component: BuiltinComponentDef<any>, data?: unknown): unknown {
+ const merged = { ...component._default, ...(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<any>): 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<any>): 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 (TypeScript storage)
+ // =========================================================================
+
+ private insertScript<T>(entity: Entity, component: ComponentDef<T>, data?: unknown): T {
+ const value = component.create(data as Partial<T>);
+ this.getStorage(component).set(entity, value);
+ return value;
+ }
+
+ private getScript<T>(entity: Entity, component: ComponentDef<T>): T {
+ const storage = this.tsStorage_.get(component._id);
+ if (!storage) {
+ throw new Error(`Component not found: ${component._name}`);
+ }
+ return storage.get(entity) as T;
+ }
+
+ private hasScript<T>(entity: Entity, component: ComponentDef<T>): boolean {
+ const storage = this.tsStorage_.get(component._id);
+ return storage?.has(entity) ?? false;
+ }
+
+ private removeScript<T>(entity: Entity, component: ComponentDef<T>): void {
+ const storage = this.tsStorage_.get(component._id);
+ storage?.delete(entity);
+ }
+
+ private getStorage(component: ComponentDef<any>): Map<Entity, unknown> {
+ let storage = this.tsStorage_.get(component._id);
+ if (!storage) {
+ storage = new Map();
+ this.tsStorage_.set(component._id, storage);
+ }
+ return storage;
+ }
+
+ // =========================================================================
+ // Query Support
+ // =========================================================================
+
+ getEntitiesWithComponents(components: AnyComponentDef[]): Entity[] {
+ if (components.length === 0) {
+ return this.getAllEntities();
+ }
+
+ 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;
+ }
+}
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index fa6e8debc..b316d3f7c 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -1,13 +1,9 @@
/**
* @file WebBindings.generated.cpp
* @brief Auto-generated Emscripten embind bindings
- * @details Generated by EHT (ESEngine Header Tool) - DO NOT EDIT
- *
- * @author ESEngine Team
- * @date 2026
+ * @details Generated by EHT - DO NOT EDIT
*
* @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
*/
#ifdef ES_PLATFORM_WEB
@@ -15,7 +11,6 @@
#include <emscripten/bind.h>
#include "../ecs/Registry.hpp"
#include "../math/Math.hpp"
-
#include "../ecs/components/Camera.hpp"
#include "../ecs/components/Canvas.hpp"
#include "../ecs/components/Hierarchy.hpp"
@@ -80,55 +75,151 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {
// Components
// =============================================================================
+struct CameraJS {
+ i32 projectionType;
+ f32 fov;
+ f32 orthoSize;
+ f32 nearPlane;
+ f32 farPlane;
+ f32 aspectRatio;
+ bool isActive;
+ i32 priority;
+};
+
+esengine::ecs::Camera cameraFromJS(const CameraJS& js) {
+ esengine::ecs::Camera c;
+ c.projectionType = static_cast<ProjectionType>(js.projectionType);
+ c.fov = js.fov;
+ c.orthoSize = js.orthoSize;
+ c.nearPlane = js.nearPlane;
+ c.farPlane = js.farPlane;
+ c.aspectRatio = js.aspectRatio;
+ c.isActive = js.isActive;
+ c.priority = js.priority;
+ return c;
+}
+
+CameraJS cameraToJS(const esengine::ecs::Camera& c) {
+ CameraJS js;
+ js.projectionType = static_cast<i32>(c.projectionType);
+ js.fov = c.fov;
+ js.orthoSize = c.orthoSize;
+ js.nearPlane = c.nearPlane;
+ js.farPlane = c.farPlane;
+ js.aspectRatio = c.aspectRatio;
+ js.isActive = c.isActive;
+ js.priority = c.priority;
+ return js;
+}
+
+struct CanvasJS {
+ glm::uvec2 designResolution;
+ f32 pixelsPerUnit;
+ i32 scaleMode;
+ f32 matchWidthOrHeight;
+ glm::vec4 backgroundColor;
+};
+
+esengine::ecs::Canvas canvasFromJS(const CanvasJS& js) {
+ esengine::ecs::Canvas c;
+ c.designResolution = js.designResolution;
+ c.pixelsPerUnit = js.pixelsPerUnit;
+ c.scaleMode = static_cast<CanvasScaleMode>(js.scaleMode);
+ c.matchWidthOrHeight = js.matchWidthOrHeight;
+ c.backgroundColor = js.backgroundColor;
+ return c;
+}
+
+CanvasJS canvasToJS(const esengine::ecs::Canvas& c) {
+ CanvasJS js;
+ js.designResolution = c.designResolution;
+ js.pixelsPerUnit = c.pixelsPerUnit;
+ js.scaleMode = static_cast<i32>(c.scaleMode);
+ js.matchWidthOrHeight = c.matchWidthOrHeight;
+ js.backgroundColor = c.backgroundColor;
+ return js;
+}
+
+struct SpriteJS {
+ u32 texture;
+ glm::vec4 color;
+ glm::vec2 size;
+ glm::vec2 uvOffset;
+ glm::vec2 uvScale;
+ i32 layer;
+ bool flipX;
+ bool flipY;
+};
+
+esengine::ecs::Sprite spriteFromJS(const SpriteJS& js) {
+ esengine::ecs::Sprite c;
+ c.texture = resource::TextureHandle(js.texture);
+ c.color = js.color;
+ c.size = js.size;
+ c.uvOffset = js.uvOffset;
+ c.uvScale = js.uvScale;
+ c.layer = js.layer;
+ c.flipX = js.flipX;
+ c.flipY = js.flipY;
+ return c;
+}
+
+SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {
+ SpriteJS js;
+ js.texture = c.texture.id();
+ js.color = c.color;
+ js.size = c.size;
+ js.uvOffset = c.uvOffset;
+ js.uvScale = c.uvScale;
+ js.layer = c.layer;
+ js.flipX = c.flipX;
+ js.flipY = c.flipY;
+ return js;
+}
+
EMSCRIPTEN_BINDINGS(esengine_components) {
- // Camera
- value_object<esengine::ecs::Camera>("Camera")
- .field("projectionType", &esengine::ecs::Camera::projectionType)
- .field("fov", &esengine::ecs::Camera::fov)
- .field("orthoSize", &esengine::ecs::Camera::orthoSize)
- .field("nearPlane", &esengine::ecs::Camera::nearPlane)
- .field("farPlane", &esengine::ecs::Camera::farPlane)
- .field("aspectRatio", &esengine::ecs::Camera::aspectRatio)
- .field("isActive", &esengine::ecs::Camera::isActive)
- .field("priority", &esengine::ecs::Camera::priority);
-
- // Canvas
- value_object<esengine::ecs::Canvas>("Canvas")
- .field("pixelsPerUnit", &esengine::ecs::Canvas::pixelsPerUnit)
- .field("scaleMode", &esengine::ecs::Canvas::scaleMode)
- .field("matchWidthOrHeight", &esengine::ecs::Canvas::matchWidthOrHeight)
- .field("backgroundColor", &esengine::ecs::Canvas::backgroundColor);
-
- // Parent
+ value_object<CameraJS>("Camera")
+ .field("projectionType", &CameraJS::projectionType)
+ .field("fov", &CameraJS::fov)
+ .field("orthoSize", &CameraJS::orthoSize)
+ .field("nearPlane", &CameraJS::nearPlane)
+ .field("farPlane", &CameraJS::farPlane)
+ .field("aspectRatio", &CameraJS::aspectRatio)
+ .field("isActive", &CameraJS::isActive)
+ .field("priority", &CameraJS::priority);
+
+ value_object<CanvasJS>("Canvas")
+ .field("designResolution", &CanvasJS::designResolution)
+ .field("pixelsPerUnit", &CanvasJS::pixelsPerUnit)
+ .field("scaleMode", &CanvasJS::scaleMode)
+ .field("matchWidthOrHeight", &CanvasJS::matchWidthOrHeight)
+ .field("backgroundColor", &CanvasJS::backgroundColor);
+
value_object<esengine::ecs::Parent>("Parent")
.field("entity", &esengine::ecs::Parent::entity);
- // Children
value_object<esengine::ecs::Children>("Children");
- // Sprite
- value_object<esengine::ecs::Sprite>("Sprite")
- .field("color", &esengine::ecs::Sprite::color)
- .field("size", &esengine::ecs::Sprite::size)
- .field("uvOffset", &esengine::ecs::Sprite::uvOffset)
- .field("uvScale", &esengine::ecs::Sprite::uvScale)
- .field("layer", &esengine::ecs::Sprite::layer)
- .field("flipX", &esengine::ecs::Sprite::flipX)
- .field("flipY", &esengine::ecs::Sprite::flipY);
-
- // LocalTransform
+ value_object<SpriteJS>("Sprite")
+ .field("texture", &SpriteJS::texture)
+ .field("color", &SpriteJS::color)
+ .field("size", &SpriteJS::size)
+ .field("uvOffset", &SpriteJS::uvOffset)
+ .field("uvScale", &SpriteJS::uvScale)
+ .field("layer", &SpriteJS::layer)
+ .field("flipX", &SpriteJS::flipX)
+ .field("flipY", &SpriteJS::flipY);
+
value_object<esengine::ecs::LocalTransform>("LocalTransform")
.field("position", &esengine::ecs::LocalTransform::position)
.field("rotation", &esengine::ecs::LocalTransform::rotation)
.field("scale", &esengine::ecs::LocalTransform::scale);
- // WorldTransform
value_object<esengine::ecs::WorldTransform>("WorldTransform")
.field("position", &esengine::ecs::WorldTransform::position)
.field("rotation", &esengine::ecs::WorldTransform::rotation)
.field("scale", &esengine::ecs::WorldTransform::scale);
- // Velocity
value_object<esengine::ecs::Velocity>("Velocity")
.field("linear", &esengine::ecs::Velocity::linear)
.field("angular", &esengine::ecs::Velocity::angular);
@@ -157,11 +248,11 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
.function("hasCamera", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Camera>(static_cast<Entity>(e));
}))
- .function("getCamera", optional_override([](Registry& r, u32 e) -> esengine::ecs::Camera& {
- return r.get<esengine::ecs::Camera>(static_cast<Entity>(e));
- }), allow_raw_pointers())
- .function("addCamera", optional_override([](Registry& r, u32 e, const esengine::ecs::Camera& c) {
- r.emplaceOrReplace<esengine::ecs::Camera>(static_cast<Entity>(e), c);
+ .function("getCamera", optional_override([](Registry& r, u32 e) {
+ return cameraToJS(r.get<esengine::ecs::Camera>(static_cast<Entity>(e)));
+ }))
+ .function("addCamera", optional_override([](Registry& r, u32 e, const CameraJS& js) {
+ r.emplaceOrReplace<esengine::ecs::Camera>(static_cast<Entity>(e), cameraFromJS(js));
}))
.function("removeCamera", optional_override([](Registry& r, u32 e) {
r.remove<esengine::ecs::Camera>(static_cast<Entity>(e));
@@ -171,11 +262,11 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
.function("hasCanvas", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Canvas>(static_cast<Entity>(e));
}))
- .function("getCanvas", optional_override([](Registry& r, u32 e) -> esengine::ecs::Canvas& {
- return r.get<esengine::ecs::Canvas>(static_cast<Entity>(e));
- }), allow_raw_pointers())
- .function("addCanvas", optional_override([](Registry& r, u32 e, const esengine::ecs::Canvas& c) {
- r.emplaceOrReplace<esengine::ecs::Canvas>(static_cast<Entity>(e), c);
+ .function("getCanvas", optional_override([](Registry& r, u32 e) {
+ return canvasToJS(r.get<esengine::ecs::Canvas>(static_cast<Entity>(e)));
+ }))
+ .function("addCanvas", optional_override([](Registry& r, u32 e, const CanvasJS& js) {
+ r.emplaceOrReplace<esengine::ecs::Canvas>(static_cast<Entity>(e), canvasFromJS(js));
}))
.function("removeCanvas", optional_override([](Registry& r, u32 e) {
r.remove<esengine::ecs::Canvas>(static_cast<Entity>(e));
@@ -213,11 +304,11 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
.function("hasSprite", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Sprite>(static_cast<Entity>(e));
}))
- .function("getSprite", optional_override([](Registry& r, u32 e) -> esengine::ecs::Sprite& {
- return r.get<esengine::ecs::Sprite>(static_cast<Entity>(e));
- }), allow_raw_pointers())
- .function("addSprite", optional_override([](Registry& r, u32 e, const esengine::ecs::Sprite& c) {
- r.emplaceOrReplace<esengine::ecs::Sprite>(static_cast<Entity>(e), c);
+ .function("getSprite", optional_override([](Registry& r, u32 e) {
+ return spriteToJS(r.get<esengine::ecs::Sprite>(static_cast<Entity>(e)));
+ }))
+ .function("addSprite", optional_override([](Registry& r, u32 e, const SpriteJS& js) {
+ r.emplaceOrReplace<esengine::ecs::Sprite>(static_cast<Entity>(e), spriteFromJS(js));
}))
.function("removeSprite", optional_override([](Registry& r, u32 e) {
r.remove<esengine::ecs::Sprite>(static_cast<Entity>(e));
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 0e9f9b010..903223404 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -1,7 +1,6 @@
/**
* @file WebSDKEntry.cpp
- * @brief ESEngine Web SDK entry point
- * @details Minimal entry for SDK library, no application logic
+ * @brief ESEngine Web SDK entry point with rendering support
*
* @author ESEngine Team
* @date 2026
@@ -13,23 +12,175 @@
#ifdef ES_PLATFORM_WEB
#include <emscripten.h>
+#include <emscripten/bind.h>
+#include <emscripten/html5.h>
-extern "C" {
+#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/RenderPipeline.hpp"
+#include "../renderer/Texture.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../ecs/Registry.hpp"
+#include "../ecs/components/Camera.hpp"
+#include "../ecs/components/Transform.hpp"
-EMSCRIPTEN_KEEPALIVE
-void es_sdk_init() {
- // SDK initialization - can be extended as needed
+#include <glm/gtc/matrix_transform.hpp>
+
+namespace esengine {
+
+static Unique<RenderContext> g_renderContext;
+static Unique<RenderPipeline> g_renderPipeline;
+static Unique<resource::ResourceManager> g_resourceManager;
+static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE g_webglContext = 0;
+static bool g_initialized = false;
+
+void initRenderer() {
+ if (g_initialized) return;
+
+ // Create WebGL2 context
+ EmscriptenWebGLContextAttributes attrs;
+ emscripten_webgl_init_context_attributes(&attrs);
+ attrs.majorVersion = 2;
+ attrs.minorVersion = 0;
+ attrs.alpha = true;
+ attrs.depth = true;
+ attrs.stencil = false;
+ attrs.antialias = true;
+ attrs.premultipliedAlpha = true;
+ attrs.preserveDrawingBuffer = false;
+ attrs.powerPreference = EM_WEBGL_POWER_PREFERENCE_DEFAULT;
+ attrs.failIfMajorPerformanceCaveat = false;
+
+ g_webglContext = emscripten_webgl_create_context("#canvas", &attrs);
+ if (g_webglContext <= 0) {
+ ES_LOG_ERROR("Failed to create WebGL2 context: {}", g_webglContext);
+ return;
+ }
+
+ EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(g_webglContext);
+ if (result != EMSCRIPTEN_RESULT_SUCCESS) {
+ ES_LOG_ERROR("Failed to make WebGL context current: {}", result);
+ return;
+ }
+
+ ES_LOG_INFO("WebGL2 context created successfully");
+
+ g_resourceManager = makeUnique<resource::ResourceManager>();
+ g_resourceManager->init();
+
+ g_renderContext = makeUnique<RenderContext>();
+ g_renderContext->init();
+
+ g_renderPipeline = makeUnique<RenderPipeline>(*g_renderContext, *g_resourceManager);
+
+ g_initialized = true;
+}
+
+void shutdownRenderer() {
+ if (!g_initialized) return;
+
+ g_renderPipeline.reset();
+ g_renderContext->shutdown();
+ g_renderContext.reset();
+ g_resourceManager->shutdown();
+ g_resourceManager.reset();
+
+ if (g_webglContext > 0) {
+ emscripten_webgl_destroy_context(g_webglContext);
+ g_webglContext = 0;
+ }
+
+ g_initialized = false;
+}
+
+resource::ResourceManager* getResourceManager() {
+ return g_resourceManager.get();
+}
+
+u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,
+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format) {
+ const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);
+ ConstSpan<u8> pixelSpan(pixels, pixelsLen);
+
+ TextureFormat texFormat = TextureFormat::RGBA8;
+ if (format == 0) texFormat = TextureFormat::RGB8;
+ else if (format == 1) texFormat = TextureFormat::RGBA8;
+
+ auto handle = rm.createTexture(width, height, pixelSpan, texFormat);
+ return handle.id();
+}
+
+u32 rm_createShader(resource::ResourceManager& rm,
+ const std::string& vertSrc, const std::string& fragSrc) {
+ auto handle = rm.createShader(vertSrc, fragSrc);
+ return handle.id();
}
-EMSCRIPTEN_KEEPALIVE
-const char* es_sdk_version() {
- return "0.1.0";
+void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId) {
+ rm.releaseTexture(resource::TextureHandle(handleId));
}
-} // extern "C"
+void rm_releaseShader(resource::ResourceManager& rm, u32 handleId) {
+ rm.releaseShader(resource::ShaderHandle(handleId));
+}
+
+void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight) {
+ if (!g_initialized || !g_renderContext) return;
+
+ glViewport(0, 0, viewportWidth, viewportHeight);
+ glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ glm::mat4 viewProjection = glm::mat4(1.0f);
+
+ auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
+ for (auto entity : cameraView) {
+ auto& camera = registry.get<ecs::Camera>(entity);
+ if (!camera.isActive) continue;
+
+ auto& transform = registry.get<ecs::LocalTransform>(entity);
+ glm::mat4 view = glm::inverse(glm::translate(glm::mat4(1.0f), transform.position));
+
+ glm::mat4 projection;
+ if (camera.projectionType == ecs::ProjectionType::Orthographic) {
+ f32 aspect = static_cast<f32>(viewportWidth) / static_cast<f32>(viewportHeight);
+ f32 halfHeight = camera.orthoSize;
+ f32 halfWidth = halfHeight * aspect;
+ projection = glm::ortho(-halfWidth, halfWidth, -halfHeight, halfHeight,
+ camera.nearPlane, camera.farPlane);
+ } else {
+ projection = glm::perspective(
+ glm::radians(camera.fov),
+ static_cast<f32>(viewportWidth) / static_cast<f32>(viewportHeight),
+ camera.nearPlane, camera.farPlane
+ );
+ }
+
+ viewProjection = projection * view;
+ break;
+ }
+
+ g_renderPipeline->begin(viewProjection);
+ g_renderPipeline->submit(registry);
+ g_renderPipeline->end();
+}
+
+} // namespace esengine
+
+EMSCRIPTEN_BINDINGS(esengine_renderer) {
+ emscripten::function("initRenderer", &esengine::initRenderer);
+ emscripten::function("shutdownRenderer", &esengine::shutdownRenderer);
+ emscripten::function("renderFrame", &esengine::renderFrame);
+ emscripten::function("getResourceManager", &esengine::getResourceManager, emscripten::allow_raw_pointers());
+
+ emscripten::class_<esengine::resource::ResourceManager>("ResourceManager")
+ .function("createTexture", &esengine::rm_createTexture)
+ .function("createShader", &esengine::rm_createShader)
+ .function("releaseTexture", &esengine::rm_releaseTexture)
+ .function("releaseShader", &esengine::rm_releaseShader);
+}
int main() {
- // Empty main - SDK is library-only, no application loop
return 0;
}
diff --git a/data/shaders/axis.esshader b/src/esengine/data/shaders/axis.esshader
similarity index 100%
rename from data/shaders/axis.esshader
rename to src/esengine/data/shaders/axis.esshader
diff --git a/data/shaders/batch.esshader b/src/esengine/data/shaders/batch.esshader
similarity index 100%
rename from data/shaders/batch.esshader
rename to src/esengine/data/shaders/batch.esshader
diff --git a/data/shaders/color.esshader b/src/esengine/data/shaders/color.esshader
similarity index 100%
rename from data/shaders/color.esshader
rename to src/esengine/data/shaders/color.esshader
diff --git a/data/shaders/gizmo.esshader b/src/esengine/data/shaders/gizmo.esshader
similarity index 100%
rename from data/shaders/gizmo.esshader
rename to src/esengine/data/shaders/gizmo.esshader
diff --git a/data/shaders/grid.esshader b/src/esengine/data/shaders/grid.esshader
similarity index 100%
rename from data/shaders/grid.esshader
rename to src/esengine/data/shaders/grid.esshader
diff --git a/data/shaders/sprite.esshader b/src/esengine/data/shaders/sprite.esshader
similarity index 100%
rename from data/shaders/sprite.esshader
rename to src/esengine/data/shaders/sprite.esshader
diff --git a/data/shaders/ui.esshader b/src/esengine/data/shaders/ui.esshader
similarity index 100%
rename from data/shaders/ui.esshader
rename to src/esengine/data/shaders/ui.esshader
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index f662bc3f9..7f331868d 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -114,6 +114,29 @@ public:
return entities;
}
+ /**
+ * @brief Restores a previously destroyed entity with the same ID
+ * @param entity The entity ID to restore
+ * @return true if restored successfully, false if entity is already valid
+ */
+ bool restore(Entity entity) {
+ if (valid(entity)) {
+ return false;
+ }
+
+ if (entity >= entityValid_.size()) {
+ entityValid_.resize(entity + 1, false);
+ }
+ entityValid_[entity] = true;
+
+ if (entity >= nextEntity_) {
+ nextEntity_ = entity + 1;
+ }
+
+ ES_LOG_TRACE("Restored entity {}", entity);
+ return true;
+ }
+
/**
* @brief Destroys an entity and removes all its components
* @param entity The entity to destroy
diff --git a/src/esengine/ecs/components/Common.hpp b/src/esengine/ecs/components/Common.hpp
index 79709f999..b3e25f103 100644
--- a/src/esengine/ecs/components/Common.hpp
+++ b/src/esengine/ecs/components/Common.hpp
@@ -17,6 +17,7 @@
#include "../../core/Types.hpp"
+#include <glm/glm.hpp>
#include <string>
#include <unordered_map>
#include <variant>
diff --git a/src/esengine/ecs/components/Transform.hpp b/src/esengine/ecs/components/Transform.hpp
index b4d9cd3be..e6e8f56b5 100644
--- a/src/esengine/ecs/components/Transform.hpp
+++ b/src/esengine/ecs/components/Transform.hpp
@@ -134,26 +134,4 @@ struct WorldTransform {
*/
struct TransformDirty {};
-// =============================================================================
-// Legacy Transform (Deprecated)
-// =============================================================================
-
-/**
- * @brief Legacy transform component (deprecated)
- *
- * @deprecated Use LocalTransform and WorldTransform instead.
- * This component is kept for backward compatibility and
- * will be removed in a future version.
- */
-struct [[deprecated("Use LocalTransform instead")]] Transform {
- glm::vec3 position{0.0f, 0.0f, 0.0f};
- glm::vec3 rotation{0.0f, 0.0f, 0.0f};
- glm::vec3 scale{1.0f, 1.0f, 1.0f};
-
- Transform() = default;
- explicit Transform(const glm::vec3& pos) : position(pos) {}
- Transform(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl)
- : position(pos), rotation(rot), scale(scl) {}
-};
-
} // namespace esengine::ecs
diff --git a/src/esengine/ecs/systems/ScriptSystem.cpp b/src/esengine/ecs/systems/ScriptSystem.cpp
deleted file mode 100644
index f78315a51..000000000
--- a/src/esengine/ecs/systems/ScriptSystem.cpp
+++ /dev/null
@@ -1,313 +0,0 @@
-/**
- * @file ScriptSystem.cpp
- * @brief Implementation of the script system
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ScriptSystem.hpp"
-#include "../Registry.hpp"
-#include "../../core/Log.hpp"
-#include "../../scripting/ScriptValue.hpp"
-
-#ifdef ES_SCRIPTING_ENABLED
- #include <quickjs.h>
-#endif
-
-namespace esengine::ecs {
-
-ScriptSystem::ScriptSystem(ScriptContext& scriptContext)
- : scriptContext_(scriptContext) {}
-
-void ScriptSystem::init(Registry& registry) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!scriptContext_.isInitialized()) {
- ES_LOG_ERROR("ScriptSystem: ScriptContext not initialized");
- return;
- }
-
- // Load all scripts and call onInit
- registry.each<ScriptComponent>([this, &registry](Entity entity, ScriptComponent& script) {
- if (script.enabled && !script.isLoaded) {
- loadScript(entity, script, registry);
-
- if (script.isLoaded && !JS_IsUndefined(script.onInitFunc)) {
- callScriptFunction(script, "onInit");
- }
- }
- });
-
- ES_LOG_INFO("ScriptSystem initialized");
-#else
- (void)registry;
- ES_LOG_WARN("ScriptSystem: Scripting not enabled on this platform");
-#endif
-}
-
-void ScriptSystem::update(Registry& registry, f32 deltaTime) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!scriptContext_.isInitialized()) {
- return;
- }
-
- JSContext* ctx = scriptContext_.getJSContext();
-
- // Update all enabled scripts
- registry.each<ScriptComponent>([this, &registry, deltaTime, ctx](Entity entity, ScriptComponent& script) {
- if (!script.enabled) {
- return;
- }
-
- // Load script if not loaded yet
- if (!script.isLoaded) {
- loadScript(entity, script, registry);
- if (script.isLoaded && !JS_IsUndefined(script.onInitFunc)) {
- callScriptFunction(script, "onInit");
- }
- }
-
- // Call onUpdate if available
- if (script.isLoaded && !JS_IsUndefined(script.onUpdateFunc)) {
- // Create deltaTime argument
- JSValue dtArg = JS_NewFloat64(ctx, static_cast<f64>(deltaTime));
-
- // Call onUpdate(deltaTime)
- JSValue result = JS_Call(ctx, script.onUpdateFunc, script.instance, 1, &dtArg);
- JS_FreeValue(ctx, dtArg);
-
- if (JS_IsException(result)) {
- JSValue exception = JS_GetException(ctx);
- const char* errorStr = JS_ToCString(ctx, exception);
- if (errorStr) {
- script.lastError = errorStr;
- ES_LOG_ERROR("Script error in onUpdate: {}", errorStr);
- JS_FreeCString(ctx, errorStr);
- }
- JS_FreeValue(ctx, exception);
- JS_FreeValue(ctx, result);
- } else {
- JS_FreeValue(ctx, result);
- }
- }
- });
-#else
- (void)registry;
- (void)deltaTime;
-#endif
-}
-
-void ScriptSystem::shutdown(Registry& registry) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!scriptContext_.isInitialized()) {
- return;
- }
-
- // Call onDestroy on all scripts
- registry.each<ScriptComponent>([this](Entity entity, ScriptComponent& script) {
- (void)entity;
- if (script.isLoaded && !JS_IsUndefined(script.onDestroyFunc)) {
- callScriptFunction(script, "onDestroy");
- }
- cleanupScript(script);
- });
-
- ES_LOG_INFO("ScriptSystem shutdown");
-#else
- (void)registry;
-#endif
-}
-
-void ScriptSystem::loadScript(Entity entity, ScriptComponent& script, Registry& registry) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!scriptContext_.isInitialized()) {
- script.lastError = "ScriptContext not initialized";
- return;
- }
-
- JSContext* ctx = scriptContext_.getJSContext();
-
- // Load script source
- std::string source;
- if (!script.scriptPath.empty()) {
- // Load from file
- if (!scriptContext_.evalFile(script.scriptPath)) {
- script.lastError = scriptContext_.getLastError();
- ES_LOG_ERROR("Failed to load script from {}: {}", script.scriptPath, script.lastError);
- return;
- }
- // Script file should define a class, we'll instantiate it below
- } else if (!script.scriptSource.empty()) {
- // Evaluate inline source
- if (!scriptContext_.evalString(script.scriptSource, "<inline>")) {
- script.lastError = scriptContext_.getLastError();
- ES_LOG_ERROR("Failed to evaluate inline script: {}", script.lastError);
- return;
- }
- } else {
- script.lastError = "No script source provided";
- ES_LOG_ERROR("ScriptComponent has no script path or source");
- return;
- }
-
- // Get global object
- JSValue global = JS_GetGlobalObject(ctx);
-
- // Assume script defines a class with the same name as the file (without extension)
- // Or for inline scripts, assume class is named "Script"
- std::string className = "Script";
- if (!script.scriptPath.empty()) {
- // Extract class name from file path (e.g., "player_controller.js" -> "PlayerController")
- usize lastSlash = script.scriptPath.find_last_of("/\\");
- usize lastDot = script.scriptPath.find_last_of('.');
- if (lastSlash != std::string::npos && lastDot != std::string::npos && lastDot > lastSlash) {
- className = script.scriptPath.substr(lastSlash + 1, lastDot - lastSlash - 1);
- // Convert snake_case to PascalCase (simple heuristic)
- if (!className.empty()) {
- className[0] = static_cast<char>(std::toupper(static_cast<u8>(className[0])));
- }
- }
- }
-
- // Get the class constructor
- JSValue classConstructor = JS_GetPropertyStr(ctx, global, className.c_str());
- JS_FreeValue(ctx, global);
-
- if (JS_IsUndefined(classConstructor) || !JS_IsFunction(ctx, classConstructor)) {
- script.lastError = "Class '" + className + "' not found in script";
- ES_LOG_ERROR("{}", script.lastError);
- JS_FreeValue(ctx, classConstructor);
- return;
- }
-
- // Create arguments for constructor: entity and registry
- JSValue entityArg = JS_NewUint32(ctx, static_cast<u32>(entity));
- JSValue registryArg = JS_GetGlobalObject(ctx); // Registry is exposed globally
- JSValue registryObj = JS_GetPropertyStr(ctx, registryArg, "Registry");
- JS_FreeValue(ctx, registryArg);
-
- JSValue args[2] = {entityArg, registryObj};
-
- // Instantiate the class: new ClassName(entity, registry)
- script.instance = JS_CallConstructor(ctx, classConstructor, 2, args);
- JS_FreeValue(ctx, entityArg);
- JS_FreeValue(ctx, registryObj);
- JS_FreeValue(ctx, classConstructor);
-
- if (JS_IsException(script.instance)) {
- JSValue exception = JS_GetException(ctx);
- const char* errorStr = JS_ToCString(ctx, exception);
- if (errorStr) {
- script.lastError = errorStr;
- ES_LOG_ERROR("Failed to instantiate script class: {}", errorStr);
- JS_FreeCString(ctx, errorStr);
- }
- JS_FreeValue(ctx, exception);
- script.instance = JS_UNDEFINED;
- return;
- }
-
- // Cache lifecycle functions
- script.onInitFunc = JS_GetPropertyStr(ctx, script.instance, "onInit");
- script.onUpdateFunc = JS_GetPropertyStr(ctx, script.instance, "onUpdate");
- script.onDestroyFunc = JS_GetPropertyStr(ctx, script.instance, "onDestroy");
-
- script.isLoaded = true;
- ES_LOG_INFO("Successfully loaded script: {}", script.scriptPath.empty() ? "<inline>" : script.scriptPath);
-#else
- (void)entity;
- (void)script;
- (void)registry;
-#endif
-}
-
-bool ScriptSystem::callScriptFunction(ScriptComponent& script,
- const std::string& funcName,
- const std::vector<ScriptValue>& args) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!scriptContext_.isInitialized()) {
- return false;
- }
-
- JSContext* ctx = scriptContext_.getJSContext();
-
- // Get the function
- JSValue func = JS_GetPropertyStr(ctx, script.instance, funcName.c_str());
- if (JS_IsUndefined(func) || !JS_IsFunction(ctx, func)) {
- JS_FreeValue(ctx, func);
- return false; // Function not defined, silently skip
- }
-
- // Prepare arguments
- std::vector<JSValue> jsArgs;
- jsArgs.reserve(args.size());
- for (const auto& arg : args) {
- // Note: ScriptValue doesn't expose JSValue directly yet
- // For now, we create arguments manually in the calling code
- }
-
- // Call the function
- JSValue result = JS_Call(ctx, func, script.instance,
- static_cast<int>(jsArgs.size()),
- jsArgs.empty() ? nullptr : jsArgs.data());
- JS_FreeValue(ctx, func);
-
- if (JS_IsException(result)) {
- JSValue exception = JS_GetException(ctx);
- const char* errorStr = JS_ToCString(ctx, exception);
- if (errorStr) {
- script.lastError = errorStr;
- ES_LOG_ERROR("Script error in {}: {}", funcName, errorStr);
- JS_FreeCString(ctx, errorStr);
- }
- JS_FreeValue(ctx, exception);
- JS_FreeValue(ctx, result);
- return false;
- }
-
- JS_FreeValue(ctx, result);
- return true;
-#else
- (void)script;
- (void)funcName;
- (void)args;
- return false;
-#endif
-}
-
-#ifdef ES_SCRIPTING_ENABLED
-void ScriptSystem::cleanupScript(ScriptComponent& script) {
- if (!scriptContext_.isInitialized()) {
- return;
- }
-
- JSContext* ctx = scriptContext_.getJSContext();
-
- if (!JS_IsUndefined(script.instance)) {
- JS_FreeValue(ctx, script.instance);
- script.instance = JS_UNDEFINED;
- }
-
- if (!JS_IsUndefined(script.onInitFunc)) {
- JS_FreeValue(ctx, script.onInitFunc);
- script.onInitFunc = JS_UNDEFINED;
- }
-
- if (!JS_IsUndefined(script.onUpdateFunc)) {
- JS_FreeValue(ctx, script.onUpdateFunc);
- script.onUpdateFunc = JS_UNDEFINED;
- }
-
- if (!JS_IsUndefined(script.onDestroyFunc)) {
- JS_FreeValue(ctx, script.onDestroyFunc);
- script.onDestroyFunc = JS_UNDEFINED;
- }
-
- script.isLoaded = false;
-}
-#endif
-
-} // namespace esengine::ecs
diff --git a/src/esengine/ecs/systems/ScriptSystem.hpp b/src/esengine/ecs/systems/ScriptSystem.hpp
deleted file mode 100644
index dabee8421..000000000
--- a/src/esengine/ecs/systems/ScriptSystem.hpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * @file ScriptSystem.hpp
- * @brief System for executing JavaScript scripts attached to entities
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-#include "../System.hpp"
-#include "../components/Script.hpp"
-#include "../../scripting/ScriptContext.hpp"
-#include "../../scripting/ScriptValue.hpp"
-
-namespace esengine::ecs {
-
-/**
- * @brief System that manages and executes JavaScript scripts on entities
- *
- * @details This system:
- * - Loads scripts from files or inline source
- * - Instantiates JavaScript class instances for each entity
- * - Calls lifecycle methods (onInit, onUpdate, onDestroy)
- * - Handles errors without crashing the engine
- * - Supports persistent variables across frames
- */
-class ScriptSystem : public System {
-public:
- /**
- * @brief Construct a new Script System
- * @param scriptContext Reference to the global script context
- */
- explicit ScriptSystem(ScriptContext& scriptContext);
-
- /**
- * @brief Initialize the script system
- * @param registry The ECS registry
- *
- * @details Loads all scripts and calls their onInit methods
- */
- void init(Registry& registry) override;
-
- /**
- * @brief Update all script components
- * @param registry The ECS registry
- * @param deltaTime Time since last frame in seconds
- *
- * @details Calls onUpdate(deltaTime) on all enabled scripts
- */
- void update(Registry& registry, f32 deltaTime) override;
-
- /**
- * @brief Shutdown the script system
- * @param registry The ECS registry
- *
- * @details Calls onDestroy on all scripts and cleans up resources
- */
- void shutdown(Registry& registry) override;
-
-private:
- /**
- * @brief Load a script from file or source
- * @param entity The target entity
- * @param script The script component to load
- * @param registry The ECS registry for passing to script constructor
- */
- void loadScript(Entity entity, ScriptComponent& script, Registry& registry);
-
- /**
- * @brief Call a JavaScript function on a script instance
- * @param script The script component
- * @param funcName Name of the function to call
- * @param args Arguments to pass to the function
- * @return true if call succeeded, false if error occurred
- */
- bool callScriptFunction(ScriptComponent& script,
- const std::string& funcName,
- const std::vector<ScriptValue>& args = {});
-
-#ifdef ES_SCRIPTING_ENABLED
- /**
- * @brief Clean up JavaScript resources for a script
- * @param script The script component to clean up
- */
- void cleanupScript(ScriptComponent& script);
-#endif
-
- ScriptContext& scriptContext_; ///< Reference to global script context
-};
-
-} // namespace esengine::ecs
diff --git a/src/esengine/editor/AssetDatabase.cpp b/src/esengine/editor/AssetDatabase.cpp
deleted file mode 100644
index a1052b1f8..000000000
--- a/src/esengine/editor/AssetDatabase.cpp
+++ /dev/null
@@ -1,407 +0,0 @@
-/**
- * @file AssetDatabase.cpp
- * @brief Asset database implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "AssetDatabase.hpp"
-#include "../platform/FileSystem.hpp"
-#include "../core/Log.hpp"
-
-#include <algorithm>
-#include <random>
-#include <sstream>
-#include <iomanip>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Helper Functions
-// =============================================================================
-
-namespace {
-
-std::string getFileName(const std::string& path) {
- usize pos = path.find_last_of("/\\");
- if (pos != std::string::npos) {
- return path.substr(pos + 1);
- }
- return path;
-}
-
-std::string getFileExtension(const std::string& path) {
- usize pos = path.find_last_of('.');
- if (pos != std::string::npos) {
- return path.substr(pos);
- }
- return "";
-}
-
-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;
-}
-
-} // namespace
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-AssetDatabase::AssetDatabase() = default;
-AssetDatabase::~AssetDatabase() = default;
-
-// =============================================================================
-// Public Methods
-// =============================================================================
-
-void AssetDatabase::setProjectPath(const std::string& path) {
- if (projectPath_ != path) {
- projectPath_ = path;
- loadDatabase();
- }
-}
-
-void AssetDatabase::scan() {
- if (projectPath_.empty()) {
- ES_LOG_WARN("AssetDatabase: Project path not set");
- return;
- }
-
- if (!FileSystem::directoryExists(projectPath_)) {
- ES_LOG_WARN("AssetDatabase: Project path does not exist: {}", projectPath_);
- return;
- }
-
- ES_LOG_INFO("AssetDatabase: Scanning {}", projectPath_);
- scanDirectory(projectPath_, true);
- saveDatabase();
- ES_LOG_INFO("AssetDatabase: Found {} assets", assetsByGUID_.size());
-}
-
-void AssetDatabase::refresh() {
- scan();
-}
-
-// =============================================================================
-// Directory Scanning
-// =============================================================================
-
-void AssetDatabase::scanDirectory(const std::string& directory, bool recursive) {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::vector<std::string> entries = FileSystem::listDirectory(directory, false);
-
- for (const auto& entryPath : entries) {
- bool isDir = FileSystem::directoryExists(entryPath);
- std::string name = getFileName(entryPath);
-
- // Skip excluded directories
- if (isDir && isExcludedDirectory(name)) {
- continue;
- }
-
- auto existingIt = pathToGUID_.find(entryPath);
- if (existingIt != pathToGUID_.end()) {
- auto& existing = assetsByGUID_[existingIt->second];
- u64 currentModTime = FileSystem::getFileModificationTime(entryPath);
- if (existing.lastModified != currentModTime) {
- existing.lastModified = currentModTime;
- existing.fileSize = isDir ? 0 : FileSystem::getFileSize(entryPath);
- if (onAssetModified_) {
- onAssetModified_(existing);
- }
- }
- } else {
- AssetMetadata metadata;
- metadata.guid = generateGUID();
- metadata.path = entryPath;
- metadata.name = name;
- metadata.extension = getFileExtension(entryPath);
- metadata.isDirectory = isDir;
- metadata.type = isDir ? AssetType::Folder : detectAssetType(entryPath);
- metadata.fileSize = isDir ? 0 : FileSystem::getFileSize(entryPath);
- metadata.lastModified = FileSystem::getFileModificationTime(entryPath);
-
- assetsByGUID_[metadata.guid] = metadata;
- pathToGUID_[metadata.path] = metadata.guid;
-
- if (onAssetAdded_) {
- onAssetAdded_(metadata);
- }
- }
-
- if (isDir && recursive) {
- scanDirectory(entryPath, true);
- }
- }
-}
-
-bool AssetDatabase::isExcludedDirectory(const std::string& name) const {
- for (const auto& excluded : excludedDirs_) {
- if (name == excluded) {
- return true;
- }
- }
- return false;
-}
-
-// =============================================================================
-// Query Methods
-// =============================================================================
-
-const AssetMetadata* AssetDatabase::findByPath(const std::string& path) const {
- auto it = pathToGUID_.find(path);
- if (it != pathToGUID_.end()) {
- auto assetIt = assetsByGUID_.find(it->second);
- if (assetIt != assetsByGUID_.end()) {
- return &assetIt->second;
- }
- }
- return nullptr;
-}
-
-const AssetMetadata* AssetDatabase::findByGUID(const std::string& guid) const {
- auto it = assetsByGUID_.find(guid);
- if (it != assetsByGUID_.end()) {
- return &it->second;
- }
- return nullptr;
-}
-
-std::vector<const AssetMetadata*> AssetDatabase::getAssetsInDirectory(const std::string& directory) const {
- std::vector<const AssetMetadata*> result;
-
- std::string dirPath = directory;
- if (!dirPath.empty() && dirPath.back() != '/' && dirPath.back() != '\\') {
- dirPath += '/';
- }
-
- for (const auto& [guid, metadata] : assetsByGUID_) {
- if (metadata.path.size() > dirPath.size() &&
- metadata.path.compare(0, dirPath.size(), dirPath) == 0) {
- usize remaining = metadata.path.size() - dirPath.size();
- usize slashPos = metadata.path.find_first_of("/\\", dirPath.size());
- if (slashPos == std::string::npos || slashPos == metadata.path.size() - 1) {
- result.push_back(&metadata);
- }
- }
- }
-
- std::sort(result.begin(), result.end(),
- [](const AssetMetadata* a, const AssetMetadata* b) {
- if (a->isDirectory != b->isDirectory) {
- return a->isDirectory;
- }
- return a->name < b->name;
- });
-
- return result;
-}
-
-std::vector<std::string> AssetDatabase::getSubdirectories(const std::string& directory) const {
- std::vector<std::string> result;
-
- auto assets = getAssetsInDirectory(directory);
- for (const auto* asset : assets) {
- if (asset->isDirectory) {
- result.push_back(asset->path);
- }
- }
-
- return result;
-}
-
-std::string AssetDatabase::generateGUID() const {
- static std::random_device rd;
- static std::mt19937_64 gen(rd());
- static std::uniform_int_distribution<u64> dis;
-
- std::stringstream ss;
- ss << std::hex << std::setfill('0');
-
- u64 part1 = dis(gen);
- u64 part2 = dis(gen);
-
- ss << std::setw(8) << ((part1 >> 32) & 0xFFFFFFFF) << "-";
- ss << std::setw(4) << ((part1 >> 16) & 0xFFFF) << "-";
- ss << std::setw(4) << (part1 & 0xFFFF) << "-";
- ss << std::setw(4) << ((part2 >> 48) & 0xFFFF) << "-";
- ss << std::setw(12) << (part2 & 0xFFFFFFFFFFFF);
-
- return ss.str();
-}
-
-std::string AssetDatabase::getDatabasePath() const {
- return projectPath_ + "/.esengine/assets.db";
-}
-
-AssetType AssetDatabase::detectAssetType(const std::string& path) const {
- std::string ext = getFileExtension(path);
- std::transform(ext.begin(), ext.end(), ext.begin(),
- [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
- return getAssetTypeFromExtension(ext);
-}
-
-// =============================================================================
-// Database Persistence
-// =============================================================================
-
-void AssetDatabase::saveDatabase() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string dbDir = projectPath_ + "/.esengine";
- if (!FileSystem::directoryExists(dbDir)) {
- FileSystem::createDirectory(dbDir);
- }
-
- std::stringstream ss;
- ss << "{\n \"version\": \"1.0\",\n \"assets\": [\n";
-
- bool first = true;
- for (const auto& [guid, metadata] : assetsByGUID_) {
- if (!first) ss << ",\n";
- first = false;
-
- ss << " {\n";
- ss << " \"guid\": \"" << escapeJsonString(metadata.guid) << "\",\n";
- ss << " \"path\": \"" << escapeJsonString(metadata.path) << "\",\n";
- ss << " \"name\": \"" << escapeJsonString(metadata.name) << "\",\n";
- ss << " \"type\": " << static_cast<int>(metadata.type) << ",\n";
- ss << " \"fileSize\": " << metadata.fileSize << ",\n";
- ss << " \"lastModified\": " << metadata.lastModified << ",\n";
- ss << " \"isDirectory\": " << (metadata.isDirectory ? "true" : "false") << "\n";
- ss << " }";
- }
-
- ss << "\n ]\n}\n";
-
- FileSystem::writeTextFile(getDatabasePath(), ss.str());
- ES_LOG_DEBUG("AssetDatabase: Saved to {}", getDatabasePath());
-}
-
-void AssetDatabase::loadDatabase() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string dbPath = getDatabasePath();
- if (!FileSystem::fileExists(dbPath)) {
- return;
- }
-
- std::string content = FileSystem::readTextFile(dbPath);
- if (content.empty()) {
- return;
- }
-
- assetsByGUID_.clear();
- pathToGUID_.clear();
-
- usize pos = 0;
- while ((pos = content.find("\"guid\":", pos)) != std::string::npos) {
- AssetMetadata metadata;
-
- auto extractString = [&](const std::string& key) -> std::string {
- usize keyPos = content.find("\"" + key + "\":", pos);
- if (keyPos == std::string::npos) return "";
- usize valueStart = content.find("\"", keyPos + key.size() + 3);
- if (valueStart == std::string::npos) return "";
- usize valueEnd = content.find("\"", valueStart + 1);
- if (valueEnd == std::string::npos) return "";
- return unescapeJsonString(content.substr(valueStart + 1, valueEnd - valueStart - 1));
- };
-
- auto extractInt = [&](const std::string& key) -> u64 {
- usize keyPos = content.find("\"" + key + "\":", pos);
- if (keyPos == std::string::npos) return 0;
- usize valueStart = keyPos + key.size() + 3;
- while (valueStart < content.size() && !std::isdigit(content[valueStart])) {
- ++valueStart;
- }
- return std::stoull(content.substr(valueStart));
- };
-
- auto extractBool = [&](const std::string& key) -> bool {
- usize keyPos = content.find("\"" + key + "\":", pos);
- if (keyPos == std::string::npos) return false;
- return content.find("true", keyPos) < content.find("false", keyPos);
- };
-
- metadata.guid = extractString("guid");
- metadata.path = extractString("path");
- metadata.name = extractString("name");
- metadata.type = static_cast<AssetType>(extractInt("type"));
- metadata.fileSize = extractInt("fileSize");
- metadata.lastModified = extractInt("lastModified");
- metadata.isDirectory = extractBool("isDirectory");
- metadata.extension = getFileExtension(metadata.path);
-
- if (!metadata.guid.empty() && !metadata.path.empty()) {
- assetsByGUID_[metadata.guid] = metadata;
- pathToGUID_[metadata.path] = metadata.guid;
- }
-
- pos = content.find("}", pos) + 1;
- }
-
- ES_LOG_DEBUG("AssetDatabase: Loaded {} assets from {}", assetsByGUID_.size(), dbPath);
-}
-
-// =============================================================================
-// Callbacks
-// =============================================================================
-
-void AssetDatabase::setOnAssetAdded(std::function<void(const AssetMetadata&)> callback) {
- onAssetAdded_ = std::move(callback);
-}
-
-void AssetDatabase::setOnAssetRemoved(std::function<void(const std::string&)> callback) {
- onAssetRemoved_ = std::move(callback);
-}
-
-void AssetDatabase::setOnAssetModified(std::function<void(const AssetMetadata&)> callback) {
- onAssetModified_ = std::move(callback);
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/AssetDatabase.hpp b/src/esengine/editor/AssetDatabase.hpp
deleted file mode 100644
index 508361a41..000000000
--- a/src/esengine/editor/AssetDatabase.hpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * @file AssetDatabase.hpp
- * @brief Centralized asset management and tracking
- * @details Maintains a database of all project assets with GUID-based
- * identification and metadata caching.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../core/Types.hpp"
-#include "panels/AssetBrowserTypes.hpp"
-
-#include <string>
-#include <vector>
-#include <unordered_map>
-#include <functional>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Data Structures
-// =============================================================================
-
-struct AssetMetadata {
- std::string guid;
- std::string path;
- std::string name;
- std::string extension;
- AssetType type = AssetType::Unknown;
- usize fileSize = 0;
- u64 lastModified = 0;
- bool isDirectory = false;
-};
-
-// =============================================================================
-// AssetDatabase Class
-// =============================================================================
-
-class AssetDatabase {
-public:
- AssetDatabase();
- ~AssetDatabase();
-
- void setProjectPath(const std::string& path);
- const std::string& getProjectPath() const { return projectPath_; }
-
- void scan();
- void refresh();
-
- const AssetMetadata* findByPath(const std::string& path) const;
- const AssetMetadata* findByGUID(const std::string& guid) const;
-
- std::vector<const AssetMetadata*> getAssetsInDirectory(const std::string& directory) const;
- std::vector<std::string> getSubdirectories(const std::string& directory) const;
-
- const std::unordered_map<std::string, AssetMetadata>& getAllAssets() const { return assetsByGUID_; }
-
- void saveDatabase();
- void loadDatabase();
-
- void setOnAssetAdded(std::function<void(const AssetMetadata&)> callback);
- void setOnAssetRemoved(std::function<void(const std::string&)> callback);
- void setOnAssetModified(std::function<void(const AssetMetadata&)> callback);
-
-private:
- void scanDirectory(const std::string& directory, bool recursive);
- bool isExcludedDirectory(const std::string& name) const;
- std::string generateGUID() const;
- std::string getDatabasePath() const;
- AssetType detectAssetType(const std::string& path) const;
-
- std::string projectPath_;
- std::unordered_map<std::string, AssetMetadata> assetsByGUID_;
- std::unordered_map<std::string, std::string> pathToGUID_;
- std::vector<std::string> excludedDirs_ = {"node_modules", "build", ".esengine", ".git", ".vscode", ".idea"};
-
- std::function<void(const AssetMetadata&)> onAssetAdded_;
- std::function<void(const std::string&)> onAssetRemoved_;
- std::function<void(const AssetMetadata&)> onAssetModified_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/CMakeLists.txt b/src/esengine/editor/CMakeLists.txt
deleted file mode 100644
index 52077d2ee..000000000
--- a/src/esengine/editor/CMakeLists.txt
+++ /dev/null
@@ -1,185 +0,0 @@
-# ESEngine Editor Build Configuration
-
-set(EDITOR_SOURCES
- main.cpp
- EditorApplication.cpp
- AssetDatabase.cpp
- ThumbnailGenerator.cpp
- DragDropManager.cpp
-
- # Docking System (Editor-specific UI)
- ui/docking/DockNode.cpp
- ui/docking/DockPanel.cpp
- ui/docking/DockTabBar.cpp
- ui/docking/DockZone.cpp
- ui/docking/DockArea.cpp
- ui/docking/DockLayoutSerializer.cpp
-
- # Project management
- project/ProjectSerializer.cpp
- project/RecentProjectsManager.cpp
- project/ProjectManager.cpp
-
- # Property editors
- property/PropertyEditor.cpp
- property/editors/FloatEditor.cpp
- property/editors/Vector3Editor.cpp
- property/editors/Vector2Editor.cpp
- property/editors/BoolEditor.cpp
- property/editors/IntEditor.cpp
- property/editors/StringEditor.cpp
- property/editors/ColorEditor.cpp
- property/editors/EnumEditor.cpp
-
- # Camera
- camera/EditorCamera.cpp
-
- # Gizmo
- gizmo/TransformGizmo.cpp
-
- # Panels
- panels/HierarchyPanel.cpp
- panels/InspectorPanel.cpp
- panels/SceneViewPanel.cpp
- panels/AssetBrowserPanel.cpp
- panels/AssetGridItem.cpp
- panels/ProjectLauncherPanel.cpp
- panels/NewProjectDialog.cpp
- panels/OutputLogPanel.cpp
- panels/GameViewPanel.cpp
-
- # Editor widgets
- widgets/StatusBar.cpp
- widgets/DrawerPanel.cpp
- widgets/EditorRootContainer.cpp
- widgets/EditorToolbar.cpp
- widgets/SceneToolbar.cpp
-
- # Preview
- preview/WebPreviewServer.cpp
- preview/WebExporter.cpp
-
- # Scene
- scene/SceneSerializer.cpp
-
- # Script
- script/ScriptComponentRegistry.cpp
-)
-
-set(EDITOR_HEADERS
- EditorApplication.hpp
- AssetDatabase.hpp
- ThumbnailGenerator.hpp
- DragDropTypes.hpp
- DragDropManager.hpp
-
- # Docking System (Editor-specific UI)
- ui/docking/DockTypes.hpp
- ui/docking/DockEvents.hpp
- ui/docking/DockNode.hpp
- ui/docking/DockPanel.hpp
- ui/docking/DockTabBar.hpp
- ui/docking/DockZone.hpp
- ui/docking/DockArea.hpp
- ui/docking/DockLayoutSerializer.hpp
-
- # Core subsystem
- core/EditorEvents.hpp
- core/Selection.hpp
-
- # Project management
- project/ProjectTypes.hpp
- project/ProjectSerializer.hpp
- project/RecentProjectsManager.hpp
- project/ProjectManager.hpp
-
- # Command subsystem
- command/Command.hpp
- command/CommandHistory.hpp
- command/MacroCommand.hpp
- command/PropertyCommand.hpp
- command/EditorCommands.hpp
-
- # Property editors
- property/PropertyEditor.hpp
- property/editors/FloatEditor.hpp
- property/editors/Vector3Editor.hpp
- property/editors/Vector2Editor.hpp
- property/editors/BoolEditor.hpp
- property/editors/IntEditor.hpp
- property/editors/StringEditor.hpp
- property/editors/ColorEditor.hpp
- property/editors/EnumEditor.hpp
-
- # Camera
- camera/EditorCamera.hpp
-
- # Gizmo
- gizmo/TransformGizmo.hpp
-
- # Panels
- panels/HierarchyPanel.hpp
- panels/InspectorPanel.hpp
- panels/SceneViewPanel.hpp
- panels/AssetBrowserPanel.hpp
- panels/AssetBrowserTypes.hpp
- panels/AssetGridItem.hpp
- panels/ProjectLauncherPanel.hpp
- panels/NewProjectDialog.hpp
- panels/OutputLogPanel.hpp
- panels/GameViewPanel.hpp
-
- # Editor widgets
- widgets/StatusBar.hpp
- widgets/DrawerPanel.hpp
- widgets/EditorRootContainer.hpp
- widgets/EditorToolbar.hpp
- widgets/SceneToolbar.hpp
-
- # Preview
- preview/WebPreviewServer.hpp
- preview/WebExporter.hpp
-
- # Scene
- scene/SceneSerializer.hpp
-
- # Script
- script/ScriptComponentRegistry.hpp
-)
-
-# Create editor executable
-add_executable(esengine_editor ${EDITOR_SOURCES} ${EDITOR_HEADERS})
-
-# Link against the engine library
-target_link_libraries(esengine_editor PRIVATE esengine)
-
-# Define ES_EDITOR macro for editor-specific code
-target_compile_definitions(esengine_editor PRIVATE ES_EDITOR)
-
-# Include directories
-target_include_directories(esengine_editor PRIVATE
- ${CMAKE_SOURCE_DIR}/src
-)
-
-# Set output directory
-set_target_properties(esengine_editor PROPERTIES
- RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
-)
-
-# Windows-specific settings
-if(WIN32)
- # Use main instead of WinMain for console output during development
- 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)
-# add_custom_command(TARGET esengine_editor POST_BUILD
-# COMMAND ${CMAKE_COMMAND} -E copy_directory
-# ${CMAKE_SOURCE_DIR}/assets
-# $<TARGET_FILE_DIR:esengine_editor>/assets
-# )
-
-message(STATUS "Editor target configured: esengine_editor")
diff --git a/src/esengine/editor/DragDropManager.cpp b/src/esengine/editor/DragDropManager.cpp
deleted file mode 100644
index ebbe69f72..000000000
--- a/src/esengine/editor/DragDropManager.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * @file DragDropManager.cpp
- * @brief Drag-and-drop manager implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DragDropManager.hpp"
-
-#include <cmath>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Drag Operations
-// =============================================================================
-
-void DragDropManager::beginDrag(const DragDropPayload& payload, const glm::vec2& startPos) {
- if (isDragging_) {
- return;
- }
-
- pendingPayload_ = payload;
- startPos_ = startPos;
- currentPos_ = startPos;
-}
-
-void DragDropManager::updateDrag(const glm::vec2& currentPos) {
- currentPos_ = currentPos;
-
- if (pendingPayload_.has_value() && !isDragging_) {
- f32 distance = glm::length(currentPos_ - startPos_);
- if (distance >= DRAG_THRESHOLD) {
- isDragging_ = true;
- activePayload_ = *pendingPayload_;
- pendingPayload_.reset();
- onDragStart.publish(activePayload_);
- }
- }
-
- if (isDragging_) {
- onDragMove.publish(activePayload_, currentPos_);
- }
-}
-
-void DragDropManager::endDrag(const glm::vec2& pos) {
- currentPos_ = pos;
-
- if (isDragging_) {
- onDragEnd.publish(activePayload_, pos);
- isDragging_ = false;
- activePayload_ = {};
- }
-
- pendingPayload_.reset();
-}
-
-void DragDropManager::cancelDrag() {
- if (isDragging_) {
- onDragCancel.publish();
- }
-
- isDragging_ = false;
- activePayload_ = {};
- pendingPayload_.reset();
-}
-
-// =============================================================================
-// Accessors
-// =============================================================================
-
-const DragDropPayload* DragDropManager::getPayload() const {
- if (isDragging_) {
- return &activePayload_;
- }
- return nullptr;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/DragDropManager.hpp b/src/esengine/editor/DragDropManager.hpp
deleted file mode 100644
index 934a79401..000000000
--- a/src/esengine/editor/DragDropManager.hpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * @file DragDropManager.hpp
- * @brief Manager for editor drag-and-drop operations
- * @details Handles drag state tracking, threshold detection, and
- * signal dispatch for drag-and-drop interactions.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DragDropTypes.hpp"
-#include "../events/Signal.hpp"
-
-#include <glm/glm.hpp>
-
-#include <optional>
-
-namespace esengine::editor {
-
-// =============================================================================
-// DragDropManager Class
-// =============================================================================
-
-class DragDropManager {
-public:
- static constexpr f32 DRAG_THRESHOLD = 5.0f;
-
- DragDropManager() = default;
- ~DragDropManager() = default;
-
- void beginDrag(const DragDropPayload& payload, const glm::vec2& startPos);
- void updateDrag(const glm::vec2& currentPos);
- void endDrag(const glm::vec2& pos);
- void cancelDrag();
-
- bool isDragging() const { return isDragging_; }
- bool hasPendingDrag() const { return pendingPayload_.has_value(); }
-
- const DragDropPayload* getPayload() const;
- glm::vec2 getDragPosition() const { return currentPos_; }
- glm::vec2 getDragStartPosition() const { return startPos_; }
- glm::vec2 getDragDelta() const { return currentPos_ - startPos_; }
-
- Signal<void(const DragDropPayload&)> onDragStart;
- Signal<void(const DragDropPayload&, const glm::vec2&)> onDragMove;
- Signal<void(const DragDropPayload&, const glm::vec2&)> onDragEnd;
- Signal<void()> onDragCancel;
-
-private:
- bool isDragging_ = false;
- std::optional<DragDropPayload> pendingPayload_;
- DragDropPayload activePayload_;
- glm::vec2 startPos_{0.0f};
- glm::vec2 currentPos_{0.0f};
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/DragDropTypes.hpp b/src/esengine/editor/DragDropTypes.hpp
deleted file mode 100644
index ad8bd2f51..000000000
--- a/src/esengine/editor/DragDropTypes.hpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * @file DragDropTypes.hpp
- * @brief Type definitions for drag-and-drop operations
- *
- * @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/Entity.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-#include <variant>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Enumerations
-// =============================================================================
-
-enum class DragDropType : u8 {
- None,
- Asset,
- Entity,
- Component
-};
-
-// =============================================================================
-// Data Structures
-// =============================================================================
-
-struct AssetDragData {
- std::string guid;
- std::string path;
- std::string name;
-};
-
-struct EntityDragData {
- Entity entity = INVALID_ENTITY;
-};
-
-struct ComponentDragData {
- Entity entity = INVALID_ENTITY;
- std::string componentType;
-};
-
-using DragDropData = std::variant<std::monostate, AssetDragData, EntityDragData, ComponentDragData>;
-
-struct DragDropPayload {
- DragDropType type = DragDropType::None;
- DragDropData data;
-
- bool isValid() const { return type != DragDropType::None; }
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/EditorApplication.cpp b/src/esengine/editor/EditorApplication.cpp
deleted file mode 100644
index b395b135b..000000000
--- a/src/esengine/editor/EditorApplication.cpp
+++ /dev/null
@@ -1,950 +0,0 @@
-/**
- * @file EditorApplication.cpp
- * @brief ESEngine Editor main application implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "EditorApplication.hpp"
-#include "../core/Log.hpp"
-#include "../renderer/RenderCommand.hpp"
-#include "../math/Math.hpp"
-#include "../platform/input/Input.hpp"
-#include "../platform/PathResolver.hpp"
-#include "../ui/widgets/Panel.hpp"
-#include "../ui/widgets/Label.hpp"
-#include "../ui/widgets/Button.hpp"
-#include "../ui/layout/StackLayout.hpp"
-#include "ui/docking/DockArea.hpp"
-#include "../ecs/components/Common.hpp"
-#include "../ecs/components/Transform.hpp"
-#include "../ecs/components/Hierarchy.hpp"
-#include "../ecs/components/Camera.hpp"
-#include "../ecs/components/Sprite.hpp"
-#include "../ecs/components/Canvas.hpp"
-#include "core/EditorEvents.hpp"
-#include "panels/HierarchyPanel.hpp"
-#include "panels/InspectorPanel.hpp"
-#include "panels/SceneViewPanel.hpp"
-#include "panels/GameViewPanel.hpp"
-#include "panels/AssetBrowserPanel.hpp"
-#include "panels/ProjectLauncherPanel.hpp"
-#include "panels/NewProjectDialog.hpp"
-#include "panels/OutputLogPanel.hpp"
-#include "widgets/EditorRootContainer.hpp"
-#include "widgets/EditorToolbar.hpp"
-#include "../platform/FileDialog.hpp"
-#include "preview/WebExporter.hpp"
-#include "scene/SceneSerializer.hpp"
-
-#include <filesystem>
-
-namespace esengine {
-namespace editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-EditorApplication::EditorApplication()
- : Application({
- .title = "ESEngine Editor",
- .width = 1280,
- .height = 720
- }) {
- commandHistory_.setDispatcher(&dispatcher_);
- selection_.setDispatcher(&dispatcher_);
- projectManager_ = makeUnique<ProjectManager>(dispatcher_, assetDatabase_);
-}
-
-// =============================================================================
-// Lifecycle
-// =============================================================================
-
-void EditorApplication::onInit() {
- ES_LOG_INFO("ESEngine Editor started");
- ES_LOG_INFO("Press ESC to exit, Ctrl+Z to undo, Ctrl+Y to redo");
-
- RenderCommand::setClearColor(clearColor_);
-
- uiContext_ = makeUnique<ui::UIContext>(getRenderContext(), dispatcher_);
- uiContext_->init();
- uiContext_->setViewport(getWidth(), getHeight());
- uiContext_->setDevicePixelRatio(getPlatform().getDevicePixelRatio());
-
- bool fontLoaded = false;
-
-#if ES_FEATURE_SDF_FONT
- // Try system fonts for MSDF rendering
- const char* msdfFontPaths[] = {
- "C:/Windows/Fonts/msyh.ttc", // Microsoft YaHei (Chinese)
- "C:/Windows/Fonts/segoeui.ttf", // Segoe UI
- "C:/Windows/Fonts/arial.ttf", // Arial
- nullptr
- };
-
- for (const char** fontPath = msdfFontPaths; *fontPath != nullptr; ++fontPath) {
- if (uiContext_->loadMSDFFont("default", *fontPath, 32.0f)) {
- ES_LOG_INFO("Loaded MSDF font: {}", *fontPath);
- fontLoaded = true;
- break;
- }
- }
-
- std::string iconFontPath = PathResolver::editorPath("assets/fonts/lucide.ttf");
- if (!uiContext_->loadMSDFFont("icons", iconFontPath, 32.0f)) {
- ES_LOG_WARN("Icon MSDF font not loaded from '{}', icons will not render", iconFontPath);
- }
-#else
- const char* fontFamilies[] = {
-#ifdef ES_PLATFORM_WINDOWS
- "Microsoft YaHei",
- "SimHei",
- "Segoe UI",
- "Arial",
-#elif defined(ES_PLATFORM_MACOS)
- "PingFang SC",
- "Hiragino Sans GB",
- "SF Pro",
-#else
- "Noto Sans CJK SC",
- "DejaVu Sans",
- "sans-serif",
-#endif
- nullptr
- };
-
- for (const char** family = fontFamilies; *family != nullptr; ++family) {
- if (uiContext_->createSystemFont("default", *family, 14.0f)) {
- ES_LOG_INFO("Created system font: {}", *family);
- fontLoaded = true;
- break;
- }
- }
-
- std::string iconFontPath = PathResolver::editorPath("assets/fonts/lucide.ttf");
- if (!uiContext_->createSystemFontFromFile("icons", iconFontPath, 16.0f)) {
- ES_LOG_WARN("Icon font not loaded from '{}', icons will not render", iconFontPath);
- }
-#endif
-
- if (!fontLoaded) {
- ES_LOG_WARN("No font loaded, text will not render");
- }
-
- // Wire up scroll events to UI system
- getPlatform().setScrollCallback([this](f32 deltaX, f32 deltaY, f32 x, f32 y) {
- if (uiContext_) {
- uiContext_->processMouseScroll(deltaX, deltaY, x, y);
- }
- });
-
- // Wire up mouse move events to UI system for hover detection
- getPlatform().setMouseMoveCallback([this](f32 x, f32 y) {
- if (uiContext_) {
- uiContext_->processMouseMove(x, y);
- }
- });
-
- // Wire up mouse button events (for right-click context menus, etc.)
- getPlatform().setMouseButtonCallback([this](MouseButton button, bool pressed, f32 x, f32 y) {
- if (!uiContext_) return;
-
- auto uiButton = static_cast<ui::MouseButton>(static_cast<u8>(button));
- if (pressed) {
- uiContext_->processMouseDown(uiButton, x, y);
- } else {
- uiContext_->processMouseUp(uiButton, x, y);
- }
- });
-
- // Wire up text input events to UI system
- getPlatform().setTextInputCallback([this](const std::string& text) {
- if (uiContext_) {
- uiContext_->processTextInput(text);
- }
- });
-
- // Initialize asset database with thumbnail generation callback
- assetDatabase_.setOnAssetAdded([this](const AssetMetadata& asset) {
- thumbnailGenerator_.generateThumbnail(asset.guid, asset.path, asset.type);
- });
- assetDatabase_.setProjectPath(PathResolver::projectPath("assets"));
- assetDatabase_.scan();
-
- // Load recent projects list
- projectManager_->getRecentProjects().load();
-
- setupEventListeners();
-
- // Start in launcher mode
- setupLauncherLayout();
-}
-
-void EditorApplication::onUpdate(f32 deltaTime) {
- if (pendingShowEditor_) {
- pendingShowEditor_ = false;
- showEditor();
- }
-
- frameTime_ += deltaTime;
- frameCount_++;
-
- if (frameTime_ >= FPS_UPDATE_INTERVAL) {
- fps_ = static_cast<f32>(frameCount_) / static_cast<f32>(frameTime_);
- frameTime_ = 0.0;
- frameCount_ = 0;
- }
-
- dispatcher_.update();
-
- if (uiContext_) {
- uiContext_->update(deltaTime);
- }
-}
-
-void EditorApplication::onRender() {
- RenderCommand::clear();
-
- if (uiContext_) {
- uiContext_->render();
- }
-}
-
-void EditorApplication::onShutdown() {
- ES_LOG_INFO("ESEngine Editor shutting down");
-
- eventConnections_.disconnectAll();
-
- if (uiContext_) {
- uiContext_->shutdown();
- uiContext_.reset();
- }
-
- commandHistory_.clear();
- selection_.clear();
- dispatcher_.clear();
-}
-
-void EditorApplication::onKey(KeyCode key, bool pressed) {
- if (key == KeyCode::LeftControl || key == KeyCode::RightControl) {
- ctrlPressed_ = pressed;
- }
-
- if (key == KeyCode::LeftShift || key == KeyCode::RightShift) {
- shiftPressed_ = pressed;
- }
-
- if (key == KeyCode::LeftAlt || key == KeyCode::RightAlt) {
- altPressed_ = pressed;
- }
-
- if (uiContext_) {
- if (pressed) {
- uiContext_->processKeyDown(key, ctrlPressed_, shiftPressed_, altPressed_);
- } else {
- uiContext_->processKeyUp(key, ctrlPressed_, shiftPressed_, altPressed_);
- }
- }
-
- if (!pressed) {
- return;
- }
-
- if (key == KeyCode::Escape) {
- ES_LOG_INFO("ESC pressed - quitting editor");
- quit();
- return;
- }
-
- if (ctrlPressed_) {
- switch (key) {
- case KeyCode::Z:
- if (shiftPressed_) {
- handleRedo();
- } else {
- handleUndo();
- }
- break;
-
- case KeyCode::Y:
- 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;
- }
- }
-}
-
-void EditorApplication::onResize(u32 width, u32 height) {
- ES_LOG_DEBUG("Editor window resized to {}x{}", width, height);
-
- if (uiContext_) {
- uiContext_->setViewport(width, height);
- uiContext_->setDevicePixelRatio(getPlatform().getDevicePixelRatio());
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void EditorApplication::handleUndo() {
- if (commandHistory_.canUndo()) {
- ES_LOG_DEBUG("Undo: {}", commandHistory_.getUndoDescription());
- commandHistory_.undo();
- } else {
- ES_LOG_DEBUG("Nothing to undo");
- }
-}
-
-void EditorApplication::handleRedo() {
- if (commandHistory_.canRedo()) {
- ES_LOG_DEBUG("Redo: {}", commandHistory_.getRedoDescription());
- commandHistory_.redo();
- } else {
- ES_LOG_DEBUG("Nothing to redo");
- }
-}
-
-void EditorApplication::onTouch(TouchType type, const TouchPoint& point) {
- glm::vec2 pos(point.x, point.y);
-
- switch (type) {
- case TouchType::Begin:
- break;
-
- case TouchType::Move:
- dragDropManager_.updateDrag(pos);
- break;
-
- case TouchType::End:
- case TouchType::Cancel:
- if (dragDropManager_.isDragging()) {
- dragDropManager_.endDrag(pos);
- }
- break;
- }
-}
-
-void EditorApplication::setupEventListeners() {
- eventConnections_.add(
- dispatcher_.sink<SelectionChanged>().connect(
- [](const SelectionChanged& e) {
- ES_LOG_DEBUG("Selection changed: {} -> {} entities",
- e.previousSelection.size(), e.currentSelection.size());
- }));
-
- eventConnections_.add(
- dispatcher_.sink<HistoryChanged>().connect(
- [](const HistoryChanged& e) {
- ES_LOG_TRACE("History changed - Undo: {}, Redo: {}",
- e.canUndo ? e.undoDescription : "(none)",
- e.canRedo ? e.redoDescription : "(none)");
- }));
-
- eventConnections_.add(
- dispatcher_.sink<EntityCreated>().connect(
- [](const EntityCreated& e) {
- ES_LOG_DEBUG("Entity created: {} ({})", e.entity, e.name);
- }));
-
- eventConnections_.add(
- dispatcher_.sink<EntityDeleted>().connect(
- [](const EntityDeleted& e) {
- ES_LOG_DEBUG("Entity deleted: {}", e.entity);
- }));
-
- eventConnections_.add(
- dispatcher_.sink<ProjectOpened>().connect(
- [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(
- dispatcher_.sink<ProjectClosed>().connect(
- [](const ProjectClosed&) {
- ES_LOG_INFO("Project closed");
- }));
-}
-
-void EditorApplication::setupEditorLayout() {
- ES_LOG_INFO("setupEditorLayout: Creating editor root container...");
-
- auto editorRoot = makeUnique<EditorRootContainer>(ui::WidgetId("editor.root"));
- editorRoot_ = editorRoot.get();
-
- auto dockArea = makeUnique<ui::DockArea>(ui::WidgetId("editor.dock_area"));
- dockArea_ = dockArea.get();
-
- dockArea_->setMinPanelSize(glm::vec2(150.0f, 100.0f));
- dockArea_->setSplitterThickness(4.0f);
- dockArea_->setTabBarHeight(26.0f);
-
- ES_LOG_INFO("setupEditorLayout: Creating SceneViewPanel...");
- auto sceneViewPanel = makeUnique<SceneViewPanel>(registry_, selection_, getResourceManager());
- sceneViewPanel->setMinSize(glm::vec2(400.0f, 300.0f));
- sceneViewPanel->setCommandHistory(&commandHistory_);
- sceneViewPanel_ = sceneViewPanel.get();
- auto sceneViewPanelId = sceneViewPanel->getPanelId();
- dockArea_->addPanel(std::move(sceneViewPanel), ui::DockDropZone::Center);
-
- ES_LOG_INFO("setupEditorLayout: Creating GameViewPanel...");
- auto gameViewPanel = makeUnique<GameViewPanel>(registry_, getResourceManager());
- gameViewPanel->setMinSize(glm::vec2(400.0f, 300.0f));
- gameViewPanel_ = gameViewPanel.get();
- ui::DockNode* sceneViewNode = dockArea_->findNodeContainingPanel(sceneViewPanelId);
- dockArea_->addPanel(std::move(gameViewPanel), ui::DockDropZone::Center, sceneViewNode);
-
- 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_, &scriptComponentRegistry_);
- inspectorPanel->setMinSize(glm::vec2(250.0f, 200.0f));
- dockArea_->addPanel(std::move(inspectorPanel), ui::DockDropZone::Right, nullptr, 0.25f);
-
- editorRoot_->setMainContent(std::move(dockArea));
-
- ES_LOG_INFO("setupEditorLayout: Creating AssetBrowserPanel for drawer...");
- 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...");
- auto outputLogPanel = makeUnique<OutputLogPanel>(ui::WidgetId("editor.output_log"));
- editorRoot_->setOutputDrawerContent(std::move(outputLogPanel));
-
- (void)sink(editorRoot_->getAssetsDrawer()->onDockRequested).connect([this]() {
- dockAssetBrowser();
- });
-
- auto* toolbar = editorRoot_->getToolbar();
- eventConnections_.add(sink(toolbar->onPlay).connect([this]() {
- ES_LOG_INFO("Play mode started");
- }));
-
- eventConnections_.add(sink(toolbar->onPause).connect([this]() {
- ES_LOG_INFO("Play mode paused");
- }));
-
- eventConnections_.add(sink(toolbar->onStop).connect([this]() {
- ES_LOG_INFO("Play mode stopped");
- }));
-
- eventConnections_.add(sink(toolbar->onWebPreview).connect([this, toolbar]() {
- if (toolbar->isWebPreviewRunning()) {
- toolbar->stopWebPreview();
- ES_LOG_INFO("Web preview stopped");
- } else {
- std::string webBuildDir = projectManager_->getWebBuildPath();
- std::string sdkPath = findWebSDKPath();
-
- if (sdkPath.empty()) {
- ES_LOG_ERROR("Web SDK not found. Please set ESENGINE_WEB_SDK environment variable.");
- 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...");
-
- WebExporter::exportProjectAsync(
- projectPath,
- sdkPath,
- webBuildDir,
- [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);
- }
- );
- }
- }));
-
- eventConnections_.add(sink(toolbar->onSave).connect([this]() {
- saveCurrentScene();
- }));
-
- eventConnections_.add(sink(toolbar->onNewScene).connect([this]() {
- newScene();
- }));
-
- uiContext_->setRoot(std::move(editorRoot));
-
- ES_LOG_INFO("Editor layout initialized with StatusBar and Drawer system");
-}
-
-void EditorApplication::createDemoScene() {
- Entity root = registry_.create();
- registry_.emplace<ecs::Name>(root, "Scene Root");
- registry_.emplace<ecs::LocalTransform>(root);
-
- 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();
-
- Entity light = registry_.create();
- registry_.emplace<ecs::Name>(light, "Directional Light");
- registry_.emplace<ecs::LocalTransform>(light, glm::vec3(0.0f, 10.0f, 0.0f));
-
- Entity player = registry_.create();
- registry_.emplace<ecs::Name>(player, "Player");
- registry_.emplace<ecs::LocalTransform>(player, glm::vec3(0.0f, -3.0f, 0.0f));
- auto& playerSprite = registry_.emplace<ecs::Sprite>(player);
- playerSprite.color = glm::vec4(0.2f, 0.6f, 1.0f, 1.0f);
- playerSprite.size = glm::vec2(1.0f, 2.0f);
-
- Entity playerMesh = registry_.create();
- registry_.emplace<ecs::Name>(playerMesh, "PlayerMesh");
- registry_.emplace<ecs::LocalTransform>(playerMesh);
- registry_.emplace<ecs::Parent>(playerMesh, player);
-
- Entity playerWeapon = registry_.create();
- registry_.emplace<ecs::Name>(playerWeapon, "Weapon");
- registry_.emplace<ecs::LocalTransform>(playerWeapon, glm::vec3(0.5f, 0.0f, 0.0f));
- registry_.emplace<ecs::Parent>(playerWeapon, player);
-
- auto& playerChildren = registry_.emplace<ecs::Children>(player);
- playerChildren.entities = {playerMesh, playerWeapon};
-
- Entity ground = registry_.create();
- registry_.emplace<ecs::Name>(ground, "Ground");
- registry_.emplace<ecs::LocalTransform>(ground, glm::vec3(0.0f, 0.0f, 0.0f), glm::quat(1.0f, 0.0f, 0.0f, 0.0f), glm::vec3(100.0f, 0.1f, 100.0f));
-
- Entity obstacle1 = registry_.create();
- registry_.emplace<ecs::Name>(obstacle1, "Obstacle 1");
- registry_.emplace<ecs::LocalTransform>(obstacle1, glm::vec3(5.0f, 0.0f, 0.0f));
- auto& obs1Sprite = registry_.emplace<ecs::Sprite>(obstacle1);
- obs1Sprite.color = glm::vec4(1.0f, 0.3f, 0.3f, 1.0f);
- obs1Sprite.size = glm::vec2(2.0f, 2.0f);
-
- Entity obstacle2 = registry_.create();
- registry_.emplace<ecs::Name>(obstacle2, "Obstacle 2");
- registry_.emplace<ecs::LocalTransform>(obstacle2, glm::vec3(-5.0f, 2.0f, 0.0f));
- auto& obs2Sprite = registry_.emplace<ecs::Sprite>(obstacle2);
- obs2Sprite.color = glm::vec4(0.3f, 1.0f, 0.3f, 1.0f);
- obs2Sprite.size = glm::vec2(1.5f, 1.5f);
-
- 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
-// =============================================================================
-
-void EditorApplication::setupLauncherLayout() {
- ES_LOG_INFO("Setting up launcher layout");
-
- mode_ = EditorMode::Launcher;
-
- auto container = makeUnique<ui::Panel>(ui::WidgetId("editor.launcher_container"));
- container->setWidth(ui::SizeValue::percent(100.0f));
- container->setHeight(ui::SizeValue::percent(100.0f));
-
- auto launcherPanel = makeUnique<ProjectLauncherPanel>(
- ui::WidgetId("editor.launcher"),
- *projectManager_,
- dispatcher_);
-
- launcherPanel_ = launcherPanel.get();
-
- eventConnections_.add(
- sink(launcherPanel_->onCreateProjectRequested).connect([this]() {
- onNewProjectRequested();
- }));
-
- eventConnections_.add(
- sink(launcherPanel_->onBrowseProjectRequested).connect([this]() {
- onOpenProjectRequested();
- }));
-
- eventConnections_.add(
- sink(launcherPanel_->onProjectOpened).connect([this](const std::string& path) {
- auto result = projectManager_->openProject(path);
- if (result.isOk()) {
- pendingShowEditor_ = true;
- } else {
- ES_LOG_ERROR("Failed to open project: {}", result.error());
- }
- }));
-
- container->addChild(std::move(launcherPanel));
-
- auto newProjectDialog = makeUnique<NewProjectDialog>(ui::WidgetId("editor.new_project_dialog"));
- newProjectDialog_ = newProjectDialog.get();
- newProjectDialog_->hide();
-
- eventConnections_.add(
- sink(newProjectDialog_->onProjectCreate).connect([this](const std::string& name, const std::string& path) {
- ES_LOG_INFO("Creating project '{}' at {}", name, path);
- auto result = projectManager_->createProject(path, name);
- if (result.isOk()) {
- pendingShowEditor_ = true;
- } else {
- ES_LOG_ERROR("Failed to create project: {}", result.error());
- }
- }));
-
- eventConnections_.add(
- sink(newProjectDialog_->onCancel).connect([this]() {
- ES_LOG_DEBUG("New project dialog cancelled");
- }));
-
- container->addChild(std::move(newProjectDialog));
-
- uiContext_->setRoot(std::move(container));
-
- ES_LOG_INFO("Launcher layout initialized");
-}
-
-void EditorApplication::showLauncher() {
- if (mode_ == EditorMode::Launcher) {
- return;
- }
-
- ES_LOG_INFO("Switching to launcher mode");
-
- dockArea_ = nullptr;
- editorRoot_ = nullptr;
- gameViewPanel_ = nullptr;
- dockedAssetBrowser_ = nullptr;
-
- setupLauncherLayout();
-}
-
-void EditorApplication::showEditor() {
- if (mode_ == EditorMode::Editor) {
- return;
- }
-
- ES_LOG_INFO("Switching to editor mode");
-
- eventConnections_.disconnectAll();
- launcherPanel_ = nullptr;
- newProjectDialog_ = nullptr;
-
- mode_ = EditorMode::Editor;
-
- createEmptyScene();
-
- setupEditorLayout();
-
- ES_LOG_INFO("Editor mode active");
-}
-
-void EditorApplication::onNewProjectRequested() {
- ES_LOG_INFO("New project requested");
- if (newProjectDialog_) {
- newProjectDialog_->show();
- }
-}
-
-void EditorApplication::onOpenProjectRequested() {
- ES_LOG_INFO("Open project requested");
-
- std::string projectFile = FileDialog::openFile(
- "Open Project",
- {{.name = "ESEngine Project", .pattern = "*.esproject"}});
-
- if (projectFile.empty()) {
- ES_LOG_DEBUG("Open project cancelled");
- return;
- }
-
- ES_LOG_INFO("Opening project: {}", projectFile);
-
- auto result = projectManager_->openProject(projectFile);
- if (result.isOk()) {
- showEditor();
- } else {
- ES_LOG_ERROR("Failed to open project: {}", result.error());
- }
-}
-
-void EditorApplication::dockAssetBrowser() {
- if (!dockArea_ || !editorRoot_) {
- return;
- }
-
- ES_LOG_INFO("Docking AssetBrowser to dock area");
-
- editorRoot_->closeAssetsDrawer();
-
- 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);
- }
-
- ES_LOG_INFO("AssetBrowser docked successfully");
-}
-
-std::string EditorApplication::findWebSDKPath() {
- namespace fs = std::filesystem;
-
- // 1. Check environment variable
- if (const char* envPath = std::getenv("ESENGINE_WEB_SDK")) {
- if (fs::exists(envPath) && fs::exists(fs::path(envPath) / "esengine.wasm")) {
- ES_LOG_DEBUG("Found Web SDK via ESENGINE_WEB_SDK: {}", envPath);
- return envPath;
- }
- }
-
- // 2. Check relative to editor root (for development)
- std::string editorDir = PathResolver::editorPath("");
- std::vector<std::string> searchPaths = {
- editorDir + "/build-web/sdk", // F:\microes\build-web\sdk
- editorDir + "/../build-web/sdk", // One level up
- editorDir + "/../../build-web/sdk", // Two levels up (if running from bin/)
- editorDir + "/sdk/web",
- editorDir + "/web-sdk"
- };
-
- for (const auto& path : searchPaths) {
- fs::path sdkPath = fs::weakly_canonical(path);
- if (fs::exists(sdkPath) && fs::exists(sdkPath / "esengine.wasm")) {
- ES_LOG_DEBUG("Found Web SDK at: {}", sdkPath.string());
- return sdkPath.string();
- }
- }
-
- ES_LOG_WARN("Web SDK not found. Searched paths:");
- for (const auto& path : searchPaths) {
- ES_LOG_WARN(" - {}", path);
- }
-
- 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
deleted file mode 100644
index 662a8de0d..000000000
--- a/src/esengine/editor/EditorApplication.hpp
+++ /dev/null
@@ -1,389 +0,0 @@
-/**
- * @file EditorApplication.hpp
- * @brief ESEngine Editor main application
- * @details The editor application provides a visual interface for creating
- * and editing game content using the ESEngine framework.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-// Project includes
-#include "../core/Application.hpp"
-#include "../math/Math.hpp"
-#include "../events/Dispatcher.hpp"
-#include "../ui/UIContext.hpp"
-#include "ui/docking/DockArea.hpp"
-#include "command/CommandHistory.hpp"
-#include "core/Selection.hpp"
-#include "AssetDatabase.hpp"
-#include "ThumbnailGenerator.hpp"
-#include "DragDropManager.hpp"
-#include "project/ProjectManager.hpp"
-#include "script/ScriptComponentRegistry.hpp"
-
-namespace esengine {
-namespace editor {
-
-class ProjectLauncherPanel;
-class NewProjectDialog;
-class EditorRootContainer;
-class AssetBrowserPanel;
-class GameViewPanel;
-class SceneViewPanel;
-class HierarchyPanel;
-
-// =============================================================================
-// Editor Mode
-// =============================================================================
-
-enum class EditorMode : u8 {
- Launcher,
- Editor
-};
-
-// =============================================================================
-// EditorApplication Class
-// =============================================================================
-
-/**
- * @brief Main editor application class
- *
- * @details Extends the base Application class to provide editor-specific
- * functionality including:
- * - Event system for inter-component communication
- * - Command history with undo/redo support
- * - Entity selection management
- * - Custom UI rendering
- * - Scene editing
- * - Asset management
- * - Plugin system (future)
- *
- * @code
- * int main() {
- * EditorApplication editor;
- * return editor.run();
- * }
- * @endcode
- */
-class EditorApplication : public Application {
-public:
- /**
- * @brief Default constructor
- */
- EditorApplication();
-
- /**
- * @brief Virtual destructor
- */
- ~EditorApplication() override = default;
-
- // =========================================================================
- // Core Systems Access
- // =========================================================================
-
- /**
- * @brief Get the event dispatcher
- * @return Reference to the event dispatcher
- */
- Dispatcher& getDispatcher() { return dispatcher_; }
-
- /**
- * @brief Get the command history
- * @return Reference to the command history
- */
- CommandHistory& getCommandHistory() { return commandHistory_; }
-
- /**
- * @brief Get the entity selection
- * @return Reference to the entity selection
- */
- EntitySelection& getSelection() { return selection_; }
-
- /**
- * @brief Get the UI context
- * @return Reference to the UI context
- */
- ui::UIContext& getUIContext() { return *uiContext_; }
-
- /**
- * @brief Get the ECS registry (from base Application class)
- * @return Reference to the ECS registry
- */
- ecs::Registry& getEditorRegistry() { return Application::getRegistry(); }
-
- /**
- * @brief Get the asset database
- * @return Reference to the asset database
- */
- AssetDatabase& getAssetDatabase() { return assetDatabase_; }
-
- /**
- * @brief Get the thumbnail generator
- * @return Reference to the thumbnail generator
- */
- ThumbnailGenerator& getThumbnailGenerator() { return thumbnailGenerator_; }
-
- /**
- * @brief Get the drag-drop manager
- * @return Reference to the drag-drop manager
- */
- DragDropManager& getDragDropManager() { return dragDropManager_; }
-
- /**
- * @brief Get the project manager
- * @return Reference to the project manager
- */
- 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)
- */
- EditorMode getMode() const { return mode_; }
-
- /**
- * @brief Switch to launcher mode
- */
- void showLauncher();
-
- /**
- * @brief Switch to editor mode
- */
- 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
- // =========================================================================
-
- /**
- * @brief Called once after engine initialization
- * @details Initializes editor-specific systems and UI.
- */
- void onInit() override;
-
- /**
- * @brief Called every frame
- * @param deltaTime Time since last frame in seconds
- */
- void onUpdate(f32 deltaTime) override;
-
- /**
- * @brief Called when rendering
- * @details Renders the editor UI and scene view.
- */
- void onRender() override;
-
- /**
- * @brief Called before application shutdown
- */
- void onShutdown() override;
-
- /**
- * @brief Called on key events
- * @param key Key code
- * @param pressed True if pressed, false if released
- */
- void onKey(KeyCode key, bool pressed) override;
-
- /**
- * @brief Called on window resize
- * @param width New width
- * @param height New height
- */
- void onResize(u32 width, u32 height) override;
-
- /**
- * @brief Called on touch/mouse input
- * @param type Touch event type
- * @param point Touch position
- */
- void onTouch(TouchType type, const TouchPoint& point) override;
-
-private:
- // =========================================================================
- // Private Methods
- // =========================================================================
-
- /**
- * @brief Handle undo action (Ctrl+Z)
- */
- void handleUndo();
-
- /**
- * @brief Handle redo action (Ctrl+Y / Ctrl+Shift+Z)
- */
- void handleRedo();
-
- /**
- * @brief Setup event listeners
- */
- void setupEventListeners();
-
- /**
- * @brief Setup editor UI layout with docking panels
- */
- void setupEditorLayout();
-
- /**
- * @brief Create demo entities for testing
- */
- void createDemoScene();
-
- /**
- * @brief Create a minimal empty scene with Canvas and Camera
- */
- void createEmptyScene();
-
- /**
- * @brief Setup project launcher UI
- */
- void setupLauncherLayout();
-
- /**
- * @brief Handle new project request from launcher
- */
- void onNewProjectRequested();
-
- /**
- * @brief Handle open project request from launcher
- */
- void onOpenProjectRequested();
-
- /**
- * @brief Dock the asset browser from drawer to dock area
- */
- void dockAssetBrowser();
-
- /**
- * @brief Find the web SDK path
- * @return Path to web SDK directory, or empty string if not found
- */
- std::string findWebSDKPath();
-
- /**
- * @brief Ensure scenes directory exists and return its path
- * @return Path to scenes directory
- */
- std::string ensureScenesDirectory();
-
- // =========================================================================
- // Constants
- // =========================================================================
-
- /** @brief Interval in seconds between FPS updates */
- static constexpr f64 FPS_UPDATE_INTERVAL = 1.0;
-
- // =========================================================================
- // Core Editor Systems
- // =========================================================================
-
- Dispatcher dispatcher_; ///< Central event bus
- CommandHistory commandHistory_; ///< Undo/redo history
- EntitySelection selection_; ///< Entity selection manager
- AssetDatabase assetDatabase_; ///< Asset database
- 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
-
- // =========================================================================
- // State
- // =========================================================================
-
- EditorMode mode_ = EditorMode::Launcher; ///< Current editor mode
- glm::vec4 clearColor_{0.15f, 0.15f, 0.15f, 1.0f}; ///< Editor background color
- f64 frameTime_ = 0.0; ///< Accumulated frame time
- u32 frameCount_ = 0; ///< Frame counter for FPS
- f32 fps_ = 0.0f; ///< Frames per second
- bool ctrlPressed_ = false; ///< Ctrl key state
- bool shiftPressed_ = false; ///< Shift key state
- 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
- // =========================================================================
-
- ConnectionHolder eventConnections_; ///< Holds event subscriptions
-};
-
-} // namespace editor
-} // namespace esengine
diff --git a/src/esengine/editor/ThumbnailGenerator.cpp b/src/esengine/editor/ThumbnailGenerator.cpp
deleted file mode 100644
index d9e953f00..000000000
--- a/src/esengine/editor/ThumbnailGenerator.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
- * @file ThumbnailGenerator.cpp
- * @brief Thumbnail generator implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ThumbnailGenerator.hpp"
-#include "panels/AssetBrowserTypes.hpp"
-#include "../core/Log.hpp"
-
-#include <stb_image.h>
-
-#include <algorithm>
-#include <cstring>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Helper Functions
-// =============================================================================
-
-namespace {
-
-std::vector<u8> resizeImage(const u8* src, u32 srcWidth, u32 srcHeight, u32 dstWidth, u32 dstHeight, u32 channels) {
- std::vector<u8> dst(dstWidth * dstHeight * channels);
-
- for (u32 y = 0; y < dstHeight; ++y) {
- for (u32 x = 0; x < dstWidth; ++x) {
- u32 srcX = x * srcWidth / dstWidth;
- u32 srcY = y * srcHeight / dstHeight;
-
- srcX = std::min(srcX, srcWidth - 1);
- srcY = std::min(srcY, srcHeight - 1);
-
- for (u32 c = 0; c < channels; ++c) {
- dst[(y * dstWidth + x) * channels + c] =
- src[(srcY * srcWidth + srcX) * channels + c];
- }
- }
- }
-
- return dst;
-}
-
-glm::vec4 getColorForType(AssetType type) {
- switch (type) {
- case AssetType::Folder: return {0.9f, 0.8f, 0.3f, 1.0f};
- case AssetType::Texture: return {0.3f, 0.7f, 0.9f, 1.0f};
- case AssetType::Audio: return {0.9f, 0.5f, 0.3f, 1.0f};
- case AssetType::Script: return {0.5f, 0.9f, 0.5f, 1.0f};
- case AssetType::Shader: return {0.8f, 0.5f, 0.9f, 1.0f};
- case AssetType::Scene: return {0.3f, 0.9f, 0.9f, 1.0f};
- case AssetType::Prefab: return {0.9f, 0.3f, 0.6f, 1.0f};
- case AssetType::Font: return {0.7f, 0.7f, 0.7f, 1.0f};
- default: return {0.5f, 0.5f, 0.5f, 1.0f};
- }
-}
-
-} // namespace
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-ThumbnailGenerator::ThumbnailGenerator() = default;
-
-ThumbnailGenerator::~ThumbnailGenerator() = default;
-
-// =============================================================================
-// Public Methods
-// =============================================================================
-
-void ThumbnailGenerator::generateThumbnail(const std::string& guid, const std::string& path, AssetType type) {
- if (hasThumbnail(guid)) {
- return;
- }
-
- if (type == AssetType::Texture) {
- generateTextureThumbnail(guid, path);
- } else {
- generatePlaceholder(guid, type);
- }
-}
-
-bool ThumbnailGenerator::hasThumbnail(const std::string& guid) const {
- return thumbnails_.find(guid) != thumbnails_.end();
-}
-
-Texture* ThumbnailGenerator::getThumbnail(const std::string& guid) const {
- auto it = thumbnails_.find(guid);
- if (it != thumbnails_.end()) {
- return it->second.get();
- }
- return nullptr;
-}
-
-void ThumbnailGenerator::clear() {
- thumbnails_.clear();
-}
-
-void ThumbnailGenerator::removeThumbnail(const std::string& guid) {
- thumbnails_.erase(guid);
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void ThumbnailGenerator::generateTextureThumbnail(const std::string& guid, const std::string& path) {
- int width, height, channels;
- stbi_set_flip_vertically_on_load(false);
- u8* data = stbi_load(path.c_str(), &width, &height, &channels, 4);
-
- if (!data) {
- ES_LOG_WARN("Failed to load image for thumbnail: {}", path);
- generatePlaceholder(guid, AssetType::Texture);
- return;
- }
-
- std::vector<u8> resized = resizeImage(data, static_cast<u32>(width), static_cast<u32>(height),
- THUMBNAIL_SIZE, THUMBNAIL_SIZE, 4);
- stbi_image_free(data);
-
- auto texture = Texture::create(THUMBNAIL_SIZE, THUMBNAIL_SIZE, resized, TextureFormat::RGBA8);
- if (texture) {
- thumbnails_[guid] = std::move(texture);
- }
-}
-
-void ThumbnailGenerator::generatePlaceholder(const std::string& guid, AssetType type) {
- glm::vec4 color = getColorForType(type);
-
- std::vector<u8> pixels(THUMBNAIL_SIZE * THUMBNAIL_SIZE * 4);
- u8 r = static_cast<u8>(color.r * 255.0f);
- u8 g = static_cast<u8>(color.g * 255.0f);
- u8 b = static_cast<u8>(color.b * 255.0f);
- u8 a = static_cast<u8>(color.a * 255.0f);
-
- for (u32 y = 0; y < THUMBNAIL_SIZE; ++y) {
- for (u32 x = 0; x < THUMBNAIL_SIZE; ++x) {
- usize idx = (y * THUMBNAIL_SIZE + x) * 4;
- pixels[idx + 0] = r;
- pixels[idx + 1] = g;
- pixels[idx + 2] = b;
- pixels[idx + 3] = a;
- }
- }
-
- auto texture = Texture::create(THUMBNAIL_SIZE, THUMBNAIL_SIZE, pixels, TextureFormat::RGBA8);
- if (texture) {
- thumbnails_[guid] = std::move(texture);
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/ThumbnailGenerator.hpp b/src/esengine/editor/ThumbnailGenerator.hpp
deleted file mode 100644
index 63b3e236c..000000000
--- a/src/esengine/editor/ThumbnailGenerator.hpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * @file ThumbnailGenerator.hpp
- * @brief Asset thumbnail generation and caching
- * @details Generates and caches thumbnail images for various asset types
- * for display in the asset browser.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../core/Types.hpp"
-#include "../renderer/Texture.hpp"
-
-#include <string>
-#include <unordered_map>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Forward Declarations
-// =============================================================================
-
-enum class AssetType : u8;
-
-// =============================================================================
-// ThumbnailGenerator Class
-// =============================================================================
-
-class ThumbnailGenerator {
-public:
- static constexpr u32 THUMBNAIL_SIZE = 64;
-
- ThumbnailGenerator();
- ~ThumbnailGenerator();
-
- void generateThumbnail(const std::string& guid, const std::string& path, AssetType type);
-
- bool hasThumbnail(const std::string& guid) const;
- Texture* getThumbnail(const std::string& guid) const;
-
- void clear();
- void removeThumbnail(const std::string& guid);
-
-private:
- void generateTextureThumbnail(const std::string& guid, const std::string& path);
- void generatePlaceholder(const std::string& guid, AssetType type);
-
- std::unordered_map<std::string, Unique<Texture>> thumbnails_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/camera/EditorCamera.cpp b/src/esengine/editor/camera/EditorCamera.cpp
deleted file mode 100644
index 0e07cadc2..000000000
--- a/src/esengine/editor/camera/EditorCamera.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/**
- * @file EditorCamera.cpp
- * @brief Editor camera implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "EditorCamera.hpp"
-#include "../../platform/Platform.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-EditorCamera::EditorCamera() {
- updateView();
-}
-
-// =============================================================================
-// Configuration
-// =============================================================================
-
-void EditorCamera::setViewportSize(f32 width, f32 height) {
- viewportWidth_ = width;
- viewportHeight_ = height;
- aspectRatio_ = width / height;
-}
-
-void EditorCamera::setFocalPoint(const glm::vec3& point) {
- focalPoint_ = point;
- updateView();
-}
-
-void EditorCamera::setDistance(f32 distance) {
- distance_ = glm::clamp(distance, 0.1f, 1000.0f);
- updateView();
-}
-
-void EditorCamera::setFieldOfView(f32 fov) {
- fov_ = glm::clamp(fov, 10.0f, 120.0f);
-}
-
-void EditorCamera::setClipPlanes(f32 near, f32 far) {
- nearClip_ = near;
- farClip_ = far;
-}
-
-// =============================================================================
-// Input Handling
-// =============================================================================
-
-bool EditorCamera::onMouseDown(const ui::MouseButtonEvent& event) {
- lastMousePos_ = glm::vec2(event.x, event.y);
-
- if (event.button == ui::MouseButton::Left && event.alt && orbitEnabled_) {
- isOrbiting_ = true;
- return true;
- }
-
- if (event.button == ui::MouseButton::Middle ||
- (event.button == ui::MouseButton::Left && event.shift)) {
- isPanning_ = true;
- return true;
- }
-
- return false;
-}
-
-bool EditorCamera::onMouseUp(const ui::MouseButtonEvent& event) {
- if (event.button == ui::MouseButton::Left) {
- isOrbiting_ = false;
- }
- if (event.button == ui::MouseButton::Middle) {
- isPanning_ = false;
- }
-
- return isOrbiting_ || isPanning_;
-}
-
-bool EditorCamera::onMouseMove(const ui::MouseMoveEvent& event) {
- glm::vec2 mousePos(event.x, event.y);
- glm::vec2 delta = mousePos - lastMousePos_;
- lastMousePos_ = mousePos;
-
- if (isOrbiting_) {
- mouseRotate(delta.x, delta.y);
- return true;
- }
-
- if (isPanning_) {
- mousePan(delta.x, delta.y);
- return true;
- }
-
- return false;
-}
-
-bool EditorCamera::onMouseScroll(const ui::ScrollEvent& event) {
- mouseZoom(event.deltaY);
- return true;
-}
-
-// =============================================================================
-// Matrix Access
-// =============================================================================
-
-glm::mat4 EditorCamera::getViewMatrix() const {
- return viewMatrix_;
-}
-
-glm::mat4 EditorCamera::getProjectionMatrix() const {
- return math::perspective(math::toRadians(fov_), aspectRatio_, nearClip_, farClip_);
-}
-
-glm::mat4 EditorCamera::getViewProjectionMatrix() const {
- return getProjectionMatrix() * getViewMatrix();
-}
-
-glm::vec3 EditorCamera::getPosition() const {
- return focalPoint_ - getForwardDirection() * distance_;
-}
-
-glm::vec3 EditorCamera::getForwardDirection() const {
- return glm::rotate(getOrientation(), glm::vec3(0.0f, 0.0f, -1.0f));
-}
-
-glm::vec3 EditorCamera::getUpDirection() const {
- return glm::rotate(getOrientation(), glm::vec3(0.0f, 1.0f, 0.0f));
-}
-
-glm::vec3 EditorCamera::getRightDirection() const {
- return glm::rotate(getOrientation(), glm::vec3(1.0f, 0.0f, 0.0f));
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void EditorCamera::updateView() {
- glm::vec3 position = getPosition();
- viewMatrix_ = glm::lookAt(position, focalPoint_, glm::vec3(0.0f, 1.0f, 0.0f));
-}
-
-glm::quat EditorCamera::getOrientation() const {
- return glm::quat(glm::vec3(-pitch_, -yaw_, 0.0f));
-}
-
-void EditorCamera::mousePan(f32 deltaX, f32 deltaY) {
- f32 speed = 0.001f * distance_;
- focalPoint_ += getRightDirection() * (-deltaX * speed);
- focalPoint_ += getUpDirection() * (deltaY * speed);
- updateView();
-}
-
-void EditorCamera::mouseRotate(f32 deltaX, f32 deltaY) {
- f32 yawSign = getUpDirection().y < 0.0f ? -1.0f : 1.0f;
- yaw_ += yawSign * deltaX * 0.003f;
- pitch_ += deltaY * 0.003f;
-
- pitch_ = glm::clamp(pitch_, -glm::half_pi<f32>() + 0.01f, glm::half_pi<f32>() - 0.01f);
-
- updateView();
-}
-
-void EditorCamera::mouseZoom(f32 delta) {
- distance_ -= delta * 0.5f;
- distance_ = glm::clamp(distance_, 0.1f, 1000.0f);
- updateView();
-}
-
-void EditorCamera::setRotation(f32 pitch, f32 yaw) {
- pitch_ = glm::clamp(pitch, -glm::half_pi<f32>() + 0.01f, glm::half_pi<f32>() - 0.01f);
- yaw_ = yaw;
- targetPitch_ = pitch_;
- targetYaw_ = yaw_;
- isAnimating_ = false;
- updateView();
-}
-
-void EditorCamera::animateTo(f32 pitch, f32 yaw) {
- targetPitch_ = glm::clamp(pitch, -glm::half_pi<f32>() + 0.01f, glm::half_pi<f32>() - 0.01f);
- targetYaw_ = yaw;
-
- while (targetYaw_ - yaw_ > glm::pi<f32>()) targetYaw_ -= glm::two_pi<f32>();
- while (targetYaw_ - yaw_ < -glm::pi<f32>()) targetYaw_ += glm::two_pi<f32>();
-
- isAnimating_ = true;
-}
-
-void EditorCamera::update(f32 deltaTime) {
- if (!isAnimating_) return;
-
- f32 t = 1.0f - glm::exp(-animationSpeed_ * deltaTime);
-
- pitch_ = glm::mix(pitch_, targetPitch_, t);
- yaw_ = glm::mix(yaw_, targetYaw_, t);
-
- f32 pitchDiff = glm::abs(pitch_ - targetPitch_);
- f32 yawDiff = glm::abs(yaw_ - targetYaw_);
-
- if (pitchDiff < 0.001f && yawDiff < 0.001f) {
- pitch_ = targetPitch_;
- yaw_ = targetYaw_;
- isAnimating_ = false;
- }
-
- updateView();
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/camera/EditorCamera.hpp b/src/esengine/editor/camera/EditorCamera.hpp
deleted file mode 100644
index 534f98015..000000000
--- a/src/esengine/editor/camera/EditorCamera.hpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/**
- * @file EditorCamera.hpp
- * @brief Editor camera with orbit, pan, and zoom controls
- * @details Provides intuitive camera controls for 3D scene editing including
- * mouse orbit, pan, and scroll wheel zoom.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-#include "../../math/Math.hpp"
-#include "../../ui/events/UIEvent.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// EditorCamera Class
-// =============================================================================
-
-/**
- * @brief 3D camera for scene editing
- *
- * @details Implements orbit camera controls common in 3D editors:
- * - Alt+LMB: Orbit around focal point
- * - Alt+MMB / MMB: Pan camera
- * - Scroll wheel: Zoom in/out
- *
- * @code
- * EditorCamera camera;
- * camera.setViewportSize(800, 600);
- * camera.setFocalPoint(glm::vec3(0.0f));
- * camera.setDistance(10.0f);
- *
- * // Handle mouse events
- * camera.onMouseDown(mouseEvent);
- * camera.onMouseMove(mouseEvent);
- * camera.onMouseScroll(scrollEvent);
- *
- * // Get matrices for rendering
- * glm::mat4 view = camera.getViewMatrix();
- * glm::mat4 proj = camera.getProjectionMatrix();
- * @endcode
- */
-class EditorCamera {
-public:
- EditorCamera();
- ~EditorCamera() = default;
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /**
- * @brief Sets the viewport dimensions
- * @param width Viewport width in pixels
- * @param height Viewport height in pixels
- */
- void setViewportSize(f32 width, f32 height);
-
- /**
- * @brief Sets the camera focal point
- * @param point World position to orbit around
- */
- void setFocalPoint(const glm::vec3& point);
-
- /**
- * @brief Sets the distance from focal point
- * @param distance Distance in world units
- */
- void setDistance(f32 distance);
-
- /**
- * @brief Sets the field of view
- * @param fov Field of view in degrees
- */
- void setFieldOfView(f32 fov);
-
- /**
- * @brief Sets near and far clip planes
- * @param near Near plane distance
- * @param far Far plane distance
- */
- void setClipPlanes(f32 near, f32 far);
-
- // =========================================================================
- // Input Handling
- // =========================================================================
-
- /**
- * @brief Handles mouse button down events
- * @param event Mouse button event
- * @return True if event was handled
- */
- bool onMouseDown(const ui::MouseButtonEvent& event);
-
- /**
- * @brief Handles mouse button up events
- * @param event Mouse button event
- * @return True if event was handled
- */
- bool onMouseUp(const ui::MouseButtonEvent& event);
-
- /**
- * @brief Handles mouse move events
- * @param event Mouse move event
- * @return True if event was handled
- */
- bool onMouseMove(const ui::MouseMoveEvent& event);
-
- /**
- * @brief Handles mouse scroll events
- * @param event Mouse scroll event
- * @return True if event was handled
- */
- bool onMouseScroll(const ui::ScrollEvent& event);
-
- // =========================================================================
- // Matrix Access
- // =========================================================================
-
- /** @brief Gets the view matrix */
- glm::mat4 getViewMatrix() const;
-
- /** @brief Gets the projection matrix */
- glm::mat4 getProjectionMatrix() const;
-
- /** @brief Gets the view-projection matrix */
- glm::mat4 getViewProjectionMatrix() const;
-
- /** @brief Gets the camera position in world space */
- glm::vec3 getPosition() const;
-
- /** @brief Gets the camera forward direction */
- glm::vec3 getForwardDirection() const;
-
- /** @brief Gets the camera up direction */
- glm::vec3 getUpDirection() const;
-
- /** @brief Gets the camera right direction */
- glm::vec3 getRightDirection() const;
-
- /** @brief Gets the focal point */
- const glm::vec3& getFocalPoint() const { return focalPoint_; }
-
- /** @brief Gets the distance from focal point */
- f32 getDistance() const { return distance_; }
-
- /** @brief Gets pitch angle */
- f32 getPitch() const { return pitch_; }
-
- /** @brief Gets yaw angle */
- f32 getYaw() const { return yaw_; }
-
- /** @brief Sets pitch and yaw angles directly (immediate) */
- void setRotation(f32 pitch, f32 yaw);
-
- /** @brief Animates to target pitch and yaw angles */
- void animateTo(f32 pitch, f32 yaw);
-
- /** @brief Updates animation, call every frame */
- void update(f32 deltaTime);
-
- /** @brief Returns true if animation is in progress */
- bool isAnimating() const { return isAnimating_; }
-
- /** @brief Enables or disables orbit rotation */
- void setOrbitEnabled(bool enabled) { orbitEnabled_ = enabled; }
-
- /** @brief Returns true if orbit is enabled */
- bool isOrbitEnabled() const { return orbitEnabled_; }
-
-private:
- void updateView();
- glm::quat getOrientation() const;
-
- void mousePan(f32 deltaX, f32 deltaY);
- void mouseRotate(f32 deltaX, f32 deltaY);
- void mouseZoom(f32 delta);
-
- glm::vec3 focalPoint_{0.0f};
- f32 distance_ = 10.0f;
- f32 pitch_ = 0.5f;
- f32 yaw_ = 0.0f;
-
- f32 fov_ = 45.0f;
- f32 aspectRatio_ = 16.0f / 9.0f;
- f32 nearClip_ = 0.1f;
- f32 farClip_ = 1000.0f;
-
- f32 viewportWidth_ = 1280.0f;
- f32 viewportHeight_ = 720.0f;
-
- glm::vec2 lastMousePos_{0.0f};
- bool isDragging_ = false;
- bool isPanning_ = false;
- bool isOrbiting_ = false;
-
- glm::mat4 viewMatrix_{1.0f};
-
- f32 targetPitch_ = 0.5f;
- f32 targetYaw_ = 0.0f;
- bool isAnimating_ = false;
- f32 animationSpeed_ = 8.0f;
- bool orbitEnabled_ = true;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/command/Command.hpp b/src/esengine/editor/command/Command.hpp
deleted file mode 100644
index a0007044a..000000000
--- a/src/esengine/editor/command/Command.hpp
+++ /dev/null
@@ -1,215 +0,0 @@
-/**
- * @file Command.hpp
- * @brief Base class for undoable commands
- * @details Defines the interface for commands that support undo/redo
- * operations. All editor operations that modify state should
- * be implemented as Command subclasses.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Type Definitions
-// =============================================================================
-
-/**
- * @brief Result of command execution
- */
-enum class CommandResult : u8 {
- Success,
- Failed,
- Cancelled,
- NoOp
-};
-
-/**
- * @brief Command execution options
- */
-struct CommandOptions {
- bool addToHistory = true;
- bool mergeWithPrevious = false;
-};
-
-// =============================================================================
-// Command Base Class
-// =============================================================================
-
-/**
- * @brief Abstract base class for undoable commands
- *
- * @details Commands encapsulate operations that can be undone and redone.
- * Each command stores enough state to reverse its effects.
- *
- * @code
- * class MoveEntityCommand : public Command {
- * public:
- * MoveEntityCommand(Entity e, const glm::vec3& newPos)
- * : entity_(e), newPosition_(newPos) {}
- *
- * CommandResult execute() override {
- * oldPosition_ = getPosition(entity_);
- * setPosition(entity_, newPosition_);
- * return CommandResult::Success;
- * }
- *
- * void undo() override {
- * setPosition(entity_, oldPosition_);
- * }
- *
- * std::string getDescription() const override {
- * return "Move Entity";
- * }
- * };
- * @endcode
- */
-class Command {
-public:
- virtual ~Command() = default;
-
- /**
- * @brief Execute the command
- * @return Result indicating success or failure
- */
- virtual CommandResult execute() = 0;
-
- /**
- * @brief Undo the command
- */
- virtual void undo() = 0;
-
- /**
- * @brief Redo the command (default: re-execute)
- * @return Result indicating success or failure
- */
- virtual CommandResult redo() {
- return execute();
- }
-
- /**
- * @brief Get a human-readable description
- * @return Description string
- */
- [[nodiscard]] virtual std::string getDescription() const = 0;
-
- /**
- * @brief Get the command type name
- * @return Type name for debugging/logging
- */
- [[nodiscard]] virtual std::string getTypeName() const {
- return "Command";
- }
-
- /**
- * @brief Check if this command can merge with another
- *
- * @param other The command to potentially merge with
- * @return true if commands can be merged
- *
- * @details Command merging allows multiple similar operations
- * (e.g., dragging) to be combined into a single undo step.
- */
- [[nodiscard]] virtual bool canMergeWith(const Command& other) const {
- (void)other;
- return false;
- }
-
- /**
- * @brief Merge another command into this one
- *
- * @param other The command to merge (will be discarded after)
- *
- * @details After merging, this command should represent the combined
- * effect of both commands. The other command will be deleted.
- */
- virtual void mergeWith(Command& other) {
- (void)other;
- }
-
- /**
- * @brief Get the merge window in milliseconds
- * @return Time window for merging (0 = no time limit)
- */
- [[nodiscard]] virtual u32 getMergeWindowMs() const {
- return 500;
- }
-
- /**
- * @brief Check if the command is still valid
- * @return true if the command can be executed/undone
- */
- [[nodiscard]] virtual bool isValid() const {
- return true;
- }
-
- /**
- * @brief Estimate memory usage of this command
- * @return Memory usage in bytes
- */
- [[nodiscard]] virtual usize getMemoryUsage() const {
- return sizeof(*this);
- }
-
- /**
- * @brief Serialize the command to a buffer
- *
- * @param buffer Output buffer
- * @return true if serialization succeeded
- *
- * @details Optional: Used for persistent undo history.
- */
- [[nodiscard]] virtual bool serialize(std::vector<u8>& buffer) const {
- (void)buffer;
- return false;
- }
-
- /**
- * @brief Get the timestamp when the command was created
- * @return Timestamp in milliseconds
- */
- [[nodiscard]] u64 getTimestamp() const {
- return timestamp_;
- }
-
- /**
- * @brief Set the timestamp (called by CommandHistory)
- * @param timestamp Timestamp in milliseconds
- */
- void setTimestamp(u64 timestamp) {
- timestamp_ = timestamp;
- }
-
-protected:
- Command() = default;
-
-private:
- u64 timestamp_ = 0;
-};
-
-// =============================================================================
-// Concept for Commands
-// =============================================================================
-
-/**
- * @brief Concept for command types
- */
-template<typename T>
-concept CommandType = std::derived_from<T, Command>;
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/command/CommandHistory.hpp b/src/esengine/editor/command/CommandHistory.hpp
deleted file mode 100644
index 9f47f8874..000000000
--- a/src/esengine/editor/command/CommandHistory.hpp
+++ /dev/null
@@ -1,552 +0,0 @@
-/**
- * @file CommandHistory.hpp
- * @brief Command history management with undo/redo support
- * @details Manages the execution history of commands, providing undo
- * and redo functionality with memory limits and command merging.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Command.hpp"
-#include "MacroCommand.hpp"
-#include "../core/EditorEvents.hpp"
-#include "../../events/Dispatcher.hpp"
-
-#include <chrono>
-#include <deque>
-#include <future>
-#include <mutex>
-#include <queue>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Configuration
-// =============================================================================
-
-/**
- * @brief Configuration for CommandHistory
- */
-struct CommandHistoryConfig {
- u32 maxUndoLevels = 100;
- usize maxMemoryUsage = 64 * 1024 * 1024; // 64 MB
- bool enableMerging = true;
- bool enableAsyncExecution = false;
-};
-
-// =============================================================================
-// Transaction Guard
-// =============================================================================
-
-class CommandHistory;
-
-/**
- * @brief RAII guard for command transactions
- *
- * @details Groups multiple commands into a single undoable operation.
- * Automatically commits on success or rolls back on exception.
- *
- * @code
- * {
- * TransactionGuard guard(history, "Batch Move");
- * for (Entity e : selection) {
- * history.execute<MoveCommand>(e, delta);
- * }
- * } // Auto-commits here
- * @endcode
- */
-class TransactionGuard {
-public:
- TransactionGuard(CommandHistory& history, const std::string& description);
- ~TransactionGuard();
-
- TransactionGuard(const TransactionGuard&) = delete;
- TransactionGuard& operator=(const TransactionGuard&) = delete;
- TransactionGuard(TransactionGuard&&) = delete;
- TransactionGuard& operator=(TransactionGuard&&) = delete;
-
- void commit();
- void rollback();
-
-private:
- CommandHistory& history_;
- bool committed_ = false;
- bool rolledBack_ = false;
-};
-
-// =============================================================================
-// CommandHistory Class
-// =============================================================================
-
-/**
- * @brief Manages command execution history with undo/redo support
- *
- * @details CommandHistory tracks executed commands and provides undo/redo
- * functionality. It supports command merging, transactions,
- * memory limits, and event notifications.
- *
- * @code
- * CommandHistory history;
- *
- * // Execute a command
- * history.execute(makeUnique<MoveCommand>(entity, newPos));
- *
- * // Or construct in-place
- * history.execute<MoveCommand>(entity, newPos);
- *
- * // Undo/Redo
- * history.undo();
- * history.redo();
- * @endcode
- */
-class CommandHistory {
-public:
- /**
- * @brief Construct with default configuration
- */
- CommandHistory() : CommandHistory(CommandHistoryConfig{}) {}
-
- /**
- * @brief Construct with custom configuration
- * @param config Configuration options
- */
- explicit CommandHistory(CommandHistoryConfig config)
- : config_(config) {}
-
- ~CommandHistory() = default;
-
- CommandHistory(const CommandHistory&) = delete;
- CommandHistory& operator=(const CommandHistory&) = delete;
- CommandHistory(CommandHistory&&) = default;
- CommandHistory& operator=(CommandHistory&&) = default;
-
- /**
- * @brief Execute a command
- * @param cmd The command to execute
- * @return Result of execution
- */
- CommandResult execute(Unique<Command> cmd) {
- return executeImpl(std::move(cmd), CommandOptions{});
- }
-
- /**
- * @brief Execute a command with options
- * @param cmd The command to execute
- * @param options Execution options
- * @return Result of execution
- */
- CommandResult execute(Unique<Command> cmd, const CommandOptions& options) {
- return executeImpl(std::move(cmd), options);
- }
-
- /**
- * @brief Execute a command constructed in-place
- * @tparam T Command type
- * @tparam Args Constructor argument types
- * @param args Constructor arguments
- * @return Result of execution
- */
- template<CommandType T, typename... Args>
- CommandResult execute(Args&&... args) {
- return execute(makeUnique<T>(std::forward<Args>(args)...));
- }
-
- /**
- * @brief Undo the last command
- * @return true if undo succeeded
- */
- bool undo() {
- if (!canUndo()) {
- return false;
- }
-
- if (inTransaction_) {
- return false;
- }
-
- auto& cmd = undoStack_.back();
- cmd->undo();
-
- redoStack_.push_back(std::move(cmd));
- undoStack_.pop_back();
-
- updateMemoryUsage();
- notifyHistoryChanged();
-
- if (dispatcher_) {
- dispatcher_->trigger(UndoRedoEvent{
- true,
- !redoStack_.empty() ? redoStack_.back()->getDescription() : ""});
- }
-
- return true;
- }
-
- /**
- * @brief Redo the last undone command
- * @return true if redo succeeded
- */
- bool redo() {
- if (!canRedo()) {
- return false;
- }
-
- if (inTransaction_) {
- return false;
- }
-
- auto& cmd = redoStack_.back();
- CommandResult result = cmd->redo();
-
- if (result == CommandResult::Failed) {
- return false;
- }
-
- undoStack_.push_back(std::move(cmd));
- redoStack_.pop_back();
-
- updateMemoryUsage();
- notifyHistoryChanged();
-
- if (dispatcher_) {
- dispatcher_->trigger(UndoRedoEvent{
- false,
- undoStack_.back()->getDescription()});
- }
-
- return true;
- }
-
- /**
- * @brief Check if undo is available
- * @return true if can undo
- */
- [[nodiscard]] bool canUndo() const {
- return !undoStack_.empty() && !inTransaction_;
- }
-
- /**
- * @brief Check if redo is available
- * @return true if can redo
- */
- [[nodiscard]] bool canRedo() const {
- return !redoStack_.empty() && !inTransaction_;
- }
-
- /**
- * @brief Get the description of the next undo action
- * @return Description string or empty
- */
- [[nodiscard]] std::string getUndoDescription() const {
- return canUndo() ? undoStack_.back()->getDescription() : "";
- }
-
- /**
- * @brief Get the description of the next redo action
- * @return Description string or empty
- */
- [[nodiscard]] std::string getRedoDescription() const {
- return canRedo() ? redoStack_.back()->getDescription() : "";
- }
-
- /**
- * @brief Check if there are unsaved changes
- * @return true if modified since last save
- */
- [[nodiscard]] bool isDirty() const {
- return dirty_;
- }
-
- /**
- * @brief Mark the current state as saved
- */
- void markSaved() {
- dirty_ = false;
- savedPosition_ = undoStack_.size();
- }
-
- /**
- * @brief Clear all history
- */
- void clear() {
- undoStack_.clear();
- redoStack_.clear();
- currentMemoryUsage_ = 0;
- dirty_ = false;
- savedPosition_ = 0;
- notifyHistoryChanged();
- }
-
- /**
- * @brief Begin a transaction
- * @param description Description of the transaction
- */
- void beginTransaction(const std::string& description) {
- if (inTransaction_) {
- return;
- }
-
- inTransaction_ = true;
- currentTransaction_ = makeUnique<MacroCommand>(description);
- }
-
- /**
- * @brief Commit the current transaction
- * @return true if committed successfully
- */
- bool commitTransaction() {
- if (!inTransaction_ || !currentTransaction_) {
- return false;
- }
-
- inTransaction_ = false;
-
- if (currentTransaction_->empty()) {
- currentTransaction_.reset();
- return true;
- }
-
- auto macro = std::move(currentTransaction_);
- pushToUndoStack(std::move(macro));
- notifyHistoryChanged();
-
- return true;
- }
-
- /**
- * @brief Rollback the current transaction
- */
- void rollbackTransaction() {
- if (!inTransaction_ || !currentTransaction_) {
- return;
- }
-
- inTransaction_ = false;
- currentTransaction_.reset();
- }
-
- /**
- * @brief Check if in a transaction
- * @return true if in transaction
- */
- [[nodiscard]] bool inTransaction() const {
- return inTransaction_;
- }
-
- /**
- * @brief Get the number of undo levels
- * @return Number of undoable commands
- */
- [[nodiscard]] usize getUndoCount() const {
- return undoStack_.size();
- }
-
- /**
- * @brief Get the number of redo levels
- * @return Number of redoable commands
- */
- [[nodiscard]] usize getRedoCount() const {
- return redoStack_.size();
- }
-
- /**
- * @brief Get current memory usage
- * @return Memory usage in bytes
- */
- [[nodiscard]] usize getMemoryUsage() const {
- return currentMemoryUsage_;
- }
-
- /**
- * @brief Set the event dispatcher for notifications
- * @param dispatcher The dispatcher to use
- */
- void setDispatcher(Dispatcher* dispatcher) {
- dispatcher_ = dispatcher;
- }
-
- /**
- * @brief Get the configuration
- * @return Configuration reference
- */
- [[nodiscard]] const CommandHistoryConfig& getConfig() const {
- return config_;
- }
-
- /**
- * @brief Update configuration
- * @param config New configuration
- */
- void setConfig(const CommandHistoryConfig& config) {
- config_ = config;
- enforceMemoryLimit();
- }
-
-private:
- friend class TransactionGuard;
-
- CommandResult executeImpl(Unique<Command> cmd, const CommandOptions& options) {
- if (!cmd || !cmd->isValid()) {
- return CommandResult::Failed;
- }
-
- cmd->setTimestamp(getCurrentTimeMs());
-
- CommandResult result = cmd->execute();
-
- if (result != CommandResult::Success) {
- return result;
- }
-
- dirty_ = true;
-
- if (!options.addToHistory) {
- return result;
- }
-
- if (inTransaction_ && currentTransaction_) {
- currentTransaction_->add(std::move(cmd), true); // Already executed
- return result;
- }
-
- if (config_.enableMerging && options.mergeWithPrevious && !undoStack_.empty()) {
- auto& lastCmd = undoStack_.back();
- if (lastCmd->canMergeWith(*cmd)) {
- lastCmd->mergeWith(*cmd);
- notifyHistoryChanged();
- return result;
- }
- }
-
- if (config_.enableMerging && !undoStack_.empty()) {
- auto& lastCmd = undoStack_.back();
- if (cmd->canMergeWith(*lastCmd)) {
- lastCmd->mergeWith(*cmd);
- notifyHistoryChanged();
- return result;
- }
- }
-
- redoStack_.clear();
- pushToUndoStack(std::move(cmd));
- notifyHistoryChanged();
-
- return result;
- }
-
- void pushToUndoStack(Unique<Command> cmd) {
- currentMemoryUsage_ += cmd->getMemoryUsage();
- undoStack_.push_back(std::move(cmd));
-
- enforceUndoLimit();
- enforceMemoryLimit();
- }
-
- void enforceUndoLimit() {
- while (undoStack_.size() > config_.maxUndoLevels) {
- currentMemoryUsage_ -= undoStack_.front()->getMemoryUsage();
- undoStack_.pop_front();
-
- if (savedPosition_ > 0) {
- savedPosition_--;
- }
- }
- }
-
- void enforceMemoryLimit() {
- while (currentMemoryUsage_ > config_.maxMemoryUsage && !undoStack_.empty()) {
- currentMemoryUsage_ -= undoStack_.front()->getMemoryUsage();
- undoStack_.pop_front();
-
- if (savedPosition_ > 0) {
- savedPosition_--;
- }
- }
- }
-
- void updateMemoryUsage() {
- currentMemoryUsage_ = 0;
- for (const auto& cmd : undoStack_) {
- currentMemoryUsage_ += cmd->getMemoryUsage();
- }
- for (const auto& cmd : redoStack_) {
- currentMemoryUsage_ += cmd->getMemoryUsage();
- }
- }
-
- void notifyHistoryChanged() {
- if (dispatcher_) {
- dispatcher_->trigger(HistoryChanged{
- canUndo(),
- canRedo(),
- getUndoDescription(),
- getRedoDescription()});
- }
- }
-
- static u64 getCurrentTimeMs() {
- auto now = std::chrono::steady_clock::now();
- auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- now.time_since_epoch());
- return static_cast<u64>(ms.count());
- }
-
- CommandHistoryConfig config_;
- std::deque<Unique<Command>> undoStack_;
- std::deque<Unique<Command>> redoStack_;
-
- usize currentMemoryUsage_ = 0;
- bool dirty_ = false;
- usize savedPosition_ = 0;
-
- bool inTransaction_ = false;
- Unique<MacroCommand> currentTransaction_;
-
- Dispatcher* dispatcher_ = nullptr;
-};
-
-// =============================================================================
-// TransactionGuard Implementation
-// =============================================================================
-
-inline TransactionGuard::TransactionGuard(CommandHistory& history,
- const std::string& description)
- : history_(history) {
- history_.beginTransaction(description);
-}
-
-inline TransactionGuard::~TransactionGuard() {
- if (!committed_ && !rolledBack_) {
- try {
- commit();
- } catch (...) {
- rollback();
- }
- }
-}
-
-inline void TransactionGuard::commit() {
- if (!committed_ && !rolledBack_) {
- history_.commitTransaction();
- committed_ = true;
- }
-}
-
-inline void TransactionGuard::rollback() {
- if (!committed_ && !rolledBack_) {
- history_.rollbackTransaction();
- rolledBack_ = true;
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/command/EditorCommands.hpp b/src/esengine/editor/command/EditorCommands.hpp
deleted file mode 100644
index fe1bef699..000000000
--- a/src/esengine/editor/command/EditorCommands.hpp
+++ /dev/null
@@ -1,435 +0,0 @@
-/**
- * @file EditorCommands.hpp
- * @brief Common editor command implementations
- * @details Provides ready-to-use commands for common editor operations
- * like creating entities, modifying transforms, etc.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Command.hpp"
-#include "PropertyCommand.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../ecs/Component.hpp"
-
-#include <glm/glm.hpp>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Entity Commands
-// =============================================================================
-
-/**
- * @brief Command to create a new entity
- */
-class CreateEntityCommand : public Command {
-public:
- explicit CreateEntityCommand(ecs::Registry& registry, std::string name = "Entity")
- : registry_(registry), name_(std::move(name)) {}
-
- CommandResult execute() override {
- entity_ = registry_.create();
- registry_.emplace<ecs::Name>(entity_, name_);
- registry_.emplace<ecs::Transform>(entity_);
- return CommandResult::Success;
- }
-
- void undo() override {
- if (entity_ != INVALID_ENTITY) {
- registry_.destroy(entity_);
- }
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Create Entity \"" + name_ + "\"";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "CreateEntityCommand";
- }
-
- [[nodiscard]] Entity getCreatedEntity() const {
- return entity_;
- }
-
-private:
- ecs::Registry& registry_;
- std::string name_;
- Entity entity_ = INVALID_ENTITY;
-};
-
-/**
- * @brief Command to delete an entity
- */
-class DeleteEntityCommand : public Command {
-public:
- DeleteEntityCommand(ecs::Registry& registry, Entity entity)
- : registry_(registry), entity_(entity) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_)) {
- return CommandResult::Failed;
- }
-
- if (registry_.has<ecs::Name>(entity_)) {
- savedName_ = registry_.get<ecs::Name>(entity_).name;
- }
-
- if (registry_.has<ecs::Transform>(entity_)) {
- savedTransform_ = registry_.get<ecs::Transform>(entity_);
- hasTransform_ = true;
- }
-
- registry_.destroy(entity_);
- return CommandResult::Success;
- }
-
- void undo() override {
- entity_ = registry_.create(entity_);
-
- if (!savedName_.empty()) {
- registry_.emplace<ecs::Name>(entity_, savedName_);
- }
-
- if (hasTransform_) {
- registry_.emplace<ecs::Transform>(entity_, savedTransform_);
- }
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Delete Entity";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "DeleteEntityCommand";
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- std::string savedName_;
- ecs::Transform savedTransform_;
- bool hasTransform_ = false;
-};
-
-/**
- * @brief Command to rename an entity
- */
-class RenameEntityCommand : public Command {
-public:
- RenameEntityCommand(ecs::Registry& registry, Entity entity, std::string newName)
- : registry_(registry)
- , entity_(entity)
- , newName_(std::move(newName)) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_) || !registry_.has<ecs::Name>(entity_)) {
- return CommandResult::Failed;
- }
-
- auto& name = registry_.get<ecs::Name>(entity_);
- oldName_ = name.name;
- name.name = newName_;
-
- return CommandResult::Success;
- }
-
- void undo() override {
- if (registry_.valid(entity_) && registry_.has<ecs::Name>(entity_)) {
- registry_.get<ecs::Name>(entity_).name = oldName_;
- }
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- auto* cmd = dynamic_cast<const RenameEntityCommand*>(&other);
- if (!cmd || cmd->entity_ != entity_) {
- return false;
- }
-
- u64 timeDiff = other.getTimestamp() > getTimestamp()
- ? other.getTimestamp() - getTimestamp()
- : getTimestamp() - other.getTimestamp();
-
- return timeDiff <= getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto& cmd = static_cast<RenameEntityCommand&>(other);
- newName_ = std::move(cmd.newName_);
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Rename Entity to \"" + newName_ + "\"";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "RenameEntityCommand";
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- std::string oldName_;
- std::string newName_;
-};
-
-// =============================================================================
-// Transform Commands
-// =============================================================================
-
-/**
- * @brief Command to modify entity position
- */
-class SetPositionCommand : public Command {
-public:
- SetPositionCommand(ecs::Registry& registry, Entity entity, const glm::vec3& position)
- : registry_(registry)
- , entity_(entity)
- , newPosition_(position) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_) || !registry_.has<ecs::Transform>(entity_)) {
- return CommandResult::Failed;
- }
-
- auto& transform = registry_.get<ecs::Transform>(entity_);
- oldPosition_ = transform.position;
- transform.position = newPosition_;
-
- return CommandResult::Success;
- }
-
- void undo() override {
- if (registry_.valid(entity_) && registry_.has<ecs::Transform>(entity_)) {
- registry_.get<ecs::Transform>(entity_).position = oldPosition_;
- }
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- auto* cmd = dynamic_cast<const SetPositionCommand*>(&other);
- if (!cmd || cmd->entity_ != entity_) {
- return false;
- }
-
- u64 timeDiff = other.getTimestamp() > getTimestamp()
- ? other.getTimestamp() - getTimestamp()
- : getTimestamp() - other.getTimestamp();
-
- return timeDiff <= getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto& cmd = static_cast<SetPositionCommand&>(other);
- newPosition_ = cmd.newPosition_;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Set Position";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "SetPositionCommand";
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- glm::vec3 oldPosition_{0.0f};
- glm::vec3 newPosition_;
-};
-
-/**
- * @brief Command to modify entity rotation
- */
-class SetRotationCommand : public Command {
-public:
- SetRotationCommand(ecs::Registry& registry, Entity entity, const glm::vec3& rotation)
- : registry_(registry)
- , entity_(entity)
- , newRotation_(rotation) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_) || !registry_.has<ecs::Transform>(entity_)) {
- return CommandResult::Failed;
- }
-
- auto& transform = registry_.get<ecs::Transform>(entity_);
- oldRotation_ = transform.rotation;
- transform.rotation = newRotation_;
-
- return CommandResult::Success;
- }
-
- void undo() override {
- if (registry_.valid(entity_) && registry_.has<ecs::Transform>(entity_)) {
- registry_.get<ecs::Transform>(entity_).rotation = oldRotation_;
- }
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- auto* cmd = dynamic_cast<const SetRotationCommand*>(&other);
- if (!cmd || cmd->entity_ != entity_) {
- return false;
- }
-
- u64 timeDiff = other.getTimestamp() > getTimestamp()
- ? other.getTimestamp() - getTimestamp()
- : getTimestamp() - other.getTimestamp();
-
- return timeDiff <= getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto& cmd = static_cast<SetRotationCommand&>(other);
- newRotation_ = cmd.newRotation_;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Set Rotation";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "SetRotationCommand";
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- glm::vec3 oldRotation_{0.0f};
- glm::vec3 newRotation_;
-};
-
-/**
- * @brief Command to modify entity scale
- */
-class SetScaleCommand : public Command {
-public:
- SetScaleCommand(ecs::Registry& registry, Entity entity, const glm::vec3& scale)
- : registry_(registry)
- , entity_(entity)
- , newScale_(scale) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_) || !registry_.has<ecs::Transform>(entity_)) {
- return CommandResult::Failed;
- }
-
- auto& transform = registry_.get<ecs::Transform>(entity_);
- oldScale_ = transform.scale;
- transform.scale = newScale_;
-
- return CommandResult::Success;
- }
-
- void undo() override {
- if (registry_.valid(entity_) && registry_.has<ecs::Transform>(entity_)) {
- registry_.get<ecs::Transform>(entity_).scale = oldScale_;
- }
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- auto* cmd = dynamic_cast<const SetScaleCommand*>(&other);
- if (!cmd || cmd->entity_ != entity_) {
- return false;
- }
-
- u64 timeDiff = other.getTimestamp() > getTimestamp()
- ? other.getTimestamp() - getTimestamp()
- : getTimestamp() - other.getTimestamp();
-
- return timeDiff <= getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto& cmd = static_cast<SetScaleCommand&>(other);
- newScale_ = cmd.newScale_;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Set Scale";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "SetScaleCommand";
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- glm::vec3 oldScale_{1.0f};
- glm::vec3 newScale_;
-};
-
-/**
- * @brief Command to modify entire transform
- */
-class SetTransformCommand : public Command {
-public:
- SetTransformCommand(ecs::Registry& registry, Entity entity,
- const ecs::Transform& transform)
- : registry_(registry)
- , entity_(entity)
- , newTransform_(transform) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_) || !registry_.has<ecs::Transform>(entity_)) {
- return CommandResult::Failed;
- }
-
- oldTransform_ = registry_.get<ecs::Transform>(entity_);
- registry_.get<ecs::Transform>(entity_) = newTransform_;
-
- return CommandResult::Success;
- }
-
- void undo() override {
- if (registry_.valid(entity_) && registry_.has<ecs::Transform>(entity_)) {
- registry_.get<ecs::Transform>(entity_) = oldTransform_;
- }
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- auto* cmd = dynamic_cast<const SetTransformCommand*>(&other);
- if (!cmd || cmd->entity_ != entity_) {
- return false;
- }
-
- u64 timeDiff = other.getTimestamp() > getTimestamp()
- ? other.getTimestamp() - getTimestamp()
- : getTimestamp() - other.getTimestamp();
-
- return timeDiff <= getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto& cmd = static_cast<SetTransformCommand&>(other);
- newTransform_ = cmd.newTransform_;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Set Transform";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "SetTransformCommand";
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- ecs::Transform oldTransform_;
- ecs::Transform newTransform_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/command/MacroCommand.hpp b/src/esengine/editor/command/MacroCommand.hpp
deleted file mode 100644
index 895758a11..000000000
--- a/src/esengine/editor/command/MacroCommand.hpp
+++ /dev/null
@@ -1,203 +0,0 @@
-/**
- * @file MacroCommand.hpp
- * @brief Composite command for grouping multiple commands
- * @details Allows multiple commands to be executed as a single undoable
- * unit. Useful for complex operations that involve multiple
- * discrete steps.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Command.hpp"
-
-#include <vector>
-
-namespace esengine::editor {
-
-// =============================================================================
-// MacroCommand Class
-// =============================================================================
-
-/**
- * @brief Groups multiple commands into a single undoable operation
- *
- * @details MacroCommand executes its child commands in order and
- * undoes them in reverse order. If any command fails during
- * execution, all previously executed commands are rolled back.
- *
- * @code
- * auto macro = makeUnique<MacroCommand>("Batch Delete");
- * for (Entity e : selection) {
- * macro->add(makeUnique<DeleteEntityCommand>(e));
- * }
- * history.execute(std::move(macro));
- * @endcode
- */
-class MacroCommand : public Command {
-public:
- /**
- * @brief Construct a macro command
- * @param description Description of the combined operation
- */
- explicit MacroCommand(std::string description)
- : description_(std::move(description)) {}
-
- /**
- * @brief Add a command to the macro
- * @param command Command to add
- * @param alreadyExecuted If true, the command was already executed
- */
- void add(Unique<Command> command, bool alreadyExecuted = false) {
- commands_.push_back(std::move(command));
- if (alreadyExecuted) {
- executedCount_ = commands_.size();
- }
- }
-
- /**
- * @brief Mark all commands as executed
- * @details Used when commands were executed individually before being
- * added to the macro (e.g., during transactions).
- */
- void markAllExecuted() {
- executedCount_ = commands_.size();
- }
-
- /**
- * @brief Get the number of commands in the macro
- * @return Number of commands
- */
- [[nodiscard]] usize size() const {
- return commands_.size();
- }
-
- /**
- * @brief Check if the macro is empty
- * @return true if no commands
- */
- [[nodiscard]] bool empty() const {
- return commands_.empty();
- }
-
- /**
- * @brief Execute all commands in order
- * @return Success if all commands succeeded
- */
- CommandResult execute() override {
- if (commands_.empty()) {
- return CommandResult::NoOp;
- }
-
- executedCount_ = 0;
-
- for (auto& cmd : commands_) {
- CommandResult result = cmd->execute();
-
- if (result == CommandResult::Failed) {
- rollback();
- return CommandResult::Failed;
- }
-
- if (result == CommandResult::Cancelled) {
- rollback();
- return CommandResult::Cancelled;
- }
-
- if (result == CommandResult::Success) {
- executedCount_++;
- }
- }
-
- return executedCount_ > 0 ? CommandResult::Success : CommandResult::NoOp;
- }
-
- /**
- * @brief Undo all commands in reverse order
- */
- void undo() override {
- for (auto it = commands_.rbegin();
- it != commands_.rbegin() + static_cast<std::ptrdiff_t>(executedCount_);
- ++it) {
- (*it)->undo();
- }
- }
-
- /**
- * @brief Redo all commands in order
- * @return Success if all commands succeeded
- */
- CommandResult redo() override {
- if (commands_.empty()) {
- return CommandResult::NoOp;
- }
-
- executedCount_ = 0;
-
- for (usize i = 0; i < commands_.size(); ++i) {
- CommandResult result = commands_[i]->redo();
-
- if (result == CommandResult::Failed || result == CommandResult::Cancelled) {
- rollback();
- return result;
- }
-
- if (result == CommandResult::Success) {
- executedCount_++;
- }
- }
-
- return executedCount_ > 0 ? CommandResult::Success : CommandResult::NoOp;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return description_;
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "MacroCommand";
- }
-
- [[nodiscard]] bool isValid() const override {
- for (const auto& cmd : commands_) {
- if (!cmd->isValid()) {
- return false;
- }
- }
- return true;
- }
-
- [[nodiscard]] usize getMemoryUsage() const override {
- usize usage = sizeof(*this);
- for (const auto& cmd : commands_) {
- usage += cmd->getMemoryUsage();
- }
- return usage;
- }
-
-private:
- /**
- * @brief Rollback executed commands on failure
- */
- void rollback() {
- for (usize i = executedCount_; i > 0; --i) {
- commands_[i - 1]->undo();
- }
- executedCount_ = 0;
- }
-
- std::string description_;
- std::vector<Unique<Command>> commands_;
- usize executedCount_ = 0;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/command/PropertyCommand.hpp b/src/esengine/editor/command/PropertyCommand.hpp
deleted file mode 100644
index 9ae41bf9a..000000000
--- a/src/esengine/editor/command/PropertyCommand.hpp
+++ /dev/null
@@ -1,319 +0,0 @@
-/**
- * @file PropertyCommand.hpp
- * @brief Template for mergeable property modification commands
- * @details Provides a base class for commands that modify a single
- * property value. Supports automatic merging of consecutive
- * changes to the same property.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Command.hpp"
-
-#include <type_traits>
-
-namespace esengine::editor {
-
-// =============================================================================
-// PropertyCommand Template
-// =============================================================================
-
-/**
- * @brief Base class for commands that modify a single property
- *
- * @tparam T The property value type
- *
- * @details PropertyCommand provides automatic support for merging
- * consecutive changes to the same target. Subclasses need only
- * implement getPropertyRef() and isSameTarget().
- *
- * @code
- * class TransformPositionCommand : public PropertyCommand<glm::vec3> {
- * public:
- * TransformPositionCommand(Registry& reg, Entity e, const glm::vec3& pos)
- * : PropertyCommand(pos), registry_(reg), entity_(e) {}
- *
- * protected:
- * glm::vec3& getPropertyRef() override {
- * return registry_.get<Transform>(entity_).position;
- * }
- *
- * bool isSameTarget(const Command& other) const override {
- * auto* cmd = dynamic_cast<const TransformPositionCommand*>(&other);
- * return cmd && cmd->entity_ == entity_;
- * }
- *
- * std::string getTargetDescription() const override {
- * return "Entity " + std::to_string(entity_);
- * }
- *
- * private:
- * Registry& registry_;
- * Entity entity_;
- * };
- * @endcode
- */
-template<typename T>
-class PropertyCommand : public Command {
-public:
- /**
- * @brief Construct with new value
- * @param newValue The value to set
- */
- explicit PropertyCommand(T newValue)
- : newValue_(std::move(newValue)) {}
-
- /**
- * @brief Construct with explicit old and new values
- * @param oldValue The original value (for undo)
- * @param newValue The value to set
- */
- PropertyCommand(T oldValue, T newValue)
- : oldValue_(std::move(oldValue))
- , newValue_(std::move(newValue))
- , hasOldValue_(true) {}
-
- CommandResult execute() override {
- if (!hasOldValue_) {
- oldValue_ = getPropertyRef();
- hasOldValue_ = true;
- }
-
- if (oldValue_ == newValue_) {
- return CommandResult::NoOp;
- }
-
- getPropertyRef() = newValue_;
- return CommandResult::Success;
- }
-
- void undo() override {
- getPropertyRef() = oldValue_;
- }
-
- CommandResult redo() override {
- getPropertyRef() = newValue_;
- return CommandResult::Success;
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- if (getTypeName() != other.getTypeName()) {
- return false;
- }
-
- if (!isSameTarget(other)) {
- return false;
- }
-
- u64 timeDiff = other.getTimestamp() > getTimestamp()
- ? other.getTimestamp() - getTimestamp()
- : getTimestamp() - other.getTimestamp();
-
- return timeDiff <= getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto& otherProp = static_cast<PropertyCommand<T>&>(other);
- newValue_ = std::move(otherProp.newValue_);
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Modify " + getPropertyName() + " on " + getTargetDescription();
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "PropertyCommand";
- }
-
- [[nodiscard]] usize getMemoryUsage() const override {
- return sizeof(*this);
- }
-
- /**
- * @brief Get the old value
- * @return The original value before modification
- */
- [[nodiscard]] const T& getOldValue() const {
- return oldValue_;
- }
-
- /**
- * @brief Get the new value
- * @return The value that was/will be set
- */
- [[nodiscard]] const T& getNewValue() const {
- return newValue_;
- }
-
-protected:
- /**
- * @brief Get a reference to the property being modified
- * @return Reference to the property
- */
- virtual T& getPropertyRef() = 0;
-
- /**
- * @brief Check if another command targets the same property
- * @param other The other command
- * @return true if same target
- */
- [[nodiscard]] virtual bool isSameTarget(const Command& other) const = 0;
-
- /**
- * @brief Get the property name for the description
- * @return Property name string
- */
- [[nodiscard]] virtual std::string getPropertyName() const {
- return "property";
- }
-
- /**
- * @brief Get a description of the target
- * @return Target description string
- */
- [[nodiscard]] virtual std::string getTargetDescription() const {
- return "target";
- }
-
- T oldValue_{};
- T newValue_;
- bool hasOldValue_ = false;
-};
-
-// =============================================================================
-// Simple Value Command
-// =============================================================================
-
-/**
- * @brief Simple command for setting a value through a pointer
- *
- * @tparam T The value type
- *
- * @code
- * int myValue = 10;
- * auto cmd = makeUnique<SimpleValueCommand<int>>(&myValue, 20);
- * history.execute(std::move(cmd)); // myValue is now 20
- * history.undo(); // myValue is back to 10
- * @endcode
- */
-template<typename T>
-class SimpleValueCommand : public Command {
-public:
- SimpleValueCommand(T* target, T newValue, std::string description = "Set Value")
- : target_(target)
- , oldValue_(*target)
- , newValue_(std::move(newValue))
- , description_(std::move(description)) {}
-
- CommandResult execute() override {
- if (oldValue_ == newValue_) {
- return CommandResult::NoOp;
- }
- *target_ = newValue_;
- return CommandResult::Success;
- }
-
- void undo() override {
- *target_ = oldValue_;
- }
-
- CommandResult redo() override {
- *target_ = newValue_;
- return CommandResult::Success;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return description_;
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "SimpleValueCommand";
- }
-
- [[nodiscard]] bool isValid() const override {
- return target_ != nullptr;
- }
-
-private:
- T* target_;
- T oldValue_;
- T newValue_;
- std::string description_;
-};
-
-// =============================================================================
-// Lambda Command
-// =============================================================================
-
-/**
- * @brief Command that uses lambdas for execute and undo
- *
- * @details Convenient for one-off commands where creating a full
- * subclass would be overkill.
- *
- * @code
- * auto cmd = makeUnique<LambdaCommand>(
- * "Toggle Flag",
- * [&flag]() { flag = !flag; return CommandResult::Success; },
- * [&flag]() { flag = !flag; }
- * );
- * @endcode
- */
-class LambdaCommand : public Command {
-public:
- using ExecuteFunc = std::function<CommandResult()>;
- using UndoFunc = std::function<void()>;
-
- LambdaCommand(std::string description, ExecuteFunc execute, UndoFunc undo)
- : description_(std::move(description))
- , executeFunc_(std::move(execute))
- , undoFunc_(std::move(undo))
- , redoFunc_(executeFunc_) {}
-
- LambdaCommand(std::string description, ExecuteFunc execute, UndoFunc undo,
- ExecuteFunc redo)
- : description_(std::move(description))
- , executeFunc_(std::move(execute))
- , undoFunc_(std::move(undo))
- , redoFunc_(std::move(redo)) {}
-
- CommandResult execute() override {
- return executeFunc_ ? executeFunc_() : CommandResult::Failed;
- }
-
- void undo() override {
- if (undoFunc_) {
- undoFunc_();
- }
- }
-
- CommandResult redo() override {
- return redoFunc_ ? redoFunc_() : CommandResult::Failed;
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return description_;
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "LambdaCommand";
- }
-
-private:
- std::string description_;
- ExecuteFunc executeFunc_;
- UndoFunc undoFunc_;
- ExecuteFunc redoFunc_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/command/TransformCommand.hpp b/src/esengine/editor/command/TransformCommand.hpp
deleted file mode 100644
index b237729a7..000000000
--- a/src/esengine/editor/command/TransformCommand.hpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * @file TransformCommand.hpp
- * @brief Command for entity transform modifications
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Command.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../ecs/components/Transform.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// TransformCommand Class
-// =============================================================================
-
-/**
- * @brief Command for modifying entity transforms
- *
- * @details Stores the old and new transform values to support undo/redo.
- */
-class TransformCommand : public Command {
-public:
- TransformCommand(ecs::Registry& registry, Entity entity,
- const ecs::LocalTransform& oldTransform,
- const ecs::LocalTransform& newTransform)
- : registry_(registry),
- entity_(entity),
- oldTransform_(oldTransform),
- newTransform_(newTransform) {}
-
- CommandResult execute() override {
- if (!registry_.valid(entity_) || !registry_.has<ecs::LocalTransform>(entity_)) {
- return CommandResult::Failed;
- }
-
- registry_.get<ecs::LocalTransform>(entity_) = newTransform_;
- return CommandResult::Success;
- }
-
- void undo() override {
- if (registry_.valid(entity_) && registry_.has<ecs::LocalTransform>(entity_)) {
- registry_.get<ecs::LocalTransform>(entity_) = oldTransform_;
- }
- }
-
- [[nodiscard]] std::string getDescription() const override {
- return "Transform Entity";
- }
-
- [[nodiscard]] std::string getTypeName() const override {
- return "TransformCommand";
- }
-
- [[nodiscard]] bool canMergeWith(const Command& other) const override {
- auto* otherCmd = dynamic_cast<const TransformCommand*>(&other);
- if (!otherCmd) return false;
-
- if (entity_ != otherCmd->entity_) return false;
-
- u64 timeDiff = otherCmd->getTimestamp() > getTimestamp()
- ? otherCmd->getTimestamp() - getTimestamp()
- : getTimestamp() - otherCmd->getTimestamp();
-
- return timeDiff < getMergeWindowMs();
- }
-
- void mergeWith(Command& other) override {
- auto* otherCmd = dynamic_cast<TransformCommand*>(&other);
- if (otherCmd) {
- newTransform_ = otherCmd->newTransform_;
- }
- }
-
- [[nodiscard]] u32 getMergeWindowMs() const override {
- return 300;
- }
-
-private:
- ecs::Registry& registry_;
- Entity entity_;
- ecs::LocalTransform oldTransform_;
- ecs::LocalTransform newTransform_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/core/EditorEvents.hpp b/src/esengine/editor/core/EditorEvents.hpp
deleted file mode 100644
index 9ab47cd91..000000000
--- a/src/esengine/editor/core/EditorEvents.hpp
+++ /dev/null
@@ -1,342 +0,0 @@
-/**
- * @file EditorEvents.hpp
- * @brief Editor event definitions
- * @details Defines all event types used by the editor for communication
- * between components. Events are pure data structures that carry
- * information about state changes.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Selection Events
-// =============================================================================
-
-/**
- * @brief Fired when an entity is selected
- */
-struct EntitySelected {
- Entity entity;
- bool additive;
-};
-
-/**
- * @brief Fired when selection is cleared
- */
-struct SelectionCleared {};
-
-/**
- * @brief Fired when selection changes
- */
-struct SelectionChanged {
- std::vector<Entity> previousSelection;
- std::vector<Entity> currentSelection;
-};
-
-// =============================================================================
-// Entity Lifecycle Events
-// =============================================================================
-
-/**
- * @brief Fired when a new entity is created
- */
-struct EntityCreated {
- Entity entity;
- std::string name;
-};
-
-/**
- * @brief Fired when an entity is about to be deleted
- */
-struct EntityDeleting {
- Entity entity;
-};
-
-/**
- * @brief Fired after an entity is deleted
- */
-struct EntityDeleted {
- Entity entity;
-};
-
-/**
- * @brief Fired when an entity is renamed
- */
-struct EntityRenamed {
- Entity entity;
- std::string oldName;
- std::string newName;
-};
-
-/**
- * @brief Fired when entity hierarchy changes
- */
-struct EntityHierarchyChanged {
- Entity entity;
- Entity oldParent;
- Entity newParent;
-};
-
-// =============================================================================
-// Component Events
-// =============================================================================
-
-/**
- * @brief Fired when a component is added to an entity
- */
-struct ComponentAdded {
- Entity entity;
- TypeId componentType;
-};
-
-/**
- * @brief Fired when a component is removed from an entity
- */
-struct ComponentRemoved {
- Entity entity;
- TypeId componentType;
-};
-
-/**
- * @brief Fired when a component is modified
- */
-struct ComponentModified {
- Entity entity;
- TypeId componentType;
- std::string propertyName;
-};
-
-// =============================================================================
-// Scene Events
-// =============================================================================
-
-/**
- * @brief Fired when a new scene is created
- */
-struct SceneCreated {
- std::string name;
-};
-
-/**
- * @brief Fired when a scene is about to be loaded
- */
-struct SceneLoading {
- std::string path;
-};
-
-/**
- * @brief Fired when a scene has finished loading
- */
-struct SceneLoaded {
- std::string path;
- bool success;
-};
-
-/**
- * @brief Fired when a scene is about to be saved
- */
-struct SceneSaving {
- std::string path;
-};
-
-/**
- * @brief Fired when a scene has been saved
- */
-struct SceneSaved {
- std::string path;
- bool success;
-};
-
-/**
- * @brief Fired when the scene is marked as modified
- */
-struct SceneModified {};
-
-// =============================================================================
-// Editor State Events
-// =============================================================================
-
-/**
- * @brief Editor play mode states
- */
-enum class PlayMode : u8 {
- Edit,
- Play,
- Pause
-};
-
-/**
- * @brief Fired when play mode changes
- */
-struct PlayModeChanged {
- PlayMode previousMode;
- PlayMode currentMode;
-};
-
-/**
- * @brief Fired when undo/redo occurs
- */
-struct UndoRedoEvent {
- bool isUndo;
- std::string commandDescription;
-};
-
-/**
- * @brief Fired when undo/redo history changes
- */
-struct HistoryChanged {
- bool canUndo;
- bool canRedo;
- std::string undoDescription;
- std::string redoDescription;
-};
-
-// =============================================================================
-// Project Events
-// =============================================================================
-
-/**
- * @brief Fired when a project is opened
- */
-struct ProjectOpened {
- std::string path;
- std::string name;
-};
-
-/**
- * @brief Fired when a project is closed
- */
-struct ProjectClosed {};
-
-/**
- * @brief Fired when project settings change
- */
-struct ProjectSettingsChanged {};
-
-// =============================================================================
-// Asset Events
-// =============================================================================
-
-/**
- * @brief Fired when an asset is imported
- */
-struct AssetImported {
- std::string path;
- std::string type;
-};
-
-/**
- * @brief Fired when an asset is deleted
- */
-struct AssetDeleted {
- std::string path;
-};
-
-/**
- * @brief Fired when an asset is renamed
- */
-struct AssetRenamed {
- std::string oldPath;
- std::string newPath;
-};
-
-/**
- * @brief Fired when an asset is selected in the browser
- */
-struct AssetSelected {
- std::string path;
-};
-
-// =============================================================================
-// UI Events
-// =============================================================================
-
-/**
- * @brief Fired when a panel gains focus
- */
-struct PanelFocused {
- std::string panelId;
-};
-
-/**
- * @brief Fired when a panel is opened
- */
-struct PanelOpened {
- std::string panelId;
-};
-
-/**
- * @brief Fired when a panel is closed
- */
-struct PanelClosed {
- std::string panelId;
-};
-
-/**
- * @brief Fired when the layout changes
- */
-struct LayoutChanged {};
-
-/**
- * @brief Fired when theme changes
- */
-struct ThemeChanged {
- std::string themeName;
-};
-
-// =============================================================================
-// Tool Events
-// =============================================================================
-
-/**
- * @brief Editor tool types
- */
-enum class EditorTool : u8 {
- Select,
- Move,
- Rotate,
- Scale,
- Rect
-};
-
-/**
- * @brief Fired when the active tool changes
- */
-struct ToolChanged {
- EditorTool previousTool;
- EditorTool currentTool;
-};
-
-/**
- * @brief Fired when gizmo mode changes
- */
-struct GizmoModeChanged {
- bool isLocal;
-};
-
-/**
- * @brief Fired when snap settings change
- */
-struct SnapSettingsChanged {
- bool snapEnabled;
- float snapValue;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/core/Selection.hpp b/src/esengine/editor/core/Selection.hpp
deleted file mode 100644
index 4e6aadf9a..000000000
--- a/src/esengine/editor/core/Selection.hpp
+++ /dev/null
@@ -1,589 +0,0 @@
-/**
- * @file Selection.hpp
- * @brief Multi-type selection management system
- * @details Provides a unified selection system that can handle different
- * types of selectable objects (entities, assets, etc.) with
- * type-safe queries and change notifications.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "EditorEvents.hpp"
-#include "../../core/Types.hpp"
-#include "../../events/Dispatcher.hpp"
-
-#include <algorithm>
-#include <any>
-#include <functional>
-#include <optional>
-#include <set>
-#include <typeindex>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Type Definitions
-// =============================================================================
-
-/**
- * @brief Type-erased identifier for selectable objects
- *
- * @details SelectableId uniquely identifies any selectable object by
- * combining its type with a raw ID value.
- */
-struct SelectableId {
- std::type_index typeId;
- u64 rawId;
-
- SelectableId() : typeId(typeid(void)), rawId(0) {}
-
- template<typename T>
- static SelectableId from(const T& value) {
- SelectableId id;
- id.typeId = std::type_index(typeid(T));
-
- if constexpr (std::is_integral_v<T>) {
- id.rawId = static_cast<u64>(value);
- } else if constexpr (std::is_pointer_v<T>) {
- // Use uintptr_t as intermediate type for safer pointer-to-integer conversion
- id.rawId = static_cast<u64>(reinterpret_cast<uintptr_t>(value));
- } else {
- id.rawId = std::hash<T>{}(value);
- }
-
- return id;
- }
-
- bool operator==(const SelectableId& other) const {
- return typeId == other.typeId && rawId == other.rawId;
- }
-
- bool operator!=(const SelectableId& other) const {
- return !(*this == other);
- }
-
- bool operator<(const SelectableId& other) const {
- if (typeId != other.typeId) {
- return typeId < other.typeId;
- }
- return rawId < other.rawId;
- }
-};
-
-/**
- * @brief Selection change event type
- */
-enum class SelectionChangeType : u8 {
- Cleared,
- Added,
- Removed,
- Replaced
-};
-
-/**
- * @brief Selection change event data
- */
-struct SelectionChangedEvent {
- SelectionChangeType type;
- std::vector<SelectableId> added;
- std::vector<SelectableId> removed;
-};
-
-} // namespace esengine::editor
-
-// Hash specialization for SelectableId
-template<>
-struct std::hash<esengine::editor::SelectableId> {
- std::size_t operator()(const esengine::editor::SelectableId& id) const noexcept {
- auto h1 = std::hash<std::type_index>{}(id.typeId);
- auto h2 = std::hash<esengine::u64>{}(id.rawId);
- return h1 ^ (h2 << 1);
- }
-};
-
-namespace esengine::editor {
-
-// =============================================================================
-// Selection Class
-// =============================================================================
-
-/**
- * @brief Multi-type selection manager
- *
- * @details Selection manages selected objects of any type. It provides
- * type-safe queries and supports multiple selection with
- * additive/toggle modes.
- *
- * @code
- * Selection selection;
- *
- * // Select entities
- * selection.select(entity1);
- * selection.addToSelection(entity2);
- *
- * // Query by type
- * auto entities = selection.getSelected<Entity>();
- *
- * // Listen for changes
- * selection.addListener([](const SelectionChangedEvent& e) {
- * // Handle selection change
- * });
- * @endcode
- */
-class Selection {
-public:
- using SelectionChangedCallback = std::function<void(const SelectionChangedEvent&)>;
-
- Selection() = default;
- ~Selection() = default;
-
- Selection(Selection&&) = default;
- Selection& operator=(Selection&&) = default;
-
- Selection(const Selection&) = delete;
- Selection& operator=(const Selection&) = delete;
-
- /**
- * @brief Select a single item (clears previous selection)
- * @tparam T Item type
- * @param item The item to select
- */
- template<typename T>
- void select(const T& item) {
- std::vector<SelectableId> oldSelection(selected_.begin(), selected_.end());
-
- selected_.clear();
- itemsByType_.clear();
-
- SelectableId id = SelectableId::from(item);
- selected_.insert(id);
- itemsByType_[std::type_index(typeid(T))].push_back(std::any(item));
-
- notifyChange(SelectionChangeType::Replaced, {id}, oldSelection);
- }
-
- /**
- * @brief Add an item to the current selection
- * @tparam T Item type
- * @param item The item to add
- */
- template<typename T>
- void addToSelection(const T& item) {
- SelectableId id = SelectableId::from(item);
-
- if (selected_.count(id) > 0) {
- return;
- }
-
- selected_.insert(id);
- itemsByType_[std::type_index(typeid(T))].push_back(std::any(item));
-
- notifyChange(SelectionChangeType::Added, {id}, {});
- }
-
- /**
- * @brief Remove an item from the selection
- * @tparam T Item type
- * @param item The item to remove
- */
- template<typename T>
- void removeFromSelection(const T& item) {
- SelectableId id = SelectableId::from(item);
-
- if (selected_.count(id) == 0) {
- return;
- }
-
- selected_.erase(id);
-
- auto typeId = std::type_index(typeid(T));
- auto& items = itemsByType_[typeId];
- items.erase(std::remove_if(items.begin(), items.end(),
- [&item](const std::any& a) {
- return std::any_cast<T>(a) == item;
- }),
- items.end());
-
- if (items.empty()) {
- itemsByType_.erase(typeId);
- }
-
- notifyChange(SelectionChangeType::Removed, {}, {id});
- }
-
- /**
- * @brief Toggle an item's selection state
- * @tparam T Item type
- * @param item The item to toggle
- */
- template<typename T>
- void toggleSelection(const T& item) {
- SelectableId id = SelectableId::from(item);
-
- if (selected_.count(id) > 0) {
- removeFromSelection(item);
- } else {
- addToSelection(item);
- }
- }
-
- /**
- * @brief Check if an item is selected
- * @tparam T Item type
- * @param item The item to check
- * @return true if selected
- */
- template<typename T>
- [[nodiscard]] bool isSelected(const T& item) const {
- return selected_.count(SelectableId::from(item)) > 0;
- }
-
- /**
- * @brief Clear all selection
- */
- void clear() {
- if (selected_.empty()) {
- return;
- }
-
- std::vector<SelectableId> oldSelection(selected_.begin(), selected_.end());
- selected_.clear();
- itemsByType_.clear();
-
- notifyChange(SelectionChangeType::Cleared, {}, oldSelection);
- }
-
- /**
- * @brief Get all selected items of a specific type
- * @tparam T Item type
- * @return Vector of selected items
- */
- template<typename T>
- [[nodiscard]] std::vector<T> getSelected() const {
- std::vector<T> result;
-
- auto it = itemsByType_.find(std::type_index(typeid(T)));
- if (it == itemsByType_.end()) {
- return result;
- }
-
- result.reserve(it->second.size());
- for (const auto& item : it->second) {
- result.push_back(std::any_cast<T>(item));
- }
-
- return result;
- }
-
- /**
- * @brief Get the first selected item of a specific type
- * @tparam T Item type
- * @return Optional containing the first item or empty
- */
- template<typename T>
- [[nodiscard]] std::optional<T> getFirstSelected() const {
- auto items = getSelected<T>();
- if (items.empty()) {
- return std::nullopt;
- }
- return items.front();
- }
-
- /**
- * @brief Check if there are selected items of a specific type
- * @tparam T Item type
- * @return true if there are selected items of type T
- */
- template<typename T>
- [[nodiscard]] bool hasSelected() const {
- auto it = itemsByType_.find(std::type_index(typeid(T)));
- return it != itemsByType_.end() && !it->second.empty();
- }
-
- /**
- * @brief Get the total count of selected items
- * @return Number of selected items
- */
- [[nodiscard]] usize count() const {
- return selected_.size();
- }
-
- /**
- * @brief Get the count of selected items of a specific type
- * @tparam T Item type
- * @return Number of selected items of type T
- */
- template<typename T>
- [[nodiscard]] usize count() const {
- auto it = itemsByType_.find(std::type_index(typeid(T)));
- if (it == itemsByType_.end()) {
- return 0;
- }
- return it->second.size();
- }
-
- /**
- * @brief Check if selection is empty
- * @return true if no items selected
- */
- [[nodiscard]] bool empty() const {
- return selected_.empty();
- }
-
- /**
- * @brief Add a selection change listener
- * @param callback The callback to invoke on changes
- * @return Listener ID for removal
- */
- u32 addListener(SelectionChangedCallback callback) {
- u32 id = nextListenerId_++;
- listeners_.emplace(id, std::move(callback));
- return id;
- }
-
- /**
- * @brief Remove a selection change listener
- * @param id The listener ID to remove
- */
- void removeListener(u32 id) {
- listeners_.erase(id);
- }
-
- /**
- * @brief Set the event dispatcher for global notifications
- * @param dispatcher The dispatcher to use
- */
- void setDispatcher(Dispatcher* dispatcher) {
- dispatcher_ = dispatcher;
- }
-
-private:
- void notifyChange(SelectionChangeType type,
- const std::vector<SelectableId>& added,
- const std::vector<SelectableId>& removed) {
- SelectionChangedEvent event{type, added, removed};
-
- for (const auto& [id, callback] : listeners_) {
- callback(event);
- }
-
- if (dispatcher_) {
- auto entities = getSelected<Entity>();
- std::vector<Entity> prevEntities;
-
- for (const auto& id : removed) {
- if (id.typeId == std::type_index(typeid(Entity))) {
- prevEntities.push_back(static_cast<Entity>(id.rawId));
- }
- }
-
- dispatcher_->trigger(SelectionChanged{prevEntities, entities});
- }
- }
-
- std::set<SelectableId> selected_;
- std::unordered_map<std::type_index, std::vector<std::any>> itemsByType_;
- std::unordered_map<u32, SelectionChangedCallback> listeners_;
- u32 nextListenerId_ = 1;
- Dispatcher* dispatcher_ = nullptr;
-};
-
-// =============================================================================
-// EntitySelection (Specialized for Entity Selection)
-// =============================================================================
-
-/**
- * @brief Specialized selection manager for entities
- *
- * @details EntitySelection provides optimized selection management
- * specifically for Entity types, with additional features
- * like hierarchy-aware selection.
- */
-class EntitySelection {
-public:
- EntitySelection() = default;
- ~EntitySelection() = default;
-
- EntitySelection(EntitySelection&&) = default;
- EntitySelection& operator=(EntitySelection&&) = default;
-
- EntitySelection(const EntitySelection&) = delete;
- EntitySelection& operator=(const EntitySelection&) = delete;
-
- /**
- * @brief Select a single entity (clears previous selection)
- * @param entity The entity to select
- */
- void select(Entity entity) {
- if (entity == INVALID_ENTITY) {
- return;
- }
-
- std::vector<Entity> previous = selected_;
- selected_.clear();
- selected_.push_back(entity);
-
- notifyChange(previous);
- }
-
- /**
- * @brief Add an entity to the selection
- * @param entity The entity to add
- */
- void addToSelection(Entity entity) {
- if (entity == INVALID_ENTITY) {
- return;
- }
-
- if (isSelected(entity)) {
- return;
- }
-
- std::vector<Entity> previous = selected_;
- selected_.push_back(entity);
-
- notifyChange(previous);
- }
-
- /**
- * @brief Remove an entity from the selection
- * @param entity The entity to remove
- */
- void removeFromSelection(Entity entity) {
- auto it = std::find(selected_.begin(), selected_.end(), entity);
- if (it == selected_.end()) {
- return;
- }
-
- std::vector<Entity> previous = selected_;
- selected_.erase(it);
-
- notifyChange(previous);
- }
-
- /**
- * @brief Toggle an entity's selection state
- * @param entity The entity to toggle
- */
- void toggleSelection(Entity entity) {
- if (isSelected(entity)) {
- removeFromSelection(entity);
- } else {
- addToSelection(entity);
- }
- }
-
- /**
- * @brief Check if an entity is selected
- * @param entity The entity to check
- * @return true if selected
- */
- [[nodiscard]] bool isSelected(Entity entity) const {
- return std::find(selected_.begin(), selected_.end(), entity) != selected_.end();
- }
-
- /**
- * @brief Clear all selection
- */
- void clear() {
- if (selected_.empty()) {
- return;
- }
-
- std::vector<Entity> previous = selected_;
- selected_.clear();
-
- notifyChange(previous);
- }
-
- /**
- * @brief Get all selected entities
- * @return Vector of selected entities
- */
- [[nodiscard]] const std::vector<Entity>& getSelected() const {
- return selected_;
- }
-
- /**
- * @brief Get the first selected entity
- * @return First entity or INVALID_ENTITY
- */
- [[nodiscard]] Entity getFirst() const {
- return selected_.empty() ? INVALID_ENTITY : selected_.front();
- }
-
- /**
- * @brief Get the number of selected entities
- * @return Selection count
- */
- [[nodiscard]] usize count() const {
- return selected_.size();
- }
-
- /**
- * @brief Check if selection is empty
- * @return true if no entities selected
- */
- [[nodiscard]] bool empty() const {
- return selected_.empty();
- }
-
- /**
- * @brief Set the event dispatcher
- * @param dispatcher The dispatcher to use
- */
- void setDispatcher(Dispatcher* dispatcher) {
- dispatcher_ = dispatcher;
- }
-
- /**
- * @brief Add a selection change listener
- * @param callback Callback function
- * @return Listener ID
- */
- u32 addListener(std::function<void(const std::vector<Entity>&,
- const std::vector<Entity>&)> callback) {
- u32 id = nextListenerId_++;
- listeners_.emplace(id, std::move(callback));
- return id;
- }
-
- /**
- * @brief Remove a listener
- * @param id Listener ID to remove
- */
- void removeListener(u32 id) {
- listeners_.erase(id);
- }
-
-private:
- void notifyChange(const std::vector<Entity>& previous) {
- for (const auto& [id, callback] : listeners_) {
- callback(previous, selected_);
- }
-
- if (dispatcher_) {
- dispatcher_->trigger(SelectionChanged{previous, selected_});
- }
- }
-
- std::vector<Entity> selected_;
- std::unordered_map<u32, std::function<void(const std::vector<Entity>&,
- const std::vector<Entity>&)>> listeners_;
- u32 nextListenerId_ = 1;
- Dispatcher* dispatcher_ = nullptr;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/gizmo/TransformGizmo.cpp b/src/esengine/editor/gizmo/TransformGizmo.cpp
deleted file mode 100644
index 31fd4c44b..000000000
--- a/src/esengine/editor/gizmo/TransformGizmo.cpp
+++ /dev/null
@@ -1,750 +0,0 @@
-/**
- * @file TransformGizmo.cpp
- * @brief Transform gizmo implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "TransformGizmo.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../renderer/RenderCommand.hpp"
-#include "../../core/Log.hpp"
-#include <glad/glad.h>
-
-namespace esengine::editor {
-
-namespace {
-
-constexpr f32 AXIS_LENGTH = 1.0f;
-constexpr f32 ARROW_HEAD_SIZE = 0.15f;
-constexpr f32 HIT_THRESHOLD = 0.1f;
-
-glm::vec4 getAxisColor(GizmoAxis axis, GizmoAxis activeAxis, GizmoAxis hoveredAxis) {
- bool isActive = (axis == activeAxis);
- bool isHovered = (axis == hoveredAxis);
-
- if (isActive) {
- return glm::vec4(1.0f, 1.0f, 0.0f, 1.0f);
- }
-
- f32 brightness = isHovered ? 1.0f : 0.85f;
-
- switch (axis) {
- case GizmoAxis::X:
- return glm::vec4(0.9f, 0.2f, 0.2f, 1.0f) * brightness;
- case GizmoAxis::Y:
- return glm::vec4(0.3f, 0.85f, 0.3f, 1.0f) * brightness;
- case GizmoAxis::Z:
- return glm::vec4(0.3f, 0.5f, 0.95f, 1.0f) * brightness;
- default:
- return glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
- }
-}
-
-void addVertex(std::vector<f32>& vertices, const glm::vec3& pos, const glm::vec4& color) {
- vertices.insert(vertices.end(), {pos.x, pos.y, pos.z, color.r, color.g, color.b, color.a});
-}
-
-void addCone(std::vector<f32>& vertices, const glm::vec3& base, const glm::vec3& tip,
- f32 radius, const glm::vec4& color, i32 segments = 12) {
- glm::vec3 dir = glm::normalize(tip - base);
- glm::vec3 up = glm::abs(dir.y) < 0.99f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0);
- glm::vec3 right = glm::normalize(glm::cross(dir, up));
- up = glm::cross(right, dir);
-
- for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = (f32(i) / segments) * glm::two_pi<f32>();
- f32 angle2 = (f32(i + 1) / segments) * glm::two_pi<f32>();
-
- glm::vec3 p1 = base + (right * glm::cos(angle1) + up * glm::sin(angle1)) * radius;
- glm::vec3 p2 = base + (right * glm::cos(angle2) + up * glm::sin(angle2)) * radius;
-
- addVertex(vertices, tip, color);
- addVertex(vertices, p1, color);
- addVertex(vertices, p2, color);
-
- addVertex(vertices, base, color);
- addVertex(vertices, p2, color);
- addVertex(vertices, p1, color);
- }
-}
-
-void addCylinder(std::vector<f32>& vertices, const glm::vec3& start, const glm::vec3& end,
- f32 radius, const glm::vec4& color, i32 segments = 8) {
- glm::vec3 dir = glm::normalize(end - start);
- glm::vec3 up = glm::abs(dir.y) < 0.99f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0);
- glm::vec3 right = glm::normalize(glm::cross(dir, up));
- up = glm::cross(right, dir);
-
- for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = (f32(i) / segments) * glm::two_pi<f32>();
- f32 angle2 = (f32(i + 1) / segments) * glm::two_pi<f32>();
-
- glm::vec3 offset1 = (right * glm::cos(angle1) + up * glm::sin(angle1)) * radius;
- glm::vec3 offset2 = (right * glm::cos(angle2) + up * glm::sin(angle2)) * radius;
-
- glm::vec3 s1 = start + offset1, s2 = start + offset2;
- glm::vec3 e1 = end + offset1, e2 = end + offset2;
-
- addVertex(vertices, s1, color);
- addVertex(vertices, e1, color);
- addVertex(vertices, e2, color);
-
- addVertex(vertices, s1, color);
- addVertex(vertices, e2, color);
- addVertex(vertices, s2, color);
- }
-}
-
-void addQuad(std::vector<f32>& vertices, const glm::vec3& p0, const glm::vec3& p1,
- const glm::vec3& p2, const glm::vec3& p3, const glm::vec4& color) {
- addVertex(vertices, p0, color);
- addVertex(vertices, p1, color);
- addVertex(vertices, p2, color);
- addVertex(vertices, p0, color);
- addVertex(vertices, p2, color);
- addVertex(vertices, p3, color);
-}
-
-void addCube(std::vector<f32>& vertices, const glm::vec3& center, f32 size, const glm::vec4& color) {
- f32 h = size * 0.5f;
-
- glm::vec3 corners[8] = {
- center + glm::vec3(-h, -h, -h), center + glm::vec3(h, -h, -h),
- center + glm::vec3(h, h, -h), center + glm::vec3(-h, h, -h),
- center + glm::vec3(-h, -h, h), center + glm::vec3(h, -h, h),
- center + glm::vec3(h, h, h), center + glm::vec3(-h, h, h)
- };
-
- auto addFace = [&](i32 a, i32 b, i32 c, i32 d) {
- addVertex(vertices, corners[a], color);
- addVertex(vertices, corners[b], color);
- addVertex(vertices, corners[c], color);
- addVertex(vertices, corners[a], color);
- addVertex(vertices, corners[c], color);
- addVertex(vertices, corners[d], color);
- };
-
- addFace(0, 1, 2, 3);
- addFace(5, 4, 7, 6);
- addFace(4, 0, 3, 7);
- addFace(1, 5, 6, 2);
- addFace(3, 2, 6, 7);
- addFace(4, 5, 1, 0);
-}
-
-void addCircle(std::vector<f32>& vertices, const glm::vec3& center, const glm::vec3& normal,
- f32 radius, const glm::vec4& color, i32 segments = 32, f32 thickness = 0.02f) {
- glm::vec3 up = glm::abs(normal.y) < 0.99f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0);
- glm::vec3 right = glm::normalize(glm::cross(normal, up));
- up = glm::normalize(glm::cross(right, normal));
-
- for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = (f32(i) / segments) * glm::two_pi<f32>();
- f32 angle2 = (f32(i + 1) / segments) * glm::two_pi<f32>();
-
- glm::vec3 p1 = center + (right * glm::cos(angle1) + up * glm::sin(angle1)) * radius;
- glm::vec3 p2 = center + (right * glm::cos(angle2) + up * glm::sin(angle2)) * radius;
-
- glm::vec3 innerP1 = center + (right * glm::cos(angle1) + up * glm::sin(angle1)) * (radius - thickness);
- glm::vec3 innerP2 = center + (right * glm::cos(angle2) + up * glm::sin(angle2)) * (radius - thickness);
-
- addVertex(vertices, p1, color);
- addVertex(vertices, p2, color);
- addVertex(vertices, innerP2, color);
-
- addVertex(vertices, p1, color);
- addVertex(vertices, innerP2, color);
- addVertex(vertices, innerP1, color);
- }
-}
-
-} // namespace
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-TransformGizmo::TransformGizmo(resource::ResourceManager& resourceManager)
- : resourceManager_(resourceManager) {}
-
-// =============================================================================
-// Initialization
-// =============================================================================
-
-void TransformGizmo::initRenderData() {
- if (initialized_) return;
-
- shaderHandle_ = resourceManager_.loadEngineShader("gizmo");
-
- VertexLayout gizmoLayout = {
- { ShaderDataType::Float3, "a_position" },
- { ShaderDataType::Float4, "a_color" }
- };
-
- // 3D geometry
- std::vector<f32> translateVerts;
- buildTranslateGeometry(translateVerts, false);
- translateVertexCount_ = static_cast<u32>(translateVerts.size() / 7);
-
- translateVAO_ = VertexArray::create();
- auto translateVBO = VertexBuffer::createRaw(translateVerts.data(),
- static_cast<u32>(translateVerts.size() * sizeof(f32)));
- translateVBO->setLayout(gizmoLayout);
- translateVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(translateVBO)));
-
- std::vector<f32> rotateVerts;
- buildRotateGeometry(rotateVerts, false);
- rotateVertexCount_ = static_cast<u32>(rotateVerts.size() / 7);
-
- rotateVAO_ = VertexArray::create();
- auto rotateVBO = VertexBuffer::createRaw(rotateVerts.data(),
- static_cast<u32>(rotateVerts.size() * sizeof(f32)));
- rotateVBO->setLayout(gizmoLayout);
- rotateVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(rotateVBO)));
-
- std::vector<f32> scaleVerts;
- buildScaleGeometry(scaleVerts, false);
- scaleVertexCount_ = static_cast<u32>(scaleVerts.size() / 7);
-
- scaleVAO_ = VertexArray::create();
- auto scaleVBO = VertexBuffer::createRaw(scaleVerts.data(),
- static_cast<u32>(scaleVerts.size() * sizeof(f32)));
- scaleVBO->setLayout(gizmoLayout);
- scaleVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(scaleVBO)));
-
- // 2D geometry
- std::vector<f32> translate2DVerts;
- buildTranslateGeometry(translate2DVerts, true);
- translate2DVertexCount_ = static_cast<u32>(translate2DVerts.size() / 7);
-
- translate2DVAO_ = VertexArray::create();
- auto translate2DVBO = VertexBuffer::createRaw(translate2DVerts.data(),
- static_cast<u32>(translate2DVerts.size() * sizeof(f32)));
- translate2DVBO->setLayout(gizmoLayout);
- translate2DVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(translate2DVBO)));
-
- std::vector<f32> rotate2DVerts;
- buildRotateGeometry(rotate2DVerts, true);
- rotate2DVertexCount_ = static_cast<u32>(rotate2DVerts.size() / 7);
-
- rotate2DVAO_ = VertexArray::create();
- auto rotate2DVBO = VertexBuffer::createRaw(rotate2DVerts.data(),
- static_cast<u32>(rotate2DVerts.size() * sizeof(f32)));
- rotate2DVBO->setLayout(gizmoLayout);
- rotate2DVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(rotate2DVBO)));
-
- std::vector<f32> scale2DVerts;
- buildScaleGeometry(scale2DVerts, true);
- scale2DVertexCount_ = static_cast<u32>(scale2DVerts.size() / 7);
-
- scale2DVAO_ = VertexArray::create();
- auto scale2DVBO = VertexBuffer::createRaw(scale2DVerts.data(),
- static_cast<u32>(scale2DVerts.size() * sizeof(f32)));
- scale2DVBO->setLayout(gizmoLayout);
- scale2DVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(scale2DVBO)));
-
- initialized_ = true;
-}
-
-void TransformGizmo::buildTranslateGeometry(std::vector<f32>& vertices, bool is2D) {
- glm::vec4 red(0.9f, 0.2f, 0.2f, 1.0f);
- glm::vec4 green(0.3f, 0.85f, 0.3f, 1.0f);
- glm::vec4 blue(0.3f, 0.5f, 0.95f, 1.0f);
- glm::vec4 yellow(0.9f, 0.9f, 0.2f, 0.6f);
- glm::vec4 cyan(0.2f, 0.9f, 0.9f, 0.6f);
- glm::vec4 magenta(0.9f, 0.2f, 0.9f, 0.6f);
-
- f32 shaftLen = 0.7f;
- f32 shaftRadius = 0.02f;
- f32 coneLen = 0.25f;
- f32 coneRadius = 0.06f;
- f32 planeOffset = shaftRadius + 0.01f;
- f32 planeSize = 0.25f;
-
- addCylinder(vertices, glm::vec3(0), glm::vec3(shaftLen, 0, 0), shaftRadius, red);
- addCone(vertices, glm::vec3(shaftLen, 0, 0), glm::vec3(shaftLen + coneLen, 0, 0), coneRadius, red);
-
- addCylinder(vertices, glm::vec3(0), glm::vec3(0, shaftLen, 0), shaftRadius, green);
- addCone(vertices, glm::vec3(0, shaftLen, 0), glm::vec3(0, shaftLen + coneLen, 0), coneRadius, green);
-
- if (!is2D) {
- addCylinder(vertices, glm::vec3(0), glm::vec3(0, 0, shaftLen), shaftRadius, blue);
- addCone(vertices, glm::vec3(0, 0, shaftLen), glm::vec3(0, 0, shaftLen + coneLen), coneRadius, blue);
- }
-
- // XY plane handle (blue tint - Z normal)
- addQuad(vertices,
- glm::vec3(planeOffset, planeOffset, 0),
- glm::vec3(planeOffset + planeSize, planeOffset, 0),
- glm::vec3(planeOffset + planeSize, planeOffset + planeSize, 0),
- glm::vec3(planeOffset, planeOffset + planeSize, 0),
- blue * glm::vec4(1.0f, 1.0f, 1.0f, 0.5f));
-
- if (!is2D) {
- // YZ plane handle (red tint - X normal)
- addQuad(vertices,
- glm::vec3(0, planeOffset, planeOffset),
- glm::vec3(0, planeOffset + planeSize, planeOffset),
- glm::vec3(0, planeOffset + planeSize, planeOffset + planeSize),
- glm::vec3(0, planeOffset, planeOffset + planeSize),
- red * glm::vec4(1.0f, 1.0f, 1.0f, 0.5f));
-
- // XZ plane handle (green tint - Y normal)
- addQuad(vertices,
- glm::vec3(planeOffset, 0, planeOffset),
- glm::vec3(planeOffset, 0, planeOffset + planeSize),
- glm::vec3(planeOffset + planeSize, 0, planeOffset + planeSize),
- glm::vec3(planeOffset + planeSize, 0, planeOffset),
- green * glm::vec4(1.0f, 1.0f, 1.0f, 0.5f));
- }
-}
-
-void TransformGizmo::buildRotateGeometry(std::vector<f32>& vertices, bool is2D) {
- glm::vec4 red(0.9f, 0.2f, 0.2f, 1.0f);
- glm::vec4 green(0.3f, 0.85f, 0.3f, 1.0f);
- glm::vec4 blue(0.3f, 0.5f, 0.95f, 1.0f);
-
- f32 radius = 0.8f;
- f32 thickness = 0.03f;
-
- if (!is2D) {
- addCircle(vertices, glm::vec3(0), glm::vec3(1, 0, 0), radius, red, 48, thickness);
- addCircle(vertices, glm::vec3(0), glm::vec3(0, 1, 0), radius, green, 48, thickness);
- }
- addCircle(vertices, glm::vec3(0), glm::vec3(0, 0, 1), radius, blue, 48, thickness);
-}
-
-void TransformGizmo::buildScaleGeometry(std::vector<f32>& vertices, bool is2D) {
- glm::vec4 red(0.9f, 0.2f, 0.2f, 1.0f);
- glm::vec4 green(0.3f, 0.85f, 0.3f, 1.0f);
- glm::vec4 blue(0.3f, 0.5f, 0.95f, 1.0f);
-
- f32 shaftLen = 0.7f;
- f32 shaftRadius = 0.02f;
- f32 cubeSize = 0.1f;
-
- addCylinder(vertices, glm::vec3(0), glm::vec3(shaftLen, 0, 0), shaftRadius, red);
- addCube(vertices, glm::vec3(shaftLen + cubeSize * 0.5f, 0, 0), cubeSize, red);
-
- addCylinder(vertices, glm::vec3(0), glm::vec3(0, shaftLen, 0), shaftRadius, green);
- addCube(vertices, glm::vec3(0, shaftLen + cubeSize * 0.5f, 0), cubeSize, green);
-
- if (!is2D) {
- addCylinder(vertices, glm::vec3(0), glm::vec3(0, 0, shaftLen), shaftRadius, blue);
- addCube(vertices, glm::vec3(0, 0, shaftLen + cubeSize * 0.5f), cubeSize, blue);
- }
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void TransformGizmo::render(const glm::mat4& view, const glm::mat4& proj,
- Entity entity, ecs::Registry& registry) {
- if (!registry.valid(entity) || !registry.has<ecs::LocalTransform>(entity)) {
- return;
- }
-
- if (!initialized_) {
- initRenderData();
- }
-
- const auto& transform = registry.get<ecs::LocalTransform>(entity);
- gizmoPosition_ = transform.position;
-
- glm::mat4 viewProj = proj * view;
- glm::mat4 model = glm::translate(glm::mat4(1.0f), gizmoPosition_);
- model = glm::scale(model, glm::vec3(size_));
-
- switch (mode_) {
- case GizmoMode::Translate:
- renderTranslateGizmo(viewProj, model);
- break;
- case GizmoMode::Rotate:
- renderRotateGizmo(viewProj, model);
- break;
- case GizmoMode::Scale:
- renderScaleGizmo(viewProj, model);
- break;
- }
-}
-
-void TransformGizmo::renderTranslateGizmo(const glm::mat4& viewProj, const glm::mat4& model) {
- Shader* shader = resourceManager_.getShader(shaderHandle_);
- VertexArray* vao = is2DMode_ ? translate2DVAO_.get() : translateVAO_.get();
- u32 vertexCount = is2DMode_ ? translate2DVertexCount_ : translateVertexCount_;
- if (!vao || !shader) return;
-
- glDisable(GL_DEPTH_TEST);
-
- shader->bind();
- shader->setUniform("u_viewProj", viewProj);
- shader->setUniform("u_model", model);
-
- vao->bind();
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertexCount));
- vao->unbind();
-
- shader->unbind();
-
- glEnable(GL_DEPTH_TEST);
-}
-
-void TransformGizmo::renderRotateGizmo(const glm::mat4& viewProj, const glm::mat4& model) {
- Shader* shader = resourceManager_.getShader(shaderHandle_);
- VertexArray* vao = is2DMode_ ? rotate2DVAO_.get() : rotateVAO_.get();
- u32 vertexCount = is2DMode_ ? rotate2DVertexCount_ : rotateVertexCount_;
- if (!vao || !shader) return;
-
- glDisable(GL_DEPTH_TEST);
-
- shader->bind();
- shader->setUniform("u_viewProj", viewProj);
- shader->setUniform("u_model", model);
-
- vao->bind();
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertexCount));
- vao->unbind();
-
- shader->unbind();
-
- glEnable(GL_DEPTH_TEST);
-}
-
-void TransformGizmo::renderScaleGizmo(const glm::mat4& viewProj, const glm::mat4& model) {
- Shader* shader = resourceManager_.getShader(shaderHandle_);
- VertexArray* vao = is2DMode_ ? scale2DVAO_.get() : scaleVAO_.get();
- u32 vertexCount = is2DMode_ ? scale2DVertexCount_ : scaleVertexCount_;
- if (!vao || !shader) return;
-
- glDisable(GL_DEPTH_TEST);
-
- shader->bind();
- shader->setUniform("u_viewProj", viewProj);
- shader->setUniform("u_model", model);
-
- vao->bind();
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertexCount));
- vao->unbind();
-
- shader->unbind();
-
- glEnable(GL_DEPTH_TEST);
-}
-
-void TransformGizmo::renderAxis(const glm::mat4& mvp, const glm::vec3& start,
- const glm::vec3& end, const glm::vec4& color) {
- (void)mvp;
- (void)start;
- (void)end;
- (void)color;
-}
-
-void TransformGizmo::renderArrow(const glm::mat4& mvp, const glm::vec3& start,
- const glm::vec3& dir, f32 length, const glm::vec4& color) {
- (void)mvp;
- (void)start;
- (void)dir;
- (void)length;
- (void)color;
-}
-
-void TransformGizmo::renderCircle(const glm::mat4& mvp, const glm::vec3& center,
- const glm::vec3& normal, f32 radius, const glm::vec4& color) {
- (void)mvp;
- (void)center;
- (void)normal;
- (void)radius;
- (void)color;
-}
-
-// =============================================================================
-// Interaction
-// =============================================================================
-
-GizmoAxis TransformGizmo::hitTest(const glm::vec3& rayOrigin, const glm::vec3& rayDir) const {
- if (mode_ == GizmoMode::Translate) {
- constexpr f32 planeOffset = 0.03f;
- constexpr f32 planeSize = 0.25f;
-
- auto checkPlaneHit = [&](const glm::vec3& planeNormal, const glm::vec3& u, const glm::vec3& v,
- GizmoAxis axis) -> bool {
- f32 denom = glm::dot(rayDir, planeNormal);
- if (std::abs(denom) < 0.001f) return false;
-
- f32 t = glm::dot(gizmoPosition_ - rayOrigin, planeNormal) / denom;
- if (t < 0.0f) return false;
-
- glm::vec3 hitPoint = rayOrigin + rayDir * t;
- glm::vec3 localHit = (hitPoint - gizmoPosition_) / size_;
-
- f32 uCoord = glm::dot(localHit, u);
- f32 vCoord = glm::dot(localHit, v);
-
- return uCoord >= planeOffset && uCoord <= planeOffset + planeSize &&
- vCoord >= planeOffset && vCoord <= planeOffset + planeSize;
- };
-
- // Check XY plane (Z normal)
- if (checkPlaneHit(glm::vec3(0, 0, 1), glm::vec3(1, 0, 0), glm::vec3(0, 1, 0), GizmoAxis::XY)) {
- return GizmoAxis::XY;
- }
-
- if (!is2DMode_) {
- // Check YZ plane (X normal)
- if (checkPlaneHit(glm::vec3(1, 0, 0), glm::vec3(0, 1, 0), glm::vec3(0, 0, 1), GizmoAxis::YZ)) {
- return GizmoAxis::YZ;
- }
-
- // Check XZ plane (Y normal)
- if (checkPlaneHit(glm::vec3(0, 1, 0), glm::vec3(1, 0, 0), glm::vec3(0, 0, 1), GizmoAxis::XZ)) {
- return GizmoAxis::XZ;
- }
- }
- }
-
- if (mode_ == GizmoMode::Translate || mode_ == GizmoMode::Scale) {
- f32 minDist = std::numeric_limits<f32>::max();
- GizmoAxis closestAxis = GizmoAxis::None;
-
- f32 distX = rayAxisDistance(rayOrigin, rayDir, gizmoPosition_, glm::vec3(1, 0, 0));
- if (distX < HIT_THRESHOLD && distX < minDist) {
- minDist = distX;
- closestAxis = GizmoAxis::X;
- }
-
- f32 distY = rayAxisDistance(rayOrigin, rayDir, gizmoPosition_, glm::vec3(0, 1, 0));
- if (distY < HIT_THRESHOLD && distY < minDist) {
- minDist = distY;
- closestAxis = GizmoAxis::Y;
- }
-
- if (!is2DMode_) {
- f32 distZ = rayAxisDistance(rayOrigin, rayDir, gizmoPosition_, glm::vec3(0, 0, 1));
- if (distZ < HIT_THRESHOLD && distZ < minDist) {
- minDist = distZ;
- closestAxis = GizmoAxis::Z;
- }
- }
-
- return closestAxis;
- }
-
- if (mode_ == GizmoMode::Rotate) {
- f32 radius = 0.8f * size_;
- f32 threshold = 0.15f * size_;
- f32 minDist = std::numeric_limits<f32>::max();
- GizmoAxis closestAxis = GizmoAxis::None;
-
- auto checkCircle = [&](const glm::vec3& normal, GizmoAxis axis) {
- f32 denom = glm::dot(rayDir, normal);
- if (std::abs(denom) < 0.001f) return;
-
- f32 t = glm::dot(gizmoPosition_ - rayOrigin, normal) / denom;
- if (t < 0.0f) return;
-
- glm::vec3 hitPoint = rayOrigin + rayDir * t;
- f32 distFromCenter = glm::length(hitPoint - gizmoPosition_);
- f32 distFromCircle = std::abs(distFromCenter - radius);
-
- if (distFromCircle < threshold && distFromCircle < minDist) {
- minDist = distFromCircle;
- closestAxis = axis;
- }
- };
-
- if (!is2DMode_) {
- checkCircle(glm::vec3(1, 0, 0), GizmoAxis::X);
- checkCircle(glm::vec3(0, 1, 0), GizmoAxis::Y);
- }
- checkCircle(glm::vec3(0, 0, 1), GizmoAxis::Z);
-
- return closestAxis;
- }
-
- return GizmoAxis::None;
-}
-
-void TransformGizmo::startDrag(GizmoAxis axis, const glm::vec3& rayOrigin, const glm::vec3& rayDir) {
- activeAxis_ = axis;
- dragging_ = true;
- rotationDelta_ = 0.0f;
-
- // Handle plane axes
- if (axis == GizmoAxis::XY || axis == GizmoAxis::XZ || axis == GizmoAxis::YZ) {
- switch (axis) {
- case GizmoAxis::XY: dragPlaneNormal_ = glm::vec3(0, 0, 1); break;
- case GizmoAxis::XZ: dragPlaneNormal_ = glm::vec3(0, 1, 0); break;
- case GizmoAxis::YZ: dragPlaneNormal_ = glm::vec3(1, 0, 0); break;
- default: break;
- }
-
- f32 denom = glm::dot(rayDir, dragPlaneNormal_);
- if (std::abs(denom) > 0.001f) {
- f32 t = glm::dot(gizmoPosition_ - rayOrigin, dragPlaneNormal_) / denom;
- dragStartPoint_ = rayOrigin + rayDir * t;
- } else {
- dragStartPoint_ = gizmoPosition_;
- }
- return;
- }
-
- glm::vec3 axisDir(0.0f);
- switch (axis) {
- case GizmoAxis::X: axisDir = glm::vec3(1, 0, 0); break;
- case GizmoAxis::Y: axisDir = glm::vec3(0, 1, 0); break;
- case GizmoAxis::Z: axisDir = glm::vec3(0, 0, 1); break;
- default: return;
- }
-
- if (mode_ == GizmoMode::Rotate) {
- dragPlaneNormal_ = axisDir;
- f32 denom = glm::dot(rayDir, dragPlaneNormal_);
- if (std::abs(denom) > 0.001f) {
- f32 t = glm::dot(gizmoPosition_ - rayOrigin, dragPlaneNormal_) / denom;
- glm::vec3 hitPoint = rayOrigin + rayDir * t;
- glm::vec3 toHit = hitPoint - gizmoPosition_;
- dragStartAngle_ = std::atan2(
- glm::dot(toHit, glm::cross(dragPlaneNormal_, glm::vec3(0, 1, 0))),
- glm::dot(toHit, glm::vec3(0, 1, 0))
- );
- if (axis == GizmoAxis::Y) {
- dragStartAngle_ = std::atan2(
- glm::dot(toHit, glm::vec3(0, 0, 1)),
- glm::dot(toHit, glm::vec3(1, 0, 0))
- );
- } else if (axis == GizmoAxis::Z) {
- dragStartAngle_ = std::atan2(
- glm::dot(toHit, glm::vec3(0, 1, 0)),
- glm::dot(toHit, glm::vec3(1, 0, 0))
- );
- } else {
- dragStartAngle_ = std::atan2(
- glm::dot(toHit, glm::vec3(0, 0, 1)),
- glm::dot(toHit, glm::vec3(0, 1, 0))
- );
- }
- dragStartPoint_ = hitPoint;
- }
- } else {
- dragPlaneNormal_ = glm::cross(axisDir, glm::cross(rayDir, axisDir));
- if (glm::length(dragPlaneNormal_) > 0.001f) {
- dragPlaneNormal_ = glm::normalize(dragPlaneNormal_);
- } else {
- dragPlaneNormal_ = glm::abs(axisDir.x) > 0.9f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0);
- }
-
- f32 denom = glm::dot(rayDir, dragPlaneNormal_);
- if (std::abs(denom) > 0.001f) {
- f32 t = glm::dot(gizmoPosition_ - rayOrigin, dragPlaneNormal_) / denom;
- dragStartPoint_ = rayOrigin + rayDir * t;
- } else {
- dragStartPoint_ = gizmoPosition_;
- }
- }
-}
-
-glm::vec3 TransformGizmo::updateDrag(const glm::vec3& rayOrigin, const glm::vec3& rayDir) {
- if (!dragging_ || activeAxis_ == GizmoAxis::None) {
- return glm::vec3(0.0f);
- }
-
- f32 denom = glm::dot(rayDir, dragPlaneNormal_);
- if (std::abs(denom) < 0.001f) {
- return glm::vec3(0.0f);
- }
-
- f32 t = glm::dot(gizmoPosition_ - rayOrigin, dragPlaneNormal_) / denom;
- glm::vec3 hitPoint = rayOrigin + rayDir * t;
- glm::vec3 delta = hitPoint - dragStartPoint_;
-
- // Handle plane movement
- if (activeAxis_ == GizmoAxis::XY || activeAxis_ == GizmoAxis::XZ || activeAxis_ == GizmoAxis::YZ) {
- glm::vec3 mask(0.0f);
- switch (activeAxis_) {
- case GizmoAxis::XY: mask = glm::vec3(1, 1, 0); break;
- case GizmoAxis::XZ: mask = glm::vec3(1, 0, 1); break;
- case GizmoAxis::YZ: mask = glm::vec3(0, 1, 1); break;
- default: break;
- }
- return delta * mask;
- }
-
- glm::vec3 axisDir(0.0f);
- switch (activeAxis_) {
- case GizmoAxis::X: axisDir = glm::vec3(1, 0, 0); break;
- case GizmoAxis::Y: axisDir = glm::vec3(0, 1, 0); break;
- case GizmoAxis::Z: axisDir = glm::vec3(0, 0, 1); break;
- default: return glm::vec3(0.0f);
- }
-
- if (mode_ == GizmoMode::Rotate) {
- glm::vec3 toHit = hitPoint - gizmoPosition_;
- f32 currentAngle;
- if (activeAxis_ == GizmoAxis::Y) {
- currentAngle = std::atan2(
- glm::dot(toHit, glm::vec3(0, 0, 1)),
- glm::dot(toHit, glm::vec3(1, 0, 0))
- );
- } else if (activeAxis_ == GizmoAxis::Z) {
- currentAngle = std::atan2(
- glm::dot(toHit, glm::vec3(0, 1, 0)),
- glm::dot(toHit, glm::vec3(1, 0, 0))
- );
- } else {
- currentAngle = std::atan2(
- glm::dot(toHit, glm::vec3(0, 0, 1)),
- glm::dot(toHit, glm::vec3(0, 1, 0))
- );
- }
- rotationDelta_ = currentAngle - dragStartAngle_;
- return glm::vec3(0.0f);
- }
-
- f32 projection = glm::dot(delta, axisDir);
- return axisDir * projection;
-}
-
-void TransformGizmo::endDrag() {
- dragging_ = false;
- activeAxis_ = GizmoAxis::None;
- rotationDelta_ = 0.0f;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-f32 TransformGizmo::rayAxisDistance(const glm::vec3& rayOrigin, const glm::vec3& rayDir,
- const glm::vec3& axisOrigin, const glm::vec3& axisDir) const {
- glm::vec3 w0 = rayOrigin - axisOrigin;
- f32 a = glm::dot(rayDir, rayDir);
- f32 b = glm::dot(rayDir, axisDir);
- f32 c = glm::dot(axisDir, axisDir);
- f32 d = glm::dot(rayDir, w0);
- f32 e = glm::dot(axisDir, w0);
-
- f32 denom = a * c - b * b;
- if (std::abs(denom) < 0.001f) {
- return std::numeric_limits<f32>::max();
- }
-
- f32 sc = (b * e - c * d) / denom;
- f32 tc = (a * e - b * d) / denom;
-
- if (tc < 0.0f || tc > AXIS_LENGTH * size_) {
- return std::numeric_limits<f32>::max();
- }
-
- glm::vec3 closestPointOnRay = rayOrigin + rayDir * sc;
- glm::vec3 closestPointOnAxis = axisOrigin + axisDir * tc;
-
- return glm::length(closestPointOnRay - closestPointOnAxis);
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/gizmo/TransformGizmo.hpp b/src/esengine/editor/gizmo/TransformGizmo.hpp
deleted file mode 100644
index 60753141b..000000000
--- a/src/esengine/editor/gizmo/TransformGizmo.hpp
+++ /dev/null
@@ -1,258 +0,0 @@
-/**
- * @file TransformGizmo.hpp
- * @brief Transform gizmo for interactive entity manipulation
- * @details Provides visual handles for translating, rotating, and scaling
- * entities in the scene view.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-#include "../../math/Math.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../renderer/Buffer.hpp"
-#include "../../resource/ResourceManager.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Enums
-// =============================================================================
-
-/**
- * @brief Gizmo manipulation mode
- */
-enum class GizmoMode : u8 {
- Translate, ///< Move entity along axes
- Rotate, ///< Rotate entity around axes
- Scale ///< Scale entity along axes
-};
-
-/**
- * @brief Gizmo axis selection
- */
-enum class GizmoAxis : u8 {
- None, ///< No axis selected
- X, ///< X axis (red)
- Y, ///< Y axis (green)
- Z, ///< Z axis (blue)
- XY, ///< XY plane
- YZ, ///< YZ plane
- XZ, ///< XZ plane
- XYZ ///< All axes (for uniform scale)
-};
-
-// =============================================================================
-// TransformGizmo Class
-// =============================================================================
-
-/**
- * @brief Interactive gizmo for manipulating entity transforms
- *
- * @details Renders visual handles for translation, rotation, and scaling.
- * Supports mouse-based manipulation with undo/redo integration.
- *
- * @code
- * TransformGizmo gizmo;
- * gizmo.setMode(GizmoMode::Translate);
- *
- * // In render loop
- * if (selectedEntity != INVALID_ENTITY) {
- * gizmo.render(camera.getViewMatrix(), camera.getProjectionMatrix(),
- * selectedEntity, registry);
- * }
- *
- * // In mouse down handler
- * glm::vec3 rayOrigin, rayDir;
- * GizmoAxis axis = gizmo.hitTest(rayOrigin, rayDir);
- * if (axis != GizmoAxis::None) {
- * gizmo.startDrag(axis, hitPoint);
- * }
- * @endcode
- */
-class TransformGizmo {
-public:
- /**
- * @brief Constructs transform gizmo with resource manager
- * @param resourceManager Resource manager for shader loading
- */
- explicit TransformGizmo(resource::ResourceManager& resourceManager);
- ~TransformGizmo() = default;
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /**
- * @brief Sets the gizmo mode
- * @param mode Manipulation mode (translate/rotate/scale)
- */
- void setMode(GizmoMode mode) { mode_ = mode; }
-
- /**
- * @brief Gets the current gizmo mode
- * @return Current mode
- */
- GizmoMode getMode() const { return mode_; }
-
- /**
- * @brief Sets the gizmo size
- * @param size Size in world units
- */
- void setSize(f32 size) { size_ = size; }
-
- /**
- * @brief Gets the gizmo size
- * @return Size in world units
- */
- f32 getSize() const { return size_; }
-
- /**
- * @brief Sets 2D mode (only X/Y axes)
- * @param enabled True for 2D mode
- */
- void set2DMode(bool enabled) { is2DMode_ = enabled; }
-
- /**
- * @brief Checks if in 2D mode
- * @return True if 2D mode
- */
- bool is2DMode() const { return is2DMode_; }
-
- // =========================================================================
- // Rendering
- // =========================================================================
-
- /**
- * @brief Renders the gizmo for the given entity
- * @param view View matrix
- * @param proj Projection matrix
- * @param entity Entity to manipulate
- * @param registry Entity registry
- */
- void render(const glm::mat4& view, const glm::mat4& proj,
- Entity entity, ecs::Registry& registry);
-
- // =========================================================================
- // Interaction
- // =========================================================================
-
- /**
- * @brief Tests if a ray hits the gizmo
- * @param rayOrigin Ray origin in world space
- * @param rayDir Ray direction (normalized)
- * @return Hit axis or GizmoAxis::None
- */
- GizmoAxis hitTest(const glm::vec3& rayOrigin, const glm::vec3& rayDir) const;
-
- /**
- * @brief Starts a drag operation
- * @param axis Axis to manipulate
- * @param rayOrigin Ray origin in world space
- * @param rayDir Ray direction (normalized)
- */
- void startDrag(GizmoAxis axis, const glm::vec3& rayOrigin, const glm::vec3& rayDir);
-
- /**
- * @brief Updates the drag operation for translation/scale
- * @param rayOrigin Ray origin in world space
- * @param rayDir Ray direction (normalized)
- * @return Delta position/scale to apply
- */
- glm::vec3 updateDrag(const glm::vec3& rayOrigin, const glm::vec3& rayDir);
-
- /**
- * @brief Gets the rotation delta during drag
- * @return Rotation delta in radians around the active axis
- */
- f32 getRotationDelta() const { return rotationDelta_; }
-
- /**
- * @brief Gets the currently active drag axis
- * @return Active axis or GizmoAxis::None
- */
- GizmoAxis getActiveAxis() const { return activeAxis_; }
-
- /**
- * @brief Ends the drag operation
- */
- void endDrag();
-
- /**
- * @brief Checks if currently dragging
- * @return True if dragging
- */
- bool isDragging() const { return dragging_; }
-
- /**
- * @brief Sets the hovered axis for visual feedback
- * @param axis The axis being hovered
- */
- void setHoveredAxis(GizmoAxis axis) { hoveredAxis_ = axis; }
-
- /**
- * @brief Gets the gizmo world position
- * @return Position in world space
- */
- const glm::vec3& getPosition() const { return gizmoPosition_; }
-
-private:
- void renderTranslateGizmo(const glm::mat4& viewProj, const glm::mat4& model);
- void renderRotateGizmo(const glm::mat4& viewProj, const glm::mat4& model);
- void renderScaleGizmo(const glm::mat4& viewProj, const glm::mat4& model);
-
- void renderAxis(const glm::mat4& mvp, const glm::vec3& start,
- const glm::vec3& end, const glm::vec4& color);
- void renderArrow(const glm::mat4& mvp, const glm::vec3& start,
- const glm::vec3& dir, f32 length, const glm::vec4& color);
- void renderCircle(const glm::mat4& mvp, const glm::vec3& center,
- const glm::vec3& normal, f32 radius, const glm::vec4& color);
-
- f32 rayAxisDistance(const glm::vec3& rayOrigin, const glm::vec3& rayDir,
- const glm::vec3& axisOrigin, const glm::vec3& axisDir) const;
-
- void initRenderData();
- void buildTranslateGeometry(std::vector<f32>& vertices, bool is2D = false);
- void buildRotateGeometry(std::vector<f32>& vertices, bool is2D = false);
- void buildScaleGeometry(std::vector<f32>& vertices, bool is2D = false);
-
- GizmoMode mode_ = GizmoMode::Translate;
- GizmoAxis activeAxis_ = GizmoAxis::None;
- GizmoAxis hoveredAxis_ = GizmoAxis::None;
- f32 size_ = 1.0f;
- bool is2DMode_ = false;
-
- bool dragging_ = false;
- glm::vec3 dragStartPoint_{0.0f};
- glm::vec3 dragPlaneNormal_{0.0f};
- f32 dragStartAngle_ = 0.0f;
- f32 rotationDelta_ = 0.0f;
- glm::vec3 gizmoPosition_{0.0f};
-
- resource::ResourceManager& resourceManager_;
- Unique<VertexArray> translateVAO_;
- Unique<VertexArray> rotateVAO_;
- Unique<VertexArray> scaleVAO_;
- Unique<VertexArray> translate2DVAO_;
- Unique<VertexArray> rotate2DVAO_;
- Unique<VertexArray> scale2DVAO_;
- resource::ShaderHandle shaderHandle_;
- u32 translateVertexCount_ = 0;
- u32 rotateVertexCount_ = 0;
- u32 scaleVertexCount_ = 0;
- u32 translate2DVertexCount_ = 0;
- u32 rotate2DVertexCount_ = 0;
- u32 scale2DVertexCount_ = 0;
- bool initialized_ = false;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/main.cpp b/src/esengine/editor/main.cpp
deleted file mode 100644
index 84c4ab15f..000000000
--- a/src/esengine/editor/main.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * @file main.cpp
- * @brief ESEngine Editor entry point
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "EditorApplication.hpp"
-#include "../core/Log.hpp"
-#include "../core/RuntimeConfig.hpp"
-
-int main() {
- esengine::Log::init();
-
- esengine::RuntimeConfig::get().setEditorMode(true);
- esengine::RuntimeConfig::get().setHotReloadEnabled(true);
-
- ES_LOG_INFO("Starting ESEngine Editor...");
-
- esengine::editor::EditorApplication editor;
- editor.run();
-
- ES_LOG_INFO("ESEngine Editor exited");
-
- return 0;
-}
diff --git a/src/esengine/editor/panels/AssetBrowserPanel.cpp b/src/esengine/editor/panels/AssetBrowserPanel.cpp
deleted file mode 100644
index b1be79f32..000000000
--- a/src/esengine/editor/panels/AssetBrowserPanel.cpp
+++ /dev/null
@@ -1,870 +0,0 @@
-/**
- * @file AssetBrowserPanel.cpp
- * @brief Asset browser panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "AssetBrowserPanel.hpp"
-#include "AssetGridItem.hpp"
-#include "../AssetDatabase.hpp"
-#include "../ThumbnailGenerator.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/layout/StackLayout.hpp"
-#include "../../ui/layout/WrapLayout.hpp"
-#include "../../ui/widgets/Label.hpp"
-#include "../../ui/widgets/Button.hpp"
-#include "../../platform/FileSystem.hpp"
-#include "../../platform/FileDialog.hpp"
-#include "../../platform/PathResolver.hpp"
-#include "../../core/Log.hpp"
-#include "../../events/Sink.hpp"
-#include "../../ui/icons/Icons.hpp"
-
-namespace icons = esengine::ui::icons;
-
-#include <algorithm>
-#include <fstream>
-#include <cctype>
-#include <filesystem>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-AssetBrowserPanel::AssetBrowserPanel(AssetDatabase& assetDB, ThumbnailGenerator& thumbnailGen)
- : DockPanel(ui::WidgetId("asset_browser_panel"), "Assets"),
- assetDB_(assetDB),
- thumbnailGen_(thumbnailGen) {
-
- setPanelType("AssetBrowser");
- setClosable(true);
- setMinSize(glm::vec2(400.0f, 250.0f));
-
- rootPath_ = assetDB_.getProjectPath();
- if (rootPath_.empty()) {
- rootPath_ = "assets";
- }
- currentPath_ = rootPath_;
-
- engineResourcesPath_ = PathResolver::editorPath("data");
- ES_LOG_INFO("AssetBrowserPanel: rootPath = {}", rootPath_);
- ES_LOG_INFO("AssetBrowserPanel: engineResourcesPath = {}", engineResourcesPath_);
- ES_LOG_INFO("AssetBrowserPanel: directoryExists = {}", FileSystem::directoryExists(rootPath_));
-
- buildUI();
-
-#ifndef ES_PLATFORM_WEB
- rebuildFolderTree();
- refreshAssetList();
- rebuildBreadcrumb();
-#endif
-}
-
-AssetBrowserPanel::~AssetBrowserPanel() = default;
-
-// =============================================================================
-// Public Methods
-// =============================================================================
-
-void AssetBrowserPanel::refresh() {
- needsRebuild_ = true;
-}
-
-void AssetBrowserPanel::setRootPath(const std::string& path) {
- if (rootPath_ != path) {
- rootPath_ = path;
- currentPath_ = rootPath_;
- rebuildFolderTree();
- refreshAssetList();
- }
-}
-
-void AssetBrowserPanel::setViewMode(AssetViewMode mode) {
- if (viewMode_ != mode) {
- viewMode_ = mode;
- updateViewModeButtons();
- refreshAssetList();
- }
-}
-
-void AssetBrowserPanel::onActivated() {
- if (needsRebuild_) {
- rebuildFolderTree();
- refreshAssetList();
- needsRebuild_ = false;
- }
-}
-
-void AssetBrowserPanel::render(ui::UIBatchRenderer& renderer) {
- if (needsRefreshAssetList_) {
- needsRefreshAssetList_ = false;
- currentPath_ = pendingNavigatePath_;
- refreshAssetList();
- rebuildBreadcrumb();
-
- auto it = pathToNode_.find(pendingNavigatePath_);
- if (it != pathToNode_.end()) {
- folderTree_->selectNode(it->second);
- folderTree_->setNodeExpanded(it->second, true);
- }
- pendingNavigatePath_.clear();
- }
-
- DockPanel::render(renderer);
-}
-
-// =============================================================================
-// UI Building
-// =============================================================================
-
-void AssetBrowserPanel::buildUI() {
- constexpr glm::vec4 panelBg{0.145f, 0.145f, 0.149f, 1.0f};
- constexpr glm::vec4 toolbarBg{0.176f, 0.176f, 0.188f, 1.0f};
- constexpr glm::vec4 mainBg{0.118f, 0.118f, 0.118f, 1.0f};
- constexpr glm::vec4 borderColor{0.235f, 0.235f, 0.235f, 1.0f};
- constexpr glm::vec4 buttonBg{0.235f, 0.235f, 0.235f, 1.0f};
- constexpr glm::vec4 primaryBg{0.231f, 0.510f, 0.965f, 1.0f};
-
- auto rootPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_root"));
- rootPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 0.0f));
- rootPanel->setDrawBackground(true);
- rootPanel->setBackgroundColor(mainBg);
-
- auto leftPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_left"));
- leftPanel->setWidth(ui::SizeValue::px(200.0f));
- leftPanel->setHeight(ui::SizeValue::flex(1.0f));
- leftPanel->setDrawBackground(true);
- leftPanel->setBackgroundColor(panelBg);
- leftPanel->setBorderColor(borderColor);
- leftPanel->setBorderWidth(ui::BorderWidth(0.0f, 1.0f, 0.0f, 0.0f));
-
- auto leftScrollView = makeUnique<ui::ScrollView>(ui::WidgetId(getId().path + "_left_scroll"));
- leftScrollView->setScrollDirection(ui::ScrollDirection::Vertical);
- leftScrollView->setWidth(ui::SizeValue::flex(1.0f));
- leftScrollView->setHeight(ui::SizeValue::flex(1.0f));
-
- auto folderTree = makeUnique<ui::TreeView>(ui::WidgetId(getId().path + "_folder_tree"));
- folderTree->setMultiSelect(false);
- folderTree->setRowHeight(24.0f);
- folderTree->setIndentSize(16.0f);
- folderTree->setShowVisibilityColumn(false);
- folderTree->setShowTypeColumn(false);
- folderTree->setWidth(ui::SizeValue::flex(1.0f));
- folderTree->setHeight(ui::SizeValue::autoSize());
- folderTree_ = folderTree.get();
-
- leftScrollView->setContent(std::move(folderTree));
- leftPanel->addChild(std::move(leftScrollView));
-
- leftPanel_ = leftPanel.get();
- rootPanel->addChild(std::move(leftPanel));
-
- auto rightPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_right"));
- rightPanel->setWidth(ui::SizeValue::flex(1.0f));
- rightPanel->setHeight(ui::SizeValue::flex(1.0f));
- rightPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f));
- rightPanel->setDrawBackground(true);
- rightPanel->setBackgroundColor(mainBg);
-
- auto toolbar = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_toolbar"));
- toolbar->setHeight(ui::SizeValue::px(38.0f));
- toolbar->setWidth(ui::SizeValue::flex(1.0f));
- toolbar->setPadding(ui::Insets(6.0f, 12.0f, 6.0f, 12.0f));
- toolbar->setDrawBackground(true);
- toolbar->setBackgroundColor(toolbarBg);
- toolbar->setBorderColor(borderColor);
- toolbar->setBorderWidth(ui::BorderWidth(0.0f, 0.0f, 1.0f, 0.0f));
- toolbar->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 8.0f));
-
- auto addBtn = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_add_btn"), icons::Plus);
- addBtn->setFontSize(14.0f);
- addBtn->setWidth(ui::SizeValue::px(32.0f));
- addBtn->setHeight(ui::SizeValue::px(26.0f));
- addBtn->setBackgroundColor(primaryBg);
- addBtn->setHoverColor({0.149f, 0.388f, 0.933f, 1.0f});
- toolbarConnections_.add(sink(addBtn->onClick).connect([this]() {
- if (getContext()) {
- contextMenu_->clearItems();
- contextMenu_->addItem(ui::MenuItem::action("create_folder", "New Folder", icons::FolderPlus));
- contextMenu_->addItem(ui::MenuItem::divider());
- contextMenu_->addItem(ui::MenuItem::action("create_scene", "New Scene", icons::Layers));
- contextMenu_->addItem(ui::MenuItem::action("create_script", "New Script", icons::File));
- getContext()->addOverlay(contextMenu_.get());
- auto bounds = getContentBounds();
- contextMenu_->show(bounds.x + 12.0f, bounds.y + 44.0f);
- }
- }));
- toolbar->addChild(std::move(addBtn));
-
- auto importBtn = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_import_btn"), icons::Download);
- importBtn->setFontSize(14.0f);
- importBtn->setWidth(ui::SizeValue::px(32.0f));
- importBtn->setHeight(ui::SizeValue::px(26.0f));
- importBtn->setBackgroundColor(buttonBg);
- importBtn->setHoverColor({0.3f, 0.3f, 0.3f, 1.0f});
- toolbarConnections_.add(sink(importBtn->onClick).connect([this]() { importAsset(); }));
- toolbar->addChild(std::move(importBtn));
-
- auto refreshBtn = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_refresh_btn"), icons::Refresh);
- refreshBtn->setFontSize(14.0f);
- refreshBtn->setWidth(ui::SizeValue::px(32.0f));
- refreshBtn->setHeight(ui::SizeValue::px(26.0f));
- refreshBtn->setBackgroundColor(buttonBg);
- refreshBtn->setHoverColor({0.3f, 0.3f, 0.3f, 1.0f});
- toolbarConnections_.add(sink(refreshBtn->onClick).connect([this]() {
- rebuildFolderTree();
- refreshAssetList();
- }));
- toolbar->addChild(std::move(refreshBtn));
-
- auto breadcrumbPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_breadcrumb"));
- breadcrumbPanel->setWidth(ui::SizeValue::flex(1.0f));
- breadcrumbPanel->setHeight(ui::SizeValue::px(26.0f));
- breadcrumbPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 2.0f));
- breadcrumbPanel->setDrawBackground(false);
- breadcrumbPanel_ = breadcrumbPanel.get();
- toolbar->addChild(std::move(breadcrumbPanel));
-
- auto searchField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + "_search"));
- searchField->setPlaceholder("Search...");
- searchField->setWidth(ui::SizeValue::px(150.0f));
- searchField->setHeight(ui::SizeValue::px(26.0f));
- searchField_ = searchField.get();
- toolbar->addChild(std::move(searchField));
-
- auto viewModePanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_viewmode"));
- viewModePanel->setWidth(ui::SizeValue::autoSize());
- viewModePanel->setHeight(ui::SizeValue::px(26.0f));
- viewModePanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 0.0f));
- viewModePanel->setDrawBackground(false);
-
- auto gridBtn = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_grid_btn"), icons::LayoutGrid);
- gridBtn->setFontSize(14.0f);
- gridBtn->setWidth(ui::SizeValue::px(28.0f));
- gridBtn->setHeight(ui::SizeValue::px(26.0f));
- gridBtn->setBackgroundColor(viewMode_ == AssetViewMode::Grid ? buttonBg : glm::vec4(0.0f));
- gridBtn->setHoverColor({0.3f, 0.3f, 0.3f, 1.0f});
- toolbarConnections_.add(sink(gridBtn->onClick).connect([this]() { setViewMode(AssetViewMode::Grid); }));
- viewModePanel->addChild(std::move(gridBtn));
-
- auto listBtn = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_list_btn"), icons::List);
- listBtn->setFontSize(14.0f);
- listBtn->setWidth(ui::SizeValue::px(28.0f));
- listBtn->setHeight(ui::SizeValue::px(26.0f));
- listBtn->setBackgroundColor(viewMode_ == AssetViewMode::List ? buttonBg : glm::vec4(0.0f));
- listBtn->setHoverColor({0.3f, 0.3f, 0.3f, 1.0f});
- toolbarConnections_.add(sink(listBtn->onClick).connect([this]() { setViewMode(AssetViewMode::List); }));
- viewModePanel->addChild(std::move(listBtn));
-
- viewModePanel_ = viewModePanel.get();
- toolbar->addChild(std::move(viewModePanel));
-
- rightPanel->addChild(std::move(toolbar));
-
- auto scrollView = makeUnique<ui::ScrollView>(ui::WidgetId(getId().path + "_scroll"));
- scrollView->setScrollDirection(ui::ScrollDirection::Vertical);
- scrollView->setWidth(ui::SizeValue::flex(1.0f));
- scrollView->setHeight(ui::SizeValue::flex(1.0f));
-
- auto gridPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_grid"));
- gridPanel->setDrawBackground(false);
- gridPanel->setWidth(ui::SizeValue::flex(1.0f));
- gridPanel->setHeight(ui::SizeValue::autoSize());
- gridPanel->setLayout(makeUnique<ui::WrapLayout>(8.0f, 8.0f));
- gridPanel->setPadding(ui::Insets::all(12.0f));
- assetGridPanel_ = gridPanel.get();
- scrollView->setContent(std::move(gridPanel));
-
- assetScrollView_ = scrollView.get();
- rightPanel->addChild(std::move(scrollView));
-
- auto statusBar = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_status"));
- statusBar->setHeight(ui::SizeValue::px(24.0f));
- statusBar->setWidth(ui::SizeValue::flex(1.0f));
- statusBar->setPadding(ui::Insets(4.0f, 12.0f, 4.0f, 12.0f));
- statusBar->setDrawBackground(true);
- statusBar->setBackgroundColor(panelBg);
- statusBar->setBorderColor(borderColor);
- statusBar->setBorderWidth(ui::BorderWidth(1.0f, 0.0f, 0.0f, 0.0f));
-
- auto statusLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_status_label"), "0 items");
- statusLabel->setFontSize(11.0f);
- statusLabel->setColor({0.6f, 0.6f, 0.6f, 1.0f});
- statusLabel_ = statusLabel.get();
- statusBar->addChild(std::move(statusLabel));
-
- rightPanel->addChild(std::move(statusBar));
-
- rightPanel_ = rightPanel.get();
- rootPanel->addChild(std::move(rightPanel));
-
- setContent(std::move(rootPanel));
-
- folderSelectedConnection_ = sink(folderTree_->onNodeSelected).connect(
- [this](ui::TreeNodeId nodeId) { onFolderSelected(nodeId); }
- );
-
- searchChangedConnection_ = sink(searchField_->onTextChanged).connect(
- [this](const std::string& text) { onSearchTextChanged(text); }
- );
-
- contextMenu_ = makeUnique<ui::ContextMenu>(ui::WidgetId("asset_browser_context_menu"));
- contextMenuItemSelectedConnection_ = sink(contextMenu_->onItemSelected).connect(
- [this](const std::string& itemId) { onContextMenuItemSelected(itemId); }
- );
- contextMenuClosedConnection_ = sink(contextMenu_->onClosed).connect(
- [this]() {
- if (getContext()) {
- getContext()->removeOverlay(contextMenu_.get());
- }
- }
- );
-}
-
-// =============================================================================
-// Directory Scanning
-// =============================================================================
-
-void AssetBrowserPanel::rebuildFolderTree() {
-#ifdef ES_PLATFORM_WEB
- auto label = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_web_msg"), "N/A on Web");
- label->setFontSize(12.0f);
- leftPanel_->clearChildren();
- leftPanel_->addChild(std::move(label));
- return;
-#endif
-
- folderTree_->clear();
- nodeToPath_.clear();
- pathToNode_.clear();
- engineNodes_.clear();
-
- if (!FileSystem::directoryExists(rootPath_)) {
- ES_LOG_WARN("Asset root path does not exist: {}", rootPath_);
- return;
- }
-
- ui::TreeNodeId projectNodeId = folderTree_->addNode(ui::INVALID_TREE_NODE, "Project");
- nodeToPath_[projectNodeId] = rootPath_;
- pathToNode_[rootPath_] = projectNodeId;
-
- addFolderNodes(rootPath_, projectNodeId);
-
- folderTree_->setNodeExpanded(projectNodeId, true);
- folderTree_->selectNode(projectNodeId);
-
- if (FileSystem::directoryExists(engineResourcesPath_)) {
- ui::TreeNodeId engineNodeId = folderTree_->addNode(ui::INVALID_TREE_NODE, "Engine");
- nodeToPath_[engineNodeId] = engineResourcesPath_;
- pathToNode_[engineResourcesPath_] = engineNodeId;
- engineNodes_.insert(engineNodeId);
-
- addFolderNodes(engineResourcesPath_, engineNodeId, true);
- }
-}
-
-void AssetBrowserPanel::addFolderNodes(const std::string& path, ui::TreeNodeId parentNode, bool isEngine) {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::vector<std::string> entries = FileSystem::listDirectory(path, false);
- ES_LOG_INFO("AssetBrowserPanel::addFolderNodes: {} has {} entries", path, entries.size());
-
- for (const auto& entry : entries) {
- if (FileSystem::directoryExists(entry)) {
- std::string folderName = getFileName(entry);
- ES_LOG_DEBUG(" Found folder: {}", folderName);
-
- ui::TreeNodeId nodeId = folderTree_->addNode(parentNode, folderName);
- nodeToPath_[nodeId] = entry;
- pathToNode_[entry] = nodeId;
-
- if (isEngine) {
- engineNodes_.insert(nodeId);
- }
-
- addFolderNodes(entry, nodeId, isEngine);
- }
- }
-}
-
-void AssetBrowserPanel::refreshAssetList() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- itemConnections_.disconnectAll();
- currentAssets_.clear();
- assetGridPanel_->clearChildren();
-
- if (!FileSystem::directoryExists(currentPath_)) {
- ES_LOG_WARN("AssetBrowserPanel::refreshAssetList: directory not found: {}", currentPath_);
- return;
- }
-
- std::vector<std::string> files = FileSystem::listDirectory(currentPath_, false);
- ES_LOG_INFO("AssetBrowserPanel::refreshAssetList: {} has {} items", currentPath_, files.size());
-
- for (const auto& filePath : files) {
- AssetEntry entry;
- entry.path = filePath;
- entry.name = getFileName(filePath);
- entry.extension = getFileExtension(filePath);
- entry.isDirectory = FileSystem::directoryExists(filePath);
-
- if (entry.isDirectory) {
- entry.type = AssetType::Folder;
- } else {
- entry.type = getAssetTypeFromExtension(entry.extension);
- entry.fileSize = FileSystem::getFileSize(filePath);
- entry.modificationTime = FileSystem::getFileModificationTime(filePath);
- }
-
- if (!searchFilter_.empty()) {
- std::string lowerName = toLower(entry.name);
- std::string lowerFilter = toLower(searchFilter_);
- if (lowerName.find(lowerFilter) == std::string::npos) {
- continue;
- }
- }
-
- currentAssets_.push_back(entry);
- }
-
- std::sort(currentAssets_.begin(), currentAssets_.end(),
- [](const AssetEntry& a, const AssetEntry& b) {
- if (a.isDirectory != b.isDirectory) {
- return a.isDirectory;
- }
- return a.name < b.name;
- });
-
- for (usize i = 0; i < currentAssets_.size(); ++i) {
- const auto& entry = currentAssets_[i];
-
- auto item = makeUnique<AssetGridItem>(
- ui::WidgetId::indexed(assetGridPanel_->getId().path, "item", static_cast<u32>(i)),
- entry
- );
-
- itemConnections_.add(sink(item->onClick).connect([this](const std::string& path) {
- onAssetItemClicked(path);
- }));
-
- itemConnections_.add(sink(item->onDoubleClick).connect([this](const std::string& path) {
- onAssetItemDoubleClicked(path);
- }));
-
- assetGridPanel_->addChild(std::move(item));
- }
-
- ES_LOG_INFO("AssetBrowserPanel::refreshAssetList: added {} items to grid", currentAssets_.size());
-
- if (statusLabel_) {
- usize count = currentAssets_.size();
- std::string text = std::to_string(count) + (count == 1 ? " item" : " items");
- if (browsingEngineResources_) {
- text += " (Read-only)";
- }
- statusLabel_->setText(text);
- }
-}
-
-// =============================================================================
-// Event Handlers
-// =============================================================================
-
-void AssetBrowserPanel::onFolderSelected(ui::TreeNodeId nodeId) {
- auto it = nodeToPath_.find(nodeId);
- if (it != nodeToPath_.end()) {
- if (currentPath_ != it->second) {
- currentPath_ = it->second;
- browsingEngineResources_ = (engineNodes_.find(nodeId) != engineNodes_.end());
- refreshAssetList();
- rebuildBreadcrumb();
- }
- }
-}
-
-void AssetBrowserPanel::onSearchTextChanged(const std::string& text) {
- searchFilter_ = text;
- refreshAssetList();
-}
-
-void AssetBrowserPanel::onAssetItemClicked(const std::string& path) {
- selectedAssetPath_ = path;
-
- for (auto& child : assetGridPanel_->getChildren()) {
- auto* item = dynamic_cast<AssetGridItem*>(child.get());
- if (item) {
- item->setSelected(item->getEntry().path == path);
- }
- }
-
- onAssetSelected.publish(path);
-}
-
-void AssetBrowserPanel::onAssetItemDoubleClicked(const std::string& path) {
- // Copy path - the source object will be destroyed when we refresh
- std::string pathCopy = path;
-
- if (FileSystem::directoryExists(pathCopy)) {
- // Defer the refresh to avoid deleting the object that's currently handling the event
- pendingNavigatePath_ = pathCopy;
- needsRefreshAssetList_ = true;
- } else {
- onAssetDoubleClicked.publish(pathCopy);
- }
-}
-
-bool AssetBrowserPanel::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button == ui::MouseButton::Right) {
- if (assetScrollView_ && assetScrollView_->getBounds().contains(event.x, event.y)) {
- contextMenu_->clearItems();
-
- if (!browsingEngineResources_) {
- contextMenu_->addItem(ui::MenuItem::action("create_folder", "New Folder", ui::icons::FolderPlus));
- contextMenu_->addItem(ui::MenuItem::divider());
- contextMenu_->addItem(ui::MenuItem::action("create_scene", "New Scene", ui::icons::Layers));
- contextMenu_->addItem(ui::MenuItem::action("create_script", "New Script", ui::icons::File));
- contextMenu_->addItem(ui::MenuItem::divider());
-
- if (!selectedAssetPath_.empty()) {
- contextMenu_->addItem(ui::MenuItem::action("rename", "Rename", ui::icons::Edit2, "F2"));
- contextMenu_->addItem(ui::MenuItem::action("delete", "Delete", ui::icons::Trash2, "Del"));
- contextMenu_->addItem(ui::MenuItem::divider());
- }
- }
-
- contextMenu_->addItem(ui::MenuItem::action("refresh", "Refresh", ui::icons::Refresh));
-
- if (getContext()) {
- getContext()->addOverlay(contextMenu_.get());
- }
- contextMenu_->show(event.x, event.y);
- return true;
- }
- }
-
- return DockPanel::onMouseDown(event);
-}
-
-void AssetBrowserPanel::onContextMenuItemSelected(const std::string& itemId) {
- if (getContext()) {
- getContext()->removeOverlay(contextMenu_.get());
- }
-
- if (itemId == "create_folder") {
- createFolder();
- } else if (itemId == "create_scene") {
- createScene();
- } else if (itemId == "create_script") {
- createScript();
- } else if (itemId == "rename") {
- renameSelectedAsset();
- } else if (itemId == "delete") {
- deleteSelectedAsset();
- } else if (itemId == "refresh") {
- rebuildFolderTree();
- refreshAssetList();
- }
-}
-
-void AssetBrowserPanel::createFolder() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string baseName = "New Folder";
- std::string folderPath = currentPath_ + "/" + baseName;
-
- i32 counter = 1;
- while (FileSystem::directoryExists(folderPath)) {
- folderPath = currentPath_ + "/" + baseName + " " + std::to_string(counter);
- ++counter;
- }
-
- if (FileSystem::createDirectory(folderPath)) {
- rebuildFolderTree();
- refreshAssetList();
- ES_LOG_INFO("Created folder: {}", folderPath);
- } else {
- ES_LOG_ERROR("Failed to create folder: {}", folderPath);
- }
-}
-
-void AssetBrowserPanel::createScene() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string baseName = "New Scene";
- std::string scenePath = currentPath_ + "/" + baseName + ".esscene";
-
- i32 counter = 1;
- while (FileSystem::fileExists(scenePath)) {
- scenePath = currentPath_ + "/" + baseName + " " + std::to_string(counter) + ".esscene";
- ++counter;
- }
-
- std::ofstream file(scenePath);
- if (file.is_open()) {
- file << "{\n";
- file << " \"version\": 1,\n";
- file << " \"name\": \"" << getFileName(scenePath) << "\",\n";
- file << " \"entities\": []\n";
- file << "}\n";
- file.close();
-
- refreshAssetList();
- ES_LOG_INFO("Created scene: {}", scenePath);
- } else {
- ES_LOG_ERROR("Failed to create scene: {}", scenePath);
- }
-}
-
-void AssetBrowserPanel::createScript() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string baseName = "NewScript";
- std::string scriptPath = currentPath_ + "/" + baseName + ".js";
-
- i32 counter = 1;
- while (FileSystem::fileExists(scriptPath)) {
- scriptPath = currentPath_ + "/" + baseName + std::to_string(counter) + ".js";
- ++counter;
- }
-
- std::ofstream file(scriptPath);
- if (file.is_open()) {
- file << "// " << getFileName(scriptPath) << "\n";
- file << "\n";
- file << "export default class {\n";
- file << " onStart() {\n";
- file << " // Called when the entity is created\n";
- file << " }\n";
- file << "\n";
- file << " onUpdate(deltaTime) {\n";
- file << " // Called every frame\n";
- file << " }\n";
- file << "}\n";
- file.close();
-
- refreshAssetList();
- ES_LOG_INFO("Created script: {}", scriptPath);
- } else {
- ES_LOG_ERROR("Failed to create script: {}", scriptPath);
- }
-}
-
-void AssetBrowserPanel::deleteSelectedAsset() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- if (selectedAssetPath_.empty()) {
- return;
- }
-
- std::error_code ec;
- bool success = false;
-
- if (FileSystem::directoryExists(selectedAssetPath_)) {
- success = std::filesystem::remove_all(selectedAssetPath_, ec) > 0;
- } else if (FileSystem::fileExists(selectedAssetPath_)) {
- success = std::filesystem::remove(selectedAssetPath_, ec);
- }
-
- if (success && !ec) {
- ES_LOG_INFO("Deleted: {}", selectedAssetPath_);
- selectedAssetPath_.clear();
- rebuildFolderTree();
- refreshAssetList();
- } else {
- ES_LOG_ERROR("Failed to delete: {} ({})", selectedAssetPath_, ec.message());
- }
-}
-
-void AssetBrowserPanel::renameSelectedAsset() {
- // TODO: Implement inline renaming
- ES_LOG_INFO("Rename asset: not yet implemented");
-}
-
-// =============================================================================
-// Utility Methods
-// =============================================================================
-
-std::string AssetBrowserPanel::getFileName(const std::string& path) const {
- usize pos = path.find_last_of("/\\");
- if (pos != std::string::npos) {
- return path.substr(pos + 1);
- }
- return path;
-}
-
-std::string AssetBrowserPanel::getFileExtension(const std::string& path) const {
- usize pos = path.find_last_of('.');
- if (pos != std::string::npos) {
- return path.substr(pos);
- }
- return "";
-}
-
-std::string AssetBrowserPanel::toLower(const std::string& str) const {
- std::string result = str;
- std::transform(result.begin(), result.end(), result.begin(),
- [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
- return result;
-}
-
-void AssetBrowserPanel::rebuildBreadcrumb() {
- if (!breadcrumbPanel_) return;
-
- breadcrumbConnections_.disconnectAll();
- breadcrumbPanel_->clearChildren();
-
- std::string actualRoot = browsingEngineResources_ ? engineResourcesPath_ : rootPath_;
- std::string rootDisplayName = browsingEngineResources_ ? "Engine" : "Project";
-
- std::string normalizedCurrent = currentPath_;
- std::string normalizedRoot = actualRoot;
- for (char& c : normalizedCurrent) { if (c == '\\') c = '/'; }
- for (char& c : normalizedRoot) { if (c == '\\') c = '/'; }
-
- std::vector<std::pair<std::string, std::string>> segments;
- segments.emplace_back(rootDisplayName, actualRoot);
-
- if (normalizedCurrent.size() > normalizedRoot.size() &&
- normalizedCurrent.substr(0, normalizedRoot.size()) == normalizedRoot) {
- std::string relativePath = normalizedCurrent.substr(normalizedRoot.size());
- if (!relativePath.empty() && relativePath[0] == '/') {
- relativePath = relativePath.substr(1);
- }
-
- std::string accumulated = actualRoot;
- std::string segment;
- for (char c : relativePath) {
- if (c == '/') {
- if (!segment.empty()) {
- accumulated += "/" + segment;
- segments.emplace_back(segment, accumulated);
- segment.clear();
- }
- } else {
- segment += c;
- }
- }
- if (!segment.empty()) {
- accumulated += "/" + segment;
- segments.emplace_back(segment, accumulated);
- }
- }
-
- constexpr glm::vec4 textColor{0.6f, 0.6f, 0.6f, 1.0f};
- constexpr glm::vec4 sepColor{0.4f, 0.4f, 0.4f, 1.0f};
-
- for (usize i = 0; i < segments.size(); ++i) {
- const auto& [name, fullPath] = segments[i];
-
- if (i > 0) {
- auto sep = makeUnique<ui::Label>(
- ui::WidgetId::indexed(breadcrumbPanel_->getId().path, "sep", static_cast<u32>(i)),
- icons::ChevronRight
- );
- sep->setIsIconFont(true);
- sep->setFontSize(10.0f);
- sep->setColor(sepColor);
- sep->setWidth(ui::SizeValue::autoSize());
- sep->setHeight(ui::SizeValue::px(26.0f));
- breadcrumbPanel_->addChild(std::move(sep));
- }
-
- auto btn = makeUnique<ui::Button>(
- ui::WidgetId::indexed(breadcrumbPanel_->getId().path, "seg", static_cast<u32>(i)),
- name
- );
- btn->setFontSize(11.0f);
- btn->setWidth(ui::SizeValue::autoSize());
- btn->setHeight(ui::SizeValue::px(22.0f));
- btn->setBackgroundColor(glm::vec4(0.0f));
- btn->setHoverColor({0.235f, 0.235f, 0.235f, 1.0f});
- btn->setTextColor(textColor);
-
- std::string pathCopy = fullPath;
- breadcrumbConnections_.add(sink(btn->onClick).connect([this, pathCopy]() {
- navigateToPath(pathCopy);
- }));
-
- breadcrumbPanel_->addChild(std::move(btn));
- }
-}
-
-void AssetBrowserPanel::updateViewModeButtons() {
- if (!viewModePanel_) return;
-
- constexpr glm::vec4 activeBg{0.235f, 0.235f, 0.235f, 1.0f};
- constexpr glm::vec4 inactiveBg{0.0f, 0.0f, 0.0f, 0.0f};
-
- auto& children = viewModePanel_->getChildren();
- if (children.size() >= 2) {
- auto* gridBtn = dynamic_cast<ui::Button*>(children[0].get());
- auto* listBtn = dynamic_cast<ui::Button*>(children[1].get());
-
- if (gridBtn) {
- gridBtn->setBackgroundColor(viewMode_ == AssetViewMode::Grid ? activeBg : inactiveBg);
- }
- if (listBtn) {
- listBtn->setBackgroundColor(viewMode_ == AssetViewMode::List ? activeBg : inactiveBg);
- }
- }
-}
-
-void AssetBrowserPanel::navigateToPath(const std::string& path) {
- if (currentPath_ == path) return;
-
- // Defer navigation to avoid deleting objects during their event handlers
- pendingNavigatePath_ = path;
- needsRefreshAssetList_ = true;
-}
-
-void AssetBrowserPanel::importAsset() {
-#ifdef ES_PLATFORM_WEB
- ES_LOG_WARN("Import not available on web platform");
- return;
-#endif
-
- std::vector<FileFilter> filters = {
- {"Images", "*.png;*.jpg;*.jpeg;*.bmp;*.tga"},
- {"Audio", "*.wav;*.mp3;*.ogg"},
- {"3D Models", "*.fbx;*.gltf;*.glb;*.obj"},
- {"All Files", "*.*"}
- };
-
- std::string sourcePath = FileDialog::openFile("Import Asset", filters);
- if (sourcePath.empty()) return;
-
- std::string fileName = getFileName(sourcePath);
- std::string destPath = currentPath_ + "/" + fileName;
-
- std::error_code ec;
- std::filesystem::copy_file(sourcePath, destPath, std::filesystem::copy_options::overwrite_existing, ec);
-
- if (!ec) {
- ES_LOG_INFO("Imported asset: {} -> {}", sourcePath, destPath);
- refreshAssetList();
- } else {
- ES_LOG_ERROR("Failed to import asset: {}", ec.message());
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/AssetBrowserPanel.hpp b/src/esengine/editor/panels/AssetBrowserPanel.hpp
deleted file mode 100644
index 0a4d43247..000000000
--- a/src/esengine/editor/panels/AssetBrowserPanel.hpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * @file AssetBrowserPanel.hpp
- * @brief Asset browser panel for the editor
- * @details Provides a file browser interface for navigating and managing
- * project assets with folder tree and grid view.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../ui/docking/DockPanel.hpp"
-#include "../../ui/widgets/TreeView.hpp"
-#include "../../ui/widgets/ScrollView.hpp"
-#include "../../ui/widgets/TextField.hpp"
-#include "../../ui/widgets/Panel.hpp"
-#include "../../ui/widgets/Label.hpp"
-#include "../../ui/widgets/ContextMenu.hpp"
-#include "../../events/Connection.hpp"
-#include "AssetBrowserTypes.hpp"
-
-#include <unordered_map>
-#include <unordered_set>
-#include <vector>
-#include <functional>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Forward Declarations
-// =============================================================================
-
-class AssetDatabase;
-class ThumbnailGenerator;
-
-// =============================================================================
-// AssetBrowserPanel Class
-// =============================================================================
-
-class AssetBrowserPanel : public ui::DockPanel {
-public:
- AssetBrowserPanel(AssetDatabase& assetDB, ThumbnailGenerator& thumbnailGen);
- ~AssetBrowserPanel() override;
-
- void refresh();
- void setRootPath(const std::string& path);
- const std::string& getRootPath() const { return rootPath_; }
-
- void setViewMode(AssetViewMode mode);
- AssetViewMode getViewMode() const { return viewMode_; }
-
- Signal<void(const std::string&)> onAssetSelected;
- Signal<void(const std::string&)> onAssetDoubleClicked;
-
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- void onActivated() override;
-
-private:
- void buildUI();
- void rebuildFolderTree();
- void addFolderNodes(const std::string& path, ui::TreeNodeId parentNode, bool isEngine = false);
- void refreshAssetList();
-
- void onFolderSelected(ui::TreeNodeId nodeId);
- void onSearchTextChanged(const std::string& text);
- void onAssetItemClicked(const std::string& path);
- void onAssetItemDoubleClicked(const std::string& path);
- void onContextMenuItemSelected(const std::string& itemId);
-
- void createFolder();
- void createScene();
- void createScript();
- void deleteSelectedAsset();
- void renameSelectedAsset();
-
- std::string getFileName(const std::string& path) const;
- std::string getFileExtension(const std::string& path) const;
- std::string toLower(const std::string& str) const;
- void rebuildBreadcrumb();
- void updateViewModeButtons();
- void navigateToPath(const std::string& path);
- void importAsset();
-
- std::string rootPath_;
- std::string currentPath_;
- std::string engineResourcesPath_;
- AssetViewMode viewMode_ = AssetViewMode::Grid;
- bool browsingEngineResources_ = false;
-
- ui::Panel* leftPanel_ = nullptr;
- ui::Panel* rightPanel_ = nullptr;
- ui::TreeView* folderTree_ = nullptr;
- ui::TextField* searchField_ = nullptr;
- ui::ScrollView* assetScrollView_ = nullptr;
- ui::Panel* assetGridPanel_ = nullptr;
- ui::Label* statusLabel_ = nullptr;
- ui::Panel* breadcrumbPanel_ = nullptr;
- ui::Panel* viewModePanel_ = nullptr;
-
- std::vector<AssetEntry> currentAssets_;
- std::unordered_map<ui::TreeNodeId, std::string> nodeToPath_;
- std::unordered_map<std::string, ui::TreeNodeId> pathToNode_;
- std::unordered_set<ui::TreeNodeId> engineNodes_;
- std::string searchFilter_;
-
- std::string selectedAssetPath_;
- bool needsRebuild_ = false;
- bool needsRefreshAssetList_ = false;
- std::string pendingNavigatePath_;
-
- AssetDatabase& assetDB_;
- ThumbnailGenerator& thumbnailGen_;
-
- Connection folderSelectedConnection_;
- Connection searchChangedConnection_;
- ConnectionHolder itemConnections_;
- ConnectionHolder breadcrumbConnections_;
- ConnectionHolder toolbarConnections_;
-
- Unique<ui::ContextMenu> contextMenu_;
- Connection contextMenuItemSelectedConnection_;
- Connection contextMenuClosedConnection_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/AssetBrowserTypes.hpp b/src/esengine/editor/panels/AssetBrowserTypes.hpp
deleted file mode 100644
index ba9185c3e..000000000
--- a/src/esengine/editor/panels/AssetBrowserTypes.hpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * @file AssetBrowserTypes.hpp
- * @brief Type definitions for the asset browser
- *
- * @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 <string>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Enumerations
-// =============================================================================
-
-enum class AssetType : u8 {
- Unknown,
- Folder,
- Texture,
- Audio,
- Script,
- Shader,
- Scene,
- Prefab,
- Font
-};
-
-enum class AssetViewMode : u8 {
- Grid,
- List
-};
-
-// =============================================================================
-// Data Structures
-// =============================================================================
-
-struct AssetEntry {
- std::string name;
- std::string path;
- std::string extension;
- AssetType type = AssetType::Unknown;
- usize fileSize = 0;
- u64 modificationTime = 0;
- bool isDirectory = false;
-};
-
-// =============================================================================
-// Utility Functions
-// =============================================================================
-
-inline AssetType getAssetTypeFromExtension(const std::string& ext) {
- if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".tga") {
- return AssetType::Texture;
- }
- if (ext == ".wav" || ext == ".mp3" || ext == ".ogg") {
- return AssetType::Audio;
- }
- if (ext == ".js" || ext == ".ts") {
- return AssetType::Script;
- }
- if (ext == ".glsl" || ext == ".vert" || ext == ".frag") {
- return AssetType::Shader;
- }
- if (ext == ".scene" || ext == ".scene.json") {
- return AssetType::Scene;
- }
- if (ext == ".prefab" || ext == ".prefab.json") {
- return AssetType::Prefab;
- }
- if (ext == ".ttf" || ext == ".otf") {
- return AssetType::Font;
- }
- return AssetType::Unknown;
-}
-
-inline glm::vec4 getAssetTypeColor(AssetType type) {
- switch (type) {
- case AssetType::Folder: return {0.863f, 0.714f, 0.478f, 1.0f}; // #dcb67a
- case AssetType::Texture: return {0.925f, 0.251f, 0.478f, 1.0f}; // #ec407a
- case AssetType::Audio: return {1.0f, 0.655f, 0.149f, 1.0f}; // #ffa726
- case AssetType::Script: return {0.259f, 0.647f, 0.961f, 1.0f}; // #42a5f5
- case AssetType::Shader: return {0.545f, 0.361f, 0.965f, 1.0f}; // #8b5cf6
- case AssetType::Scene: return {0.4f, 0.733f, 0.416f, 1.0f}; // #66bb6a
- case AssetType::Prefab: return {0.149f, 0.651f, 0.604f, 1.0f}; // #26a69a
- case AssetType::Font: return {0.565f, 0.792f, 0.976f, 1.0f}; // #90caf9
- default: return {0.565f, 0.792f, 0.976f, 1.0f}; // #90caf9
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/AssetGridItem.cpp b/src/esengine/editor/panels/AssetGridItem.cpp
deleted file mode 100644
index 2d6653b63..000000000
--- a/src/esengine/editor/panels/AssetGridItem.cpp
+++ /dev/null
@@ -1,234 +0,0 @@
-/**
- * @file AssetGridItem.cpp
- * @brief Grid item widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "AssetGridItem.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/icons/Icons.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-
-#include <chrono>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Helper Functions
-// =============================================================================
-
-namespace {
-
-f64 getCurrentTimeSeconds() {
- auto now = std::chrono::steady_clock::now();
- auto duration = now.time_since_epoch();
- return std::chrono::duration<f64>(duration).count();
-}
-
-const char* getAssetTypeIcon(AssetType type) {
- using namespace ui::icons;
- switch (type) {
- case AssetType::Folder: return Folder;
- case AssetType::Texture: return Image;
- case AssetType::Audio: return Music;
- case AssetType::Script: return FileCode;
- case AssetType::Scene: return Layers;
- case AssetType::Prefab: return Box;
- case AssetType::Shader: return Code;
- case AssetType::Font: return FileText;
- default: return File;
- }
-}
-
-template<typename FontType>
-std::string truncateText(const std::string& text, FontType& font, f32 fontSize, f32 maxWidth) {
- glm::vec2 textSize = font.measureText(text, fontSize);
- if (textSize.x <= maxWidth) {
- return text;
- }
-
- const std::string ellipsis = "...";
- f32 ellipsisWidth = font.measureText(ellipsis, fontSize).x;
- f32 availableWidth = maxWidth - ellipsisWidth;
-
- if (availableWidth <= 0) {
- return ellipsis;
- }
-
- std::string result;
- f32 currentWidth = 0.0f;
- const u8* ptr = reinterpret_cast<const u8*>(text.data());
- const u8* end = ptr + text.size();
-
- while (ptr < end) {
- const u8* charStart = ptr;
- u32 codepoint;
-
- if ((*ptr & 0x80) == 0) {
- codepoint = *ptr++;
- } else if ((*ptr & 0xE0) == 0xC0) {
- codepoint = (*ptr++ & 0x1F) << 6;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F);
- } else if ((*ptr & 0xF0) == 0xE0) {
- codepoint = (*ptr++ & 0x0F) << 12;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F);
- } else if ((*ptr & 0xF8) == 0xF0) {
- codepoint = (*ptr++ & 0x07) << 18;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 12;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F);
- } else {
- ptr++;
- continue;
- }
-
- f32 charWidth = font.getCharWidth(codepoint, fontSize);
- if (currentWidth + charWidth > availableWidth) {
- break;
- }
-
- currentWidth += charWidth;
- result.append(reinterpret_cast<const char*>(charStart),
- static_cast<usize>(ptr - charStart));
- }
-
- return result + ellipsis;
-}
-
-} // namespace
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-AssetGridItem::AssetGridItem(const ui::WidgetId& id, const AssetEntry& entry)
- : Widget(id), entry_(entry) {
- setWidth(ui::SizeValue::px(ITEM_WIDTH));
- setHeight(ui::SizeValue::px(ITEM_HEIGHT));
-}
-
-void AssetGridItem::setSelected(bool selected) {
- selected_ = selected;
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 AssetGridItem::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableWidth;
- (void)availableHeight;
- return {ITEM_WIDTH, ITEM_HEIGHT};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void AssetGridItem::render(ui::UIBatchRenderer& renderer) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- ui::Rect bounds = getBounds();
-
- if (bounds.width <= 0 || bounds.height <= 0) {
- return;
- }
-
- constexpr glm::vec4 selectedBg{0.035f, 0.278f, 0.443f, 1.0f}; // #094771
- constexpr glm::vec4 selectedBorder{0.231f, 0.510f, 0.965f, 1.0f}; // #3b82f6
- constexpr glm::vec4 hoverBg{0.176f, 0.176f, 0.188f, 1.0f}; // #2d2d30
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
-
- if (selected_) {
- renderer.drawRoundedRect(bounds, selectedBg, ui::CornerRadii::all(4.0f));
- renderer.drawRoundedRectOutline(bounds, selectedBorder, ui::CornerRadii::all(4.0f), 1.0f);
- } else if (isHovered()) {
- renderer.drawRoundedRect(bounds, hoverBg, ui::CornerRadii::all(4.0f));
- }
-
- f32 iconX = bounds.x + (bounds.width - ICON_SIZE) * 0.5f;
- f32 iconY = bounds.y + ICON_PADDING;
- ui::Rect iconBounds{iconX, iconY, ICON_SIZE, ICON_SIZE};
-
- constexpr glm::vec4 thumbnailBg{0.102f, 0.102f, 0.102f, 1.0f}; // #1a1a1a
- constexpr glm::vec4 thumbnailBorder{0.2f, 0.2f, 0.2f, 1.0f}; // #333
- renderer.drawRoundedRect(iconBounds, thumbnailBg, ui::CornerRadii::all(4.0f));
- renderer.drawRoundedRectOutline(iconBounds, thumbnailBorder, ui::CornerRadii::all(4.0f), 1.0f);
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* iconFont = ctx->getIconMSDFFont();
- ui::MSDFFont* font = ctx->getDefaultMSDFFont();
-#else
- ui::SystemFont* iconFont = ctx->getIconSystemFont();
- ui::SystemFont* font = ctx->getDefaultSystemFont();
-#endif
-
- if (iconFont) {
- glm::vec4 iconColor = getAssetTypeColor(entry_.type);
- const char* icon = getAssetTypeIcon(entry_.type);
- renderer.drawTextInBounds(icon, iconBounds, *iconFont, 32.0f, iconColor,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (font) {
- f32 labelWidth = bounds.width - 8.0f;
- ui::Rect labelBounds{
- bounds.x + 4.0f,
- bounds.y + ICON_PADDING + ICON_SIZE + 6.0f,
- labelWidth,
- LABEL_HEIGHT
- };
-
- std::string displayName = truncateText(entry_.name, *font, 11.0f, labelWidth);
- renderer.drawTextInBounds(
- displayName,
- labelBounds,
- *font,
- 11.0f,
- textColor,
- ui::HAlign::Center,
- ui::VAlign::Top
- );
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool AssetGridItem::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button == ui::MouseButton::Left) {
- f64 currentTime = getCurrentTimeSeconds();
- constexpr f64 DOUBLE_CLICK_THRESHOLD = 0.3;
-
- if (currentTime - lastClickTime_ < DOUBLE_CLICK_THRESHOLD) {
- onDoubleClick.publish(entry_.path);
- lastClickTime_ = 0.0;
- } else {
- onClick.publish(entry_.path);
- lastClickTime_ = currentTime;
- }
- return true;
- }
- return false;
-}
-
-bool AssetGridItem::onMouseUp(const ui::MouseButtonEvent& event) {
- (void)event;
- return false;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/AssetGridItem.hpp b/src/esengine/editor/panels/AssetGridItem.hpp
deleted file mode 100644
index 4a2ca7989..000000000
--- a/src/esengine/editor/panels/AssetGridItem.hpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * @file AssetGridItem.hpp
- * @brief Grid item widget for displaying assets in the browser
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-#include "AssetBrowserTypes.hpp"
-
-#include <glm/glm.hpp>
-
-namespace esengine::editor {
-
-// =============================================================================
-// AssetGridItem Class
-// =============================================================================
-
-class AssetGridItem : public ui::Widget {
-public:
- static constexpr f32 ITEM_WIDTH = 90.0f;
- static constexpr f32 ITEM_HEIGHT = 110.0f;
- static constexpr f32 ICON_SIZE = 64.0f;
- static constexpr f32 ICON_PADDING = 12.0f;
- static constexpr f32 LABEL_HEIGHT = 30.0f;
-
- AssetGridItem(const ui::WidgetId& id, const AssetEntry& entry);
-
- const AssetEntry& getEntry() const { return entry_; }
-
- void setSelected(bool selected);
- bool isSelected() const { return selected_; }
-
- Signal<void(const std::string&)> onClick;
- Signal<void(const std::string&)> onDoubleClick;
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseUp(const ui::MouseButtonEvent& event) override;
-
-private:
- AssetEntry entry_;
- bool selected_ = false;
- f64 lastClickTime_ = 0.0;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/GameViewPanel.cpp b/src/esengine/editor/panels/GameViewPanel.cpp
deleted file mode 100644
index a5b7661c4..000000000
--- a/src/esengine/editor/panels/GameViewPanel.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/**
- * @file GameViewPanel.cpp
- * @brief Game view panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "GameViewPanel.hpp"
-#include "../../renderer/RenderCommand.hpp"
-#include "../../renderer/RenderContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../ecs/components/Camera.hpp"
-#include "../../ecs/components/Canvas.hpp"
-#include "../../ecs/components/Sprite.hpp"
-#include "../../math/Math.hpp"
-
-#include <glad/glad.h>
-
-#ifndef GL_VIEWPORT
-#define GL_VIEWPORT 0x0BA2
-#endif
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-GameViewPanel::GameViewPanel(ecs::Registry& registry, resource::ResourceManager& resourceManager)
- : DockPanel(ui::WidgetId("game_view_panel"), "Game"),
- registry_(registry),
- resourceManager_(resourceManager) {
-
- FramebufferSpec spec;
- spec.width = viewport_width_;
- spec.height = viewport_height_;
- spec.depthStencil = true;
- framebuffer_ = Framebuffer::create(spec);
-
- setMinSize(glm::vec2(200.0f, 200.0f));
-}
-
-// =============================================================================
-// Configuration
-// =============================================================================
-
-void GameViewPanel::setViewportSize(u32 width, u32 height) {
- if (width == viewport_width_ && height == viewport_height_) {
- return;
- }
-
- viewport_width_ = width;
- viewport_height_ = height;
- framebuffer_needs_resize_ = true;
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void GameViewPanel::render(ui::UIBatchRenderer& renderer) {
- const ui::Rect& bounds = getBounds();
-
- u32 newWidth = static_cast<u32>(bounds.width);
- u32 newHeight = static_cast<u32>(bounds.height);
-
- if (newWidth != viewport_width_ || newHeight != viewport_height_) {
- setViewportSize(newWidth, newHeight);
- }
-
- if (framebuffer_needs_resize_) {
- updateFramebufferSize();
- }
-
- if (framebuffer_) {
- renderGameToTexture();
-
- renderer.drawTexturedRect(
- bounds,
- framebuffer_->getColorAttachment(),
- glm::vec4(1.0f),
- glm::vec2(0.0f, 1.0f),
- glm::vec2(1.0f, 0.0f)
- );
- }
-}
-
-void GameViewPanel::renderGameToTexture() {
- if (!framebuffer_) {
- return;
- }
-
- GLint savedViewport[4];
- glGetIntegerv(GL_VIEWPORT, savedViewport);
-
- framebuffer_->bind();
-
- RenderCommand::setViewport(0, 0, viewport_width_, viewport_height_);
-
- Entity canvasEntity = findCanvas();
- ecs::Canvas* canvas = canvasEntity != INVALID_ENTITY
- ? registry_.tryGet<ecs::Canvas>(canvasEntity)
- : nullptr;
-
- glm::vec4 clearColor = canvas ? canvas->backgroundColor : glm::vec4(0.1f, 0.1f, 0.1f, 1.0f);
- RenderCommand::setClearColor(clearColor);
- RenderCommand::clear();
-
- Entity cameraEntity = findActiveCamera();
- if (cameraEntity != INVALID_ENTITY) {
- auto* transform = registry_.tryGet<ecs::LocalTransform>(cameraEntity);
- auto* camera = registry_.tryGet<ecs::Camera>(cameraEntity);
-
- if (transform && camera) {
- glm::mat4 view = glm::inverse(
- glm::translate(glm::mat4(1.0f), transform->position) *
- glm::mat4_cast(transform->rotation)
- );
-
- f32 viewportAspect = static_cast<f32>(viewport_width_) / static_cast<f32>(viewport_height_);
-
- glm::mat4 proj;
- if (camera->projectionType == ecs::ProjectionType::Perspective) {
- f32 aspectRatio = camera->aspectRatio > 0.0f ? camera->aspectRatio : viewportAspect;
- proj = glm::perspective(
- glm::radians(camera->fov),
- aspectRatio,
- camera->nearPlane,
- camera->farPlane
- );
- } else {
- f32 orthoHeight = camera->orthoSize;
- f32 orthoWidth = orthoHeight * viewportAspect;
-
- if (canvas) {
- orthoHeight = canvas->getOrthoSize();
- f32 designAspect = canvas->getDesignAspectRatio();
-
- switch (canvas->scaleMode) {
- case ecs::CanvasScaleMode::FixedHeight:
- orthoWidth = orthoHeight * viewportAspect;
- break;
- case ecs::CanvasScaleMode::FixedWidth:
- orthoWidth = canvas->getWorldSize().x * 0.5f;
- orthoHeight = orthoWidth / viewportAspect;
- break;
- case ecs::CanvasScaleMode::Expand:
- if (viewportAspect > designAspect) {
- orthoWidth = orthoHeight * viewportAspect;
- } else {
- orthoHeight = orthoWidth / viewportAspect;
- }
- break;
- case ecs::CanvasScaleMode::Shrink:
- if (viewportAspect < designAspect) {
- orthoWidth = orthoHeight * viewportAspect;
- } else {
- orthoHeight = orthoWidth / viewportAspect;
- }
- break;
- case ecs::CanvasScaleMode::Match: {
- f32 logWidth = glm::log2(viewportAspect / designAspect);
- f32 blend = canvas->matchWidthOrHeight;
- f32 scaleFactor = glm::pow(2.0f, logWidth * (1.0f - blend));
- orthoWidth = orthoHeight * designAspect * scaleFactor;
- orthoHeight = orthoWidth / viewportAspect;
- break;
- }
- }
- }
-
- proj = glm::ortho(
- -orthoWidth, orthoWidth,
- -orthoHeight, orthoHeight,
- camera->nearPlane, camera->farPlane
- );
- }
-
- glm::mat4 viewProj = proj * view;
- renderSceneContent(viewProj);
- }
- }
-
- framebuffer_->unbind();
-
- glViewport(savedViewport[0], savedViewport[1], savedViewport[2], savedViewport[3]);
-}
-
-void GameViewPanel::renderSceneContent(const glm::mat4& viewProj) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- RenderContext& renderCtx = ctx->getRenderContext();
-
- if (!render_pipeline_) {
- render_pipeline_ = makeUnique<RenderPipeline>(renderCtx, resourceManager_);
- }
-
- render_pipeline_->begin(viewProj);
- render_pipeline_->submit(registry_);
- render_pipeline_->end();
-}
-
-void GameViewPanel::updateFramebufferSize() {
- if (viewport_width_ == 0 || viewport_height_ == 0) {
- return;
- }
-
- if (framebuffer_) {
- framebuffer_->resize(viewport_width_, viewport_height_);
- framebuffer_needs_resize_ = false;
- }
-}
-
-Entity GameViewPanel::findActiveCamera() {
- auto view = registry_.view<ecs::Camera>();
-
- Entity bestCamera = INVALID_ENTITY;
- i32 bestPriority = std::numeric_limits<i32>::min();
-
- for (auto entity : view) {
- const auto& camera = view.get(entity);
- if (camera.isActive && camera.priority > bestPriority) {
- bestCamera = entity;
- bestPriority = camera.priority;
- }
- }
-
- return bestCamera;
-}
-
-Entity GameViewPanel::findCanvas() {
- auto view = registry_.view<ecs::Canvas>();
- for (auto entity : view) {
- return entity;
- }
- return INVALID_ENTITY;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/GameViewPanel.hpp b/src/esengine/editor/panels/GameViewPanel.hpp
deleted file mode 100644
index 133f1fd74..000000000
--- a/src/esengine/editor/panels/GameViewPanel.hpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * @file GameViewPanel.hpp
- * @brief Game viewport panel showing the game camera view
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../ui/docking/DockPanel.hpp"
-#include "../../renderer/Framebuffer.hpp"
-#include "../../renderer/RenderPipeline.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../resource/ResourceManager.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// GameViewPanel Class
-// =============================================================================
-
-/**
- * @brief Game viewport panel showing the active game camera view
- *
- * @details Unlike SceneViewPanel which uses an EditorCamera for free navigation,
- * GameViewPanel renders from the perspective of the active game camera
- * (an entity with Camera component where isActive=true).
- */
-class GameViewPanel : public ui::DockPanel {
-public:
- GameViewPanel(ecs::Registry& registry, resource::ResourceManager& resourceManager);
- ~GameViewPanel() override = default;
-
- void setViewportSize(u32 width, u32 height);
-
- void render(ui::UIBatchRenderer& renderer) override;
-
-private:
- void renderGameToTexture();
- void renderSceneContent(const glm::mat4& viewProj);
- void updateFramebufferSize();
- Entity findActiveCamera();
- Entity findCanvas();
-
- ecs::Registry& registry_;
- resource::ResourceManager& resourceManager_;
- Unique<Framebuffer> framebuffer_;
- Unique<RenderPipeline> render_pipeline_;
-
- u32 viewport_width_ = 1280;
- u32 viewport_height_ = 720;
- bool framebuffer_needs_resize_ = false;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/HierarchyPanel.cpp b/src/esengine/editor/panels/HierarchyPanel.cpp
deleted file mode 100644
index 431db0091..000000000
--- a/src/esengine/editor/panels/HierarchyPanel.cpp
+++ /dev/null
@@ -1,711 +0,0 @@
-/**
- * @file HierarchyPanel.cpp
- * @brief Hierarchy panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "HierarchyPanel.hpp"
-#include "../../ecs/components/Common.hpp"
-#include "../../ecs/components/Hierarchy.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../ecs/components/Camera.hpp"
-#include "../../ecs/components/Sprite.hpp"
-#include "../../core/Log.hpp"
-#include "../../events/Sink.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/layout/StackLayout.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/icons/Icons.hpp"
-
-#include <algorithm>
-#include <cctype>
-#include <sstream>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-HierarchyPanel::HierarchyPanel(ecs::Registry& registry, EntitySelection& selection)
- : DockPanel(ui::WidgetId("hierarchy_panel"), "Hierarchy"),
- registry_(registry),
- selection_(selection) {
-
- setPanelType("Hierarchy");
- setClosable(false);
- setMinSize(glm::vec2(280.0f, 200.0f));
-
- buildUI();
-
- nodeSelectedConnection_ = sink(treeView_->onNodeSelected).connect(
- [this](ui::TreeNodeId nodeId) { onNodeSelected(nodeId); }
- );
-
- nodeDoubleClickedConnection_ = sink(treeView_->onNodeDoubleClicked).connect(
- [this](ui::TreeNodeId nodeId) { onNodeDoubleClicked(nodeId); }
- );
-
- nodeRightClickedConnection_ = sink(treeView_->onNodeRightClicked).connect(
- [this](ui::TreeNodeId nodeId, f32 x, f32 y) { onNodeRightClicked(nodeId, x, y); }
- );
-
- searchChangedConnection_ = sink(searchField_->onTextChanged).connect(
- [this](const std::string& text) { onSearchTextChanged(text); }
- );
-
- addEntityClickedConnection_ = sink(addEntityButton_->onClick).connect(
- [this]() { createEntity(); }
- );
-
- createFolderClickedConnection_ = sink(createFolderButton_->onClick).connect(
- [this]() { createFolder(); }
- );
-
- contextMenu_ = makeUnique<ui::ContextMenu>(ui::WidgetId("hierarchy_context_menu"));
- contextMenuItemSelectedConnection_ = sink(contextMenu_->onItemSelected).connect(
- [this](const std::string& itemId) { onContextMenuItemSelected(itemId); }
- );
- contextMenuClosedConnection_ = sink(contextMenu_->onClosed).connect(
- [this]() {
- if (getContext()) {
- getContext()->removeOverlay(contextMenu_.get());
- }
- }
- );
-
- u32 listenerId = selection_.addListener(
- [this](const std::vector<Entity>& prev, const std::vector<Entity>& curr) {
- onSelectionChanged(prev, curr);
- }
- );
- selectionChangedConnection_ = Connection(listenerId, [this](CallbackId id) {
- selection_.removeListener(static_cast<u32>(id));
- });
-
- rebuildTree();
-}
-
-HierarchyPanel::~HierarchyPanel() {
- // Connections are automatically cleaned up by Connection RAII
-}
-
-// =============================================================================
-// UI Building
-// =============================================================================
-
-void HierarchyPanel::buildUI() {
- constexpr glm::vec4 toolbarBg{0.2f, 0.2f, 0.2f, 1.0f}; // #333333
- constexpr glm::vec4 mainBg{0.165f, 0.165f, 0.165f, 1.0f}; // #2a2a2a
- constexpr glm::vec4 borderColor{0.102f, 0.102f, 0.102f, 1.0f}; // #1a1a1a
- constexpr glm::vec4 headerIconColor{0.4f, 0.4f, 0.4f, 1.0f}; // #666666
- constexpr glm::vec4 headerTextColor{0.6f, 0.6f, 0.6f, 1.0f}; // #999999
-
- auto rootPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_root"));
- rootPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f));
- rootPanel->setWidth(ui::SizeValue::flex(1.0f));
- rootPanel->setHeight(ui::SizeValue::flex(1.0f));
- rootPanel->setDrawBackground(true);
- rootPanel->setBackgroundColor(mainBg);
-
- // =========================================================================
- // Toolbar
- // =========================================================================
- auto toolbar = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_toolbar"));
- toolbar->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 4.0f));
- toolbar->setHeight(ui::SizeValue::px(34.0f));
- toolbar->setWidth(ui::SizeValue::flex(1.0f));
- toolbar->setPadding(ui::Insets(4.0f, 8.0f, 4.0f, 8.0f));
- toolbar->setDrawBackground(true);
- toolbar->setBackgroundColor(toolbarBg);
- toolbar->setBorderColor(borderColor);
- toolbar->setBorderWidth(ui::BorderWidth(0.0f, 0.0f, 1.0f, 0.0f));
-
- auto filterButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_filter_btn"), ui::icons::Filter);
- filterButton->setButtonStyle(ui::ButtonStyle::Ghost);
- filterButton->setWidth(ui::SizeValue::px(26.0f));
- filterButton->setHeight(ui::SizeValue::px(26.0f));
- filterButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- toolbar->addChild(std::move(filterButton));
-
- auto searchField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + "_search"));
- searchField->setPlaceholder("Search...");
- searchField->setWidth(ui::SizeValue::flex(1.0f));
- searchField->setHeight(ui::SizeValue::px(26.0f));
- searchField_ = searchField.get();
- toolbar->addChild(std::move(searchField));
-
- auto addButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_add_btn"), ui::icons::Plus);
- addButton->setButtonStyle(ui::ButtonStyle::Ghost);
- addButton->setWidth(ui::SizeValue::px(26.0f));
- addButton->setHeight(ui::SizeValue::px(26.0f));
- addButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- addEntityButton_ = addButton.get();
- toolbar->addChild(std::move(addButton));
-
- auto folderButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_folder_btn"), ui::icons::FolderPlus);
- folderButton->setButtonStyle(ui::ButtonStyle::Ghost);
- folderButton->setWidth(ui::SizeValue::px(26.0f));
- folderButton->setHeight(ui::SizeValue::px(26.0f));
- folderButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- createFolderButton_ = folderButton.get();
- toolbar->addChild(std::move(folderButton));
-
- auto settingsButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_settings_btn"), ui::icons::Settings);
- settingsButton->setButtonStyle(ui::ButtonStyle::Ghost);
- settingsButton->setWidth(ui::SizeValue::px(26.0f));
- settingsButton->setHeight(ui::SizeValue::px(26.0f));
- settingsButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- toolbar->addChild(std::move(settingsButton));
-
- toolbar_ = toolbar.get();
- rootPanel->addChild(std::move(toolbar));
-
- // =========================================================================
- // Column Headers
- // =========================================================================
- auto columnHeader = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_header"));
- columnHeader->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 6.0f));
- columnHeader->setHeight(ui::SizeValue::px(24.0f));
- columnHeader->setWidth(ui::SizeValue::flex(1.0f));
- columnHeader->setPadding(ui::Insets(0.0f, 8.0f, 0.0f, 8.0f));
- columnHeader->setDrawBackground(true);
- columnHeader->setBackgroundColor(toolbarBg);
- columnHeader->setBorderColor(borderColor);
- columnHeader->setBorderWidth(ui::BorderWidth(0.0f, 0.0f, 1.0f, 0.0f));
-
- auto headerIcons = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_header_icons"));
- headerIcons->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 6.0f));
- headerIcons->setWidth(ui::SizeValue::px(54.0f));
- headerIcons->setHeight(ui::SizeValue::flex(1.0f));
-
- auto eyeLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_eye_icon"), ui::icons::Eye);
- eyeLabel->setFontSize(12.0f);
- eyeLabel->setColor(headerIconColor);
- eyeLabel->setIsIconFont(true);
- headerIcons->addChild(std::move(eyeLabel));
-
- auto starLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_star_icon"), ui::icons::Star);
- starLabel->setFontSize(12.0f);
- starLabel->setColor(headerIconColor);
- starLabel->setIsIconFont(true);
- headerIcons->addChild(std::move(starLabel));
-
- auto lockLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_lock_icon"), ui::icons::Lock);
- lockLabel->setFontSize(12.0f);
- lockLabel->setColor(headerIconColor);
- lockLabel->setIsIconFont(true);
- headerIcons->addChild(std::move(lockLabel));
-
- columnHeader->addChild(std::move(headerIcons));
-
- auto itemLabelHeader = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label_header"), "Item Label");
- itemLabelHeader->setFontSize(11.0f);
- itemLabelHeader->setColor(headerTextColor);
- itemLabelHeader->setWidth(ui::SizeValue::flex(1.0f));
- itemLabelHeader->setClipContent(true);
- columnHeader->addChild(std::move(itemLabelHeader));
-
- auto typeHeader = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_type_header"), "Type");
- typeHeader->setFontSize(11.0f);
- typeHeader->setColor(headerTextColor);
- typeHeader->setWidth(ui::SizeValue::px(80.0f));
- columnHeader->addChild(std::move(typeHeader));
-
- columnHeader_ = columnHeader.get();
- rootPanel->addChild(std::move(columnHeader));
-
- auto scrollView = makeUnique<ui::ScrollView>(ui::WidgetId(getId().path + "_scroll"));
- scrollView->setScrollDirection(ui::ScrollDirection::Vertical);
- scrollView->setWidth(ui::SizeValue::flex(1.0f));
- scrollView->setHeight(ui::SizeValue::flex(1.0f));
-
- auto treeView = makeUnique<ui::TreeView>(ui::WidgetId(getId().path + "_tree"));
- treeView->setMultiSelect(false);
- treeView->setRowHeight(22.0f);
- treeView->setIndentSize(16.0f);
- treeView->setWidth(ui::SizeValue::flex(1.0f));
- treeView->setHeight(ui::SizeValue::autoSize());
- treeView_ = treeView.get();
-
- scrollView->setContent(std::move(treeView));
- scrollView_ = scrollView.get();
- rootPanel->addChild(std::move(scrollView));
-
- auto statusBar = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_status"));
- statusBar->setHeight(ui::SizeValue::px(24.0f));
- statusBar->setWidth(ui::SizeValue::flex(1.0f));
- statusBar->setPadding(ui::Insets(0.0f, 8.0f, 0.0f, 8.0f));
- statusBar->setDrawBackground(true);
- statusBar->setBackgroundColor(toolbarBg);
- statusBar->setBorderColor(borderColor);
- statusBar->setBorderWidth(ui::BorderWidth(1.0f, 0.0f, 0.0f, 0.0f));
-
- auto entityCountLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_count"), "0 entities");
- entityCountLabel->setFontSize(11.0f);
- entityCountLabel->setColor({0.6f, 0.6f, 0.6f, 1.0f});
- entityCountLabel->setWidth(ui::SizeValue::flex(1.0f));
- entityCountLabel->setHeight(ui::SizeValue::flex(1.0f));
- entityCountLabel_ = entityCountLabel.get();
- statusBar->addChild(std::move(entityCountLabel));
-
- statusBar_ = statusBar.get();
- rootPanel->addChild(std::move(statusBar));
-
- rootPanel_ = rootPanel.get();
- setContent(std::move(rootPanel));
-}
-
-void HierarchyPanel::onSearchTextChanged(const std::string& text) {
- searchFilter_ = text;
- rebuildTree();
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-void HierarchyPanel::render(ui::UIBatchRenderer& renderer) {
- DockPanel::render(renderer);
-}
-
-bool HierarchyPanel::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button == ui::MouseButton::Right) {
- if (scrollView_ && scrollView_->getBounds().contains(event.x, event.y)) {
- contextMenuTargetEntity_ = INVALID_ENTITY;
-
- contextMenu_->clearItems();
- contextMenu_->addItem(ui::MenuItem::action("create_entity", "Create Empty Entity", ui::icons::Plus));
- contextMenu_->addItem(ui::MenuItem::action("create_folder", "Create Folder", ui::icons::FolderPlus));
- contextMenu_->addItem(ui::MenuItem::divider());
- contextMenu_->addItem(ui::MenuItem::action("paste", "Paste", ui::icons::Clipboard, "Ctrl+V"));
-
- if (getContext()) {
- getContext()->addOverlay(contextMenu_.get());
- }
- contextMenu_->show(event.x, event.y);
- return true;
- }
- }
-
- return DockPanel::onMouseDown(event);
-}
-
-bool HierarchyPanel::onKeyDown(const ui::KeyEvent& event) {
- if (event.key == KeyCode::Delete) {
- deleteSelectedEntity();
- return true;
- }
-
- if (event.ctrl && event.key == KeyCode::D) {
- // TODO: Duplicate selected entity
- ES_LOG_INFO("Duplicate entity: not yet implemented");
- return true;
- }
-
- return DockPanel::onKeyDown(event);
-}
-
-// =============================================================================
-// Public Methods
-// =============================================================================
-
-void HierarchyPanel::refresh() {
- rebuildTree();
-}
-
-void HierarchyPanel::setShowOrphans(bool showOrphans) {
- if (showOrphans_ != showOrphans) {
- showOrphans_ = showOrphans;
- needsRebuild_ = true;
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-void HierarchyPanel::onActivated() {
- if (needsRebuild_) {
- rebuildTree();
- needsRebuild_ = false;
- }
-}
-
-void HierarchyPanel::onDeactivated() {
- // Nothing to do
-}
-
-// =============================================================================
-// Tree Building
-// =============================================================================
-
-void HierarchyPanel::rebuildTree() {
- if (!treeView_) {
- return;
- }
-
- // Clear tree and mappings
- treeView_->clear();
- nodeToEntity_.clear();
- entityToNode_.clear();
-
- // Collect all entities
- std::vector<Entity> allEntities;
- registry_.forEachEntity([&allEntities](Entity entity) {
- 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
- std::string lowerFilter = searchFilter_;
- std::transform(lowerFilter.begin(), lowerFilter.end(), lowerFilter.begin(),
- [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
-
- // Build tree starting from root entities (entities without Parent component)
- usize rootCount = 0;
- for (Entity entity : allEntities) {
- // Skip if entity has a parent (will be added as child)
- if (registry_.has<ecs::Parent>(entity)) {
- continue;
- }
-
- // If we have a search filter, check if entity or any descendant matches
- if (!searchFilter_.empty()) {
- bool matches = false;
- std::string displayName = getEntityDisplayName(entity);
- std::string lowerName = displayName;
- std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(),
- [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
- if (lowerName.find(lowerFilter) != std::string::npos) {
- matches = true;
- }
- if (!matches) continue;
- }
-
- // Add as root node
- addEntityToTree(entity, ui::INVALID_TREE_NODE);
- rootCount++;
- }
- ES_LOG_DEBUG("HierarchyPanel::rebuildTree: Added {} root nodes", rootCount);
-
- // Sync with current selection
- if (!selection_.empty()) {
- Entity selectedEntity = selection_.getFirst();
- auto it = entityToNode_.find(selectedEntity);
- if (it != entityToNode_.end()) {
- treeView_->selectNode(it->second, true);
- }
- }
-
- updateStatusBar();
-}
-
-ui::TreeNodeId HierarchyPanel::addEntityToTree(Entity entity, ui::TreeNodeId parentNodeId) {
- std::string displayName = getEntityDisplayName(entity);
-
- ui::TreeNodeId nodeId = treeView_->addNode(parentNodeId, displayName);
-
- treeView_->setNodeIcon(nodeId, getEntityIcon(entity));
- treeView_->setNodeType(nodeId, getEntityType(entity));
-
- nodeToEntity_[nodeId] = entity;
- entityToNode_[entity] = nodeId;
-
- // 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) {
- if (registry_.valid(childEntity)) {
- sortedChildren.push_back(childEntity);
- } else {
- ES_LOG_WARN("HierarchyPanel: Invalid child entity {} for parent {}",
- childEntity, entity);
- }
- }
- 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 (!sortedChildren.empty()) {
- treeView_->setNodeExpanded(nodeId, true);
- }
- }
-
- return nodeId;
-}
-
-std::string HierarchyPanel::getEntityDisplayName(Entity entity) const {
- if (registry_.has<ecs::Name>(entity)) {
- const auto& name = registry_.get<ecs::Name>(entity);
- if (!name.value.empty()) {
- return name.value;
- }
- }
-
- std::ostringstream oss;
- oss << "Entity " << entity;
- return oss.str();
-}
-
-std::string HierarchyPanel::getEntityIcon(Entity entity) const {
- if (registry_.has<ecs::Folder>(entity)) {
- return ui::icons::Folder;
- }
- if (registry_.has<ecs::Camera>(entity)) {
- return ui::icons::Camera;
- }
- if (registry_.has<ecs::Sprite>(entity)) {
- return ui::icons::Image;
- }
- return ui::icons::Box;
-}
-
-std::string HierarchyPanel::getEntityType(Entity entity) const {
- if (registry_.has<ecs::Folder>(entity)) {
- return "Folder";
- }
- if (registry_.has<ecs::Camera>(entity)) {
- return "Camera";
- }
- if (registry_.has<ecs::Sprite>(entity)) {
- return "Sprite";
- }
- return "Entity";
-}
-
-// =============================================================================
-// Event Handlers
-// =============================================================================
-
-void HierarchyPanel::onNodeSelected(ui::TreeNodeId nodeId) {
- if (processingSelection_) {
- return;
- }
-
- Entity entity = getEntityForNode(nodeId);
- if (entity == INVALID_ENTITY) {
- return;
- }
-
- if (!selection_.isSelected(entity)) {
- processingSelection_ = true;
- selection_.select(entity);
- processingSelection_ = false;
- }
-}
-
-void HierarchyPanel::onNodeDoubleClicked(ui::TreeNodeId nodeId) {
- (void)nodeId;
-}
-
-void HierarchyPanel::onNodeRightClicked(ui::TreeNodeId nodeId, f32 x, f32 y) {
- ES_LOG_DEBUG("HierarchyPanel::onNodeRightClicked nodeId={} x={} y={}", nodeId, x, y);
-
- Entity entity = getEntityForNode(nodeId);
- if (entity == INVALID_ENTITY) {
- ES_LOG_DEBUG(" -> entity not found for node");
- return;
- }
-
- contextMenuTargetEntity_ = entity;
-
- contextMenu_->clearItems();
- contextMenu_->addItem(ui::MenuItem::action("create_entity", "Create Empty Entity", ui::icons::Plus));
- contextMenu_->addItem(ui::MenuItem::action("create_child", "Create Child Entity", ui::icons::Plus));
- contextMenu_->addItem(ui::MenuItem::action("create_folder", "Create Folder", ui::icons::FolderPlus));
- contextMenu_->addItem(ui::MenuItem::divider());
- contextMenu_->addItem(ui::MenuItem::action("rename", "Rename", ui::icons::Edit2, "F2"));
- contextMenu_->addItem(ui::MenuItem::action("duplicate", "Duplicate", ui::icons::Copy, "Ctrl+D"));
- contextMenu_->addItem(ui::MenuItem::divider());
- contextMenu_->addItem(ui::MenuItem::action("delete", "Delete", ui::icons::Trash2, "Del"));
-
- if (getContext()) {
- getContext()->addOverlay(contextMenu_.get());
- }
- contextMenu_->show(x, y);
-}
-
-void HierarchyPanel::onContextMenuItemSelected(const std::string& itemId) {
- if (getContext()) {
- getContext()->removeOverlay(contextMenu_.get());
- }
-
- if (itemId == "create_entity") {
- createEntity();
- } else if (itemId == "create_child") {
- if (contextMenuTargetEntity_ != INVALID_ENTITY) {
- createChildEntity(contextMenuTargetEntity_);
- }
- } else if (itemId == "create_folder") {
- createFolder();
- } else if (itemId == "rename") {
- renameSelectedEntity();
- } else if (itemId == "duplicate") {
- // TODO: Implement entity duplication
- ES_LOG_INFO("Duplicate entity: not yet implemented");
- } else if (itemId == "delete") {
- deleteSelectedEntity();
- }
-
- contextMenuTargetEntity_ = INVALID_ENTITY;
-}
-
-void HierarchyPanel::onSelectionChanged(const std::vector<Entity>& previous,
- const std::vector<Entity>& current) {
- if (!treeView_ || processingSelection_) {
- return;
- }
-
- processingSelection_ = true;
-
- for (Entity entity : previous) {
- auto it = entityToNode_.find(entity);
- if (it != entityToNode_.end()) {
- treeView_->deselectNode(it->second);
- }
- }
-
- for (Entity entity : current) {
- auto it = entityToNode_.find(entity);
- if (it != entityToNode_.end()) {
- treeView_->selectNode(it->second, false);
- }
- }
-
- processingSelection_ = false;
-}
-
-// =============================================================================
-// Entity Operations
-// =============================================================================
-
-void HierarchyPanel::createEntity() {
- Entity entity = registry_.create();
-
- registry_.emplace<ecs::Name>(entity, ecs::Name{"Entity"});
- registry_.emplace<ecs::LocalTransform>(entity);
-
- rebuildTree();
- selection_.select(entity);
-
- ES_LOG_DEBUG("Created entity: {}", entity);
-}
-
-void HierarchyPanel::createChildEntity(Entity parent) {
- if (!registry_.valid(parent)) {
- return;
- }
-
- Entity child = registry_.create();
- registry_.emplace<ecs::Name>(child, ecs::Name{"Entity"});
- registry_.emplace<ecs::LocalTransform>(child);
- registry_.emplace<ecs::Parent>(child, parent);
-
- if (!registry_.has<ecs::Children>(parent)) {
- registry_.emplace<ecs::Children>(parent);
- }
- registry_.get<ecs::Children>(parent).entities.push_back(child);
-
- rebuildTree();
- selection_.select(child);
-
- ES_LOG_DEBUG("Created child entity: {} under parent: {}", child, parent);
-}
-
-void HierarchyPanel::createFolder() {
- Entity folder = registry_.create();
- registry_.emplace<ecs::Name>(folder, ecs::Name{"Folder"});
- registry_.emplace<ecs::Folder>(folder);
-
- rebuildTree();
- selection_.select(folder);
-
- ES_LOG_DEBUG("Created folder entity: {}", folder);
-}
-
-void HierarchyPanel::deleteSelectedEntity() {
- if (selection_.empty()) {
- return;
- }
-
- Entity entity = selection_.getFirst();
- if (!registry_.valid(entity)) {
- return;
- }
-
- selection_.clear();
-
- if (registry_.has<ecs::Parent>(entity)) {
- Entity parent = registry_.get<ecs::Parent>(entity).entity;
- if (registry_.valid(parent) && registry_.has<ecs::Children>(parent)) {
- auto& siblings = registry_.get<ecs::Children>(parent).entities;
- siblings.erase(std::remove(siblings.begin(), siblings.end(), entity), siblings.end());
- }
- }
-
- if (registry_.has<ecs::Children>(entity)) {
- auto children = registry_.get<ecs::Children>(entity).entities;
- for (Entity child : children) {
- if (registry_.valid(child)) {
- registry_.destroy(child);
- }
- }
- }
-
- registry_.destroy(entity);
- rebuildTree();
-
- ES_LOG_DEBUG("Deleted entity: {}", entity);
-}
-
-void HierarchyPanel::renameSelectedEntity() {
- // TODO: Implement inline renaming via TreeView
- ES_LOG_INFO("Rename entity: not yet implemented");
-}
-
-void HierarchyPanel::updateStatusBar() {
- if (!entityCountLabel_) return;
-
- usize count = registry_.entityCount();
- std::ostringstream oss;
- oss << count << (count == 1 ? " entity" : " entities");
- entityCountLabel_->setText(oss.str());
-}
-
-// =============================================================================
-// Mapping Helpers
-// =============================================================================
-
-Entity HierarchyPanel::getEntityForNode(ui::TreeNodeId nodeId) const {
- auto it = nodeToEntity_.find(nodeId);
- return it != nodeToEntity_.end() ? it->second : INVALID_ENTITY;
-}
-
-ui::TreeNodeId HierarchyPanel::getNodeForEntity(Entity entity) const {
- auto it = entityToNode_.find(entity);
- return it != entityToNode_.end() ? it->second : ui::INVALID_TREE_NODE;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/HierarchyPanel.hpp b/src/esengine/editor/panels/HierarchyPanel.hpp
deleted file mode 100644
index b88029ec6..000000000
--- a/src/esengine/editor/panels/HierarchyPanel.hpp
+++ /dev/null
@@ -1,243 +0,0 @@
-/**
- * @file HierarchyPanel.hpp
- * @brief Hierarchy panel for scene entity management
- * @details Displays all entities in the scene in a tree view, showing
- * parent-child relationships and allowing entity selection.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../ui/docking/DockPanel.hpp"
-#include "../../ui/widgets/TreeView.hpp"
-#include "../../ui/widgets/ScrollView.hpp"
-#include "../../ui/widgets/Panel.hpp"
-#include "../../ui/widgets/TextField.hpp"
-#include "../../ui/widgets/Button.hpp"
-#include "../../ui/widgets/Label.hpp"
-#include "../../ui/widgets/ContextMenu.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../core/Selection.hpp"
-#include "../../events/Connection.hpp"
-
-#include <unordered_map>
-
-namespace esengine::editor {
-
-// =============================================================================
-// HierarchyPanel Class
-// =============================================================================
-
-/**
- * @brief Hierarchy panel for displaying and managing scene entities
- *
- * @details HierarchyPanel provides a tree view of all entities in the scene.
- * It displays:
- * - Entity names (from Name component)
- * - Parent-child relationships (from Parent/Children components)
- * - Selection state (synchronized with EntitySelection)
- *
- * The panel automatically updates when entities are created, destroyed,
- * or modified.
- *
- * @code
- * auto hierarchyPanel = makeUnique<HierarchyPanel>(registry, selection);
- * hierarchyPanel->setPanelType("Hierarchy");
- * dockArea->addPanel(std::move(hierarchyPanel));
- * @endcode
- */
-class HierarchyPanel : public ui::DockPanel {
-public:
- /**
- * @brief Constructs a hierarchy panel
- * @param registry The ECS registry to display
- * @param selection The entity selection manager
- */
- HierarchyPanel(ecs::Registry& registry, EntitySelection& selection);
-
- ~HierarchyPanel() override;
-
- /**
- * @brief Refreshes the tree view from the registry
- *
- * @details Rebuilds the entire tree structure from scratch.
- * Call this after batch entity operations.
- */
- void refresh();
-
- /**
- * @brief Sets whether to show entities without Parent component as roots
- * @param showOrphans True to show orphaned entities at root level
- */
- void setShowOrphans(bool showOrphans);
-
- /**
- * @brief Returns true if showing orphaned entities
- */
- bool getShowOrphans() const { return showOrphans_; }
-
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onKeyDown(const ui::KeyEvent& event) override;
-
-protected:
- void onActivated() override;
- void onDeactivated() override;
-
-private:
- // =========================================================================
- // Tree Building
- // =========================================================================
-
- /**
- * @brief Rebuilds the tree from registry state
- */
- void rebuildTree();
-
- /**
- * @brief Adds an entity to the tree
- * @param entity Entity to add
- * @param parentNodeId Parent tree node (INVALID_TREE_NODE for root)
- */
- ui::TreeNodeId addEntityToTree(Entity entity, ui::TreeNodeId parentNodeId);
-
- /**
- * @brief Gets the display name for an entity
- * @param entity Entity to get name for
- * @return Display name (Name component or "Entity {id}")
- */
- std::string getEntityDisplayName(Entity entity) const;
-
- /**
- * @brief Gets the icon for an entity based on its components
- * @param entity Entity to get icon for
- * @return Icon Unicode character or empty string for default
- */
- std::string getEntityIcon(Entity entity) const;
-
- /**
- * @brief Gets the type name for an entity based on its components
- * @param entity Entity to get type for
- * @return Type name string
- */
- std::string getEntityType(Entity entity) const;
-
- // =========================================================================
- // Event Handlers
- // =========================================================================
-
- /**
- * @brief Called when a tree node is selected
- * @param nodeId Selected node ID
- */
- void onNodeSelected(ui::TreeNodeId nodeId);
-
- /**
- * @brief Called when a tree node is double-clicked
- * @param nodeId Clicked node ID
- */
- void onNodeDoubleClicked(ui::TreeNodeId nodeId);
-
- /**
- * @brief Called when a tree node is right-clicked
- * @param nodeId Clicked node ID
- * @param x Screen X position
- * @param y Screen Y position
- */
- void onNodeRightClicked(ui::TreeNodeId nodeId, f32 x, f32 y);
-
- /**
- * @brief Handles context menu item selection
- * @param itemId Selected menu item ID
- */
- void onContextMenuItemSelected(const std::string& itemId);
-
- /**
- * @brief Called when entity selection changes externally
- * @param previous Previous selection
- * @param current Current selection
- */
- void onSelectionChanged(const std::vector<Entity>& previous,
- const std::vector<Entity>& current);
-
- void createEntity();
- void createChildEntity(Entity parent);
- void createFolder();
- void deleteSelectedEntity();
- void renameSelectedEntity();
- void updateStatusBar();
-
- // =========================================================================
- // Mapping Helpers
- // =========================================================================
-
- /**
- * @brief Gets the entity for a tree node
- * @param nodeId Tree node ID
- * @return Entity or INVALID_ENTITY if not found
- */
- Entity getEntityForNode(ui::TreeNodeId nodeId) const;
-
- /**
- * @brief Gets the tree node for an entity
- * @param entity Entity
- * @return Tree node ID or INVALID_TREE_NODE if not found
- */
- ui::TreeNodeId getNodeForEntity(Entity entity) const;
-
- void buildUI();
- void onSearchTextChanged(const std::string& text);
-
- // =========================================================================
- // Member Variables
- // =========================================================================
-
- ecs::Registry& registry_;
- EntitySelection& selection_;
-
- ui::Panel* rootPanel_ = nullptr;
- ui::Panel* toolbar_ = nullptr;
- ui::Button* addEntityButton_ = nullptr;
- ui::Button* createFolderButton_ = nullptr;
- ui::TextField* searchField_ = nullptr;
- ui::Panel* columnHeader_ = nullptr;
- ui::ScrollView* scrollView_ = nullptr;
- ui::TreeView* treeView_ = nullptr;
- ui::Panel* statusBar_ = nullptr;
- ui::Label* entityCountLabel_ = nullptr;
-
- Unique<ui::ContextMenu> contextMenu_;
- Entity contextMenuTargetEntity_ = INVALID_ENTITY;
-
- // Bidirectional mapping between entities and tree nodes
- std::unordered_map<ui::TreeNodeId, Entity> nodeToEntity_;
- std::unordered_map<Entity, ui::TreeNodeId> entityToNode_;
-
- std::string searchFilter_;
-
- // Settings
- bool showOrphans_ = true;
- bool needsRebuild_ = false;
- bool processingSelection_ = false;
-
- // Event connections
- Connection selectionChangedConnection_;
- Connection nodeSelectedConnection_;
- Connection nodeDoubleClickedConnection_;
- Connection nodeRightClickedConnection_;
- Connection searchChangedConnection_;
- Connection addEntityClickedConnection_;
- Connection createFolderClickedConnection_;
- Connection contextMenuItemSelectedConnection_;
- Connection contextMenuClosedConnection_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/InspectorPanel.cpp b/src/esengine/editor/panels/InspectorPanel.cpp
deleted file mode 100644
index 3fefa72d6..000000000
--- a/src/esengine/editor/panels/InspectorPanel.cpp
+++ /dev/null
@@ -1,1288 +0,0 @@
-/**
- * @file InspectorPanel.cpp
- * @brief Inspector panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "InspectorPanel.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../ecs/components/Common.hpp"
-#include "../../ecs/components/Camera.hpp"
-#include "../../ecs/components/Sprite.hpp"
-#include "../../math/Math.hpp"
-#include "../../events/Sink.hpp"
-#include "../../core/Log.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/layout/StackLayout.hpp"
-#include "../../ui/icons/Icons.hpp"
-#include "../../ui/widgets/Button.hpp"
-#include "../../ui/widgets/ClickablePanel.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-
-#include "../../ui/font/SystemFont.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-InspectorPanel::InspectorPanel(ecs::Registry& registry,
- EntitySelection& selection,
- CommandHistory& history,
- ScriptComponentRegistry* scriptRegistry)
- : DockPanel(ui::WidgetId("inspector_panel"), "Inspector"),
- registry_(registry),
- selection_(selection),
- history_(history),
- scriptRegistry_(scriptRegistry) {
-
- setPanelType("Inspector");
- setClosable(false);
- setMinSize(glm::vec2(250.0f, 200.0f));
-
- buildUI();
- connectToolbarButtons();
-
- selectionListenerId_ = selection_.addListener(
- [this](const std::vector<Entity>&, const std::vector<Entity>&) {
- refresh();
- });
-
- refresh();
-}
-
-InspectorPanel::~InspectorPanel() {
- if (selectionListenerId_ != 0) {
- selection_.removeListener(selectionListenerId_);
- }
-}
-
-// =============================================================================
-// UI Building
-// =============================================================================
-
-void InspectorPanel::buildUI() {
- constexpr glm::vec4 toolbarBg{0.2f, 0.2f, 0.2f, 1.0f}; // #333333
- constexpr glm::vec4 mainBg{0.165f, 0.165f, 0.165f, 1.0f}; // #2a2a2a
- constexpr glm::vec4 headerBg{0.176f, 0.176f, 0.188f, 1.0f}; // #2d2d30
- constexpr glm::vec4 borderColor{0.102f, 0.102f, 0.102f, 1.0f}; // #1a1a1a
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 dimTextColor{0.6f, 0.6f, 0.6f, 1.0f}; // #999999
-
- auto rootPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_root"));
- rootPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f));
- rootPanel->setDrawBackground(true);
- rootPanel->setBackgroundColor(mainBg);
-
- // =========================================================================
- // Toolbar
- // =========================================================================
- auto toolbar = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_toolbar"));
- toolbar->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 4.0f));
- toolbar->setHeight(ui::SizeValue::px(34.0f));
- toolbar->setWidth(ui::SizeValue::flex(1.0f));
- toolbar->setPadding(ui::Insets(4.0f, 8.0f, 4.0f, 8.0f));
- toolbar->setDrawBackground(true);
- toolbar->setBackgroundColor(toolbarBg);
- toolbar->setBorderColor(borderColor);
- toolbar->setBorderWidth(ui::BorderWidth(0.0f, 0.0f, 1.0f, 0.0f));
-
- auto lockButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_lock_btn"), ui::icons::Lock);
- lockButton->setButtonStyle(ui::ButtonStyle::Ghost);
- lockButton->setWidth(ui::SizeValue::px(26.0f));
- lockButton->setHeight(ui::SizeValue::px(26.0f));
- lockButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- lockButton_ = lockButton.get();
- toolbar->addChild(std::move(lockButton));
-
- auto debugButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_debug_btn"), ui::icons::Bug);
- debugButton->setButtonStyle(ui::ButtonStyle::Ghost);
- debugButton->setWidth(ui::SizeValue::px(26.0f));
- debugButton->setHeight(ui::SizeValue::px(26.0f));
- debugButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- debugButton_ = debugButton.get();
- toolbar->addChild(std::move(debugButton));
-
- auto spacer = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_spacer"));
- spacer->setWidth(ui::SizeValue::flex(1.0f));
- spacer->setHeight(ui::SizeValue::px(26.0f));
- spacer->setDrawBackground(false);
- toolbar->addChild(std::move(spacer));
-
- auto addComponentButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_add_btn"), ui::icons::Plus);
- addComponentButton->setButtonStyle(ui::ButtonStyle::Ghost);
- addComponentButton->setWidth(ui::SizeValue::px(26.0f));
- addComponentButton->setHeight(ui::SizeValue::px(26.0f));
- addComponentButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- addComponentButton_ = addComponentButton.get();
- toolbar->addChild(std::move(addComponentButton));
-
- auto settingsButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + "_settings_btn"), ui::icons::Settings);
- settingsButton->setButtonStyle(ui::ButtonStyle::Ghost);
- settingsButton->setWidth(ui::SizeValue::px(26.0f));
- settingsButton->setHeight(ui::SizeValue::px(26.0f));
- settingsButton->setCornerRadii(ui::CornerRadii::all(3.0f));
- settingsButton_ = settingsButton.get();
- toolbar->addChild(std::move(settingsButton));
-
- rootPanel->addChild(std::move(toolbar));
-
- // =========================================================================
- // Entity Header
- // =========================================================================
- auto headerPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_header"));
- headerPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 8.0f));
- headerPanel->setHeight(ui::SizeValue::px(32.0f));
- headerPanel->setWidth(ui::SizeValue::flex(1.0f));
- headerPanel->setPadding(ui::Insets(6.0f, 12.0f, 6.0f, 12.0f));
- headerPanel->setDrawBackground(true);
- headerPanel->setBackgroundColor(headerBg);
- headerPanel->setBorderColor(borderColor);
- headerPanel->setBorderWidth(ui::BorderWidth(0.0f, 0.0f, 1.0f, 0.0f));
-
- auto entityIconLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_entity_icon"), ui::icons::Box);
- entityIconLabel->setFontSize(14.0f);
- entityIconLabel->setColor(dimTextColor);
- entityIconLabel->setIsIconFont(true);
- entityIconLabel_ = entityIconLabel.get();
- headerPanel->addChild(std::move(entityIconLabel));
-
- auto entityNameLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_entity_name"));
- entityNameLabel->setText("No Selection");
- entityNameLabel->setFontSize(13.0f);
- entityNameLabel->setColor(textColor);
- entityNameLabel->setWidth(ui::SizeValue::flex(1.0f));
- entityNameLabel_ = entityNameLabel.get();
- headerPanel->addChild(std::move(entityNameLabel));
-
- auto entityIdLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_entity_id"));
- entityIdLabel->setText("");
- entityIdLabel->setFontSize(11.0f);
- entityIdLabel->setColor(dimTextColor);
- entityIdLabel_ = entityIdLabel.get();
- headerPanel->addChild(std::move(entityIdLabel));
-
- headerPanel_ = headerPanel.get();
- rootPanel->addChild(std::move(headerPanel));
-
- // =========================================================================
- // Scroll Content
- // =========================================================================
- auto scrollView = makeUnique<ui::ScrollView>(ui::WidgetId(getId().path + "_scroll"));
- scrollView->setScrollDirection(ui::ScrollDirection::Vertical);
- scrollView->setWidth(ui::SizeValue::flex(1.0f));
- scrollView->setHeight(ui::SizeValue::flex(1.0f));
- scrollView_ = scrollView.get();
-
- auto contentPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_content"));
- contentPanel->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f));
- contentPanel->setWidth(ui::SizeValue::flex(1.0f));
- contentPanel->setHeight(ui::SizeValue::autoSize());
- contentPanel->setPadding(ui::Insets(4.0f, 0.0f, 4.0f, 0.0f));
- contentPanel_ = contentPanel.get();
-
- scrollView->setContent(std::move(contentPanel));
- rootPanel->addChild(std::move(scrollView));
-
- // =========================================================================
- // Status Bar
- // =========================================================================
- auto statusBar = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_status"));
- statusBar->setHeight(ui::SizeValue::px(24.0f));
- statusBar->setWidth(ui::SizeValue::flex(1.0f));
- statusBar->setPadding(ui::Insets(4.0f, 12.0f, 4.0f, 12.0f));
- statusBar->setDrawBackground(true);
- statusBar->setBackgroundColor(toolbarBg);
- statusBar->setBorderColor(borderColor);
- statusBar->setBorderWidth(ui::BorderWidth(1.0f, 0.0f, 0.0f, 0.0f));
-
- auto componentCountLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_count"), "0 components");
- componentCountLabel->setFontSize(11.0f);
- componentCountLabel->setColor(dimTextColor);
- componentCountLabel_ = componentCountLabel.get();
- statusBar->addChild(std::move(componentCountLabel));
-
- rootPanel->addChild(std::move(statusBar));
-
- rootPanel_ = rootPanel.get();
- setContent(std::move(rootPanel));
-}
-
-InspectorPanel::SectionWidgets InspectorPanel::createComponentSection(const std::string& name, const std::string& icon) {
- constexpr glm::vec4 sectionHeaderBg{0.2f, 0.2f, 0.2f, 1.0f}; // #333333
- constexpr glm::vec4 sectionBg{0.165f, 0.165f, 0.165f, 1.0f}; // #2a2a2a
- constexpr glm::vec4 borderColor{0.102f, 0.102f, 0.102f, 1.0f}; // #1a1a1a
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 iconColor{0.6f, 0.6f, 0.6f, 1.0f}; // #999999
-
- SectionWidgets widgets;
-
- auto section = makeUnique<ui::Panel>(ui::WidgetId(contentPanel_->getId().path + "_" + name));
- section->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f));
- section->setWidth(ui::SizeValue::flex(1.0f));
- section->setHeight(ui::SizeValue::autoSize());
- section->setDrawBackground(true);
- section->setBackgroundColor(sectionBg);
- section->setBorderColor(borderColor);
- section->setBorderWidth(ui::BorderWidth(0.0f, 0.0f, 1.0f, 0.0f));
- widgets.section = section.get();
-
- auto header = makeUnique<ui::ClickablePanel>(ui::WidgetId(section->getId().path + "_header"));
- header->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 6.0f));
- header->setHeight(ui::SizeValue::px(26.0f));
- header->setWidth(ui::SizeValue::flex(1.0f));
- header->setPadding(ui::Insets(4.0f, 8.0f, 4.0f, 8.0f));
- header->setDrawBackground(true);
- header->setBackgroundColor(sectionHeaderBg);
-
- bool isCollapsed = collapsedSections_.count(name) > 0;
- std::string chevronIcon = isCollapsed ? ui::icons::ChevronRight : ui::icons::ChevronDown;
-
- auto chevronLabel = makeUnique<ui::Label>(ui::WidgetId(header->getId().path + "_chevron"), chevronIcon);
- chevronLabel->setFontSize(10.0f);
- chevronLabel->setColor(iconColor);
- chevronLabel->setIsIconFont(true);
- widgets.chevron = chevronLabel.get();
- header->addChild(std::move(chevronLabel));
-
- auto iconLabel = makeUnique<ui::Label>(ui::WidgetId(header->getId().path + "_icon"), icon);
- iconLabel->setFontSize(12.0f);
- iconLabel->setColor(iconColor);
- iconLabel->setIsIconFont(true);
- header->addChild(std::move(iconLabel));
-
- auto headerLabel = makeUnique<ui::Label>(ui::WidgetId(header->getId().path + "_label"));
- headerLabel->setText(name);
- headerLabel->setFontSize(12.0f);
- headerLabel->setColor(textColor);
- headerLabel->setWidth(ui::SizeValue::flex(1.0f));
- header->addChild(std::move(headerLabel));
-
- auto removeButton = makeUnique<ui::Button>(ui::WidgetId(header->getId().path + "_remove"), ui::icons::X);
- removeButton->setButtonStyle(ui::ButtonStyle::Ghost);
- removeButton->setWidth(ui::SizeValue::px(18.0f));
- removeButton->setHeight(ui::SizeValue::px(18.0f));
- removeButton->setCornerRadii(ui::CornerRadii::all(2.0f));
- header->addChild(std::move(removeButton));
-
- ui::ClickablePanel* headerPtr = header.get();
- section->addChild(std::move(header));
-
- auto content = makeUnique<ui::Panel>(ui::WidgetId(section->getId().path + "_content"));
- content->setLayout(makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 4.0f));
- content->setWidth(ui::SizeValue::flex(1.0f));
- content->setHeight(ui::SizeValue::autoSize());
- content->setPadding(ui::Insets(8.0f, 12.0f, 8.0f, 12.0f));
- content->setVisible(!isCollapsed);
- widgets.content = content.get();
- section->addChild(std::move(content));
-
- editorConnections_.add(sink(headerPtr->onClick).connect(
- [this, name](const ui::MouseButtonEvent& event) {
- if (event.button == ui::MouseButton::Left) {
- toggleSection(name);
- }
- }
- ));
-
- sectionWidgets_[name] = widgets;
- contentPanel_->addChild(std::move(section));
- return widgets;
-}
-
-void InspectorPanel::toggleSection(const std::string& name) {
- if (collapsedSections_.count(name) > 0) {
- collapsedSections_.erase(name);
- } else {
- collapsedSections_.insert(name);
- }
-
- auto it = sectionWidgets_.find(name);
- if (it != sectionWidgets_.end()) {
- updateSectionVisibility(name, it->second);
- }
-}
-
-void InspectorPanel::updateSectionVisibility(const std::string& name, SectionWidgets& widgets) {
- bool isCollapsed = collapsedSections_.count(name) > 0;
-
- if (widgets.content) {
- widgets.content->setVisible(!isCollapsed);
- }
-
- if (widgets.chevron) {
- widgets.chevron->setText(isCollapsed ? ui::icons::ChevronRight : ui::icons::ChevronDown);
- }
-
- if (scrollView_) {
- scrollView_->invalidateLayout();
- }
-}
-
-// =============================================================================
-// Public Interface
-// =============================================================================
-
-void InspectorPanel::refresh() {
- Entity selected = selection_.getFirst();
-
- if (selected != currentEntity_) {
- currentEntity_ = selected;
- rebuildInspector();
- }
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-void InspectorPanel::render(ui::UIBatchRenderer& renderer) {
- syncEditorValues();
-
- if (rootPanel_) {
- if (rootPanel_->getContext() != getContext()) {
- rootPanel_->setContext(getContext());
- }
- rootPanel_->layout(getBounds());
- rootPanel_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void InspectorPanel::rebuildInspector() {
- clearInspector();
-
- constexpr glm::vec4 dimTextColor{0.533f, 0.533f, 0.533f, 1.0f}; // #888
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
-
- if (currentEntity_ == INVALID_ENTITY || !registry_.valid(currentEntity_)) {
- if (entityIconLabel_) {
- entityIconLabel_->setText(ui::icons::Box);
- entityIconLabel_->setColor(dimTextColor);
- }
- if (entityNameLabel_) {
- entityNameLabel_->setText("No Selection");
- entityNameLabel_->setColor(dimTextColor);
- }
- if (entityIdLabel_) {
- entityIdLabel_->setText("");
- }
- if (componentCountLabel_) {
- componentCountLabel_->setText("0 components");
- }
-
- auto noSelectionLabel = makeUnique<ui::Label>(
- ui::WidgetId(contentPanel_->getId().path + "_no_selection"));
- noSelectionLabel->setText("Select an entity to view properties");
- noSelectionLabel->setFontSize(12.0f);
- noSelectionLabel->setColor(dimTextColor);
- contentPanel_->addChild(std::move(noSelectionLabel));
- return;
- }
-
- std::string displayName = "Entity " + std::to_string(currentEntity_);
- std::string entityIcon = ui::icons::Box;
-
- if (registry_.has<ecs::Name>(currentEntity_)) {
- displayName = registry_.get<ecs::Name>(currentEntity_).value;
- }
- if (registry_.has<ecs::Camera>(currentEntity_)) {
- entityIcon = ui::icons::Camera;
- } else if (registry_.has<ecs::Sprite>(currentEntity_)) {
- entityIcon = ui::icons::Image;
- }
-
- if (entityIconLabel_) {
- entityIconLabel_->setText(entityIcon);
- entityIconLabel_->setColor(textColor);
- }
- if (entityNameLabel_) {
- entityNameLabel_->setText(displayName);
- entityNameLabel_->setColor(textColor);
- }
- if (entityIdLabel_) {
- entityIdLabel_->setText("ID: " + std::to_string(currentEntity_));
- }
-
- i32 componentCount = 0;
-
- addTagsEditor(currentEntity_);
- componentCount++;
-
- if (registry_.has<ecs::Name>(currentEntity_)) {
- addNameEditor(currentEntity_);
- componentCount++;
- }
-
- if (registry_.has<ecs::LocalTransform>(currentEntity_)) {
- addLocalTransformEditor(currentEntity_);
- componentCount++;
- }
-
- if (registry_.has<ecs::Camera>(currentEntity_)) {
- addCameraEditor(currentEntity_);
- componentCount++;
- }
-
- if (registry_.has<ecs::Sprite>(currentEntity_)) {
- addSpriteEditor(currentEntity_);
- 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");
- componentCountLabel_->setText(countText);
- }
-}
-
-void InspectorPanel::clearInspector() {
- editorConnections_.disconnectAll();
- sectionWidgets_.clear();
- positionEditor_ = nullptr;
- rotationEditor_ = nullptr;
- scaleEditor_ = nullptr;
- if (contentPanel_) {
- contentPanel_->clearChildren();
- }
-}
-
-void InspectorPanel::syncEditorValues() {
- if (currentEntity_ == INVALID_ENTITY || !registry_.valid(currentEntity_)) {
- return;
- }
-
- if (registry_.has<ecs::LocalTransform>(currentEntity_)) {
- const auto& transform = registry_.get<ecs::LocalTransform>(currentEntity_);
-
- if (positionEditor_) {
- positionEditor_->setValue(transform.position);
- }
- if (rotationEditor_) {
- glm::vec3 eulerAngles = math::quatToEulerDegrees(transform.rotation);
- rotationEditor_->setValue(eulerAngles);
- }
- if (scaleEditor_) {
- scaleEditor_->setValue(transform.scale);
- }
- }
-}
-
-void InspectorPanel::addNameEditor(Entity entity) {
- auto widgets = createComponentSection("Name", ui::icons::User);
- auto& name = registry_.get<ecs::Name>(entity);
-
- auto nameEditor = makeUnique<StringEditor>(
- ui::WidgetId(widgets.content->getId().path + "_name"),
- "name");
- nameEditor->setLabel("Name");
- nameEditor->setValue(name.value);
- nameEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(nameEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Name>(entity)) {
- auto& n = registry_.get<ecs::Name>(entity);
- try {
- n.value = std::any_cast<std::string>(value);
- if (entityNameLabel_) {
- entityNameLabel_->setText(n.value);
- }
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast name value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(nameEditor));
-}
-
-void InspectorPanel::addLocalTransformEditor(Entity entity) {
- auto widgets = createComponentSection("Transform", ui::icons::Move3d);
- auto& transform = registry_.get<ecs::LocalTransform>(entity);
-
- auto positionEditor = makeUnique<Vector3Editor>(
- ui::WidgetId(widgets.content->getId().path + "_position"),
- "position");
- positionEditor->setLabel("Position");
- positionEditor->setValue(transform.position);
- positionEditor->setCommandHistory(&history_);
- positionEditor_ = positionEditor.get();
-
- editorConnections_.add(sink(positionEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::LocalTransform>(entity)) {
- auto& t = registry_.get<ecs::LocalTransform>(entity);
- try {
- t.position = std::any_cast<glm::vec3>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast position value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(positionEditor));
-
- glm::vec3 eulerAngles = math::quatToEulerDegrees(transform.rotation);
-
- auto rotationEditor = makeUnique<Vector3Editor>(
- ui::WidgetId(widgets.content->getId().path + "_rotation"),
- "rotation");
- rotationEditor->setLabel("Rotation");
- rotationEditor->setValue(eulerAngles);
- rotationEditor->setCommandHistory(&history_);
- rotationEditor_ = rotationEditor.get();
-
- editorConnections_.add(sink(rotationEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::LocalTransform>(entity)) {
- auto& t = registry_.get<ecs::LocalTransform>(entity);
- try {
- glm::vec3 euler = std::any_cast<glm::vec3>(value);
- t.rotation = math::eulerDegreesToQuat(euler);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast rotation value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(rotationEditor));
-
- auto scaleEditor = makeUnique<Vector3Editor>(
- ui::WidgetId(widgets.content->getId().path + "_scale"),
- "scale");
- scaleEditor->setLabel("Scale");
- scaleEditor->setValue(transform.scale);
- scaleEditor->setCommandHistory(&history_);
- scaleEditor_ = scaleEditor.get();
-
- editorConnections_.add(sink(scaleEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::LocalTransform>(entity)) {
- auto& t = registry_.get<ecs::LocalTransform>(entity);
- try {
- t.scale = std::any_cast<glm::vec3>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast scale value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(scaleEditor));
-}
-
-void InspectorPanel::addCameraEditor(Entity entity) {
- auto widgets = createComponentSection("Camera", ui::icons::Camera);
- auto& camera = registry_.get<ecs::Camera>(entity);
-
- auto projTypeEditor = makeUnique<EnumEditor>(
- ui::WidgetId(widgets.content->getId().path + "_projType"),
- "projectionType");
- projTypeEditor->setLabel("Projection");
- projTypeEditor->addOption(EnumOption::create(
- static_cast<i32>(ecs::ProjectionType::Perspective), "Perspective"));
- projTypeEditor->addOption(EnumOption::create(
- static_cast<i32>(ecs::ProjectionType::Orthographic), "Orthographic"));
- projTypeEditor->setValue(static_cast<i32>(camera.projectionType));
- projTypeEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(projTypeEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.projectionType = static_cast<ecs::ProjectionType>(std::any_cast<i32>(value));
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast projectionType value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(projTypeEditor));
-
- auto fovEditor = makeUnique<FloatEditor>(
- ui::WidgetId(widgets.content->getId().path + "_fov"),
- "fov");
- fovEditor->setLabel("FOV");
- fovEditor->setValue(camera.fov);
- fovEditor->setRange(1.0f, 180.0f);
- fovEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(fovEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.fov = std::any_cast<f32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast fov value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(fovEditor));
-
- auto orthoSizeEditor = makeUnique<FloatEditor>(
- ui::WidgetId(widgets.content->getId().path + "_orthoSize"),
- "orthoSize");
- orthoSizeEditor->setLabel("Ortho Size");
- orthoSizeEditor->setValue(camera.orthoSize);
- orthoSizeEditor->setRange(0.1f, 100.0f);
- orthoSizeEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(orthoSizeEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.orthoSize = std::any_cast<f32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast orthoSize value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(orthoSizeEditor));
-
- auto nearEditor = makeUnique<FloatEditor>(
- ui::WidgetId(widgets.content->getId().path + "_near"),
- "nearPlane");
- nearEditor->setLabel("Near");
- nearEditor->setValue(camera.nearPlane);
- nearEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(nearEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.nearPlane = std::any_cast<f32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast nearPlane value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(nearEditor));
-
- auto farEditor = makeUnique<FloatEditor>(
- ui::WidgetId(widgets.content->getId().path + "_far"),
- "farPlane");
- farEditor->setLabel("Far");
- farEditor->setValue(camera.farPlane);
- farEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(farEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.farPlane = std::any_cast<f32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast farPlane value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(farEditor));
-
- auto aspectEditor = makeUnique<FloatEditor>(
- ui::WidgetId(widgets.content->getId().path + "_aspect"),
- "aspectRatio");
- aspectEditor->setLabel("Aspect");
- aspectEditor->setValue(camera.aspectRatio);
- aspectEditor->setRange(0.0f, 4.0f);
- aspectEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(aspectEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.aspectRatio = std::any_cast<f32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast aspectRatio value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(aspectEditor));
-
- auto activeEditor = makeUnique<BoolEditor>(
- ui::WidgetId(widgets.content->getId().path + "_active"),
- "isActive");
- activeEditor->setLabel("Active");
- activeEditor->setValue(camera.isActive);
- activeEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(activeEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.isActive = std::any_cast<bool>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast isActive value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(activeEditor));
-
- auto priorityEditor = makeUnique<IntEditor>(
- ui::WidgetId(widgets.content->getId().path + "_priority"),
- "priority");
- priorityEditor->setLabel("Priority");
- priorityEditor->setValue(camera.priority);
- priorityEditor->setRange(-100, 100);
- priorityEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(priorityEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Camera>(entity)) {
- auto& c = registry_.get<ecs::Camera>(entity);
- try {
- c.priority = std::any_cast<i32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast priority value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(priorityEditor));
-}
-
-void InspectorPanel::addSpriteEditor(Entity entity) {
- auto widgets = createComponentSection("Sprite", ui::icons::Image);
- auto& sprite = registry_.get<ecs::Sprite>(entity);
-
- auto colorEditor = makeUnique<ColorEditor>(
- ui::WidgetId(widgets.content->getId().path + "_color"),
- "color");
- colorEditor->setLabel("Color");
- colorEditor->setValue(sprite.color);
- colorEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(colorEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.color = std::any_cast<glm::vec4>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast color value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(colorEditor));
-
- auto sizeEditor = makeUnique<Vector2Editor>(
- ui::WidgetId(widgets.content->getId().path + "_size"),
- "size");
- sizeEditor->setLabel("Size");
- sizeEditor->setValue(sprite.size);
- sizeEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(sizeEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.size = std::any_cast<glm::vec2>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast size value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(sizeEditor));
-
- auto uvOffsetEditor = makeUnique<Vector2Editor>(
- ui::WidgetId(widgets.content->getId().path + "_uvOffset"),
- "uvOffset");
- uvOffsetEditor->setLabel("UV Offset");
- uvOffsetEditor->setValue(sprite.uvOffset);
- uvOffsetEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(uvOffsetEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.uvOffset = std::any_cast<glm::vec2>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast uvOffset value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(uvOffsetEditor));
-
- auto uvScaleEditor = makeUnique<Vector2Editor>(
- ui::WidgetId(widgets.content->getId().path + "_uvScale"),
- "uvScale");
- uvScaleEditor->setLabel("UV Scale");
- uvScaleEditor->setValue(sprite.uvScale);
- uvScaleEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(uvScaleEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.uvScale = std::any_cast<glm::vec2>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast uvScale value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(uvScaleEditor));
-
- auto layerEditor = makeUnique<IntEditor>(
- ui::WidgetId(widgets.content->getId().path + "_layer"),
- "layer");
- layerEditor->setLabel("Layer");
- layerEditor->setValue(sprite.layer);
- layerEditor->setRange(-1000, 1000);
- layerEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(layerEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.layer = std::any_cast<i32>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast layer value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(layerEditor));
-
- auto flipXEditor = makeUnique<BoolEditor>(
- ui::WidgetId(widgets.content->getId().path + "_flipX"),
- "flipX");
- flipXEditor->setLabel("Flip X");
- flipXEditor->setValue(sprite.flipX);
- flipXEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(flipXEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.flipX = std::any_cast<bool>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast flipX value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(flipXEditor));
-
- auto flipYEditor = makeUnique<BoolEditor>(
- ui::WidgetId(widgets.content->getId().path + "_flipY"),
- "flipY");
- flipYEditor->setLabel("Flip Y");
- flipYEditor->setValue(sprite.flipY);
- flipYEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(flipYEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (registry_.valid(entity) && registry_.has<ecs::Sprite>(entity)) {
- auto& s = registry_.get<ecs::Sprite>(entity);
- try {
- s.flipY = std::any_cast<bool>(value);
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast flipY value");
- }
- }
- }
- ));
-
- widgets.content->addChild(std::move(flipYEditor));
-}
-
-void InspectorPanel::addTagsEditor(Entity entity) {
- auto widgets = createComponentSection("Tags", ui::icons::Check);
-
- bool hasActive = registry_.has<ecs::Active>(entity);
- auto activeEditor = makeUnique<BoolEditor>(
- ui::WidgetId(widgets.content->getId().path + "_active"),
- "active");
- activeEditor->setLabel("Active");
- activeEditor->setValue(hasActive);
- activeEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(activeEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (!registry_.valid(entity)) return;
- try {
- bool active = std::any_cast<bool>(value);
- if (active && !registry_.has<ecs::Active>(entity)) {
- registry_.emplace<ecs::Active>(entity);
- } else if (!active && registry_.has<ecs::Active>(entity)) {
- registry_.remove<ecs::Active>(entity);
- }
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast active value");
- }
- }
- ));
-
- widgets.content->addChild(std::move(activeEditor));
-
- bool hasVisible = registry_.has<ecs::Visible>(entity);
- auto visibleEditor = makeUnique<BoolEditor>(
- ui::WidgetId(widgets.content->getId().path + "_visible"),
- "visible");
- visibleEditor->setLabel("Visible");
- visibleEditor->setValue(hasVisible);
- visibleEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(visibleEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (!registry_.valid(entity)) return;
- try {
- bool visible = std::any_cast<bool>(value);
- if (visible && !registry_.has<ecs::Visible>(entity)) {
- registry_.emplace<ecs::Visible>(entity);
- } else if (!visible && registry_.has<ecs::Visible>(entity)) {
- registry_.remove<ecs::Visible>(entity);
- }
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast visible value");
- }
- }
- ));
-
- widgets.content->addChild(std::move(visibleEditor));
-
- bool hasStatic = registry_.has<ecs::Static>(entity);
- auto staticEditor = makeUnique<BoolEditor>(
- ui::WidgetId(widgets.content->getId().path + "_static"),
- "static");
- staticEditor->setLabel("Static");
- staticEditor->setValue(hasStatic);
- staticEditor->setCommandHistory(&history_);
-
- editorConnections_.add(sink(staticEditor->onValueChanged).connect(
- [this, entity](const std::any& value) {
- if (!registry_.valid(entity)) return;
- try {
- bool isStatic = std::any_cast<bool>(value);
- if (isStatic && !registry_.has<ecs::Static>(entity)) {
- registry_.emplace<ecs::Static>(entity);
- } else if (!isStatic && registry_.has<ecs::Static>(entity)) {
- registry_.remove<ecs::Static>(entity);
- }
- } catch (const std::bad_any_cast&) {
- ES_LOG_ERROR("Failed to cast static value");
- }
- }
- ));
-
- 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;
- }
- }
- }
- }
-}
-
-void InspectorPanel::connectToolbarButtons() {
- if (addComponentButton_) {
- toolbarConnections_.add(sink(addComponentButton_->onClick).connect(
- [this]() { onAddComponentClicked(); }
- ));
- }
-}
-
-void InspectorPanel::onAddComponentClicked() {
- if (currentEntity_ == INVALID_ENTITY || !registry_.valid(currentEntity_)) {
- ES_LOG_WARN("No entity selected to add component");
- return;
- }
-
- ES_LOG_INFO("Add component clicked for entity {}", currentEntity_);
-
- // Add Camera component if not already present
- if (!registry_.has<ecs::Camera>(currentEntity_)) {
- registry_.emplace<ecs::Camera>(currentEntity_);
- ES_LOG_INFO("Added Camera component to entity {}", currentEntity_);
- rebuildInspector();
- return;
- }
-
- // Add Sprite component if not already present
- if (!registry_.has<ecs::Sprite>(currentEntity_)) {
- registry_.emplace<ecs::Sprite>(currentEntity_);
- ES_LOG_INFO("Added Sprite component to entity {}", currentEntity_);
- rebuildInspector();
- return;
- }
-
- ES_LOG_INFO("Entity already has all available components");
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/InspectorPanel.hpp b/src/esengine/editor/panels/InspectorPanel.hpp
deleted file mode 100644
index de20d5f47..000000000
--- a/src/esengine/editor/panels/InspectorPanel.hpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * @file InspectorPanel.hpp
- * @brief Inspector panel for editing entity properties
- * @details Displays and edits components of the selected entity with undo/redo support.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../ui/docking/DockPanel.hpp"
-#include "../../ui/widgets/ScrollView.hpp"
-#include "../../ui/widgets/Label.hpp"
-#include "../../ui/widgets/Panel.hpp"
-#include "../../ui/widgets/TextField.hpp"
-#include "../../ui/widgets/Button.hpp"
-#include "../../ui/widgets/ContextMenu.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../ecs/Entity.hpp"
-#include "../core/Selection.hpp"
-#include "../command/CommandHistory.hpp"
-#include "../property/editors/Vector3Editor.hpp"
-#include "../property/editors/Vector2Editor.hpp"
-#include "../property/editors/FloatEditor.hpp"
-#include "../property/editors/BoolEditor.hpp"
-#include "../property/editors/IntEditor.hpp"
-#include "../property/editors/StringEditor.hpp"
-#include "../property/editors/ColorEditor.hpp"
-#include "../property/editors/EnumEditor.hpp"
-#include "../../events/Connection.hpp"
-#include "../script/ScriptComponentRegistry.hpp"
-
-#include <unordered_set>
-#include <unordered_map>
-
-namespace esengine::editor {
-
-// =============================================================================
-// InspectorPanel Class
-// =============================================================================
-
-/**
- * @brief Panel for inspecting and editing entity properties
- *
- * @details Shows all components of the selected entity and provides
- * property editors for each component. Changes are tracked
- * through CommandHistory for undo/redo support.
- *
- * @code
- * InspectorPanel inspector(registry, selection, history);
- * // Selection changes trigger automatic refresh
- * @endcode
- */
-class InspectorPanel : public ui::DockPanel {
-public:
- /**
- * @brief Constructs inspector panel
- * @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,
- ScriptComponentRegistry* scriptRegistry = nullptr);
-
- ~InspectorPanel() override;
-
- /**
- * @brief Refreshes inspector to show selected entity's components
- * @details Called automatically when selection changes
- */
- void refresh();
-
- /**
- * @brief Updates editor values from component data without rebuilding
- * @details Should be called each frame to sync with external changes
- */
- void syncEditorValues();
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- void render(ui::UIBatchRenderer& renderer) override;
-
-private:
- void buildUI();
- void rebuildInspector();
- void clearInspector();
-
- struct SectionWidgets {
- ui::Panel* section = nullptr;
- ui::Panel* content = nullptr;
- ui::Label* chevron = nullptr;
- ui::Button* removeButton = nullptr;
- };
-
- SectionWidgets createComponentSection(const std::string& name, const std::string& icon);
- void toggleSection(const std::string& name);
- void updateSectionVisibility(const std::string& name, SectionWidgets& widgets);
-
- // Component editors
- void addNameEditor(Entity entity);
- void addLocalTransformEditor(Entity entity);
- 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;
- ui::Label* entityIconLabel_ = nullptr;
- ui::Label* entityNameLabel_ = nullptr;
- ui::Label* entityIdLabel_ = nullptr;
- ui::Label* componentCountLabel_ = nullptr;
- ui::ScrollView* scrollView_ = nullptr;
- ui::Panel* contentPanel_ = nullptr;
-
- std::unordered_set<std::string> collapsedSections_;
- std::unordered_map<std::string, SectionWidgets> sectionWidgets_;
-
- Entity currentEntity_ = INVALID_ENTITY;
-
- // Dynamic editor connections (cleared on rebuild)
- ConnectionHolder editorConnections_;
-
- // Persistent connections (RAII cleanup)
- Connection selectionChangedConnection_;
- Connection addComponentClickedConnection_;
- Connection addComponentMenuSelectedConnection_;
- Connection addComponentMenuClosedConnection_;
-
- Vector3Editor* positionEditor_ = nullptr;
- Vector3Editor* rotationEditor_ = nullptr;
- Vector3Editor* scaleEditor_ = nullptr;
-
- // Toolbar buttons
- ui::Button* addComponentButton_ = nullptr;
- ui::Button* lockButton_ = nullptr;
- ui::Button* debugButton_ = nullptr;
- ui::Button* settingsButton_ = nullptr;
-
- Unique<ui::ContextMenu> addComponentMenu_;
- bool needsRebuild_ = false;
-
- void setupConnections();
- void showAddComponentMenu();
- void onAddComponentMenuSelected(const std::string& itemId);
- void removeComponent(const std::string& componentName);
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/NewProjectDialog.cpp b/src/esengine/editor/panels/NewProjectDialog.cpp
deleted file mode 100644
index 0d4cc45d0..000000000
--- a/src/esengine/editor/panels/NewProjectDialog.cpp
+++ /dev/null
@@ -1,225 +0,0 @@
-/**
- * @file NewProjectDialog.cpp
- * @brief Dialog for creating new projects implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "NewProjectDialog.hpp"
-#include "../../ui/widgets/Button.hpp"
-#include "../../ui/widgets/Label.hpp"
-#include "../../ui/widgets/TextField.hpp"
-#include "../../ui/widgets/Panel.hpp"
-#include "../../ui/layout/StackLayout.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../platform/FileDialog.hpp"
-#include "../../events/Sink.hpp"
-#include "../../core/Log.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-NewProjectDialog::NewProjectDialog(const ui::WidgetId& id)
- : Widget(id) {
- setupUI();
-}
-
-NewProjectDialog::~NewProjectDialog() = default;
-
-// =============================================================================
-// Setup
-// =============================================================================
-
-void NewProjectDialog::setupUI() {
- auto dialogPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".dialog"));
- dialogPanel->setBackgroundColor(glm::vec4(0.18f, 0.18f, 0.20f, 1.0f));
- dialogPanel->setCornerRadii(ui::CornerRadii::all(12.0f));
- dialogPanel->setWidth(ui::SizeValue::px(480.0f));
- dialogPanel->setHeight(ui::SizeValue::px(340.0f));
-
- auto layout = makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 12.0f);
- dialogPanel->setLayout(std::move(layout));
- dialogPanel->setPadding(ui::Insets(32.0f, 32.0f, 32.0f, 32.0f));
-
- auto titleLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".title"), "Create New Project");
- titleLabel->setFontSize(22.0f);
- titleLabel->setColor(glm::vec4(1.0f));
- titleLabel_ = titleLabel.get();
- dialogPanel->addChild(std::move(titleLabel));
-
- auto spacer1 = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".spacer1"));
- spacer1->setHeight(ui::SizeValue::px(8.0f));
- dialogPanel->addChild(std::move(spacer1));
-
- auto nameLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".name_label"), "Project Name");
- nameLabel->setFontSize(13.0f);
- nameLabel->setColor(glm::vec4(0.7f, 0.7f, 0.7f, 1.0f));
- nameLabel_ = nameLabel.get();
- dialogPanel->addChild(std::move(nameLabel));
-
- auto nameField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + ".name_field"));
- nameField->setPlaceholder("MyGame");
- nameField->setWidth(ui::SizeValue::percent(100.0f));
- nameField->setHeight(ui::SizeValue::px(38.0f));
- nameField_ = nameField.get();
- dialogPanel->addChild(std::move(nameField));
-
- auto pathLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".path_label"), "Location");
- pathLabel->setFontSize(13.0f);
- pathLabel->setColor(glm::vec4(0.7f, 0.7f, 0.7f, 1.0f));
- pathLabel_ = pathLabel.get();
- dialogPanel->addChild(std::move(pathLabel));
-
- auto pathRow = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".path_row"));
- auto pathRowLayout = makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 8.0f);
- pathRow->setLayout(std::move(pathRowLayout));
- pathRow->setWidth(ui::SizeValue::percent(100.0f));
- pathRow->setHeight(ui::SizeValue::px(38.0f));
-
- auto pathField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + ".path_field"));
- pathField->setPlaceholder("Select folder...");
- pathField->setWidth(ui::SizeValue::px(310.0f));
- pathField->setHeight(ui::SizeValue::px(38.0f));
- pathField_ = pathField.get();
- pathRow->addChild(std::move(pathField));
-
- auto browseButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + ".browse"), "...");
- browseButton->setButtonStyle(ui::ButtonStyle::Secondary);
- browseButton->setWidth(ui::SizeValue::px(50.0f));
- browseButton->setHeight(ui::SizeValue::px(38.0f));
- browseButton_ = browseButton.get();
- connections_.push_back(
- sink(browseButton_->onClick).connect([this]() { onBrowseClicked(); }));
- pathRow->addChild(std::move(browseButton));
-
- dialogPanel->addChild(std::move(pathRow));
-
- auto spacer2 = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".spacer2"));
- spacer2->setHeight(ui::SizeValue::px(24.0f));
- dialogPanel->addChild(std::move(spacer2));
-
- auto buttonRow = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".buttons"));
- auto buttonLayout = makeUnique<ui::StackLayout>(ui::StackDirection::Horizontal, 12.0f);
- buttonRow->setLayout(std::move(buttonLayout));
- buttonRow->setHeight(ui::SizeValue::px(42.0f));
-
- auto cancelButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + ".cancel"), "Cancel");
- cancelButton->setButtonStyle(ui::ButtonStyle::Secondary);
- cancelButton->setWidth(ui::SizeValue::px(110.0f));
- cancelButton->setHeight(ui::SizeValue::px(42.0f));
- cancelButton_ = cancelButton.get();
- connections_.push_back(
- sink(cancelButton_->onClick).connect([this]() { onCancelClicked(); }));
- buttonRow->addChild(std::move(cancelButton));
-
- auto createButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + ".create"), "Create Project");
- createButton->setButtonStyle(ui::ButtonStyle::Primary);
- createButton->setWidth(ui::SizeValue::px(130.0f));
- createButton->setHeight(ui::SizeValue::px(42.0f));
- createButton_ = createButton.get();
- connections_.push_back(
- sink(createButton_->onClick).connect([this]() { onCreateClicked(); }));
- buttonRow->addChild(std::move(createButton));
-
- dialogPanel->addChild(std::move(buttonRow));
-
- dialogPanel_ = dialogPanel.get();
- addChild(std::move(dialogPanel));
-}
-
-// =============================================================================
-// Methods
-// =============================================================================
-
-void NewProjectDialog::show() {
- showing_ = true;
- setVisible(true);
- if (nameField_) {
- nameField_->setText("");
- }
- if (pathField_) {
- pathField_->setText("");
- }
-}
-
-void NewProjectDialog::hide() {
- showing_ = false;
- setVisible(false);
-}
-
-void NewProjectDialog::onBrowseClicked() {
- std::string folder = FileDialog::selectFolder("Select Project Location");
- if (!folder.empty() && pathField_) {
- pathField_->setText(folder);
- }
-}
-
-void NewProjectDialog::onCreateClicked() {
- if (!nameField_ || !pathField_) return;
-
- std::string name = nameField_->getText();
- std::string basePath = pathField_->getText();
-
- if (name.empty()) {
- ES_LOG_WARN("Project name cannot be empty");
- return;
- }
-
- if (basePath.empty()) {
- ES_LOG_WARN("Project location cannot be empty");
- return;
- }
-
- std::string fullPath = basePath + "/" + name;
- ES_LOG_INFO("Creating project '{}' at {}", name, fullPath);
-
- showing_ = false;
- onProjectCreate.publish(name, fullPath);
-}
-
-void NewProjectDialog::onCancelClicked() {
- onCancel.publish();
- hide();
-}
-
-// =============================================================================
-// Widget Overrides
-// =============================================================================
-
-glm::vec2 NewProjectDialog::measure(f32 availableWidth, f32 availableHeight) {
- return glm::vec2(availableWidth, availableHeight);
-}
-
-void NewProjectDialog::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- if (dialogPanel_) {
- f32 dialogWidth = 480.0f;
- f32 dialogHeight = 340.0f;
- f32 dialogX = bounds.x + (bounds.width - dialogWidth) / 2.0f;
- f32 dialogY = bounds.y + (bounds.height - dialogHeight) / 2.0f;
- dialogPanel_->layout(ui::Rect{dialogX, dialogY, dialogWidth, dialogHeight});
- }
-}
-
-void NewProjectDialog::render(ui::UIBatchRenderer& renderer) {
- if (!showing_) return;
-
- renderer.drawRect(getBounds(), glm::vec4(0.0f, 0.0f, 0.0f, 0.6f));
-
- for (usize i = 0; i < getChildCount(); ++i) {
- auto* child = getChild(i);
- if (child && child->isVisible()) {
- child->renderTree(renderer);
- }
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/NewProjectDialog.hpp b/src/esengine/editor/panels/NewProjectDialog.hpp
deleted file mode 100644
index 432ac13a5..000000000
--- a/src/esengine/editor/panels/NewProjectDialog.hpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * @file NewProjectDialog.hpp
- * @brief Dialog for creating new projects
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../ui/core/Types.hpp"
-#include "../../events/Signal.hpp"
-#include "../../events/Connection.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine::ui {
-class Button;
-class Label;
-class TextField;
-class Panel;
-}
-
-namespace esengine::editor {
-
-// =============================================================================
-// NewProjectDialog
-// =============================================================================
-
-class NewProjectDialog : public ui::Widget {
-public:
- NewProjectDialog(const ui::WidgetId& id);
- ~NewProjectDialog() override;
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- Signal<void(const std::string& name, const std::string& path)> onProjectCreate;
- Signal<void()> onCancel;
-
- // =========================================================================
- // Methods
- // =========================================================================
-
- void show();
- void hide();
- bool isShowing() const { return showing_; }
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- void layoutChildren(const ui::Rect& contentBounds) override;
-
-private:
- void setupUI();
- void onBrowseClicked();
- void onCreateClicked();
- void onCancelClicked();
-
- ui::Panel* dialogPanel_ = nullptr;
- ui::Label* titleLabel_ = nullptr;
- ui::Label* nameLabel_ = nullptr;
- ui::TextField* nameField_ = nullptr;
- ui::Label* pathLabel_ = nullptr;
- ui::TextField* pathField_ = nullptr;
- ui::Button* browseButton_ = nullptr;
- ui::Button* createButton_ = nullptr;
- ui::Button* cancelButton_ = nullptr;
-
- bool showing_ = false;
- std::vector<Connection> connections_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/OutputLogPanel.cpp b/src/esengine/editor/panels/OutputLogPanel.cpp
deleted file mode 100644
index d520618b7..000000000
--- a/src/esengine/editor/panels/OutputLogPanel.cpp
+++ /dev/null
@@ -1,285 +0,0 @@
-/**
- * @file OutputLogPanel.cpp
- * @brief Output log panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "OutputLogPanel.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/icons/Icons.hpp"
-#include "../../math/Math.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-OutputLogPanel::OutputLogPanel(const ui::WidgetId& id)
- : Widget(id) {
-
- logSinkId_ = Log::addSink([this](const LogEntry& entry) {
- onLogEntry(entry);
- });
-}
-
-OutputLogPanel::~OutputLogPanel() {
- if (logSinkId_ != 0) {
- Log::removeSink(logSinkId_);
- }
-}
-
-// =============================================================================
-// Public Methods
-// =============================================================================
-
-void OutputLogPanel::clear() {
- std::lock_guard<std::mutex> lock(entriesMutex_);
- entries_.clear();
- scrollOffset_ = 0.0f;
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 OutputLogPanel::measure(f32 availableWidth, f32 availableHeight) {
- return {availableWidth, availableHeight};
-}
-
-void OutputLogPanel::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- clearButtonBounds_ = ui::Rect{
- bounds.x + bounds.width - 64.0f,
- bounds.y + 4.0f,
- 24.0f,
- 24.0f
- };
-
- autoScrollButtonBounds_ = ui::Rect{
- bounds.x + bounds.width - 36.0f,
- bounds.y + 4.0f,
- 24.0f,
- 24.0f
- };
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void OutputLogPanel::render(ui::UIBatchRenderer& renderer) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- const ui::Rect& bounds = getBounds();
-
- constexpr glm::vec4 bgColor{0.118f, 0.118f, 0.118f, 1.0f}; // #1e1e1e
- constexpr glm::vec4 toolbarBg{0.145f, 0.145f, 0.149f, 1.0f}; // #252526
- constexpr glm::vec4 borderColor{0.235f, 0.235f, 0.235f, 1.0f}; // #3c3c3c
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 iconColor{0.533f, 0.533f, 0.533f, 1.0f}; // #888
- constexpr glm::vec4 iconHoverColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 activeColor{0.231f, 0.510f, 0.965f, 1.0f}; // #3b82f6
- constexpr glm::vec4 buttonHoverBg{0.235f, 0.235f, 0.235f, 1.0f}; // #3c3c3c
-
- renderer.drawRect(bounds, bgColor);
-
- ui::Rect toolbarBounds{bounds.x, bounds.y, bounds.width, TOOLBAR_HEIGHT};
- renderer.drawRect(toolbarBounds, toolbarBg);
-
- ui::Rect bottomBorder{bounds.x, bounds.y + TOOLBAR_HEIGHT - 1.0f, bounds.width, 1.0f};
- renderer.drawRect(bottomBorder, borderColor);
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* iconFont = ctx->getIconMSDFFont();
- ui::MSDFFont* textFont = ctx->getDefaultMSDFFont();
-#else
- ui::SystemFont* iconFont = ctx->getIconSystemFont();
- ui::SystemFont* textFont = ctx->getDefaultSystemFont();
-#endif
-
- if (iconFont) {
- if (clearHovered_) {
- renderer.drawRoundedRect(clearButtonBounds_, buttonHoverBg, ui::CornerRadii::all(3.0f));
- }
- renderer.drawTextInBounds(ui::icons::Trash2, clearButtonBounds_, *iconFont, 14.0f,
- clearHovered_ ? iconHoverColor : iconColor,
- ui::HAlign::Center, ui::VAlign::Center);
-
- if (autoScrollHovered_) {
- renderer.drawRoundedRect(autoScrollButtonBounds_, buttonHoverBg, ui::CornerRadii::all(3.0f));
- }
- renderer.drawTextInBounds(ui::icons::ChevronsDown, autoScrollButtonBounds_, *iconFont, 14.0f,
- autoScroll_ ? activeColor : (autoScrollHovered_ ? iconHoverColor : iconColor),
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (textFont) {
- ui::Rect logArea{
- bounds.x,
- bounds.y + TOOLBAR_HEIGHT,
- bounds.width,
- bounds.height - TOOLBAR_HEIGHT
- };
-
- renderer.pushClipRect(logArea);
-
- std::lock_guard<std::mutex> lock(entriesMutex_);
-
- f32 y = logArea.y - scrollOffset_;
- usize visibleCount = 0;
-
- for (const auto& entry : entries_) {
- if (!shouldShowEntry(entry.level)) continue;
-
- f32 lineY = y + visibleCount * LINE_HEIGHT;
-
- if (lineY + LINE_HEIGHT < logArea.y) {
- visibleCount++;
- continue;
- }
- if (lineY > logArea.y + logArea.height) {
- break;
- }
-
- glm::vec4 levelColor = getColorForLevel(entry.level);
- const char* prefix = getLevelPrefix(entry.level);
-
- ui::Rect prefixBounds{logArea.x + 8.0f, lineY, 60.0f, LINE_HEIGHT};
- renderer.drawTextInBounds(prefix, prefixBounds, *textFont, 12.0f, levelColor,
- ui::HAlign::Left, ui::VAlign::Center);
-
- ui::Rect msgBounds{logArea.x + 72.0f, lineY, logArea.width - 80.0f, LINE_HEIGHT};
- renderer.drawTextInBounds(entry.message, msgBounds, *textFont, 12.0f, textColor,
- ui::HAlign::Left, ui::VAlign::Center);
-
- visibleCount++;
- }
-
- f32 totalHeight = static_cast<f32>(visibleCount) * LINE_HEIGHT;
- maxScroll_ = glm::max(0.0f, totalHeight - logArea.height);
-
- renderer.popClipRect();
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool OutputLogPanel::onScroll(const ui::ScrollEvent& event) {
- const ui::Rect& bounds = getBounds();
- if (!bounds.contains(event.x, event.y)) {
- return false;
- }
-
- scrollOffset_ -= event.deltaY * 40.0f;
- scrollOffset_ = glm::clamp(scrollOffset_, 0.0f, maxScroll_);
- autoScroll_ = false;
- return true;
-}
-
-bool OutputLogPanel::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button != ui::MouseButton::Left) {
- return false;
- }
-
- if (clearButtonBounds_.contains(event.x, event.y)) {
- clear();
- return true;
- }
-
- if (autoScrollButtonBounds_.contains(event.x, event.y)) {
- autoScroll_ = !autoScroll_;
- if (autoScroll_) {
- scrollOffset_ = maxScroll_;
- }
- return true;
- }
-
- return false;
-}
-
-bool OutputLogPanel::onMouseMove(const ui::MouseMoveEvent& event) {
- clearHovered_ = clearButtonBounds_.contains(event.x, event.y);
- autoScrollHovered_ = autoScrollButtonBounds_.contains(event.x, event.y);
- return false;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void OutputLogPanel::onLogEntry(const LogEntry& entry) {
- std::lock_guard<std::mutex> lock(entriesMutex_);
-
- entries_.push_back(entry);
-
- while (entries_.size() > MAX_LOG_ENTRIES) {
- entries_.pop_front();
- }
-
- if (autoScroll_) {
- usize visibleCount = 0;
- for (const auto& e : entries_) {
- if (shouldShowEntry(e.level)) visibleCount++;
- }
- f32 totalHeight = static_cast<f32>(visibleCount) * LINE_HEIGHT;
- const ui::Rect& bounds = getBounds();
- f32 logAreaHeight = bounds.height - TOOLBAR_HEIGHT;
- maxScroll_ = glm::max(0.0f, totalHeight - logAreaHeight);
- scrollOffset_ = maxScroll_;
- }
-}
-
-bool OutputLogPanel::shouldShowEntry(LogLevel level) const {
- switch (level) {
- case LogLevel::Trace: return showTrace_;
- case LogLevel::Debug: return showDebug_;
- case LogLevel::Info: return showInfo_;
- case LogLevel::Warn: return showWarn_;
- case LogLevel::Error:
- case LogLevel::Fatal: return showError_;
- default: return true;
- }
-}
-
-glm::vec4 OutputLogPanel::getColorForLevel(LogLevel level) const {
- switch (level) {
- case LogLevel::Trace: return {0.533f, 0.533f, 0.533f, 1.0f}; // gray
- case LogLevel::Debug: return {0.533f, 0.533f, 0.533f, 1.0f}; // gray
- case LogLevel::Info: return {0.231f, 0.510f, 0.965f, 1.0f}; // blue
- case LogLevel::Warn: return {0.902f, 0.667f, 0.157f, 1.0f}; // yellow/orange
- case LogLevel::Error:
- case LogLevel::Fatal: return {0.937f, 0.325f, 0.314f, 1.0f}; // red
- default: return {0.878f, 0.878f, 0.878f, 1.0f};
- }
-}
-
-const char* OutputLogPanel::getLevelPrefix(LogLevel level) const {
- switch (level) {
- case LogLevel::Trace: return "[TRACE]";
- case LogLevel::Debug: return "[DEBUG]";
- case LogLevel::Info: return "[INFO]";
- case LogLevel::Warn: return "[WARN]";
- case LogLevel::Error: return "[ERROR]";
- case LogLevel::Fatal: return "[FATAL]";
- default: return "[???]";
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/OutputLogPanel.hpp b/src/esengine/editor/panels/OutputLogPanel.hpp
deleted file mode 100644
index 3e33006cb..000000000
--- a/src/esengine/editor/panels/OutputLogPanel.hpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * @file OutputLogPanel.hpp
- * @brief Output log panel for displaying engine log messages
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../core/Log.hpp"
-
-#include <deque>
-#include <mutex>
-
-namespace esengine::editor {
-
-// =============================================================================
-// OutputLogPanel Class
-// =============================================================================
-
-class OutputLogPanel : public ui::Widget {
-public:
- static constexpr usize MAX_LOG_ENTRIES = 1000;
- static constexpr f32 LINE_HEIGHT = 18.0f;
- static constexpr f32 TOOLBAR_HEIGHT = 32.0f;
-
- explicit OutputLogPanel(const ui::WidgetId& id);
- ~OutputLogPanel() override;
-
- void clear();
-
- void setShowTrace(bool show) { showTrace_ = show; }
- void setShowDebug(bool show) { showDebug_ = show; }
- void setShowInfo(bool show) { showInfo_ = show; }
- void setShowWarn(bool show) { showWarn_ = show; }
- void setShowError(bool show) { showError_ = show; }
-
- bool isShowTrace() const { return showTrace_; }
- bool isShowDebug() const { return showDebug_; }
- bool isShowInfo() const { return showInfo_; }
- bool isShowWarn() const { return showWarn_; }
- bool isShowError() const { return showError_; }
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(ui::UIBatchRenderer& renderer) override;
- bool onScroll(const ui::ScrollEvent& event) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
-
-protected:
- void layoutChildren(const ui::Rect& contentBounds) override;
-
-private:
- void onLogEntry(const LogEntry& entry);
- bool shouldShowEntry(LogLevel level) const;
- glm::vec4 getColorForLevel(LogLevel level) const;
- const char* getLevelPrefix(LogLevel level) const;
-
- std::deque<LogEntry> entries_;
- std::mutex entriesMutex_;
- u32 logSinkId_ = 0;
-
- f32 scrollOffset_ = 0.0f;
- f32 maxScroll_ = 0.0f;
- bool autoScroll_ = true;
-
- bool showTrace_ = true;
- bool showDebug_ = true;
- bool showInfo_ = true;
- bool showWarn_ = true;
- bool showError_ = true;
-
- ui::Rect clearButtonBounds_;
- ui::Rect autoScrollButtonBounds_;
- bool clearHovered_ = false;
- bool autoScrollHovered_ = false;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/ProjectLauncherPanel.cpp b/src/esengine/editor/panels/ProjectLauncherPanel.cpp
deleted file mode 100644
index a6645dd40..000000000
--- a/src/esengine/editor/panels/ProjectLauncherPanel.cpp
+++ /dev/null
@@ -1,276 +0,0 @@
-/**
- * @file ProjectLauncherPanel.cpp
- * @brief Project launcher panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ProjectLauncherPanel.hpp"
-#include "../project/ProjectManager.hpp"
-#include "../project/ProjectTypes.hpp"
-#include "../../events/Dispatcher.hpp"
-#include "../../ui/widgets/Button.hpp"
-#include "../../ui/widgets/Label.hpp"
-#include "../../ui/widgets/Panel.hpp"
-#include "../../ui/widgets/ScrollView.hpp"
-#include "../../ui/layout/StackLayout.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/icons/Icons.hpp"
-#include "../../core/Log.hpp"
-
-namespace esengine::editor {
-
-namespace {
-
-glm::vec4 hexColor(u32 hex, f32 alpha = 1.0f) {
- return glm::vec4(
- ((hex >> 16) & 0xFF) / 255.0f,
- ((hex >> 8) & 0xFF) / 255.0f,
- (hex & 0xFF) / 255.0f,
- alpha
- );
-}
-
-constexpr f32 HEADER_PADDING_TOP = 60.0f;
-constexpr f32 HEADER_PADDING_HORIZONTAL = 40.0f;
-constexpr f32 HEADER_PADDING_BOTTOM = 40.0f;
-constexpr f32 CONTENT_GAP = 60.0f;
-constexpr f32 ACTIONS_MIN_WIDTH = 280.0f;
-constexpr f32 RECENT_MAX_WIDTH = 600.0f;
-constexpr f32 FOOTER_HEIGHT = 50.0f;
-constexpr f32 BUTTON_HEIGHT = 40.0f;
-constexpr f32 BUTTON_GAP = 12.0f;
-constexpr f32 RECENT_ITEM_HEIGHT = 52.0f;
-
-} // namespace
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-ProjectLauncherPanel::ProjectLauncherPanel(const ui::WidgetId& id,
- ProjectManager& projectManager,
- Dispatcher& dispatcher)
- : Widget(id)
- , project_manager_(projectManager)
- , dispatcher_(dispatcher) {
- setupUI();
- refreshRecentProjects();
-}
-
-ProjectLauncherPanel::~ProjectLauncherPanel() = default;
-
-// =============================================================================
-// Setup
-// =============================================================================
-
-void ProjectLauncherPanel::setupUI() {
- auto leftPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".left"));
- leftPanel->setBackgroundColor(hexColor(0x1e1e1e));
- auto leftLayout = makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f);
- leftPanel->setLayout(std::move(leftLayout));
- leftPanel->setPadding(ui::Insets(HEADER_PADDING_TOP, HEADER_PADDING_HORIZONTAL,
- HEADER_PADDING_BOTTOM, HEADER_PADDING_HORIZONTAL));
- leftPanel_ = leftPanel.get();
-
- auto titleLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".title"), "ESEngine Editor");
- titleLabel->setFontSize(32.0f);
- titleLabel->setColor(hexColor(0xffffff));
- titleLabel_ = titleLabel.get();
- leftPanel->addChild(std::move(titleLabel));
-
- auto subtitleSpacer = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".subtitle_spacer"));
- subtitleSpacer->setHeight(ui::SizeValue::px(8.0f));
- leftPanel->addChild(std::move(subtitleSpacer));
-
- auto subtitleLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".subtitle"),
- "Professional Game Development Tool");
- subtitleLabel->setFontSize(14.0f);
- subtitleLabel->setColor(hexColor(0x858585));
- subtitleLabel_ = subtitleLabel.get();
- leftPanel->addChild(std::move(subtitleLabel));
-
- auto actionsSpacer = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".actions_spacer"));
- actionsSpacer->setHeight(ui::SizeValue::px(40.0f));
- leftPanel->addChild(std::move(actionsSpacer));
-
- auto openProjectButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + ".open"),
- "Open Project");
- openProjectButton->setButtonStyle(ui::ButtonStyle::Primary);
- openProjectButton->setWidth(ui::SizeValue::percent(100.0f));
- openProjectButton->setHeight(ui::SizeValue::px(BUTTON_HEIGHT));
- openProjectButton->setFontSize(13.0f);
- openProjectButton->setCornerRadii(ui::CornerRadii::all(2.0f));
- openProjectButton_ = openProjectButton.get();
- connections_.push_back(
- sink(openProjectButton_->onClick).connect([this]() {
- ES_LOG_INFO("ProjectLauncher: Browse project requested");
- onBrowseProjectRequested.publish();
- }));
- leftPanel->addChild(std::move(openProjectButton));
-
- auto buttonSpacer = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".button_spacer"));
- buttonSpacer->setHeight(ui::SizeValue::px(BUTTON_GAP));
- leftPanel->addChild(std::move(buttonSpacer));
-
- auto newProjectButton = makeUnique<ui::Button>(ui::WidgetId(getId().path + ".new"),
- "Create Project");
- newProjectButton->setButtonStyle(ui::ButtonStyle::Secondary);
- newProjectButton->setWidth(ui::SizeValue::percent(100.0f));
- newProjectButton->setHeight(ui::SizeValue::px(BUTTON_HEIGHT));
- newProjectButton->setFontSize(13.0f);
- newProjectButton->setCornerRadii(ui::CornerRadii::all(2.0f));
- newProjectButton_ = newProjectButton.get();
- connections_.push_back(
- sink(newProjectButton_->onClick).connect([this]() {
- ES_LOG_INFO("ProjectLauncher: New project requested");
- onCreateProjectRequested.publish();
- }));
- leftPanel->addChild(std::move(newProjectButton));
-
- auto flexSpacer = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".flex_spacer"));
- flexSpacer->setHeight(ui::SizeValue::percent(100.0f));
- leftPanel->addChild(std::move(flexSpacer));
-
- auto versionLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".version"),
- "Version 1.0.0");
- versionLabel->setFontSize(11.0f);
- versionLabel->setColor(hexColor(0x6e6e6e));
- versionLabel_ = versionLabel.get();
- leftPanel->addChild(std::move(versionLabel));
-
- addChild(std::move(leftPanel));
-
- auto rightPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".right"));
- rightPanel->setBackgroundColor(hexColor(0x1e1e1e));
- auto rightLayout = makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 0.0f);
- rightPanel->setLayout(std::move(rightLayout));
- rightPanel->setPadding(ui::Insets(HEADER_PADDING_TOP, HEADER_PADDING_HORIZONTAL,
- HEADER_PADDING_BOTTOM, HEADER_PADDING_HORIZONTAL));
- rightPanel_ = rightPanel.get();
-
- auto recentLabel = makeUnique<ui::Label>(ui::WidgetId(getId().path + ".recent_label"),
- "RECENT PROJECTS");
- recentLabel->setFontSize(13.0f);
- recentLabel->setColor(hexColor(0xcccccc));
- recentLabel_ = recentLabel.get();
- rightPanel->addChild(std::move(recentLabel));
-
- auto recentSpacer = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".recent_spacer"));
- recentSpacer->setHeight(ui::SizeValue::px(16.0f));
- rightPanel->addChild(std::move(recentSpacer));
-
- auto recentScrollView = makeUnique<ui::ScrollView>(
- ui::WidgetId(getId().path + ".recent_scroll"));
- recentScrollView->setScrollDirection(ui::ScrollDirection::Vertical);
- recentScrollView->setShowScrollbars(true);
- recentScrollView->setWidth(ui::SizeValue::percent(100.0f));
- recentScrollView->setHeight(ui::SizeValue::percent(100.0f));
- recentScrollView_ = recentScrollView.get();
-
- auto recentListPanel = makeUnique<ui::Panel>(ui::WidgetId(getId().path + ".recent_list"));
- auto listLayout = makeUnique<ui::StackLayout>(ui::StackDirection::Vertical, 1.0f);
- recentListPanel->setLayout(std::move(listLayout));
- recentListPanel_ = recentListPanel.get();
- recentScrollView->setContent(std::move(recentListPanel));
-
- rightPanel->addChild(std::move(recentScrollView));
-
- addChild(std::move(rightPanel));
-}
-
-// =============================================================================
-// Recent Projects
-// =============================================================================
-
-void ProjectLauncherPanel::refreshRecentProjects() {
- if (!recentListPanel_) return;
-
- recentListPanel_->clearChildren();
-
- const auto& recentProjects = project_manager_.getRecentProjects().getRecentProjects();
-
- if (recentProjects.empty()) {
- auto emptyLabel = makeUnique<ui::Label>(
- ui::WidgetId(getId().path + ".empty"),
- "No recent projects");
- emptyLabel->setFontSize(13.0f);
- emptyLabel->setColor(hexColor(0x858585));
- recentListPanel_->addChild(std::move(emptyLabel));
- return;
- }
-
- for (usize i = 0; i < recentProjects.size(); ++i) {
- createRecentProjectItem(recentProjects[i], recentListPanel_, i);
- }
-}
-
-void ProjectLauncherPanel::createRecentProjectItem(const RecentProject& project,
- ui::Panel* container, usize index) {
- std::string itemId = getId().path + ".item_" + std::to_string(index);
- std::string projectPath = project.path;
-
- auto itemButton = makeUnique<ui::Button>(ui::WidgetId(itemId), project.name);
- itemButton->setButtonStyle(ui::ButtonStyle::Ghost);
- itemButton->setWidth(ui::SizeValue::percent(100.0f));
- itemButton->setHeight(ui::SizeValue::px(RECENT_ITEM_HEIGHT));
- itemButton->setFontSize(13.0f);
- itemButton->setCornerRadii(ui::CornerRadii::all(2.0f));
- itemButton->setTextAlignment(ui::HAlign::Left);
-
- connections_.push_back(
- sink(itemButton->onClick).connect([this, projectPath]() {
- ES_LOG_INFO("ProjectLauncher: Opening project {}", projectPath);
- onProjectOpened.publish(projectPath);
- }));
-
- container->addChild(std::move(itemButton));
-}
-
-// =============================================================================
-// Widget Overrides
-// =============================================================================
-
-glm::vec2 ProjectLauncherPanel::measure(f32 availableWidth, f32 availableHeight) {
- return glm::vec2(availableWidth, availableHeight);
-}
-
-void ProjectLauncherPanel::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 contentWidth = bounds.width - HEADER_PADDING_HORIZONTAL * 2;
- f32 leftWidth = ACTIONS_MIN_WIDTH;
- f32 rightWidth = contentWidth - leftWidth - CONTENT_GAP;
-
- if (rightWidth > RECENT_MAX_WIDTH) {
- rightWidth = RECENT_MAX_WIDTH;
- }
-
- if (leftPanel_) {
- leftPanel_->layout(ui::Rect{
- bounds.x,
- bounds.y,
- leftWidth + HEADER_PADDING_HORIZONTAL * 2,
- bounds.height
- });
- }
-
- if (rightPanel_) {
- rightPanel_->layout(ui::Rect{
- bounds.x + leftWidth + HEADER_PADDING_HORIZONTAL * 2 + CONTENT_GAP,
- bounds.y,
- rightWidth + HEADER_PADDING_HORIZONTAL * 2,
- bounds.height
- });
- }
-}
-
-void ProjectLauncherPanel::render(ui::UIBatchRenderer& renderer) {
- renderer.drawRect(getBounds(), hexColor(0x1e1e1e));
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/ProjectLauncherPanel.hpp b/src/esengine/editor/panels/ProjectLauncherPanel.hpp
deleted file mode 100644
index 7ea76a605..000000000
--- a/src/esengine/editor/panels/ProjectLauncherPanel.hpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * @file ProjectLauncherPanel.hpp
- * @brief Project launcher panel for selecting or creating projects
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../ui/core/Types.hpp"
-#include "../../events/Signal.hpp"
-#include "../../events/Connection.hpp"
-#include "../project/ProjectTypes.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine {
-class Dispatcher;
-}
-
-namespace esengine::ui {
-class Panel;
-class Label;
-class Button;
-class ScrollView;
-}
-
-namespace esengine::editor {
-
-class ProjectManager;
-
-// =============================================================================
-// ProjectLauncherPanel
-// =============================================================================
-
-class ProjectLauncherPanel : public ui::Widget {
-public:
- ProjectLauncherPanel(const ui::WidgetId& id, ProjectManager& projectManager,
- Dispatcher& dispatcher);
- ~ProjectLauncherPanel() override;
-
- Signal<void(const std::string&)> onProjectOpened;
- Signal<void()> onCreateProjectRequested;
- Signal<void()> onBrowseProjectRequested;
-
- void refreshRecentProjects();
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- void layoutChildren(const ui::Rect& contentBounds) override;
-
-private:
- void setupUI();
- void createRecentProjectItem(const RecentProject& project, ui::Panel* container, usize index);
-
- ProjectManager& project_manager_;
- Dispatcher& dispatcher_;
-
- ui::Panel* leftPanel_ = nullptr;
- ui::Panel* rightPanel_ = nullptr;
- ui::Label* titleLabel_ = nullptr;
- ui::Label* subtitleLabel_ = nullptr;
- ui::Button* newProjectButton_ = nullptr;
- ui::Button* openProjectButton_ = nullptr;
- ui::Label* versionLabel_ = nullptr;
- ui::Label* recentLabel_ = nullptr;
- ui::ScrollView* recentScrollView_ = nullptr;
- ui::Panel* recentListPanel_ = nullptr;
-
- std::vector<Connection> connections_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/SceneViewPanel.cpp b/src/esengine/editor/panels/SceneViewPanel.cpp
deleted file mode 100644
index f7bb722fe..000000000
--- a/src/esengine/editor/panels/SceneViewPanel.cpp
+++ /dev/null
@@ -1,1168 +0,0 @@
-/**
- * @file SceneViewPanel.cpp
- * @brief Scene view panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "SceneViewPanel.hpp"
-#include "../../renderer/RenderCommand.hpp"
-#include "../../renderer/RenderContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../ecs/components/Sprite.hpp"
-#include "../../ecs/components/Canvas.hpp"
-#include "../../core/Log.hpp"
-#include "../command/TransformCommand.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-
-#include <glad/glad.h>
-#include <cstdio>
-#include <vector>
-#include <chrono>
-
-#ifndef GL_VIEWPORT
-#define GL_VIEWPORT 0x0BA2
-#endif
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-SceneViewPanel::SceneViewPanel(ecs::Registry& registry, EntitySelection& selection,
- resource::ResourceManager& resourceManager)
- : DockPanel(ui::WidgetId("scene_view_panel"), "Scene"),
- registry_(registry),
- selection_(selection),
- resourceManager_(resourceManager) {
-
- FramebufferSpec spec;
- spec.width = viewportWidth_;
- spec.height = viewportHeight_;
- spec.depthStencil = true;
- framebuffer_ = Framebuffer::create(spec);
-
- camera_.setViewportSize(static_cast<f32>(viewportWidth_), static_cast<f32>(viewportHeight_));
- camera_.setFocalPoint(glm::vec3(0.0f));
- camera_.setDistance(10.0f);
-
- toolbar_ = makeUnique<SceneToolbar>(ui::WidgetId("scene_toolbar"));
-
- connections_.add(sink(toolbar_->onViewModeChanged).connect([this](ViewMode mode) {
- setViewMode(mode);
- }));
-
- connections_.add(sink(toolbar_->onGridVisibilityChanged).connect([this](bool visible) {
- gridVisible_ = visible;
- }));
-
- connections_.add(sink(toolbar_->onGizmosVisibilityChanged).connect([this](bool visible) {
- gizmosVisible_ = visible;
- }));
-
- transformGizmo_ = makeUnique<TransformGizmo>(resourceManager);
- transformGizmo_->setSize(1.5f);
-
- connections_.add(sink(toolbar_->onGizmoModeChanged).connect([this](GizmoMode mode) {
- transformGizmo_->setMode(mode);
- }));
-
- connections_.add(sink(toolbar_->onStatsVisibilityChanged).connect([this](bool visible) {
- stats_visible_ = visible;
- }));
-
- setMinSize(glm::vec2(200.0f, 200.0f));
-}
-
-// =============================================================================
-// Configuration
-// =============================================================================
-
-void SceneViewPanel::setViewportSize(u32 width, u32 height) {
- if (width == viewportWidth_ && height == viewportHeight_) {
- return;
- }
-
- viewportWidth_ = width;
- viewportHeight_ = height;
- framebufferNeedsResize_ = true;
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-void SceneViewPanel::render(ui::UIBatchRenderer& renderer) {
- using Clock = std::chrono::steady_clock;
- static auto startTime = Clock::now();
- f64 currentTime = std::chrono::duration<f64>(Clock::now() - startTime).count();
- f32 deltaTime = static_cast<f32>(currentTime - last_frame_time_);
- prev_frame_time_ = last_frame_time_;
- last_frame_time_ = currentTime;
-
- if (deltaTime > 0.0f && deltaTime < 1.0f) {
- camera_.update(deltaTime);
- }
-
- const ui::Rect& bounds = getBounds();
-
- ui::Rect toolbarBounds = {bounds.x, bounds.y, bounds.width, SceneToolbar::HEIGHT};
- viewportBounds_ = {
- bounds.x,
- bounds.y + SceneToolbar::HEIGHT,
- bounds.width,
- bounds.height - SceneToolbar::HEIGHT
- };
-
- u32 newWidth = static_cast<u32>(viewportBounds_.width);
- u32 newHeight = static_cast<u32>(viewportBounds_.height);
-
- if (newWidth != viewportWidth_ || newHeight != viewportHeight_) {
- setViewportSize(newWidth, newHeight);
- }
-
- if (framebufferNeedsResize_) {
- updateFramebufferSize();
- }
-
- if (framebuffer_) {
- renderSceneToTexture();
-
- renderer.drawTexturedRect(
- viewportBounds_,
- framebuffer_->getColorAttachment(),
- glm::vec4(1.0f),
- glm::vec2(0.0f, 1.0f),
- glm::vec2(1.0f, 0.0f)
- );
-
- renderer.flush();
- if (gizmosVisible_) {
- if (viewMode_ == ViewMode::Mode3D) {
- renderAxisGizmo();
- } else {
- renderAxisGizmo2D();
- }
- }
-
- if (stats_visible_) {
- renderStats(renderer);
- }
- }
-
- if (toolbar_) {
- toolbar_->setContext(getContext());
- toolbar_->measure(toolbarBounds.width, toolbarBounds.height);
- toolbar_->layout(toolbarBounds);
- toolbar_->render(renderer);
- }
-}
-
-bool SceneViewPanel::onMouseDown(const ui::MouseButtonEvent& event) {
- if (toolbar_ && toolbar_->getBounds().contains(event.x, event.y)) {
- return toolbar_->onMouseDown(event);
- }
-
- if (viewMode_ == ViewMode::Mode3D) {
- if (event.button == ui::MouseButton::Left && !event.alt && !event.ctrl && !event.shift) {
- i32 axisHit = hitTestAxisGizmo(event.x, event.y);
- if (axisHit >= 0) {
- switch (axisHit) {
- case 0: setViewToRight(); break;
- case 1: setViewToTop(); break;
- case 2: setViewToFront(); break;
- case 3: setViewToLeft(); break;
- case 4: setViewToBottom(); break;
- case 5: setViewToBack(); break;
- }
- return true;
- }
- }
- }
-
- if (event.button == ui::MouseButton::Left && !event.alt) {
- if (viewportBounds_.contains(event.x, event.y)) {
- glm::vec3 rayOrigin, rayDir;
- screenToWorldRay(event.x, event.y, rayOrigin, rayDir);
-
- if (gizmosVisible_ && selection_.count() > 0) {
- GizmoAxis axis = transformGizmo_->hitTest(rayOrigin, rayDir);
- if (axis != GizmoAxis::None) {
- Entity selected = selection_.getFirst();
- if (selected != INVALID_ENTITY && registry_.has<ecs::LocalTransform>(selected)) {
- draggingEntity_ = selected;
- dragStartTransform_ = registry_.get<ecs::LocalTransform>(selected);
- }
- transformGizmo_->startDrag(axis, rayOrigin, rayDir);
- return true;
- }
- }
-
- Entity hit = pickEntity(rayOrigin, rayDir);
- if (hit != INVALID_ENTITY) {
- if (event.ctrl) {
- selection_.toggleSelection(hit);
- } else {
- selection_.select(hit);
- }
- } else if (!event.ctrl) {
- selection_.clear();
- }
- return true;
- }
- }
-
- camera_.onMouseDown(event);
- return true;
-}
-
-bool SceneViewPanel::onMouseUp(const ui::MouseButtonEvent& event) {
- if (transformGizmo_->isDragging()) {
- transformGizmo_->endDrag();
-
- if (commandHistory_ && draggingEntity_ != INVALID_ENTITY &&
- registry_.has<ecs::LocalTransform>(draggingEntity_)) {
- const auto& currentTransform = registry_.get<ecs::LocalTransform>(draggingEntity_);
-
- if (currentTransform.position != dragStartTransform_.position ||
- currentTransform.rotation != dragStartTransform_.rotation ||
- currentTransform.scale != dragStartTransform_.scale) {
- commandHistory_->execute(makeUnique<TransformCommand>(
- registry_, draggingEntity_, dragStartTransform_, currentTransform));
- }
- }
-
- draggingEntity_ = INVALID_ENTITY;
- }
- camera_.onMouseUp(event);
- return true;
-}
-
-bool SceneViewPanel::onMouseMove(const ui::MouseMoveEvent& event) {
- if (toolbar_) {
- toolbar_->onMouseMove(event);
- }
-
- if (transformGizmo_->isDragging()) {
- glm::vec3 rayOrigin, rayDir;
- screenToWorldRay(event.x, event.y, rayOrigin, rayDir);
-
- glm::vec3 delta = transformGizmo_->updateDrag(rayOrigin, rayDir);
-
- Entity selected = selection_.getFirst();
- if (selected != INVALID_ENTITY && registry_.has<ecs::LocalTransform>(selected)) {
- auto& transform = registry_.get<ecs::LocalTransform>(selected);
-
- switch (transformGizmo_->getMode()) {
- case GizmoMode::Translate:
- transform.position = dragStartTransform_.position + delta;
- break;
- case GizmoMode::Scale:
- transform.scale = dragStartTransform_.scale + delta;
- break;
- case GizmoMode::Rotate: {
- f32 rotationDelta = transformGizmo_->getRotationDelta();
- GizmoAxis axis = transformGizmo_->getActiveAxis();
- glm::vec3 rotationAxis(0.0f);
- if (axis == GizmoAxis::X) {
- rotationAxis = glm::vec3(1, 0, 0);
- } else if (axis == GizmoAxis::Y) {
- rotationAxis = glm::vec3(0, 1, 0);
- } else if (axis == GizmoAxis::Z) {
- rotationAxis = glm::vec3(0, 0, 1);
- }
- glm::quat deltaRotation = glm::angleAxis(rotationDelta, rotationAxis);
- transform.rotation = deltaRotation * dragStartTransform_.rotation;
- break;
- }
- }
- }
- return true;
- }
-
- camera_.onMouseMove(event);
- return true;
-}
-
-bool SceneViewPanel::onScroll(const ui::ScrollEvent& event) {
- camera_.onMouseScroll(event);
- return true;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void SceneViewPanel::renderSceneToTexture() {
- if (!framebuffer_) {
- return;
- }
-
- // Save current viewport
- GLint savedViewport[4];
- glGetIntegerv(GL_VIEWPORT, savedViewport);
-
- framebuffer_->bind();
-
- RenderCommand::setViewport(0, 0, viewportWidth_, viewportHeight_);
- RenderCommand::setClearColor(glm::vec4(0.2f, 0.2f, 0.2f, 1.0f));
- RenderCommand::clear();
-
- renderSceneContent();
-
- framebuffer_->unbind();
-
- // Restore viewport
- glViewport(savedViewport[0], savedViewport[1], savedViewport[2], savedViewport[3]);
-}
-
-void SceneViewPanel::renderSceneContent() {
- glm::mat4 view = camera_.getViewMatrix();
- glm::mat4 proj = camera_.getProjectionMatrix();
- glm::mat4 viewProj = proj * view;
-
- if (viewMode_ == ViewMode::Mode2D) {
- if (gridVisible_) {
- if (!grid2DInitialized_) {
- initGrid2DData();
- }
- renderGrid2D(viewProj);
- }
- if (gizmosVisible_) {
- renderCanvasGizmo(viewProj);
- }
- } else {
- if (gridVisible_) {
- if (!gridInitialized_) {
- initGridData();
- }
- renderGrid(viewProj);
- }
- }
- renderSprites(viewProj);
-
- if (gizmosVisible_ && selection_.count() > 0) {
- renderSelectionBox(viewProj);
-
- Entity selected = selection_.getFirst();
- if (selected != INVALID_ENTITY) {
- transformGizmo_->render(view, proj, selected, registry_);
- }
- }
-}
-
-void SceneViewPanel::initGridData() {
- std::vector<f32> vertices;
-
- constexpr f32 gridSize = 100.0f;
- constexpr f32 gridStep = 1.0f;
-
- for (f32 x = -gridSize; x <= gridSize; x += gridStep) {
- vertices.push_back(x);
- vertices.push_back(0.0f);
- vertices.push_back(-gridSize);
-
- vertices.push_back(x);
- vertices.push_back(0.0f);
- vertices.push_back(gridSize);
- }
-
- for (f32 z = -gridSize; z <= gridSize; z += gridStep) {
- vertices.push_back(-gridSize);
- vertices.push_back(0.0f);
- vertices.push_back(z);
-
- vertices.push_back(gridSize);
- vertices.push_back(0.0f);
- vertices.push_back(z);
- }
-
- gridVertexCount_ = static_cast<u32>(vertices.size() / 3);
-
- gridVAO_ = VertexArray::create();
-
- auto vbo = VertexBuffer::createRaw(vertices.data(), static_cast<u32>(vertices.size() * sizeof(f32)));
- vbo->setLayout({
- { ShaderDataType::Float3, "a_position" }
- });
-
- gridVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
-
- gridShaderHandle_ = resourceManager_.loadEngineShader("grid");
-
- gridInitialized_ = true;
- ES_LOG_DEBUG("Grid initialized with {} vertices", gridVertexCount_);
-}
-
-void SceneViewPanel::renderGrid(const glm::mat4& viewProj) {
- Shader* gridShader = resourceManager_.getShader(gridShaderHandle_);
- if (!gridVAO_ || !gridShader) return;
-
- gridShader->bind();
- gridShader->setUniform("u_viewProj", viewProj);
- gridShader->setUniform("u_color", glm::vec4(0.3f, 0.3f, 0.3f, 1.0f));
-
- gridVAO_->bind();
- glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(gridVertexCount_));
-}
-
-void SceneViewPanel::initGrid2DData() {
- std::vector<f32> vertices;
-
- constexpr f32 gridSize = 100.0f;
- constexpr f32 gridStep = 1.0f;
-
- for (f32 x = -gridSize; x <= gridSize; x += gridStep) {
- vertices.push_back(x);
- vertices.push_back(-gridSize);
- vertices.push_back(0.0f);
-
- vertices.push_back(x);
- vertices.push_back(gridSize);
- vertices.push_back(0.0f);
- }
-
- for (f32 y = -gridSize; y <= gridSize; y += gridStep) {
- vertices.push_back(-gridSize);
- vertices.push_back(y);
- vertices.push_back(0.0f);
-
- vertices.push_back(gridSize);
- vertices.push_back(y);
- vertices.push_back(0.0f);
- }
-
- grid2DVertexCount_ = static_cast<u32>(vertices.size() / 3);
-
- grid2DVAO_ = VertexArray::create();
-
- auto vbo = VertexBuffer::createRaw(vertices.data(), static_cast<u32>(vertices.size() * sizeof(f32)));
- vbo->setLayout({
- { ShaderDataType::Float3, "a_position" }
- });
-
- grid2DVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
-
- if (!gridShaderHandle_.isValid()) {
- gridShaderHandle_ = resourceManager_.loadEngineShader("grid");
- }
-
- grid2DInitialized_ = true;
- ES_LOG_DEBUG("2D Grid initialized with {} vertices", grid2DVertexCount_);
-}
-
-void SceneViewPanel::renderGrid2D(const glm::mat4& viewProj) {
- Shader* gridShader = resourceManager_.getShader(gridShaderHandle_);
- if (!grid2DVAO_ || !gridShader) return;
-
- gridShader->bind();
- gridShader->setUniform("u_viewProj", viewProj);
- gridShader->setUniform("u_color", glm::vec4(0.3f, 0.3f, 0.3f, 1.0f));
-
- grid2DVAO_->bind();
- glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(grid2DVertexCount_));
-}
-
-void SceneViewPanel::renderSprites(const glm::mat4& viewProj) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- RenderContext& renderCtx = ctx->getRenderContext();
-
- // Lazy initialize RenderPipeline
- if (!renderPipeline_) {
- renderPipeline_ = makeUnique<RenderPipeline>(renderCtx, resourceManager_);
- }
-
- // Use RenderPipeline for sprite rendering
- renderPipeline_->begin(viewProj);
- renderPipeline_->submit(registry_);
- renderPipeline_->end();
-}
-
-void SceneViewPanel::renderSelectionBox(const glm::mat4& viewProj) {
- Shader* shader = resourceManager_.getShader(resourceManager_.loadEngineShader("gizmo"));
- if (!shader) return;
-
- glDisable(GL_DEPTH_TEST);
-
- const auto& selectedEntities = selection_.getSelected();
- for (Entity entity : selectedEntities) {
- if (!registry_.valid(entity) || !registry_.has<ecs::LocalTransform>(entity)) {
- continue;
- }
-
- const auto& transform = registry_.get<ecs::LocalTransform>(entity);
-
- glm::vec3 halfSize(0.5f);
- if (registry_.has<ecs::Sprite>(entity)) {
- const auto& sprite = registry_.get<ecs::Sprite>(entity);
- halfSize = glm::vec3(sprite.size.x * 0.5f * transform.scale.x, sprite.size.y * 0.5f * transform.scale.y, 0.01f);
- }
-
- glm::mat4 model = glm::translate(glm::mat4(1.0f), transform.position);
- model *= glm::mat4_cast(transform.rotation);
-
- glm::vec4 color(1.0f, 0.6f, 0.0f, 1.0f);
-
- glm::vec3 corners[8] = {
- glm::vec3(-halfSize.x, -halfSize.y, -halfSize.z),
- glm::vec3( halfSize.x, -halfSize.y, -halfSize.z),
- glm::vec3( halfSize.x, halfSize.y, -halfSize.z),
- glm::vec3(-halfSize.x, halfSize.y, -halfSize.z),
- glm::vec3(-halfSize.x, -halfSize.y, halfSize.z),
- glm::vec3( halfSize.x, -halfSize.y, halfSize.z),
- glm::vec3( halfSize.x, halfSize.y, halfSize.z),
- glm::vec3(-halfSize.x, halfSize.y, halfSize.z)
- };
-
- std::vector<f32> vertices;
- auto addLine = [&](i32 a, i32 b) {
- vertices.insert(vertices.end(), {corners[a].x, corners[a].y, corners[a].z, color.r, color.g, color.b, color.a});
- vertices.insert(vertices.end(), {corners[b].x, corners[b].y, corners[b].z, color.r, color.g, color.b, color.a});
- };
-
- // Bottom face
- addLine(0, 1); addLine(1, 2); addLine(2, 3); addLine(3, 0);
- // Top face
- addLine(4, 5); addLine(5, 6); addLine(6, 7); addLine(7, 4);
- // Vertical edges
- addLine(0, 4); addLine(1, 5); addLine(2, 6); addLine(3, 7);
-
- Unique<VertexArray> vao = VertexArray::create();
- auto vbo = VertexBuffer::createRaw(vertices.data(), static_cast<u32>(vertices.size() * sizeof(f32)));
- vbo->setLayout({
- { ShaderDataType::Float3, "a_position" },
- { ShaderDataType::Float4, "a_color" }
- });
- vao->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
-
- shader->bind();
- shader->setUniform("u_viewProj", viewProj);
- shader->setUniform("u_model", model);
-
- vao->bind();
- glDrawArrays(GL_LINES, 0, 24);
- vao->unbind();
- }
-
- glEnable(GL_DEPTH_TEST);
-}
-
-void SceneViewPanel::updateFramebufferSize() {
- if (viewportWidth_ == 0 || viewportHeight_ == 0) {
- return;
- }
-
- if (framebuffer_) {
- framebuffer_->resize(viewportWidth_, viewportHeight_);
- camera_.setViewportSize(static_cast<f32>(viewportWidth_), static_cast<f32>(viewportHeight_));
- framebufferNeedsResize_ = false;
- }
-}
-
-void SceneViewPanel::initAxisGizmoData() {
- std::vector<f32> vertices;
-
- auto addVertex = [&vertices](const glm::vec3& pos, const glm::vec4& color) {
- vertices.insert(vertices.end(), {pos.x, pos.y, pos.z, color.r, color.g, color.b, color.a});
- };
-
- auto addCone = [&](const glm::vec3& base, const glm::vec3& tip, f32 radius,
- const glm::vec4& color, i32 segments = 16) {
- glm::vec3 dir = glm::normalize(tip - base);
- glm::vec3 up = glm::abs(dir.y) < 0.99f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0);
- glm::vec3 right = glm::normalize(glm::cross(dir, up));
- up = glm::cross(right, dir);
-
- for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = (f32(i) / segments) * glm::two_pi<f32>();
- f32 angle2 = (f32(i + 1) / segments) * glm::two_pi<f32>();
-
- glm::vec3 p1 = base + (right * glm::cos(angle1) + up * glm::sin(angle1)) * radius;
- glm::vec3 p2 = base + (right * glm::cos(angle2) + up * glm::sin(angle2)) * radius;
-
- addVertex(tip, color);
- addVertex(p1, color);
- addVertex(p2, color);
-
- addVertex(base, color);
- addVertex(p2, color);
- addVertex(p1, color);
- }
- };
-
- auto addCylinder = [&](const glm::vec3& start, const glm::vec3& end, f32 radius,
- const glm::vec4& color, i32 segments = 10) {
- glm::vec3 dir = glm::normalize(end - start);
- glm::vec3 up = glm::abs(dir.y) < 0.99f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0);
- glm::vec3 right = glm::normalize(glm::cross(dir, up));
- up = glm::cross(right, dir);
-
- for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = (f32(i) / segments) * glm::two_pi<f32>();
- f32 angle2 = (f32(i + 1) / segments) * glm::two_pi<f32>();
-
- glm::vec3 offset1 = (right * glm::cos(angle1) + up * glm::sin(angle1)) * radius;
- glm::vec3 offset2 = (right * glm::cos(angle2) + up * glm::sin(angle2)) * radius;
-
- glm::vec3 s1 = start + offset1, s2 = start + offset2;
- glm::vec3 e1 = end + offset1, e2 = end + offset2;
-
- addVertex(s1, color);
- addVertex(e1, color);
- addVertex(e2, color);
-
- addVertex(s1, color);
- addVertex(e2, color);
- addVertex(s2, color);
- }
- };
-
- auto addSphere = [&](const glm::vec3& center, f32 radius, const glm::vec4& color,
- i32 rings = 8, i32 sectors = 12) {
- for (i32 r = 0; r < rings; ++r) {
- f32 theta1 = (f32(r) / rings) * glm::pi<f32>();
- f32 theta2 = (f32(r + 1) / rings) * glm::pi<f32>();
-
- for (i32 s = 0; s < sectors; ++s) {
- f32 phi1 = (f32(s) / sectors) * glm::two_pi<f32>();
- f32 phi2 = (f32(s + 1) / sectors) * glm::two_pi<f32>();
-
- glm::vec3 n1(glm::sin(theta1) * glm::cos(phi1), glm::cos(theta1), glm::sin(theta1) * glm::sin(phi1));
- glm::vec3 n2(glm::sin(theta1) * glm::cos(phi2), glm::cos(theta1), glm::sin(theta1) * glm::sin(phi2));
- glm::vec3 n3(glm::sin(theta2) * glm::cos(phi2), glm::cos(theta2), glm::sin(theta2) * glm::sin(phi2));
- glm::vec3 n4(glm::sin(theta2) * glm::cos(phi1), glm::cos(theta2), glm::sin(theta2) * glm::sin(phi1));
-
- addVertex(center + n1 * radius, color);
- addVertex(center + n3 * radius, color);
- addVertex(center + n2 * radius, color);
-
- addVertex(center + n1 * radius, color);
- addVertex(center + n4 * radius, color);
- addVertex(center + n3 * radius, color);
- }
- }
- };
-
- glm::vec4 red(0.9f, 0.2f, 0.2f, 0.9f);
- glm::vec4 green(0.3f, 0.85f, 0.3f, 0.9f);
- glm::vec4 blue(0.3f, 0.5f, 0.95f, 0.9f);
- glm::vec4 dimRed(0.5f, 0.2f, 0.2f, 0.5f);
- glm::vec4 dimGreen(0.2f, 0.45f, 0.2f, 0.5f);
- glm::vec4 dimBlue(0.2f, 0.3f, 0.55f, 0.5f);
- glm::vec4 gray(0.45f, 0.45f, 0.5f, 0.85f);
-
- f32 shaftLen = 0.6f;
- f32 shaftRadius = 0.04f;
- f32 coneLen = 0.35f;
- f32 coneRadius = 0.12f;
-
- addCylinder(glm::vec3(0), glm::vec3(shaftLen, 0, 0), shaftRadius, red);
- addCone(glm::vec3(shaftLen, 0, 0), glm::vec3(shaftLen + coneLen, 0, 0), coneRadius, red);
-
- addCylinder(glm::vec3(0), glm::vec3(0, shaftLen, 0), shaftRadius, green);
- addCone(glm::vec3(0, shaftLen, 0), glm::vec3(0, shaftLen + coneLen, 0), coneRadius, green);
-
- addCylinder(glm::vec3(0), glm::vec3(0, 0, shaftLen), shaftRadius, blue);
- addCone(glm::vec3(0, 0, shaftLen), glm::vec3(0, 0, shaftLen + coneLen), coneRadius, blue);
-
- f32 backDist = 0.35f;
- f32 backRadius = 0.08f;
- addSphere(glm::vec3(-backDist, 0, 0), backRadius, dimRed);
- addSphere(glm::vec3(0, -backDist, 0), backRadius, dimGreen);
- addSphere(glm::vec3(0, 0, -backDist), backRadius, dimBlue);
-
- addSphere(glm::vec3(0), 0.1f, gray);
-
- axisVertexCount_ = static_cast<u32>(vertices.size() / 7);
-
- axisVAO_ = VertexArray::create();
-
- auto vbo = VertexBuffer::createRaw(vertices.data(), static_cast<u32>(vertices.size() * sizeof(f32)));
- vbo->setLayout({
- { ShaderDataType::Float3, "a_position" },
- { ShaderDataType::Float4, "a_color" }
- });
-
- axisVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
-
- axisShaderHandle_ = resourceManager_.loadEngineShader("axis");
-
- axisInitialized_ = true;
-}
-
-void SceneViewPanel::renderAxisGizmo() {
- if (!axisInitialized_) {
- initAxisGizmoData();
- }
-
- Shader* axisShader = resourceManager_.getShader(axisShaderHandle_);
- if (!axisVAO_ || !axisShader) return;
-
- const ui::Rect& bounds = getBounds();
- f32 gizmoSize = 60.0f;
- f32 padding = 12.0f;
-
- axisGizmoCenter_ = glm::vec2(
- bounds.x + bounds.width - gizmoSize - padding,
- bounds.y + gizmoSize + padding
- );
-
- GLint savedViewport[4];
- glGetIntegerv(GL_VIEWPORT, savedViewport);
-
- f32 vpX = axisGizmoCenter_.x - gizmoSize;
- f32 vpY = savedViewport[3] - axisGizmoCenter_.y - gizmoSize;
- glViewport(static_cast<GLint>(vpX), static_cast<GLint>(vpY),
- static_cast<GLsizei>(gizmoSize * 2), static_cast<GLsizei>(gizmoSize * 2));
-
- glEnable(GL_DEPTH_TEST);
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glClear(GL_DEPTH_BUFFER_BIT);
-
- glm::mat4 rotation = glm::mat4_cast(glm::conjugate(glm::quat(glm::vec3(-camera_.getPitch(), -camera_.getYaw(), 0.0f))));
- glm::mat4 proj = glm::ortho(-1.5f, 1.5f, -1.5f, 1.5f, -10.0f, 10.0f);
- glm::mat4 viewProj = proj * rotation;
-
- axisShader->bind();
- axisShader->setUniform("u_viewProj", viewProj);
-
- axisVAO_->bind();
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(axisVertexCount_));
- axisVAO_->unbind();
- axisShader->unbind();
-
- glViewport(savedViewport[0], savedViewport[1], savedViewport[2], savedViewport[3]);
- glDisable(GL_DEPTH_TEST);
-}
-
-i32 SceneViewPanel::hitTestAxisGizmo(f32 x, f32 y) {
- f32 localX = x - axisGizmoCenter_.x;
- f32 localY = y - axisGizmoCenter_.y;
-
- f32 dist = glm::sqrt(localX * localX + localY * localY);
- if (dist > axisGizmoRadius_ * 2.0f) return -1;
-
- glm::quat camOrientation = glm::quat(glm::vec3(-camera_.getPitch(), -camera_.getYaw(), 0.0f));
- glm::mat4 rotation = glm::mat4_cast(glm::conjugate(camOrientation));
-
- f32 posAxisDist = 0.95f;
- f32 negAxisDist = 0.35f;
- f32 scale = axisGizmoRadius_ / 1.5f;
-
- glm::vec3 xPos = glm::vec3(rotation * glm::vec4(posAxisDist, 0, 0, 0));
- glm::vec3 yPos = glm::vec3(rotation * glm::vec4(0, posAxisDist, 0, 0));
- glm::vec3 zPos = glm::vec3(rotation * glm::vec4(0, 0, posAxisDist, 0));
- glm::vec3 xNeg = glm::vec3(rotation * glm::vec4(-negAxisDist, 0, 0, 0));
- glm::vec3 yNeg = glm::vec3(rotation * glm::vec4(0, -negAxisDist, 0, 0));
- glm::vec3 zNeg = glm::vec3(rotation * glm::vec4(0, 0, -negAxisDist, 0));
-
- glm::vec2 screenXPos = glm::vec2(xPos.x, -xPos.y) * scale;
- glm::vec2 screenYPos = glm::vec2(yPos.x, -yPos.y) * scale;
- glm::vec2 screenZPos = glm::vec2(zPos.x, -zPos.y) * scale;
- glm::vec2 screenXNeg = glm::vec2(xNeg.x, -xNeg.y) * scale;
- glm::vec2 screenYNeg = glm::vec2(yNeg.x, -yNeg.y) * scale;
- glm::vec2 screenZNeg = glm::vec2(zNeg.x, -zNeg.y) * scale;
-
- glm::vec2 clickPos(localX, localY);
- f32 threshold = 18.0f;
- f32 smallThreshold = 12.0f;
-
- if (glm::length(clickPos - screenXPos) < threshold) return 0;
- if (glm::length(clickPos - screenYPos) < threshold) return 1;
- if (glm::length(clickPos - screenZPos) < threshold) return 2;
-
- if (glm::length(clickPos - screenXNeg) < smallThreshold) return 3;
- if (glm::length(clickPos - screenYNeg) < smallThreshold) return 4;
- if (glm::length(clickPos - screenZNeg) < smallThreshold) return 5;
-
- return -1;
-}
-
-void SceneViewPanel::setViewToTop() {
- camera_.animateTo(glm::half_pi<f32>() - 0.01f, 0.0f);
-}
-
-void SceneViewPanel::setViewToBottom() {
- camera_.animateTo(-glm::half_pi<f32>() + 0.01f, 0.0f);
-}
-
-void SceneViewPanel::setViewToFront() {
- camera_.animateTo(0.0f, 0.0f);
-}
-
-void SceneViewPanel::setViewToBack() {
- camera_.animateTo(0.0f, glm::pi<f32>());
-}
-
-void SceneViewPanel::setViewToRight() {
- camera_.animateTo(0.0f, -glm::half_pi<f32>());
-}
-
-void SceneViewPanel::setViewToLeft() {
- camera_.animateTo(0.0f, glm::half_pi<f32>());
-}
-
-void SceneViewPanel::setViewMode(ViewMode mode) {
- if (viewMode_ == mode) return;
-
- viewMode_ = mode;
-
- if (transformGizmo_) {
- transformGizmo_->set2DMode(mode == ViewMode::Mode2D);
- }
-
- if (mode == ViewMode::Mode2D) {
- camera_.animateTo(0.0f, 0.0f);
- camera_.setOrbitEnabled(false);
- } else {
- camera_.animateTo(0.5f, 0.5f);
- camera_.setOrbitEnabled(true);
- }
-}
-
-void SceneViewPanel::initAxisGizmo2DData() {
- std::vector<f32> vertices;
-
- auto addVertex = [&vertices](const glm::vec3& pos, const glm::vec4& color) {
- vertices.insert(vertices.end(), {pos.x, pos.y, pos.z, color.r, color.g, color.b, color.a});
- };
-
- auto addArrow2D = [&](const glm::vec3& start, const glm::vec3& end, f32 thickness, f32 headSize,
- const glm::vec4& color) {
- glm::vec3 dir = glm::normalize(end - start);
- glm::vec3 perp(-dir.y, dir.x, 0.0f);
-
- glm::vec3 shaftEnd = end - dir * headSize;
-
- glm::vec3 s1 = start + perp * thickness;
- glm::vec3 s2 = start - perp * thickness;
- glm::vec3 e1 = shaftEnd + perp * thickness;
- glm::vec3 e2 = shaftEnd - perp * thickness;
-
- addVertex(s1, color);
- addVertex(e1, color);
- addVertex(e2, color);
- addVertex(s1, color);
- addVertex(e2, color);
- addVertex(s2, color);
-
- glm::vec3 h1 = shaftEnd + perp * headSize * 0.5f;
- glm::vec3 h2 = shaftEnd - perp * headSize * 0.5f;
-
- addVertex(end, color);
- addVertex(h1, color);
- addVertex(h2, color);
- };
-
- glm::vec4 red(0.9f, 0.2f, 0.2f, 0.9f);
- glm::vec4 green(0.3f, 0.85f, 0.3f, 0.9f);
-
- f32 length = 0.8f;
- f32 thickness = 0.04f;
- f32 headSize = 0.2f;
-
- addArrow2D(glm::vec3(0), glm::vec3(length, 0, 0), thickness, headSize, red);
- addArrow2D(glm::vec3(0), glm::vec3(0, length, 0), thickness, headSize, green);
-
- axis2DVertexCount_ = static_cast<u32>(vertices.size() / 7);
-
- axis2DVAO_ = VertexArray::create();
-
- auto vbo = VertexBuffer::createRaw(vertices.data(), static_cast<u32>(vertices.size() * sizeof(f32)));
- vbo->setLayout({
- { ShaderDataType::Float3, "a_position" },
- { ShaderDataType::Float4, "a_color" }
- });
-
- axis2DVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
-
- axis2DInitialized_ = true;
-}
-
-void SceneViewPanel::renderAxisGizmo2D() {
- if (!axis2DInitialized_) {
- initAxisGizmo2DData();
- }
-
- Shader* axisShader = resourceManager_.getShader(axisShaderHandle_);
- if (!axis2DVAO_ || !axisShader) return;
-
- const ui::Rect& bounds = getBounds();
- f32 gizmoSize = 50.0f;
- f32 padding = 12.0f;
-
- axisGizmoCenter_ = glm::vec2(
- bounds.x + bounds.width - gizmoSize - padding,
- bounds.y + gizmoSize + padding
- );
-
- GLint savedViewport[4];
- glGetIntegerv(GL_VIEWPORT, savedViewport);
-
- f32 vpX = axisGizmoCenter_.x - gizmoSize;
- f32 vpY = savedViewport[3] - axisGizmoCenter_.y - gizmoSize;
- glViewport(static_cast<GLint>(vpX), static_cast<GLint>(vpY),
- static_cast<GLsizei>(gizmoSize * 2), static_cast<GLsizei>(gizmoSize * 2));
-
- glDisable(GL_DEPTH_TEST);
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-
- glm::mat4 proj = glm::ortho(-1.2f, 1.2f, -1.2f, 1.2f, -1.0f, 1.0f);
-
- axisShader->bind();
- axisShader->setUniform("u_viewProj", proj);
-
- axis2DVAO_->bind();
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(axis2DVertexCount_));
- axis2DVAO_->unbind();
- axisShader->unbind();
-
- glViewport(savedViewport[0], savedViewport[1], savedViewport[2], savedViewport[3]);
-}
-
-i32 SceneViewPanel::hitTestAxisGizmo2D(f32 x, f32 y) {
- (void)x;
- (void)y;
- return -1;
-}
-
-Entity SceneViewPanel::findCanvas() {
- auto view = registry_.view<ecs::Canvas>();
- for (auto entity : view) {
- return entity;
- }
- return INVALID_ENTITY;
-}
-
-void SceneViewPanel::initCanvasGizmoData() {
- std::vector<f32> vertices;
-
- // Simple rectangle (4 corners, 8 vertices for lines)
- // We'll draw as GL_LINES so we need pairs
- // Bottom: (-1,-1) to (1,-1)
- // Right: (1,-1) to (1,1)
- // Top: (1,1) to (-1,1)
- // Left: (-1,1) to (-1,-1)
- f32 rect[] = {
- -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f,
- 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
- 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f,
- -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f
- };
-
- for (f32 v : rect) {
- vertices.push_back(v);
- }
-
- canvasGizmoVAO_ = VertexArray::create();
-
- auto vbo = VertexBuffer::createRaw(vertices.data(), static_cast<u32>(vertices.size() * sizeof(f32)));
- vbo->setLayout({
- { ShaderDataType::Float3, "a_position" }
- });
-
- canvasGizmoVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
-
- canvasGizmoInitialized_ = true;
-}
-
-void SceneViewPanel::renderCanvasGizmo(const glm::mat4& viewProj) {
- Entity canvasEntity = findCanvas();
- if (canvasEntity == INVALID_ENTITY) return;
-
- auto* canvas = registry_.tryGet<ecs::Canvas>(canvasEntity);
- if (!canvas) return;
-
- if (!canvasGizmoInitialized_) {
- initCanvasGizmoData();
- }
-
- Shader* gridShader = resourceManager_.getShader(gridShaderHandle_);
- if (!canvasGizmoVAO_ || !gridShader) return;
-
- glm::vec2 worldSize = canvas->getWorldSize();
- f32 halfWidth = worldSize.x * 0.5f;
- f32 halfHeight = worldSize.y * 0.5f;
-
- glm::mat4 model = glm::scale(glm::mat4(1.0f), glm::vec3(halfWidth, halfHeight, 1.0f));
- glm::mat4 mvp = viewProj * model;
-
- gridShader->bind();
- gridShader->setUniform("u_viewProj", mvp);
- gridShader->setUniform("u_color", glm::vec4(0.4f, 0.8f, 1.0f, 0.8f));
-
- canvasGizmoVAO_->bind();
- glDrawArrays(GL_LINES, 0, 8);
-}
-
-void SceneViewPanel::renderStats(ui::UIBatchRenderer& renderer) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* font = ctx->getDefaultMSDFFont();
-#else
- ui::SystemFont* font = ctx->getDefaultSystemFont();
-#endif
- if (!font) return;
-
- RenderPipeline::Stats stats{};
- if (renderPipeline_) {
- stats = renderPipeline_->getStats();
- }
-
- f64 frameDelta = last_frame_time_ - prev_frame_time_;
- f32 fps = (frameDelta > 0.001) ? 1.0f / static_cast<f32>(frameDelta) : 0.0f;
- f32 frameMs = static_cast<f32>(frameDelta * 1000.0);
-
- constexpr f32 padding = 10.0f;
- constexpr f32 lineHeight = 16.0f;
- constexpr f32 fontSize = 11.0f;
- constexpr f32 panelWidth = 160.0f;
- constexpr f32 panelHeight = 180.0f;
- constexpr f32 sectionGap = 6.0f;
-
- ui::Rect panelBounds = {
- viewportBounds_.x + padding,
- viewportBounds_.y + viewportBounds_.height - panelHeight - padding,
- panelWidth,
- panelHeight
- };
-
- constexpr glm::vec4 bgColor{0.08f, 0.08f, 0.10f, 0.92f};
- constexpr glm::vec4 headerColor{0.4f, 0.7f, 1.0f, 1.0f};
- constexpr glm::vec4 valueColor{0.9f, 0.9f, 0.9f, 1.0f};
- constexpr glm::vec4 labelColor{0.6f, 0.6f, 0.6f, 1.0f};
-
- renderer.drawRoundedRect(panelBounds, bgColor, ui::CornerRadii::all(6.0f));
-
- f32 y = panelBounds.y + padding;
- f32 x = panelBounds.x + padding;
- char buffer[64];
-
- renderer.drawText("Rendering", glm::vec2(x, y), *font, fontSize, headerColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "FPS: %.1f (%.2fms)", fps, frameMs);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, valueColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "Draw Calls: %u", stats.draw_calls);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, valueColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "Tris: %u Verts: %u", stats.triangles, stats.vertices);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, valueColor);
- y += lineHeight + sectionGap;
-
- renderer.drawText("Batching", glm::vec2(x, y), *font, fontSize, headerColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "Batches: %u", stats.batch_count);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, valueColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "Tex Switches: %u", stats.texture_switches);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, labelColor);
- y += lineHeight + sectionGap;
-
- renderer.drawText("Scene", glm::vec2(x, y), *font, fontSize, headerColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "Sprites: %u", stats.total_items);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, valueColor);
- y += lineHeight;
-
- snprintf(buffer, sizeof(buffer), "Visible: %u Culled: %u", stats.visible_items, stats.culled_items);
- renderer.drawText(buffer, glm::vec2(x, y), *font, fontSize, labelColor);
-}
-
-// =============================================================================
-// Ray Picking
-// =============================================================================
-
-void SceneViewPanel::screenToWorldRay(f32 screenX, f32 screenY,
- glm::vec3& rayOrigin, glm::vec3& rayDir) {
- f32 localX = screenX - viewportBounds_.x;
- f32 localY = screenY - viewportBounds_.y;
-
- f32 ndcX = (localX / viewportBounds_.width) * 2.0f - 1.0f;
- f32 ndcY = 1.0f - (localY / viewportBounds_.height) * 2.0f;
-
- glm::mat4 view = camera_.getViewMatrix();
- glm::mat4 proj = camera_.getProjectionMatrix();
- glm::mat4 invViewProj = glm::inverse(proj * view);
-
- glm::vec4 nearPoint = invViewProj * glm::vec4(ndcX, ndcY, -1.0f, 1.0f);
- glm::vec4 farPoint = invViewProj * glm::vec4(ndcX, ndcY, 1.0f, 1.0f);
-
- nearPoint /= nearPoint.w;
- farPoint /= farPoint.w;
-
- rayOrigin = glm::vec3(nearPoint);
- rayDir = glm::normalize(glm::vec3(farPoint - nearPoint));
-}
-
-bool SceneViewPanel::rayIntersectsAABB(const glm::vec3& rayOrigin, const glm::vec3& rayDir,
- const glm::vec3& boxMin, const glm::vec3& boxMax, f32& t) {
- glm::vec3 invDir = 1.0f / rayDir;
-
- glm::vec3 t1 = (boxMin - rayOrigin) * invDir;
- glm::vec3 t2 = (boxMax - rayOrigin) * invDir;
-
- glm::vec3 tMin = glm::min(t1, t2);
- glm::vec3 tMax = glm::max(t1, t2);
-
- f32 tNear = glm::max(glm::max(tMin.x, tMin.y), tMin.z);
- f32 tFar = glm::min(glm::min(tMax.x, tMax.y), tMax.z);
-
- if (tNear > tFar || tFar < 0.0f) {
- return false;
- }
-
- t = tNear >= 0.0f ? tNear : tFar;
- return true;
-}
-
-Entity SceneViewPanel::pickEntity(const glm::vec3& rayOrigin, const glm::vec3& rayDir) {
- f32 closestDist = std::numeric_limits<f32>::max();
- Entity closestEntity = INVALID_ENTITY;
-
- auto spriteView = registry_.view<ecs::LocalTransform, ecs::Sprite>();
- for (auto entity : spriteView) {
- const auto& transform = spriteView.get<ecs::LocalTransform>(entity);
- const auto& sprite = spriteView.get<ecs::Sprite>(entity);
-
- glm::vec3 halfSize(sprite.size.x * 0.5f, sprite.size.y * 0.5f, 0.1f);
- glm::vec3 boxMin = transform.position - halfSize;
- glm::vec3 boxMax = transform.position + halfSize;
-
- f32 t;
- if (rayIntersectsAABB(rayOrigin, rayDir, boxMin, boxMax, t)) {
- if (t < closestDist) {
- closestDist = t;
- closestEntity = entity;
- }
- }
- }
-
- return closestEntity;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/panels/SceneViewPanel.hpp b/src/esengine/editor/panels/SceneViewPanel.hpp
deleted file mode 100644
index 786b473c4..000000000
--- a/src/esengine/editor/panels/SceneViewPanel.hpp
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * @file SceneViewPanel.hpp
- * @brief Scene viewport panel for 3D scene editing
- * @details Renders the 3D scene to a texture using a framebuffer and displays
- * it in a dockable panel with camera controls.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../ui/docking/DockPanel.hpp"
-#include "../../renderer/Framebuffer.hpp"
-#include "../../renderer/Buffer.hpp"
-#include "../../renderer/Shader.hpp"
-#include "../camera/EditorCamera.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../resource/ResourceManager.hpp"
-#include "../core/Selection.hpp"
-#include "../widgets/EditorToolbar.hpp"
-#include "../widgets/SceneToolbar.hpp"
-#include "../gizmo/TransformGizmo.hpp"
-#include "../command/CommandHistory.hpp"
-#include "../../events/Connection.hpp"
-#include "../../renderer/RenderPipeline.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// SceneViewPanel Class
-// =============================================================================
-
-/**
- * @brief 3D scene viewport for editing
- *
- * @details Renders the game scene to an off-screen framebuffer and displays
- * the result in the panel. Provides camera controls for navigating
- * the scene and selecting entities.
- *
- * @code
- * SceneViewPanel sceneView(registry, selection);
- * sceneView.setViewportSize(800, 600);
- * // Renders automatically in the docking system
- * @endcode
- */
-class SceneViewPanel : public ui::DockPanel {
-public:
- /**
- * @brief Constructs scene view panel
- * @param registry Entity registry
- * @param selection Entity selection manager
- * @param resourceManager Resource manager for texture lookup
- */
- SceneViewPanel(ecs::Registry& registry, EntitySelection& selection,
- resource::ResourceManager& resourceManager);
-
- ~SceneViewPanel() override = default;
-
- /**
- * @brief Sets the viewport size
- * @param width Width in pixels
- * @param height Height in pixels
- */
- void setViewportSize(u32 width, u32 height);
-
- /**
- * @brief Gets the editor camera
- * @return Reference to the camera
- */
- EditorCamera& getCamera() { return camera_; }
-
- /**
- * @brief Gets the editor camera (const)
- * @return Const reference to the camera
- */
- const EditorCamera& getCamera() const { return camera_; }
-
- /** @brief Sets the view mode (2D or 3D) */
- void setViewMode(ViewMode mode);
-
- /** @brief Gets the current view mode */
- ViewMode getViewMode() const { return viewMode_; }
-
- /** @brief Sets the command history for undo/redo support */
- void setCommandHistory(CommandHistory* history) { commandHistory_ = history; }
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseUp(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
- bool onScroll(const ui::ScrollEvent& event) override;
-
- void setViewToTop();
- void setViewToFront();
- void setViewToRight();
- void setViewToBack();
- void setViewToLeft();
- void setViewToBottom();
-
-private:
- void renderSceneToTexture();
- void renderSceneContent();
- void renderGrid(const glm::mat4& viewProj);
- void renderGrid2D(const glm::mat4& viewProj);
- void renderSprites(const glm::mat4& viewProj);
- void renderCanvasGizmo(const glm::mat4& viewProj);
- void renderSelectionBox(const glm::mat4& viewProj);
- void renderStats(ui::UIBatchRenderer& renderer);
- void initGrid2DData();
- void initCanvasGizmoData();
- void renderAxisGizmo();
- void renderAxisGizmo2D();
- void updateFramebufferSize();
- void initGridData();
- void initAxisGizmoData();
- void initAxisGizmo2DData();
- i32 hitTestAxisGizmo(f32 x, f32 y);
- i32 hitTestAxisGizmo2D(f32 x, f32 y);
- Entity findCanvas();
-
- void screenToWorldRay(f32 screenX, f32 screenY, glm::vec3& rayOrigin, glm::vec3& rayDir);
- Entity pickEntity(const glm::vec3& rayOrigin, const glm::vec3& rayDir);
- bool rayIntersectsAABB(const glm::vec3& rayOrigin, const glm::vec3& rayDir,
- const glm::vec3& boxMin, const glm::vec3& boxMax, f32& t);
-
- ecs::Registry& registry_;
- EntitySelection& selection_;
- resource::ResourceManager& resourceManager_;
-
- Unique<Framebuffer> framebuffer_;
- EditorCamera camera_;
-
- Unique<VertexArray> gridVAO_;
- Unique<VertexArray> grid2DVAO_;
- resource::ShaderHandle gridShaderHandle_;
- u32 gridVertexCount_ = 0;
- u32 grid2DVertexCount_ = 0;
- bool gridInitialized_ = false;
- bool grid2DInitialized_ = false;
-
- Unique<VertexArray> axisVAO_;
- resource::ShaderHandle axisShaderHandle_;
- u32 axisVertexCount_ = 0;
- bool axisInitialized_ = false;
- glm::vec2 axisGizmoCenter_{0.0f};
- f32 axisGizmoRadius_ = 50.0f;
- i32 hoveredAxis_ = -1;
-
- u32 viewportWidth_ = 1280;
- u32 viewportHeight_ = 720;
- bool framebufferNeedsResize_ = false;
-
- f64 last_frame_time_ = 0.0;
- f64 prev_frame_time_ = 0.0;
-
- ViewMode viewMode_ = ViewMode::Mode3D;
- Unique<VertexArray> axis2DVAO_;
- u32 axis2DVertexCount_ = 0;
- bool axis2DInitialized_ = false;
-
- Unique<VertexArray> canvasGizmoVAO_;
- bool canvasGizmoInitialized_ = false;
-
- Unique<SceneToolbar> toolbar_;
- Unique<TransformGizmo> transformGizmo_;
- Unique<RenderPipeline> renderPipeline_;
- bool gridVisible_ = true;
- bool gizmosVisible_ = true;
- bool stats_visible_ = false;
- ui::Rect viewportBounds_;
-
- CommandHistory* commandHistory_ = nullptr;
- ecs::LocalTransform dragStartTransform_;
- Entity draggingEntity_ = INVALID_ENTITY;
-
- ConnectionHolder connections_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/preview/WebExporter.cpp b/src/esengine/editor/preview/WebExporter.cpp
deleted file mode 100644
index b4bfafbc5..000000000
--- a/src/esengine/editor/preview/WebExporter.cpp
+++ /dev/null
@@ -1,312 +0,0 @@
-/**
- * @file WebExporter.cpp
- * @brief Web build exporter implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "WebExporter.hpp"
-#include "../../core/Log.hpp"
-#include "../../platform/FileSystem.hpp"
-#include "../../platform/PathResolver.hpp"
-
-#include <cstdlib>
-#include <filesystem>
-#include <fstream>
-
-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,
- const std::string& outputPath,
- ProgressCallback callback
-) {
- ES_LOG_INFO("Exporting project to web: {}", outputPath);
-
- if (callback) callback("Creating output directory...", 0.0f);
-
- try {
- fs::create_directories(outputPath);
- } catch (const std::exception& e) {
- ES_LOG_ERROR("Failed to create output directory: {}", e.what());
- return false;
- }
-
- if (callback) callback("Checking dependencies...", 0.05f);
- if (!ensureDependencies(projectPath, callback)) {
- return false;
- }
-
- if (callback) callback("Compiling TypeScript...", 0.15f);
- if (!compileTypeScript(projectPath, callback)) {
- return false;
- }
-
- if (callback) callback("Copying SDK files...", 0.35f);
- if (!copySDKFiles(sdkPath, outputPath, callback)) {
- return false;
- }
-
- if (callback) callback("Copying assets...", 0.5f);
- if (!copyAssets(projectPath, outputPath, callback)) {
- return false;
- }
-
- if (callback) callback("Copying user scripts...", 0.7f);
- if (!copyUserScripts(projectPath, outputPath, callback)) {
- return false;
- }
-
- if (callback) callback("Generating index.html...", 0.9f);
- std::string projectName = fs::path(projectPath).filename().string();
- if (!generateIndexHtml(outputPath, projectName)) {
- return false;
- }
-
- if (callback) callback("Export complete!", 1.0f);
- ES_LOG_INFO("Web export completed successfully");
- return true;
-}
-
-bool WebExporter::ensureDependencies(const std::string& projectPath, ProgressCallback& callback) {
- fs::path nodeModules = fs::path(projectPath) / "node_modules";
- fs::path packageJson = fs::path(projectPath) / "package.json";
- fs::path packageLock = fs::path(projectPath) / "package-lock.json";
-
- // Check if package.json exists
- if (!fs::exists(packageJson)) {
- ES_LOG_ERROR("No package.json found in project. Please create project files first.");
- return false;
- }
-
- bool needsInstall = false;
-
- // Check if node_modules/esengine exists
- fs::path esengineModule = nodeModules / "esengine";
- if (!fs::exists(esengineModule)) {
- needsInstall = true;
- } else {
- // Check if package.json is newer than package-lock.json (SDK path may have changed)
- if (fs::exists(packageLock)) {
- auto pkgTime = fs::last_write_time(packageJson);
- auto lockTime = fs::last_write_time(packageLock);
- if (pkgTime > lockTime) {
- ES_LOG_INFO("package.json updated, reinstalling dependencies...");
- needsInstall = true;
- }
- }
- }
-
- if (!needsInstall) {
- ES_LOG_DEBUG("Dependencies already installed");
- return true;
- }
-
- // Install dependencies
- ES_LOG_INFO("Installing dependencies (npm install)...");
- if (callback) callback("Installing npm dependencies...", 0.08f);
-
-#ifdef _WIN32
- std::string cmd = "cd /d \"" + projectPath + "\" && npm install";
-#else
- std::string cmd = "cd \"" + projectPath + "\" && npm install";
-#endif
-
- int result = std::system(cmd.c_str());
-
- if (result != 0) {
- ES_LOG_ERROR("npm install failed (exit code: {}). Please run 'npm install' manually in the project directory.", result);
- return false;
- }
-
- ES_LOG_INFO("Dependencies installed successfully");
- return true;
-}
-
-bool WebExporter::compileTypeScript(const std::string& projectPath, ProgressCallback& callback) {
- fs::path srcDir = fs::path(projectPath) / "src";
- fs::path buildDir = fs::path(projectPath) / "build" / "js";
- fs::path mainTs = srcDir / "main.ts";
- fs::path mainJs = buildDir / "main.js";
-
- // Check if source exists
- if (!fs::exists(mainTs)) {
- ES_LOG_ERROR("No src/main.ts found in project");
- return false;
- }
-
- // Create build directory if needed
- if (!fs::exists(buildDir)) {
- fs::create_directories(buildDir);
- }
-
- // 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...");
-
-#ifdef _WIN32
- std::string cmd = "cd /d \"" + projectPath + "\" && npm run build";
-#else
- std::string cmd = "cd \"" + projectPath + "\" && npm run build";
-#endif
-
- int result = std::system(cmd.c_str());
-
- if (result != 0) {
- ES_LOG_ERROR("Build failed (exit code: {})", result);
- return false;
- }
-
- if (!fs::exists(mainJs)) {
- ES_LOG_ERROR("Build did not produce build/js/main.js");
- return false;
- }
-
- ES_LOG_INFO("Build completed successfully");
- return true;
-}
-
-bool WebExporter::copyUserScripts(const std::string& projectPath, const std::string& outputPath, ProgressCallback& callback) {
- fs::path srcScripts = fs::path(projectPath) / "build" / "js";
- fs::path dstScripts = fs::path(outputPath) / "scripts";
-
- if (!fs::exists(srcScripts)) {
- ES_LOG_ERROR("Compiled scripts not found at {}", srcScripts.string());
- return false;
- }
-
- try {
- if (fs::exists(dstScripts)) {
- fs::remove_all(dstScripts);
- }
- fs::copy(srcScripts, dstScripts, fs::copy_options::recursive | fs::copy_options::overwrite_existing);
- ES_LOG_DEBUG("Copied user scripts to {}", dstScripts.string());
- } catch (const std::exception& e) {
- ES_LOG_ERROR("Failed to copy user scripts: {}", e.what());
- return false;
- }
-
- return true;
-}
-
-bool WebExporter::copySDKFiles(const std::string& sdkPath, const std::string& outputPath, ProgressCallback& callback) {
- const char* sdkFiles[] = {
- "esengine.js",
- "esengine.wasm",
- "esengine.d.ts"
- };
-
- for (const char* file : sdkFiles) {
- fs::path src = fs::path(sdkPath) / file;
- fs::path dst = fs::path(outputPath) / file;
-
- if (!fs::exists(src)) {
- if (std::string(file) == "esengine.d.ts") {
- continue;
- }
- ES_LOG_ERROR("SDK file not found: {}", src.string());
- return false;
- }
-
- try {
- fs::copy_file(src, dst, fs::copy_options::overwrite_existing);
- ES_LOG_DEBUG("Copied: {}", file);
- } catch (const std::exception& e) {
- ES_LOG_ERROR("Failed to copy {}: {}", file, e.what());
- return false;
- }
- }
-
- return true;
-}
-
-bool WebExporter::copyAssets(const std::string& projectPath, const std::string& outputPath, ProgressCallback& callback) {
- fs::path srcAssets = fs::path(projectPath) / "assets";
- fs::path dstAssets = fs::path(outputPath) / "assets";
-
- if (!fs::exists(srcAssets)) {
- ES_LOG_WARN("No assets directory found in project");
- return true;
- }
-
- try {
- if (fs::exists(dstAssets)) {
- fs::remove_all(dstAssets);
- }
- fs::copy(srcAssets, dstAssets, fs::copy_options::recursive | fs::copy_options::overwrite_existing);
- ES_LOG_DEBUG("Copied assets directory");
- } catch (const std::exception& e) {
- ES_LOG_ERROR("Failed to copy assets: {}", e.what());
- return false;
- }
-
- return true;
-}
-
-bool WebExporter::generateIndexHtml(const std::string& outputPath, const std::string& projectName) {
- 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;
- }
-
- 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;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/preview/WebExporter.hpp b/src/esengine/editor/preview/WebExporter.hpp
deleted file mode 100644
index c341f9f9a..000000000
--- a/src/esengine/editor/preview/WebExporter.hpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * @file WebExporter.hpp
- * @brief Web build exporter for game projects
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../../core/Types.hpp"
-#include <string>
-#include <functional>
-#include <future>
-#include <atomic>
-
-namespace esengine::editor {
-
-/**
- * @brief Exports game project to web-ready format
- */
-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 (blocking)
- */
- static bool exportProject(
- const std::string& projectPath,
- const std::string& sdkPath,
- const std::string& outputPath,
- 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);
- static bool copyAssets(const std::string& projectPath, const std::string& outputPath, ProgressCallback& callback);
- static bool copyUserScripts(const std::string& projectPath, const std::string& outputPath, ProgressCallback& callback);
- static bool generateIndexHtml(const std::string& outputPath, const std::string& projectName);
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/preview/WebPreviewServer.cpp b/src/esengine/editor/preview/WebPreviewServer.cpp
deleted file mode 100644
index 588cf3304..000000000
--- a/src/esengine/editor/preview/WebPreviewServer.cpp
+++ /dev/null
@@ -1,213 +0,0 @@
-/**
- * @file WebPreviewServer.cpp
- * @brief Local HTTP server for web preview implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "WebPreviewServer.hpp"
-#include "../../core/Log.hpp"
-
-#include <sstream>
-#include <filesystem>
-
-#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 {
-namespace editor {
-
-// =============================================================================
-// Destructor
-// =============================================================================
-
-WebPreviewServer::~WebPreviewServer() {
- stop();
-}
-
-// =============================================================================
-// Public Methods
-// =============================================================================
-
-bool WebPreviewServer::start(const std::string& directory, u16 port) {
- if (running_) {
- ES_LOG_WARN("WebPreviewServer already running on port {}", port_);
- return false;
- }
-
- if (!std::filesystem::exists(directory)) {
- ES_LOG_ERROR("Web build directory does not exist: {}. Please build the web version first.", directory);
- return false;
- }
-
- directory_ = directory;
-
- 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 << "\"";
-
- STARTUPINFOA si = {};
- si.cb = sizeof(si);
- si.dwFlags = STARTF_USESHOWWINDOW;
- si.wShowWindow = SW_HIDE;
-
- PROCESS_INFORMATION pi = {};
-
- std::string cmdStr = cmd.str();
- if (!CreateProcessA(
- nullptr,
- const_cast<char*>(cmdStr.c_str()),
- nullptr,
- nullptr,
- FALSE,
- CREATE_NO_WINDOW,
- nullptr,
- directory.c_str(),
- &si,
- &pi
- )) {
- ES_LOG_ERROR("Failed to start HTTP server: error code {}", GetLastError());
- return false;
- }
-
- processHandle_ = pi.hProcess;
- threadHandle_ = pi.hThread;
-#else
- pid_ = fork();
- if (pid_ < 0) {
- ES_LOG_ERROR("Failed to fork process for HTTP server");
- return false;
- }
-
- if (pid_ == 0) {
- 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(),
- "--directory", directory.c_str(), nullptr);
- _exit(1);
- }
-#endif
-
- running_ = true;
- ES_LOG_INFO("HTTP server started on port {} serving {}", port_, directory_);
- return true;
-}
-
-void WebPreviewServer::stop() {
- if (!running_) {
- return;
- }
-
-#ifdef ES_PLATFORM_WINDOWS
- if (processHandle_) {
- TerminateProcess(processHandle_, 0);
- CloseHandle(processHandle_);
- processHandle_ = nullptr;
- }
- if (threadHandle_) {
- CloseHandle(threadHandle_);
- threadHandle_ = nullptr;
- }
-#else
- if (pid_ > 0) {
- kill(pid_, SIGTERM);
- waitpid(pid_, nullptr, 0);
- pid_ = 0;
- }
-#endif
-
- running_ = false;
- ES_LOG_INFO("HTTP server stopped");
-}
-
-std::string WebPreviewServer::getUrl() const {
- std::stringstream ss;
- ss << "http://localhost:" << port_ << "/";
- return ss.str();
-}
-
-void WebPreviewServer::openInBrowser(const std::string& url) {
-#ifdef ES_PLATFORM_WINDOWS
- ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
-#elif defined(__APPLE__)
- std::string cmd = "open \"" + url + "\"";
- std::system(cmd.c_str());
-#else
- std::string cmd = "xdg-open \"" + url + "\"";
- std::system(cmd.c_str());
-#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
deleted file mode 100644
index b68c049cc..000000000
--- a/src/esengine/editor/preview/WebPreviewServer.hpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * @file WebPreviewServer.hpp
- * @brief Local HTTP server for web preview
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../../core/Types.hpp"
-#include <string>
-
-#ifdef ES_PLATFORM_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <winsock2.h>
-#include <windows.h>
-#endif
-
-namespace esengine {
-namespace editor {
-
-class WebPreviewServer {
-public:
- WebPreviewServer() = default;
- ~WebPreviewServer();
-
- WebPreviewServer(const WebPreviewServer&) = delete;
- WebPreviewServer& operator=(const WebPreviewServer&) = delete;
-
- bool start(const std::string& directory, u16 port = 8080);
- void stop();
- bool isRunning() const { return running_; }
- u16 getPort() const { return port_; }
- std::string getUrl() const;
-
- static void openInBrowser(const std::string& url);
- static bool isPortAvailable(u16 port);
-
-private:
- bool running_ = false;
- u16 port_ = 8080;
- std::string directory_;
-
-#ifdef ES_PLATFORM_WINDOWS
- HANDLE processHandle_ = nullptr;
- HANDLE threadHandle_ = nullptr;
-#else
- pid_t pid_ = 0;
-#endif
-};
-
-} // namespace editor
-} // namespace esengine
diff --git a/src/esengine/editor/project/ProjectManager.cpp b/src/esengine/editor/project/ProjectManager.cpp
deleted file mode 100644
index 22947035d..000000000
--- a/src/esengine/editor/project/ProjectManager.cpp
+++ /dev/null
@@ -1,390 +0,0 @@
-/**
- * @file ProjectManager.cpp
- * @brief Core project management implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ProjectManager.hpp"
-#include "ProjectSerializer.hpp"
-#include "../AssetDatabase.hpp"
-#include "../core/EditorEvents.hpp"
-#include "../../events/Dispatcher.hpp"
-#include "../../platform/FileSystem.hpp"
-#include "../../platform/PathResolver.hpp"
-#include "../../core/Log.hpp"
-
-#include <algorithm>
-#include <chrono>
-#include <filesystem>
-#include <unordered_map>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-ProjectManager::ProjectManager(Dispatcher& dispatcher, AssetDatabase& assetDatabase)
- : dispatcher_(dispatcher)
- , asset_database_(assetDatabase) {
-}
-
-ProjectManager::~ProjectManager() {
- if (has_open_project_) {
- closeProject();
- }
-}
-
-// =============================================================================
-// Project Operations
-// =============================================================================
-
-Result<bool> ProjectManager::createProject(const std::string& directory,
- const std::string& name) {
-#ifdef ES_PLATFORM_WEB
- return Result<bool>::err("Project creation not supported on web platform");
-#endif
-
- if (directory.empty()) {
- return Result<bool>::err("Directory path cannot be empty");
- }
-
- if (name.empty()) {
- return Result<bool>::err("Project name cannot be empty");
- }
-
- if (FileSystem::directoryExists(directory)) {
- return Result<bool>::err("Directory already exists: " + directory);
- }
-
- ES_LOG_INFO("ProjectManager: Creating project '{}' at {}", name, directory);
-
- if (!FileSystem::createDirectory(directory)) {
- return Result<bool>::err("Failed to create project directory");
- }
-
- createDirectoryStructure(directory);
-
- ProjectInfo project;
- project.name = name;
- project.rootDirectory = directory;
- project.path = directory + "/" + PROJECT_FILE_NAME;
- project.engineVersion = ENGINE_VERSION;
- project.formatVersion = PROJECT_FORMAT_VERSION;
- project.created = getCurrentTimestamp();
- project.lastOpened = project.created;
- project.settings.targetPlatforms = {TargetPlatform::Windows};
- project.settings.defaultScene = "scenes/main.scene";
- project.settings.renderer.defaultWidth = 1280;
- project.settings.renderer.defaultHeight = 720;
- project.settings.renderer.vsync = true;
-
- std::string json = ProjectSerializer::serialize(project);
- if (!FileSystem::writeTextFile(project.path, json)) {
- return Result<bool>::err("Failed to write project file");
- }
-
- ES_LOG_INFO("ProjectManager: Project created successfully");
-
- auto result = openProject(project.path);
- if (result.isErr()) {
- return result;
- }
-
- return Result<bool>::ok(true);
-}
-
-Result<bool> ProjectManager::openProject(const std::string& projectFilePath) {
-#ifdef ES_PLATFORM_WEB
- return Result<bool>::err("Project opening not supported on web platform");
-#endif
-
- if (projectFilePath.empty()) {
- return Result<bool>::err("Project file path cannot be empty");
- }
-
- if (!FileSystem::fileExists(projectFilePath)) {
- return Result<bool>::err("Project file not found: " + projectFilePath);
- }
-
- ES_LOG_INFO("ProjectManager: Opening project from {}", projectFilePath);
-
- if (has_open_project_) {
- closeProject();
- }
-
- std::string content = FileSystem::readTextFile(projectFilePath);
- if (content.empty()) {
- return Result<bool>::err("Failed to read project file");
- }
-
- ProjectInfo project;
- if (!ProjectSerializer::deserialize(content, project)) {
- return Result<bool>::err("Failed to parse project file");
- }
-
- project.path = projectFilePath;
- project.rootDirectory = getParentDirectory(projectFilePath);
- project.lastOpened = getCurrentTimestamp();
-
- std::string updatedJson = ProjectSerializer::serialize(project);
- FileSystem::writeTextFile(projectFilePath, updatedJson);
-
- current_project_ = std::move(project);
- has_open_project_ = true;
-
- updatePathResolver(current_project_.rootDirectory);
- initializeAssetDatabase(current_project_.rootDirectory);
-
- recent_projects_.addProject(current_project_.path, current_project_.name);
-
- fireProjectOpenedEvent();
-
- checkAndSyncDependencies();
-
- ES_LOG_INFO("ProjectManager: Project '{}' opened successfully", current_project_.name);
-
- return Result<bool>::ok(true);
-}
-
-void ProjectManager::closeProject() {
- if (!has_open_project_) {
- return;
- }
-
- ES_LOG_INFO("ProjectManager: Closing project '{}'", current_project_.name);
-
- fireProjectClosedEvent();
-
- current_project_ = ProjectInfo{};
- has_open_project_ = false;
-
- PathResolver::setProjectRoot("");
-}
-
-// =============================================================================
-// Project State
-// =============================================================================
-
-bool ProjectManager::hasOpenProject() const {
- return has_open_project_;
-}
-
-const ProjectInfo& ProjectManager::getCurrentProject() const {
- return current_project_;
-}
-
-ProjectInfo& ProjectManager::getCurrentProject() {
- return current_project_;
-}
-
-// =============================================================================
-// Settings
-// =============================================================================
-
-void ProjectManager::saveProjectSettings() {
- if (!has_open_project_) {
- ES_LOG_WARN("ProjectManager: No project open, cannot save settings");
- return;
- }
-
- std::string json = ProjectSerializer::serialize(current_project_);
- if (FileSystem::writeTextFile(current_project_.path, json)) {
- ES_LOG_DEBUG("ProjectManager: Project settings saved");
- } else {
- ES_LOG_ERROR("ProjectManager: Failed to save project settings");
- }
-}
-
-void ProjectManager::updateSettings(const ProjectSettings& settings) {
- if (!has_open_project_) {
- return;
- }
-
- current_project_.settings = settings;
- saveProjectSettings();
- fireProjectSettingsChangedEvent();
-}
-
-// =============================================================================
-// Build Paths
-// =============================================================================
-
-std::string ProjectManager::getWebBuildPath() const {
- if (!has_open_project_) {
- return "";
- }
- return current_project_.rootDirectory + "/build/web";
-}
-
-// =============================================================================
-// Recent Projects
-// =============================================================================
-
-RecentProjectsManager& ProjectManager::getRecentProjects() {
- return recent_projects_;
-}
-
-const RecentProjectsManager& ProjectManager::getRecentProjects() const {
- return recent_projects_;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void ProjectManager::createDirectoryStructure(const std::string& rootDir) {
- const std::vector<std::string> directories = {
- "/src",
- "/src/components",
- "/src/systems",
- "/assets",
- "/assets/scenes",
- "/assets/textures",
- "/assets/audio",
- "/assets/fonts",
- "/assets/prefabs",
- "/assets/shaders",
- "/build",
- "/.esengine"
- };
-
- for (const auto& dir : directories) {
- FileSystem::createDirectory(rootDir + dir);
- }
-
- copyTemplates(rootDir);
-}
-
-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(), '\\', '/');
-
- std::unordered_map<std::string, std::string> vars = {
- {"{{PROJECT_NAME}}", current_project_.name},
- {"{{SDK_PATH}}", sdkDir}
- };
-
- copyTemplateDirectory(templateDir, rootDir, vars);
-}
-
-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;
- }
-
- 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();
- }
- }
-
- FileSystem::writeTextFile(dst, content);
- ES_LOG_DEBUG("Created {}", dst);
-}
-
-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) {
- PathResolver::setProjectRoot(rootDir);
- ES_LOG_DEBUG("ProjectManager: PathResolver project root set to {}", rootDir);
-}
-
-void ProjectManager::initializeAssetDatabase(const std::string& rootDir) {
- asset_database_.setProjectPath(rootDir);
- asset_database_.scan();
-}
-
-void ProjectManager::fireProjectOpenedEvent() {
- dispatcher_.trigger(ProjectOpened{
- .path = current_project_.path,
- .name = current_project_.name
- });
-}
-
-void ProjectManager::fireProjectClosedEvent() {
- dispatcher_.trigger(ProjectClosed{});
-}
-
-void ProjectManager::fireProjectSettingsChangedEvent() {
- dispatcher_.trigger(ProjectSettingsChanged{});
-}
-
-std::string ProjectManager::getParentDirectory(const std::string& path) {
- usize pos = path.find_last_of("/\\");
- if (pos != std::string::npos) {
- return path.substr(0, pos);
- }
- return path;
-}
-
-u64 ProjectManager::getCurrentTimestamp() {
- auto now = std::chrono::system_clock::now();
- return static_cast<u64>(
- std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
-}
-
-void ProjectManager::checkAndSyncDependencies() {
- std::string rootDir = current_project_.rootDirectory;
- std::string packageJsonPath = rootDir + "/package.json";
- std::string nodeModulesPath = rootDir + "/node_modules";
- std::string esengineModulePath = nodeModulesPath + "/esengine";
-
- if (!FileSystem::fileExists(packageJsonPath)) {
- ES_LOG_INFO("No package.json found, copying templates...");
- copyTemplates(rootDir);
- return;
- }
-
- if (!FileSystem::directoryExists(esengineModulePath)) {
- ES_LOG_WARN("Dependencies not installed. Please run 'npm install' in {}", rootDir);
- }
-
- std::string sdkDir = PathResolver::editorPath("sdk");
- std::replace(sdkDir.begin(), sdkDir.end(), '\\', '/');
- std::string currentPackageJson = FileSystem::readTextFile(packageJsonPath);
-
- if (currentPackageJson.find(sdkDir) == std::string::npos) {
- ES_LOG_INFO("Updating package.json with current SDK path...");
- 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.");
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/project/ProjectManager.hpp b/src/esengine/editor/project/ProjectManager.hpp
deleted file mode 100644
index dbfa72260..000000000
--- a/src/esengine/editor/project/ProjectManager.hpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * @file ProjectManager.hpp
- * @brief Core project management functionality
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "ProjectTypes.hpp"
-#include "RecentProjectsManager.hpp"
-#include "../../core/Types.hpp"
-
-#include <string>
-#include <unordered_map>
-
-namespace esengine {
-class Dispatcher;
-}
-
-namespace esengine::editor {
-
-class AssetDatabase;
-
-// =============================================================================
-// ProjectManager
-// =============================================================================
-
-class ProjectManager {
-public:
- // =========================================================================
- // Constructor
- // =========================================================================
-
- explicit ProjectManager(Dispatcher& dispatcher, AssetDatabase& assetDatabase);
- ~ProjectManager();
-
- ProjectManager(const ProjectManager&) = delete;
- ProjectManager& operator=(const ProjectManager&) = delete;
-
- // =========================================================================
- // Project Operations
- // =========================================================================
-
- [[nodiscard]] Result<bool> createProject(const std::string& directory,
- const std::string& name);
- [[nodiscard]] Result<bool> openProject(const std::string& projectFilePath);
- void closeProject();
-
- // =========================================================================
- // Project State
- // =========================================================================
-
- [[nodiscard]] bool hasOpenProject() const;
- [[nodiscard]] const ProjectInfo& getCurrentProject() const;
- [[nodiscard]] ProjectInfo& getCurrentProject();
-
- // =========================================================================
- // Settings
- // =========================================================================
-
- void saveProjectSettings();
- void updateSettings(const ProjectSettings& settings);
-
- // =========================================================================
- // Build Paths
- // =========================================================================
-
- [[nodiscard]] std::string getWebBuildPath() const;
-
- // =========================================================================
- // Recent Projects
- // =========================================================================
-
- [[nodiscard]] RecentProjectsManager& getRecentProjects();
- [[nodiscard]] const RecentProjectsManager& getRecentProjects() const;
-
-private:
- void createDirectoryStructure(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();
- void fireProjectClosedEvent();
- void fireProjectSettingsChangedEvent();
-
- [[nodiscard]] static std::string getParentDirectory(const std::string& path);
- [[nodiscard]] static u64 getCurrentTimestamp();
-
- Dispatcher& dispatcher_;
- AssetDatabase& asset_database_;
- ProjectInfo current_project_;
- RecentProjectsManager recent_projects_;
- bool has_open_project_ = false;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/project/ProjectSerializer.cpp b/src/esengine/editor/project/ProjectSerializer.cpp
deleted file mode 100644
index 319069bb7..000000000
--- a/src/esengine/editor/project/ProjectSerializer.cpp
+++ /dev/null
@@ -1,283 +0,0 @@
-/**
- * @file ProjectSerializer.cpp
- * @brief Project file JSON serialization implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ProjectSerializer.hpp"
-#include "../../core/Log.hpp"
-
-#include <sstream>
-
-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;
-}
-
-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])) {
- ++valueStart;
- }
- if (valueStart >= json.size()) return 0;
-
- try {
- return std::stoull(json.substr(valueStart));
- } catch (...) {
- return 0;
- }
-}
-
-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;
-}
-
-std::vector<std::string> extractStringArray(const std::string& json, usize startPos,
- const std::string& key) {
- std::vector<std::string> result;
- std::string searchKey = "\"" + key + "\":";
- usize keyPos = json.find(searchKey, startPos);
- if (keyPos == std::string::npos) return result;
-
- usize arrayStart = json.find("[", keyPos);
- usize arrayEnd = json.find("]", arrayStart);
- if (arrayStart == std::string::npos || arrayEnd == std::string::npos) return result;
-
- std::string arrayContent = json.substr(arrayStart + 1, arrayEnd - arrayStart - 1);
- usize pos = 0;
- while ((pos = arrayContent.find("\"", pos)) != std::string::npos) {
- usize endPos = pos + 1;
- while (endPos < arrayContent.size()) {
- if (arrayContent[endPos] == '"' && arrayContent[endPos - 1] != '\\') break;
- ++endPos;
- }
- if (endPos < arrayContent.size()) {
- result.push_back(unescapeJsonString(arrayContent.substr(pos + 1, endPos - pos - 1)));
- }
- pos = endPos + 1;
- }
- return result;
-}
-
-} // namespace
-
-// =============================================================================
-// Project Serialization
-// =============================================================================
-
-std::string ProjectSerializer::serialize(const ProjectInfo& project) {
- std::stringstream ss;
-
- ss << "{\n";
- ss << " \"version\": " << project.formatVersion << ",\n";
- ss << " \"name\": \"" << escapeJsonString(project.name) << "\",\n";
- ss << " \"engineVersion\": \"" << escapeJsonString(project.engineVersion) << "\",\n";
- ss << " \"created\": " << project.created << ",\n";
- ss << " \"lastOpened\": " << project.lastOpened << ",\n";
-
- ss << " \"settings\": {\n";
-
- ss << " \"targetPlatforms\": [";
- for (usize i = 0; i < project.settings.targetPlatforms.size(); ++i) {
- if (i > 0) ss << ", ";
- ss << "\"" << targetPlatformToString(project.settings.targetPlatforms[i]) << "\"";
- }
- ss << "],\n";
-
- ss << " \"defaultScene\": \"" << escapeJsonString(project.settings.defaultScene) << "\",\n";
-
- ss << " \"renderer\": {\n";
- ss << " \"defaultWidth\": " << project.settings.renderer.defaultWidth << ",\n";
- ss << " \"defaultHeight\": " << project.settings.renderer.defaultHeight << ",\n";
- ss << " \"vsync\": " << (project.settings.renderer.vsync ? "true" : "false") << "\n";
- ss << " }\n";
-
- ss << " }\n";
- ss << "}\n";
-
- return ss.str();
-}
-
-bool ProjectSerializer::deserialize(const std::string& json, ProjectInfo& outProject) {
- if (json.empty()) {
- ES_LOG_ERROR("ProjectSerializer: Empty JSON");
- return false;
- }
-
- outProject.formatVersion = static_cast<u32>(extractUInt(json, 0, "version"));
- outProject.name = extractString(json, 0, "name");
- outProject.engineVersion = extractString(json, 0, "engineVersion");
- outProject.created = extractUInt(json, 0, "created");
- outProject.lastOpened = extractUInt(json, 0, "lastOpened");
-
- if (outProject.name.empty()) {
- ES_LOG_ERROR("ProjectSerializer: Missing project name");
- return false;
- }
-
- usize settingsPos = json.find("\"settings\":");
- if (settingsPos != std::string::npos) {
- auto platforms = extractStringArray(json, settingsPos, "targetPlatforms");
- outProject.settings.targetPlatforms.clear();
- for (const auto& p : platforms) {
- outProject.settings.targetPlatforms.push_back(targetPlatformFromString(p));
- }
-
- outProject.settings.defaultScene = extractString(json, settingsPos, "defaultScene");
-
- usize rendererPos = json.find("\"renderer\":", settingsPos);
- if (rendererPos != std::string::npos) {
- outProject.settings.renderer.defaultWidth =
- static_cast<u32>(extractUInt(json, rendererPos, "defaultWidth"));
- outProject.settings.renderer.defaultHeight =
- static_cast<u32>(extractUInt(json, rendererPos, "defaultHeight"));
- outProject.settings.renderer.vsync = extractBool(json, rendererPos, "vsync");
-
- if (outProject.settings.renderer.defaultWidth == 0) {
- outProject.settings.renderer.defaultWidth = 1280;
- }
- if (outProject.settings.renderer.defaultHeight == 0) {
- outProject.settings.renderer.defaultHeight = 720;
- }
- }
- }
-
- return true;
-}
-
-// =============================================================================
-// Recent Projects Serialization
-// =============================================================================
-
-std::string ProjectSerializer::serializeRecentProjects(
- const std::vector<RecentProject>& projects) {
- std::stringstream ss;
-
- ss << "{\n";
- ss << " \"version\": 1,\n";
- ss << " \"projects\": [\n";
-
- for (usize i = 0; i < projects.size(); ++i) {
- const auto& p = projects[i];
- ss << " {\n";
- ss << " \"path\": \"" << escapeJsonString(p.path) << "\",\n";
- ss << " \"name\": \"" << escapeJsonString(p.name) << "\",\n";
- ss << " \"lastOpened\": " << p.lastOpened << "\n";
- ss << " }";
- if (i + 1 < projects.size()) ss << ",";
- ss << "\n";
- }
-
- ss << " ]\n";
- ss << "}\n";
-
- return ss.str();
-}
-
-bool ProjectSerializer::deserializeRecentProjects(
- const std::string& json, std::vector<RecentProject>& outProjects) {
- outProjects.clear();
-
- if (json.empty()) {
- return false;
- }
-
- usize pos = 0;
- while ((pos = json.find("\"path\":", pos)) != std::string::npos) {
- RecentProject project;
- project.path = extractString(json, pos, "path");
- project.name = extractString(json, pos, "name");
- project.lastOpened = extractUInt(json, pos, "lastOpened");
-
- if (!project.path.empty()) {
- outProjects.push_back(std::move(project));
- }
-
- usize nextBrace = json.find("}", pos);
- if (nextBrace == std::string::npos) break;
- pos = nextBrace + 1;
- }
-
- return true;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/project/ProjectSerializer.hpp b/src/esengine/editor/project/ProjectSerializer.hpp
deleted file mode 100644
index c28db1219..000000000
--- a/src/esengine/editor/project/ProjectSerializer.hpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * @file ProjectSerializer.hpp
- * @brief Project file JSON serialization
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "ProjectTypes.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// ProjectSerializer
-// =============================================================================
-
-class ProjectSerializer {
-public:
- [[nodiscard]] static std::string serialize(const ProjectInfo& project);
- [[nodiscard]] static bool deserialize(const std::string& json, ProjectInfo& outProject);
-
- [[nodiscard]] static std::string serializeRecentProjects(
- const std::vector<RecentProject>& projects);
- [[nodiscard]] static bool deserializeRecentProjects(
- const std::string& json, std::vector<RecentProject>& outProjects);
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/project/ProjectTypes.hpp b/src/esengine/editor/project/ProjectTypes.hpp
deleted file mode 100644
index c044dc43a..000000000
--- a/src/esengine/editor/project/ProjectTypes.hpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * @file ProjectTypes.hpp
- * @brief Project management type definitions
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constants
-// =============================================================================
-
-constexpr const char* PROJECT_FILE_NAME = "project.esproject";
-constexpr const char* ENGINE_VERSION = "1.0.0";
-constexpr u32 PROJECT_FORMAT_VERSION = 1;
-
-// =============================================================================
-// Target Platform
-// =============================================================================
-
-enum class TargetPlatform : u8 {
- Windows,
- MacOS,
- Linux,
- Web,
- WxGame
-};
-
-[[nodiscard]] inline const char* targetPlatformToString(TargetPlatform platform) {
- switch (platform) {
- case TargetPlatform::Windows: return "windows";
- case TargetPlatform::MacOS: return "macos";
- case TargetPlatform::Linux: return "linux";
- case TargetPlatform::Web: return "web";
- case TargetPlatform::WxGame: return "wxgame";
- }
- return "unknown";
-}
-
-[[nodiscard]] inline TargetPlatform targetPlatformFromString(const std::string& str) {
- if (str == "windows") return TargetPlatform::Windows;
- if (str == "macos") return TargetPlatform::MacOS;
- if (str == "linux") return TargetPlatform::Linux;
- if (str == "web") return TargetPlatform::Web;
- if (str == "wxgame") return TargetPlatform::WxGame;
- return TargetPlatform::Windows;
-}
-
-// =============================================================================
-// Project Settings
-// =============================================================================
-
-struct RendererSettings {
- u32 defaultWidth = 1280;
- u32 defaultHeight = 720;
- bool vsync = true;
-};
-
-struct ProjectSettings {
- std::vector<TargetPlatform> targetPlatforms{TargetPlatform::Windows};
- std::string defaultScene;
- RendererSettings renderer;
-};
-
-// =============================================================================
-// Project Info
-// =============================================================================
-
-struct ProjectInfo {
- std::string name;
- std::string path;
- std::string rootDirectory;
- std::string engineVersion{ENGINE_VERSION};
- u32 formatVersion{PROJECT_FORMAT_VERSION};
- u64 created = 0;
- u64 lastOpened = 0;
- ProjectSettings settings;
-
- [[nodiscard]] bool isValid() const {
- return !name.empty() && !path.empty() && !rootDirectory.empty();
- }
-};
-
-// =============================================================================
-// Recent Project
-// =============================================================================
-
-struct RecentProject {
- std::string path;
- std::string name;
- u64 lastOpened = 0;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/project/RecentProjectsManager.cpp b/src/esengine/editor/project/RecentProjectsManager.cpp
deleted file mode 100644
index c86c3fe46..000000000
--- a/src/esengine/editor/project/RecentProjectsManager.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * @file RecentProjectsManager.cpp
- * @brief Recent projects list management implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "RecentProjectsManager.hpp"
-#include "ProjectSerializer.hpp"
-#include "../../platform/FileSystem.hpp"
-#include "../../core/Log.hpp"
-
-#include <algorithm>
-#include <chrono>
-#include <cstdlib>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Persistence
-// =============================================================================
-
-void RecentProjectsManager::load() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string configPath = getConfigFilePath();
- if (!FileSystem::fileExists(configPath)) {
- ES_LOG_DEBUG("RecentProjectsManager: No recent projects file found");
- return;
- }
-
- std::string content = FileSystem::readTextFile(configPath);
- if (content.empty()) {
- return;
- }
-
- if (ProjectSerializer::deserializeRecentProjects(content, recent_projects_)) {
- ES_LOG_DEBUG("RecentProjectsManager: Loaded {} recent projects", recent_projects_.size());
- }
-}
-
-void RecentProjectsManager::save() {
-#ifdef ES_PLATFORM_WEB
- return;
-#endif
-
- std::string configDir = getConfigDirectory();
- if (!FileSystem::directoryExists(configDir)) {
- FileSystem::createDirectory(configDir);
- }
-
- std::string json = ProjectSerializer::serializeRecentProjects(recent_projects_);
- FileSystem::writeTextFile(getConfigFilePath(), json);
- ES_LOG_DEBUG("RecentProjectsManager: Saved {} recent projects", recent_projects_.size());
-}
-
-// =============================================================================
-// Project Management
-// =============================================================================
-
-void RecentProjectsManager::addProject(const std::string& path, const std::string& name) {
- auto it = std::find_if(recent_projects_.begin(), recent_projects_.end(),
- [&path](const RecentProject& p) { return p.path == path; });
-
- auto now = std::chrono::system_clock::now();
- auto timestamp = static_cast<u64>(
- std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
-
- if (it != recent_projects_.end()) {
- it->lastOpened = timestamp;
- it->name = name;
- std::rotate(recent_projects_.begin(), it, it + 1);
- } else {
- RecentProject project;
- project.path = path;
- project.name = name;
- project.lastOpened = timestamp;
- recent_projects_.insert(recent_projects_.begin(), project);
-
- if (recent_projects_.size() > MAX_RECENT_PROJECTS) {
- recent_projects_.resize(MAX_RECENT_PROJECTS);
- }
- }
-
- save();
-}
-
-void RecentProjectsManager::removeProject(const std::string& path) {
- auto it = std::remove_if(recent_projects_.begin(), recent_projects_.end(),
- [&path](const RecentProject& p) { return p.path == path; });
-
- if (it != recent_projects_.end()) {
- recent_projects_.erase(it, recent_projects_.end());
- save();
- }
-}
-
-void RecentProjectsManager::clearAll() {
- recent_projects_.clear();
- save();
-}
-
-// =============================================================================
-// Accessors
-// =============================================================================
-
-const std::vector<RecentProject>& RecentProjectsManager::getRecentProjects() const {
- return recent_projects_;
-}
-
-bool RecentProjectsManager::hasRecentProjects() const {
- return !recent_projects_.empty();
-}
-
-// =============================================================================
-// Config Path
-// =============================================================================
-
-std::string RecentProjectsManager::getConfigDirectory() {
-#if defined(_WIN32) || defined(_WIN64)
- const char* appData = std::getenv("APPDATA");
- if (appData) {
- return std::string(appData) + "\\ESEngine";
- }
- return "";
-#elif defined(__APPLE__)
- const char* home = std::getenv("HOME");
- if (home) {
- return std::string(home) + "/Library/Application Support/ESEngine";
- }
- return "";
-#else
- const char* home = std::getenv("HOME");
- if (home) {
- return std::string(home) + "/.config/esengine";
- }
- return "";
-#endif
-}
-
-std::string RecentProjectsManager::getConfigFilePath() {
- std::string dir = getConfigDirectory();
- if (dir.empty()) {
- return "";
- }
-#if defined(_WIN32) || defined(_WIN64)
- return dir + "\\recent_projects.json";
-#else
- return dir + "/recent_projects.json";
-#endif
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/project/RecentProjectsManager.hpp b/src/esengine/editor/project/RecentProjectsManager.hpp
deleted file mode 100644
index deb5f0d51..000000000
--- a/src/esengine/editor/project/RecentProjectsManager.hpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * @file RecentProjectsManager.hpp
- * @brief Recent projects list management
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "ProjectTypes.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// RecentProjectsManager
-// =============================================================================
-
-class RecentProjectsManager {
-public:
- static constexpr usize MAX_RECENT_PROJECTS = 10;
-
- // =========================================================================
- // Lifecycle
- // =========================================================================
-
- RecentProjectsManager() = default;
- ~RecentProjectsManager() = default;
-
- RecentProjectsManager(const RecentProjectsManager&) = delete;
- RecentProjectsManager& operator=(const RecentProjectsManager&) = delete;
-
- // =========================================================================
- // Persistence
- // =========================================================================
-
- void load();
- void save();
-
- // =========================================================================
- // Project Management
- // =========================================================================
-
- void addProject(const std::string& path, const std::string& name);
- void removeProject(const std::string& path);
- void clearAll();
-
- // =========================================================================
- // Accessors
- // =========================================================================
-
- [[nodiscard]] const std::vector<RecentProject>& getRecentProjects() const;
- [[nodiscard]] bool hasRecentProjects() const;
-
-private:
- [[nodiscard]] static std::string getConfigDirectory();
- [[nodiscard]] static std::string getConfigFilePath();
-
- std::vector<RecentProject> recent_projects_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/PropertyEditor.cpp b/src/esengine/editor/property/PropertyEditor.cpp
deleted file mode 100644
index aeac2b942..000000000
--- a/src/esengine/editor/property/PropertyEditor.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * @file PropertyEditor.cpp
- * @brief PropertyEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "PropertyEditor.hpp"
-#include "../command/CommandHistory.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-PropertyEditor::PropertyEditor(const ui::WidgetId& id, const std::string& propertyName)
- : ui::Widget(id), propertyName_(propertyName), label_(propertyName) {}
-
-// =============================================================================
-// Label
-// =============================================================================
-
-void PropertyEditor::setLabel(const std::string& label) {
- if (label_ == label) {
- return;
- }
-
- label_ = label;
- invalidateLayout();
-}
-
-void PropertyEditor::setShowLabel(bool show) {
- if (showLabel_ == show) {
- return;
- }
-
- showLabel_ = show;
- invalidateLayout();
-}
-
-// =============================================================================
-// Command Integration
-// =============================================================================
-
-void PropertyEditor::setCommandHistory(CommandHistory* history) {
- commandHistory_ = history;
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-void PropertyEditor::notifyValueChanged(const std::any& oldValue, const std::any& newValue) {
- if (commandHistory_) {
- auto command = createCommand(oldValue, newValue);
- if (command) {
- commandHistory_->execute(std::move(command));
- }
- }
-
- onValueChanged.publish(newValue);
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/PropertyEditor.hpp b/src/esengine/editor/property/PropertyEditor.hpp
deleted file mode 100644
index 16d37b525..000000000
--- a/src/esengine/editor/property/PropertyEditor.hpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * @file PropertyEditor.hpp
- * @brief Base class for property editing widgets
- * @details Provides the foundation for type-specific property editors that
- * integrate with the command system for undo/redo support.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <any>
-#include <string>
-
-namespace esengine::editor {
-
-class Command;
-class CommandHistory;
-
-// =============================================================================
-// PropertyEditor Class
-// =============================================================================
-
-/**
- * @brief Base class for property editing widgets
- *
- * @details PropertyEditor provides a common interface for widgets that edit
- * component properties. Each editor creates commands for modifications
- * to enable undo/redo support.
- *
- * @code
- * class FloatEditor : public PropertyEditor {
- * public:
- * void setValue(const std::any& value) override {
- * f32 floatValue = std::any_cast<f32>(value);
- * textField_->setText(std::to_string(floatValue));
- * }
- *
- * std::any getValue() const override {
- * return std::stof(textField_->getText());
- * }
- * };
- * @endcode
- */
-class PropertyEditor : public ui::Widget {
-public:
- /**
- * @brief Constructs a property editor
- * @param id Unique widget identifier
- * @param propertyName Name of the property being edited
- */
- explicit PropertyEditor(const ui::WidgetId& id, const std::string& propertyName);
-
- ~PropertyEditor() override = default;
-
- // =========================================================================
- // Property Access
- // =========================================================================
-
- /**
- * @brief Sets the property value
- * @param value New value (type-specific, stored as std::any)
- */
- virtual void setValue(const std::any& value) = 0;
-
- /**
- * @brief Gets the current property value
- * @return Current value as std::any
- */
- virtual std::any getValue() const = 0;
-
- /**
- * @brief Gets the property name
- * @return Property name string
- */
- const std::string& getPropertyName() const { return propertyName_; }
-
- // =========================================================================
- // Label
- // =========================================================================
-
- /**
- * @brief Sets the display label
- * @param label Label text (defaults to property name)
- */
- void setLabel(const std::string& label);
-
- /**
- * @brief Gets the display label
- * @return Label text
- */
- const std::string& getLabel() const { return label_; }
-
- /**
- * @brief Sets whether to show the label
- * @param show True to show label
- */
- void setShowLabel(bool show);
-
- /**
- * @brief Gets whether the label is shown
- * @return True if label is shown
- */
- bool getShowLabel() const { return showLabel_; }
-
- // =========================================================================
- // Command Integration
- // =========================================================================
-
- /**
- * @brief Sets the command history for undo/redo
- * @param history Command history manager
- */
- void setCommandHistory(CommandHistory* history);
-
- /**
- * @brief Gets the command history
- * @return Command history manager or nullptr
- */
- CommandHistory* getCommandHistory() const { return commandHistory_; }
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /**
- * @brief Emitted when the value changes
- * @param value New value as std::any
- */
- Signal<void(const std::any&)> onValueChanged;
-
-protected:
- /**
- * @brief Creates a command for a value change
- * @param oldValue Previous value
- * @param newValue New value
- * @return Command object or nullptr
- */
- virtual Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) = 0;
-
- /**
- * @brief Notifies that the value has changed
- * @param oldValue Previous value
- * @param newValue New value
- *
- * @details Creates and executes a command if command history is set,
- * otherwise just emits the signal.
- */
- void notifyValueChanged(const std::any& oldValue, const std::any& newValue);
-
- std::string propertyName_;
- std::string label_;
- bool showLabel_ = true;
-
- CommandHistory* commandHistory_ = nullptr;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/BoolEditor.cpp b/src/esengine/editor/property/editors/BoolEditor.cpp
deleted file mode 100644
index 6af5bc46a..000000000
--- a/src/esengine/editor/property/editors/BoolEditor.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * @file BoolEditor.cpp
- * @brief BoolEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "BoolEditor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-BoolEditor::BoolEditor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto labelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- labelWidget->setText(label_);
- labelWidget->setFontSize(12.0f);
- labelWidget_ = labelWidget.get();
- addChild(std::move(labelWidget));
- }
-
- auto checkboxWidget = makeUnique<ui::Checkbox>(ui::WidgetId(getId().path + "_checkbox"));
- checkboxWidget->setCheckboxSize(CHECKBOX_SIZE);
- checkbox_ = checkboxWidget.get();
- addChild(std::move(checkboxWidget));
-
- connections_.add(sink(checkbox_->onChanged).connect(
- [this](bool checked) { onCheckboxChanged(checked); }
- ));
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void BoolEditor::setValue(const std::any& value) {
- try {
- bool newValue = std::any_cast<bool>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
-
- updatingFromValue_ = true;
- if (checkbox_) {
- checkbox_->setChecked(value_);
- }
- updatingFromValue_ = false;
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any BoolEditor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 BoolEditor::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableWidth;
- (void)availableHeight;
-
- f32 width = 0.0f;
- f32 height = 20.0f;
-
- if (labelWidget_ && showLabel_) {
- width += LABEL_WIDTH + SPACING;
- }
-
- width += CHECKBOX_SIZE;
-
- return glm::vec2(width, height);
-}
-
-void BoolEditor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
-
- if (labelWidget_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, LABEL_WIDTH, bounds.height};
- labelWidget_->layout(labelBounds);
- x += LABEL_WIDTH + SPACING;
- }
-
- if (checkbox_) {
- f32 checkboxY = bounds.y + (bounds.height - CHECKBOX_SIZE) * 0.5f;
- ui::Rect checkboxBounds{x, checkboxY, CHECKBOX_SIZE, CHECKBOX_SIZE};
- checkbox_->layout(checkboxBounds);
- }
-}
-
-void BoolEditor::render(ui::UIBatchRenderer& renderer) {
- constexpr glm::vec4 labelColor{0.686f, 0.686f, 0.686f, 1.0f};
-
- if (labelWidget_ && showLabel_) {
- labelWidget_->setColor(labelColor);
- labelWidget_->renderTree(renderer);
- }
-
- if (checkbox_) {
- checkbox_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> BoolEditor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- bool oldBool = std::any_cast<bool>(oldValue);
- bool newBool = std::any_cast<bool>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newBool]() {
- setValue(newBool);
- return CommandResult::Success;
- },
- [this, oldBool]() {
- setValue(oldBool);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void BoolEditor::onCheckboxChanged(bool checked) {
- if (updatingFromValue_) {
- return;
- }
-
- bool oldValue = value_;
- if (oldValue != checked) {
- value_ = checked;
- notifyValueChanged(oldValue, checked);
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/BoolEditor.hpp b/src/esengine/editor/property/editors/BoolEditor.hpp
deleted file mode 100644
index cf62e398d..000000000
--- a/src/esengine/editor/property/editors/BoolEditor.hpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * @file BoolEditor.hpp
- * @brief Property editor for boolean values
- * @details Uses a Checkbox widget for visual editing of bool properties.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "../../../ui/widgets/Checkbox.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// BoolEditor Class
-// =============================================================================
-
-class BoolEditor : public PropertyEditor {
-public:
- explicit BoolEditor(const ui::WidgetId& id, const std::string& propertyName);
- ~BoolEditor() override = default;
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- void onCheckboxChanged(bool checked);
-
- bool value_ = false;
- bool updatingFromValue_ = false;
-
- ui::Label* labelWidget_ = nullptr;
- ui::Checkbox* checkbox_ = nullptr;
- ConnectionHolder connections_;
-
- static constexpr f32 LABEL_WIDTH = 80.0f;
- static constexpr f32 CHECKBOX_SIZE = 16.0f;
- static constexpr f32 SPACING = 8.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/ColorEditor.cpp b/src/esengine/editor/property/editors/ColorEditor.cpp
deleted file mode 100644
index 45a9f8d6e..000000000
--- a/src/esengine/editor/property/editors/ColorEditor.cpp
+++ /dev/null
@@ -1,327 +0,0 @@
-/**
- * @file ColorEditor.cpp
- * @brief ColorEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ColorEditor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-ColorEditor::ColorEditor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto mainLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- mainLabelWidget->setText(label_);
- mainLabelWidget->setFontSize(12.0f);
- mainLabel_ = mainLabelWidget.get();
- addChild(std::move(mainLabelWidget));
- }
-
- auto colorPreviewWidget = makeUnique<ui::Panel>(ui::WidgetId(getId().path + "_preview"));
- colorPreviewWidget->setDrawBackground(true);
- colorPreviewWidget->setBackgroundColor(value_);
- colorPreview_ = colorPreviewWidget.get();
- addChild(std::move(colorPreviewWidget));
-
- auto rLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_r_label"));
- rLabelWidget->setText("R");
- rLabelWidget->setFontSize(12.0f);
- rLabel_ = rLabelWidget.get();
- addChild(std::move(rLabelWidget));
-
- auto rEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_r"), "r");
- rEditorWidget->setShowLabel(false);
- rEditorWidget->setRange(0.0f, 1.0f);
- rEditor_ = rEditorWidget.get();
- addChild(std::move(rEditorWidget));
-
- auto gLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_g_label"));
- gLabelWidget->setText("G");
- gLabelWidget->setFontSize(12.0f);
- gLabel_ = gLabelWidget.get();
- addChild(std::move(gLabelWidget));
-
- auto gEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_g"), "g");
- gEditorWidget->setShowLabel(false);
- gEditorWidget->setRange(0.0f, 1.0f);
- gEditor_ = gEditorWidget.get();
- addChild(std::move(gEditorWidget));
-
- auto bLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_b_label"));
- bLabelWidget->setText("B");
- bLabelWidget->setFontSize(12.0f);
- bLabel_ = bLabelWidget.get();
- addChild(std::move(bLabelWidget));
-
- auto bEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_b"), "b");
- bEditorWidget->setShowLabel(false);
- bEditorWidget->setRange(0.0f, 1.0f);
- bEditor_ = bEditorWidget.get();
- addChild(std::move(bEditorWidget));
-
- auto aLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_a_label"));
- aLabelWidget->setText("A");
- aLabelWidget->setFontSize(12.0f);
- aLabel_ = aLabelWidget.get();
- addChild(std::move(aLabelWidget));
-
- auto aEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_a"), "a");
- aEditorWidget->setShowLabel(false);
- aEditorWidget->setRange(0.0f, 1.0f);
- aEditor_ = aEditorWidget.get();
- addChild(std::move(aEditorWidget));
-
- connections_.add(sink(rEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
- connections_.add(sink(gEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
- connections_.add(sink(bEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
- connections_.add(sink(aEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void ColorEditor::setValue(const std::any& value) {
- try {
- glm::vec4 newValue = std::any_cast<glm::vec4>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
-
- updatingFromValue_ = true;
- rEditor_->setValue(value_.r);
- gEditor_->setValue(value_.g);
- bEditor_->setValue(value_.b);
- aEditor_->setValue(value_.a);
- if (colorPreview_) {
- colorPreview_->setBackgroundColor(value_);
- }
- updatingFromValue_ = false;
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any ColorEditor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 ColorEditor::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableWidth;
- (void)availableHeight;
-
- f32 width = 0.0f;
- f32 height = ROW_HEIGHT * 2.0f + SPACING;
-
- if (mainLabel_ && showLabel_) {
- width += MAIN_LABEL_WIDTH + SPACING;
- }
-
- width += COLOR_PREVIEW_SIZE + SPACING;
- width += (COMPONENT_LABEL_WIDTH + SPACING + FLOAT_EDITOR_WIDTH + SPACING) * 2;
-
- return glm::vec2(width, height);
-}
-
-void ColorEditor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
- f32 y = bounds.y;
-
- if (mainLabel_ && showLabel_) {
- ui::Rect labelBounds{x, y, MAIN_LABEL_WIDTH, ROW_HEIGHT};
- mainLabel_->layout(labelBounds);
- x += MAIN_LABEL_WIDTH + SPACING;
- }
-
- if (colorPreview_) {
- ui::Rect previewBounds{x, y, COLOR_PREVIEW_SIZE, ROW_HEIGHT * 2.0f + SPACING};
- colorPreview_->layout(previewBounds);
- x += COLOR_PREVIEW_SIZE + SPACING;
- }
-
- f32 rowX = x;
-
- if (rLabel_) {
- ui::Rect labelBounds{rowX, y, COMPONENT_LABEL_WIDTH, ROW_HEIGHT};
- rLabel_->layout(labelBounds);
- rowX += COMPONENT_LABEL_WIDTH + SPACING;
- }
-
- if (rEditor_) {
- ui::Rect editorBounds{rowX, y, FLOAT_EDITOR_WIDTH, ROW_HEIGHT};
- rEditor_->layout(editorBounds);
- rowX += FLOAT_EDITOR_WIDTH + SPACING;
- }
-
- if (gLabel_) {
- ui::Rect labelBounds{rowX, y, COMPONENT_LABEL_WIDTH, ROW_HEIGHT};
- gLabel_->layout(labelBounds);
- rowX += COMPONENT_LABEL_WIDTH + SPACING;
- }
-
- if (gEditor_) {
- ui::Rect editorBounds{rowX, y, FLOAT_EDITOR_WIDTH, ROW_HEIGHT};
- gEditor_->layout(editorBounds);
- }
-
- y += ROW_HEIGHT + SPACING;
- rowX = x;
-
- if (bLabel_) {
- ui::Rect labelBounds{rowX, y, COMPONENT_LABEL_WIDTH, ROW_HEIGHT};
- bLabel_->layout(labelBounds);
- rowX += COMPONENT_LABEL_WIDTH + SPACING;
- }
-
- if (bEditor_) {
- ui::Rect editorBounds{rowX, y, FLOAT_EDITOR_WIDTH, ROW_HEIGHT};
- bEditor_->layout(editorBounds);
- rowX += FLOAT_EDITOR_WIDTH + SPACING;
- }
-
- if (aLabel_) {
- ui::Rect labelBounds{rowX, y, COMPONENT_LABEL_WIDTH, ROW_HEIGHT};
- aLabel_->layout(labelBounds);
- rowX += COMPONENT_LABEL_WIDTH + SPACING;
- }
-
- if (aEditor_) {
- ui::Rect editorBounds{rowX, y, FLOAT_EDITOR_WIDTH, ROW_HEIGHT};
- aEditor_->layout(editorBounds);
- }
-}
-
-void ColorEditor::render(ui::UIBatchRenderer& renderer) {
- constexpr glm::vec4 labelColor{0.686f, 0.686f, 0.686f, 1.0f};
- constexpr glm::vec4 rColor{0.9f, 0.4f, 0.4f, 1.0f};
- constexpr glm::vec4 gColor{0.4f, 0.9f, 0.4f, 1.0f};
- constexpr glm::vec4 bColor{0.4f, 0.6f, 0.9f, 1.0f};
- constexpr glm::vec4 aColor{0.7f, 0.7f, 0.7f, 1.0f};
-
- if (mainLabel_ && showLabel_) {
- mainLabel_->setColor(labelColor);
- mainLabel_->renderTree(renderer);
- }
-
- if (colorPreview_) {
- colorPreview_->setBackgroundColor(value_);
- colorPreview_->renderTree(renderer);
- }
-
- if (rLabel_) {
- rLabel_->setColor(rColor);
- rLabel_->renderTree(renderer);
- }
- if (rEditor_) {
- rEditor_->renderTree(renderer);
- }
-
- if (gLabel_) {
- gLabel_->setColor(gColor);
- gLabel_->renderTree(renderer);
- }
- if (gEditor_) {
- gEditor_->renderTree(renderer);
- }
-
- if (bLabel_) {
- bLabel_->setColor(bColor);
- bLabel_->renderTree(renderer);
- }
- if (bEditor_) {
- bEditor_->renderTree(renderer);
- }
-
- if (aLabel_) {
- aLabel_->setColor(aColor);
- aLabel_->renderTree(renderer);
- }
- if (aEditor_) {
- aEditor_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> ColorEditor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- glm::vec4 oldVec = std::any_cast<glm::vec4>(oldValue);
- glm::vec4 newVec = std::any_cast<glm::vec4>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newVec]() {
- setValue(newVec);
- return CommandResult::Success;
- },
- [this, oldVec]() {
- setValue(oldVec);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void ColorEditor::onComponentChanged() {
- if (updatingFromValue_) {
- return;
- }
-
- glm::vec4 oldValue = value_;
-
- try {
- value_.r = std::any_cast<f32>(rEditor_->getValue());
- value_.g = std::any_cast<f32>(gEditor_->getValue());
- value_.b = std::any_cast<f32>(bEditor_->getValue());
- value_.a = std::any_cast<f32>(aEditor_->getValue());
-
- if (colorPreview_) {
- colorPreview_->setBackgroundColor(value_);
- }
-
- if (oldValue != value_) {
- notifyValueChanged(oldValue, value_);
- }
- } catch (const std::bad_any_cast&) {
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/ColorEditor.hpp b/src/esengine/editor/property/editors/ColorEditor.hpp
deleted file mode 100644
index 8c9b7326d..000000000
--- a/src/esengine/editor/property/editors/ColorEditor.hpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * @file ColorEditor.hpp
- * @brief Property editor for RGBA color values
- * @details Combines four FloatEditors (R, G, B, A) for editing glm::vec4.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "FloatEditor.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../ui/widgets/Panel.hpp"
-#include "../../../events/Connection.hpp"
-
-#include <glm/glm.hpp>
-
-namespace esengine::editor {
-
-// =============================================================================
-// ColorEditor Class
-// =============================================================================
-
-class ColorEditor : public PropertyEditor {
-public:
- explicit ColorEditor(const ui::WidgetId& id, const std::string& propertyName);
- ~ColorEditor() override = default;
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- void onComponentChanged();
-
- glm::vec4 value_{1.0f};
- bool updatingFromValue_ = false;
-
- ui::Label* mainLabel_ = nullptr;
- ui::Panel* colorPreview_ = nullptr;
- ui::Label* rLabel_ = nullptr;
- ui::Label* gLabel_ = nullptr;
- ui::Label* bLabel_ = nullptr;
- ui::Label* aLabel_ = nullptr;
-
- FloatEditor* rEditor_ = nullptr;
- FloatEditor* gEditor_ = nullptr;
- FloatEditor* bEditor_ = nullptr;
- FloatEditor* aEditor_ = nullptr;
- ConnectionHolder connections_;
-
- static constexpr f32 MAIN_LABEL_WIDTH = 60.0f;
- static constexpr f32 COLOR_PREVIEW_SIZE = 20.0f;
- static constexpr f32 COMPONENT_LABEL_WIDTH = 10.0f;
- static constexpr f32 FLOAT_EDITOR_WIDTH = 40.0f;
- static constexpr f32 SPACING = 4.0f;
- static constexpr f32 ROW_HEIGHT = 20.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/EnumEditor.cpp b/src/esengine/editor/property/editors/EnumEditor.cpp
deleted file mode 100644
index 5f350c559..000000000
--- a/src/esengine/editor/property/editors/EnumEditor.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/**
- * @file EnumEditor.cpp
- * @brief EnumEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "EnumEditor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-EnumEditor::EnumEditor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto labelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- labelWidget->setText(label_);
- labelWidget->setFontSize(12.0f);
- labelWidget_ = labelWidget.get();
- addChild(std::move(labelWidget));
- }
-
- auto dropdownWidget = makeUnique<ui::Dropdown>(ui::WidgetId(getId().path + "_dropdown"));
- dropdownWidget->setFontSize(12.0f);
- dropdown_ = dropdownWidget.get();
- addChild(std::move(dropdownWidget));
-
- connections_.add(sink(dropdown_->onSelectionChanged).connect(
- [this](i32 value) { onDropdownChanged(value); }
- ));
-}
-
-// =============================================================================
-// Options
-// =============================================================================
-
-void EnumEditor::addOption(const EnumOption& option) {
- options_.push_back(option);
- rebuildDropdown();
-}
-
-void EnumEditor::addOptions(const std::vector<EnumOption>& options) {
- options_.insert(options_.end(), options.begin(), options.end());
- rebuildDropdown();
-}
-
-void EnumEditor::clearOptions() {
- options_.clear();
- rebuildDropdown();
-}
-
-void EnumEditor::rebuildDropdown() {
- if (!dropdown_) return;
-
- dropdown_->clearItems();
- for (const auto& opt : options_) {
- dropdown_->addItem(ui::DropdownItem::create(opt.value, opt.label));
- }
- dropdown_->setSelectedValue(value_);
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void EnumEditor::setValue(const std::any& value) {
- try {
- i32 newValue = std::any_cast<i32>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
-
- updatingFromExternal_ = true;
- if (dropdown_) {
- dropdown_->setSelectedValue(value_);
- }
- updatingFromExternal_ = false;
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any EnumEditor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 EnumEditor::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- f32 width = 0.0f;
- f32 height = 24.0f;
-
- if (labelWidget_ && showLabel_) {
- width += LABEL_WIDTH + SPACING;
- }
-
- f32 dropdownWidth = availableWidth - width;
- if (dropdownWidth < DROPDOWN_WIDTH) {
- dropdownWidth = DROPDOWN_WIDTH;
- }
- width += dropdownWidth;
-
- return glm::vec2(width, height);
-}
-
-void EnumEditor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
- f32 remainingWidth = bounds.width;
-
- if (labelWidget_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, LABEL_WIDTH, bounds.height};
- labelWidget_->layout(labelBounds);
- x += LABEL_WIDTH + SPACING;
- remainingWidth -= LABEL_WIDTH + SPACING;
- }
-
- if (dropdown_) {
- ui::Rect dropdownBounds{x, bounds.y, remainingWidth, bounds.height};
- dropdown_->layout(dropdownBounds);
- }
-}
-
-void EnumEditor::render(ui::UIBatchRenderer& renderer) {
- constexpr glm::vec4 labelColor{0.686f, 0.686f, 0.686f, 1.0f};
-
- if (labelWidget_ && showLabel_) {
- labelWidget_->setColor(labelColor);
- labelWidget_->renderTree(renderer);
- }
-
- if (dropdown_) {
- dropdown_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> EnumEditor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- i32 oldInt = std::any_cast<i32>(oldValue);
- i32 newInt = std::any_cast<i32>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newInt]() {
- setValue(newInt);
- return CommandResult::Success;
- },
- [this, oldInt]() {
- setValue(oldInt);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void EnumEditor::onDropdownChanged(i32 value) {
- if (updatingFromExternal_) {
- return;
- }
-
- i32 oldValue = value_;
- if (oldValue != value) {
- value_ = value;
- notifyValueChanged(oldValue, value);
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/EnumEditor.hpp b/src/esengine/editor/property/editors/EnumEditor.hpp
deleted file mode 100644
index 5b9025ef2..000000000
--- a/src/esengine/editor/property/editors/EnumEditor.hpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * @file EnumEditor.hpp
- * @brief Property editor for enum values using dropdown
- * @details A dropdown-based editor for selecting from a list of enum options.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "../../../ui/widgets/Dropdown.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-#include <vector>
-
-namespace esengine::editor {
-
-// =============================================================================
-// EnumOption
-// =============================================================================
-
-struct EnumOption {
- i32 value = 0;
- std::string label;
-
- static EnumOption create(i32 value, const std::string& label) {
- return EnumOption{value, label};
- }
-};
-
-// =============================================================================
-// EnumEditor Class
-// =============================================================================
-
-/**
- * @brief Property editor for enum values
- *
- * @details Displays a dropdown with labeled options for enum selection.
- * Uses i32 values internally to support any enum type.
- *
- * @code
- * auto editor = makeUnique<EnumEditor>(WidgetId("projType"), "Projection Type");
- * editor->addOption(EnumOption::create(0, "Perspective"));
- * editor->addOption(EnumOption::create(1, "Orthographic"));
- * editor->setValue(static_cast<i32>(camera.projectionType));
- * @endcode
- */
-class EnumEditor : public PropertyEditor {
-public:
- static constexpr f32 LABEL_WIDTH = 80.0f;
- static constexpr f32 DROPDOWN_WIDTH = 100.0f;
- static constexpr f32 SPACING = 8.0f;
-
- EnumEditor(const ui::WidgetId& id, const std::string& propertyName);
-
- // =========================================================================
- // Options
- // =========================================================================
-
- void addOption(const EnumOption& option);
- void addOptions(const std::vector<EnumOption>& options);
- void clearOptions();
-
- const std::vector<EnumOption>& getOptions() const { return options_; }
-
- // =========================================================================
- // PropertyEditor Interface
- // =========================================================================
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- void onDropdownChanged(i32 value);
- void rebuildDropdown();
-
- i32 value_ = 0;
- std::vector<EnumOption> options_;
-
- ui::Label* labelWidget_ = nullptr;
- ui::Dropdown* dropdown_ = nullptr;
-
- ConnectionHolder connections_;
-
- bool updatingFromExternal_ = false;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/FloatEditor.cpp b/src/esengine/editor/property/editors/FloatEditor.cpp
deleted file mode 100644
index 30b81dd03..000000000
--- a/src/esengine/editor/property/editors/FloatEditor.cpp
+++ /dev/null
@@ -1,291 +0,0 @@
-/**
- * @file FloatEditor.cpp
- * @brief FloatEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "FloatEditor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-#include <sstream>
-#include <iomanip>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-FloatEditor::FloatEditor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto labelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- labelWidget->setText(label_);
- labelWidget->setFontSize(12.0f);
- labelWidget_ = labelWidget.get();
- addChild(std::move(labelWidget));
- }
-
- auto textField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + "_text"));
- textField->setWidth(ui::SizeValue::px(TEXTFIELD_WIDTH));
- textField_ = textField.get();
- addChild(std::move(textField));
-
- connections_.add(sink(textField_->onTextChanged).connect(
- [this](const std::string& text) { onTextChanged(text); }
- ));
-
- updateTextFromValue();
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void FloatEditor::setValue(const std::any& value) {
- try {
- f32 newValue = std::any_cast<f32>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
- updateTextFromValue();
- updateSliderFromValue();
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any FloatEditor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Range Configuration
-// =============================================================================
-
-void FloatEditor::setRange(f32 min, f32 max) {
- min_ = min;
- max_ = max;
-
- if (slider_) {
- slider_->setRange(min_, max_);
- }
-}
-
-void FloatEditor::setStep(f32 step) {
- step_ = step;
-
- if (slider_) {
- slider_->setStep(step_);
- }
-}
-
-// =============================================================================
-// Display Options
-// =============================================================================
-
-void FloatEditor::setShowSlider(bool show) {
- if (showSlider_ == show) {
- return;
- }
-
- showSlider_ = show;
-
- if (showSlider_ && !slider_) {
- auto sliderWidget = makeUnique<ui::Slider>(
- ui::WidgetId(getId().path + "_slider"),
- ui::SliderOrientation::Horizontal
- );
- sliderWidget->setRange(min_, max_);
- sliderWidget->setStep(step_);
- slider_ = sliderWidget.get();
- addChild(std::move(sliderWidget));
-
- connections_.add(sink(slider_->onValueChanged).connect(
- [this](f32 value) { onSliderChanged(value); }
- ));
-
- updateSliderFromValue();
- } else if (!showSlider_ && slider_) {
- removeChild(slider_);
- slider_ = nullptr;
- }
-
- invalidateLayout();
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 FloatEditor::measure(f32 availableWidth, f32 availableHeight) {
- f32 width = 0.0f;
- f32 height = 20.0f;
-
- if (labelWidget_ && showLabel_) {
- width += LABEL_WIDTH + SPACING;
- }
-
- width += TEXTFIELD_WIDTH;
-
- if (slider_ && showSlider_) {
- width += SPACING;
- f32 sliderWidth = availableWidth - width;
- if (sliderWidth > 100.0f) {
- width += sliderWidth;
- }
- }
-
- const ui::SizeConstraints& constraints = getConstraints();
- width = glm::clamp(width, constraints.minWidth, constraints.maxWidth);
- height = glm::clamp(height, constraints.minHeight, constraints.maxHeight);
-
- return glm::vec2(width, height);
-}
-
-void FloatEditor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
- f32 remainingWidth = bounds.width;
-
- if (labelWidget_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, LABEL_WIDTH, bounds.height};
- labelWidget_->layout(labelBounds);
- x += LABEL_WIDTH + SPACING;
- remainingWidth -= LABEL_WIDTH + SPACING;
- }
-
- if (textField_) {
- f32 textFieldWidth = remainingWidth;
- if (slider_ && showSlider_) {
- textFieldWidth = TEXTFIELD_WIDTH;
- }
- ui::Rect textBounds{x, bounds.y, textFieldWidth, bounds.height};
- textField_->layout(textBounds);
- x += textFieldWidth;
- }
-
- if (slider_ && showSlider_) {
- x += SPACING;
- f32 sliderWidth = bounds.x + bounds.width - x;
- ui::Rect sliderBounds{x, bounds.y, sliderWidth, bounds.height};
- slider_->layout(sliderBounds);
- }
-}
-
-void FloatEditor::render(ui::UIBatchRenderer& renderer) {
- constexpr glm::vec4 labelColor{0.686f, 0.686f, 0.686f, 1.0f};
-
- if (labelWidget_ && showLabel_) {
- labelWidget_->setColor(labelColor);
- labelWidget_->renderTree(renderer);
- }
-
- if (textField_) {
- textField_->renderTree(renderer);
- }
-
- if (slider_ && showSlider_) {
- slider_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> FloatEditor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- f32 oldFloat = std::any_cast<f32>(oldValue);
- f32 newFloat = std::any_cast<f32>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newFloat]() {
- setValue(newFloat);
- return CommandResult::Success;
- },
- [this, oldFloat]() {
- setValue(oldFloat);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void FloatEditor::onTextChanged(const std::string& text) {
- if (updatingFromSlider_) {
- return;
- }
-
- updatingFromText_ = true;
-
- try {
- f32 oldValue = value_;
- f32 newValue = std::stof(text);
-
- if (oldValue != newValue) {
- value_ = newValue;
- updateSliderFromValue();
- notifyValueChanged(oldValue, newValue);
- }
- } catch (const std::invalid_argument&) {
- } catch (const std::out_of_range&) {
- }
-
- updatingFromText_ = false;
-}
-
-void FloatEditor::onSliderChanged(f32 value) {
- if (updatingFromText_) {
- return;
- }
-
- updatingFromSlider_ = true;
-
- f32 oldValue = value_;
- if (oldValue != value) {
- value_ = value;
- updateTextFromValue();
- notifyValueChanged(oldValue, value);
- }
-
- updatingFromSlider_ = false;
-}
-
-void FloatEditor::updateTextFromValue() {
- if (updatingFromText_ || !textField_) {
- return;
- }
-
- std::ostringstream oss;
- oss << std::fixed << std::setprecision(2) << value_;
- textField_->setText(oss.str());
-}
-
-void FloatEditor::updateSliderFromValue() {
- if (updatingFromSlider_ || !slider_) {
- return;
- }
-
- slider_->setValue(value_);
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/FloatEditor.hpp b/src/esengine/editor/property/editors/FloatEditor.hpp
deleted file mode 100644
index 4cb2a3ca0..000000000
--- a/src/esengine/editor/property/editors/FloatEditor.hpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * @file FloatEditor.hpp
- * @brief Property editor for floating-point values
- * @details Combines a TextField for precise input with an optional Slider
- * for visual adjustment.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "../../../ui/widgets/TextField.hpp"
-#include "../../../ui/widgets/Slider.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// FloatEditor Class
-// =============================================================================
-
-/**
- * @brief Property editor for f32 values
- *
- * @details Renders a label (optional), text field, and optional slider.
- * Creates PropertyCommand<f32> for undo/redo support.
- *
- * @code
- * auto editor = makeUnique<FloatEditor>(WidgetId("speed"), "Speed");
- * editor->setValue(5.0f);
- * editor->setRange(0.0f, 100.0f);
- * editor->setShowSlider(true);
- * editor->onValueChanged.connect([](const std::any& value) {
- * f32 speed = std::any_cast<f32>(value);
- * ES_LOG_INFO("Speed: {}", speed);
- * });
- * @endcode
- */
-class FloatEditor : public PropertyEditor {
-public:
- /**
- * @brief Constructs a float editor
- * @param id Unique widget identifier
- * @param propertyName Name of the property being edited
- */
- explicit FloatEditor(const ui::WidgetId& id, const std::string& propertyName);
-
- ~FloatEditor() override = default;
-
- // =========================================================================
- // PropertyEditor Interface
- // =========================================================================
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- // =========================================================================
- // Range Configuration
- // =========================================================================
-
- /**
- * @brief Sets the value range for the slider
- * @param min Minimum value
- * @param max Maximum value
- */
- void setRange(f32 min, f32 max);
-
- /**
- * @brief Gets the minimum value
- * @return Minimum value
- */
- f32 getMin() const { return min_; }
-
- /**
- * @brief Gets the maximum value
- * @return Maximum value
- */
- f32 getMax() const { return max_; }
-
- /**
- * @brief Sets the step size for the slider
- * @param step Step size
- */
- void setStep(f32 step);
-
- /**
- * @brief Gets the step size
- * @return Step size
- */
- f32 getStep() const { return step_; }
-
- // =========================================================================
- // Display Options
- // =========================================================================
-
- /**
- * @brief Sets whether to show the slider
- * @param show True to show slider
- */
- void setShowSlider(bool show);
-
- /**
- * @brief Gets whether the slider is shown
- * @return True if slider is shown
- */
- bool getShowSlider() const { return showSlider_; }
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- void onTextChanged(const std::string& text);
- void onSliderChanged(f32 value);
-
- void updateTextFromValue();
- void updateSliderFromValue();
-
- f32 value_ = 0.0f;
- f32 min_ = 0.0f;
- f32 max_ = 100.0f;
- f32 step_ = 1.0f;
-
- bool showSlider_ = false;
- bool updatingFromText_ = false;
- bool updatingFromSlider_ = false;
-
- ui::Label* labelWidget_ = nullptr;
- ui::TextField* textField_ = nullptr;
- ui::Slider* slider_ = nullptr;
- ConnectionHolder connections_;
-
- static constexpr f32 LABEL_WIDTH = 60.0f;
- static constexpr f32 TEXTFIELD_WIDTH = 80.0f;
- static constexpr f32 SPACING = 8.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/IntEditor.cpp b/src/esengine/editor/property/editors/IntEditor.cpp
deleted file mode 100644
index f1850deaa..000000000
--- a/src/esengine/editor/property/editors/IntEditor.cpp
+++ /dev/null
@@ -1,275 +0,0 @@
-/**
- * @file IntEditor.cpp
- * @brief IntEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "IntEditor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-#include <sstream>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-IntEditor::IntEditor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto labelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- labelWidget->setText(label_);
- labelWidget->setFontSize(12.0f);
- labelWidget_ = labelWidget.get();
- addChild(std::move(labelWidget));
- }
-
- auto textField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + "_text"));
- textField->setWidth(ui::SizeValue::px(TEXTFIELD_WIDTH));
- textField_ = textField.get();
- addChild(std::move(textField));
-
- connections_.add(sink(textField_->onTextChanged).connect(
- [this](const std::string& text) { onTextChanged(text); }
- ));
-
- updateTextFromValue();
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void IntEditor::setValue(const std::any& value) {
- try {
- i32 newValue = std::any_cast<i32>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
- updateTextFromValue();
- updateSliderFromValue();
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any IntEditor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Range Configuration
-// =============================================================================
-
-void IntEditor::setRange(i32 min, i32 max) {
- min_ = min;
- max_ = max;
-
- if (slider_) {
- slider_->setRange(static_cast<f32>(min_), static_cast<f32>(max_));
- }
-}
-
-void IntEditor::setShowSlider(bool show) {
- if (showSlider_ == show) {
- return;
- }
-
- showSlider_ = show;
-
- if (showSlider_ && !slider_) {
- auto sliderWidget = makeUnique<ui::Slider>(
- ui::WidgetId(getId().path + "_slider"),
- ui::SliderOrientation::Horizontal
- );
- sliderWidget->setRange(static_cast<f32>(min_), static_cast<f32>(max_));
- sliderWidget->setStep(1.0f);
- slider_ = sliderWidget.get();
- addChild(std::move(sliderWidget));
-
- connections_.add(sink(slider_->onValueChanged).connect(
- [this](f32 value) { onSliderChanged(value); }
- ));
-
- updateSliderFromValue();
- } else if (!showSlider_ && slider_) {
- removeChild(slider_);
- slider_ = nullptr;
- }
-
- invalidateLayout();
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 IntEditor::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- f32 width = 0.0f;
- f32 height = 20.0f;
-
- if (labelWidget_ && showLabel_) {
- width += LABEL_WIDTH + SPACING;
- }
-
- width += TEXTFIELD_WIDTH;
-
- if (slider_ && showSlider_) {
- width += SPACING;
- f32 sliderWidth = availableWidth - width;
- if (sliderWidth > 60.0f) {
- width += sliderWidth;
- }
- }
-
- return glm::vec2(width, height);
-}
-
-void IntEditor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
- f32 remainingWidth = bounds.width;
-
- if (labelWidget_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, LABEL_WIDTH, bounds.height};
- labelWidget_->layout(labelBounds);
- x += LABEL_WIDTH + SPACING;
- remainingWidth -= LABEL_WIDTH + SPACING;
- }
-
- if (textField_) {
- f32 textFieldWidth = remainingWidth;
- if (slider_ && showSlider_) {
- textFieldWidth = TEXTFIELD_WIDTH;
- }
- ui::Rect textBounds{x, bounds.y, textFieldWidth, bounds.height};
- textField_->layout(textBounds);
- x += textFieldWidth;
- }
-
- if (slider_ && showSlider_) {
- x += SPACING;
- f32 sliderWidth = bounds.x + bounds.width - x;
- ui::Rect sliderBounds{x, bounds.y, sliderWidth, bounds.height};
- slider_->layout(sliderBounds);
- }
-}
-
-void IntEditor::render(ui::UIBatchRenderer& renderer) {
- constexpr glm::vec4 labelColor{0.686f, 0.686f, 0.686f, 1.0f};
-
- if (labelWidget_ && showLabel_) {
- labelWidget_->setColor(labelColor);
- labelWidget_->renderTree(renderer);
- }
-
- if (textField_) {
- textField_->renderTree(renderer);
- }
-
- if (slider_ && showSlider_) {
- slider_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> IntEditor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- i32 oldInt = std::any_cast<i32>(oldValue);
- i32 newInt = std::any_cast<i32>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newInt]() {
- setValue(newInt);
- return CommandResult::Success;
- },
- [this, oldInt]() {
- setValue(oldInt);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void IntEditor::onTextChanged(const std::string& text) {
- if (updatingFromSlider_) {
- return;
- }
-
- updatingFromText_ = true;
-
- try {
- i32 oldValue = value_;
- i32 newValue = std::stoi(text);
-
- if (oldValue != newValue) {
- value_ = newValue;
- updateSliderFromValue();
- notifyValueChanged(oldValue, newValue);
- }
- } catch (const std::invalid_argument&) {
- } catch (const std::out_of_range&) {
- }
-
- updatingFromText_ = false;
-}
-
-void IntEditor::onSliderChanged(f32 value) {
- if (updatingFromText_) {
- return;
- }
-
- updatingFromSlider_ = true;
-
- i32 oldValue = value_;
- i32 newValue = static_cast<i32>(value);
- if (oldValue != newValue) {
- value_ = newValue;
- updateTextFromValue();
- notifyValueChanged(oldValue, newValue);
- }
-
- updatingFromSlider_ = false;
-}
-
-void IntEditor::updateTextFromValue() {
- if (updatingFromText_ || !textField_) {
- return;
- }
-
- textField_->setText(std::to_string(value_));
-}
-
-void IntEditor::updateSliderFromValue() {
- if (updatingFromSlider_ || !slider_) {
- return;
- }
-
- slider_->setValue(static_cast<f32>(value_));
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/IntEditor.hpp b/src/esengine/editor/property/editors/IntEditor.hpp
deleted file mode 100644
index e3429b565..000000000
--- a/src/esengine/editor/property/editors/IntEditor.hpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * @file IntEditor.hpp
- * @brief Property editor for integer values
- * @details Uses a TextField for input with optional slider.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "../../../ui/widgets/TextField.hpp"
-#include "../../../ui/widgets/Slider.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// IntEditor Class
-// =============================================================================
-
-class IntEditor : public PropertyEditor {
-public:
- explicit IntEditor(const ui::WidgetId& id, const std::string& propertyName);
- ~IntEditor() override = default;
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- void setRange(i32 min, i32 max);
- i32 getMin() const { return min_; }
- i32 getMax() const { return max_; }
-
- void setShowSlider(bool show);
- bool getShowSlider() const { return showSlider_; }
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- void onTextChanged(const std::string& text);
- void onSliderChanged(f32 value);
- void updateTextFromValue();
- void updateSliderFromValue();
-
- i32 value_ = 0;
- i32 min_ = 0;
- i32 max_ = 100;
-
- bool showSlider_ = false;
- bool updatingFromText_ = false;
- bool updatingFromSlider_ = false;
-
- ui::Label* labelWidget_ = nullptr;
- ui::TextField* textField_ = nullptr;
- ui::Slider* slider_ = nullptr;
- ConnectionHolder connections_;
-
- static constexpr f32 LABEL_WIDTH = 60.0f;
- static constexpr f32 TEXTFIELD_WIDTH = 60.0f;
- static constexpr f32 SPACING = 8.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/StringEditor.cpp b/src/esengine/editor/property/editors/StringEditor.cpp
deleted file mode 100644
index 23f001822..000000000
--- a/src/esengine/editor/property/editors/StringEditor.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/**
- * @file StringEditor.cpp
- * @brief StringEditor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "StringEditor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-StringEditor::StringEditor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto labelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- labelWidget->setText(label_);
- labelWidget->setFontSize(12.0f);
- labelWidget_ = labelWidget.get();
- addChild(std::move(labelWidget));
- }
-
- auto textField = makeUnique<ui::TextField>(ui::WidgetId(getId().path + "_text"));
- textField_ = textField.get();
- addChild(std::move(textField));
-
- connections_.add(sink(textField_->onTextChanged).connect(
- [this](const std::string& text) { onTextChanged(text); }
- ));
-
- connections_.add(sink(textField_->onSubmit).connect(
- [this](const std::string& text) { onTextSubmit(text); }
- ));
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void StringEditor::setValue(const std::any& value) {
- try {
- std::string newValue = std::any_cast<std::string>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
- pendingValue_ = newValue;
- hasUncommittedChanges_ = false;
-
- updatingFromValue_ = true;
- if (textField_) {
- textField_->setText(value_);
- }
- updatingFromValue_ = false;
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any StringEditor::getValue() const {
- return value_;
-}
-
-void StringEditor::setPlaceholder(const std::string& placeholder) {
- if (textField_) {
- textField_->setPlaceholder(placeholder);
- }
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 StringEditor::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- f32 width = 0.0f;
- f32 height = 20.0f;
-
- if (labelWidget_ && showLabel_) {
- width += LABEL_WIDTH + SPACING;
- }
-
- f32 textFieldWidth = availableWidth - width;
- if (textFieldWidth < 80.0f) {
- textFieldWidth = 80.0f;
- }
- width += textFieldWidth;
-
- return glm::vec2(width, height);
-}
-
-void StringEditor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
-
- if (labelWidget_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, LABEL_WIDTH, bounds.height};
- labelWidget_->layout(labelBounds);
- x += LABEL_WIDTH + SPACING;
- }
-
- if (textField_) {
- f32 textFieldWidth = bounds.x + bounds.width - x;
- ui::Rect textBounds{x, bounds.y, textFieldWidth, bounds.height};
- textField_->layout(textBounds);
- }
-}
-
-void StringEditor::render(ui::UIBatchRenderer& renderer) {
- constexpr glm::vec4 labelColor{0.686f, 0.686f, 0.686f, 1.0f};
-
- if (labelWidget_ && showLabel_) {
- labelWidget_->setColor(labelColor);
- labelWidget_->renderTree(renderer);
- }
-
- if (textField_) {
- textField_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> StringEditor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- std::string oldStr = std::any_cast<std::string>(oldValue);
- std::string newStr = std::any_cast<std::string>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newStr]() {
- setValue(newStr);
- return CommandResult::Success;
- },
- [this, oldStr]() {
- setValue(oldStr);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void StringEditor::onTextChanged(const std::string& text) {
- if (updatingFromValue_) {
- return;
- }
-
- pendingValue_ = text;
- hasUncommittedChanges_ = (pendingValue_ != value_);
-}
-
-void StringEditor::onTextSubmit(const std::string& text) {
- if (updatingFromValue_) {
- return;
- }
-
- if (value_ != text) {
- std::string oldValue = value_;
- value_ = text;
- pendingValue_ = text;
- hasUncommittedChanges_ = false;
- notifyValueChanged(oldValue, value_);
- }
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/StringEditor.hpp b/src/esengine/editor/property/editors/StringEditor.hpp
deleted file mode 100644
index 3681e0c08..000000000
--- a/src/esengine/editor/property/editors/StringEditor.hpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * @file StringEditor.hpp
- * @brief Property editor for string values
- * @details Uses a TextField for text input.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "../../../ui/widgets/TextField.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// StringEditor Class
-// =============================================================================
-
-class StringEditor : public PropertyEditor {
-public:
- explicit StringEditor(const ui::WidgetId& id, const std::string& propertyName);
- ~StringEditor() override = default;
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- void setPlaceholder(const std::string& placeholder);
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- void onTextChanged(const std::string& text);
- void onTextSubmit(const std::string& text);
-
- std::string value_;
- std::string pendingValue_;
- bool updatingFromValue_ = false;
- bool hasUncommittedChanges_ = false;
-
- ui::Label* labelWidget_ = nullptr;
- ui::TextField* textField_ = nullptr;
- ConnectionHolder connections_;
-
- static constexpr f32 LABEL_WIDTH = 60.0f;
- static constexpr f32 SPACING = 8.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/Vector2Editor.cpp b/src/esengine/editor/property/editors/Vector2Editor.cpp
deleted file mode 100644
index 801cef56f..000000000
--- a/src/esengine/editor/property/editors/Vector2Editor.cpp
+++ /dev/null
@@ -1,310 +0,0 @@
-/**
- * @file Vector2Editor.cpp
- * @brief Vector2Editor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Vector2Editor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Vector2Editor::Vector2Editor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto mainLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- mainLabelWidget->setText(label_);
- mainLabelWidget->setFontSize(12.0f);
- mainLabel_ = mainLabelWidget.get();
- addChild(std::move(mainLabelWidget));
- }
-
- auto xEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_x"), "x");
- xEditorWidget->setShowLabel(false);
- xEditor_ = xEditorWidget.get();
- addChild(std::move(xEditorWidget));
-
- auto yEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_y"), "y");
- yEditorWidget->setShowLabel(false);
- yEditor_ = yEditorWidget.get();
- addChild(std::move(yEditorWidget));
-
- connections_.add(sink(xEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
- connections_.add(sink(yEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void Vector2Editor::setValue(const std::any& value) {
- try {
- glm::vec2 newValue = std::any_cast<glm::vec2>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
-
- updatingFromValue_ = true;
- xEditor_->setValue(value_.x);
- yEditor_->setValue(value_.y);
- updatingFromValue_ = false;
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any Vector2Editor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 Vector2Editor::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableWidth;
- (void)availableHeight;
-
- f32 width = 0.0f;
- f32 height = 22.0f;
-
- if (mainLabel_ && showLabel_) {
- width += MAIN_LABEL_WIDTH + SPACING;
- }
-
- f32 axisWidth = AXIS_BAR_WIDTH + AXIS_INPUT_WIDTH;
- width += axisWidth + SPACING + axisWidth;
-
- return glm::vec2(width, height);
-}
-
-void Vector2Editor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
- f32 axisWidth = AXIS_BAR_WIDTH + AXIS_INPUT_WIDTH;
-
- if (mainLabel_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, MAIN_LABEL_WIDTH, bounds.height};
- mainLabel_->layout(labelBounds);
- x += MAIN_LABEL_WIDTH + SPACING;
- }
-
- xAxisBounds_ = ui::Rect{x, bounds.y, AXIS_BAR_WIDTH, bounds.height};
- if (xEditor_) {
- ui::Rect editorBounds{x + AXIS_BAR_WIDTH, bounds.y, AXIS_INPUT_WIDTH, bounds.height};
- xEditor_->layout(editorBounds);
- }
- x += axisWidth + SPACING;
-
- yAxisBounds_ = ui::Rect{x, bounds.y, AXIS_BAR_WIDTH, bounds.height};
- if (yEditor_) {
- ui::Rect editorBounds{x + AXIS_BAR_WIDTH, bounds.y, AXIS_INPUT_WIDTH, bounds.height};
- yEditor_->layout(editorBounds);
- }
-}
-
-void Vector2Editor::render(ui::UIBatchRenderer& renderer) {
- const ui::Rect& bounds = getBounds();
-
- constexpr glm::vec4 labelColor{0.6f, 0.6f, 0.6f, 1.0f};
- constexpr glm::vec4 xBarColor{0.75f, 0.25f, 0.25f, 1.0f};
- constexpr glm::vec4 yBarColor{0.25f, 0.63f, 0.25f, 1.0f};
- constexpr glm::vec4 inputBg{0.1f, 0.1f, 0.1f, 1.0f};
- constexpr glm::vec4 inputBorder{0.27f, 0.27f, 0.27f, 1.0f};
-
- f32 axisWidth = AXIS_BAR_WIDTH + AXIS_INPUT_WIDTH;
-
- if (mainLabel_ && showLabel_) {
- mainLabel_->setColor(labelColor);
- mainLabel_->renderTree(renderer);
- }
-
- renderer.drawRoundedRect(
- ui::Rect{xAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBg,
- ui::CornerRadii::all(2.0f)
- );
- renderer.drawRoundedRectOutline(
- ui::Rect{xAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBorder,
- ui::CornerRadii::all(2.0f),
- 1.0f
- );
- renderer.drawRect(ui::Rect{xAxisBounds_.x, bounds.y + 1.0f, AXIS_BAR_WIDTH, bounds.height - 2.0f}, xBarColor);
- if (xEditor_) {
- xEditor_->renderTree(renderer);
- }
-
- renderer.drawRoundedRect(
- ui::Rect{yAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBg,
- ui::CornerRadii::all(2.0f)
- );
- renderer.drawRoundedRectOutline(
- ui::Rect{yAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBorder,
- ui::CornerRadii::all(2.0f),
- 1.0f
- );
- renderer.drawRect(ui::Rect{yAxisBounds_.x, bounds.y + 1.0f, AXIS_BAR_WIDTH, bounds.height - 2.0f}, yBarColor);
- if (yEditor_) {
- yEditor_->renderTree(renderer);
- }
-}
-
-bool Vector2Editor::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button != ui::MouseButton::Left) {
- return false;
- }
-
- i32 axis = getAxisAtPosition(event.x, event.y);
- if (axis < 0) {
- return false;
- }
-
- dragStartX_ = event.x;
-
- switch (axis) {
- case 0:
- draggingAxis_ = DragAxis::X;
- dragStartValue_ = value_.x;
- break;
- case 1:
- draggingAxis_ = DragAxis::Y;
- dragStartValue_ = value_.y;
- break;
- default:
- return false;
- }
-
- return true;
-}
-
-bool Vector2Editor::onMouseMove(const ui::MouseMoveEvent& event) {
- if (draggingAxis_ == DragAxis::None) {
- return false;
- }
-
- f32 delta = event.x - dragStartX_;
- f32 sensitivity = 0.1f;
-
- if (event.shift) {
- sensitivity = 0.01f;
- } else if (event.ctrl) {
- sensitivity = 1.0f;
- }
-
- f32 newValue = dragStartValue_ + delta * sensitivity;
- newValue = std::round(newValue * 1000.0f) / 1000.0f;
-
- glm::vec2 oldValue = value_;
-
- switch (draggingAxis_) {
- case DragAxis::X:
- value_.x = newValue;
- break;
- case DragAxis::Y:
- value_.y = newValue;
- break;
- default:
- break;
- }
-
- if (oldValue != value_) {
- updatingFromValue_ = true;
- xEditor_->setValue(value_.x);
- yEditor_->setValue(value_.y);
- updatingFromValue_ = false;
-
- notifyValueChanged(oldValue, value_);
- }
-
- return true;
-}
-
-bool Vector2Editor::onMouseUp(const ui::MouseButtonEvent& event) {
- if (event.button != ui::MouseButton::Left || draggingAxis_ == DragAxis::None) {
- return false;
- }
-
- draggingAxis_ = DragAxis::None;
- return true;
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> Vector2Editor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- glm::vec2 oldVec = std::any_cast<glm::vec2>(oldValue);
- glm::vec2 newVec = std::any_cast<glm::vec2>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newVec]() {
- setValue(newVec);
- return CommandResult::Success;
- },
- [this, oldVec]() {
- setValue(oldVec);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void Vector2Editor::onComponentChanged() {
- if (updatingFromValue_) {
- return;
- }
-
- glm::vec2 oldValue = value_;
-
- try {
- value_.x = std::any_cast<f32>(xEditor_->getValue());
- value_.y = std::any_cast<f32>(yEditor_->getValue());
-
- if (oldValue != value_) {
- notifyValueChanged(oldValue, value_);
- }
- } catch (const std::bad_any_cast&) {
- }
-}
-
-i32 Vector2Editor::getAxisAtPosition(f32 x, f32 y) const {
- if (xAxisBounds_.contains(x, y)) {
- return 0;
- }
- if (yAxisBounds_.contains(x, y)) {
- return 1;
- }
- return -1;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/Vector2Editor.hpp b/src/esengine/editor/property/editors/Vector2Editor.hpp
deleted file mode 100644
index b3c3de414..000000000
--- a/src/esengine/editor/property/editors/Vector2Editor.hpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * @file Vector2Editor.hpp
- * @brief Property editor for 2D vector values
- * @details Combines two FloatEditors (X, Y) for editing glm::vec2.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "FloatEditor.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-#include <glm/glm.hpp>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Vector2Editor Class
-// =============================================================================
-
-/**
- * @brief Property editor for glm::vec2 values
- *
- * @details Renders two axis inputs with colored bars and drag-to-adjust
- * support. Drag on axis bars to change values with different
- * sensitivities (Shift for fine, Ctrl for coarse).
- */
-class Vector2Editor : public PropertyEditor {
-public:
- explicit Vector2Editor(const ui::WidgetId& id, const std::string& propertyName);
- ~Vector2Editor() override = default;
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
- bool onMouseUp(const ui::MouseButtonEvent& event) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- enum class DragAxis { None, X, Y };
-
- void onComponentChanged();
- i32 getAxisAtPosition(f32 x, f32 y) const;
-
- glm::vec2 value_{0.0f};
- bool updatingFromValue_ = false;
-
- ui::Label* mainLabel_ = nullptr;
- FloatEditor* xEditor_ = nullptr;
- FloatEditor* yEditor_ = nullptr;
- ConnectionHolder connections_;
-
- DragAxis draggingAxis_ = DragAxis::None;
- f32 dragStartX_ = 0.0f;
- f32 dragStartValue_ = 0.0f;
-
- ui::Rect xAxisBounds_{};
- ui::Rect yAxisBounds_{};
-
- static constexpr f32 MAIN_LABEL_WIDTH = 60.0f;
- static constexpr f32 AXIS_BAR_WIDTH = 4.0f;
- static constexpr f32 AXIS_INPUT_WIDTH = 54.0f;
- static constexpr f32 SPACING = 2.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/Vector3Editor.cpp b/src/esengine/editor/property/editors/Vector3Editor.cpp
deleted file mode 100644
index 2998a2f40..000000000
--- a/src/esengine/editor/property/editors/Vector3Editor.cpp
+++ /dev/null
@@ -1,357 +0,0 @@
-/**
- * @file Vector3Editor.cpp
- * @brief Vector3Editor implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Vector3Editor.hpp"
-#include "../../command/PropertyCommand.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Vector3Editor::Vector3Editor(const ui::WidgetId& id, const std::string& propertyName)
- : PropertyEditor(id, propertyName) {
-
- if (showLabel_) {
- auto mainLabelWidget = makeUnique<ui::Label>(ui::WidgetId(getId().path + "_label"));
- mainLabelWidget->setText(label_);
- mainLabelWidget->setFontSize(12.0f);
- mainLabel_ = mainLabelWidget.get();
- addChild(std::move(mainLabelWidget));
- }
-
- auto xEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_x"), "x");
- xEditorWidget->setShowLabel(false);
- xEditor_ = xEditorWidget.get();
- addChild(std::move(xEditorWidget));
-
- auto yEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_y"), "y");
- yEditorWidget->setShowLabel(false);
- yEditor_ = yEditorWidget.get();
- addChild(std::move(yEditorWidget));
-
- auto zEditorWidget = makeUnique<FloatEditor>(ui::WidgetId(getId().path + "_z"), "z");
- zEditorWidget->setShowLabel(false);
- zEditor_ = zEditorWidget.get();
- addChild(std::move(zEditorWidget));
-
- connections_.add(sink(xEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
- connections_.add(sink(yEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
- connections_.add(sink(zEditor_->onValueChanged).connect(
- [this](const std::any&) { onComponentChanged(); }
- ));
-}
-
-// =============================================================================
-// PropertyEditor Interface
-// =============================================================================
-
-void Vector3Editor::setValue(const std::any& value) {
- try {
- glm::vec3 newValue = std::any_cast<glm::vec3>(value);
- if (value_ == newValue) {
- return;
- }
-
- value_ = newValue;
-
- updatingFromValue_ = true;
- xEditor_->setValue(value_.x);
- yEditor_->setValue(value_.y);
- zEditor_->setValue(value_.z);
- updatingFromValue_ = false;
- } catch (const std::bad_any_cast&) {
- }
-}
-
-std::any Vector3Editor::getValue() const {
- return value_;
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 Vector3Editor::measure(f32 availableWidth, f32 availableHeight) {
- f32 width = 0.0f;
- f32 height = 22.0f;
-
- if (mainLabel_ && showLabel_) {
- width += MAIN_LABEL_WIDTH + SPACING;
- }
-
- f32 axisWidth = AXIS_BAR_WIDTH + AXIS_INPUT_WIDTH;
- width += axisWidth + SPACING + axisWidth + SPACING + axisWidth;
-
- const ui::SizeConstraints& constraints = getConstraints();
- width = glm::clamp(width, constraints.minWidth, constraints.maxWidth);
- height = glm::clamp(height, constraints.minHeight, constraints.maxHeight);
-
- return glm::vec2(width, height);
-}
-
-void Vector3Editor::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
-
- f32 x = bounds.x;
- f32 axisWidth = AXIS_BAR_WIDTH + AXIS_INPUT_WIDTH;
-
- if (mainLabel_ && showLabel_) {
- ui::Rect labelBounds{x, bounds.y, MAIN_LABEL_WIDTH, bounds.height};
- mainLabel_->layout(labelBounds);
- x += MAIN_LABEL_WIDTH + SPACING;
- }
-
- xAxisBounds_ = ui::Rect{x, bounds.y, AXIS_BAR_WIDTH, bounds.height};
- if (xEditor_) {
- ui::Rect editorBounds{x + AXIS_BAR_WIDTH, bounds.y, AXIS_INPUT_WIDTH, bounds.height};
- xEditor_->layout(editorBounds);
- }
- x += axisWidth + SPACING;
-
- yAxisBounds_ = ui::Rect{x, bounds.y, AXIS_BAR_WIDTH, bounds.height};
- if (yEditor_) {
- ui::Rect editorBounds{x + AXIS_BAR_WIDTH, bounds.y, AXIS_INPUT_WIDTH, bounds.height};
- yEditor_->layout(editorBounds);
- }
- x += axisWidth + SPACING;
-
- zAxisBounds_ = ui::Rect{x, bounds.y, AXIS_BAR_WIDTH, bounds.height};
- if (zEditor_) {
- ui::Rect editorBounds{x + AXIS_BAR_WIDTH, bounds.y, AXIS_INPUT_WIDTH, bounds.height};
- zEditor_->layout(editorBounds);
- }
-}
-
-void Vector3Editor::render(ui::UIBatchRenderer& renderer) {
- const ui::Rect& bounds = getBounds();
-
- constexpr glm::vec4 labelColor{0.6f, 0.6f, 0.6f, 1.0f};
- constexpr glm::vec4 xBarColor{0.75f, 0.25f, 0.25f, 1.0f};
- constexpr glm::vec4 yBarColor{0.25f, 0.63f, 0.25f, 1.0f};
- constexpr glm::vec4 zBarColor{0.25f, 0.38f, 0.75f, 1.0f};
- constexpr glm::vec4 inputBg{0.1f, 0.1f, 0.1f, 1.0f};
- constexpr glm::vec4 inputBorder{0.27f, 0.27f, 0.27f, 1.0f};
-
- f32 axisWidth = AXIS_BAR_WIDTH + AXIS_INPUT_WIDTH;
-
- if (mainLabel_ && showLabel_) {
- mainLabel_->setColor(labelColor);
- mainLabel_->renderTree(renderer);
- }
-
- renderer.drawRoundedRect(
- ui::Rect{xAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBg,
- ui::CornerRadii::all(2.0f)
- );
- renderer.drawRoundedRectOutline(
- ui::Rect{xAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBorder,
- ui::CornerRadii::all(2.0f),
- 1.0f
- );
- renderer.drawRect(ui::Rect{xAxisBounds_.x, bounds.y + 1.0f, AXIS_BAR_WIDTH, bounds.height - 2.0f}, xBarColor);
- if (xEditor_) {
- xEditor_->renderTree(renderer);
- }
-
- renderer.drawRoundedRect(
- ui::Rect{yAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBg,
- ui::CornerRadii::all(2.0f)
- );
- renderer.drawRoundedRectOutline(
- ui::Rect{yAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBorder,
- ui::CornerRadii::all(2.0f),
- 1.0f
- );
- renderer.drawRect(ui::Rect{yAxisBounds_.x, bounds.y + 1.0f, AXIS_BAR_WIDTH, bounds.height - 2.0f}, yBarColor);
- if (yEditor_) {
- yEditor_->renderTree(renderer);
- }
-
- renderer.drawRoundedRect(
- ui::Rect{zAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBg,
- ui::CornerRadii::all(2.0f)
- );
- renderer.drawRoundedRectOutline(
- ui::Rect{zAxisBounds_.x, bounds.y, axisWidth, bounds.height},
- inputBorder,
- ui::CornerRadii::all(2.0f),
- 1.0f
- );
- renderer.drawRect(ui::Rect{zAxisBounds_.x, bounds.y + 1.0f, AXIS_BAR_WIDTH, bounds.height - 2.0f}, zBarColor);
- if (zEditor_) {
- zEditor_->renderTree(renderer);
- }
-}
-
-bool Vector3Editor::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button != ui::MouseButton::Left) {
- return false;
- }
-
- i32 axis = getAxisAtPosition(event.x, event.y);
- if (axis < 0) {
- return false;
- }
-
- valueBeforeDrag_ = value_;
- dragStartX_ = event.x;
-
- switch (axis) {
- case 0:
- draggingAxis_ = DragAxis::X;
- dragStartValue_ = value_.x;
- break;
- case 1:
- draggingAxis_ = DragAxis::Y;
- dragStartValue_ = value_.y;
- break;
- case 2:
- draggingAxis_ = DragAxis::Z;
- dragStartValue_ = value_.z;
- break;
- default:
- return false;
- }
-
- return true;
-}
-
-bool Vector3Editor::onMouseMove(const ui::MouseMoveEvent& event) {
- if (draggingAxis_ == DragAxis::None) {
- return false;
- }
-
- f32 delta = event.x - dragStartX_;
- f32 sensitivity = 0.1f;
-
- if (event.shift) {
- sensitivity = 0.01f;
- } else if (event.ctrl) {
- sensitivity = 1.0f;
- }
-
- f32 newValue = dragStartValue_ + delta * sensitivity;
- newValue = std::round(newValue * 1000.0f) / 1000.0f;
-
- glm::vec3 oldValue = value_;
-
- switch (draggingAxis_) {
- case DragAxis::X:
- value_.x = newValue;
- break;
- case DragAxis::Y:
- value_.y = newValue;
- break;
- case DragAxis::Z:
- value_.z = newValue;
- break;
- default:
- break;
- }
-
- if (oldValue != value_) {
- updatingFromValue_ = true;
- xEditor_->setValue(value_.x);
- yEditor_->setValue(value_.y);
- zEditor_->setValue(value_.z);
- updatingFromValue_ = false;
-
- notifyValueChanged(oldValue, value_);
- }
-
- return true;
-}
-
-bool Vector3Editor::onMouseUp(const ui::MouseButtonEvent& event) {
- if (event.button != ui::MouseButton::Left || draggingAxis_ == DragAxis::None) {
- return false;
- }
-
- draggingAxis_ = DragAxis::None;
- return true;
-}
-
-// =============================================================================
-// Protected Methods
-// =============================================================================
-
-Unique<Command> Vector3Editor::createCommand(const std::any& oldValue,
- const std::any& newValue) {
- try {
- glm::vec3 oldVec = std::any_cast<glm::vec3>(oldValue);
- glm::vec3 newVec = std::any_cast<glm::vec3>(newValue);
-
- return makeUnique<LambdaCommand>(
- "Modify " + propertyName_,
- [this, newVec]() {
- setValue(newVec);
- return CommandResult::Success;
- },
- [this, oldVec]() {
- setValue(oldVec);
- }
- );
- } catch (const std::bad_any_cast&) {
- return nullptr;
- }
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void Vector3Editor::onComponentChanged() {
- if (updatingFromValue_) {
- return;
- }
-
- glm::vec3 oldValue = value_;
-
- try {
- value_.x = std::any_cast<f32>(xEditor_->getValue());
- value_.y = std::any_cast<f32>(yEditor_->getValue());
- value_.z = std::any_cast<f32>(zEditor_->getValue());
-
- if (oldValue != value_) {
- notifyValueChanged(oldValue, value_);
- }
- } catch (const std::bad_any_cast&) {
- }
-}
-
-i32 Vector3Editor::getAxisAtPosition(f32 x, f32 y) const {
- if (xAxisBounds_.contains(x, y)) {
- return 0;
- }
- if (yAxisBounds_.contains(x, y)) {
- return 1;
- }
- if (zAxisBounds_.contains(x, y)) {
- return 2;
- }
- return -1;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/property/editors/Vector3Editor.hpp b/src/esengine/editor/property/editors/Vector3Editor.hpp
deleted file mode 100644
index 7eba4136e..000000000
--- a/src/esengine/editor/property/editors/Vector3Editor.hpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * @file Vector3Editor.hpp
- * @brief Property editor for 3D vector values
- * @details Combines three FloatEditors (X, Y, Z) for editing glm::vec3.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../PropertyEditor.hpp"
-#include "FloatEditor.hpp"
-#include "../../../ui/widgets/Label.hpp"
-#include "../../../events/Connection.hpp"
-
-#include <glm/glm.hpp>
-
-namespace esengine::editor {
-
-// =============================================================================
-// Vector3Editor Class
-// =============================================================================
-
-/**
- * @brief Property editor for glm::vec3 values
- *
- * @details Renders three axis inputs with colored bars and drag-to-adjust
- * support. Drag on axis bars to change values with different
- * sensitivities (Shift for fine, Ctrl for coarse).
- *
- * @code
- * auto editor = makeUnique<Vector3Editor>(WidgetId("position"), "Position");
- * editor->setValue(glm::vec3(1.0f, 2.0f, 3.0f));
- * editor->onValueChanged.connect([](const std::any& value) {
- * glm::vec3 pos = std::any_cast<glm::vec3>(value);
- * ES_LOG_INFO("Position: ({}, {}, {})", pos.x, pos.y, pos.z);
- * });
- * @endcode
- */
-class Vector3Editor : public PropertyEditor {
-public:
- /**
- * @brief Constructs a Vector3 editor
- * @param id Unique widget identifier
- * @param propertyName Name of the property being edited
- */
- explicit Vector3Editor(const ui::WidgetId& id, const std::string& propertyName);
-
- ~Vector3Editor() override = default;
-
- // =========================================================================
- // PropertyEditor Interface
- // =========================================================================
-
- void setValue(const std::any& value) override;
- std::any getValue() const override;
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
- bool onMouseUp(const ui::MouseButtonEvent& event) override;
-
-protected:
- Unique<Command> createCommand(const std::any& oldValue,
- const std::any& newValue) override;
-
-private:
- enum class DragAxis { None, X, Y, Z };
-
- void onComponentChanged();
- i32 getAxisAtPosition(f32 x, f32 y) const;
-
- glm::vec3 value_{0.0f};
- bool updatingFromValue_ = false;
-
- ui::Label* mainLabel_ = nullptr;
- FloatEditor* xEditor_ = nullptr;
- FloatEditor* yEditor_ = nullptr;
- FloatEditor* zEditor_ = nullptr;
- ConnectionHolder connections_;
-
- DragAxis draggingAxis_ = DragAxis::None;
- f32 dragStartX_ = 0.0f;
- f32 dragStartValue_ = 0.0f;
- glm::vec3 valueBeforeDrag_{0.0f};
-
- ui::Rect xAxisBounds_{};
- ui::Rect yAxisBounds_{};
- ui::Rect zAxisBounds_{};
-
- static constexpr f32 MAIN_LABEL_WIDTH = 60.0f;
- static constexpr f32 AXIS_BAR_WIDTH = 4.0f;
- static constexpr f32 AXIS_INPUT_WIDTH = 54.0f;
- static constexpr f32 SPACING = 2.0f;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/scene/SceneSerializer.cpp b/src/esengine/editor/scene/SceneSerializer.cpp
deleted file mode 100644
index acbd64e40..000000000
--- a/src/esengine/editor/scene/SceneSerializer.cpp
+++ /dev/null
@@ -1,863 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 87b02ff1d..000000000
--- a/src/esengine/editor/scene/SceneSerializer.hpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 195bbf21e..000000000
--- a/src/esengine/editor/script/ScriptComponentRegistry.cpp
+++ /dev/null
@@ -1,461 +0,0 @@
-/**
- * @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
deleted file mode 100644
index 6c870d258..000000000
--- a/src/esengine/editor/script/ScriptComponentRegistry.hpp
+++ /dev/null
@@ -1,192 +0,0 @@
-/**
- * @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/ui/docking/DockArea.cpp b/src/esengine/editor/ui/docking/DockArea.cpp
deleted file mode 100644
index 91ae33dd3..000000000
--- a/src/esengine/editor/ui/docking/DockArea.cpp
+++ /dev/null
@@ -1,659 +0,0 @@
-/**
- * @file DockArea.cpp
- * @brief DockArea implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DockArea.hpp"
-#include "DockPanel.hpp"
-#include "DockTabBar.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../../events/Sink.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-DockArea::DockArea(const WidgetId& id)
- : Widget(id)
- , zoneDetector_(this) {}
-
-DockArea::~DockArea() = default;
-
-// =============================================================================
-// Tree Access
-// =============================================================================
-
-DockNode* DockArea::findNode(DockNodeId id) {
- if (!rootNode_) return nullptr;
- return rootNode_->findNode(id);
-}
-
-DockPanel* DockArea::findPanel(DockPanelId id) {
- if (!rootNode_) return nullptr;
-
- DockPanel* found = nullptr;
- rootNode_->forEachLeaf([&](DockNode& node) {
- if (!found) {
- found = node.findPanel(id);
- }
- });
- return found;
-}
-
-DockNode* DockArea::findNodeContainingPanel(DockPanelId panelId) {
- if (!rootNode_) return nullptr;
- return rootNode_->findNodeContainingPanel(panelId);
-}
-
-// =============================================================================
-// Panel Management
-// =============================================================================
-
-void DockArea::addPanel(Unique<DockPanel> panel, DockDropZone zone,
- DockNode* targetNode, f32 ratio) {
- if (!panel) return;
-
- if (!rootNode_) {
- rootNode_ = DockNode::createTabs(generateNodeId());
- setNodeArea(rootNode_.get());
- rootNode_->addPanel(std::move(panel));
- invalidateLayout();
- onLayoutChanged.publish();
- return;
- }
-
- if (!targetNode) {
- targetNode = rootNode_.get();
- }
-
- if (zone == DockDropZone::Center || zone == DockDropZone::None) {
- if (targetNode->isTabs()) {
- targetNode->addPanel(std::move(panel));
- } else {
- DockNode* leaf = nullptr;
- targetNode->forEachLeaf([&](DockNode& node) {
- if (!leaf) leaf = &node;
- });
- if (leaf) {
- leaf->addPanel(std::move(panel));
- }
- }
- } else if (isEdgeDropZone(zone)) {
- DockSplitDirection dir = dropZoneToSplitDirection(zone);
- bool insertFirst = dropZoneIsFirst(zone);
-
- DockNode* newTabsNode = splitNode(targetNode, dir, ratio, insertFirst);
- if (newTabsNode) {
- newTabsNode->addPanel(std::move(panel));
- }
- }
-
- invalidateLayout();
- onLayoutChanged.publish();
-}
-
-Unique<DockPanel> DockArea::removePanel(DockPanelId panelId) {
- DockNode* node = findNodeContainingPanel(panelId);
- if (!node) return nullptr;
-
- DockPanel* panel = node->findPanel(panelId);
- if (!panel) return nullptr;
-
- auto removed = node->removePanel(panel);
-
- if (node->isEmpty()) {
- tryMergeNode(node);
- }
-
- invalidateLayout();
- onLayoutChanged.publish();
- return removed;
-}
-
-void DockArea::movePanel(DockPanel* panel, const DockDropTarget& target) {
- if (!panel || target.zone == DockDropZone::None) return;
-
- DockNode* sourceNode = panel->getOwnerNode();
- if (!sourceNode) return;
-
- auto detachedPanel = sourceNode->removePanel(panel);
- if (!detachedPanel) return;
-
- if (target.zone == DockDropZone::Center) {
- if (target.targetNode) {
- if (target.targetNode->isTabs()) {
- target.targetNode->addPanel(std::move(detachedPanel));
- } else {
- DockNode* leaf = nullptr;
- target.targetNode->forEachLeaf([&](DockNode& node) {
- if (!leaf) leaf = &node;
- });
- if (leaf) {
- leaf->addPanel(std::move(detachedPanel));
- }
- }
- }
- } else if (isEdgeDropZone(target.zone)) {
- DockSplitDirection dir = dropZoneToSplitDirection(target.zone);
- bool insertFirst = dropZoneIsFirst(target.zone);
-
- DockNode* newNode = splitNode(target.targetNode, dir, target.splitRatio, insertFirst);
- if (newNode) {
- newNode->addPanel(std::move(detachedPanel));
- }
- }
-
- if (sourceNode->isEmpty()) {
- tryMergeNode(sourceNode);
- }
-
- invalidateLayout();
- onLayoutChanged.publish();
-}
-
-void DockArea::closePanel(DockPanelId panelId) {
- auto panel = removePanel(panelId);
- if (panel) {
- onPanelClosed.publish(panelId);
- }
-}
-
-std::vector<DockPanel*> DockArea::getAllPanels() const {
- std::vector<DockPanel*> result;
-
- if (rootNode_) {
- rootNode_->forEachLeaf([&](DockNode& node) {
- for (const auto& panel : node.getPanels()) {
- if (panel) {
- result.push_back(panel.get());
- }
- }
- });
- }
-
- return result;
-}
-
-// =============================================================================
-// Node Operations
-// =============================================================================
-
-DockNode* DockArea::splitNode(DockNode* node, DockSplitDirection direction,
- f32 ratio, bool insertFirst) {
- if (!node) return nullptr;
-
- auto newTabsNode = DockNode::createTabs(generateNodeId());
- DockNode* newTabsPtr = newTabsNode.get();
-
- if (node == rootNode_.get()) {
- auto newSplit = DockNode::createSplit(generateNodeId(), direction);
- newSplit->setSplitRatio(insertFirst ? ratio : (1.0f - ratio));
-
- if (insertFirst) {
- newSplit->setFirst(std::move(newTabsNode));
- newSplit->setSecond(std::move(rootNode_));
- } else {
- newSplit->setFirst(std::move(rootNode_));
- newSplit->setSecond(std::move(newTabsNode));
- }
-
- rootNode_ = std::move(newSplit);
- setNodeArea(rootNode_.get());
- } else {
- DockNode* parent = node->getParent();
- if (!parent || !parent->isSplit()) return nullptr;
-
- bool isFirst = (parent->getFirst() == node);
-
- Unique<DockNode> detached = isFirst ? parent->detachFirst() : parent->detachSecond();
-
- auto newSplit = DockNode::createSplit(generateNodeId(), direction);
- newSplit->setSplitRatio(insertFirst ? ratio : (1.0f - ratio));
-
- if (insertFirst) {
- newSplit->setFirst(std::move(newTabsNode));
- newSplit->setSecond(std::move(detached));
- } else {
- newSplit->setFirst(std::move(detached));
- newSplit->setSecond(std::move(newTabsNode));
- }
-
- if (isFirst) {
- parent->setFirst(std::move(newSplit));
- } else {
- parent->setSecond(std::move(newSplit));
- }
-
- setNodeArea(parent);
- }
-
- return newTabsPtr;
-}
-
-void DockArea::tryMergeNode(DockNode* node) {
- if (!node || !node->isEmpty()) return;
-
- DockNode* parent = node->getParent();
- if (!parent || !parent->isSplit()) {
- if (node == rootNode_.get() && node->isEmpty()) {
- rootNode_.reset();
- }
- return;
- }
-
- bool isFirst = (parent->getFirst() == node);
- DockNode* sibling = isFirst ? parent->getSecond() : parent->getFirst();
-
- if (!sibling) return;
-
- Unique<DockNode> siblingOwned = isFirst ? parent->detachSecond() : parent->detachFirst();
-
- DockNode* grandparent = parent->getParent();
- if (grandparent && grandparent->isSplit()) {
- bool parentIsFirst = (grandparent->getFirst() == parent);
- if (parentIsFirst) {
- grandparent->setFirst(std::move(siblingOwned));
- } else {
- grandparent->setSecond(std::move(siblingOwned));
- }
- } else if (parent == rootNode_.get()) {
- rootNode_ = std::move(siblingOwned);
- if (rootNode_) {
- rootNode_->parent_ = nullptr;
- setNodeArea(rootNode_.get());
- }
- }
-
- tabBarConnections_.erase(node->getId());
- tabBars_.erase(node->getId());
- tabBarConnections_.erase(parent->getId());
- tabBars_.erase(parent->getId());
-}
-
-// =============================================================================
-// Drag and Drop
-// =============================================================================
-
-void DockArea::beginPanelDrag(DockPanel* panel, const glm::vec2& startPos) {
- zoneDetector_.beginDrag(panel, startPos);
-}
-
-// =============================================================================
-// Widget Overrides
-// =============================================================================
-
-glm::vec2 DockArea::measure(f32 availableWidth, f32 availableHeight) {
- return {availableWidth, availableHeight};
-}
-
-void DockArea::layoutChildren(const Rect& contentBounds) {
- (void)contentBounds;
-
- if (rootNode_) {
- rootNode_->setBounds(getBounds());
- rootNode_->layout(splitterThickness_, tabBarHeight_);
-
- UIContext* ctx = getContext();
- rootNode_->forEachLeaf([ctx](DockNode& node) {
- for (const auto& panel : node.getPanels()) {
- if (panel && panel->getContext() != ctx) {
- panel->setContext(ctx);
- }
- }
- });
- }
-}
-
-void DockArea::render(UIBatchRenderer& renderer) {
- if (!rootNode_) {
- return;
- }
-
- renderNode(renderer, rootNode_.get());
-
- zoneDetector_.render(renderer);
-}
-
-Widget* DockArea::hitTest(f32 x, f32 y) {
- if (!containsPoint(x, y)) {
- return nullptr;
- }
-
- if (hitTestSplitter(x, y)) {
- return this;
- }
-
- if (rootNode_) {
- DockNode* leafNode = rootNode_->findLeafAt(x, y);
- if (leafNode) {
- Rect tabBarBounds{
- leafNode->getBounds().x,
- leafNode->getBounds().y,
- leafNode->getBounds().width,
- tabBarHeight_
- };
- if (tabBarBounds.contains({x, y})) {
- DockTabBar* tabBar = getOrCreateTabBar(leafNode);
- if (tabBar) {
- return tabBar;
- }
- }
-
- DockPanel* activePanel = leafNode->getActivePanel();
- if (activePanel) {
- Widget* hit = activePanel->hitTest(x, y);
- if (hit) {
- return hit;
- }
- }
- }
- }
-
- return this;
-}
-
-void DockArea::renderNode(UIBatchRenderer& renderer, DockNode* node) {
- if (!node) return;
-
- if (node->isSplit()) {
- renderNode(renderer, node->getFirst());
- renderNode(renderer, node->getSecond());
- renderSplitter(renderer, node);
- } else {
- renderTabBar(renderer, node);
-
- DockPanel* activePanel = node->getActivePanel();
- if (activePanel) {
- if (activePanel->getContext() != getContext()) {
- activePanel->setContext(getContext());
- }
- activePanel->render(renderer);
- }
- }
-}
-
-void DockArea::renderSplitter(UIBatchRenderer& renderer, DockNode* node) {
- if (!node || !node->isSplit()) return;
-
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- Rect splitterBounds = node->getSplitterBounds(splitterThickness_);
- glm::vec2 mousePos = ctx->getMousePosition();
- bool hovered = (draggedSplitter_ == node) ||
- splitterBounds.contains({mousePos.x, mousePos.y});
-
- glm::vec4 color = hovered
- ? ctx->getTheme().colors.accent
- : ctx->getTheme().colors.border;
-
- renderer.drawRect(splitterBounds, color);
-}
-
-void DockArea::renderTabBar(UIBatchRenderer& renderer, DockNode* node) {
- if (!node || !node->isTabs()) return;
-
- const Rect& nodeBounds = node->getBounds();
- if (nodeBounds.width <= 0 || nodeBounds.height <= 0) {
- return;
- }
-
- DockTabBar* tabBar = getOrCreateTabBar(node);
- if (!tabBar) return;
-
- tabBar->setContext(getContext());
-
- Rect tabBarBounds{
- nodeBounds.x,
- nodeBounds.y,
- nodeBounds.width,
- tabBarHeight_
- };
-
- tabBar->layout(tabBarBounds);
- tabBar->render(renderer);
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool DockArea::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) return false;
-
- if (zoneDetector_.isDragging()) {
- return true;
- }
-
- DockNode* splitter = hitTestSplitter(event.x, event.y);
- if (splitter) {
- draggedSplitter_ = splitter;
- splitterDragStart_ = {event.x, event.y};
- splitterDragStartRatio_ = splitter->getSplitRatio();
- return true;
- }
-
- if (rootNode_) {
- rootNode_->forEachLeaf([&](DockNode& node) {
- DockTabBar* tabBar = getOrCreateTabBar(&node);
- if (tabBar) {
- Rect tabBarBounds{
- node.getBounds().x,
- node.getBounds().y,
- node.getBounds().width,
- tabBarHeight_
- };
- if (tabBarBounds.contains({event.x, event.y})) {
- tabBar->onMouseDown(event);
- }
- }
- });
- }
-
- return false;
-}
-
-bool DockArea::onMouseUp(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) return false;
-
- if (zoneDetector_.isDragging()) {
- DockPanel* panel = zoneDetector_.getDraggedPanel();
- DockDropTarget target = zoneDetector_.endDrag();
- if (panel && target.zone != DockDropZone::None) {
- movePanel(panel, target);
- }
- return true;
- }
-
- if (draggedSplitter_) {
- draggedSplitter_ = nullptr;
- return true;
- }
-
- if (rootNode_) {
- rootNode_->forEachLeaf([&](DockNode& node) {
- DockTabBar* tabBar = getOrCreateTabBar(&node);
- if (tabBar) {
- tabBar->onMouseUp(event);
- }
- });
- }
-
- return false;
-}
-
-bool DockArea::onMouseMove(const MouseMoveEvent& event) {
- lastMouseX_ = event.x;
- lastMouseY_ = event.y;
-
- if (zoneDetector_.isDragging()) {
- zoneDetector_.updateDrag({event.x, event.y});
- return true;
- }
-
- if (draggedSplitter_) {
- handleSplitterDrag(event.x, event.y);
- return true;
- }
-
- if (rootNode_) {
- rootNode_->forEachLeaf([&](DockNode& node) {
- DockTabBar* tabBar = getOrCreateTabBar(&node);
- if (tabBar) {
- tabBar->onMouseMove(event);
- }
- });
- }
-
- return false;
-}
-
-void DockArea::onStateChanged() {
- Widget::onStateChanged();
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-DockNode* DockArea::hitTestSplitter(f32 x, f32 y) {
- if (!rootNode_) return nullptr;
-
- DockNode* result = nullptr;
- rootNode_->forEachNode([&](DockNode& node) {
- if (!result && node.isSplit() && node.hitTestSplitter(x, y, splitterThickness_)) {
- result = &node;
- }
- });
- return result;
-}
-
-void DockArea::handleSplitterDrag(f32 x, f32 y) {
- if (!draggedSplitter_) return;
-
- const Rect& bounds = draggedSplitter_->getBounds();
- f32 newRatio;
-
- if (draggedSplitter_->getSplitDirection() == DockSplitDirection::Horizontal) {
- f32 relX = x - bounds.x;
- newRatio = relX / bounds.width;
-
- f32 availableWidth = bounds.width - splitterThickness_;
- f32 minFirst = getMinSizeForNode(draggedSplitter_->getFirst()).x;
- f32 minSecond = getMinSizeForNode(draggedSplitter_->getSecond()).x;
-
- f32 minRatio = minFirst / availableWidth;
- f32 maxRatio = 1.0f - (minSecond / availableWidth);
- newRatio = std::clamp(newRatio, minRatio, maxRatio);
- } else {
- f32 relY = y - bounds.y;
- newRatio = relY / bounds.height;
-
- f32 availableHeight = bounds.height - splitterThickness_;
- f32 minFirst = getMinSizeForNode(draggedSplitter_->getFirst()).y;
- f32 minSecond = getMinSizeForNode(draggedSplitter_->getSecond()).y;
-
- f32 minRatio = minFirst / availableHeight;
- f32 maxRatio = 1.0f - (minSecond / availableHeight);
- newRatio = std::clamp(newRatio, minRatio, maxRatio);
- }
-
- draggedSplitter_->setSplitRatio(newRatio);
- invalidateLayout();
-}
-
-glm::vec2 DockArea::getMinSizeForNode(DockNode* node) const {
- if (!node) return minPanelSize_;
-
- if (node->isTabs()) {
- glm::vec2 maxMin = minPanelSize_;
- for (const auto& panel : node->getPanels()) {
- if (panel) {
- const auto& constraints = panel->getConstraints();
- maxMin.x = std::max(maxMin.x, constraints.minWidth);
- maxMin.y = std::max(maxMin.y, constraints.minHeight);
- }
- }
- return maxMin;
- }
-
- if (node->isSplit()) {
- glm::vec2 firstMin = getMinSizeForNode(node->getFirst());
- glm::vec2 secondMin = getMinSizeForNode(node->getSecond());
-
- if (node->getSplitDirection() == DockSplitDirection::Horizontal) {
- return {firstMin.x + secondMin.x + splitterThickness_,
- std::max(firstMin.y, secondMin.y)};
- } else {
- return {std::max(firstMin.x, secondMin.x),
- firstMin.y + secondMin.y + splitterThickness_};
- }
- }
-
- return minPanelSize_;
-}
-
-void DockArea::setNodeArea(DockNode* node) {
- if (!node) return;
-
- node->area_ = this;
-
- if (node->getFirst()) {
- setNodeArea(node->getFirst());
- }
- if (node->getSecond()) {
- setNodeArea(node->getSecond());
- }
-}
-
-DockTabBar* DockArea::getOrCreateTabBar(DockNode* node) {
- if (!node || !node->isTabs()) return nullptr;
-
- auto it = tabBars_.find(node->getId());
- if (it != tabBars_.end()) {
- return it->second.get();
- }
-
- auto tabBar = makeUnique<DockTabBar>(
- WidgetId("dock.tabbar." + std::to_string(node->getId())),
- node
- );
-
- std::vector<Connection> connections;
-
- connections.push_back(sink(tabBar->onTabSelected).connect([this, node](i32 index) {
- node->setActiveTabIndex(index);
- DockPanel* panel = node->getActivePanel();
- if (panel) {
- onPanelActivated.publish(panel->getPanelId());
- }
- }));
-
- connections.push_back(sink(tabBar->onTabCloseRequested).connect([this](DockPanelId panelId) {
- closePanel(panelId);
- }));
-
- connections.push_back(sink(tabBar->onTabDragStart).connect([this](DockPanelId panelId, glm::vec2 pos) {
- DockPanel* panel = findPanel(panelId);
- if (panel) {
- beginPanelDrag(panel, pos);
- }
- }));
-
- DockTabBar* ptr = tabBar.get();
- DockNodeId nodeId = node->getId();
- tabBars_[nodeId] = std::move(tabBar);
- tabBarConnections_[nodeId] = std::move(connections);
- return ptr;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockArea.hpp b/src/esengine/editor/ui/docking/DockArea.hpp
deleted file mode 100644
index 367c65279..000000000
--- a/src/esengine/editor/ui/docking/DockArea.hpp
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * @file DockArea.hpp
- * @brief Main container widget for the docking system
- * @details Manages the dock tree, handles panel operations,
- * splitter dragging, and drag-drop coordination.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-#include "DockNode.hpp"
-#include "DockZone.hpp"
-#include "../../../ui/widgets/Widget.hpp"
-#include "../../../events/Signal.hpp"
-#include "../../../events/Connection.hpp"
-
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::ui {
-
-// Forward declarations
-class DockPanel;
-class DockTabBar;
-
-// =============================================================================
-// DockArea Class
-// =============================================================================
-
-/**
- * @brief Main container widget for dockable panels
- *
- * @details DockArea manages the entire docking tree structure including:
- * - Tree manipulation (splitting, merging, tabbing)
- * - Drag and drop operations
- * - Splitter dragging for resizing
- * - Layout calculation for all nodes
- *
- * @code
- * auto dockArea = makeUnique<DockArea>(WidgetId("editor.dock"));
- *
- * // Add panels
- * dockArea->addPanel(makeUnique<HierarchyPanel>(), DockDropZone::Left);
- * dockArea->addPanel(makeUnique<InspectorPanel>(), DockDropZone::Right);
- * dockArea->addPanel(makeUnique<ScenePanel>(), DockDropZone::Center);
- *
- * uiContext.setRoot(std::move(dockArea));
- * @endcode
- */
-class DockArea : public Widget {
-public:
- explicit DockArea(const WidgetId& id);
- ~DockArea() override;
-
- // =========================================================================
- // Tree Access
- // =========================================================================
-
- /** @brief Gets the root dock node */
- DockNode* getRootNode() const { return rootNode_.get(); }
-
- /** @brief Find a node by ID */
- DockNode* findNode(DockNodeId id);
-
- /** @brief Find a panel by ID */
- DockPanel* findPanel(DockPanelId id);
-
- /** @brief Find the node containing a panel */
- DockNode* findNodeContainingPanel(DockPanelId panelId);
-
- // =========================================================================
- // Panel Management
- // =========================================================================
-
- /**
- * @brief Add a panel to the dock area
- * @param panel Panel to add (ownership transferred)
- * @param zone Dock zone (Left, Right, Top, Bottom, Center)
- * @param targetNode Node to dock relative to (nullptr = root)
- * @param ratio Split ratio for edge docking
- */
- void addPanel(Unique<DockPanel> panel,
- DockDropZone zone = DockDropZone::Center,
- DockNode* targetNode = nullptr,
- f32 ratio = 0.3f);
-
- /**
- * @brief Remove a panel from the dock area
- * @param panelId ID of panel to remove
- * @return The removed panel
- */
- Unique<DockPanel> removePanel(DockPanelId panelId);
-
- /**
- * @brief Move a panel to a new location
- * @param panel Panel to move
- * @param target Drop target information
- */
- void movePanel(DockPanel* panel, const DockDropTarget& target);
-
- /**
- * @brief Close a panel
- * @param panelId ID of panel to close
- */
- void closePanel(DockPanelId panelId);
-
- /**
- * @brief Get all panels in the dock area
- */
- std::vector<DockPanel*> getAllPanels() const;
-
- // =========================================================================
- // Node Operations
- // =========================================================================
-
- /**
- * @brief Split a node to create space for docking
- * @param node Node to split
- * @param direction Split direction
- * @param ratio Split ratio
- * @param insertFirst Insert new node as first child
- * @return The new tabs node for adding panels
- */
- DockNode* splitNode(DockNode* node,
- DockSplitDirection direction,
- f32 ratio = 0.5f,
- bool insertFirst = false);
-
- /**
- * @brief Try to merge empty nodes up the tree
- * @param node Node to start checking from
- */
- void tryMergeNode(DockNode* node);
-
- // =========================================================================
- // ID Generation
- // =========================================================================
-
- /** @brief Generate a unique node ID */
- DockNodeId generateNodeId() { return nextNodeId_++; }
-
- // =========================================================================
- // Drag and Drop
- // =========================================================================
-
- /** @brief Get the zone detector for drag operations */
- DockZoneDetector& getZoneDetector() { return zoneDetector_; }
-
- /** @brief Check if a drag operation is in progress */
- bool isDragging() const { return zoneDetector_.isDragging(); }
-
- /**
- * @brief Start dragging a panel
- * @param panel Panel to drag
- * @param startPos Initial mouse position
- */
- void beginPanelDrag(DockPanel* panel, const glm::vec2& startPos);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Set minimum panel size */
- void setMinPanelSize(const glm::vec2& size) { minPanelSize_ = size; }
-
- /** @brief Get minimum panel size */
- glm::vec2 getMinPanelSize() const { return minPanelSize_; }
-
- /** @brief Set splitter thickness in pixels */
- void setSplitterThickness(f32 thickness) { splitterThickness_ = thickness; }
-
- /** @brief Get splitter thickness */
- f32 getSplitterThickness() const { return splitterThickness_; }
-
- /** @brief Set tab bar height */
- void setTabBarHeight(f32 height) { tabBarHeight_ = height; }
-
- /** @brief Get tab bar height */
- f32 getTabBarHeight() const { return tabBarHeight_; }
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /** @brief Emitted when a panel is closed */
- Signal<void(DockPanelId)> onPanelClosed;
-
- /** @brief Emitted when a panel is activated (selected) */
- Signal<void(DockPanelId)> onPanelActivated;
-
- /** @brief Emitted when the layout changes */
- Signal<void()> onLayoutChanged;
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
-
- Widget* hitTest(f32 x, f32 y) override;
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
-
-protected:
- void layoutChildren(const Rect& contentBounds) override;
- void onStateChanged() override;
-
-private:
- void layoutNode(DockNode* node);
- void renderNode(UIBatchRenderer& renderer, DockNode* node);
- void renderSplitter(UIBatchRenderer& renderer, DockNode* node);
- void renderTabBar(UIBatchRenderer& renderer, DockNode* node);
-
- DockNode* hitTestSplitter(f32 x, f32 y);
- void handleSplitterDrag(f32 x, f32 y);
- glm::vec2 getMinSizeForNode(DockNode* node) const;
-
- void setNodeArea(DockNode* node);
- void connectTabBarSignals(DockNode* node);
-
- DockTabBar* getOrCreateTabBar(DockNode* node);
-
- Unique<DockNode> rootNode_;
- DockNodeId nextNodeId_ = 1;
-
- DockZoneDetector zoneDetector_;
-
- std::unordered_map<DockNodeId, Unique<DockTabBar>> tabBars_;
- std::unordered_map<DockNodeId, std::vector<Connection>> tabBarConnections_;
-
- DockNode* draggedSplitter_ = nullptr;
- glm::vec2 splitterDragStart_{0.0f};
- f32 splitterDragStartRatio_ = 0.0f;
-
- glm::vec2 minPanelSize_{100.0f, 100.0f};
- f32 splitterThickness_ = 4.0f;
- f32 tabBarHeight_ = 24.0f;
-
- f32 lastMouseX_ = 0.0f;
- f32 lastMouseY_ = 0.0f;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockEvents.hpp b/src/esengine/editor/ui/docking/DockEvents.hpp
deleted file mode 100644
index 7d2a9adf8..000000000
--- a/src/esengine/editor/ui/docking/DockEvents.hpp
+++ /dev/null
@@ -1,181 +0,0 @@
-/**
- * @file DockEvents.hpp
- * @brief Event definitions for docking system
- * @details Defines event structures for dock panel operations,
- * layout changes, and drag-drop actions.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Panel Events
-// =============================================================================
-
-/**
- * @brief Emitted when a panel is closed
- */
-struct DockPanelClosedEvent {
- DockPanelId panelId;
-};
-
-/**
- * @brief Emitted when a panel is activated (selected)
- */
-struct DockPanelActivatedEvent {
- DockPanelId panelId;
-};
-
-/**
- * @brief Emitted when a panel's title changes
- */
-struct DockPanelTitleChangedEvent {
- DockPanelId panelId;
- std::string newTitle;
-};
-
-/**
- * @brief Emitted when a panel is added to the dock area
- */
-struct DockPanelAddedEvent {
- DockPanelId panelId;
- DockNodeId nodeId;
-};
-
-/**
- * @brief Emitted when a panel is removed from the dock area
- */
-struct DockPanelRemovedEvent {
- DockPanelId panelId;
-};
-
-// =============================================================================
-// Layout Events
-// =============================================================================
-
-/**
- * @brief Emitted when the dock layout changes
- */
-struct DockLayoutChangedEvent {
- // No data - just notification that layout changed
-};
-
-/**
- * @brief Emitted when a node is split
- */
-struct DockNodeSplitEvent {
- DockNodeId parentId;
- DockNodeId newNodeId;
- DockSplitDirection direction;
-};
-
-/**
- * @brief Emitted when nodes are merged
- */
-struct DockNodeMergedEvent {
- DockNodeId removedNodeId;
- DockNodeId remainingNodeId;
-};
-
-/**
- * @brief Emitted when a splitter ratio changes
- */
-struct DockSplitterChangedEvent {
- DockNodeId nodeId;
- f32 oldRatio;
- f32 newRatio;
-};
-
-// =============================================================================
-// Tab Events
-// =============================================================================
-
-/**
- * @brief Emitted when a tab is selected
- */
-struct DockTabSelectedEvent {
- DockNodeId nodeId;
- i32 tabIndex;
- DockPanelId panelId;
-};
-
-/**
- * @brief Emitted when tab order changes within a node
- */
-struct DockTabReorderedEvent {
- DockNodeId nodeId;
- i32 oldIndex;
- i32 newIndex;
-};
-
-// =============================================================================
-// Drag Events
-// =============================================================================
-
-/**
- * @brief Emitted when panel drag starts
- */
-struct DockDragStartEvent {
- DockPanelId panelId;
- glm::vec2 startPosition;
-};
-
-/**
- * @brief Emitted during panel drag
- */
-struct DockDragUpdateEvent {
- DockPanelId panelId;
- glm::vec2 currentPosition;
- DockDropZone hoveredZone;
- DockNodeId targetNodeId;
-};
-
-/**
- * @brief Emitted when panel drag ends
- */
-struct DockDragEndEvent {
- DockPanelId panelId;
- DockDropZone dropZone;
- DockNodeId targetNodeId;
- bool cancelled;
-};
-
-// =============================================================================
-// Floating Panel Events (for future floating window support)
-// =============================================================================
-
-/**
- * @brief Emitted when a panel becomes floating
- */
-struct DockPanelFloatEvent {
- DockPanelId panelId;
- glm::vec2 position;
- glm::vec2 size;
-};
-
-/**
- * @brief Emitted when a floating panel is docked
- */
-struct DockPanelDockedEvent {
- DockPanelId panelId;
- DockNodeId targetNodeId;
- DockDropZone dropZone;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockLayoutSerializer.cpp b/src/esengine/editor/ui/docking/DockLayoutSerializer.cpp
deleted file mode 100644
index 59fd6d23c..000000000
--- a/src/esengine/editor/ui/docking/DockLayoutSerializer.cpp
+++ /dev/null
@@ -1,343 +0,0 @@
-/**
- * @file DockLayoutSerializer.cpp
- * @brief DockLayoutSerializer implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DockLayoutSerializer.hpp"
-#include "DockArea.hpp"
-#include "DockNode.hpp"
-#include "DockPanel.hpp"
-#include "../../../core/Log.hpp"
-
-#include <sstream>
-#include <iomanip>
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// JSON Helper Functions
-// =============================================================================
-
-namespace {
-
-std::string escapeJsonString(const std::string& str) {
- std::ostringstream oss;
- for (char c : str) {
- switch (c) {
- case '"': oss << "\\\""; break;
- case '\\': oss << "\\\\"; break;
- case '\n': oss << "\\n"; break;
- case '\r': oss << "\\r"; break;
- case '\t': oss << "\\t"; break;
- default: oss << c; break;
- }
- }
- return oss.str();
-}
-
-void skipWhitespace(const std::string& json, usize& pos) {
- while (pos < json.size() && std::isspace(json[pos])) {
- ++pos;
- }
-}
-
-bool expectChar(const std::string& json, usize& pos, char c) {
- skipWhitespace(json, pos);
- if (pos < json.size() && json[pos] == c) {
- ++pos;
- return true;
- }
- return false;
-}
-
-std::string parseString(const std::string& json, usize& pos) {
- skipWhitespace(json, pos);
- if (pos >= json.size() || json[pos] != '"') return "";
- ++pos;
-
- std::string result;
- while (pos < json.size() && json[pos] != '"') {
- if (json[pos] == '\\' && pos + 1 < json.size()) {
- ++pos;
- switch (json[pos]) {
- case '"': result += '"'; break;
- case '\\': result += '\\'; break;
- case 'n': result += '\n'; break;
- case 'r': result += '\r'; break;
- case 't': result += '\t'; break;
- default: result += json[pos]; break;
- }
- } else {
- result += json[pos];
- }
- ++pos;
- }
- if (pos < json.size()) ++pos;
- return result;
-}
-
-f32 parseNumber(const std::string& json, usize& pos) {
- skipWhitespace(json, pos);
- usize start = pos;
- while (pos < json.size() && (std::isdigit(json[pos]) || json[pos] == '.' ||
- json[pos] == '-' || json[pos] == '+' ||
- json[pos] == 'e' || json[pos] == 'E')) {
- ++pos;
- }
- return std::stof(json.substr(start, pos - start));
-}
-
-i32 parseInt(const std::string& json, usize& pos) {
- skipWhitespace(json, pos);
- usize start = pos;
- if (pos < json.size() && json[pos] == '-') ++pos;
- while (pos < json.size() && std::isdigit(json[pos])) {
- ++pos;
- }
- return std::stoi(json.substr(start, pos - start));
-}
-
-} // namespace
-
-// =============================================================================
-// Serialization
-// =============================================================================
-
-std::string DockLayoutSerializer::serialize(const DockArea& area) const {
- DockLayoutData data = serializeToData(area);
- return toJson(data);
-}
-
-DockLayoutData DockLayoutSerializer::serializeToData(const DockArea& area) const {
- DockLayoutData data;
- data.version = 1;
-
- DockNode* root = area.getRootNode();
- if (!root) {
- data.rootNodeIndex = -1;
- return data;
- }
-
- std::vector<i32> nodeIndexMap;
- serializeNode(root, data, nodeIndexMap);
- data.rootNodeIndex = 0;
-
- return data;
-}
-
-void DockLayoutSerializer::serializeNode(const DockNode* node, DockLayoutData& data,
- std::vector<i32>& nodeIndexMap) const {
- if (!node) return;
-
- DockNodeData nodeData;
- nodeData.id = node->getId();
- nodeData.type = node->getType();
-
- if (node->isSplit()) {
- nodeData.splitDirection = node->getSplitDirection();
- nodeData.splitRatio = node->getSplitRatio();
-
- i32 currentIndex = static_cast<i32>(data.nodes.size());
- data.nodes.push_back(nodeData);
-
- if (node->getFirst()) {
- data.nodes[static_cast<usize>(currentIndex)].firstChildIndex =
- static_cast<i32>(data.nodes.size());
- serializeNode(node->getFirst(), data, nodeIndexMap);
- }
-
- if (node->getSecond()) {
- data.nodes[static_cast<usize>(currentIndex)].secondChildIndex =
- static_cast<i32>(data.nodes.size());
- serializeNode(node->getSecond(), data, nodeIndexMap);
- }
- } else {
- nodeData.activeTabIndex = node->getActiveTabIndex();
- for (const auto& panel : node->getPanels()) {
- if (panel) {
- nodeData.panelIds.push_back(panel->getPanelId());
- }
- }
- data.nodes.push_back(nodeData);
- }
-}
-
-// =============================================================================
-// Deserialization
-// =============================================================================
-
-bool DockLayoutSerializer::deserialize(DockArea& area, const std::string& json,
- const PanelFactory& factory) const {
- DockLayoutData data;
- if (!fromJson(json, data)) {
- ES_LOG_ERROR("Failed to parse dock layout JSON");
- return false;
- }
- return deserializeFromData(area, data, factory);
-}
-
-bool DockLayoutSerializer::deserializeFromData(DockArea& /*area*/, const DockLayoutData& data,
- const PanelFactory& /*factory*/) const {
- if (data.rootNodeIndex < 0 ||
- static_cast<usize>(data.rootNodeIndex) >= data.nodes.size()) {
- return true;
- }
-
- // TODO: Clear existing layout and rebuild from data
- // This requires access to DockArea internals or additional API
- ES_LOG_WARN("DockLayoutSerializer::deserializeFromData not fully implemented");
-
- return true;
-}
-
-DockNode* DockLayoutSerializer::deserializeNode(DockArea& /*area*/, const DockLayoutData& data,
- i32 nodeIndex,
- const PanelFactory& /*factory*/) const {
- if (nodeIndex < 0 || static_cast<usize>(nodeIndex) >= data.nodes.size()) {
- return nullptr;
- }
-
- // TODO: Create nodes using DockArea API
- // This requires additional DockArea methods for direct node creation
- (void)data.nodes[static_cast<usize>(nodeIndex)];
-
- return nullptr;
-}
-
-// =============================================================================
-// JSON Conversion
-// =============================================================================
-
-std::string DockLayoutSerializer::toJson(const DockLayoutData& data) const {
- std::ostringstream oss;
- oss << std::fixed << std::setprecision(4);
-
- oss << "{\n";
- oss << " \"version\": " << data.version << ",\n";
- oss << " \"layoutName\": \"" << escapeJsonString(data.layoutName) << "\",\n";
- oss << " \"rootNodeIndex\": " << data.rootNodeIndex << ",\n";
- oss << " \"nextNodeId\": " << data.nextNodeId << ",\n";
- oss << " \"nodes\": [\n";
-
- for (usize i = 0; i < data.nodes.size(); ++i) {
- const DockNodeData& node = data.nodes[i];
- oss << " {\n";
- oss << " \"id\": " << node.id << ",\n";
- oss << " \"type\": " << static_cast<i32>(node.type) << ",\n";
- oss << " \"splitDirection\": " << static_cast<i32>(node.splitDirection) << ",\n";
- oss << " \"splitRatio\": " << node.splitRatio << ",\n";
- oss << " \"activeTabIndex\": " << node.activeTabIndex << ",\n";
- oss << " \"firstChildIndex\": " << node.firstChildIndex << ",\n";
- oss << " \"secondChildIndex\": " << node.secondChildIndex << ",\n";
- oss << " \"panelIds\": [";
-
- for (usize j = 0; j < node.panelIds.size(); ++j) {
- oss << node.panelIds[j];
- if (j + 1 < node.panelIds.size()) oss << ", ";
- }
-
- oss << "]\n";
- oss << " }";
- if (i + 1 < data.nodes.size()) oss << ",";
- oss << "\n";
- }
-
- oss << " ]\n";
- oss << "}\n";
-
- return oss.str();
-}
-
-bool DockLayoutSerializer::fromJson(const std::string& json, DockLayoutData& outData) const {
- usize pos = 0;
-
- if (!expectChar(json, pos, '{')) return false;
-
- while (pos < json.size()) {
- skipWhitespace(json, pos);
- if (json[pos] == '}') break;
-
- std::string key = parseString(json, pos);
- if (!expectChar(json, pos, ':')) return false;
-
- if (key == "version") {
- outData.version = static_cast<u32>(parseInt(json, pos));
- } else if (key == "layoutName") {
- outData.layoutName = parseString(json, pos);
- } else if (key == "rootNodeIndex") {
- outData.rootNodeIndex = parseInt(json, pos);
- } else if (key == "nextNodeId") {
- outData.nextNodeId = static_cast<DockNodeId>(parseInt(json, pos));
- } else if (key == "nodes") {
- if (!expectChar(json, pos, '[')) return false;
-
- while (pos < json.size()) {
- skipWhitespace(json, pos);
- if (json[pos] == ']') {
- ++pos;
- break;
- }
-
- DockNodeData node;
- if (!expectChar(json, pos, '{')) return false;
-
- while (pos < json.size()) {
- skipWhitespace(json, pos);
- if (json[pos] == '}') {
- ++pos;
- break;
- }
-
- std::string nodeKey = parseString(json, pos);
- if (!expectChar(json, pos, ':')) return false;
-
- if (nodeKey == "id") {
- node.id = static_cast<DockNodeId>(parseInt(json, pos));
- } else if (nodeKey == "type") {
- node.type = static_cast<DockNodeType>(parseInt(json, pos));
- } else if (nodeKey == "splitDirection") {
- node.splitDirection = static_cast<DockSplitDirection>(parseInt(json, pos));
- } else if (nodeKey == "splitRatio") {
- node.splitRatio = parseNumber(json, pos);
- } else if (nodeKey == "activeTabIndex") {
- node.activeTabIndex = parseInt(json, pos);
- } else if (nodeKey == "firstChildIndex") {
- node.firstChildIndex = parseInt(json, pos);
- } else if (nodeKey == "secondChildIndex") {
- node.secondChildIndex = parseInt(json, pos);
- } else if (nodeKey == "panelIds") {
- if (!expectChar(json, pos, '[')) return false;
- while (pos < json.size()) {
- skipWhitespace(json, pos);
- if (json[pos] == ']') {
- ++pos;
- break;
- }
- node.panelIds.push_back(
- static_cast<DockPanelId>(parseInt(json, pos)));
- expectChar(json, pos, ',');
- }
- }
-
- expectChar(json, pos, ',');
- }
-
- outData.nodes.push_back(node);
- expectChar(json, pos, ',');
- }
- }
-
- expectChar(json, pos, ',');
- }
-
- return true;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockLayoutSerializer.hpp b/src/esengine/editor/ui/docking/DockLayoutSerializer.hpp
deleted file mode 100644
index cb69ee3fd..000000000
--- a/src/esengine/editor/ui/docking/DockLayoutSerializer.hpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/**
- * @file DockLayoutSerializer.hpp
- * @brief Serialization and deserialization for dock layouts
- * @details Saves and loads dock tree structure to/from JSON format.
- * Panels are identified by ID; actual panel restoration
- * is delegated to the application.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-#include "../../../core/Types.hpp"
-
-#include <string>
-#include <vector>
-#include <functional>
-
-namespace esengine::ui {
-
-// Forward declarations
-class DockArea;
-class DockNode;
-class DockPanel;
-
-// =============================================================================
-// Serialized Data Structures
-// =============================================================================
-
-/**
- * @brief Serialized representation of a dock node
- */
-struct DockNodeData {
- DockNodeId id = 0;
- DockNodeType type = DockNodeType::Tabs;
-
- // Split node data
- DockSplitDirection splitDirection = DockSplitDirection::Horizontal;
- f32 splitRatio = 0.5f;
-
- // Tabs node data
- std::vector<DockPanelId> panelIds;
- i32 activeTabIndex = 0;
-
- // Children (for split nodes)
- i32 firstChildIndex = -1;
- i32 secondChildIndex = -1;
-};
-
-/**
- * @brief Complete serialized dock layout
- */
-struct DockLayoutData {
- std::vector<DockNodeData> nodes;
- i32 rootNodeIndex = -1;
- DockNodeId nextNodeId = 1;
-
- // Metadata
- std::string layoutName;
- u32 version = 1;
-};
-
-// =============================================================================
-// DockLayoutSerializer Class
-// =============================================================================
-
-/**
- * @brief Panel factory callback for deserialization
- * @param panelId The panel ID to create
- * @return Created panel or nullptr if panel cannot be restored
- */
-using PanelFactory = std::function<Unique<DockPanel>(DockPanelId)>;
-
-/**
- * @brief Serializes and deserializes dock layouts
- *
- * @details The serializer captures the structural layout (splits, tabs,
- * ratios) but not panel contents. During deserialization, a
- * PanelFactory callback is used to create panels by ID.
- *
- * @code
- * // Save layout
- * DockLayoutSerializer serializer;
- * std::string json = serializer.serialize(dockArea);
- * saveToFile("layout.json", json);
- *
- * // Load layout
- * std::string json = loadFromFile("layout.json");
- * serializer.deserialize(dockArea, json, [](DockPanelId id) {
- * return createPanelById(id);
- * });
- * @endcode
- */
-class DockLayoutSerializer {
-public:
- // =========================================================================
- // Serialization
- // =========================================================================
-
- /**
- * @brief Serialize dock area to JSON string
- * @param area The dock area to serialize
- * @return JSON string representation
- */
- std::string serialize(const DockArea& area) const;
-
- /**
- * @brief Serialize dock area to layout data
- * @param area The dock area to serialize
- * @return Layout data structure
- */
- DockLayoutData serializeToData(const DockArea& area) const;
-
- // =========================================================================
- // Deserialization
- // =========================================================================
-
- /**
- * @brief Deserialize dock area from JSON string
- * @param area The dock area to populate
- * @param json JSON string to parse
- * @param factory Factory function to create panels
- * @return True if successful
- */
- bool deserialize(DockArea& area, const std::string& json,
- const PanelFactory& factory) const;
-
- /**
- * @brief Deserialize dock area from layout data
- * @param area The dock area to populate
- * @param data Layout data structure
- * @param factory Factory function to create panels
- * @return True if successful
- */
- bool deserializeFromData(DockArea& area, const DockLayoutData& data,
- const PanelFactory& factory) const;
-
- // =========================================================================
- // JSON Conversion
- // =========================================================================
-
- /**
- * @brief Convert layout data to JSON string
- * @param data Layout data to convert
- * @return JSON string
- */
- std::string toJson(const DockLayoutData& data) const;
-
- /**
- * @brief Parse JSON string to layout data
- * @param json JSON string to parse
- * @param outData Output layout data
- * @return True if parsing successful
- */
- bool fromJson(const std::string& json, DockLayoutData& outData) const;
-
-private:
- void serializeNode(const DockNode* node, DockLayoutData& data,
- std::vector<i32>& nodeIndexMap) const;
-
- DockNode* deserializeNode(DockArea& area, const DockLayoutData& data,
- i32 nodeIndex, const PanelFactory& factory) const;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockNode.cpp b/src/esengine/editor/ui/docking/DockNode.cpp
deleted file mode 100644
index 7d45c4b46..000000000
--- a/src/esengine/editor/ui/docking/DockNode.cpp
+++ /dev/null
@@ -1,381 +0,0 @@
-/**
- * @file DockNode.cpp
- * @brief DockNode implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DockNode.hpp"
-#include "DockPanel.hpp"
-
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Factory Methods
-// =============================================================================
-
-Unique<DockNode> DockNode::createTabs(DockNodeId id) {
- return Unique<DockNode>(new DockNode(id, DockNodeType::Tabs));
-}
-
-Unique<DockNode> DockNode::createSplit(DockNodeId id, DockSplitDirection direction) {
- auto node = Unique<DockNode>(new DockNode(id, DockNodeType::Split));
- node->splitDirection_ = direction;
- return node;
-}
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-DockNode::DockNode(DockNodeId id, DockNodeType type)
- : id_(id), type_(type) {}
-
-DockNode::~DockNode() = default;
-
-// =============================================================================
-// Tree Structure
-// =============================================================================
-
-void DockNode::setFirst(Unique<DockNode> node) {
- first_ = std::move(node);
- if (first_) {
- first_->parent_ = this;
- first_->area_ = area_;
- }
-}
-
-void DockNode::setSecond(Unique<DockNode> node) {
- second_ = std::move(node);
- if (second_) {
- second_->parent_ = this;
- second_->area_ = area_;
- }
-}
-
-Unique<DockNode> DockNode::detachFirst() {
- if (first_) {
- first_->parent_ = nullptr;
- first_->area_ = nullptr;
- }
- return std::move(first_);
-}
-
-Unique<DockNode> DockNode::detachSecond() {
- if (second_) {
- second_->parent_ = nullptr;
- second_->area_ = nullptr;
- }
- return std::move(second_);
-}
-
-void DockNode::updateChildParents() {
- if (first_) {
- first_->parent_ = this;
- first_->area_ = area_;
- }
- if (second_) {
- second_->parent_ = this;
- second_->area_ = area_;
- }
-}
-
-// =============================================================================
-// Split Properties
-// =============================================================================
-
-void DockNode::setSplitRatio(f32 ratio) {
- splitRatio_ = std::clamp(ratio, 0.1f, 0.9f);
-}
-
-// =============================================================================
-// Tab Properties
-// =============================================================================
-
-void DockNode::setActiveTabIndex(i32 index) {
- if (!panels_.empty()) {
- activeTabIndex_ = std::clamp(index, 0, static_cast<i32>(panels_.size()) - 1);
- } else {
- activeTabIndex_ = 0;
- }
-}
-
-DockPanel* DockNode::getActivePanel() const {
- if (activeTabIndex_ >= 0 && activeTabIndex_ < static_cast<i32>(panels_.size())) {
- return panels_[static_cast<usize>(activeTabIndex_)].get();
- }
- return nullptr;
-}
-
-// =============================================================================
-// Panel Management
-// =============================================================================
-
-void DockNode::addPanel(Unique<DockPanel> panel) {
- if (panel) {
- panel->ownerNode_ = this;
- panels_.push_back(std::move(panel));
- if (panels_.size() == 1) {
- activeTabIndex_ = 0;
- }
- }
-}
-
-void DockNode::insertPanel(Unique<DockPanel> panel, i32 index) {
- if (panel) {
- panel->ownerNode_ = this;
- index = std::clamp(index, 0, static_cast<i32>(panels_.size()));
- panels_.insert(panels_.begin() + index, std::move(panel));
-
- if (activeTabIndex_ >= index) {
- activeTabIndex_++;
- }
- }
-}
-
-Unique<DockPanel> DockNode::removePanel(DockPanel* panel) {
- i32 index = findPanelIndex(panel);
- if (index >= 0) {
- return removePanelAt(index);
- }
- return nullptr;
-}
-
-Unique<DockPanel> DockNode::removePanelAt(i32 index) {
- if (index < 0 || index >= static_cast<i32>(panels_.size())) {
- return nullptr;
- }
-
- auto panel = std::move(panels_[static_cast<usize>(index)]);
- panel->ownerNode_ = nullptr;
- panels_.erase(panels_.begin() + index);
-
- if (activeTabIndex_ >= static_cast<i32>(panels_.size())) {
- activeTabIndex_ = static_cast<i32>(panels_.size()) - 1;
- }
- if (activeTabIndex_ < 0) {
- activeTabIndex_ = 0;
- }
-
- return panel;
-}
-
-i32 DockNode::findPanelIndex(DockPanel* panel) const {
- for (usize i = 0; i < panels_.size(); ++i) {
- if (panels_[i].get() == panel) {
- return static_cast<i32>(i);
- }
- }
- return -1;
-}
-
-DockPanel* DockNode::findPanel(DockPanelId id) const {
- for (const auto& panel : panels_) {
- if (panel->getPanelId() == id) {
- return panel.get();
- }
- }
- return nullptr;
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-void DockNode::layout(f32 splitterThickness, f32 tabBarHeight) {
- if (isSplit()) {
- layoutSplit(splitterThickness, tabBarHeight);
- } else {
- layoutTabs(tabBarHeight);
- }
-}
-
-void DockNode::layoutSplit(f32 splitterThickness, f32 tabBarHeight) {
- if (!first_ || !second_) return;
-
- if (splitDirection_ == DockSplitDirection::Horizontal) {
- f32 availableWidth = bounds_.width - splitterThickness;
- f32 firstWidth = availableWidth * splitRatio_;
- f32 secondWidth = availableWidth - firstWidth;
-
- Rect firstBounds{
- bounds_.x,
- bounds_.y,
- firstWidth,
- bounds_.height
- };
-
- Rect secondBounds{
- bounds_.x + firstWidth + splitterThickness,
- bounds_.y,
- secondWidth,
- bounds_.height
- };
-
- first_->setBounds(firstBounds);
- second_->setBounds(secondBounds);
- } else {
- f32 availableHeight = bounds_.height - splitterThickness;
- f32 firstHeight = availableHeight * splitRatio_;
- f32 secondHeight = availableHeight - firstHeight;
-
- Rect firstBounds{
- bounds_.x,
- bounds_.y,
- bounds_.width,
- firstHeight
- };
-
- Rect secondBounds{
- bounds_.x,
- bounds_.y + firstHeight + splitterThickness,
- bounds_.width,
- secondHeight
- };
-
- first_->setBounds(firstBounds);
- second_->setBounds(secondBounds);
- }
-
- first_->layout(splitterThickness, tabBarHeight);
- second_->layout(splitterThickness, tabBarHeight);
-}
-
-void DockNode::layoutTabs(f32 tabBarHeight) {
- contentBounds_ = Rect{
- bounds_.x,
- bounds_.y + tabBarHeight,
- bounds_.width,
- bounds_.height - tabBarHeight
- };
-
- for (auto& panel : panels_) {
- if (panel) {
- panel->layout(contentBounds_);
- }
- }
-}
-
-Rect DockNode::getSplitterBounds(f32 thickness) const {
- if (!isSplit()) return {};
-
- if (splitDirection_ == DockSplitDirection::Horizontal) {
- f32 availableWidth = bounds_.width - thickness;
- f32 splitterX = bounds_.x + availableWidth * splitRatio_;
- return Rect{
- splitterX,
- bounds_.y,
- thickness,
- bounds_.height
- };
- } else {
- f32 availableHeight = bounds_.height - thickness;
- f32 splitterY = bounds_.y + availableHeight * splitRatio_;
- return Rect{
- bounds_.x,
- splitterY,
- bounds_.width,
- thickness
- };
- }
-}
-
-bool DockNode::hitTestSplitter(f32 x, f32 y, f32 tolerance) const {
- if (!isSplit()) return false;
-
- Rect splitterBounds = getSplitterBounds(tolerance * 2.0f);
- return splitterBounds.contains({x, y});
-}
-
-// =============================================================================
-// Tree Traversal
-// =============================================================================
-
-DockNode* DockNode::findNode(DockNodeId id) {
- if (id_ == id) return this;
-
- if (first_) {
- if (auto* found = first_->findNode(id)) {
- return found;
- }
- }
-
- if (second_) {
- if (auto* found = second_->findNode(id)) {
- return found;
- }
- }
-
- return nullptr;
-}
-
-DockNode* DockNode::findNodeContainingPanel(DockPanelId panelId) {
- if (isTabs()) {
- for (const auto& panel : panels_) {
- if (panel && panel->getPanelId() == panelId) {
- return this;
- }
- }
- }
-
- if (first_) {
- if (auto* found = first_->findNodeContainingPanel(panelId)) {
- return found;
- }
- }
-
- if (second_) {
- if (auto* found = second_->findNodeContainingPanel(panelId)) {
- return found;
- }
- }
-
- return nullptr;
-}
-
-DockNode* DockNode::findLeafAt(f32 x, f32 y) {
- if (!bounds_.contains({x, y})) {
- return nullptr;
- }
-
- if (isTabs()) {
- return this;
- }
-
- if (first_) {
- if (auto* found = first_->findLeafAt(x, y)) {
- return found;
- }
- }
-
- if (second_) {
- if (auto* found = second_->findLeafAt(x, y)) {
- return found;
- }
- }
-
- return nullptr;
-}
-
-void DockNode::forEachLeaf(const std::function<void(DockNode&)>& callback) {
- if (isTabs()) {
- callback(*this);
- } else {
- if (first_) first_->forEachLeaf(callback);
- if (second_) second_->forEachLeaf(callback);
- }
-}
-
-void DockNode::forEachNode(const std::function<void(DockNode&)>& callback) {
- callback(*this);
- if (first_) first_->forEachNode(callback);
- if (second_) second_->forEachNode(callback);
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockNode.hpp b/src/esengine/editor/ui/docking/DockNode.hpp
deleted file mode 100644
index 4337304c9..000000000
--- a/src/esengine/editor/ui/docking/DockNode.hpp
+++ /dev/null
@@ -1,338 +0,0 @@
-/**
- * @file DockNode.hpp
- * @brief Binary tree node for the docking system
- * @details Represents either a Split node with two children or a Tabs node
- * containing one or more DockPanels.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-#include "../../../ui/core/Types.hpp"
-
-#include <functional>
-#include <vector>
-
-namespace esengine::ui {
-
-// Forward declarations
-class DockPanel;
-class DockArea;
-
-// =============================================================================
-// DockNode Class
-// =============================================================================
-
-/**
- * @brief A node in the docking binary tree structure
- *
- * @details Each node is either:
- * - **Split**: Has two child nodes divided by a splitter
- * - **Tabs**: Contains one or more DockPanels displayed as tabs
- *
- * @code
- * // Create a tabs node
- * auto tabsNode = DockNode::createTabs(1);
- * tabsNode->addPanel(std::move(panel));
- *
- * // Create a split node
- * auto splitNode = DockNode::createSplit(2, DockSplitDirection::Horizontal);
- * splitNode->setFirst(std::move(leftNode));
- * splitNode->setSecond(std::move(rightNode));
- * @endcode
- */
-class DockNode {
-public:
- // =========================================================================
- // Factory Methods
- // =========================================================================
-
- /**
- * @brief Create a Tabs node
- * @param id Unique node identifier
- */
- static Unique<DockNode> createTabs(DockNodeId id);
-
- /**
- * @brief Create a Split node
- * @param id Unique node identifier
- * @param direction Split direction (Horizontal or Vertical)
- */
- static Unique<DockNode> createSplit(DockNodeId id, DockSplitDirection direction);
-
- ~DockNode();
-
- // Non-copyable
- DockNode(const DockNode&) = delete;
- DockNode& operator=(const DockNode&) = delete;
-
- // =========================================================================
- // Identity
- // =========================================================================
-
- /** @brief Gets the node's unique identifier */
- DockNodeId getId() const { return id_; }
-
- /** @brief Gets the node type (Split or Tabs) */
- DockNodeType getType() const { return type_; }
-
- /** @brief Returns true if this is a Split node */
- bool isSplit() const { return type_ == DockNodeType::Split; }
-
- /** @brief Returns true if this is a Tabs node */
- bool isTabs() const { return type_ == DockNodeType::Tabs; }
-
- // =========================================================================
- // Tree Structure
- // =========================================================================
-
- /** @brief Gets the parent node (nullptr if root) */
- DockNode* getParent() const { return parent_; }
-
- /** @brief Gets the owning DockArea */
- DockArea* getArea() const { return area_; }
-
- /** @brief Gets the first child (Split nodes only) */
- DockNode* getFirst() const { return first_.get(); }
-
- /** @brief Gets the second child (Split nodes only) */
- DockNode* getSecond() const { return second_.get(); }
-
- /**
- * @brief Sets the first child node
- * @param node Child node (ownership transferred)
- */
- void setFirst(Unique<DockNode> node);
-
- /**
- * @brief Sets the second child node
- * @param node Child node (ownership transferred)
- */
- void setSecond(Unique<DockNode> node);
-
- /**
- * @brief Detach and return the first child
- */
- Unique<DockNode> detachFirst();
-
- /**
- * @brief Detach and return the second child
- */
- Unique<DockNode> detachSecond();
-
- // =========================================================================
- // Split Properties (Split nodes only)
- // =========================================================================
-
- /** @brief Gets the split direction */
- DockSplitDirection getSplitDirection() const { return splitDirection_; }
-
- /** @brief Sets the split direction */
- void setSplitDirection(DockSplitDirection direction) { splitDirection_ = direction; }
-
- /** @brief Gets the split ratio (0.0 to 1.0) */
- f32 getSplitRatio() const { return splitRatio_; }
-
- /**
- * @brief Sets the split ratio
- * @param ratio Value between 0.1 and 0.9 (clamped)
- */
- void setSplitRatio(f32 ratio);
-
- // =========================================================================
- // Tab Properties (Tabs nodes only)
- // =========================================================================
-
- /** @brief Gets all panels in this node */
- const std::vector<Unique<DockPanel>>& getPanels() const { return panels_; }
-
- /** @brief Gets the number of panels */
- usize getPanelCount() const { return panels_.size(); }
-
- /** @brief Gets the active tab index */
- i32 getActiveTabIndex() const { return activeTabIndex_; }
-
- /**
- * @brief Sets the active tab index
- * @param index Index of tab to activate
- */
- void setActiveTabIndex(i32 index);
-
- /** @brief Gets the currently active panel (may be nullptr) */
- DockPanel* getActivePanel() const;
-
- // =========================================================================
- // Panel Management (Tabs nodes only)
- // =========================================================================
-
- /**
- * @brief Add a panel to the end of the tab list
- * @param panel Panel to add (ownership transferred)
- */
- void addPanel(Unique<DockPanel> panel);
-
- /**
- * @brief Insert a panel at a specific index
- * @param panel Panel to insert (ownership transferred)
- * @param index Position to insert at
- */
- void insertPanel(Unique<DockPanel> panel, i32 index);
-
- /**
- * @brief Remove a panel by pointer
- * @param panel Panel to remove
- * @return The removed panel
- */
- Unique<DockPanel> removePanel(DockPanel* panel);
-
- /**
- * @brief Remove a panel by index
- * @param index Index of panel to remove
- * @return The removed panel
- */
- Unique<DockPanel> removePanelAt(i32 index);
-
- /**
- * @brief Find panel index by pointer
- * @param panel Panel to find
- * @return Index or -1 if not found
- */
- i32 findPanelIndex(DockPanel* panel) const;
-
- /**
- * @brief Find panel by ID
- * @param id Panel ID to search for
- * @return Panel pointer or nullptr
- */
- DockPanel* findPanel(DockPanelId id) const;
-
- // =========================================================================
- // Layout
- // =========================================================================
-
- /** @brief Gets the node's bounding rectangle */
- const Rect& getBounds() const { return bounds_; }
-
- /**
- * @brief Sets the node's bounding rectangle
- * @param bounds New bounds
- */
- void setBounds(const Rect& bounds) { bounds_ = bounds; }
-
- /**
- * @brief Perform layout on this node and children
- * @param splitterThickness Thickness of splitters in pixels
- * @param tabBarHeight Height of tab bars in pixels
- */
- void layout(f32 splitterThickness, f32 tabBarHeight);
-
- /**
- * @brief Gets the content area (excluding tab bar for Tabs nodes)
- */
- Rect getContentBounds() const { return contentBounds_; }
-
- // =========================================================================
- // Splitter (Split nodes only)
- // =========================================================================
-
- /**
- * @brief Get the splitter bounds for rendering/hit testing
- * @param thickness Splitter thickness in pixels
- */
- Rect getSplitterBounds(f32 thickness = 4.0f) const;
-
- /**
- * @brief Test if a point hits the splitter
- * @param x X coordinate
- * @param y Y coordinate
- * @param tolerance Hit tolerance in pixels
- */
- bool hitTestSplitter(f32 x, f32 y, f32 tolerance = 4.0f) const;
-
- // =========================================================================
- // Tree Traversal
- // =========================================================================
-
- /**
- * @brief Find a node by ID in this subtree
- * @param id Node ID to find
- * @return Node pointer or nullptr
- */
- DockNode* findNode(DockNodeId id);
-
- /**
- * @brief Find the node containing a specific panel
- * @param panelId Panel ID to search for
- * @return Node pointer or nullptr
- */
- DockNode* findNodeContainingPanel(DockPanelId panelId);
-
- /**
- * @brief Find the leaf node at a given point
- * @param x X coordinate
- * @param y Y coordinate
- * @return Leaf node pointer or nullptr
- */
- DockNode* findLeafAt(f32 x, f32 y);
-
- /**
- * @brief Execute a callback for each leaf (Tabs) node
- * @param callback Function to call
- */
- void forEachLeaf(const std::function<void(DockNode&)>& callback);
-
- /**
- * @brief Execute a callback for each node (pre-order traversal)
- * @param callback Function to call
- */
- void forEachNode(const std::function<void(DockNode&)>& callback);
-
- // =========================================================================
- // Validation
- // =========================================================================
-
- /** @brief Returns true if this is an empty Tabs node */
- bool isEmpty() const { return isTabs() && panels_.empty(); }
-
- /** @brief Returns true if this is a leaf node (Tabs) */
- bool isLeaf() const { return isTabs(); }
-
-private:
- DockNode(DockNodeId id, DockNodeType type);
-
- void updateChildParents();
- void layoutSplit(f32 splitterThickness, f32 tabBarHeight);
- void layoutTabs(f32 tabBarHeight);
-
- DockNodeId id_;
- DockNodeType type_;
- DockNode* parent_ = nullptr;
- DockArea* area_ = nullptr;
-
- // Split node data
- DockSplitDirection splitDirection_ = DockSplitDirection::Horizontal;
- f32 splitRatio_ = 0.5f;
- Unique<DockNode> first_;
- Unique<DockNode> second_;
-
- // Tabs node data
- std::vector<Unique<DockPanel>> panels_;
- i32 activeTabIndex_ = 0;
-
- // Layout
- Rect bounds_;
- Rect contentBounds_;
-
- friend class DockArea;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockPanel.cpp b/src/esengine/editor/ui/docking/DockPanel.cpp
deleted file mode 100644
index 2e6c56fa4..000000000
--- a/src/esengine/editor/ui/docking/DockPanel.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * @file DockPanel.cpp
- * @brief DockPanel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DockPanel.hpp"
-#include "DockNode.hpp"
-#include "DockArea.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Static Members
-// =============================================================================
-
-DockPanelId DockPanel::nextPanelId_ = 1;
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-DockPanel::DockPanel(const WidgetId& id, const std::string& title)
- : Widget(id)
- , panelId_(nextPanelId_++)
- , title_(title) {
- setName(title);
-}
-
-DockPanel::~DockPanel() = default;
-
-// =============================================================================
-// Title
-// =============================================================================
-
-void DockPanel::setTitle(const std::string& title) {
- if (title_ != title) {
- title_ = title;
- setName(title);
- onTitleChanged.publish(title_);
- }
-}
-
-// =============================================================================
-// Dock Context
-// =============================================================================
-
-DockArea* DockPanel::getDockArea() const {
- if (ownerNode_) {
- return ownerNode_->getArea();
- }
- return nullptr;
-}
-
-// =============================================================================
-// Content
-// =============================================================================
-
-void DockPanel::setContent(Unique<Widget> content) {
- if (contentWidget_) {
- removeChild(contentWidget_);
- contentWidget_ = nullptr;
- }
-
- if (content) {
- contentWidget_ = content.get();
- addChild(std::move(content));
- }
-}
-
-// =============================================================================
-// Widget Overrides
-// =============================================================================
-
-glm::vec2 DockPanel::measure(f32 availableWidth, f32 availableHeight) {
- glm::vec2 contentSize = minSize_;
-
- if (contentWidget_) {
- contentSize = contentWidget_->measure(availableWidth, availableHeight);
- }
-
- return glm::vec2{
- std::max(contentSize.x, minSize_.x),
- std::max(contentSize.y, minSize_.y)
- };
-}
-
-void DockPanel::layoutChildren(const Rect& contentBounds) {
- if (contentWidget_) {
- contentWidget_->layout(contentBounds);
- }
-}
-
-void DockPanel::invalidateLayout() {
- Widget::invalidateLayout();
-
- if (ownerNode_) {
- DockArea* area = ownerNode_->getArea();
- if (area) {
- area->invalidateLayout();
- }
- }
-}
-
-void DockPanel::render(UIBatchRenderer& renderer) {
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- const Rect& bounds = getBounds();
-
- WidgetStyle style = ctx->getTheme().getPanelStyle();
- renderer.drawRect(bounds, style.backgroundColor);
-
- if (contentWidget_) {
- contentWidget_->renderTree(renderer);
- }
-
- onRenderContent(renderer);
-}
-
-void DockPanel::renderTree(UIBatchRenderer& renderer) {
- if (!isVisible()) return;
- render(renderer);
-}
-
-void DockPanel::onRenderContent(UIBatchRenderer& renderer) {
- (void)renderer;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockPanel.hpp b/src/esengine/editor/ui/docking/DockPanel.hpp
deleted file mode 100644
index fa44cbcd2..000000000
--- a/src/esengine/editor/ui/docking/DockPanel.hpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/**
- * @file DockPanel.hpp
- * @brief Dockable panel base class
- * @details A panel widget that can be docked, tabbed, and dragged
- * within the docking system.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-#include "../../../ui/widgets/Widget.hpp"
-#include "../../../events/Signal.hpp"
-
-#include <string>
-
-namespace esengine::ui {
-
-// Forward declarations
-class DockNode;
-class DockArea;
-
-// =============================================================================
-// DockPanel Class
-// =============================================================================
-
-/**
- * @brief A dockable panel that can be moved between dock nodes
- *
- * @details DockPanel is the base class for all dockable panels in the editor.
- * It provides:
- * - A title for the tab bar
- * - Optional icon
- * - Close button support
- * - Content widget container
- *
- * @code
- * class HierarchyPanel : public DockPanel {
- * public:
- * HierarchyPanel()
- * : DockPanel(WidgetId("hierarchy"), "Hierarchy") {
- * setContent(makeUnique<TreeView>(WidgetId("hierarchy.tree")));
- * }
- * };
- * @endcode
- */
-class DockPanel : public Widget {
-public:
- /**
- * @brief Constructs a dock panel
- * @param id Widget identifier
- * @param title Title displayed in the tab bar
- */
- DockPanel(const WidgetId& id, const std::string& title);
-
- ~DockPanel() override;
-
- // =========================================================================
- // Identity
- // =========================================================================
-
- /** @brief Gets the panel's unique ID */
- DockPanelId getPanelId() const { return panelId_; }
-
- /** @brief Gets the panel type identifier for serialization */
- const std::string& getPanelType() const { return panelType_; }
-
- /** @brief Sets the panel type identifier */
- void setPanelType(const std::string& type) { panelType_ = type; }
-
- // =========================================================================
- // Title
- // =========================================================================
-
- /** @brief Gets the panel title */
- const std::string& getTitle() const { return title_; }
-
- /** @brief Sets the panel title */
- void setTitle(const std::string& title);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Sets whether the panel can be closed */
- void setClosable(bool closable) { closable_ = closable; }
-
- /** @brief Returns true if the panel can be closed */
- bool isClosable() const { return closable_; }
-
- /** @brief Sets the minimum panel size */
- void setMinSize(const glm::vec2& minSize) { minSize_ = minSize; }
-
- /** @brief Gets the minimum panel size */
- glm::vec2 getMinSize() const { return minSize_; }
-
- // =========================================================================
- // Icon
- // =========================================================================
-
- /** @brief Sets the icon texture ID (0 for no icon) */
- void setIconTextureId(u32 textureId) { iconTextureId_ = textureId; }
-
- /** @brief Gets the icon texture ID */
- u32 getIconTextureId() const { return iconTextureId_; }
-
- // =========================================================================
- // Dock Context
- // =========================================================================
-
- /** @brief Gets the node that owns this panel */
- DockNode* getOwnerNode() const { return ownerNode_; }
-
- /** @brief Gets the DockArea containing this panel */
- DockArea* getDockArea() const;
-
- // =========================================================================
- // Content
- // =========================================================================
-
- /**
- * @brief Sets the content widget
- * @param content Widget to display (ownership transferred)
- */
- void setContent(Unique<Widget> content);
-
- /** @brief Gets the content widget */
- Widget* getContent() const { return contentWidget_; }
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /** @brief Emitted when close is requested */
- Signal<void()> onCloseRequested;
-
- /** @brief Emitted when title changes */
- Signal<void(const std::string&)> onTitleChanged;
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
- void renderTree(UIBatchRenderer& renderer) override;
- void invalidateLayout() override;
-
-protected:
- void layoutChildren(const Rect& contentBounds) override;
-
- /**
- * @brief Called to render panel-specific content
- * @param renderer Batch renderer
- *
- * @details Override this for custom panel content instead of using setContent.
- */
- virtual void onRenderContent(UIBatchRenderer& renderer);
-
- /**
- * @brief Called when the panel becomes active (selected tab)
- */
- virtual void onActivated() {}
-
- /**
- * @brief Called when the panel becomes inactive (different tab selected)
- */
- virtual void onDeactivated() {}
-
-private:
- static DockPanelId nextPanelId_;
-
- DockPanelId panelId_;
- std::string panelType_;
- std::string title_;
- bool closable_ = true;
- glm::vec2 minSize_{100.0f, 100.0f};
- u32 iconTextureId_ = 0;
-
- DockNode* ownerNode_ = nullptr;
- Widget* contentWidget_ = nullptr;
-
- friend class DockNode;
- friend class DockArea;
- friend class DockTabBar;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockTabBar.cpp b/src/esengine/editor/ui/docking/DockTabBar.cpp
deleted file mode 100644
index d9706f437..000000000
--- a/src/esengine/editor/ui/docking/DockTabBar.cpp
+++ /dev/null
@@ -1,362 +0,0 @@
-/**
- * @file DockTabBar.cpp
- * @brief DockTabBar implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DockTabBar.hpp"
-#include "DockArea.hpp"
-#include "DockNode.hpp"
-#include "DockPanel.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../../ui/font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../../../ui/font/BitmapFont.hpp"
-#endif
-
-#include "../../../ui/font/SystemFont.hpp"
-
-#include <cmath>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-DockTabBar::DockTabBar(const WidgetId& id, DockNode* ownerNode)
- : Widget(id)
- , ownerNode_(ownerNode) {}
-
-DockTabBar::~DockTabBar() = default;
-
-// =============================================================================
-// Tab Data
-// =============================================================================
-
-void DockTabBar::updateTabs() {
- tabs_.clear();
-
- if (!ownerNode_ || !ownerNode_->isTabs()) return;
-
- i32 activeIndex = ownerNode_->getActiveTabIndex();
- const auto& panels = ownerNode_->getPanels();
-
- for (usize i = 0; i < panels.size(); ++i) {
- const auto& panel = panels[i];
- if (!panel) continue;
-
- DockTabInfo tab;
- tab.panelId = panel->getPanelId();
- tab.title = panel->getTitle();
- tab.iconTextureId = panel->getIconTextureId();
- tab.closable = panel->isClosable();
- tab.active = (static_cast<i32>(i) == activeIndex);
- tab.hovered = (static_cast<i32>(i) == hoveredTabIndex_);
- tab.closeHovered = (static_cast<i32>(i) == hoveredCloseIndex_);
-
- tabs_.push_back(tab);
- }
-
- layoutTabs();
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 DockTabBar::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
- return {availableWidth, tabHeight_};
-}
-
-void DockTabBar::layoutTabs() {
- if (tabs_.empty()) return;
-
- const Rect& bounds = getBounds();
- f32 totalWidth = bounds.width - tabPadding_ * 2.0f;
- f32 tabWidth = totalWidth / static_cast<f32>(tabs_.size()) - tabSpacing_;
- tabWidth = std::clamp(tabWidth, tabMinWidth_, tabMaxWidth_);
-
- f32 x = bounds.x + tabPadding_;
-
- for (auto& tab : tabs_) {
- tab.bounds = Rect{
- x,
- bounds.y,
- tabWidth,
- tabHeight_
- };
-
- if (tab.closable) {
- f32 closeX = x + tabWidth - closeButtonSize_ - 4.0f;
- f32 closeY = bounds.y + (tabHeight_ - closeButtonSize_) * 0.5f;
- tab.closeButtonBounds = Rect{
- closeX,
- closeY,
- closeButtonSize_,
- closeButtonSize_
- };
- }
-
- x += tabWidth + tabSpacing_;
- }
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void DockTabBar::render(UIBatchRenderer& renderer) {
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- updateTabs();
-
- const Rect& bounds = getBounds();
- const Theme& theme = ctx->getTheme();
-
- renderer.drawRect(bounds, theme.colors.backgroundDark);
-
- for (usize i = 0; i < tabs_.size(); ++i) {
- renderTab(renderer, tabs_[i], i);
- }
-}
-
-void DockTabBar::renderTab(UIBatchRenderer& renderer, const DockTabInfo& tab, usize /*index*/) {
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- const Theme& theme = ctx->getTheme();
-
- glm::vec4 bgColor;
- if (tab.active) {
- bgColor = theme.colors.backgroundLight;
- } else if (tab.hovered) {
- bgColor = theme.colors.backgroundMedium;
- } else {
- bgColor = theme.colors.backgroundDark;
- }
-
- renderer.drawRect(tab.bounds, bgColor);
-
- if (tab.active) {
- Rect indicator{
- tab.bounds.x,
- tab.bounds.y + tab.bounds.height - 2.0f,
- tab.bounds.width,
- 2.0f
- };
- renderer.drawRect(indicator, theme.colors.accent);
- }
-
- f32 textX = tab.bounds.x + tabPadding_;
- f32 maxTextWidth = tab.bounds.width - tabPadding_ * 2.0f;
-
- if (tab.closable) {
- maxTextWidth -= closeButtonSize_ + 4.0f;
- }
-
- glm::vec4 textColor = tab.active ? theme.colors.textPrimary : theme.colors.textSecondary;
-
- Rect textBounds{
- textX,
- tab.bounds.y,
- maxTextWidth,
- tab.bounds.height
- };
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = ctx->getDefaultMSDFFont();
- if (font) {
- renderer.drawTextInBounds(tab.title, textBounds, *font,
- theme.typography.fontSizeSmall, textColor,
- HAlign::Left, VAlign::Center);
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = ctx->getDefaultBitmapFont();
- if (font) {
- renderer.drawTextInBounds(tab.title, textBounds, *font,
- theme.typography.fontSizeSmall, textColor,
- HAlign::Left, VAlign::Center);
- }
-#else
- SystemFont* font = ctx->getDefaultSystemFont();
- if (font) {
- renderer.drawTextInBounds(tab.title, textBounds, *font,
- theme.typography.fontSizeSmall, textColor,
- HAlign::Left, VAlign::Center);
- }
-#endif
-
- if (tab.closable) {
- glm::vec4 closeColor = tab.closeHovered
- ? theme.colors.error
- : theme.colors.textSecondary;
-
- f32 cx = tab.closeButtonBounds.x + tab.closeButtonBounds.width * 0.5f;
- f32 cy = tab.closeButtonBounds.y + tab.closeButtonBounds.height * 0.5f;
- f32 size = closeButtonSize_ * 0.3f;
-
- renderer.drawLine({cx - size, cy - size}, {cx + size, cy + size}, closeColor, 1.5f);
- renderer.drawLine({cx - size, cy + size}, {cx + size, cy - size}, closeColor, 1.5f);
- }
-}
-
-// =============================================================================
-// Hit Testing
-// =============================================================================
-
-i32 DockTabBar::hitTestTab(f32 x, f32 y) const {
- for (usize i = 0; i < tabs_.size(); ++i) {
- if (tabs_[i].bounds.contains({x, y})) {
- return static_cast<i32>(i);
- }
- }
- return -1;
-}
-
-i32 DockTabBar::hitTestCloseButton(f32 x, f32 y) const {
- for (usize i = 0; i < tabs_.size(); ++i) {
- if (tabs_[i].closable && tabs_[i].closeButtonBounds.contains({x, y})) {
- return static_cast<i32>(i);
- }
- }
- return -1;
-}
-
-void DockTabBar::updateHoverState(f32 x, f32 y) {
- i32 oldHoveredTab = hoveredTabIndex_;
- i32 oldHoveredClose = hoveredCloseIndex_;
-
- hoveredCloseIndex_ = hitTestCloseButton(x, y);
- hoveredTabIndex_ = hitTestTab(x, y);
-
- if (hoveredCloseIndex_ != oldHoveredClose || hoveredTabIndex_ != oldHoveredTab) {
- for (usize i = 0; i < tabs_.size(); ++i) {
- tabs_[i].hovered = (static_cast<i32>(i) == hoveredTabIndex_);
- tabs_[i].closeHovered = (static_cast<i32>(i) == hoveredCloseIndex_);
- }
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool DockTabBar::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) return false;
-
- i32 closeIndex = hitTestCloseButton(event.x, event.y);
- if (closeIndex >= 0) {
- return true;
- }
-
- i32 tabIndex = hitTestTab(event.x, event.y);
- if (tabIndex >= 0) {
- pressedTabIndex_ = tabIndex;
- pressStartPos_ = {event.x, event.y};
- potentialDrag_ = true;
-
- if (ownerNode_) {
- ownerNode_->setActiveTabIndex(tabIndex);
- }
- onTabSelected.publish(tabIndex);
- return true;
- }
-
- return false;
-}
-
-bool DockTabBar::onMouseUp(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) return false;
-
- if (isDragging_) {
- DockArea* area = ownerNode_ ? ownerNode_->getArea() : nullptr;
- if (area) {
- area->onMouseUp(event);
- }
- isDragging_ = false;
- pressedTabIndex_ = -1;
- return true;
- }
-
- i32 closeIndex = hitTestCloseButton(event.x, event.y);
- if (closeIndex >= 0 && closeIndex < static_cast<i32>(tabs_.size())) {
- onTabCloseRequested.publish(tabs_[static_cast<usize>(closeIndex)].panelId);
- return true;
- }
-
- potentialDrag_ = false;
- isDragging_ = false;
- pressedTabIndex_ = -1;
-
- return false;
-}
-
-bool DockTabBar::onMouseMove(const MouseMoveEvent& event) {
- updateHoverState(event.x, event.y);
-
- if (isDragging_) {
- DockArea* area = ownerNode_ ? ownerNode_->getArea() : nullptr;
- if (area) {
- area->onMouseMove(event);
- }
- return true;
- }
-
- if (potentialDrag_ && pressedTabIndex_ >= 0) {
- f32 dx = event.x - pressStartPos_.x;
- f32 dy = event.y - pressStartPos_.y;
- f32 distance = std::sqrt(dx * dx + dy * dy);
-
- if (distance > dragThreshold_) {
- isDragging_ = true;
- potentialDrag_ = false;
-
- if (pressedTabIndex_ < static_cast<i32>(tabs_.size())) {
- onTabDragStart.publish(
- tabs_[static_cast<usize>(pressedTabIndex_)].panelId,
- {event.x, event.y}
- );
-
- DockArea* area = ownerNode_ ? ownerNode_->getArea() : nullptr;
- if (area) {
- area->onMouseMove(event);
- }
- }
- }
- }
-
- return false;
-}
-
-bool DockTabBar::onMouseEnter(const MouseEnterEvent& event) {
- updateHoverState(event.x, event.y);
- return false;
-}
-
-bool DockTabBar::onMouseLeave(const MouseLeaveEvent& event) {
- (void)event;
- hoveredTabIndex_ = -1;
- hoveredCloseIndex_ = -1;
-
- for (auto& tab : tabs_) {
- tab.hovered = false;
- tab.closeHovered = false;
- }
-
- return false;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockTabBar.hpp b/src/esengine/editor/ui/docking/DockTabBar.hpp
deleted file mode 100644
index af2b521bb..000000000
--- a/src/esengine/editor/ui/docking/DockTabBar.hpp
+++ /dev/null
@@ -1,161 +0,0 @@
-/**
- * @file DockTabBar.hpp
- * @brief Tab bar widget for dock nodes
- * @details Renders tabs for panels in a Tabs node and handles
- * tab selection, drag initiation, and close buttons.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-#include "../../../ui/widgets/Widget.hpp"
-#include "../../../events/Signal.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine::ui {
-
-// Forward declarations
-class DockNode;
-
-// =============================================================================
-// DockTabInfo
-// =============================================================================
-
-/**
- * @brief Information about a single tab for rendering
- */
-struct DockTabInfo {
- DockPanelId panelId = INVALID_DOCK_PANEL_ID;
- std::string title;
- Rect bounds;
- Rect closeButtonBounds;
- u32 iconTextureId = 0;
- bool closable = true;
- bool hovered = false;
- bool active = false;
- bool closeHovered = false;
-};
-
-// =============================================================================
-// DockTabBar Class
-// =============================================================================
-
-/**
- * @brief Tab bar widget for a dock node with tabs
- *
- * @details Renders tab buttons and handles:
- * - Tab selection on click
- * - Close button clicks
- * - Drag initiation for panel reordering/undocking
- */
-class DockTabBar : public Widget {
-public:
- /**
- * @brief Constructs a tab bar for a dock node
- * @param id Widget identifier
- * @param ownerNode The Tabs node this bar belongs to
- */
- DockTabBar(const WidgetId& id, DockNode* ownerNode);
-
- ~DockTabBar() override;
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Sets the tab height in pixels */
- void setTabHeight(f32 height) { tabHeight_ = height; invalidateLayout(); }
-
- /** @brief Gets the tab height */
- f32 getTabHeight() const { return tabHeight_; }
-
- /** @brief Sets the minimum tab width */
- void setTabMinWidth(f32 width) { tabMinWidth_ = width; }
-
- /** @brief Sets the maximum tab width */
- void setTabMaxWidth(f32 width) { tabMaxWidth_ = width; }
-
- /** @brief Sets the drag threshold in pixels */
- void setDragThreshold(f32 pixels) { dragThreshold_ = pixels; }
-
- // =========================================================================
- // Tab Data
- // =========================================================================
-
- /** @brief Refresh tab info from owner node */
- void updateTabs();
-
- /** @brief Gets the tab info list */
- const std::vector<DockTabInfo>& getTabs() const { return tabs_; }
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /** @brief Emitted when a tab is selected (index) */
- Signal<void(i32)> onTabSelected;
-
- /** @brief Emitted when a tab close is requested (panel ID) */
- Signal<void(DockPanelId)> onTabCloseRequested;
-
- /** @brief Emitted when tab drag starts (panel ID, position) */
- Signal<void(DockPanelId, glm::vec2)> onTabDragStart;
-
- /** @brief Emitted when tabs are reordered (from index, to index) */
- Signal<void(i32, i32)> onTabReordered;
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
- bool onMouseEnter(const MouseEnterEvent& event) override;
- bool onMouseLeave(const MouseLeaveEvent& event) override;
-
-private:
- i32 hitTestTab(f32 x, f32 y) const;
- i32 hitTestCloseButton(f32 x, f32 y) const;
- void layoutTabs();
- void renderTab(UIBatchRenderer& renderer, const DockTabInfo& tab, usize index);
- void updateHoverState(f32 x, f32 y);
-
- DockNode* ownerNode_;
- std::vector<DockTabInfo> tabs_;
-
- // Dimensions
- f32 tabHeight_ = 24.0f;
- f32 tabMinWidth_ = 60.0f;
- f32 tabMaxWidth_ = 200.0f;
- f32 tabPadding_ = 8.0f;
- f32 tabSpacing_ = 1.0f;
- f32 closeButtonSize_ = 14.0f;
-
- // Drag state
- f32 dragThreshold_ = 5.0f;
- bool isDragging_ = false;
- bool potentialDrag_ = false;
- i32 pressedTabIndex_ = -1;
- glm::vec2 pressStartPos_{0.0f};
-
- // Hover state
- i32 hoveredTabIndex_ = -1;
- i32 hoveredCloseIndex_ = -1;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockTypes.hpp b/src/esengine/editor/ui/docking/DockTypes.hpp
deleted file mode 100644
index e6392c93d..000000000
--- a/src/esengine/editor/ui/docking/DockTypes.hpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * @file DockTypes.hpp
- * @brief Core types and enumerations for the docking system
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../../core/Types.hpp"
-
-#include <limits>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Type Aliases
-// =============================================================================
-
-/** @brief Unique identifier for dock nodes */
-using DockNodeId = u32;
-
-/** @brief Invalid dock node ID constant */
-constexpr DockNodeId INVALID_DOCK_NODE_ID = 0;
-
-/** @brief Unique identifier for dock panels */
-using DockPanelId = u32;
-
-/** @brief Invalid dock panel ID constant */
-constexpr DockPanelId INVALID_DOCK_PANEL_ID = 0;
-
-// =============================================================================
-// Enumerations
-// =============================================================================
-
-/**
- * @brief Direction for splitting dock nodes
- */
-enum class DockSplitDirection : u8 {
- Horizontal, ///< Left | Right split
- Vertical ///< Top / Bottom split
-};
-
-/**
- * @brief Type of node in the dock tree
- */
-enum class DockNodeType : u8 {
- Split, ///< Node with two children divided by a splitter
- Tabs ///< Node with one or more panels in tabs
-};
-
-/**
- * @brief Drop zone positions for drag-and-drop docking
- */
-enum class DockDropZone : u8 {
- None, ///< No valid drop zone
- Left, ///< Dock to the left edge
- Right, ///< Dock to the right edge
- Top, ///< Dock to the top edge
- Bottom, ///< Dock to the bottom edge
- Center, ///< Tab into existing container
- Root ///< Dock to window edge (root level)
-};
-
-/**
- * @brief State of a dock tab
- */
-enum class DockTabState : u8 {
- Normal, ///< Default state
- Hovered, ///< Mouse hovering over tab
- Active, ///< Currently selected tab
- Dragging ///< Tab is being dragged
-};
-
-// =============================================================================
-// Utility Functions
-// =============================================================================
-
-/**
- * @brief Get the opposite split direction
- */
-inline constexpr DockSplitDirection oppositeSplitDirection(DockSplitDirection dir) {
- return dir == DockSplitDirection::Horizontal
- ? DockSplitDirection::Vertical
- : DockSplitDirection::Horizontal;
-}
-
-/**
- * @brief Check if a drop zone creates a split
- */
-inline constexpr bool isEdgeDropZone(DockDropZone zone) {
- return zone == DockDropZone::Left || zone == DockDropZone::Right ||
- zone == DockDropZone::Top || zone == DockDropZone::Bottom;
-}
-
-/**
- * @brief Get the split direction for an edge drop zone
- */
-inline constexpr DockSplitDirection dropZoneToSplitDirection(DockDropZone zone) {
- return (zone == DockDropZone::Left || zone == DockDropZone::Right)
- ? DockSplitDirection::Horizontal
- : DockSplitDirection::Vertical;
-}
-
-/**
- * @brief Check if the drop zone inserts before (first child) or after (second child)
- */
-inline constexpr bool dropZoneIsFirst(DockDropZone zone) {
- return zone == DockDropZone::Left || zone == DockDropZone::Top;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockZone.cpp b/src/esengine/editor/ui/docking/DockZone.cpp
deleted file mode 100644
index f85e438d6..000000000
--- a/src/esengine/editor/ui/docking/DockZone.cpp
+++ /dev/null
@@ -1,297 +0,0 @@
-/**
- * @file DockZone.cpp
- * @brief DockZoneDetector implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DockZone.hpp"
-#include "DockArea.hpp"
-#include "DockNode.hpp"
-#include "DockPanel.hpp"
-#include "../../../ui/UIContext.hpp"
-#include "../../../ui/rendering/UIBatchRenderer.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-DockZoneDetector::DockZoneDetector(DockArea* area)
- : area_(area) {}
-
-// =============================================================================
-// Drag Operations
-// =============================================================================
-
-void DockZoneDetector::beginDrag(DockPanel* panel, const glm::vec2& startPos) {
- draggedPanel_ = panel;
- dragStartPos_ = startPos;
- dragCurrentPos_ = startPos;
- dragging_ = true;
- currentTarget_ = {};
- zoneOverlays_.clear();
-}
-
-void DockZoneDetector::updateDrag(const glm::vec2& pos) {
- if (!dragging_) return;
-
- dragCurrentPos_ = pos;
-
- DockNode* targetNode = nullptr;
- DockDropZone zone = detectZoneAtPosition(pos, targetNode);
-
- currentTarget_.zone = zone;
- currentTarget_.targetNode = targetNode;
-
- if (zone != DockDropZone::None && targetNode) {
- currentTarget_.previewBounds = calculatePreviewBounds(currentTarget_);
- calculateZoneOverlays(targetNode);
- } else {
- zoneOverlays_.clear();
- }
-}
-
-DockDropTarget DockZoneDetector::endDrag() {
- DockDropTarget result = currentTarget_;
- dragging_ = false;
- draggedPanel_ = nullptr;
- currentTarget_ = {};
- zoneOverlays_.clear();
- return result;
-}
-
-void DockZoneDetector::cancelDrag() {
- dragging_ = false;
- draggedPanel_ = nullptr;
- currentTarget_ = {};
- zoneOverlays_.clear();
-}
-
-// =============================================================================
-// Zone Detection
-// =============================================================================
-
-DockDropZone DockZoneDetector::detectZoneAtPosition(const glm::vec2& pos, DockNode*& outNode) {
- outNode = nullptr;
-
- if (!area_) return DockDropZone::None;
-
- DockNode* root = area_->getRootNode();
- if (!root) return DockDropZone::None;
-
- DockNode* hitNode = nullptr;
- root->forEachLeaf([&](DockNode& node) {
- if (node.getBounds().contains(pos)) {
- hitNode = &node;
- }
- });
-
- if (!hitNode) {
- if (root->getBounds().contains(pos)) {
- hitNode = root;
- } else {
- return DockDropZone::None;
- }
- }
-
- outNode = hitNode;
- const Rect& bounds = hitNode->getBounds();
-
- f32 relX = (pos.x - bounds.x) / bounds.width;
- f32 relY = (pos.y - bounds.y) / bounds.height;
-
- if (relX < edgeThreshold_) return DockDropZone::Left;
- if (relX > (1.0f - edgeThreshold_)) return DockDropZone::Right;
- if (relY < edgeThreshold_) return DockDropZone::Top;
- if (relY > (1.0f - edgeThreshold_)) return DockDropZone::Bottom;
-
- return DockDropZone::Center;
-}
-
-// =============================================================================
-// Zone Overlays
-// =============================================================================
-
-void DockZoneDetector::calculateZoneOverlays(DockNode* targetNode) {
- zoneOverlays_.clear();
-
- if (!targetNode) return;
-
- const Rect& bounds = targetNode->getBounds();
- f32 cx = bounds.x + bounds.width * 0.5f;
- f32 cy = bounds.y + bounds.height * 0.5f;
- f32 halfZone = zoneSize_ * 0.5f;
- f32 offset = zoneSize_ + 4.0f;
-
- DockZoneOverlay centerOverlay;
- centerOverlay.zone = DockDropZone::Center;
- centerOverlay.bounds = Rect{cx - halfZone, cy - halfZone, zoneSize_, zoneSize_};
- centerOverlay.hovered = (currentTarget_.zone == DockDropZone::Center);
- zoneOverlays_.push_back(centerOverlay);
-
- DockZoneOverlay leftOverlay;
- leftOverlay.zone = DockDropZone::Left;
- leftOverlay.bounds = Rect{cx - halfZone - offset, cy - halfZone, zoneSize_, zoneSize_};
- leftOverlay.hovered = (currentTarget_.zone == DockDropZone::Left);
- zoneOverlays_.push_back(leftOverlay);
-
- DockZoneOverlay rightOverlay;
- rightOverlay.zone = DockDropZone::Right;
- rightOverlay.bounds = Rect{cx + halfZone + 4.0f, cy - halfZone, zoneSize_, zoneSize_};
- rightOverlay.hovered = (currentTarget_.zone == DockDropZone::Right);
- zoneOverlays_.push_back(rightOverlay);
-
- DockZoneOverlay topOverlay;
- topOverlay.zone = DockDropZone::Top;
- topOverlay.bounds = Rect{cx - halfZone, cy - halfZone - offset, zoneSize_, zoneSize_};
- topOverlay.hovered = (currentTarget_.zone == DockDropZone::Top);
- zoneOverlays_.push_back(topOverlay);
-
- DockZoneOverlay bottomOverlay;
- bottomOverlay.zone = DockDropZone::Bottom;
- bottomOverlay.bounds = Rect{cx - halfZone, cy + halfZone + 4.0f, zoneSize_, zoneSize_};
- bottomOverlay.hovered = (currentTarget_.zone == DockDropZone::Bottom);
- zoneOverlays_.push_back(bottomOverlay);
-}
-
-Rect DockZoneDetector::calculatePreviewBounds(const DockDropTarget& target) {
- if (!target.targetNode) return {};
-
- const Rect& bounds = target.targetNode->getBounds();
- f32 ratio = target.splitRatio;
-
- switch (target.zone) {
- case DockDropZone::Left:
- return Rect{bounds.x, bounds.y, bounds.width * ratio, bounds.height};
-
- case DockDropZone::Right:
- return Rect{
- bounds.x + bounds.width * (1.0f - ratio),
- bounds.y,
- bounds.width * ratio,
- bounds.height
- };
-
- case DockDropZone::Top:
- return Rect{bounds.x, bounds.y, bounds.width, bounds.height * ratio};
-
- case DockDropZone::Bottom:
- return Rect{
- bounds.x,
- bounds.y + bounds.height * (1.0f - ratio),
- bounds.width,
- bounds.height * ratio
- };
-
- case DockDropZone::Center:
- return bounds;
-
- default:
- return {};
- }
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void DockZoneDetector::render(UIBatchRenderer& renderer) {
- if (!dragging_) return;
-
- renderDropPreview(renderer);
- renderZoneOverlays(renderer);
-}
-
-void DockZoneDetector::renderDropPreview(UIBatchRenderer& renderer) {
- if (currentTarget_.zone == DockDropZone::None) return;
-
- UIContext* ctx = area_ ? area_->getContext() : nullptr;
- if (!ctx) return;
-
- glm::vec4 previewColor = ctx->getTheme().colors.accent;
- previewColor.a = previewAlpha_;
-
- renderer.drawRect(currentTarget_.previewBounds, previewColor);
-}
-
-void DockZoneDetector::renderZoneOverlays(UIBatchRenderer& renderer) {
- for (const auto& overlay : zoneOverlays_) {
- renderZoneButton(renderer, overlay);
- }
-}
-
-void DockZoneDetector::renderZoneButton(UIBatchRenderer& renderer, const DockZoneOverlay& overlay) {
- UIContext* ctx = area_ ? area_->getContext() : nullptr;
- if (!ctx) return;
-
- const Theme& theme = ctx->getTheme();
-
- glm::vec4 bgColor = overlay.hovered
- ? theme.colors.accent
- : glm::vec4{0.3f, 0.3f, 0.3f, 0.9f};
-
- glm::vec4 borderColor = theme.colors.accent;
-
- renderer.drawRoundedRect(overlay.bounds, bgColor, CornerRadii::all(4.0f));
- renderer.drawRoundedRectOutline(overlay.bounds, borderColor, CornerRadii::all(4.0f), 1.0f);
-
- glm::vec4 iconColor = overlay.hovered
- ? theme.colors.textPrimary
- : theme.colors.textSecondary;
-
- f32 cx = overlay.bounds.x + overlay.bounds.width * 0.5f;
- f32 cy = overlay.bounds.y + overlay.bounds.height * 0.5f;
- f32 iconSize = zoneSize_ * 0.4f;
- f32 halfIcon = iconSize * 0.5f;
-
- switch (overlay.zone) {
- case DockDropZone::Center: {
- Rect iconRect{cx - halfIcon, cy - halfIcon, iconSize, iconSize};
- renderer.drawRoundedRectOutline(iconRect, iconColor, CornerRadii::all(2.0f), 1.5f);
- break;
- }
-
- case DockDropZone::Left: {
- Rect leftRect{cx - halfIcon, cy - halfIcon, iconSize * 0.4f, iconSize};
- renderer.drawRect(leftRect, iconColor);
- Rect rightRect{cx - halfIcon + iconSize * 0.5f, cy - halfIcon, iconSize * 0.5f, iconSize};
- renderer.drawRoundedRectOutline(rightRect, iconColor, CornerRadii::all(1.0f), 1.0f);
- break;
- }
-
- case DockDropZone::Right: {
- Rect leftRect{cx - halfIcon, cy - halfIcon, iconSize * 0.5f, iconSize};
- renderer.drawRoundedRectOutline(leftRect, iconColor, CornerRadii::all(1.0f), 1.0f);
- Rect rightRect{cx + halfIcon - iconSize * 0.4f, cy - halfIcon, iconSize * 0.4f, iconSize};
- renderer.drawRect(rightRect, iconColor);
- break;
- }
-
- case DockDropZone::Top: {
- Rect topRect{cx - halfIcon, cy - halfIcon, iconSize, iconSize * 0.4f};
- renderer.drawRect(topRect, iconColor);
- Rect bottomRect{cx - halfIcon, cy - halfIcon + iconSize * 0.5f, iconSize, iconSize * 0.5f};
- renderer.drawRoundedRectOutline(bottomRect, iconColor, CornerRadii::all(1.0f), 1.0f);
- break;
- }
-
- case DockDropZone::Bottom: {
- Rect topRect{cx - halfIcon, cy - halfIcon, iconSize, iconSize * 0.5f};
- renderer.drawRoundedRectOutline(topRect, iconColor, CornerRadii::all(1.0f), 1.0f);
- Rect bottomRect{cx - halfIcon, cy + halfIcon - iconSize * 0.4f, iconSize, iconSize * 0.4f};
- renderer.drawRect(bottomRect, iconColor);
- break;
- }
-
- default:
- break;
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/ui/docking/DockZone.hpp b/src/esengine/editor/ui/docking/DockZone.hpp
deleted file mode 100644
index 8c25bfe0a..000000000
--- a/src/esengine/editor/ui/docking/DockZone.hpp
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * @file DockZone.hpp
- * @brief Drop zone detection for docking drag-and-drop
- * @details Handles detection of drop zones and rendering of
- * drop zone indicators and preview.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "DockTypes.hpp"
-#include "../../../ui/core/Types.hpp"
-
-#include <glm/glm.hpp>
-
-#include <vector>
-
-namespace esengine::ui {
-
-// Forward declarations
-class DockNode;
-class DockPanel;
-class DockArea;
-class UIBatchRenderer;
-
-// =============================================================================
-// DockDropTarget
-// =============================================================================
-
-/**
- * @brief Information about a potential drop target
- */
-struct DockDropTarget {
- DockDropZone zone = DockDropZone::None;
- DockNode* targetNode = nullptr;
- Rect previewBounds;
- f32 splitRatio = 0.3f;
-};
-
-// =============================================================================
-// DockZoneOverlay
-// =============================================================================
-
-/**
- * @brief Visual overlay for a dock zone indicator
- */
-struct DockZoneOverlay {
- Rect bounds;
- DockDropZone zone;
- bool hovered = false;
-};
-
-// =============================================================================
-// DockZoneDetector Class
-// =============================================================================
-
-/**
- * @brief Detects drop zones and renders drag feedback
- *
- * @details During a drag operation, the detector:
- * - Tracks the current mouse position
- * - Determines valid drop zones based on cursor location
- * - Calculates preview bounds for visual feedback
- * - Renders zone indicators and drop preview
- */
-class DockZoneDetector {
-public:
- /**
- * @brief Constructs a zone detector for a dock area
- * @param area The owning DockArea
- */
- explicit DockZoneDetector(DockArea* area);
-
- // =========================================================================
- // Drag Operations
- // =========================================================================
-
- /**
- * @brief Begin a drag operation
- * @param panel The panel being dragged
- * @param startPos Initial mouse position
- */
- void beginDrag(DockPanel* panel, const glm::vec2& startPos);
-
- /**
- * @brief Update drag with current mouse position
- * @param pos Current mouse position
- */
- void updateDrag(const glm::vec2& pos);
-
- /**
- * @brief End drag and return the final drop target
- * @return Drop target (zone may be None if cancelled)
- */
- DockDropTarget endDrag();
-
- /**
- * @brief Cancel the current drag operation
- */
- void cancelDrag();
-
- /** @brief Returns true if currently dragging */
- bool isDragging() const { return dragging_; }
-
- /** @brief Gets the panel being dragged */
- DockPanel* getDraggedPanel() const { return draggedPanel_; }
-
- // =========================================================================
- // Target Information
- // =========================================================================
-
- /** @brief Gets the current drop target */
- const DockDropTarget& getCurrentTarget() const { return currentTarget_; }
-
- /** @brief Gets all zone overlays for rendering */
- const std::vector<DockZoneOverlay>& getZoneOverlays() const { return zoneOverlays_; }
-
- // =========================================================================
- // Rendering
- // =========================================================================
-
- /**
- * @brief Render drop zone indicators and preview
- * @param renderer UI batch renderer
- */
- void render(UIBatchRenderer& renderer);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Sets the zone indicator button size */
- void setZoneSize(f32 size) { zoneSize_ = size; }
-
- /** @brief Sets the preview overlay opacity */
- void setPreviewAlpha(f32 alpha) { previewAlpha_ = alpha; }
-
- /** @brief Sets the edge detection threshold (fraction of node size) */
- void setEdgeThreshold(f32 threshold) { edgeThreshold_ = threshold; }
-
-private:
- DockDropZone detectZoneAtPosition(const glm::vec2& pos, DockNode*& outNode);
- void calculateZoneOverlays(DockNode* targetNode);
- Rect calculatePreviewBounds(const DockDropTarget& target);
- void renderZoneOverlays(UIBatchRenderer& renderer);
- void renderDropPreview(UIBatchRenderer& renderer);
- void renderZoneButton(UIBatchRenderer& renderer, const DockZoneOverlay& overlay);
-
- DockArea* area_;
- DockPanel* draggedPanel_ = nullptr;
- bool dragging_ = false;
-
- glm::vec2 dragStartPos_{0.0f};
- glm::vec2 dragCurrentPos_{0.0f};
-
- DockDropTarget currentTarget_;
- std::vector<DockZoneOverlay> zoneOverlays_;
-
- f32 zoneSize_ = 32.0f;
- f32 previewAlpha_ = 0.3f;
- f32 edgeThreshold_ = 0.3f;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/editor/widgets/DrawerPanel.cpp b/src/esengine/editor/widgets/DrawerPanel.cpp
deleted file mode 100644
index 690ab9149..000000000
--- a/src/esengine/editor/widgets/DrawerPanel.cpp
+++ /dev/null
@@ -1,248 +0,0 @@
-/**
- * @file DrawerPanel.cpp
- * @brief Bottom drawer panel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "DrawerPanel.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/icons/Icons.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-#include "../../math/Math.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-DrawerPanel::DrawerPanel(const ui::WidgetId& id, const std::string& title)
- : Widget(id), title_(title) {}
-
-// =============================================================================
-// Configuration
-// =============================================================================
-
-void DrawerPanel::setOpen(bool open) {
- open_ = open;
- invalidateLayout();
-}
-
-void DrawerPanel::setDrawerHeight(f32 height) {
- drawerHeight_ = glm::max(height, MIN_HEIGHT);
- if (open_) {
- invalidateLayout();
- }
-}
-
-void DrawerPanel::setContent(Unique<Widget> content) {
- if (content_) {
- removeChild(content_);
- }
-
- content_ = content.get();
- if (content) {
- addChild(std::move(content));
- }
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 DrawerPanel::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- if (!open_) {
- return {availableWidth, 0.0f};
- }
-
- return {availableWidth, drawerHeight_};
-}
-
-void DrawerPanel::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
- updateContentBounds();
-}
-
-void DrawerPanel::updateContentBounds() {
- if (!content_ || !open_) {
- return;
- }
-
- const ui::Rect& bounds = getBounds();
-
- resizeHandleBounds_ = ui::Rect{
- bounds.x,
- bounds.y - 4.0f,
- bounds.width,
- RESIZE_HANDLE_HEIGHT
- };
-
- ui::Rect contentBounds{
- bounds.x,
- bounds.y + HEADER_HEIGHT,
- bounds.width,
- bounds.height - HEADER_HEIGHT
- };
-
- content_->measure(contentBounds.width, contentBounds.height);
- content_->layout(contentBounds);
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void DrawerPanel::render(ui::UIBatchRenderer& renderer) {
- if (!open_) {
- return;
- }
-
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- const ui::Rect& bounds = getBounds();
-
- constexpr glm::vec4 bgColor{0.118f, 0.118f, 0.118f, 1.0f}; // #1e1e1e
- constexpr glm::vec4 headerBg{0.145f, 0.145f, 0.149f, 1.0f}; // #252526
- constexpr glm::vec4 borderColor{0.235f, 0.235f, 0.235f, 1.0f}; // #3c3c3c
- constexpr glm::vec4 topBorderColor{0.231f, 0.510f, 0.965f, 1.0f}; // #3b82f6
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 iconColor{0.533f, 0.533f, 0.533f, 1.0f}; // #888
- constexpr glm::vec4 iconHoverColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 buttonHoverBg{0.235f, 0.235f, 0.235f, 1.0f}; // #3c3c3c
- constexpr glm::vec4 resizeHandleColor{0.298f, 0.298f, 0.298f, 1.0f}; // #4c4c4c
-
- renderer.drawRect(bounds, bgColor);
-
- ui::Rect topBorder{bounds.x, bounds.y, bounds.width, 2.0f};
- renderer.drawRect(topBorder, topBorderColor);
-
- ui::Rect headerBounds{bounds.x, bounds.y, bounds.width, HEADER_HEIGHT};
- renderer.drawRect(headerBounds, headerBg);
-
- ui::Rect headerBottomBorder{bounds.x, bounds.y + HEADER_HEIGHT - 1.0f, bounds.width, 1.0f};
- renderer.drawRect(headerBottomBorder, borderColor);
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* iconFont = ctx->getIconMSDFFont();
- ui::MSDFFont* textFont = ctx->getDefaultMSDFFont();
-#else
- ui::SystemFont* iconFont = ctx->getIconSystemFont();
- ui::SystemFont* textFont = ctx->getDefaultSystemFont();
-#endif
-
- f32 headerCenterY = bounds.y + HEADER_HEIGHT * 0.5f;
-
- if (iconFont) {
- ui::Rect folderIconBounds{bounds.x + 12.0f, headerCenterY - 7.0f, 14.0f, 14.0f};
- renderer.drawTextInBounds(ui::icons::FolderOpen, folderIconBounds, *iconFont, 14.0f, textColor,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (textFont) {
- ui::Rect titleBounds{bounds.x + 32.0f, headerCenterY - 6.0f, 200.0f, 12.0f};
- renderer.drawTextInBounds(title_, titleBounds, *textFont, 12.0f, textColor,
- ui::HAlign::Left, ui::VAlign::Center);
- }
-
- f32 buttonX = bounds.x + bounds.width - 8.0f;
-
- closeButtonBounds_ = ui::Rect{buttonX - 24.0f, bounds.y + 2.0f, 24.0f, 24.0f};
- if (closeHovered_) {
- renderer.drawRoundedRect(closeButtonBounds_, buttonHoverBg, ui::CornerRadii::all(3.0f));
- }
- if (iconFont) {
- renderer.drawTextInBounds(ui::icons::X, closeButtonBounds_, *iconFont, 14.0f,
- closeHovered_ ? iconHoverColor : iconColor,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (showDockButton_) {
- dockButtonBounds_ = ui::Rect{buttonX - 52.0f, bounds.y + 2.0f, 24.0f, 24.0f};
- if (dockHovered_) {
- renderer.drawRoundedRect(dockButtonBounds_, buttonHoverBg, ui::CornerRadii::all(3.0f));
- }
- if (iconFont) {
- renderer.drawTextInBounds(ui::icons::PanelBottom, dockButtonBounds_, *iconFont, 14.0f,
- dockHovered_ ? iconHoverColor : iconColor,
- ui::HAlign::Center, ui::VAlign::Center);
- }
- }
-
- if (content_) {
- content_->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool DrawerPanel::onMouseDown(const ui::MouseButtonEvent& event) {
- if (!open_ || event.button != ui::MouseButton::Left) {
- return false;
- }
-
- if (closeButtonBounds_.contains(event.x, event.y)) {
- onClose.publish();
- return true;
- }
-
- if (showDockButton_ && dockButtonBounds_.contains(event.x, event.y)) {
- onDockRequested.publish();
- return true;
- }
-
- if (resizeHandleBounds_.contains(event.x, event.y)) {
- resizing_ = true;
- resizeStartY_ = event.y;
- resizeStartHeight_ = drawerHeight_;
- return true;
- }
-
- return false;
-}
-
-bool DrawerPanel::onMouseUp(const ui::MouseButtonEvent& event) {
- if (event.button == ui::MouseButton::Left && resizing_) {
- resizing_ = false;
- return true;
- }
- return false;
-}
-
-bool DrawerPanel::onMouseMove(const ui::MouseMoveEvent& event) {
- closeHovered_ = closeButtonBounds_.contains(event.x, event.y);
- dockHovered_ = showDockButton_ && dockButtonBounds_.contains(event.x, event.y);
-
- if (resizing_) {
- f32 delta = resizeStartY_ - event.y;
- f32 newHeight = resizeStartHeight_ + delta;
-
- ui::UIContext* ctx = getContext();
- if (ctx) {
- f32 maxHeight = ctx->getViewportSize().y * 0.7f;
- newHeight = glm::clamp(newHeight, MIN_HEIGHT, maxHeight);
- }
-
- setDrawerHeight(newHeight);
- return true;
- }
-
- return false;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/DrawerPanel.hpp b/src/esengine/editor/widgets/DrawerPanel.hpp
deleted file mode 100644
index 01671e6de..000000000
--- a/src/esengine/editor/widgets/DrawerPanel.hpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * @file DrawerPanel.hpp
- * @brief Bottom drawer panel that slides up from status bar
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <string>
-
-namespace esengine::editor {
-
-// =============================================================================
-// DrawerPanel Class
-// =============================================================================
-
-class DrawerPanel : public ui::Widget {
-public:
- static constexpr f32 DEFAULT_HEIGHT = 300.0f;
- static constexpr f32 MIN_HEIGHT = 200.0f;
- static constexpr f32 HEADER_HEIGHT = 28.0f;
- static constexpr f32 RESIZE_HANDLE_HEIGHT = 8.0f;
-
- DrawerPanel(const ui::WidgetId& id, const std::string& title);
-
- void setOpen(bool open);
- bool isOpen() const { return open_; }
-
- void setDrawerHeight(f32 height);
- f32 getDrawerHeight() const { return drawerHeight_; }
-
- void setTitle(const std::string& title) { title_ = title; }
- const std::string& getTitle() const { return title_; }
-
- void setContent(Unique<Widget> content);
- Widget* getContent() const { return content_; }
-
- void setShowDockButton(bool show) { showDockButton_ = show; }
- bool isShowDockButton() const { return showDockButton_; }
-
- Signal<void()> onClose;
- Signal<void()> onDockRequested;
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseUp(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
-
-private:
- void updateContentBounds();
-
- std::string title_;
- Widget* content_ = nullptr;
- f32 drawerHeight_ = DEFAULT_HEIGHT;
- bool open_ = false;
- bool showDockButton_ = true;
-
- bool resizing_ = false;
- f32 resizeStartY_ = 0.0f;
- f32 resizeStartHeight_ = 0.0f;
-
- ui::Rect closeButtonBounds_;
- ui::Rect dockButtonBounds_;
- ui::Rect resizeHandleBounds_;
- bool closeHovered_ = false;
- bool dockHovered_ = false;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/EditorRootContainer.cpp b/src/esengine/editor/widgets/EditorRootContainer.cpp
deleted file mode 100644
index 156c4cd29..000000000
--- a/src/esengine/editor/widgets/EditorRootContainer.cpp
+++ /dev/null
@@ -1,287 +0,0 @@
-/**
- * @file EditorRootContainer.cpp
- * @brief Root container implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "EditorRootContainer.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../events/Sink.hpp"
-#include "../../core/Log.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-EditorRootContainer::EditorRootContainer(const ui::WidgetId& id) : Widget(id) {
- auto toolbar = makeUnique<EditorToolbar>(ui::WidgetId(id.path + ".toolbar"));
- toolbar_ = toolbar.get();
- addChild(std::move(toolbar));
-
- auto statusBar = makeUnique<StatusBar>(ui::WidgetId(id.path + ".status_bar"));
- statusBar_ = statusBar.get();
- addChild(std::move(statusBar));
-
- auto assetsDrawer = makeUnique<DrawerPanel>(
- ui::WidgetId(id.path + ".assets_drawer"), "Content Browser");
- assetsDrawer_ = assetsDrawer.get();
- assetsDrawer_->setShowDockButton(true);
- addChild(std::move(assetsDrawer));
-
- auto outputDrawer = makeUnique<DrawerPanel>(
- ui::WidgetId(id.path + ".output_drawer"), "Output");
- outputDrawer_ = outputDrawer.get();
- outputDrawer_->setShowDockButton(false);
- addChild(std::move(outputDrawer));
-
- connections_.add(sink(statusBar_->onAssetsToggle).connect([this]() {
- toggleAssetsDrawer();
- }));
-
- connections_.add(sink(statusBar_->onOutputToggle).connect([this]() {
- toggleOutputDrawer();
- }));
-
- connections_.add(sink(assetsDrawer_->onClose).connect([this]() {
- closeAssetsDrawer();
- }));
-
- connections_.add(sink(outputDrawer_->onClose).connect([this]() {
- closeOutputDrawer();
- }));
-}
-
-// =============================================================================
-// Content Management
-// =============================================================================
-
-void EditorRootContainer::setMainContent(Unique<Widget> content) {
- if (mainContent_) {
- removeChild(mainContent_);
- }
-
- mainContent_ = content.get();
- if (content) {
- addChild(std::move(content));
- }
-
- invalidateLayout();
-}
-
-void EditorRootContainer::setAssetsDrawerContent(Unique<Widget> content) {
- if (assetsDrawer_) {
- assetsDrawer_->setContent(std::move(content));
- }
-}
-
-void EditorRootContainer::setOutputDrawerContent(Unique<Widget> content) {
- if (outputDrawer_) {
- outputDrawer_->setContent(std::move(content));
- }
-}
-
-// =============================================================================
-// Drawer Control
-// =============================================================================
-
-void EditorRootContainer::openAssetsDrawer() {
- if (outputDrawer_->isOpen()) {
- outputDrawer_->setOpen(false);
- statusBar_->setOutputDrawerOpen(false);
- }
- assetsDrawer_->setOpen(true);
- statusBar_->setAssetsDrawerOpen(true);
- invalidateLayout();
-}
-
-void EditorRootContainer::closeAssetsDrawer() {
- assetsDrawer_->setOpen(false);
- statusBar_->setAssetsDrawerOpen(false);
- invalidateLayout();
-}
-
-void EditorRootContainer::toggleAssetsDrawer() {
- ES_LOG_INFO("EditorRootContainer::toggleAssetsDrawer called, isOpen={}", assetsDrawer_->isOpen());
- if (assetsDrawer_->isOpen()) {
- closeAssetsDrawer();
- } else {
- openAssetsDrawer();
- }
- ES_LOG_INFO("After toggle, isOpen={}", assetsDrawer_->isOpen());
-}
-
-bool EditorRootContainer::isAssetsDrawerOpen() const {
- return assetsDrawer_ && assetsDrawer_->isOpen();
-}
-
-void EditorRootContainer::openOutputDrawer() {
- if (assetsDrawer_->isOpen()) {
- assetsDrawer_->setOpen(false);
- statusBar_->setAssetsDrawerOpen(false);
- }
- outputDrawer_->setOpen(true);
- statusBar_->setOutputDrawerOpen(true);
- invalidateLayout();
-}
-
-void EditorRootContainer::closeOutputDrawer() {
- outputDrawer_->setOpen(false);
- statusBar_->setOutputDrawerOpen(false);
- invalidateLayout();
-}
-
-void EditorRootContainer::toggleOutputDrawer() {
- if (outputDrawer_->isOpen()) {
- closeOutputDrawer();
- } else {
- openOutputDrawer();
- }
-}
-
-bool EditorRootContainer::isOutputDrawerOpen() const {
- return outputDrawer_ && outputDrawer_->isOpen();
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 EditorRootContainer::measure(f32 availableWidth, f32 availableHeight) {
- return {availableWidth, availableHeight};
-}
-
-void EditorRootContainer::layout(const ui::Rect& bounds) {
- Widget::layout(bounds);
- updateLayout();
-}
-
-void EditorRootContainer::updateLayout() {
- const ui::Rect& bounds = getBounds();
-
- ui::Rect toolbarBounds{
- bounds.x,
- bounds.y,
- bounds.width,
- EditorToolbar::HEIGHT
- };
- toolbar_->measure(toolbarBounds.width, toolbarBounds.height);
- toolbar_->layout(toolbarBounds);
-
- ui::Rect statusBarBounds{
- bounds.x,
- bounds.y + bounds.height - StatusBar::HEIGHT,
- bounds.width,
- StatusBar::HEIGHT
- };
- statusBar_->measure(statusBarBounds.width, statusBarBounds.height);
- statusBar_->layout(statusBarBounds);
-
- f32 drawerHeight = 0.0f;
- DrawerPanel* activeDrawer = nullptr;
-
- if (assetsDrawer_->isOpen()) {
- activeDrawer = assetsDrawer_;
- drawerHeight = assetsDrawer_->getDrawerHeight();
- } else if (outputDrawer_->isOpen()) {
- activeDrawer = outputDrawer_;
- drawerHeight = outputDrawer_->getDrawerHeight();
- }
-
- if (activeDrawer) {
- ui::Rect drawerBounds{
- bounds.x,
- bounds.y + bounds.height - StatusBar::HEIGHT - drawerHeight,
- bounds.width,
- drawerHeight
- };
- activeDrawer->measure(drawerBounds.width, drawerBounds.height);
- activeDrawer->layout(drawerBounds);
- }
-
- if (!assetsDrawer_->isOpen()) {
- assetsDrawer_->layout(ui::Rect{0, 0, 0, 0});
- }
- if (!outputDrawer_->isOpen()) {
- outputDrawer_->layout(ui::Rect{0, 0, 0, 0});
- }
-
- if (mainContent_) {
- f32 mainContentHeight = bounds.height - EditorToolbar::HEIGHT - StatusBar::HEIGHT - drawerHeight;
- ui::Rect mainBounds{
- bounds.x,
- bounds.y + EditorToolbar::HEIGHT,
- bounds.width,
- mainContentHeight
- };
- mainContent_->measure(mainBounds.width, mainBounds.height);
- mainContent_->layout(mainBounds);
- }
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void EditorRootContainer::renderTree(ui::UIBatchRenderer& renderer) {
- if (!isVisible()) return;
-
- toolbar_->renderTree(renderer);
-
- if (mainContent_) {
- mainContent_->renderTree(renderer);
- }
-
- if (assetsDrawer_->isOpen()) {
- assetsDrawer_->renderTree(renderer);
- }
-
- if (outputDrawer_->isOpen()) {
- outputDrawer_->renderTree(renderer);
- }
-
- statusBar_->renderTree(renderer);
-}
-
-ui::Widget* EditorRootContainer::hitTest(f32 x, f32 y) {
- if (!containsPoint(x, y)) {
- return nullptr;
- }
-
- if (auto* hit = toolbar_->hitTest(x, y)) {
- return hit;
- }
-
- if (auto* hit = statusBar_->hitTest(x, y)) {
- return hit;
- }
-
- if (outputDrawer_->isOpen()) {
- if (auto* hit = outputDrawer_->hitTest(x, y)) {
- return hit;
- }
- }
-
- if (assetsDrawer_->isOpen()) {
- if (auto* hit = assetsDrawer_->hitTest(x, y)) {
- return hit;
- }
- }
-
- if (mainContent_) {
- if (auto* hit = mainContent_->hitTest(x, y)) {
- return hit;
- }
- }
-
- return this;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/EditorRootContainer.hpp b/src/esengine/editor/widgets/EditorRootContainer.hpp
deleted file mode 100644
index ce9de30bb..000000000
--- a/src/esengine/editor/widgets/EditorRootContainer.hpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * @file EditorRootContainer.hpp
- * @brief Root container managing main content, drawers, and status bar
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-#include "EditorToolbar.hpp"
-#include "StatusBar.hpp"
-#include "DrawerPanel.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// EditorRootContainer Class
-// =============================================================================
-
-class EditorRootContainer : public ui::Widget {
-public:
- explicit EditorRootContainer(const ui::WidgetId& id);
-
- void setMainContent(Unique<Widget> content);
- Widget* getMainContent() const { return mainContent_; }
-
- void setAssetsDrawerContent(Unique<Widget> content);
- void setOutputDrawerContent(Unique<Widget> content);
-
- void openAssetsDrawer();
- void closeAssetsDrawer();
- void toggleAssetsDrawer();
- bool isAssetsDrawerOpen() const;
-
- void openOutputDrawer();
- void closeOutputDrawer();
- void toggleOutputDrawer();
- bool isOutputDrawerOpen() const;
-
- EditorToolbar* getToolbar() const { return toolbar_; }
- StatusBar* getStatusBar() const { return statusBar_; }
- DrawerPanel* getAssetsDrawer() const { return assetsDrawer_; }
- DrawerPanel* getOutputDrawer() const { return outputDrawer_; }
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const ui::Rect& bounds) override;
- void renderTree(ui::UIBatchRenderer& renderer) override;
- Widget* hitTest(f32 x, f32 y) override;
-
-private:
- void updateLayout();
-
- EditorToolbar* toolbar_ = nullptr;
- Widget* mainContent_ = nullptr;
- StatusBar* statusBar_ = nullptr;
- DrawerPanel* assetsDrawer_ = nullptr;
- DrawerPanel* outputDrawer_ = nullptr;
- ConnectionHolder connections_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/EditorToolbar.cpp b/src/esengine/editor/widgets/EditorToolbar.cpp
deleted file mode 100644
index 34b550d6a..000000000
--- a/src/esengine/editor/widgets/EditorToolbar.cpp
+++ /dev/null
@@ -1,226 +0,0 @@
-/**
- * @file EditorToolbar.cpp
- * @brief Editor toolbar implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "EditorToolbar.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/icons/Icons.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-
-namespace esengine::editor {
-
-namespace icons = ui::icons;
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-EditorToolbar::EditorToolbar(const ui::WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// State Control
-// =============================================================================
-
-void EditorToolbar::play() {
- if (state_ != PlayState::Playing) {
- state_ = PlayState::Playing;
- onPlay.publish();
- }
-}
-
-void EditorToolbar::pause() {
- if (state_ == PlayState::Playing) {
- state_ = PlayState::Paused;
- onPause.publish();
- }
-}
-
-void EditorToolbar::stop() {
- if (state_ != PlayState::Stopped) {
- state_ = PlayState::Stopped;
- onStop.publish();
- }
-}
-
-void EditorToolbar::startWebPreview(const std::string& directory) {
- if (previewServer_.isRunning()) {
- previewServer_.stop();
- }
- if (previewServer_.start(directory)) {
- WebPreviewServer::openInBrowser(previewServer_.getUrl());
- }
-}
-
-void EditorToolbar::stopWebPreview() {
- previewServer_.stop();
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 EditorToolbar::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
- return {availableWidth, HEIGHT};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void EditorToolbar::render(ui::UIBatchRenderer& renderer) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- const ui::Rect& bounds = getBounds();
- updateButtonBounds();
-
- constexpr glm::vec4 bgColor{0.145f, 0.145f, 0.149f, 1.0f};
- constexpr glm::vec4 borderColor{0.235f, 0.235f, 0.235f, 1.0f};
- constexpr glm::vec4 buttonBg{0.235f, 0.235f, 0.235f, 1.0f};
- constexpr glm::vec4 buttonHover{0.3f, 0.3f, 0.3f, 1.0f};
- constexpr glm::vec4 playingBg{0.231f, 0.510f, 0.965f, 1.0f};
- constexpr glm::vec4 pausedBg{0.988f, 0.722f, 0.067f, 1.0f};
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f};
-
- renderer.drawRect(bounds, bgColor);
-
- ui::Rect bottomBorder{bounds.x, bounds.y + bounds.height - 1.0f, bounds.width, 1.0f};
- renderer.drawRect(bottomBorder, borderColor);
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* iconFont = ctx->getIconMSDFFont();
-#else
- ui::SystemFont* iconFont = ctx->getIconSystemFont();
-#endif
- if (!iconFont) return;
-
- auto drawButton = [&](const ButtonState& btn, const std::string& icon, bool active, const glm::vec4& activeBg) {
- glm::vec4 bg = active ? activeBg : (btn.hovered ? buttonHover : buttonBg);
- renderer.drawRoundedRect(btn.bounds, bg, ui::CornerRadii::all(4.0f));
- renderer.drawTextInBounds(icon, btn.bounds, *iconFont, 16.0f, textColor,
- ui::HAlign::Center, ui::VAlign::Center);
- };
-
- bool playing = state_ == PlayState::Playing;
- bool paused = state_ == PlayState::Paused;
- bool previewing = previewServer_.isRunning();
-
- 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);
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-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();
- } else if (state_ == PlayState::Stopped) {
- play();
- }
- return true;
- }
-
- if (pauseButton_.bounds.contains(event.x, event.y)) {
- if (state_ == PlayState::Playing) {
- pause();
- } else if (state_ == PlayState::Paused) {
- play();
- }
- return true;
- }
-
- if (stopButton_.bounds.contains(event.x, event.y)) {
- stop();
- return true;
- }
-
- if (webPreviewButton_.bounds.contains(event.x, event.y)) {
- onWebPreview.publish();
- return true;
- }
-
- return false;
-}
-
-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);
- webPreviewButton_.hovered = webPreviewButton_.bounds.contains(event.x, event.y);
- return false;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void EditorToolbar::updateButtonBounds() {
- const ui::Rect& bounds = getBounds();
-
- constexpr f32 buttonSize = 28.0f;
- constexpr f32 buttonGap = 4.0f;
- constexpr f32 groupWidth = buttonSize * 3 + buttonGap * 2;
- constexpr f32 padding = 8.0f;
-
- 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};
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/EditorToolbar.hpp b/src/esengine/editor/widgets/EditorToolbar.hpp
deleted file mode 100644
index 45cf13e03..000000000
--- a/src/esengine/editor/widgets/EditorToolbar.hpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * @file EditorToolbar.hpp
- * @brief Editor toolbar with play/pause/stop controls
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-#include "../preview/WebPreviewServer.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// PlayState Enum
-// =============================================================================
-
-enum class PlayState : u8 {
- Stopped,
- Playing,
- Paused
-};
-
-enum class ViewMode : u8 {
- Mode3D,
- Mode2D
-};
-
-// =============================================================================
-// EditorToolbar Class
-// =============================================================================
-
-class EditorToolbar : public ui::Widget {
-public:
- static constexpr f32 HEIGHT = 40.0f;
-
- explicit EditorToolbar(const ui::WidgetId& id);
-
- PlayState getPlayState() const { return state_; }
- bool isPlaying() const { return state_ == PlayState::Playing; }
- bool isPaused() const { return state_ == PlayState::Paused; }
- bool isStopped() const { return state_ == PlayState::Stopped; }
-
- void play();
- void pause();
- void stop();
-
- Signal<void()> onPlay;
- Signal<void()> onPause;
- Signal<void()> onStop;
- Signal<void()> onWebPreview;
- Signal<void()> onSave;
- Signal<void()> onNewScene;
-
- void startWebPreview(const std::string& directory);
- void stopWebPreview();
- bool isWebPreviewRunning() const { return previewServer_.isRunning(); }
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
-
-private:
- void updateButtonBounds();
-
- PlayState state_ = PlayState::Stopped;
-
- struct ButtonState {
- ui::Rect bounds;
- bool hovered = false;
- };
-
- ButtonState newSceneButton_;
- ButtonState saveButton_;
- ButtonState playButton_;
- ButtonState pauseButton_;
- ButtonState stopButton_;
- ButtonState webPreviewButton_;
-
- WebPreviewServer previewServer_;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/SceneToolbar.cpp b/src/esengine/editor/widgets/SceneToolbar.cpp
deleted file mode 100644
index 13b532a60..000000000
--- a/src/esengine/editor/widgets/SceneToolbar.cpp
+++ /dev/null
@@ -1,206 +0,0 @@
-/**
- * @file SceneToolbar.cpp
- * @brief Scene view toolbar implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "SceneToolbar.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/icons/Icons.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-
-namespace esengine::editor {
-
-namespace icons = ui::icons;
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-SceneToolbar::SceneToolbar(const ui::WidgetId& id)
- : Widget(id) {
- setHeight(ui::SizeValue::px(HEIGHT));
-}
-
-// =============================================================================
-// State Setters
-// =============================================================================
-
-void SceneToolbar::setViewMode(ViewMode mode) {
- if (viewMode_ != mode) {
- viewMode_ = mode;
- onViewModeChanged.publish(mode);
- }
-}
-
-void SceneToolbar::setGridVisible(bool visible) {
- if (gridVisible_ != visible) {
- gridVisible_ = visible;
- onGridVisibilityChanged.publish(visible);
- }
-}
-
-void SceneToolbar::setGizmosVisible(bool visible) {
- if (gizmosVisible_ != visible) {
- gizmosVisible_ = visible;
- onGizmosVisibilityChanged.publish(visible);
- }
-}
-
-void SceneToolbar::setGizmoMode(GizmoMode mode) {
- if (gizmoMode_ != mode) {
- gizmoMode_ = mode;
- onGizmoModeChanged.publish(mode);
- }
-}
-
-void SceneToolbar::setStatsVisible(bool visible) {
- if (stats_visible_ != visible) {
- stats_visible_ = visible;
- onStatsVisibilityChanged.publish(visible);
- }
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void SceneToolbar::render(ui::UIBatchRenderer& renderer) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- const ui::Rect& bounds = getBounds();
- updateButtonBounds();
-
- constexpr glm::vec4 bgColor{0.12f, 0.12f, 0.14f, 0.95f};
- constexpr glm::vec4 borderColor{0.2f, 0.2f, 0.22f, 1.0f};
- constexpr glm::vec4 buttonBg{0.2f, 0.2f, 0.22f, 1.0f};
- constexpr glm::vec4 buttonHover{0.28f, 0.28f, 0.30f, 1.0f};
- constexpr glm::vec4 activeBg{0.3f, 0.5f, 0.8f, 0.8f};
- constexpr glm::vec4 textColor{0.85f, 0.85f, 0.85f, 1.0f};
-
- renderer.drawRect(bounds, bgColor);
- renderer.drawRect({bounds.x, bounds.y + bounds.height - 1.0f, bounds.width, 1.0f}, borderColor);
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* iconFont = ctx->getIconMSDFFont();
-#else
- ui::SystemFont* iconFont = ctx->getIconSystemFont();
-#endif
- if (!iconFont) return;
-
- auto drawButton = [&](const ui::Rect& btnBounds, const char* icon, bool active, bool hovered) {
- glm::vec4 bg = active ? activeBg : (hovered ? buttonHover : buttonBg);
- renderer.drawRoundedRect(btnBounds, bg, ui::CornerRadii::all(4.0f));
- renderer.drawTextInBounds(icon, btnBounds, *iconFont, 16.0f, textColor,
- ui::HAlign::Center, ui::VAlign::Center);
- };
-
- drawButton(viewMode2DButtonBounds_, icons::Square, viewMode_ == ViewMode::Mode2D, hoveredButton_ == 0);
- drawButton(viewMode3DButtonBounds_, icons::Box, viewMode_ == ViewMode::Mode3D, hoveredButton_ == 1);
-
- f32 separatorX = viewMode3DButtonBounds_.x + viewMode3DButtonBounds_.width + 8.0f;
- renderer.drawRect({separatorX, bounds.y + 6.0f, 1.0f, bounds.height - 12.0f}, glm::vec4(0.3f, 0.3f, 0.32f, 1.0f));
-
- drawButton(gridButtonBounds_, icons::Grid, gridVisible_, hoveredButton_ == 2);
- drawButton(gizmosButtonBounds_, icons::Move3d, gizmosVisible_, hoveredButton_ == 3);
-
- f32 separator2X = gizmosButtonBounds_.x + gizmosButtonBounds_.width + 8.0f;
- renderer.drawRect({separator2X, bounds.y + 6.0f, 1.0f, bounds.height - 12.0f}, glm::vec4(0.3f, 0.3f, 0.32f, 1.0f));
-
- drawButton(translateButtonBounds_, icons::Move, gizmoMode_ == GizmoMode::Translate, hoveredButton_ == 4);
- drawButton(rotateButtonBounds_, icons::Rotate3d, gizmoMode_ == GizmoMode::Rotate, hoveredButton_ == 5);
- drawButton(scaleButtonBounds_, icons::Scale3d, gizmoMode_ == GizmoMode::Scale, hoveredButton_ == 6);
-
- drawButton(stats_button_bounds_, icons::Info, stats_visible_, hoveredButton_ == 7);
-}
-
-// =============================================================================
-// Input Handling
-// =============================================================================
-
-bool SceneToolbar::onMouseDown(const ui::MouseButtonEvent& event) {
- if (event.button != ui::MouseButton::Left) {
- return false;
- }
-
- updateButtonBounds();
- i32 btn = getHoveredButton(event.x, event.y);
-
- switch (btn) {
- case 0: setViewMode(ViewMode::Mode2D); return true;
- case 1: setViewMode(ViewMode::Mode3D); return true;
- case 2: setGridVisible(!gridVisible_); return true;
- case 3: setGizmosVisible(!gizmosVisible_); return true;
- case 4: setGizmoMode(GizmoMode::Translate); return true;
- case 5: setGizmoMode(GizmoMode::Rotate); return true;
- case 6: setGizmoMode(GizmoMode::Scale); return true;
- case 7: setStatsVisible(!stats_visible_); return true;
- }
-
- return false;
-}
-
-bool SceneToolbar::onMouseMove(const ui::MouseMoveEvent& event) {
- updateButtonBounds();
- hoveredButton_ = getHoveredButton(event.x, event.y);
- return false;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void SceneToolbar::updateButtonBounds() {
- const ui::Rect& bounds = getBounds();
-
- constexpr f32 btnSize = 24.0f;
- constexpr f32 padding = 4.0f;
- constexpr f32 groupGap = 16.0f;
-
- f32 y = bounds.y + (bounds.height - btnSize) * 0.5f;
- f32 x = bounds.x + padding;
-
- viewMode2DButtonBounds_ = {x, y, btnSize, btnSize};
- x += btnSize + 2.0f;
- viewMode3DButtonBounds_ = {x, y, btnSize, btnSize};
- x += btnSize + groupGap;
-
- gridButtonBounds_ = {x, y, btnSize, btnSize};
- x += btnSize + 2.0f;
- gizmosButtonBounds_ = {x, y, btnSize, btnSize};
- x += btnSize + groupGap;
-
- translateButtonBounds_ = {x, y, btnSize, btnSize};
- x += btnSize + 2.0f;
- rotateButtonBounds_ = {x, y, btnSize, btnSize};
- x += btnSize + 2.0f;
- scaleButtonBounds_ = {x, y, btnSize, btnSize};
-
- stats_button_bounds_ = {bounds.x + bounds.width - btnSize - padding, y, btnSize, btnSize};
-}
-
-i32 SceneToolbar::getHoveredButton(f32 x, f32 y) const {
- if (viewMode2DButtonBounds_.contains(x, y)) return 0;
- if (viewMode3DButtonBounds_.contains(x, y)) return 1;
- if (gridButtonBounds_.contains(x, y)) return 2;
- if (gizmosButtonBounds_.contains(x, y)) return 3;
- if (translateButtonBounds_.contains(x, y)) return 4;
- if (rotateButtonBounds_.contains(x, y)) return 5;
- if (scaleButtonBounds_.contains(x, y)) return 6;
- if (stats_button_bounds_.contains(x, y)) return 7;
- return -1;
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/SceneToolbar.hpp b/src/esengine/editor/widgets/SceneToolbar.hpp
deleted file mode 100644
index 9c64bf699..000000000
--- a/src/esengine/editor/widgets/SceneToolbar.hpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * @file SceneToolbar.hpp
- * @brief Scene view toolbar for view controls and gizmo modes
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-#include "../gizmo/TransformGizmo.hpp"
-#include "EditorToolbar.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// SceneToolbar Class
-// =============================================================================
-
-/**
- * @brief Toolbar embedded in SceneViewPanel for view and gizmo controls
- */
-class SceneToolbar : public ui::Widget {
-public:
- static constexpr f32 HEIGHT = 32.0f;
-
- explicit SceneToolbar(const ui::WidgetId& id);
- ~SceneToolbar() override = default;
-
- // =========================================================================
- // State Accessors
- // =========================================================================
-
- ViewMode getViewMode() const { return viewMode_; }
- void setViewMode(ViewMode mode);
-
- bool isGridVisible() const { return gridVisible_; }
- void setGridVisible(bool visible);
-
- bool isGizmosVisible() const { return gizmosVisible_; }
- void setGizmosVisible(bool visible);
-
- GizmoMode getGizmoMode() const { return gizmoMode_; }
- void setGizmoMode(GizmoMode mode);
-
- bool isStatsVisible() const { return stats_visible_; }
- void setStatsVisible(bool visible);
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- Signal<void(ViewMode)> onViewModeChanged;
- Signal<void(bool)> onGridVisibilityChanged;
- Signal<void(bool)> onGizmosVisibilityChanged;
- Signal<void(GizmoMode)> onGizmoModeChanged;
- Signal<void(bool)> onStatsVisibilityChanged;
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
- bool onMouseMove(const ui::MouseMoveEvent& event) override;
-
-private:
- void updateButtonBounds();
- i32 getHoveredButton(f32 x, f32 y) const;
-
- ViewMode viewMode_ = ViewMode::Mode3D;
- bool gridVisible_ = true;
- bool gizmosVisible_ = true;
- bool stats_visible_ = false;
- GizmoMode gizmoMode_ = GizmoMode::Translate;
-
- ui::Rect viewMode2DButtonBounds_;
- ui::Rect viewMode3DButtonBounds_;
- ui::Rect gridButtonBounds_;
- ui::Rect gizmosButtonBounds_;
- ui::Rect translateButtonBounds_;
- ui::Rect rotateButtonBounds_;
- ui::Rect scaleButtonBounds_;
- ui::Rect stats_button_bounds_;
-
- i32 hoveredButton_ = -1;
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/StatusBar.cpp b/src/esengine/editor/widgets/StatusBar.cpp
deleted file mode 100644
index 6891ce423..000000000
--- a/src/esengine/editor/widgets/StatusBar.cpp
+++ /dev/null
@@ -1,276 +0,0 @@
-/**
- * @file StatusBar.cpp
- * @brief Editor status bar implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "StatusBar.hpp"
-#include "../../ui/UIContext.hpp"
-#include "../../ui/rendering/UIBatchRenderer.hpp"
-#include "../../ui/icons/Icons.hpp"
-#include "../../core/Log.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../../ui/font/MSDFFont.hpp"
-#endif
-
-#include "../../ui/font/SystemFont.hpp"
-
-namespace esengine::editor {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-StatusBar::StatusBar(const ui::WidgetId& id) : Widget(id) {
- setHeight(ui::SizeValue::px(HEIGHT));
- setWidth(ui::SizeValue::flex(1.0f));
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 StatusBar::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
- return {availableWidth, HEIGHT};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void StatusBar::render(ui::UIBatchRenderer& renderer) {
- ui::UIContext* ctx = getContext();
- if (!ctx) return;
-
- const ui::Rect& bounds = getBounds();
-
- constexpr glm::vec4 bgColor{0.176f, 0.176f, 0.176f, 1.0f}; // #2d2d2d
- constexpr glm::vec4 borderColor{0.102f, 0.102f, 0.102f, 1.0f}; // #1a1a1a
- constexpr glm::vec4 dividerColor{0.267f, 0.267f, 0.267f, 1.0f}; // #444
- constexpr glm::vec4 textColor{0.533f, 0.533f, 0.533f, 1.0f}; // #888
- constexpr glm::vec4 textHoverColor{0.8f, 0.8f, 0.8f, 1.0f}; // #ccc
- constexpr glm::vec4 activeColor{1.0f, 1.0f, 1.0f, 1.0f}; // #fff
- constexpr glm::vec4 activeBg{0.294f, 0.294f, 0.294f, 1.0f}; // #4a4a4a
- constexpr glm::vec4 activeIndicator{0.0f, 0.471f, 0.831f, 1.0f}; // #0078d4
- constexpr glm::vec4 hoverBg{1.0f, 1.0f, 1.0f, 0.05f};
- constexpr glm::vec4 assetsBtnBg{0.227f, 0.227f, 0.227f, 1.0f}; // #3a3a3a
-
- renderer.drawRect(bounds, bgColor);
-
- ui::Rect topBorder{bounds.x, bounds.y, bounds.width, 1.0f};
- renderer.drawRect(topBorder, borderColor);
-
- updateButtonRects();
-
-#if ES_FEATURE_SDF_FONT
- ui::MSDFFont* iconFont = ctx->getIconMSDFFont();
- ui::MSDFFont* textFont = ctx->getDefaultMSDFFont();
-#else
- ui::SystemFont* iconFont = ctx->getIconSystemFont();
- ui::SystemFont* textFont = ctx->getDefaultSystemFont();
-#endif
-
- if (assetsButton_.bounds.width > 0) {
- glm::vec4 btnBg = assetsDrawerOpen_ ? activeBg : assetsBtnBg;
- glm::vec4 btnText = assetsDrawerOpen_ ? activeColor : textHoverColor;
-
- if (assetsButton_.hovered && !assetsDrawerOpen_) {
- btnBg = glm::vec4(0.267f, 0.267f, 0.267f, 1.0f);
- }
-
- renderer.drawRect(assetsButton_.bounds, btnBg);
-
- ui::Rect rightBorder{
- assetsButton_.bounds.x + assetsButton_.bounds.width - 1.0f,
- assetsButton_.bounds.y,
- 1.0f,
- assetsButton_.bounds.height
- };
- renderer.drawRect(rightBorder, borderColor);
-
- if (assetsDrawerOpen_) {
- ui::Rect indicator{
- assetsButton_.bounds.x,
- assetsButton_.bounds.y + assetsButton_.bounds.height - 2.0f,
- assetsButton_.bounds.width,
- 2.0f
- };
- renderer.drawRect(indicator, activeIndicator);
- }
-
- f32 iconX = assetsButton_.bounds.x + 10.0f;
- f32 centerY = assetsButton_.bounds.y + assetsButton_.bounds.height * 0.5f;
-
- if (iconFont) {
- ui::Rect iconBounds{iconX, centerY - 7.0f, 14.0f, 14.0f};
- renderer.drawTextInBounds(ui::icons::FolderOpen, iconBounds, *iconFont, 14.0f, btnText,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (textFont) {
- f32 textX = iconX + 20.0f;
- ui::Rect textBounds{textX, centerY - 6.0f, 50.0f, 12.0f};
- renderer.drawTextInBounds("Assets", textBounds, *textFont, 11.0f, btnText,
- ui::HAlign::Left, ui::VAlign::Center);
- }
-
- if (iconFont) {
- const char* chevron = assetsDrawerOpen_ ? ui::icons::ChevronDown : ui::icons::ChevronUp;
- ui::Rect chevronBounds{assetsButton_.bounds.x + assetsButton_.bounds.width - 18.0f,
- centerY - 6.0f, 12.0f, 12.0f};
- renderer.drawTextInBounds(chevron, chevronBounds, *iconFont, 12.0f, btnText,
- ui::HAlign::Center, ui::VAlign::Center);
- }
- }
-
- f32 dividerX = assetsButton_.bounds.x + assetsButton_.bounds.width + 2.0f;
- ui::Rect divider1{dividerX, bounds.y + 5.0f, 1.0f, 14.0f};
- renderer.drawRect(divider1, dividerColor);
-
- if (outputButton_.bounds.width > 0) {
- glm::vec4 btnBg = outputDrawerOpen_ ? activeBg : glm::vec4(0.0f);
- glm::vec4 btnText = outputDrawerOpen_ ? activeColor : textColor;
-
- if (outputButton_.hovered && !outputDrawerOpen_) {
- btnBg = hoverBg;
- btnText = textHoverColor;
- }
-
- if (btnBg.a > 0.0f) {
- renderer.drawRect(outputButton_.bounds, btnBg);
- }
-
- if (outputDrawerOpen_) {
- ui::Rect indicator{
- outputButton_.bounds.x,
- outputButton_.bounds.y + outputButton_.bounds.height - 2.0f,
- outputButton_.bounds.width,
- 2.0f
- };
- renderer.drawRect(indicator, activeIndicator);
- }
-
- f32 centerY = outputButton_.bounds.y + outputButton_.bounds.height * 0.5f;
-
- if (iconFont) {
- ui::Rect iconBounds{outputButton_.bounds.x + 8.0f, centerY - 6.0f, 12.0f, 12.0f};
- renderer.drawTextInBounds(ui::icons::FileText, iconBounds, *iconFont, 12.0f, btnText,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (textFont) {
- ui::Rect textBounds{outputButton_.bounds.x + 24.0f, centerY - 6.0f, 50.0f, 12.0f};
- renderer.drawTextInBounds("Output", textBounds, *textFont, 11.0f, btnText,
- ui::HAlign::Left, ui::VAlign::Center);
- }
- }
-
- if (layoutButton_.bounds.width > 0 && iconFont) {
- glm::vec4 btnText = layoutButton_.hovered ? textHoverColor : textColor;
- glm::vec4 btnBg = layoutButton_.hovered ? hoverBg : glm::vec4(0.0f);
-
- if (btnBg.a > 0.0f) {
- renderer.drawRect(layoutButton_.bounds, btnBg);
- }
-
- f32 centerY = layoutButton_.bounds.y + layoutButton_.bounds.height * 0.5f;
- ui::Rect iconBounds{layoutButton_.bounds.x + 5.0f, centerY - 7.0f, 14.0f, 14.0f};
- renderer.drawTextInBounds(ui::icons::LayoutGrid, iconBounds, *iconFont, 14.0f, btnText,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- if (textFont) {
- constexpr glm::vec4 saveIconColor{0.29f, 0.87f, 0.5f, 1.0f}; // #4ade80
- f32 rightX = bounds.x + bounds.width - 10.0f;
- f32 centerY = bounds.y + bounds.height * 0.5f;
-
- if (iconFont) {
- ui::Rect saveIconBounds{rightX - 80.0f, centerY - 6.0f, 12.0f, 12.0f};
- renderer.drawTextInBounds(ui::icons::Save, saveIconBounds, *iconFont, 12.0f, saveIconColor,
- ui::HAlign::Center, ui::VAlign::Center);
- }
-
- ui::Rect saveTextBounds{rightX - 65.0f, centerY - 6.0f, 60.0f, 12.0f};
- renderer.drawTextInBounds("Saved", saveTextBounds, *textFont, 11.0f, textColor,
- ui::HAlign::Left, ui::VAlign::Center);
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool StatusBar::onMouseDown(const ui::MouseButtonEvent& event) {
- ES_LOG_DEBUG("StatusBar::onMouseDown at ({}, {})", event.x, event.y);
- ES_LOG_DEBUG(" StatusBar bounds: ({}, {}, {}, {})",
- getBounds().x, getBounds().y, getBounds().width, getBounds().height);
- ES_LOG_DEBUG(" AssetsButton bounds: ({}, {}, {}, {})",
- assetsButton_.bounds.x, assetsButton_.bounds.y,
- assetsButton_.bounds.width, assetsButton_.bounds.height);
-
- if (event.button != ui::MouseButton::Left) {
- return false;
- }
-
- if (assetsButton_.bounds.contains(event.x, event.y)) {
- ES_LOG_INFO("StatusBar: Assets button clicked!");
- onAssetsToggle.publish();
- return true;
- }
-
- if (outputButton_.bounds.contains(event.x, event.y)) {
- ES_LOG_INFO("StatusBar: Output button clicked!");
- onOutputToggle.publish();
- return true;
- }
-
- if (layoutButton_.bounds.contains(event.x, event.y)) {
- ES_LOG_INFO("StatusBar: Layout button clicked!");
- onResetLayout.publish();
- return true;
- }
-
- return false;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void StatusBar::updateButtonRects() {
- const ui::Rect& bounds = getBounds();
-
- constexpr f32 ASSETS_BTN_WIDTH = 100.0f;
- constexpr f32 OUTPUT_BTN_WIDTH = 70.0f;
- constexpr f32 LAYOUT_BTN_WIDTH = 24.0f;
-
- assetsButton_.bounds = ui::Rect{
- bounds.x,
- bounds.y,
- ASSETS_BTN_WIDTH,
- bounds.height
- };
-
- outputButton_.bounds = ui::Rect{
- bounds.x + ASSETS_BTN_WIDTH + 5.0f,
- bounds.y,
- OUTPUT_BTN_WIDTH,
- bounds.height
- };
-
- layoutButton_.bounds = ui::Rect{
- bounds.x + bounds.width - LAYOUT_BTN_WIDTH - 100.0f,
- bounds.y,
- LAYOUT_BTN_WIDTH,
- bounds.height
- };
-}
-
-} // namespace esengine::editor
diff --git a/src/esengine/editor/widgets/StatusBar.hpp b/src/esengine/editor/widgets/StatusBar.hpp
deleted file mode 100644
index e54966584..000000000
--- a/src/esengine/editor/widgets/StatusBar.hpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * @file StatusBar.hpp
- * @brief Editor status bar with drawer toggle buttons
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../ui/widgets/Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <string>
-
-namespace esengine::editor {
-
-// =============================================================================
-// StatusBar Class
-// =============================================================================
-
-class StatusBar : public ui::Widget {
-public:
- static constexpr f32 HEIGHT = 24.0f;
-
- explicit StatusBar(const ui::WidgetId& id);
-
- void setAssetsDrawerOpen(bool open) { assetsDrawerOpen_ = open; }
- void setOutputDrawerOpen(bool open) { outputDrawerOpen_ = open; }
-
- bool isAssetsDrawerOpen() const { return assetsDrawerOpen_; }
- bool isOutputDrawerOpen() const { return outputDrawerOpen_; }
-
- Signal<void()> onAssetsToggle;
- Signal<void()> onOutputToggle;
- Signal<void()> onResetLayout;
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(ui::UIBatchRenderer& renderer) override;
- bool onMouseDown(const ui::MouseButtonEvent& event) override;
-
-private:
- struct ButtonRect {
- ui::Rect bounds;
- bool hovered = false;
- };
-
- void updateButtonRects();
-
- bool assetsDrawerOpen_ = false;
- bool outputDrawerOpen_ = false;
-
- ButtonRect assetsButton_;
- ButtonRect outputButton_;
- ButtonRect layoutButton_;
-
- glm::vec2 lastMousePos_{0.0f};
-};
-
-} // namespace esengine::editor
diff --git a/src/esengine/platform/Platform.hpp b/src/esengine/platform/Platform.hpp
index c386c4c69..51495d9de 100644
--- a/src/esengine/platform/Platform.hpp
+++ b/src/esengine/platform/Platform.hpp
@@ -92,6 +92,20 @@ enum class KeyCode : u32 {
Y = 89, ///< Y key
Z = 90, ///< Z key
+ // Function keys
+ F1 = 112, ///< F1 key
+ F2 = 113, ///< F2 key
+ F3 = 114, ///< F3 key
+ F4 = 115, ///< F4 key
+ F5 = 116, ///< F5 key
+ F6 = 117, ///< F6 key
+ F7 = 118, ///< F7 key
+ F8 = 119, ///< F8 key
+ F9 = 120, ///< F9 key
+ F10 = 121, ///< F10 key
+ F11 = 122, ///< F11 key
+ F12 = 123, ///< F12 key
+
// Modifier keys
LeftShift = 16, ///< Left Shift key
RightShift = 161, ///< Right Shift key
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
index 1f79bfa0b..aee5aeecc 100644
--- a/src/esengine/renderer/Renderer.cpp
+++ b/src/esengine/renderer/Renderer.cpp
@@ -329,6 +329,13 @@ void BatchRenderer2D::init() {
data_->vao->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
data_->shader_handle = resource_manager_.loadEngineShader("batch");
+ if (!data_->shader_handle.isValid()) {
+ ES_LOG_INFO("Using embedded batch shader for Web platform");
+ data_->shader_handle = resource_manager_.createShader(
+ ShaderSources::BATCH_VERTEX,
+ ShaderSources::BATCH_FRAGMENT
+ );
+ }
data_->textureSlots[0] = context_.getWhiteTextureId();
for (u32 i = 1; i < MAX_TEXTURE_SLOTS; ++i) {
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
index 20dfbfe00..40eb5ef9f 100644
--- a/src/esengine/renderer/Shader.hpp
+++ b/src/esengine/renderer/Shader.hpp
@@ -281,6 +281,71 @@ inline const char* COLOR_FRAGMENT = R"(
}
)";
+/**
+ * @brief Vertex shader for batched sprite rendering
+ */
+inline const char* BATCH_VERTEX = R"(#version 300 es
+ layout(location = 0) in vec3 a_position;
+ layout(location = 1) in vec4 a_color;
+ layout(location = 2) in vec2 a_texCoord;
+ layout(location = 3) in float a_texIndex;
+
+ uniform mat4 u_projection;
+
+ out vec4 v_color;
+ out vec2 v_texCoord;
+ out float v_texIndex;
+
+ void main() {
+ gl_Position = u_projection * vec4(a_position, 1.0);
+ v_color = a_color;
+ v_texCoord = a_texCoord;
+ v_texIndex = a_texIndex;
+ }
+)";
+
+/**
+ * @brief Fragment shader for batched sprite rendering
+ */
+inline const char* BATCH_FRAGMENT = R"(#version 300 es
+ precision mediump float;
+
+ in vec4 v_color;
+ in vec2 v_texCoord;
+ in float v_texIndex;
+
+ uniform sampler2D u_textures[16];
+
+ out vec4 fragColor;
+
+ void main() {
+ int index = int(v_texIndex);
+ vec4 texColor = vec4(1.0);
+
+ // WebGL2 requires constant index for sampler arrays
+ switch(index) {
+ case 0: texColor = texture(u_textures[0], v_texCoord); break;
+ case 1: texColor = texture(u_textures[1], v_texCoord); break;
+ case 2: texColor = texture(u_textures[2], v_texCoord); break;
+ case 3: texColor = texture(u_textures[3], v_texCoord); break;
+ case 4: texColor = texture(u_textures[4], v_texCoord); break;
+ case 5: texColor = texture(u_textures[5], v_texCoord); break;
+ case 6: texColor = texture(u_textures[6], v_texCoord); break;
+ case 7: texColor = texture(u_textures[7], v_texCoord); break;
+ case 8: texColor = texture(u_textures[8], v_texCoord); break;
+ case 9: texColor = texture(u_textures[9], v_texCoord); break;
+ case 10: texColor = texture(u_textures[10], v_texCoord); break;
+ case 11: texColor = texture(u_textures[11], v_texCoord); break;
+ case 12: texColor = texture(u_textures[12], v_texCoord); break;
+ case 13: texColor = texture(u_textures[13], v_texCoord); break;
+ case 14: texColor = texture(u_textures[14], v_texCoord); break;
+ case 15: texColor = texture(u_textures[15], v_texCoord); break;
+ }
+
+ fragColor = texColor * v_color;
+ }
+)";
+
} // namespace ShaderSources
} // namespace esengine
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 0ca662ed1..2086b4386 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -112,7 +112,7 @@ ShaderHandle ResourceManager::loadEngineShader(const std::string& name, const st
return cached;
}
- std::string path = PathResolver::editorPath("data/shaders/" + name + ".esshader");
+ std::string path = PathResolver::editorPath("src/esengine/data/shaders/" + name + ".esshader");
ShaderLoader loader;
auto result = loader.loadFromFile(path, platform);
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index ef6a81c76..47606ceed 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -134,7 +134,7 @@ public:
ShaderHandle loadShaderFile(const std::string& path, const std::string& platform = "");
/**
- * @brief Loads an engine shader from data/shaders/ (with caching)
+ * @brief Loads an engine shader from src/esengine/data/shaders/ (with caching)
* @param name Shader name without path or extension (e.g., "grid", "ui")
* @param platform Platform variant (empty for auto-detect)
* @return Handle to the shader, or invalid handle on failure
diff --git a/src/esengine/scripting/ScriptContext.cpp b/src/esengine/scripting/ScriptContext.cpp
deleted file mode 100644
index 1f510a3f7..000000000
--- a/src/esengine/scripting/ScriptContext.cpp
+++ /dev/null
@@ -1,180 +0,0 @@
-/**
- * @file ScriptContext.cpp
- * @brief JavaScript scripting context implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ScriptContext.hpp"
-#include "../core/Log.hpp"
-#include "../platform/FileSystem.hpp"
-
-namespace esengine {
-
-ScriptContext::~ScriptContext() {
- if (initialized_) {
- shutdown();
- }
-}
-
-bool ScriptContext::init() {
- if (initialized_) {
- ES_LOG_WARN("ScriptContext already initialized");
- return true;
- }
-
-#ifdef ES_SCRIPTING_ENABLED
- // Create QuickJS runtime
- rt_ = JS_NewRuntime();
- if (!rt_) {
- lastError_ = "Failed to create QuickJS runtime";
- ES_LOG_ERROR("{}", lastError_);
- return false;
- }
-
- // Create JavaScript context
- ctx_ = JS_NewContext(rt_);
- if (!ctx_) {
- lastError_ = "Failed to create QuickJS context";
- ES_LOG_ERROR("{}", lastError_);
- JS_FreeRuntime(rt_);
- rt_ = nullptr;
- return false;
- }
-
- initialized_ = true;
- ES_LOG_INFO("ScriptContext initialized (QuickJS)");
- return true;
-#else
- lastError_ = "Scripting not enabled on this platform";
- ES_LOG_WARN("{}", lastError_);
- return false;
-#endif
-}
-
-void ScriptContext::shutdown() {
- if (!initialized_) {
- return;
- }
-
-#ifdef ES_SCRIPTING_ENABLED
- if (ctx_) {
- JS_FreeContext(ctx_);
- ctx_ = nullptr;
- }
-
- if (rt_) {
- JS_FreeRuntime(rt_);
- rt_ = nullptr;
- }
-
- ES_LOG_INFO("ScriptContext shutdown");
-#endif
-
- initialized_ = false;
- lastError_.clear();
-}
-
-bool ScriptContext::evalString(const std::string& code, const std::string& filename) {
- if (!initialized_) {
- lastError_ = "ScriptContext not initialized";
- ES_LOG_ERROR("{}", lastError_);
- return false;
- }
-
- clearError();
-
-#ifdef ES_SCRIPTING_ENABLED
- // Execute JavaScript code
- JSValue result = JS_Eval(
- ctx_,
- code.c_str(),
- code.size(),
- filename.c_str(),
- JS_EVAL_TYPE_GLOBAL
- );
-
- // Check for exceptions
- if (JS_IsException(result)) {
- captureException();
- JS_FreeValue(ctx_, result);
- return false;
- }
-
- // Free result value
- JS_FreeValue(ctx_, result);
-
- ES_LOG_DEBUG("Script executed: {}", filename);
- return true;
-#else
- lastError_ = "Scripting not enabled on this platform";
- return false;
-#endif
-}
-
-bool ScriptContext::evalFile(const std::string& path) {
- if (!initialized_) {
- lastError_ = "ScriptContext not initialized";
- ES_LOG_ERROR("{}", lastError_);
- return false;
- }
-
- // Read file contents using FileSystem
- std::string code = FileSystem::readTextFile(path);
- if (code.empty()) {
- lastError_ = "Failed to read script file or file is empty: " + path;
- ES_LOG_ERROR("{}", lastError_);
- return false;
- }
-
- // Execute code with file path as filename
- return evalString(code, path);
-}
-
-#ifdef ES_SCRIPTING_ENABLED
-void ScriptContext::captureException() {
- if (!ctx_) {
- lastError_ = "No context available";
- return;
- }
-
- // Get exception object
- JSValue exception = JS_GetException(ctx_);
- if (JS_IsNull(exception)) {
- lastError_ = "Unknown JavaScript error";
- JS_FreeValue(ctx_, exception);
- return;
- }
-
- // Convert exception to string
- const char* errorStr = JS_ToCString(ctx_, exception);
- if (errorStr) {
- lastError_ = errorStr;
- JS_FreeCString(ctx_, errorStr);
- } else {
- lastError_ = "Failed to convert exception to string";
- }
-
- // Try to get stack trace if available
- JSValue stack = JS_GetPropertyStr(ctx_, exception, "stack");
- if (!JS_IsUndefined(stack)) {
- const char* stackStr = JS_ToCString(ctx_, stack);
- if (stackStr) {
- lastError_ += "\nStack trace:\n";
- lastError_ += stackStr;
- JS_FreeCString(ctx_, stackStr);
- }
- JS_FreeValue(ctx_, stack);
- }
-
- JS_FreeValue(ctx_, exception);
-
- ES_LOG_ERROR("JavaScript error: {}", lastError_);
-}
-#endif
-
-} // namespace esengine
diff --git a/src/esengine/scripting/ScriptContext.hpp b/src/esengine/scripting/ScriptContext.hpp
deleted file mode 100644
index d15b95519..000000000
--- a/src/esengine/scripting/ScriptContext.hpp
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * @file ScriptContext.hpp
- * @brief JavaScript scripting context wrapper for QuickJS
- * @details Provides RAII-based JavaScript runtime management for native platforms.
- * Web platforms use Emscripten bindings instead.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../core/Types.hpp"
-#include <string>
-
-#ifdef ES_SCRIPTING_ENABLED
- #include <quickjs.h>
-#endif
-
-namespace esengine {
-
-/**
- * @brief JavaScript execution context using QuickJS
- *
- * @details Manages QuickJS runtime and context lifecycle. Only available
- * on native platforms (Windows/Linux/macOS). Web platforms use
- * browser's native JavaScript engine via Emscripten bindings.
- *
- * Usage:
- * @code
- * ScriptContext ctx;
- * ctx.init();
- * if (ctx.evalString("console.log('Hello from JavaScript!')")) {
- * // Script executed successfully
- * } else {
- * ES_LOG_ERROR("Script error: {}", ctx.getLastError());
- * }
- * ctx.shutdown();
- * @endcode
- */
-class ScriptContext {
-public:
- ScriptContext() = default;
- ~ScriptContext();
-
- ScriptContext(const ScriptContext&) = delete;
- ScriptContext& operator=(const ScriptContext&) = delete;
-
- /**
- * @brief Initialize JavaScript runtime and context
- * @return true if successful, false on error
- */
- bool init();
-
- /**
- * @brief Shutdown JavaScript runtime and free resources
- */
- void shutdown();
-
- /**
- * @brief Execute JavaScript code from a file
- * @param path File path to JavaScript source
- * @return true if execution succeeded, false on error
- */
- bool evalFile(const std::string& path);
-
- /**
- * @brief Execute JavaScript code from a string
- * @param code JavaScript source code
- * @param filename Optional filename for error messages (default: "<eval>")
- * @return true if execution succeeded, false on error
- */
- bool evalString(const std::string& code, const std::string& filename = "<eval>");
-
- /**
- * @brief Get last error message
- * @return Error string, empty if no error
- */
- std::string getLastError() const { return lastError_; }
-
- /**
- * @brief Check if an error occurred
- * @return true if there's an error, false otherwise
- */
- bool hasError() const { return !lastError_.empty(); }
-
- /**
- * @brief Clear error state
- */
- void clearError() { lastError_.clear(); }
-
- /**
- * @brief Check if context is initialized
- * @return true if initialized, false otherwise
- */
- bool isInitialized() const { return initialized_; }
-
-#ifdef ES_SCRIPTING_ENABLED
- /**
- * @brief Get QuickJS context (for advanced bindings)
- * @return JSContext pointer or nullptr if not initialized
- */
- JSContext* getJSContext() { return ctx_; }
-
- /**
- * @brief Get QuickJS runtime (for advanced bindings)
- * @return JSRuntime pointer or nullptr if not initialized
- */
- JSRuntime* getJSRuntime() { return rt_; }
-#endif
-
-private:
- /**
- * @brief Extract error message from QuickJS exception
- */
- void captureException();
-
- bool initialized_ = false;
- std::string lastError_;
-
-#ifdef ES_SCRIPTING_ENABLED
- JSRuntime* rt_ = nullptr;
- JSContext* ctx_ = nullptr;
-#endif
-};
-
-} // namespace esengine
diff --git a/src/esengine/scripting/ScriptValue.cpp b/src/esengine/scripting/ScriptValue.cpp
deleted file mode 100644
index 7c3e96256..000000000
--- a/src/esengine/scripting/ScriptValue.cpp
+++ /dev/null
@@ -1,456 +0,0 @@
-/**
- * @file ScriptValue.cpp
- * @brief RAII wrapper for QuickJS values implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ScriptValue.hpp"
-#include "../core/Log.hpp"
-
-namespace esengine {
-
-// =============================================================================
-// Constructors and Destructor
-// =============================================================================
-
-ScriptValue::ScriptValue(ScriptContext& ctx)
- : ctx_(&ctx) {
-#ifdef ES_SCRIPTING_ENABLED
- value_ = JS_UNDEFINED;
-#endif
-}
-
-#ifdef ES_SCRIPTING_ENABLED
-ScriptValue::ScriptValue(ScriptContext& ctx, JSValue value)
- : ctx_(&ctx), value_(value) {
-}
-#endif
-
-ScriptValue::~ScriptValue() {
-#ifdef ES_SCRIPTING_ENABLED
- if (ctx_ && ctx_->getJSContext()) {
- JS_FreeValue(ctx_->getJSContext(), value_);
- }
-#endif
-}
-
-ScriptValue::ScriptValue(ScriptValue&& other) noexcept
- : ctx_(other.ctx_) {
-#ifdef ES_SCRIPTING_ENABLED
- value_ = other.value_;
- other.value_ = JS_UNDEFINED;
-#endif
- other.ctx_ = nullptr;
-}
-
-ScriptValue& ScriptValue::operator=(ScriptValue&& other) noexcept {
- if (this != &other) {
-#ifdef ES_SCRIPTING_ENABLED
- if (ctx_ && ctx_->getJSContext()) {
- JS_FreeValue(ctx_->getJSContext(), value_);
- }
- value_ = other.value_;
- other.value_ = JS_UNDEFINED;
-#endif
- ctx_ = other.ctx_;
- other.ctx_ = nullptr;
- }
- return *this;
-}
-
-// =============================================================================
-// Factory methods
-// =============================================================================
-
-ScriptValue ScriptValue::undefined(ScriptContext& ctx) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_UNDEFINED);
-#else
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::null(ScriptContext& ctx) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NULL);
-#else
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::boolean(ScriptContext& ctx, bool value) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NewBool(ctx.getJSContext(), value));
-#else
- (void)value;
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::number(ScriptContext& ctx, f64 value) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NewFloat64(ctx.getJSContext(), value));
-#else
- (void)value;
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::integer(ScriptContext& ctx, i32 value) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NewInt32(ctx.getJSContext(), value));
-#else
- (void)value;
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::string(ScriptContext& ctx, const std::string& value) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NewString(ctx.getJSContext(), value.c_str()));
-#else
- (void)value;
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::object(ScriptContext& ctx) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NewObject(ctx.getJSContext()));
-#else
- return ScriptValue(ctx);
-#endif
-}
-
-ScriptValue ScriptValue::array(ScriptContext& ctx) {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(ctx, JS_NewArray(ctx.getJSContext()));
-#else
- return ScriptValue(ctx);
-#endif
-}
-
-// =============================================================================
-// Type checking
-// =============================================================================
-
-bool ScriptValue::isUndefined() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsUndefined(value_);
-#else
- return true;
-#endif
-}
-
-bool ScriptValue::isNull() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsNull(value_);
-#else
- return false;
-#endif
-}
-
-bool ScriptValue::isBool() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsBool(value_);
-#else
- return false;
-#endif
-}
-
-bool ScriptValue::isNumber() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsNumber(value_);
-#else
- return false;
-#endif
-}
-
-bool ScriptValue::isString() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsString(value_);
-#else
- return false;
-#endif
-}
-
-bool ScriptValue::isObject() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsObject(value_);
-#else
- return false;
-#endif
-}
-
-bool ScriptValue::isArray() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsArray(ctx_->getJSContext(), value_);
-#else
- return false;
-#endif
-}
-
-bool ScriptValue::isFunction() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_IsFunction(ctx_->getJSContext(), value_);
-#else
- return false;
-#endif
-}
-
-// =============================================================================
-// Type conversion
-// =============================================================================
-
-bool ScriptValue::toBool() const {
-#ifdef ES_SCRIPTING_ENABLED
- return JS_ToBool(ctx_->getJSContext(), value_) != 0;
-#else
- return false;
-#endif
-}
-
-f64 ScriptValue::toNumber() const {
-#ifdef ES_SCRIPTING_ENABLED
- f64 result = 0.0;
- if (JS_ToFloat64(ctx_->getJSContext(), &result, value_) < 0) {
- ES_LOG_WARN("Failed to convert ScriptValue to number");
- return 0.0;
- }
- return result;
-#else
- return 0.0;
-#endif
-}
-
-i32 ScriptValue::toInt32() const {
-#ifdef ES_SCRIPTING_ENABLED
- i32 result = 0;
- if (JS_ToInt32(ctx_->getJSContext(), &result, value_) < 0) {
- ES_LOG_WARN("Failed to convert ScriptValue to int32");
- return 0;
- }
- return result;
-#else
- return 0;
-#endif
-}
-
-std::string ScriptValue::toString() const {
-#ifdef ES_SCRIPTING_ENABLED
- const char* str = JS_ToCString(ctx_->getJSContext(), value_);
- if (!str) {
- ES_LOG_WARN("Failed to convert ScriptValue to string");
- return "";
- }
- std::string result(str);
- JS_FreeCString(ctx_->getJSContext(), str);
- return result;
-#else
- return "";
-#endif
-}
-
-// =============================================================================
-// Object property access
-// =============================================================================
-
-ScriptValue ScriptValue::get(const std::string& key) const {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isObject()) {
- ES_LOG_WARN("Cannot get property '{}' from non-object", key);
- return ScriptValue::undefined(*ctx_);
- }
- JSValue prop = JS_GetPropertyStr(ctx_->getJSContext(), value_, key.c_str());
- return ScriptValue(*ctx_, prop);
-#else
- (void)key;
- return ScriptValue(*ctx_);
-#endif
-}
-
-void ScriptValue::set(const std::string& key, ScriptValue&& value) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isObject()) {
- ES_LOG_WARN("Cannot set property '{}' on non-object", key);
- return;
- }
- // JS_SetPropertyStr takes ownership of the value, so we need to duplicate it
- JSValue val = JS_DupValue(ctx_->getJSContext(), value.value_);
- if (JS_SetPropertyStr(ctx_->getJSContext(), value_, key.c_str(), val) < 0) {
- ES_LOG_WARN("Failed to set property '{}'", key);
- }
-#else
- (void)key;
- (void)value;
-#endif
-}
-
-bool ScriptValue::has(const std::string& key) const {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isObject()) {
- return false;
- }
- JSAtom atom = JS_NewAtom(ctx_->getJSContext(), key.c_str());
- int result = JS_HasProperty(ctx_->getJSContext(), value_, atom);
- JS_FreeAtom(ctx_->getJSContext(), atom);
- return result > 0;
-#else
- (void)key;
- return false;
-#endif
-}
-
-// =============================================================================
-// Array operations
-// =============================================================================
-
-usize ScriptValue::length() const {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isArray()) {
- return 0;
- }
- JSValue lengthVal = JS_GetPropertyStr(ctx_->getJSContext(), value_, "length");
- i32 len = 0;
- JS_ToInt32(ctx_->getJSContext(), &len, lengthVal);
- JS_FreeValue(ctx_->getJSContext(), lengthVal);
- return static_cast<usize>(len);
-#else
- return 0;
-#endif
-}
-
-ScriptValue ScriptValue::getAt(usize index) const {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isArray()) {
- ES_LOG_WARN("Cannot get index {} from non-array", index);
- return ScriptValue::undefined(*ctx_);
- }
- JSValue elem = JS_GetPropertyUint32(ctx_->getJSContext(), value_, static_cast<u32>(index));
- return ScriptValue(*ctx_, elem);
-#else
- (void)index;
- return ScriptValue(*ctx_);
-#endif
-}
-
-void ScriptValue::setAt(usize index, ScriptValue&& value) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isArray()) {
- ES_LOG_WARN("Cannot set index {} on non-array", index);
- return;
- }
- JSValue val = JS_DupValue(ctx_->getJSContext(), value.value_);
- if (JS_SetPropertyUint32(ctx_->getJSContext(), value_, static_cast<u32>(index), val) < 0) {
- ES_LOG_WARN("Failed to set array element at index {}", index);
- }
-#else
- (void)index;
- (void)value;
-#endif
-}
-
-// =============================================================================
-// Function calls
-// =============================================================================
-
-ScriptValue ScriptValue::call(const std::vector<ScriptValue>& args) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isFunction()) {
- ES_LOG_ERROR("Cannot call non-function value");
- return ScriptValue::undefined(*ctx_);
- }
-
- // Prepare arguments
- std::vector<JSValue> jsArgs;
- jsArgs.reserve(args.size());
- for (const auto& arg : args) {
- jsArgs.push_back(arg.value_);
- }
-
- // Call function
- JSValue result = JS_Call(
- ctx_->getJSContext(),
- value_,
- JS_UNDEFINED,
- static_cast<int>(jsArgs.size()),
- jsArgs.data()
- );
-
- if (JS_IsException(result)) {
- ES_LOG_ERROR("Exception during function call");
- JS_FreeValue(ctx_->getJSContext(), result);
- return ScriptValue::undefined(*ctx_);
- }
-
- return ScriptValue(*ctx_, result);
-#else
- (void)args;
- return ScriptValue(*ctx_);
-#endif
-}
-
-ScriptValue ScriptValue::callMethod(const std::string& methodName, const std::vector<ScriptValue>& args) {
-#ifdef ES_SCRIPTING_ENABLED
- if (!isObject()) {
- ES_LOG_ERROR("Cannot call method on non-object");
- return ScriptValue::undefined(*ctx_);
- }
-
- JSValue func = JS_GetPropertyStr(ctx_->getJSContext(), value_, methodName.c_str());
- if (!JS_IsFunction(ctx_->getJSContext(), func)) {
- ES_LOG_ERROR("Property '{}' is not a function", methodName);
- JS_FreeValue(ctx_->getJSContext(), func);
- return ScriptValue::undefined(*ctx_);
- }
-
- // Prepare arguments
- std::vector<JSValue> jsArgs;
- jsArgs.reserve(args.size());
- for (const auto& arg : args) {
- jsArgs.push_back(arg.value_);
- }
-
- // Call method with 'this' binding
- JSValue result = JS_Call(
- ctx_->getJSContext(),
- func,
- value_, // 'this' object
- static_cast<int>(jsArgs.size()),
- jsArgs.data()
- );
-
- JS_FreeValue(ctx_->getJSContext(), func);
-
- if (JS_IsException(result)) {
- ES_LOG_ERROR("Exception during method call: {}", methodName);
- JS_FreeValue(ctx_->getJSContext(), result);
- return ScriptValue::undefined(*ctx_);
- }
-
- return ScriptValue(*ctx_, result);
-#else
- (void)methodName;
- (void)args;
- return ScriptValue(*ctx_);
-#endif
-}
-
-// =============================================================================
-// Utilities
-// =============================================================================
-
-ScriptValue ScriptValue::clone() const {
-#ifdef ES_SCRIPTING_ENABLED
- return ScriptValue(*ctx_, JS_DupValue(ctx_->getJSContext(), value_));
-#else
- return ScriptValue(*ctx_);
-#endif
-}
-
-} // namespace esengine
diff --git a/src/esengine/scripting/ScriptValue.hpp b/src/esengine/scripting/ScriptValue.hpp
deleted file mode 100644
index 83f6ebc0c..000000000
--- a/src/esengine/scripting/ScriptValue.hpp
+++ /dev/null
@@ -1,206 +0,0 @@
-/**
- * @file ScriptValue.hpp
- * @brief RAII wrapper for QuickJS values
- * @details Provides type-safe JavaScript value management with automatic
- * reference counting and lifetime management.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../core/Types.hpp"
-#include "ScriptContext.hpp"
-
-#include <string>
-#include <vector>
-
-namespace esengine {
-
-/**
- * @brief RAII wrapper for JavaScript values
- *
- * @details Manages QuickJS JSValue lifecycle with automatic reference counting.
- * Provides type-safe conversion and object manipulation methods.
- *
- * Usage:
- * @code
- * ScriptContext ctx;
- * ctx.init();
- *
- * // Create values
- * ScriptValue num = ScriptValue::number(ctx, 42.0);
- * ScriptValue str = ScriptValue::string(ctx, "Hello");
- * ScriptValue obj = ScriptValue::object(ctx);
- *
- * // Set object properties
- * obj.set("name", ScriptValue::string(ctx, "Player"));
- * obj.set("health", ScriptValue::number(ctx, 100.0));
- *
- * // Get properties
- * ScriptValue name = obj.get("name");
- * std::string nameStr = name.toString();
- * @endcode
- */
-class ScriptValue {
-public:
- /**
- * @brief Create undefined value
- */
- ScriptValue(ScriptContext& ctx);
-
- /**
- * @brief Create from existing JSValue (takes ownership)
- */
-#ifdef ES_SCRIPTING_ENABLED
- ScriptValue(ScriptContext& ctx, JSValue value);
-#endif
-
- ~ScriptValue();
-
- // Move semantics
- ScriptValue(ScriptValue&& other) noexcept;
- ScriptValue& operator=(ScriptValue&& other) noexcept;
-
- // Disable copy (use clone() instead for explicit copying)
- ScriptValue(const ScriptValue&) = delete;
- ScriptValue& operator=(const ScriptValue&) = delete;
-
- // =============================================================================
- // Factory methods for creating values
- // =============================================================================
-
- static ScriptValue undefined(ScriptContext& ctx);
- static ScriptValue null(ScriptContext& ctx);
- static ScriptValue boolean(ScriptContext& ctx, bool value);
- static ScriptValue number(ScriptContext& ctx, f64 value);
- static ScriptValue integer(ScriptContext& ctx, i32 value);
- static ScriptValue string(ScriptContext& ctx, const std::string& value);
- static ScriptValue object(ScriptContext& ctx);
- static ScriptValue array(ScriptContext& ctx);
-
- // =============================================================================
- // Type checking
- // =============================================================================
-
- bool isUndefined() const;
- bool isNull() const;
- bool isBool() const;
- bool isNumber() const;
- bool isString() const;
- bool isObject() const;
- bool isArray() const;
- bool isFunction() const;
-
- // =============================================================================
- // Type conversion
- // =============================================================================
-
- bool toBool() const;
- f64 toNumber() const;
- i32 toInt32() const;
- std::string toString() const;
-
- // =============================================================================
- // Object property access
- // =============================================================================
-
- /**
- * @brief Get object property by name
- * @param key Property name
- * @return ScriptValue containing the property value
- */
- ScriptValue get(const std::string& key) const;
-
- /**
- * @brief Set object property
- * @param key Property name
- * @param value Value to set
- */
- void set(const std::string& key, ScriptValue&& value);
-
- /**
- * @brief Check if object has property
- * @param key Property name
- * @return true if property exists, false otherwise
- */
- bool has(const std::string& key) const;
-
- // =============================================================================
- // Array operations
- // =============================================================================
-
- /**
- * @brief Get array length
- * @return Array length or 0 if not an array
- */
- usize length() const;
-
- /**
- * @brief Get array element by index
- * @param index Array index
- * @return ScriptValue containing the element
- */
- ScriptValue getAt(usize index) const;
-
- /**
- * @brief Set array element
- * @param index Array index
- * @param value Value to set
- */
- void setAt(usize index, ScriptValue&& value);
-
- // =============================================================================
- // Function calls
- // =============================================================================
-
- /**
- * @brief Call function with arguments
- * @param args Function arguments
- * @return Return value of the function
- */
- ScriptValue call(const std::vector<ScriptValue>& args);
-
- /**
- * @brief Call method on object
- * @param methodName Method name
- * @param args Method arguments
- * @return Return value of the method
- */
- ScriptValue callMethod(const std::string& methodName, const std::vector<ScriptValue>& args);
-
- // =============================================================================
- // Utilities
- // =============================================================================
-
- /**
- * @brief Create a deep copy of this value
- * @return Cloned ScriptValue
- */
- ScriptValue clone() const;
-
- /**
- * @brief Get context this value belongs to
- */
- ScriptContext* getContext() { return ctx_; }
-
-#ifdef ES_SCRIPTING_ENABLED
- /**
- * @brief Get underlying JSValue (advanced usage)
- * @return JSValue handle
- */
- JSValue getJSValue() const { return value_; }
-#endif
-
-private:
- ScriptContext* ctx_ = nullptr;
-
-#ifdef ES_SCRIPTING_ENABLED
- JSValue value_;
-#endif
-};
-
-} // namespace esengine
diff --git a/src/esengine/scripting/bindings/ECSBindings.generated.cpp b/src/esengine/scripting/bindings/ECSBindings.generated.cpp
deleted file mode 100644
index 999824c30..000000000
--- a/src/esengine/scripting/bindings/ECSBindings.generated.cpp
+++ /dev/null
@@ -1,483 +0,0 @@
-/**
- * @file ECSBindings.generated.cpp
- * @brief Auto-generated QuickJS bindings for Native platform
- * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY
- *
- * @author ESEngine Binding Generator
- * @date 2026
- */
-
-#ifdef ES_SCRIPTING_ENABLED
-
-#include "ECSBindings.hpp"
-#include "../../ecs/Registry.hpp"
-#include "../../math/Math.hpp"
-
-#include "../../ecs/components/Camera.hpp"
-#include "../../ecs/components/Canvas.hpp"
-#include "../../ecs/components/Hierarchy.hpp"
-#include "../../ecs/components/Sprite.hpp"
-#include "../../ecs/components/Transform.hpp"
-#include "../../ecs/components/Velocity.hpp"
-
-namespace esengine::scripting {
-
-// Global registry pointer for C callbacks
-static ecs::Registry* g_registry = nullptr;
-
-// =============================================================================
-// Type Conversion Helpers
-// =============================================================================
-
-static glm::vec3 jsToVec3(JSContext* ctx, JSValue jsObj) {
- glm::vec3 result(0.0f);
- JSValue x = JS_GetPropertyStr(ctx, jsObj, "x");
- JSValue y = JS_GetPropertyStr(ctx, jsObj, "y");
- JSValue z = JS_GetPropertyStr(ctx, jsObj, "z");
- double dx, dy, dz;
- JS_ToFloat64(ctx, &dx, x);
- JS_ToFloat64(ctx, &dy, y);
- JS_ToFloat64(ctx, &dz, z);
- result.x = static_cast<f32>(dx);
- result.y = static_cast<f32>(dy);
- result.z = static_cast<f32>(dz);
- JS_FreeValue(ctx, x);
- JS_FreeValue(ctx, y);
- JS_FreeValue(ctx, z);
- return result;
-}
-
-static JSValue vec3ToJS(JSContext* ctx, const glm::vec3& vec) {
- JSValue obj = JS_NewObject(ctx);
- JS_SetPropertyStr(ctx, obj, "x", JS_NewFloat64(ctx, vec.x));
- JS_SetPropertyStr(ctx, obj, "y", JS_NewFloat64(ctx, vec.y));
- JS_SetPropertyStr(ctx, obj, "z", JS_NewFloat64(ctx, vec.z));
- return obj;
-}
-
-static glm::quat jsToQuat(JSContext* ctx, JSValue jsObj) {
- glm::quat result(1.0f, 0.0f, 0.0f, 0.0f);
- JSValue w = JS_GetPropertyStr(ctx, jsObj, "w");
- JSValue x = JS_GetPropertyStr(ctx, jsObj, "x");
- JSValue y = JS_GetPropertyStr(ctx, jsObj, "y");
- JSValue z = JS_GetPropertyStr(ctx, jsObj, "z");
- double dw, dx, dy, dz;
- JS_ToFloat64(ctx, &dw, w);
- JS_ToFloat64(ctx, &dx, x);
- JS_ToFloat64(ctx, &dy, y);
- JS_ToFloat64(ctx, &dz, z);
- result.w = static_cast<f32>(dw);
- result.x = static_cast<f32>(dx);
- result.y = static_cast<f32>(dy);
- result.z = static_cast<f32>(dz);
- JS_FreeValue(ctx, w);
- JS_FreeValue(ctx, x);
- JS_FreeValue(ctx, y);
- JS_FreeValue(ctx, z);
- return result;
-}
-
-static JSValue quatToJS(JSContext* ctx, const glm::quat& quat) {
- JSValue obj = JS_NewObject(ctx);
- JS_SetPropertyStr(ctx, obj, "w", JS_NewFloat64(ctx, quat.w));
- JS_SetPropertyStr(ctx, obj, "x", JS_NewFloat64(ctx, quat.x));
- JS_SetPropertyStr(ctx, obj, "y", JS_NewFloat64(ctx, quat.y));
- JS_SetPropertyStr(ctx, obj, "z", JS_NewFloat64(ctx, quat.z));
- return obj;
-}
-
-// =============================================================================
-// Camera Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getCamera(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::Camera>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have Camera component");
- }
- auto& comp = g_registry->get<esengine::ecs::Camera>(entity);
- JSValue obj = JS_NewObject(ctx);
- // TODO: Add converter for ProjectionType
- JS_SetPropertyStr(ctx, obj, "fov", JS_NewFloat64(ctx, comp.fov));
- JS_SetPropertyStr(ctx, obj, "orthoSize", JS_NewFloat64(ctx, comp.orthoSize));
- JS_SetPropertyStr(ctx, obj, "nearPlane", JS_NewFloat64(ctx, comp.nearPlane));
- JS_SetPropertyStr(ctx, obj, "farPlane", JS_NewFloat64(ctx, comp.farPlane));
- JS_SetPropertyStr(ctx, obj, "aspectRatio", JS_NewFloat64(ctx, comp.aspectRatio));
- // TODO: Add converter for bool
- // TODO: Add converter for i32
- return obj;
-}
-
-static JSValue js_Registry_addCamera(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::Camera comp;
- JSValue projectionTypeVal = JS_GetPropertyStr(ctx, argv[1], "projectionType");
- JS_FreeValue(ctx, projectionTypeVal);
- JSValue fovVal = JS_GetPropertyStr(ctx, argv[1], "fov");
- double dfov;
- JS_ToFloat64(ctx, &dfov, fovVal);
- comp.fov = static_cast<f32>(dfov);
- JS_FreeValue(ctx, fovVal);
- JSValue orthoSizeVal = JS_GetPropertyStr(ctx, argv[1], "orthoSize");
- double dorthoSize;
- JS_ToFloat64(ctx, &dorthoSize, orthoSizeVal);
- comp.orthoSize = static_cast<f32>(dorthoSize);
- JS_FreeValue(ctx, orthoSizeVal);
- JSValue nearPlaneVal = JS_GetPropertyStr(ctx, argv[1], "nearPlane");
- double dnearPlane;
- JS_ToFloat64(ctx, &dnearPlane, nearPlaneVal);
- comp.nearPlane = static_cast<f32>(dnearPlane);
- JS_FreeValue(ctx, nearPlaneVal);
- JSValue farPlaneVal = JS_GetPropertyStr(ctx, argv[1], "farPlane");
- double dfarPlane;
- JS_ToFloat64(ctx, &dfarPlane, farPlaneVal);
- comp.farPlane = static_cast<f32>(dfarPlane);
- JS_FreeValue(ctx, farPlaneVal);
- JSValue aspectRatioVal = JS_GetPropertyStr(ctx, argv[1], "aspectRatio");
- double daspectRatio;
- JS_ToFloat64(ctx, &daspectRatio, aspectRatioVal);
- comp.aspectRatio = static_cast<f32>(daspectRatio);
- JS_FreeValue(ctx, aspectRatioVal);
- JSValue isActiveVal = JS_GetPropertyStr(ctx, argv[1], "isActive");
- JS_FreeValue(ctx, isActiveVal);
- JSValue priorityVal = JS_GetPropertyStr(ctx, argv[1], "priority");
- JS_FreeValue(ctx, priorityVal);
- g_registry->emplaceOrReplace<esengine::ecs::Camera>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// Canvas Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getCanvas(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::Canvas>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have Canvas component");
- }
- auto& comp = g_registry->get<esengine::ecs::Canvas>(entity);
- JSValue obj = JS_NewObject(ctx);
- // TODO: Add converter for glm::uvec2
- JS_SetPropertyStr(ctx, obj, "pixelsPerUnit", JS_NewFloat64(ctx, comp.pixelsPerUnit));
- // TODO: Add converter for CanvasScaleMode
- JS_SetPropertyStr(ctx, obj, "matchWidthOrHeight", JS_NewFloat64(ctx, comp.matchWidthOrHeight));
- // TODO: Add converter for glm::vec4
- return obj;
-}
-
-static JSValue js_Registry_addCanvas(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::Canvas comp;
- JSValue designResolutionVal = JS_GetPropertyStr(ctx, argv[1], "designResolution");
- JS_FreeValue(ctx, designResolutionVal);
- JSValue pixelsPerUnitVal = JS_GetPropertyStr(ctx, argv[1], "pixelsPerUnit");
- double dpixelsPerUnit;
- JS_ToFloat64(ctx, &dpixelsPerUnit, pixelsPerUnitVal);
- comp.pixelsPerUnit = static_cast<f32>(dpixelsPerUnit);
- JS_FreeValue(ctx, pixelsPerUnitVal);
- JSValue scaleModeVal = JS_GetPropertyStr(ctx, argv[1], "scaleMode");
- JS_FreeValue(ctx, scaleModeVal);
- JSValue matchWidthOrHeightVal = JS_GetPropertyStr(ctx, argv[1], "matchWidthOrHeight");
- double dmatchWidthOrHeight;
- JS_ToFloat64(ctx, &dmatchWidthOrHeight, matchWidthOrHeightVal);
- comp.matchWidthOrHeight = static_cast<f32>(dmatchWidthOrHeight);
- JS_FreeValue(ctx, matchWidthOrHeightVal);
- JSValue backgroundColorVal = JS_GetPropertyStr(ctx, argv[1], "backgroundColor");
- JS_FreeValue(ctx, backgroundColorVal);
- g_registry->emplaceOrReplace<esengine::ecs::Canvas>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// Parent Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getParent(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::Parent>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have Parent component");
- }
- auto& comp = g_registry->get<esengine::ecs::Parent>(entity);
- JSValue obj = JS_NewObject(ctx);
- // TODO: Add converter for Entity
- return obj;
-}
-
-static JSValue js_Registry_addParent(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::Parent comp;
- JSValue entityVal = JS_GetPropertyStr(ctx, argv[1], "entity");
- JS_FreeValue(ctx, entityVal);
- g_registry->emplaceOrReplace<esengine::ecs::Parent>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// Children Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getChildren(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::Children>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have Children component");
- }
- auto& comp = g_registry->get<esengine::ecs::Children>(entity);
- JSValue obj = JS_NewObject(ctx);
- return obj;
-}
-
-static JSValue js_Registry_addChildren(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::Children comp;
- g_registry->emplaceOrReplace<esengine::ecs::Children>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// Sprite Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getSprite(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::Sprite>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have Sprite component");
- }
- auto& comp = g_registry->get<esengine::ecs::Sprite>(entity);
- JSValue obj = JS_NewObject(ctx);
- // TODO: Add converter for resource::TextureHandle
- // TODO: Add converter for glm::vec4
- // TODO: Add converter for glm::vec2
- // TODO: Add converter for glm::vec2
- // TODO: Add converter for glm::vec2
- // TODO: Add converter for i32
- // TODO: Add converter for bool
- // TODO: Add converter for bool
- return obj;
-}
-
-static JSValue js_Registry_addSprite(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::Sprite comp;
- JSValue textureVal = JS_GetPropertyStr(ctx, argv[1], "texture");
- JS_FreeValue(ctx, textureVal);
- JSValue colorVal = JS_GetPropertyStr(ctx, argv[1], "color");
- JS_FreeValue(ctx, colorVal);
- JSValue sizeVal = JS_GetPropertyStr(ctx, argv[1], "size");
- JS_FreeValue(ctx, sizeVal);
- JSValue uvOffsetVal = JS_GetPropertyStr(ctx, argv[1], "uvOffset");
- JS_FreeValue(ctx, uvOffsetVal);
- JSValue uvScaleVal = JS_GetPropertyStr(ctx, argv[1], "uvScale");
- JS_FreeValue(ctx, uvScaleVal);
- JSValue layerVal = JS_GetPropertyStr(ctx, argv[1], "layer");
- JS_FreeValue(ctx, layerVal);
- JSValue flipXVal = JS_GetPropertyStr(ctx, argv[1], "flipX");
- JS_FreeValue(ctx, flipXVal);
- JSValue flipYVal = JS_GetPropertyStr(ctx, argv[1], "flipY");
- JS_FreeValue(ctx, flipYVal);
- g_registry->emplaceOrReplace<esengine::ecs::Sprite>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// LocalTransform Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getLocalTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::LocalTransform>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have LocalTransform component");
- }
- auto& comp = g_registry->get<esengine::ecs::LocalTransform>(entity);
- JSValue obj = JS_NewObject(ctx);
- JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, comp.position));
- JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, comp.rotation));
- JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, comp.scale));
- // TODO: Add converter for glm::mat4
- JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, comp.position));
- JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, comp.rotation));
- JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, comp.scale));
- return obj;
-}
-
-static JSValue js_Registry_addLocalTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::LocalTransform comp;
- JSValue positionVal = JS_GetPropertyStr(ctx, argv[1], "position");
- comp.position = jsToVec3(ctx, positionVal);
- JS_FreeValue(ctx, positionVal);
- JSValue rotationVal = JS_GetPropertyStr(ctx, argv[1], "rotation");
- comp.rotation = jsToQuat(ctx, rotationVal);
- JS_FreeValue(ctx, rotationVal);
- JSValue scaleVal = JS_GetPropertyStr(ctx, argv[1], "scale");
- comp.scale = jsToVec3(ctx, scaleVal);
- JS_FreeValue(ctx, scaleVal);
- JSValue matrixVal = JS_GetPropertyStr(ctx, argv[1], "matrix");
- JS_FreeValue(ctx, matrixVal);
- JSValue positionVal = JS_GetPropertyStr(ctx, argv[1], "position");
- comp.position = jsToVec3(ctx, positionVal);
- JS_FreeValue(ctx, positionVal);
- JSValue rotationVal = JS_GetPropertyStr(ctx, argv[1], "rotation");
- comp.rotation = jsToQuat(ctx, rotationVal);
- JS_FreeValue(ctx, rotationVal);
- JSValue scaleVal = JS_GetPropertyStr(ctx, argv[1], "scale");
- comp.scale = jsToVec3(ctx, scaleVal);
- JS_FreeValue(ctx, scaleVal);
- g_registry->emplaceOrReplace<esengine::ecs::LocalTransform>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// WorldTransform Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getWorldTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::WorldTransform>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have WorldTransform component");
- }
- auto& comp = g_registry->get<esengine::ecs::WorldTransform>(entity);
- JSValue obj = JS_NewObject(ctx);
- // TODO: Add converter for glm::mat4
- JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, comp.position));
- JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, comp.rotation));
- JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, comp.scale));
- return obj;
-}
-
-static JSValue js_Registry_addWorldTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::WorldTransform comp;
- JSValue matrixVal = JS_GetPropertyStr(ctx, argv[1], "matrix");
- JS_FreeValue(ctx, matrixVal);
- JSValue positionVal = JS_GetPropertyStr(ctx, argv[1], "position");
- comp.position = jsToVec3(ctx, positionVal);
- JS_FreeValue(ctx, positionVal);
- JSValue rotationVal = JS_GetPropertyStr(ctx, argv[1], "rotation");
- comp.rotation = jsToQuat(ctx, rotationVal);
- JS_FreeValue(ctx, rotationVal);
- JSValue scaleVal = JS_GetPropertyStr(ctx, argv[1], "scale");
- comp.scale = jsToVec3(ctx, scaleVal);
- JS_FreeValue(ctx, scaleVal);
- g_registry->emplaceOrReplace<esengine::ecs::WorldTransform>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// Velocity Component Bindings
-// =============================================================================
-
-static JSValue js_Registry_getVelocity(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- if (!g_registry->has<esengine::ecs::Velocity>(entity)) {
- return JS_ThrowReferenceError(ctx, "Entity does not have Velocity component");
- }
- auto& comp = g_registry->get<esengine::ecs::Velocity>(entity);
- JSValue obj = JS_NewObject(ctx);
- JS_SetPropertyStr(ctx, obj, "linear", vec3ToJS(ctx, comp.linear));
- JS_SetPropertyStr(ctx, obj, "angular", vec3ToJS(ctx, comp.angular));
- return obj;
-}
-
-static JSValue js_Registry_addVelocity(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
- u32 entity;
- JS_ToUint32(ctx, &entity, argv[0]);
- esengine::ecs::Velocity comp;
- JSValue linearVal = JS_GetPropertyStr(ctx, argv[1], "linear");
- comp.linear = jsToVec3(ctx, linearVal);
- JS_FreeValue(ctx, linearVal);
- JSValue angularVal = JS_GetPropertyStr(ctx, argv[1], "angular");
- comp.angular = jsToVec3(ctx, angularVal);
- JS_FreeValue(ctx, angularVal);
- g_registry->emplaceOrReplace<esengine::ecs::Velocity>(entity, comp);
- return JS_UNDEFINED;
-}
-
-// =============================================================================
-// Main Binding Function
-// =============================================================================
-
-void bindECS(ScriptContext& ctx, ecs::Registry& registry) {
- g_registry = &registry;
- JSContext* jsCtx = ctx.getJSContext();
- JSValue global = JS_GetGlobalObject(jsCtx);
- JSValue registryObj = JS_NewObject(jsCtx);
-
- // Entity management
- JS_SetPropertyStr(jsCtx, registryObj, "create",
- JS_NewCFunction(jsCtx, js_Registry_create, "create", 0));
- JS_SetPropertyStr(jsCtx, registryObj, "destroy",
- JS_NewCFunction(jsCtx, js_Registry_destroy, "destroy", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "valid",
- JS_NewCFunction(jsCtx, js_Registry_valid, "valid", 1));
-
- // Camera component
- JS_SetPropertyStr(jsCtx, registryObj, "getCamera",
- JS_NewCFunction(jsCtx, js_Registry_getCamera, "getCamera", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addCamera",
- JS_NewCFunction(jsCtx, js_Registry_addCamera, "addCamera", 2));
-
- // Canvas component
- JS_SetPropertyStr(jsCtx, registryObj, "getCanvas",
- JS_NewCFunction(jsCtx, js_Registry_getCanvas, "getCanvas", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addCanvas",
- JS_NewCFunction(jsCtx, js_Registry_addCanvas, "addCanvas", 2));
-
- // Parent component
- JS_SetPropertyStr(jsCtx, registryObj, "getParent",
- JS_NewCFunction(jsCtx, js_Registry_getParent, "getParent", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addParent",
- JS_NewCFunction(jsCtx, js_Registry_addParent, "addParent", 2));
-
- // Children component
- JS_SetPropertyStr(jsCtx, registryObj, "getChildren",
- JS_NewCFunction(jsCtx, js_Registry_getChildren, "getChildren", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addChildren",
- JS_NewCFunction(jsCtx, js_Registry_addChildren, "addChildren", 2));
-
- // Sprite component
- JS_SetPropertyStr(jsCtx, registryObj, "getSprite",
- JS_NewCFunction(jsCtx, js_Registry_getSprite, "getSprite", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addSprite",
- JS_NewCFunction(jsCtx, js_Registry_addSprite, "addSprite", 2));
-
- // LocalTransform component
- JS_SetPropertyStr(jsCtx, registryObj, "getLocalTransform",
- JS_NewCFunction(jsCtx, js_Registry_getLocalTransform, "getLocalTransform", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addLocalTransform",
- JS_NewCFunction(jsCtx, js_Registry_addLocalTransform, "addLocalTransform", 2));
-
- // WorldTransform component
- JS_SetPropertyStr(jsCtx, registryObj, "getWorldTransform",
- JS_NewCFunction(jsCtx, js_Registry_getWorldTransform, "getWorldTransform", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addWorldTransform",
- JS_NewCFunction(jsCtx, js_Registry_addWorldTransform, "addWorldTransform", 2));
-
- // Velocity component
- JS_SetPropertyStr(jsCtx, registryObj, "getVelocity",
- JS_NewCFunction(jsCtx, js_Registry_getVelocity, "getVelocity", 1));
- JS_SetPropertyStr(jsCtx, registryObj, "addVelocity",
- JS_NewCFunction(jsCtx, js_Registry_addVelocity, "addVelocity", 2));
-
- JS_SetPropertyStr(jsCtx, global, "Registry", registryObj);
- JS_FreeValue(jsCtx, global);
-}
-
-
-} // namespace esengine::scripting
-
-#endif // ES_SCRIPTING_ENABLED
diff --git a/src/esengine/scripting/bindings/ECSBindings.hpp b/src/esengine/scripting/bindings/ECSBindings.hpp
deleted file mode 100644
index d9f6b0584..000000000
--- a/src/esengine/scripting/bindings/ECSBindings.hpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * @file ECSBindings.hpp
- * @brief JavaScript bindings for ECS system
- * @details Exposes Entity, Registry, and Components to JavaScript
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../ScriptContext.hpp"
-
-namespace esengine {
-
-namespace ecs {
-class Registry;
-}
-
-/**
- * @brief Register ECS bindings with JavaScript context
- *
- * @details Exposes the following to JavaScript:
- * - Entity creation/destruction
- * - Component get/set operations
- * - Transform, Velocity, Sprite components
- * - Vec3, Quat math types
- *
- * Usage:
- * @code
- * ScriptContext ctx;
- * ctx.init();
- * bindECS(ctx);
- *
- * // JavaScript can now use:
- * // let entity = Registry.create();
- * // let transform = Registry.getTransform(entity);
- * // transform.position.x += 1.0;
- * // Registry.setTransform(entity, transform);
- * @endcode
- *
- * @param ctx JavaScript context to bind to
- * @param registry ECS registry instance to expose
- */
-void bindECS(ScriptContext& ctx, ecs::Registry& registry);
-
-} // namespace esengine
diff --git a/src/esengine/ui/UIContext.cpp b/src/esengine/ui/UIContext.cpp
deleted file mode 100644
index 90573cf0b..000000000
--- a/src/esengine/ui/UIContext.cpp
+++ /dev/null
@@ -1,699 +0,0 @@
-/**
- * @file UIContext.cpp
- * @brief UIContext implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "UIContext.hpp"
-#include "../core/Log.hpp"
-#include "../events/Dispatcher.hpp"
-#include "../renderer/RenderCommand.hpp"
-#include "../renderer/RenderContext.hpp"
-#include "rendering/UIBatchRenderer.hpp"
-#include "widgets/Widget.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "font/SDFFont.hpp"
-#include "font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "font/BitmapFont.hpp"
-#endif
-
-#include "font/SystemFont.hpp"
-
-#include <glm/gtc/matrix_transform.hpp>
-
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-UIContext::UIContext(RenderContext& renderContext, Dispatcher& dispatcher)
- : renderContext_(renderContext), dispatcher_(dispatcher) {}
-
-UIContext::~UIContext() {
- if (initialized_) {
- shutdown();
- }
-}
-
-// =============================================================================
-// Lifecycle
-// =============================================================================
-
-void UIContext::init() {
- if (initialized_) return;
-
- renderer_ = makeUnique<UIBatchRenderer>(renderContext_);
- renderer_->init();
-
- theme_ = Theme::createDark();
-
- initialized_ = true;
- ES_LOG_INFO("UIContext initialized");
-}
-
-void UIContext::shutdown() {
- if (!initialized_) return;
-
- root_.reset();
-#if ES_FEATURE_SDF_FONT
- fonts_.clear();
- msdfFonts_.clear();
-#endif
-#if ES_FEATURE_BITMAP_FONT
- bitmapFonts_.clear();
-#endif
- systemFonts_.clear();
- theme_.reset();
-
- if (renderer_) {
- renderer_->shutdown();
- renderer_.reset();
- }
-
- focusedWidget_ = nullptr;
- hoveredWidget_ = nullptr;
- pressedWidget_ = nullptr;
-
- initialized_ = false;
- ES_LOG_INFO("UIContext shutdown");
-}
-
-bool UIContext::isInitialized() const {
- return initialized_;
-}
-
-// =============================================================================
-// Root Widget
-// =============================================================================
-
-void UIContext::setRoot(Unique<Widget> root) {
- if (root_) {
- root_->setContext(nullptr);
- }
-
- root_ = std::move(root);
-
- if (root_) {
- root_->setContext(this);
- root_->invalidateLayout();
- }
-
- focusedWidget_ = nullptr;
- hoveredWidget_ = nullptr;
- pressedWidget_ = nullptr;
-}
-
-// =============================================================================
-// Theme
-// =============================================================================
-
-void UIContext::setTheme(Unique<Theme> theme) {
- if (theme) {
- theme_ = std::move(theme);
- }
-}
-
-// =============================================================================
-// Font Management
-// =============================================================================
-
-#if ES_FEATURE_SDF_FONT
-SDFFont* UIContext::loadFont(const std::string& name, const std::string& path, f32 fontSize,
- f32 sdfSpread) {
- auto font = SDFFont::create(path, fontSize, sdfSpread);
- if (!font) {
- ES_LOG_ERROR("Failed to load font: {}", path);
- return nullptr;
- }
-
- SDFFont* ptr = font.get();
- fonts_[name] = std::move(font);
-
- ES_LOG_INFO("Loaded SDF font '{}' from {}", name, path);
- return ptr;
-}
-
-SDFFont* UIContext::getFont(const std::string& name) {
- auto it = fonts_.find(name);
- if (it != fonts_.end()) {
- return it->second.get();
- }
- return nullptr;
-}
-
-SDFFont* UIContext::getDefaultFont() {
- return getFont(defaultFontName_);
-}
-
-SDFFont* UIContext::getIconFont() {
- return getFont("icons");
-}
-
-MSDFFont* UIContext::loadMSDFFont(const std::string& name, const std::string& path, f32 fontSize,
- f32 pixelRange) {
- auto font = MSDFFont::create(path, fontSize, pixelRange);
- if (!font) {
- ES_LOG_ERROR("Failed to load MSDF font: {}", path);
- return nullptr;
- }
-
- MSDFFont* ptr = font.get();
- msdfFonts_[name] = std::move(font);
-
- ES_LOG_INFO("Loaded MSDF font '{}' from {}", name, path);
- return ptr;
-}
-
-MSDFFont* UIContext::getMSDFFont(const std::string& name) {
- auto it = msdfFonts_.find(name);
- if (it != msdfFonts_.end()) {
- return it->second.get();
- }
- return nullptr;
-}
-
-MSDFFont* UIContext::getDefaultMSDFFont() {
- return getMSDFFont(defaultFontName_);
-}
-
-MSDFFont* UIContext::getIconMSDFFont() {
- return getMSDFFont("icons");
-}
-#endif // ES_FEATURE_SDF_FONT
-
-#if ES_FEATURE_BITMAP_FONT
-BitmapFont* UIContext::loadBitmapFont(const std::string& name, const std::string& atlasPath,
- const std::string& metricsPath) {
- auto font = BitmapFont::load(atlasPath, metricsPath);
- if (!font) {
- ES_LOG_ERROR("Failed to load bitmap font: {} / {}", atlasPath, metricsPath);
- return nullptr;
- }
-
- BitmapFont* ptr = font.get();
- bitmapFonts_[name] = std::move(font);
-
- ES_LOG_INFO("Loaded bitmap font '{}' from {}", name, atlasPath);
- return ptr;
-}
-
-BitmapFont* UIContext::getBitmapFont(const std::string& name) {
- auto it = bitmapFonts_.find(name);
- if (it != bitmapFonts_.end()) {
- return it->second.get();
- }
- return nullptr;
-}
-
-BitmapFont* UIContext::getDefaultBitmapFont() {
- return getBitmapFont(defaultFontName_);
-}
-#endif // ES_FEATURE_BITMAP_FONT
-
-// =============================================================================
-// System Font
-// =============================================================================
-
-SystemFont* UIContext::createSystemFont(const std::string& name, const std::string& fontFamily,
- f32 fontSize) {
- auto font = SystemFont::create(fontFamily, fontSize);
- if (!font) {
- ES_LOG_ERROR("Failed to create system font: {}", fontFamily);
- return nullptr;
- }
-
- font->preloadASCII();
-
- SystemFont* ptr = font.get();
- systemFonts_[name] = std::move(font);
-
- ES_LOG_INFO("Created system font '{}' with family '{}'", name, fontFamily);
- return ptr;
-}
-
-SystemFont* UIContext::createSystemFontFromFile(const std::string& name, const std::string& filePath,
- f32 fontSize) {
- auto font = SystemFont::createFromFile(filePath, fontSize);
- if (!font) {
- ES_LOG_ERROR("Failed to create font from file: {}", filePath);
- return nullptr;
- }
-
- font->preloadASCII();
-
- SystemFont* ptr = font.get();
- systemFonts_[name] = std::move(font);
-
- ES_LOG_INFO("Created font '{}' from file '{}'", name, filePath);
- return ptr;
-}
-
-SystemFont* UIContext::getSystemFont(const std::string& name) {
- auto it = systemFonts_.find(name);
- if (it != systemFonts_.end()) {
- return it->second.get();
- }
- return nullptr;
-}
-
-SystemFont* UIContext::getDefaultSystemFont() {
- return getSystemFont(defaultFontName_);
-}
-
-SystemFont* UIContext::getIconSystemFont() {
- return getSystemFont("icons");
-}
-
-// =============================================================================
-// Update and Render
-// =============================================================================
-
-void UIContext::update(f32 deltaTime) {
- (void)deltaTime;
-
- if (!root_) return;
-
- doLayout();
-}
-
-void UIContext::render() {
- if (!root_ || !renderer_) {
- return;
- }
-
- u32 physicalWidth = static_cast<u32>(viewportWidth_ * devicePixelRatio_);
- u32 physicalHeight = static_cast<u32>(viewportHeight_ * devicePixelRatio_);
-
- RenderCommand::setViewport(0, 0, physicalWidth, physicalHeight);
-
- glm::mat4 projection = glm::ortho(0.0f, static_cast<f32>(viewportWidth_),
- static_cast<f32>(viewportHeight_), 0.0f, -1.0f, 1.0f);
-
- renderer_->begin(projection, devicePixelRatio_);
- root_->renderTree(*renderer_);
-
- for (Widget* overlay : overlays_) {
- if (overlay && overlay->isVisible()) {
- overlay->render(*renderer_);
- }
- }
-
- renderer_->end();
-}
-
-void UIContext::setViewport(u32 width, u32 height) {
- if (viewportWidth_ != width || viewportHeight_ != height) {
- viewportWidth_ = width;
- viewportHeight_ = height;
-
- if (root_) {
- root_->invalidateLayout();
- }
- }
-}
-
-void UIContext::setDevicePixelRatio(f32 ratio) {
- devicePixelRatio_ = ratio > 0.0f ? ratio : 1.0f;
-}
-
-void UIContext::doLayout() {
- if (!root_) return;
-
- if (root_->isLayoutDirty()) {
- Rect rootBounds(0.0f, 0.0f, static_cast<f32>(viewportWidth_),
- static_cast<f32>(viewportHeight_));
-
- root_->measure(rootBounds.width, rootBounds.height);
- root_->layout(rootBounds);
- }
-}
-
-// =============================================================================
-// Input Processing
-// =============================================================================
-
-void UIContext::processMouseMove(f32 x, f32 y) {
- f32 deltaX = x - lastMouseX_;
- f32 deltaY = y - lastMouseY_;
- lastMouseX_ = x;
- lastMouseY_ = y;
-
- for (auto it = overlays_.rbegin(); it != overlays_.rend(); ++it) {
- Widget* overlay = *it;
- if (overlay && overlay->isVisible()) {
- MouseMoveEvent event;
- event.x = x;
- event.y = y;
- event.deltaX = deltaX;
- event.deltaY = deltaY;
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
- event.alt = altDown_;
- overlay->onMouseMove(event);
- }
- }
-
- updateHoveredWidget(x, y);
-
- if (pressedWidget_) {
- MouseMoveEvent event;
- event.x = x;
- event.y = y;
- event.deltaX = deltaX;
- event.deltaY = deltaY;
- event.leftButton = mouseButtonDown_[static_cast<usize>(MouseButton::Left)];
- event.rightButton = mouseButtonDown_[static_cast<usize>(MouseButton::Right)];
- event.middleButton = mouseButtonDown_[static_cast<usize>(MouseButton::Middle)];
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
- event.alt = altDown_;
-
- pressedWidget_->onMouseMove(event);
- } else if (hoveredWidget_) {
- MouseMoveEvent event;
- event.x = x;
- event.y = y;
- event.deltaX = deltaX;
- event.deltaY = deltaY;
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
- event.alt = altDown_;
-
- hoveredWidget_->onMouseMove(event);
- }
-}
-
-void UIContext::processMouseDown(MouseButton button, f32 x, f32 y) {
- mouseButtonDown_[static_cast<usize>(button)] = true;
- lastMouseX_ = x;
- lastMouseY_ = y;
-
- for (auto it = overlays_.rbegin(); it != overlays_.rend(); ++it) {
- Widget* overlay = *it;
- if (overlay && overlay->isVisible()) {
- Widget* hit = overlay->hitTest(x, y);
- if (hit) {
- MouseButtonEvent event;
- event.button = button;
- event.pressed = true;
- event.x = x;
- event.y = y;
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
- event.alt = altDown_;
-
- Widget* target = hit;
- while (target && !event.consumed && !event.propagationStopped) {
- if (target->onMouseDown(event)) {
- event.consume();
- }
- target = target->getParent();
- }
-
- if (event.consumed) {
- return;
- }
- }
- }
- }
-
- updateHoveredWidget(x, y);
-
- if (hoveredWidget_) {
- pressedWidget_ = hoveredWidget_;
-
- if (hoveredWidget_->isFocusable()) {
- setFocus(hoveredWidget_);
- } else {
- setFocus(nullptr);
- }
-
- MouseButtonEvent event;
- event.button = button;
- event.pressed = true;
- event.x = x;
- event.y = y;
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
- event.alt = altDown_;
-
- Widget* target = hoveredWidget_;
- while (target && !event.consumed && !event.propagationStopped) {
- if (target->onMouseDown(event)) {
- event.consume();
- }
- target = target->getParent();
- }
- } else {
- setFocus(nullptr);
- }
-}
-
-void UIContext::processMouseUp(MouseButton button, f32 x, f32 y) {
- mouseButtonDown_[static_cast<usize>(button)] = false;
- lastMouseX_ = x;
- lastMouseY_ = y;
-
- Widget* startWidget = pressedWidget_ ? pressedWidget_ : hoveredWidget_;
-
- if (startWidget) {
- MouseButtonEvent event;
- event.button = button;
- event.pressed = false;
- event.x = x;
- event.y = y;
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
- event.alt = altDown_;
-
- Widget* target = startWidget;
- while (target && !event.consumed && !event.propagationStopped) {
- if (target->onMouseUp(event)) {
- event.consume();
- }
- target = target->getParent();
- }
- }
-
- if (button == MouseButton::Left) {
- pressedWidget_ = nullptr;
- }
-
- updateHoveredWidget(x, y);
-}
-
-void UIContext::processMouseScroll(f32 deltaX, f32 deltaY, f32 x, f32 y) {
- updateHoveredWidget(x, y);
-
- if (hoveredWidget_) {
- ScrollEvent event;
- event.deltaX = deltaX;
- event.deltaY = deltaY;
- event.x = x;
- event.y = y;
- event.ctrl = ctrlDown_;
- event.shift = shiftDown_;
-
- Widget* target = hoveredWidget_;
- while (target && !event.consumed && !event.propagationStopped) {
- if (target->onScroll(event)) {
- event.consume();
- }
- target = target->getParent();
- }
- }
-}
-
-void UIContext::processKeyDown(KeyCode key, bool ctrl, bool shift, bool alt) {
- ctrlDown_ = ctrl;
- shiftDown_ = shift;
- altDown_ = alt;
-
- if (focusedWidget_) {
- KeyEvent event;
- event.key = key;
- event.pressed = true;
- event.ctrl = ctrl;
- event.shift = shift;
- event.alt = alt;
-
- Widget* target = focusedWidget_;
- while (target && !event.consumed && !event.propagationStopped) {
- if (target->onKeyDown(event)) {
- event.consume();
- }
- target = target->getParent();
- }
- }
-}
-
-void UIContext::processKeyUp(KeyCode key, bool ctrl, bool shift, bool alt) {
- ctrlDown_ = ctrl;
- shiftDown_ = shift;
- altDown_ = alt;
-
- if (focusedWidget_) {
- KeyEvent event;
- event.key = key;
- event.pressed = false;
- event.ctrl = ctrl;
- event.shift = shift;
- event.alt = alt;
-
- Widget* target = focusedWidget_;
- while (target && !event.consumed && !event.propagationStopped) {
- if (target->onKeyUp(event)) {
- event.consume();
- }
- target = target->getParent();
- }
- }
-}
-
-void UIContext::processTextInput(const std::string& text) {
- if (focusedWidget_ && !text.empty()) {
- TextInputEvent event;
- event.text = text;
- event.codepoint = static_cast<u32>(text[0]);
-
- focusedWidget_->onTextInput(event);
- }
-}
-
-// =============================================================================
-// Focus Management
-// =============================================================================
-
-Widget* UIContext::getFocusedWidget() {
- if (focusedWidget_ && focusedWidget_->getContext() != this) {
- focusedWidget_ = nullptr;
- }
- return focusedWidget_;
-}
-
-void UIContext::setFocus(Widget* widget) {
- if (focusedWidget_ == widget) return;
-
- if (focusedWidget_) {
- BlurEvent blurEvent;
- focusedWidget_->setFocused(false);
- focusedWidget_->onBlur(blurEvent);
- }
-
- focusedWidget_ = widget;
-
- if (focusedWidget_) {
- FocusEvent focusEvent;
- focusedWidget_->setFocused(true);
- focusedWidget_->onFocus(focusEvent);
- }
-}
-
-void UIContext::clearWidgetReferences(Widget* widget) {
- if (!widget) return;
-
- if (focusedWidget_ == widget) {
- focusedWidget_ = nullptr;
- }
- if (hoveredWidget_ == widget) {
- hoveredWidget_ = nullptr;
- }
- if (pressedWidget_ == widget) {
- pressedWidget_ = nullptr;
- }
-}
-
-Widget* UIContext::findWidgetById(const WidgetId& id) {
- if (!root_) return nullptr;
-
- if (root_->getId() == id) {
- return root_.get();
- }
-
- return root_->findChild(id);
-}
-
-// =============================================================================
-// Internal
-// =============================================================================
-
-void UIContext::updateHoveredWidget(f32 x, f32 y) {
- Widget* newHovered = root_ ? root_->hitTest(x, y) : nullptr;
-
- if (newHovered != hoveredWidget_) {
- if (hoveredWidget_) {
- MouseLeaveEvent leaveEvent;
- hoveredWidget_->onMouseLeave(leaveEvent);
-
- if (!pressedWidget_) {
- hoveredWidget_->setState(false, false);
- }
- }
-
- hoveredWidget_ = newHovered;
-
- if (hoveredWidget_) {
- MouseEnterEvent enterEvent;
- enterEvent.x = x;
- enterEvent.y = y;
- hoveredWidget_->onMouseEnter(enterEvent);
-
- if (!pressedWidget_ || pressedWidget_ == hoveredWidget_) {
- hoveredWidget_->setState(true, false);
- }
- }
- }
-}
-
-// =============================================================================
-// Overlay Management
-// =============================================================================
-
-void UIContext::addOverlay(Widget* overlay) {
- if (!overlay) return;
-
- auto it = std::find(overlays_.begin(), overlays_.end(), overlay);
- if (it == overlays_.end()) {
- overlays_.push_back(overlay);
- overlay->setContext(this);
- }
-}
-
-void UIContext::removeOverlay(Widget* overlay) {
- auto it = std::find(overlays_.begin(), overlays_.end(), overlay);
- if (it != overlays_.end()) {
- overlays_.erase(it);
- }
-}
-
-// =============================================================================
-// Clipboard
-// =============================================================================
-
-void UIContext::setClipboardText(const std::string& text) {
- clipboardText_ = text;
-
- // TODO: Integrate with platform clipboard when available
- // Platform::setClipboard(text);
-}
-
-std::string UIContext::getClipboardText() const {
- // TODO: Integrate with platform clipboard when available
- // return Platform::getClipboard();
-
- return clipboardText_;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/UIContext.hpp b/src/esengine/ui/UIContext.hpp
deleted file mode 100644
index 1468d79f4..000000000
--- a/src/esengine/ui/UIContext.hpp
+++ /dev/null
@@ -1,454 +0,0 @@
-/**
- * @file UIContext.hpp
- * @brief Central UI coordinator
- * @details Manages the UI widget tree, themes, fonts, input processing,
- * and rendering coordination.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../core/Types.hpp"
-#include "../platform/Platform.hpp"
-#include "core/Theme.hpp"
-#include "core/Types.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine {
-
-class RenderContext;
-class Dispatcher;
-
-namespace ui {
-
-#if ES_FEATURE_SDF_FONT
-class SDFFont;
-class MSDFFont;
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-class BitmapFont;
-#endif
-
-class SystemFont;
-class UIBatchRenderer;
-class Widget;
-
-#if ES_FEATURE_SDF_FONT
-using Font = SDFFont;
-#elif ES_FEATURE_BITMAP_FONT
-using Font = BitmapFont;
-#endif
-
-// =============================================================================
-// UIContext Class
-// =============================================================================
-
-/**
- * @brief Central coordinator for the UI system
- *
- * @details Manages the complete UI lifecycle including:
- * - Widget tree management
- * - Theme and font management
- * - Input event processing
- * - Rendering coordination
- *
- * @code
- * UIContext ui(renderContext, dispatcher);
- * ui.init();
- * ui.loadFont("default", "assets/fonts/Roboto.ttf");
- *
- * auto root = makeUnique<Panel>("root");
- * root->addChild(makeUnique<Button>("btn", "Click Me"));
- * ui.setRoot(std::move(root));
- *
- * // In game loop:
- * ui.update(deltaTime);
- * ui.render();
- * @endcode
- */
-class UIContext {
-public:
- UIContext(RenderContext& renderContext, Dispatcher& dispatcher);
- ~UIContext();
-
- // Non-copyable
- UIContext(const UIContext&) = delete;
- UIContext& operator=(const UIContext&) = delete;
-
- // =========================================================================
- // Lifecycle
- // =========================================================================
-
- /**
- * @brief Initializes the UI context
- */
- void init();
-
- /**
- * @brief Shuts down the UI context
- */
- void shutdown();
-
- /**
- * @brief Returns true if initialized
- */
- bool isInitialized() const;
-
- // =========================================================================
- // Root Widget
- // =========================================================================
-
- /**
- * @brief Sets the root widget of the UI tree
- * @param root The root widget (ownership transferred)
- */
- void setRoot(Unique<Widget> root);
-
- /**
- * @brief Gets the root widget
- */
- Widget* getRoot() { return root_.get(); }
-
- /**
- * @brief Gets the root widget (const)
- */
- const Widget* getRoot() const { return root_.get(); }
-
- // =========================================================================
- // Theme
- // =========================================================================
-
- /**
- * @brief Sets the UI theme
- * @param theme New theme (ownership transferred)
- */
- void setTheme(Unique<Theme> theme);
-
- /**
- * @brief Gets the current theme
- */
- Theme& getTheme() { return *theme_; }
-
- /**
- * @brief Gets the current theme (const)
- */
- const Theme& getTheme() const { return *theme_; }
-
- // =========================================================================
- // Font Management
- // =========================================================================
-
-#if ES_FEATURE_SDF_FONT
- /**
- * @brief Loads a font from file (uses SDF rendering)
- */
- SDFFont* loadFont(const std::string& name, const std::string& path, f32 fontSize = 48.0f,
- f32 sdfSpread = 8.0f);
-
- SDFFont* getFont(const std::string& name);
- SDFFont* getDefaultFont();
- SDFFont* getIconFont();
-
- /**
- * @brief Loads a font from file (uses MSDF rendering for sharper text)
- */
- MSDFFont* loadMSDFFont(const std::string& name, const std::string& path, f32 fontSize = 32.0f,
- f32 pixelRange = 4.0f);
-
- MSDFFont* getMSDFFont(const std::string& name);
- MSDFFont* getDefaultMSDFFont();
- MSDFFont* getIconMSDFFont();
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
- /**
- * @brief Loads a bitmap font from atlas and metrics files
- */
- BitmapFont* loadBitmapFont(const std::string& name, const std::string& atlasPath,
- const std::string& metricsPath);
-
- BitmapFont* getBitmapFont(const std::string& name);
- BitmapFont* getDefaultBitmapFont();
-#endif
-
- /**
- * @brief Creates a system font using OS native APIs
- * @param name Font identifier name
- * @param fontFamily System font family (e.g. "Microsoft YaHei", "Arial")
- * @param fontSize Font size in pixels
- * @return Pointer to created font or nullptr on failure
- */
- SystemFont* createSystemFont(const std::string& name, const std::string& fontFamily,
- f32 fontSize = 32.0f);
-
- /**
- * @brief Creates a font from a TTF file
- * @param name Font identifier name
- * @param filePath Path to TTF font file
- * @param fontSize Font size in pixels
- * @return Pointer to created font or nullptr on failure
- */
- SystemFont* createSystemFontFromFile(const std::string& name, const std::string& filePath,
- f32 fontSize = 32.0f);
-
- SystemFont* getSystemFont(const std::string& name);
- SystemFont* getDefaultSystemFont();
- SystemFont* getIconSystemFont();
-
- void setDefaultFontName(const std::string& name) { defaultFontName_ = name; }
-
- // =========================================================================
- // Update and Render
- // =========================================================================
-
- /**
- * @brief Updates the UI
- * @param deltaTime Time since last update in seconds
- */
- void update(f32 deltaTime);
-
- /**
- * @brief Renders the UI
- */
- void render();
-
- /**
- * @brief Sets the viewport size
- * @param width Viewport width in logical pixels
- * @param height Viewport height in logical pixels
- */
- void setViewport(u32 width, u32 height);
-
- /**
- * @brief Sets the device pixel ratio for high-DPI displays
- * @param ratio Pixel ratio (1.0 for standard, 2.0 for retina, etc.)
- */
- void setDevicePixelRatio(f32 ratio);
-
- /**
- * @brief Gets the device pixel ratio
- */
- f32 getDevicePixelRatio() const { return devicePixelRatio_; }
-
- /**
- * @brief Gets the viewport size
- */
- glm::vec2 getViewportSize() const { return {viewportWidth_, viewportHeight_}; }
-
- /**
- * @brief Gets the current mouse position
- */
- glm::vec2 getMousePosition() const { return {lastMouseX_, lastMouseY_}; }
-
- // =========================================================================
- // Input Processing
- // =========================================================================
-
- /**
- * @brief Processes mouse movement
- * @param x Mouse X position
- * @param y Mouse Y position
- */
- void processMouseMove(f32 x, f32 y);
-
- /**
- * @brief Processes mouse button press
- * @param button Mouse button
- * @param x Mouse X position
- * @param y Mouse Y position
- */
- void processMouseDown(MouseButton button, f32 x, f32 y);
-
- /**
- * @brief Processes mouse button release
- * @param button Mouse button
- * @param x Mouse X position
- * @param y Mouse Y position
- */
- void processMouseUp(MouseButton button, f32 x, f32 y);
-
- /**
- * @brief Processes mouse scroll
- * @param deltaX Horizontal scroll amount
- * @param deltaY Vertical scroll amount
- * @param x Mouse X position
- * @param y Mouse Y position
- */
- void processMouseScroll(f32 deltaX, f32 deltaY, f32 x, f32 y);
-
- /**
- * @brief Processes key press
- * @param key Key code
- * @param ctrl Control modifier
- * @param shift Shift modifier
- * @param alt Alt modifier
- */
- void processKeyDown(KeyCode key, bool ctrl, bool shift, bool alt);
-
- /**
- * @brief Processes key release
- * @param key Key code
- * @param ctrl Control modifier
- * @param shift Shift modifier
- * @param alt Alt modifier
- */
- void processKeyUp(KeyCode key, bool ctrl, bool shift, bool alt);
-
- /**
- * @brief Processes text input
- * @param text Input text
- */
- void processTextInput(const std::string& text);
-
- // =========================================================================
- // Focus Management
- // =========================================================================
-
- /**
- * @brief Gets the currently focused widget
- * @return Focused widget or nullptr if none/invalid
- */
- Widget* getFocusedWidget();
-
- /**
- * @brief Sets focus to a widget
- * @param widget Widget to focus (nullptr to clear focus)
- */
- void setFocus(Widget* widget);
-
- /**
- * @brief Clears focus from all widgets
- */
- void clearFocus() { setFocus(nullptr); }
-
- /**
- * @brief Clears all references to a widget (called when widget is destroyed)
- * @param widget Widget being destroyed
- */
- void clearWidgetReferences(Widget* widget);
-
- /**
- * @brief Finds a widget by ID in the tree
- * @param id Widget ID to find
- * @return Widget pointer or nullptr if not found
- */
- Widget* findWidgetById(const WidgetId& id);
-
- // =========================================================================
- // Overlay Management
- // =========================================================================
-
- /**
- * @brief Adds an overlay widget (rendered on top of everything)
- * @param overlay Widget to add as overlay
- */
- void addOverlay(Widget* overlay);
-
- /**
- * @brief Removes an overlay widget
- * @param overlay Widget to remove
- */
- void removeOverlay(Widget* overlay);
-
- /**
- * @brief Checks if any overlay is currently active
- */
- bool hasActiveOverlay() const { return !overlays_.empty(); }
-
- // =========================================================================
- // Clipboard
- // =========================================================================
-
- /**
- * @brief Sets the clipboard text
- * @param text Text to copy to clipboard
- */
- void setClipboardText(const std::string& text);
-
- /**
- * @brief Gets the clipboard text
- * @return Current clipboard text
- */
- std::string getClipboardText() const;
-
- // =========================================================================
- // Renderer Access
- // =========================================================================
-
- /**
- * @brief Gets the UI batch renderer
- */
- UIBatchRenderer& getRenderer() { return *renderer_; }
-
- /**
- * @brief Gets the render context
- */
- RenderContext& getRenderContext() { return renderContext_; }
-
- /**
- * @brief Gets the event dispatcher
- */
- Dispatcher& getDispatcher() { return dispatcher_; }
-
-private:
- void updateHoveredWidget(f32 x, f32 y);
- void doLayout();
-
- RenderContext& renderContext_;
- Dispatcher& dispatcher_;
-
- Unique<UIBatchRenderer> renderer_;
- Unique<Widget> root_;
- Unique<Theme> theme_;
-
-#if ES_FEATURE_SDF_FONT
- std::unordered_map<std::string, Unique<SDFFont>> fonts_;
- std::unordered_map<std::string, Unique<MSDFFont>> msdfFonts_;
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
- std::unordered_map<std::string, Unique<BitmapFont>> bitmapFonts_;
-#endif
-
- std::unordered_map<std::string, Unique<SystemFont>> systemFonts_;
-
- std::string defaultFontName_ = "default";
-
- u32 viewportWidth_ = 0;
- u32 viewportHeight_ = 0;
- f32 devicePixelRatio_ = 1.0f;
-
- Widget* focusedWidget_ = nullptr;
- Widget* hoveredWidget_ = nullptr;
- Widget* pressedWidget_ = nullptr;
-
- f32 lastMouseX_ = 0.0f;
- f32 lastMouseY_ = 0.0f;
- bool mouseButtonDown_[static_cast<usize>(MouseButton::Count)] = {};
- bool ctrlDown_ = false;
- bool shiftDown_ = false;
- bool altDown_ = false;
-
- std::string clipboardText_;
-
- std::vector<Widget*> overlays_;
-
- bool initialized_ = false;
-};
-
-} // namespace ui
-} // namespace esengine
diff --git a/src/esengine/ui/core/Theme.hpp b/src/esengine/ui/core/Theme.hpp
deleted file mode 100644
index 13f4ba8d2..000000000
--- a/src/esengine/ui/core/Theme.hpp
+++ /dev/null
@@ -1,486 +0,0 @@
-/**
- * @file Theme.hpp
- * @brief UI theming system for consistent visual styling
- * @details Provides theme colors, spacing constants, and widget styles
- * for a unified visual appearance across the UI system.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Types.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Theme Colors
-// =============================================================================
-
-/**
- * @brief Color palette for theming
- *
- * @details Contains all colors used by the UI system, organized by
- * semantic purpose rather than specific widgets.
- */
-struct ThemeColors {
- glm::vec4 background{0.118f, 0.118f, 0.118f, 1.0f};
- glm::vec4 backgroundDark{0.094f, 0.094f, 0.094f, 1.0f};
- glm::vec4 backgroundMedium{0.145f, 0.145f, 0.149f, 1.0f};
- glm::vec4 backgroundLight{0.176f, 0.176f, 0.176f, 1.0f};
- glm::vec4 surface{0.145f, 0.145f, 0.149f, 1.0f};
- glm::vec4 surfaceHover{0.165f, 0.176f, 0.180f, 1.0f};
-
- glm::vec4 textPrimary{0.8f, 0.8f, 0.8f, 1.0f};
- glm::vec4 textSecondary{0.522f, 0.522f, 0.522f, 1.0f};
- glm::vec4 textDisabled{0.431f, 0.431f, 0.431f, 1.0f};
- glm::vec4 textPlaceholder{0.431f, 0.431f, 0.431f, 1.0f};
-
- glm::vec4 accent{0.055f, 0.388f, 0.612f, 1.0f};
- glm::vec4 accentHover{0.067f, 0.467f, 0.733f, 1.0f};
- glm::vec4 accentPressed{0.043f, 0.310f, 0.490f, 1.0f};
-
- glm::vec4 button{0.176f, 0.176f, 0.188f, 1.0f};
- glm::vec4 buttonHover{0.216f, 0.216f, 0.239f, 1.0f};
- glm::vec4 buttonPressed{0.157f, 0.157f, 0.169f, 1.0f};
- glm::vec4 buttonDisabled{0.176f, 0.176f, 0.176f, 1.0f};
- glm::vec4 buttonBorder{0.243f, 0.243f, 0.259f, 1.0f};
-
- glm::vec4 input{0.051f, 0.051f, 0.051f, 1.0f};
- glm::vec4 inputBorder{0.2f, 0.2f, 0.2f, 1.0f};
- glm::vec4 inputBorderFocused{0.0f, 0.478f, 0.8f, 1.0f};
-
- glm::vec4 border{0.243f, 0.243f, 0.259f, 1.0f};
- glm::vec4 borderLight{0.314f, 0.314f, 0.314f, 1.0f};
- glm::vec4 separator{0.169f, 0.169f, 0.169f, 1.0f};
-
- glm::vec4 selection{0.035f, 0.278f, 0.443f, 1.0f};
- glm::vec4 highlight{1.0f, 1.0f, 1.0f, 0.05f};
- glm::vec4 error{0.957f, 0.529f, 0.443f, 1.0f};
- glm::vec4 warning{0.808f, 0.569f, 0.471f, 1.0f};
- glm::vec4 success{0.306f, 0.788f, 0.690f, 1.0f};
-
- glm::vec4 scrollbarTrack{0.0f, 0.0f, 0.0f, 0.0f};
- glm::vec4 scrollbarThumb{1.0f, 1.0f, 1.0f, 0.1f};
- glm::vec4 scrollbarThumbHover{1.0f, 1.0f, 1.0f, 0.2f};
-
- glm::vec4 shadow{0.0f, 0.0f, 0.0f, 0.4f};
- glm::vec4 overlay{0.0f, 0.0f, 0.0f, 0.5f};
-
- glm::vec4 dockTabBackground{0.165f, 0.165f, 0.165f, 1.0f};
- glm::vec4 dockTabHover{0.2f, 0.2f, 0.2f, 1.0f};
- glm::vec4 dockTabActive{0.118f, 0.118f, 0.118f, 1.0f};
- glm::vec4 dockTabIndicator{0.0f, 0.478f, 0.8f, 1.0f};
- glm::vec4 dockSplitter{0.102f, 0.102f, 0.102f, 1.0f};
- glm::vec4 dockSplitterHover{0.29f, 0.61f, 1.0f, 1.0f};
- glm::vec4 dockDropPreview{0.29f, 0.61f, 1.0f, 0.15f};
- glm::vec4 dockZoneButton{0.235f, 0.235f, 0.235f, 0.9f};
- glm::vec4 dockZoneButtonHover{0.0f, 0.478f, 0.8f, 1.0f};
-};
-
-// =============================================================================
-// Theme Spacing
-// =============================================================================
-
-/**
- * @brief Spacing constants for consistent layout
- *
- * @details Defines standard spacing values used throughout the UI
- * for padding, margins, and gaps.
- */
-struct ThemeSpacing {
- f32 unit = 4.0f;
-
- f32 xs = 2.0f;
- f32 sm = 4.0f;
- f32 md = 8.0f;
- f32 lg = 12.0f;
- f32 xl = 16.0f;
- f32 xxl = 24.0f;
-
- f32 panelPadding = 8.0f;
- f32 itemSpacing = 4.0f;
- f32 sectionSpacing = 16.0f;
-
- f32 borderRadius = 4.0f;
- f32 borderRadiusLarge = 8.0f;
- f32 borderWidth = 1.0f;
-
- f32 scrollbarWidth = 12.0f;
- f32 scrollbarMinThumb = 32.0f;
-
- // Docking spacing
- f32 dockTabHeight = 24.0f;
- f32 dockTabMinWidth = 80.0f;
- f32 dockTabMaxWidth = 200.0f;
- f32 dockTabPadding = 8.0f;
- f32 dockTabSpacing = 1.0f;
- f32 dockTabCloseSize = 14.0f;
- f32 dockSplitterSize = 4.0f;
- f32 dockZoneSize = 32.0f;
- f32 dockZoneGap = 4.0f;
- f32 dockDropPreviewAlpha = 0.30f;
- f32 dockEdgeThreshold = 0.30f;
-};
-
-// =============================================================================
-// Theme Typography
-// =============================================================================
-
-/**
- * @brief Typography settings for text rendering
- */
-struct ThemeTypography {
- std::string defaultFont = "default";
-
- f32 fontSizeSmall = 12.0f;
- f32 fontSizeNormal = 14.0f;
- f32 fontSizeMedium = 18.0f;
- f32 fontSizeLarge = 22.0f;
- f32 fontSizeTitle = 26.0f;
- f32 fontSizeHeader = 32.0f;
-
- f32 lineHeight = 1.4f;
- f32 letterSpacing = 0.0f;
-};
-
-// =============================================================================
-// Widget Style
-// =============================================================================
-
-/**
- * @brief Style configuration for a specific widget type
- *
- * @details Contains all visual properties that can be applied to a widget,
- * including colors, spacing, and corner radii.
- */
-struct WidgetStyle {
- glm::vec4 backgroundColor{0.0f, 0.0f, 0.0f, 0.0f};
- glm::vec4 backgroundColorHover{0.0f, 0.0f, 0.0f, 0.0f};
- glm::vec4 backgroundColorPressed{0.0f, 0.0f, 0.0f, 0.0f};
- glm::vec4 backgroundColorDisabled{0.0f, 0.0f, 0.0f, 0.0f};
-
- glm::vec4 foregroundColor{1.0f, 1.0f, 1.0f, 1.0f};
- glm::vec4 foregroundColorHover{1.0f, 1.0f, 1.0f, 1.0f};
- glm::vec4 foregroundColorPressed{1.0f, 1.0f, 1.0f, 1.0f};
- glm::vec4 foregroundColorDisabled{0.5f, 0.5f, 0.5f, 1.0f};
-
- glm::vec4 textColor{1.0f, 1.0f, 1.0f, 1.0f};
- glm::vec4 textColorDisabled{0.5f, 0.5f, 0.5f, 1.0f};
-
- glm::vec4 borderColor{0.0f, 0.0f, 0.0f, 0.0f};
- glm::vec4 borderColorFocused{0.0f, 0.0f, 0.0f, 0.0f};
-
- f32 borderWidth = 0.0f;
- CornerRadii cornerRadii;
- Insets padding;
-
- f32 fontSize = 14.0f;
-
- /** @brief Gets the background color based on widget state */
- glm::vec4 getBackgroundColor(const WidgetState& state) const {
- if (state.disabled) {
- return backgroundColorDisabled;
- }
- if (state.pressed) {
- return backgroundColorPressed;
- }
- if (state.hovered) {
- return backgroundColorHover;
- }
- return backgroundColor;
- }
-
- /** @brief Gets the foreground color based on widget state */
- glm::vec4 getForegroundColor(const WidgetState& state) const {
- if (state.disabled) {
- return foregroundColorDisabled;
- }
- if (state.pressed) {
- return foregroundColorPressed;
- }
- if (state.hovered) {
- return foregroundColorHover;
- }
- return foregroundColor;
- }
-
- /** @brief Gets the text color based on widget state */
- glm::vec4 getTextColor(const WidgetState& state) const {
- return state.disabled ? textColorDisabled : textColor;
- }
-
- /** @brief Gets the border color based on widget state */
- glm::vec4 getBorderColor(const WidgetState& state) const {
- return state.focused ? borderColorFocused : borderColor;
- }
-};
-
-// =============================================================================
-// Theme
-// =============================================================================
-
-/**
- * @brief Complete UI theme containing colors, spacing, and widget styles
- *
- * @details Provides a centralized configuration for all visual aspects
- * of the UI system. Create custom themes by copying and modifying
- * the default theme.
- */
-class Theme {
-public:
- ThemeColors colors;
- ThemeSpacing spacing;
- ThemeTypography typography;
-
- /** @brief Creates the default dark theme */
- static Unique<Theme> createDark() {
- auto theme = makeUnique<Theme>();
- theme->initDark();
- return theme;
- }
-
- /** @brief Creates a light theme */
- static Unique<Theme> createLight() {
- auto theme = makeUnique<Theme>();
- theme->initLight();
- return theme;
- }
-
- /** @brief Gets the style for a panel widget */
- WidgetStyle getPanelStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.surface;
- style.backgroundColorHover = colors.surface;
- style.backgroundColorPressed = colors.surface;
- style.backgroundColorDisabled = colors.surface;
- style.borderColor = colors.border;
- style.borderWidth = spacing.borderWidth;
- style.cornerRadii = CornerRadii::all(spacing.borderRadius);
- style.padding = Insets::all(spacing.panelPadding);
- return style;
- }
-
- /** @brief Gets the style for a button widget */
- WidgetStyle getButtonStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.button;
- style.backgroundColorHover = colors.buttonHover;
- style.backgroundColorPressed = colors.buttonPressed;
- style.backgroundColorDisabled = colors.buttonDisabled;
- style.textColor = colors.textPrimary;
- style.textColorDisabled = colors.textDisabled;
- style.cornerRadii = CornerRadii::all(spacing.borderRadius);
- style.padding = Insets::symmetric(spacing.lg, spacing.md);
- style.fontSize = typography.fontSizeNormal;
- return style;
- }
-
- /** @brief Gets the style for a primary (accent) button */
- WidgetStyle getPrimaryButtonStyle() const {
- WidgetStyle style = getButtonStyle();
- style.backgroundColor = colors.accent;
- style.backgroundColorHover = colors.accentHover;
- style.backgroundColorPressed = colors.accentPressed;
- return style;
- }
-
- /** @brief Gets the style for a label widget */
- WidgetStyle getLabelStyle() const {
- WidgetStyle style;
- style.textColor = colors.textPrimary;
- style.textColorDisabled = colors.textDisabled;
- style.fontSize = typography.fontSizeNormal;
- return style;
- }
-
- /** @brief Gets the style for a scrollbar widget */
- WidgetStyle getScrollbarStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.scrollbarTrack;
- style.backgroundColorHover = colors.scrollbarTrack;
- style.foregroundColor = colors.scrollbarThumb;
- style.foregroundColorHover = colors.scrollbarThumbHover;
- return style;
- }
-
- /** @brief Gets the style for a text input widget */
- WidgetStyle getTextInputStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.input;
- style.backgroundColorHover = colors.input;
- style.backgroundColorPressed = colors.input;
- style.backgroundColorDisabled = colors.backgroundDark;
- style.textColor = colors.textPrimary;
- style.textColorDisabled = colors.textDisabled;
- style.borderColor = colors.inputBorder;
- style.borderColorFocused = colors.inputBorderFocused;
- style.borderWidth = spacing.borderWidth;
- style.cornerRadii = CornerRadii::all(spacing.borderRadius);
- style.padding = Insets::symmetric(spacing.md, spacing.sm);
- style.fontSize = typography.fontSizeNormal;
- return style;
- }
-
- /** @brief Gets the style for a slider track */
- WidgetStyle getSliderTrackStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.backgroundDark;
- style.backgroundColorHover = colors.backgroundDark;
- style.cornerRadii = CornerRadii::all(2.0f);
- return style;
- }
-
- /** @brief Gets the style for a slider thumb */
- WidgetStyle getSliderThumbStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.accent;
- style.backgroundColorHover = colors.accentHover;
- style.backgroundColorPressed = colors.accentPressed;
- style.cornerRadii = CornerRadii::all(6.0f);
- return style;
- }
-
- // =========================================================================
- // Docking Styles
- // =========================================================================
-
- /** @brief Gets the style for a dock tab bar background */
- WidgetStyle getDockTabBarStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.dockTabBackground;
- style.backgroundColorHover = colors.dockTabBackground;
- style.backgroundColorPressed = colors.dockTabBackground;
- style.padding = Insets{0.0f, spacing.dockTabPadding, 0.0f, spacing.dockTabPadding};
- return style;
- }
-
- /** @brief Gets the style for an inactive dock tab */
- WidgetStyle getDockTabStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.dockTabBackground;
- style.backgroundColorHover = colors.dockTabHover;
- style.backgroundColorPressed = colors.dockTabActive;
- style.textColor = colors.textSecondary;
- style.textColorDisabled = colors.textDisabled;
- style.padding = Insets::symmetric(spacing.dockTabPadding, spacing.sm);
- style.fontSize = typography.fontSizeSmall;
- return style;
- }
-
- /** @brief Gets the style for an active dock tab */
- WidgetStyle getDockTabActiveStyle() const {
- WidgetStyle style = getDockTabStyle();
- style.backgroundColor = colors.dockTabActive;
- style.backgroundColorHover = colors.dockTabActive;
- style.textColor = colors.textPrimary;
- style.borderColor = colors.dockTabIndicator;
- style.borderWidth = 2.0f;
- return style;
- }
-
- /** @brief Gets the style for the dock splitter */
- WidgetStyle getDockSplitterStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.dockSplitter;
- style.backgroundColorHover = colors.dockSplitterHover;
- style.backgroundColorPressed = colors.dockSplitterHover;
- return style;
- }
-
- /** @brief Gets the style for dock zone indicator buttons */
- WidgetStyle getDockZoneButtonStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.dockZoneButton;
- style.backgroundColorHover = colors.dockZoneButtonHover;
- style.backgroundColorPressed = colors.dockZoneButtonHover;
- style.textColor = colors.textSecondary;
- style.borderColor = colors.accent;
- style.borderWidth = 1.0f;
- style.cornerRadii = CornerRadii::all(4.0f);
- return style;
- }
-
- /** @brief Gets the style for dock drop preview overlay */
- WidgetStyle getDockDropPreviewStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.dockDropPreview;
- style.backgroundColorHover = colors.dockDropPreview;
- return style;
- }
-
- /** @brief Gets the style for dock panel content area */
- WidgetStyle getDockPanelStyle() const {
- WidgetStyle style;
- style.backgroundColor = colors.background;
- style.backgroundColorHover = colors.background;
- style.borderColor = colors.border;
- style.borderWidth = 0.0f;
- style.padding = Insets::all(spacing.panelPadding);
- return style;
- }
-
-private:
- void initDark() {
- // Colors are already initialized to dark theme defaults
- }
-
- void initLight() {
- // Override with light theme colors
- colors.background = {0.95f, 0.95f, 0.95f, 1.0f};
- colors.backgroundDark = {0.90f, 0.90f, 0.90f, 1.0f};
- colors.backgroundMedium = {0.93f, 0.93f, 0.93f, 1.0f};
- colors.backgroundLight = {1.0f, 1.0f, 1.0f, 1.0f};
- colors.surface = {1.0f, 1.0f, 1.0f, 1.0f};
- colors.surfaceHover = {0.98f, 0.98f, 0.98f, 1.0f};
-
- colors.textPrimary = {0.10f, 0.10f, 0.10f, 1.0f};
- colors.textSecondary = {0.40f, 0.40f, 0.40f, 1.0f};
- colors.textDisabled = {0.60f, 0.60f, 0.60f, 1.0f};
- colors.textPlaceholder = {0.55f, 0.55f, 0.55f, 1.0f};
-
- colors.button = {0.90f, 0.90f, 0.90f, 1.0f};
- colors.buttonHover = {0.85f, 0.85f, 0.85f, 1.0f};
- colors.buttonPressed = {0.80f, 0.80f, 0.80f, 1.0f};
- colors.buttonDisabled = {0.92f, 0.92f, 0.92f, 1.0f};
-
- colors.input = {1.0f, 1.0f, 1.0f, 1.0f};
- colors.inputBorder = {0.75f, 0.75f, 0.75f, 1.0f};
-
- colors.border = {0.80f, 0.80f, 0.80f, 1.0f};
- colors.borderLight = {0.85f, 0.85f, 0.85f, 1.0f};
- colors.separator = {0.88f, 0.88f, 0.88f, 1.0f};
-
- colors.selection = {0.26f, 0.59f, 0.98f, 0.20f};
- colors.highlight = {0.0f, 0.0f, 0.0f, 0.03f};
-
- colors.scrollbarTrack = {0.90f, 0.90f, 0.90f, 0.5f};
- colors.scrollbarThumb = {0.60f, 0.60f, 0.60f, 0.5f};
- colors.scrollbarThumbHover = {0.50f, 0.50f, 0.50f, 0.6f};
-
- colors.shadow = {0.0f, 0.0f, 0.0f, 0.15f};
- colors.overlay = {0.0f, 0.0f, 0.0f, 0.3f};
-
- // Light theme docking colors
- colors.dockTabBackground = {0.92f, 0.92f, 0.92f, 1.0f};
- colors.dockTabHover = {0.88f, 0.88f, 0.88f, 1.0f};
- colors.dockTabActive = {1.0f, 1.0f, 1.0f, 1.0f};
- colors.dockSplitter = {0.85f, 0.85f, 0.85f, 1.0f};
- colors.dockSplitterHover = {0.26f, 0.59f, 0.98f, 1.0f};
- colors.dockDropPreview = {0.26f, 0.59f, 0.98f, 0.20f};
- colors.dockZoneButton = {0.95f, 0.95f, 0.95f, 0.95f};
- }
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/core/Types.hpp b/src/esengine/ui/core/Types.hpp
deleted file mode 100644
index 653cc86f9..000000000
--- a/src/esengine/ui/core/Types.hpp
+++ /dev/null
@@ -1,429 +0,0 @@
-/**
- * @file Types.hpp
- * @brief Core UI type definitions for the ESEngine UI system
- * @details Provides fundamental types for UI layout and rendering including
- * rectangles, insets, widget state, widget identification, and
- * corner radii for rounded rectangles.
- *
- * @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 <functional>
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Rect
-// =============================================================================
-
-/**
- * @brief Axis-aligned rectangle defined by position and size
- *
- * @details Used for widget bounds, clip regions, and hit testing.
- * Origin is top-left corner with Y increasing downward.
- */
-struct Rect {
- f32 x = 0.0f;
- f32 y = 0.0f;
- f32 width = 0.0f;
- f32 height = 0.0f;
-
- constexpr Rect() = default;
- constexpr Rect(f32 x, f32 y, f32 w, f32 h) : x(x), y(y), width(w), height(h) {}
-
- /** @brief Creates a rect from position and size vectors */
- static constexpr Rect fromPosSize(const glm::vec2& pos, const glm::vec2& size) {
- return Rect(pos.x, pos.y, size.x, size.y);
- }
-
- /** @brief Creates a rect from min/max corners */
- static constexpr Rect fromMinMax(const glm::vec2& min, const glm::vec2& max) {
- return Rect(min.x, min.y, max.x - min.x, max.y - min.y);
- }
-
- /** @brief Returns the left edge X coordinate */
- constexpr f32 left() const { return x; }
-
- /** @brief Returns the top edge Y coordinate */
- constexpr f32 top() const { return y; }
-
- /** @brief Returns the right edge X coordinate */
- constexpr f32 right() const { return x + width; }
-
- /** @brief Returns the bottom edge Y coordinate */
- constexpr f32 bottom() const { return y + height; }
-
- /** @brief Returns the top-left corner position */
- constexpr glm::vec2 position() const { return {x, y}; }
-
- /** @brief Returns the size as a vector */
- constexpr glm::vec2 size() const { return {width, height}; }
-
- /** @brief Returns the center point */
- constexpr glm::vec2 center() const { return {x + width * 0.5f, y + height * 0.5f}; }
-
- /** @brief Returns the top-left corner */
- constexpr glm::vec2 topLeft() const { return {x, y}; }
-
- /** @brief Returns the top-right corner */
- constexpr glm::vec2 topRight() const { return {x + width, y}; }
-
- /** @brief Returns the bottom-left corner */
- constexpr glm::vec2 bottomLeft() const { return {x, y + height}; }
-
- /** @brief Returns the bottom-right corner */
- constexpr glm::vec2 bottomRight() const { return {x + width, y + height}; }
-
- /** @brief Tests if a point is inside the rectangle */
- constexpr bool contains(const glm::vec2& point) const {
- return point.x >= x && point.x < x + width && point.y >= y && point.y < y + height;
- }
-
- /** @brief Tests if a point (separate coords) is inside the rectangle */
- constexpr bool contains(f32 px, f32 py) const {
- return px >= x && px < x + width && py >= y && py < y + height;
- }
-
- /** @brief Tests if another rectangle is fully contained */
- constexpr bool contains(const Rect& other) const {
- return other.x >= x && other.right() <= right() && other.y >= y && other.bottom() <= bottom();
- }
-
- /** @brief Tests if this rectangle intersects with another */
- constexpr bool intersects(const Rect& other) const {
- return x < other.right() && right() > other.x && y < other.bottom() && bottom() > other.y;
- }
-
- /** @brief Returns the intersection of two rectangles (may be empty) */
- constexpr Rect intersect(const Rect& other) const {
- f32 l = (x > other.x) ? x : other.x;
- f32 t = (y > other.y) ? y : other.y;
- f32 r = (right() < other.right()) ? right() : other.right();
- f32 b = (bottom() < other.bottom()) ? bottom() : other.bottom();
-
- if (r <= l || b <= t) {
- return Rect();
- }
- return Rect(l, t, r - l, b - t);
- }
-
- /** @brief Returns true if the rectangle has zero or negative area */
- constexpr bool isEmpty() const { return width <= 0.0f || height <= 0.0f; }
-
- /** @brief Returns true if the rectangle is valid (positive size) */
- constexpr bool isValid() const { return width > 0.0f && height > 0.0f; }
-
- constexpr bool operator==(const Rect& other) const {
- return x == other.x && y == other.y && width == other.width && height == other.height;
- }
-
- constexpr bool operator!=(const Rect& other) const { return !(*this == other); }
-};
-
-// =============================================================================
-// Insets
-// =============================================================================
-
-/**
- * @brief Edge insets for padding and margins
- *
- * @details Represents spacing on all four sides of a rectangle.
- * Used for widget padding, margins, and borders.
- */
-struct Insets {
- f32 top = 0.0f;
- f32 right = 0.0f;
- f32 bottom = 0.0f;
- f32 left = 0.0f;
-
- constexpr Insets() = default;
- constexpr Insets(f32 t, f32 r, f32 b, f32 l) : top(t), right(r), bottom(b), left(l) {}
-
- /** @brief Creates insets with the same value on all sides */
- static constexpr Insets all(f32 value) { return Insets(value, value, value, value); }
-
- /** @brief Creates insets with symmetric horizontal and vertical values */
- static constexpr Insets symmetric(f32 horizontal, f32 vertical) {
- return Insets(vertical, horizontal, vertical, horizontal);
- }
-
- /** @brief Creates insets with only horizontal values */
- static constexpr Insets horizontal(f32 value) { return Insets(0.0f, value, 0.0f, value); }
-
- /** @brief Creates insets with only vertical values */
- static constexpr Insets vertical(f32 value) { return Insets(value, 0.0f, value, 0.0f); }
-
- /** @brief Returns the total horizontal inset (left + right) */
- constexpr f32 totalHorizontal() const { return left + right; }
-
- /** @brief Returns the total vertical inset (top + bottom) */
- constexpr f32 totalVertical() const { return top + bottom; }
-
- /** @brief Returns the total size as a vector */
- constexpr glm::vec2 total() const { return {totalHorizontal(), totalVertical()}; }
-
- /** @brief Expands a rectangle by these insets */
- constexpr Rect expand(const Rect& rect) const {
- return Rect(rect.x - left, rect.y - top, rect.width + totalHorizontal(),
- rect.height + totalVertical());
- }
-
- /** @brief Shrinks a rectangle by these insets */
- constexpr Rect shrink(const Rect& rect) const {
- return Rect(rect.x + left, rect.y + top, rect.width - totalHorizontal(),
- rect.height - totalVertical());
- }
-
- constexpr Insets operator+(const Insets& other) const {
- return Insets(top + other.top, right + other.right, bottom + other.bottom,
- left + other.left);
- }
-
- constexpr Insets operator*(f32 scale) const {
- return Insets(top * scale, right * scale, bottom * scale, left * scale);
- }
-
- constexpr bool operator==(const Insets& other) const {
- return top == other.top && right == other.right && bottom == other.bottom &&
- left == other.left;
- }
-
- constexpr bool operator!=(const Insets& other) const { return !(*this == other); }
-};
-
-// =============================================================================
-// CornerRadii
-// =============================================================================
-
-/**
- * @brief Corner radii for rounded rectangles
- *
- * @details Specifies the radius for each corner of a rounded rectangle.
- * Used by the UI renderer for SDF rounded rect drawing.
- */
-struct CornerRadii {
- f32 topLeft = 0.0f;
- f32 topRight = 0.0f;
- f32 bottomRight = 0.0f;
- f32 bottomLeft = 0.0f;
-
- constexpr CornerRadii() = default;
- constexpr CornerRadii(f32 tl, f32 tr, f32 br, f32 bl)
- : topLeft(tl), topRight(tr), bottomRight(br), bottomLeft(bl) {}
-
- /** @brief Creates radii with the same value for all corners */
- static constexpr CornerRadii all(f32 radius) {
- return CornerRadii(radius, radius, radius, radius);
- }
-
- /** @brief Creates radii with top corners only */
- static constexpr CornerRadii top(f32 radius) { return CornerRadii(radius, radius, 0.0f, 0.0f); }
-
- /** @brief Creates radii with bottom corners only */
- static constexpr CornerRadii bottom(f32 radius) {
- return CornerRadii(0.0f, 0.0f, radius, radius);
- }
-
- /** @brief Creates radii with left corners only */
- static constexpr CornerRadii leftSide(f32 radius) {
- return CornerRadii(radius, 0.0f, 0.0f, radius);
- }
-
- /** @brief Creates radii with right corners only */
- static constexpr CornerRadii rightSide(f32 radius) {
- return CornerRadii(0.0f, radius, radius, 0.0f);
- }
-
- /** @brief Returns true if all corners have zero radius */
- constexpr bool isZero() const {
- return topLeft == 0.0f && topRight == 0.0f && bottomRight == 0.0f && bottomLeft == 0.0f;
- }
-
- /** @brief Returns true if all corners have the same radius */
- constexpr bool isUniform() const {
- return topLeft == topRight && topRight == bottomRight && bottomRight == bottomLeft;
- }
-
- /** @brief Returns the maximum corner radius */
- constexpr f32 maxRadius() const {
- f32 m1 = (topLeft > topRight) ? topLeft : topRight;
- f32 m2 = (bottomRight > bottomLeft) ? bottomRight : bottomLeft;
- return (m1 > m2) ? m1 : m2;
- }
-
- /** @brief Returns radii as vec4 (topLeft, topRight, bottomRight, bottomLeft) */
- constexpr glm::vec4 toVec4() const { return {topLeft, topRight, bottomRight, bottomLeft}; }
-
- constexpr bool operator==(const CornerRadii& other) const {
- return topLeft == other.topLeft && topRight == other.topRight &&
- bottomRight == other.bottomRight && bottomLeft == other.bottomLeft;
- }
-
- constexpr bool operator!=(const CornerRadii& other) const { return !(*this == other); }
-};
-
-// =============================================================================
-// WidgetState
-// =============================================================================
-
-/**
- * @brief Interactive state flags for a widget
- *
- * @details Tracks the current interaction state of a widget for
- * visual feedback and input handling.
- */
-struct WidgetState {
- bool hovered = false;
- bool pressed = false;
- bool focused = false;
- bool disabled = false;
- bool visible = true;
-
- /** @brief Returns true if the widget can receive input */
- constexpr bool isInteractive() const { return !disabled && visible; }
-
- /** @brief Returns true if the widget should render as active (pressed or focused) */
- constexpr bool isActive() const { return (pressed || focused) && isInteractive(); }
-
- /** @brief Resets all interaction states (keeps disabled and visible) */
- void resetInteraction() {
- hovered = false;
- pressed = false;
- }
-};
-
-// =============================================================================
-// WidgetId
-// =============================================================================
-
-/**
- * @brief Unique identifier for a widget in the UI hierarchy
- *
- * @details Uses a hierarchical string path and precomputed hash for
- * efficient comparison and lookup.
- */
-struct WidgetId {
- std::string path;
- u64 hash = 0;
-
- WidgetId() = default;
-
- explicit WidgetId(const std::string& p) : path(p), hash(computeHash(p)) {}
-
- /** @brief Creates a child ID by appending a name to a parent path */
- static WidgetId from(const std::string& parent, const std::string& name) {
- if (parent.empty()) {
- return WidgetId(name);
- }
- return WidgetId(parent + "." + name);
- }
-
- /** @brief Creates an indexed child ID (for list items) */
- static WidgetId indexed(const std::string& parent, const std::string& name, u32 index) {
- if (parent.empty()) {
- return WidgetId(name + "[" + std::to_string(index) + "]");
- }
- return WidgetId(parent + "." + name + "[" + std::to_string(index) + "]");
- }
-
- /** @brief Returns the last component of the path (the widget's own name) */
- std::string name() const {
- auto pos = path.rfind('.');
- if (pos == std::string::npos) {
- return path;
- }
- return path.substr(pos + 1);
- }
-
- /** @brief Returns the parent path (empty if root) */
- std::string parentPath() const {
- auto pos = path.rfind('.');
- if (pos == std::string::npos) {
- return "";
- }
- return path.substr(0, pos);
- }
-
- bool operator==(const WidgetId& other) const { return hash == other.hash && path == other.path; }
-
- bool operator!=(const WidgetId& other) const { return !(*this == other); }
-
- bool operator<(const WidgetId& other) const {
- if (hash != other.hash) {
- return hash < other.hash;
- }
- return path < other.path;
- }
-
-private:
- static u64 computeHash(const std::string& str) {
- return std::hash<std::string>{}(str);
- }
-};
-
-// =============================================================================
-// Mouse Button
-// =============================================================================
-
-/**
- * @brief Mouse button identifiers
- */
-enum class MouseButton : u8 {
- Left = 0,
- Right = 1,
- Middle = 2,
- Button4 = 3,
- Button5 = 4,
- Count = 5
-};
-
-// =============================================================================
-// Cursor Type
-// =============================================================================
-
-/**
- * @brief Standard cursor types for UI feedback
- */
-enum class CursorType : u8 {
- Arrow,
- IBeam,
- Crosshair,
- Hand,
- ResizeH,
- ResizeV,
- ResizeNESW,
- ResizeNWSE,
- Move,
- NotAllowed
-};
-
-} // namespace esengine::ui
-
-// =============================================================================
-// Hash Specialization
-// =============================================================================
-
-namespace std {
-
-template<>
-struct hash<esengine::ui::WidgetId> {
- size_t operator()(const esengine::ui::WidgetId& id) const noexcept {
- return static_cast<size_t>(id.hash);
- }
-};
-
-} // namespace std
diff --git a/src/esengine/ui/events/UIEvent.hpp b/src/esengine/ui/events/UIEvent.hpp
deleted file mode 100644
index 8564b3561..000000000
--- a/src/esengine/ui/events/UIEvent.hpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/**
- * @file UIEvent.hpp
- * @brief UI event types for input handling
- * @details Defines event structures for mouse, keyboard, scroll, and focus
- * events used by the UI widget system.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-#include "../../platform/input/Input.hpp"
-#include "../core/Types.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Event Phase
-// =============================================================================
-
-/**
- * @brief Phase of event propagation
- */
-enum class EventPhase : u8 {
- Capture,
- Target,
- Bubble
-};
-
-// =============================================================================
-// Base Event
-// =============================================================================
-
-/**
- * @brief Base class for all UI events
- */
-struct UIEvent {
- EventPhase phase = EventPhase::Target;
- bool consumed = false;
- bool propagationStopped = false;
-
- void consume() { consumed = true; }
- void stopPropagation() { propagationStopped = true; }
-};
-
-// =============================================================================
-// Mouse Events
-// =============================================================================
-
-/**
- * @brief Mouse button event (press/release)
- */
-struct MouseButtonEvent : UIEvent {
- MouseButton button = MouseButton::Left;
- bool pressed = false;
- f32 x = 0.0f;
- f32 y = 0.0f;
- bool ctrl = false;
- bool shift = false;
- bool alt = false;
-
- glm::vec2 position() const { return {x, y}; }
-};
-
-/**
- * @brief Mouse movement event
- */
-struct MouseMoveEvent : UIEvent {
- f32 x = 0.0f;
- f32 y = 0.0f;
- f32 deltaX = 0.0f;
- f32 deltaY = 0.0f;
- bool leftButton = false;
- bool rightButton = false;
- bool middleButton = false;
- bool ctrl = false;
- bool shift = false;
- bool alt = false;
-
- glm::vec2 position() const { return {x, y}; }
- glm::vec2 delta() const { return {deltaX, deltaY}; }
-};
-
-/**
- * @brief Mouse enter/leave event
- */
-struct MouseEnterEvent : UIEvent {
- f32 x = 0.0f;
- f32 y = 0.0f;
-
- glm::vec2 position() const { return {x, y}; }
-};
-
-/**
- * @brief Mouse leave event
- */
-struct MouseLeaveEvent : UIEvent {};
-
-/**
- * @brief Mouse scroll event
- */
-struct ScrollEvent : UIEvent {
- f32 deltaX = 0.0f;
- f32 deltaY = 0.0f;
- f32 x = 0.0f;
- f32 y = 0.0f;
- bool ctrl = false;
- bool shift = false;
-
- glm::vec2 delta() const { return {deltaX, deltaY}; }
- glm::vec2 position() const { return {x, y}; }
-};
-
-// =============================================================================
-// Keyboard Events
-// =============================================================================
-
-/**
- * @brief Key press/release event
- */
-struct KeyEvent : UIEvent {
- KeyCode key = KeyCode::Unknown;
- bool pressed = false;
- bool repeat = false;
- bool ctrl = false;
- bool shift = false;
- bool alt = false;
-};
-
-/**
- * @brief Text input event (character typed)
- */
-struct TextInputEvent : UIEvent {
- std::string text;
- u32 codepoint = 0;
-};
-
-// =============================================================================
-// Focus Events
-// =============================================================================
-
-/**
- * @brief Focus gained event
- */
-struct FocusEvent : UIEvent {};
-
-/**
- * @brief Focus lost event
- */
-struct BlurEvent : UIEvent {};
-
-// =============================================================================
-// Drag Events
-// =============================================================================
-
-/**
- * @brief Drag start event
- */
-struct DragStartEvent : UIEvent {
- f32 x = 0.0f;
- f32 y = 0.0f;
-
- glm::vec2 position() const { return {x, y}; }
-};
-
-/**
- * @brief Drag move event
- */
-struct DragMoveEvent : UIEvent {
- f32 x = 0.0f;
- f32 y = 0.0f;
- f32 deltaX = 0.0f;
- f32 deltaY = 0.0f;
-
- glm::vec2 position() const { return {x, y}; }
- glm::vec2 delta() const { return {deltaX, deltaY}; }
-};
-
-/**
- * @brief Drag end event
- */
-struct DragEndEvent : UIEvent {
- f32 x = 0.0f;
- f32 y = 0.0f;
-
- glm::vec2 position() const { return {x, y}; }
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/BitmapFont.cpp b/src/esengine/ui/font/BitmapFont.cpp
deleted file mode 100644
index 460dda91e..000000000
--- a/src/esengine/ui/font/BitmapFont.cpp
+++ /dev/null
@@ -1,372 +0,0 @@
-/**
- * @file BitmapFont.cpp
- * @brief Bitmap font rendering implementation
- *
- * @author ESEngine Team
- * @date 2026
- */
-
-#include "BitmapFont.hpp"
-#include "../../core/Log.hpp"
-#include "../../platform/FileSystem.hpp"
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
-#define STB_IMAGE_IMPLEMENTATION_INCLUDED
-#include <stb_image.h>
-
-#include <cstring>
-#include <sstream>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Simple JSON Parser (minimal, no external deps)
-// =============================================================================
-
-namespace {
-
-std::string trim(const std::string& s) {
- auto start = s.find_first_not_of(" \t\n\r");
- if (start == std::string::npos) return "";
- auto end = s.find_last_not_of(" \t\n\r");
- return s.substr(start, end - start + 1);
-}
-
-std::string extractString(const std::string& json, const std::string& key) {
- std::string search = "\"" + key + "\"";
- auto pos = json.find(search);
- if (pos == std::string::npos) return "";
-
- pos = json.find(':', pos);
- if (pos == std::string::npos) return "";
-
- pos = json.find('"', pos + 1);
- if (pos == std::string::npos) return "";
-
- auto endPos = json.find('"', pos + 1);
- if (endPos == std::string::npos) return "";
-
- return json.substr(pos + 1, endPos - pos - 1);
-}
-
-f32 extractFloat(const std::string& json, const std::string& key, f32 defaultVal = 0.0f) {
- std::string search = "\"" + key + "\"";
- auto pos = json.find(search);
- if (pos == std::string::npos) return defaultVal;
-
- pos = json.find(':', pos);
- if (pos == std::string::npos) return defaultVal;
-
- pos++;
- while (pos < json.size() && (json[pos] == ' ' || json[pos] == '\t')) pos++;
-
- std::string numStr;
- while (pos < json.size() && (std::isdigit(json[pos]) || json[pos] == '.' || json[pos] == '-')) {
- numStr += json[pos++];
- }
-
- if (numStr.empty()) return defaultVal;
- return std::stof(numStr);
-}
-
-i32 extractInt(const std::string& json, const std::string& key, i32 defaultVal = 0) {
- return static_cast<i32>(extractFloat(json, key, static_cast<f32>(defaultVal)));
-}
-
-u32 nextCodepoint(const std::string& text, usize& i) {
- u32 codepoint = 0;
- const u8* ptr = reinterpret_cast<const u8*>(text.data()) + i;
- const u8* end = reinterpret_cast<const u8*>(text.data()) + text.size();
-
- if (ptr >= end) return 0;
-
- if ((*ptr & 0x80) == 0) {
- codepoint = *ptr;
- i += 1;
- } else if ((*ptr & 0xE0) == 0xC0) {
- codepoint = (*ptr & 0x1F) << 6;
- if (ptr + 1 < end) codepoint |= (*(ptr + 1) & 0x3F);
- i += 2;
- } else if ((*ptr & 0xF0) == 0xE0) {
- codepoint = (*ptr & 0x0F) << 12;
- if (ptr + 1 < end) codepoint |= (*(ptr + 1) & 0x3F) << 6;
- if (ptr + 2 < end) codepoint |= (*(ptr + 2) & 0x3F);
- i += 3;
- } else if ((*ptr & 0xF8) == 0xF0) {
- codepoint = (*ptr & 0x07) << 18;
- if (ptr + 1 < end) codepoint |= (*(ptr + 1) & 0x3F) << 12;
- if (ptr + 2 < end) codepoint |= (*(ptr + 2) & 0x3F) << 6;
- if (ptr + 3 < end) codepoint |= (*(ptr + 3) & 0x3F);
- i += 4;
- } else {
- i += 1;
- }
- return codepoint;
-}
-
-} // namespace
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-BitmapFont::~BitmapFont() {
- if (textureId_ != 0) {
- glDeleteTextures(1, &textureId_);
- textureId_ = 0;
- }
-}
-
-BitmapFont::BitmapFont(BitmapFont&& other) noexcept
- : textureId_(other.textureId_),
- atlasWidth_(other.atlasWidth_),
- atlasHeight_(other.atlasHeight_),
- fontSize_(other.fontSize_),
- lineHeight_(other.lineHeight_),
- ascent_(other.ascent_),
- descent_(other.descent_),
- glyphs_(std::move(other.glyphs_)) {
- other.textureId_ = 0;
-}
-
-BitmapFont& BitmapFont::operator=(BitmapFont&& other) noexcept {
- if (this != &other) {
- if (textureId_ != 0) {
- glDeleteTextures(1, &textureId_);
- }
-
- textureId_ = other.textureId_;
- atlasWidth_ = other.atlasWidth_;
- atlasHeight_ = other.atlasHeight_;
- fontSize_ = other.fontSize_;
- lineHeight_ = other.lineHeight_;
- ascent_ = other.ascent_;
- descent_ = other.descent_;
- glyphs_ = std::move(other.glyphs_);
-
- other.textureId_ = 0;
- }
- return *this;
-}
-
-// =============================================================================
-// Factory Methods
-// =============================================================================
-
-Unique<BitmapFont> BitmapFont::load(const std::string& atlasPath,
- const std::string& metricsPath) {
- auto font = makeUnique<BitmapFont>();
-
- if (!font->loadAtlasTexture(atlasPath)) {
- ES_LOG_ERROR("BitmapFont: Failed to load atlas: {}", atlasPath);
- return nullptr;
- }
-
- std::string metricsJson = FileSystem::readTextFile(metricsPath);
- if (metricsJson.empty()) {
- ES_LOG_ERROR("BitmapFont: Failed to read metrics: {}", metricsPath);
- return nullptr;
- }
-
- if (!font->parseMetrics(metricsJson)) {
- ES_LOG_ERROR("BitmapFont: Failed to parse metrics: {}", metricsPath);
- return nullptr;
- }
-
- ES_LOG_INFO("BitmapFont loaded: {} ({} glyphs, {}x{})",
- atlasPath, font->glyphs_.size(), font->atlasWidth_, font->atlasHeight_);
-
- return font;
-}
-
-Unique<BitmapFont> BitmapFont::loadFromMemory(const u8* atlasData, usize atlasSize,
- const std::string& metricsJson) {
- auto font = makeUnique<BitmapFont>();
-
- if (!font->loadAtlasFromMemory(atlasData, atlasSize)) {
- ES_LOG_ERROR("BitmapFont: Failed to load atlas from memory");
- return nullptr;
- }
-
- if (!font->parseMetrics(metricsJson)) {
- ES_LOG_ERROR("BitmapFont: Failed to parse metrics");
- return nullptr;
- }
-
- ES_LOG_INFO("BitmapFont loaded from memory ({} glyphs, {}x{})",
- font->glyphs_.size(), font->atlasWidth_, font->atlasHeight_);
-
- return font;
-}
-
-// =============================================================================
-// Atlas Loading
-// =============================================================================
-
-bool BitmapFont::loadAtlasTexture(const std::string& path) {
- auto data = FileSystem::readBinaryFile(path);
- if (data.empty()) {
- return false;
- }
- return loadAtlasFromMemory(data.data(), data.size());
-}
-
-bool BitmapFont::loadAtlasFromMemory(const u8* data, usize size) {
- int width, height, channels;
- stbi_set_flip_vertically_on_load(false);
-
- u8* pixels = stbi_load_from_memory(data, static_cast<int>(size),
- &width, &height, &channels, 4);
- if (!pixels) {
- ES_LOG_ERROR("BitmapFont: Failed to decode atlas image");
- return false;
- }
-
- atlasWidth_ = static_cast<u32>(width);
- atlasHeight_ = static_cast<u32>(height);
-
- glGenTextures(1, &textureId_);
- glBindTexture(GL_TEXTURE_2D, textureId_);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
- GL_RGBA, GL_UNSIGNED_BYTE, pixels);
- glBindTexture(GL_TEXTURE_2D, 0);
-
- stbi_image_free(pixels);
- return true;
-}
-
-// =============================================================================
-// Metrics Parsing
-// =============================================================================
-
-bool BitmapFont::parseMetrics(const std::string& json) {
- fontSize_ = extractFloat(json, "fontSize", 32.0f);
- lineHeight_ = extractFloat(json, "lineHeight", fontSize_ * 1.2f);
- ascent_ = extractFloat(json, "ascent", fontSize_ * 0.8f);
- descent_ = extractFloat(json, "descent", fontSize_ * 0.2f);
-
- // Parse glyphs array
- auto glyphsStart = json.find("\"glyphs\"");
- if (glyphsStart == std::string::npos) {
- ES_LOG_ERROR("BitmapFont: No glyphs array in metrics");
- return false;
- }
-
- auto arrayStart = json.find('[', glyphsStart);
- if (arrayStart == std::string::npos) return false;
-
- auto arrayEnd = json.find(']', arrayStart);
- if (arrayEnd == std::string::npos) return false;
-
- std::string glyphsArray = json.substr(arrayStart + 1, arrayEnd - arrayStart - 1);
-
- // Parse each glyph object
- usize pos = 0;
- while (pos < glyphsArray.size()) {
- auto objStart = glyphsArray.find('{', pos);
- if (objStart == std::string::npos) break;
-
- auto objEnd = glyphsArray.find('}', objStart);
- if (objEnd == std::string::npos) break;
-
- std::string glyphJson = glyphsArray.substr(objStart, objEnd - objStart + 1);
-
- u32 codepoint = static_cast<u32>(extractInt(glyphJson, "codepoint", 0));
- if (codepoint == 0) {
- // Try "char" field for ASCII character
- std::string charStr = extractString(glyphJson, "char");
- if (!charStr.empty()) {
- usize idx = 0;
- codepoint = nextCodepoint(charStr, idx);
- }
- }
-
- if (codepoint != 0) {
- BitmapGlyphInfo glyph;
- glyph.width = extractFloat(glyphJson, "width");
- glyph.height = extractFloat(glyphJson, "height");
- glyph.bearingX = extractFloat(glyphJson, "bearingX");
- glyph.bearingY = extractFloat(glyphJson, "bearingY");
- glyph.advance = extractFloat(glyphJson, "advance");
- glyph.u0 = extractFloat(glyphJson, "u0");
- glyph.v0 = extractFloat(glyphJson, "v0");
- glyph.u1 = extractFloat(glyphJson, "u1");
- glyph.v1 = extractFloat(glyphJson, "v1");
-
- glyphs_[codepoint] = glyph;
- }
-
- pos = objEnd + 1;
- }
-
- return !glyphs_.empty();
-}
-
-// =============================================================================
-// Glyph Access
-// =============================================================================
-
-const BitmapGlyphInfo* BitmapFont::getGlyph(u32 codepoint) const {
- auto it = glyphs_.find(codepoint);
- if (it != glyphs_.end()) {
- return &it->second;
- }
- return nullptr;
-}
-
-// =============================================================================
-// Text Measurement
-// =============================================================================
-
-glm::vec2 BitmapFont::measureText(const std::string& text, f32 fontSize) const {
- if (text.empty() || fontSize_ == 0.0f) return {0.0f, 0.0f};
-
- f32 scale = fontSize / fontSize_;
- f32 width = 0.0f;
- f32 maxWidth = 0.0f;
- i32 lines = 1;
-
- usize i = 0;
- while (i < text.size()) {
- u32 codepoint = nextCodepoint(text, i);
-
- if (codepoint == '\n') {
- maxWidth = std::max(maxWidth, width);
- width = 0.0f;
- lines++;
- continue;
- }
-
- const auto* glyph = getGlyph(codepoint);
- if (glyph) {
- width += glyph->advance * scale;
- }
- }
-
- maxWidth = std::max(maxWidth, width);
- f32 height = static_cast<f32>(lines) * lineHeight_ * scale;
-
- return {maxWidth, height};
-}
-
-f32 BitmapFont::getCharWidth(u32 codepoint, f32 fontSize) const {
- const auto* glyph = getGlyph(codepoint);
- if (!glyph || fontSize_ == 0.0f) return 0.0f;
-
- f32 scale = fontSize / fontSize_;
- return glyph->advance * scale;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/BitmapFont.hpp b/src/esengine/ui/font/BitmapFont.hpp
deleted file mode 100644
index 2f4537671..000000000
--- a/src/esengine/ui/font/BitmapFont.hpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * @file BitmapFont.hpp
- * @brief Bitmap font rendering for lightweight deployments
- *
- * @details Pre-rendered bitmap fonts for scenarios where FreeType is not
- * available or package size is critical (e.g., playable ads).
- *
- * @author ESEngine Team
- * @date 2026
- */
-#pragma once
-
-#include "../../core/Types.hpp"
-#include <glm/glm.hpp>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::ui {
-
-/**
- * @brief Glyph information for bitmap fonts
- */
-struct BitmapGlyphInfo {
- f32 width = 0.0f;
- f32 height = 0.0f;
- f32 bearingX = 0.0f;
- f32 bearingY = 0.0f;
- f32 advance = 0.0f;
- f32 u0 = 0.0f;
- f32 v0 = 0.0f;
- f32 u1 = 0.0f;
- f32 v1 = 0.0f;
-};
-
-/**
- * @brief Lightweight bitmap font for size-constrained deployments
- *
- * @details Uses pre-rendered font atlas and metrics file.
- * No FreeType dependency, minimal runtime overhead.
- *
- * @code
- * auto font = BitmapFont::load("font_atlas.png", "font_metrics.json");
- * if (font) {
- * renderer.drawText("Hello", {10, 10}, *font, 32.0f, {1,1,1,1});
- * }
- * @endcode
- */
-class BitmapFont {
-public:
- BitmapFont() = default;
- ~BitmapFont();
-
- BitmapFont(const BitmapFont&) = delete;
- BitmapFont& operator=(const BitmapFont&) = delete;
- BitmapFont(BitmapFont&& other) noexcept;
- BitmapFont& operator=(BitmapFont&& other) noexcept;
-
- /**
- * @brief Load bitmap font from atlas image and metrics file
- * @param atlasPath Path to the font atlas texture (PNG)
- * @param metricsPath Path to the glyph metrics file (JSON)
- * @return Font instance or nullptr on failure
- */
- static Unique<BitmapFont> load(const std::string& atlasPath,
- const std::string& metricsPath);
-
- /**
- * @brief Load bitmap font from embedded data
- * @param atlasData Raw PNG data
- * @param atlasSize Size of PNG data
- * @param metricsJson JSON string with glyph metrics
- * @return Font instance or nullptr on failure
- */
- static Unique<BitmapFont> loadFromMemory(const u8* atlasData, usize atlasSize,
- const std::string& metricsJson);
-
- /**
- * @brief Get glyph information for a codepoint
- * @param codepoint Unicode codepoint
- * @return Pointer to glyph info, or nullptr if not found
- */
- const BitmapGlyphInfo* getGlyph(u32 codepoint) const;
-
- /** @brief Get the atlas texture ID */
- u32 getTextureId() const { return textureId_; }
-
- /** @brief Get the base font size (pixels) */
- f32 getFontSize() const { return fontSize_; }
-
- /** @brief Get line height */
- f32 getLineHeight() const { return lineHeight_; }
-
- /** @brief Get ascent (baseline to top) */
- f32 getAscent() const { return ascent_; }
-
- /** @brief Get descent (baseline to bottom) */
- f32 getDescent() const { return descent_; }
-
- /** @brief Measure text dimensions */
- glm::vec2 measureText(const std::string& text, f32 fontSize) const;
-
- /** @brief Get character width */
- f32 getCharWidth(u32 codepoint, f32 fontSize) const;
-
-private:
- bool loadAtlasTexture(const std::string& path);
- bool loadAtlasFromMemory(const u8* data, usize size);
- bool parseMetrics(const std::string& json);
-
- u32 textureId_ = 0;
- u32 atlasWidth_ = 0;
- u32 atlasHeight_ = 0;
- f32 fontSize_ = 0.0f;
- f32 lineHeight_ = 0.0f;
- f32 ascent_ = 0.0f;
- f32 descent_ = 0.0f;
- std::unordered_map<u32, BitmapGlyphInfo> glyphs_;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/IFont.hpp b/src/esengine/ui/font/IFont.hpp
deleted file mode 100644
index b776785ac..000000000
--- a/src/esengine/ui/font/IFont.hpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * @file IFont.hpp
- * @brief Abstract font interface
- * @details Unified interface for different font rendering backends:
- * MSDFFont, BitmapFont, SystemFont
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../../core/Types.hpp"
-#include <glm/glm.hpp>
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Glyph Information
-// =============================================================================
-
-struct GlyphInfo {
- f32 width = 0.0f;
- f32 height = 0.0f;
- f32 bearingX = 0.0f;
- f32 bearingY = 0.0f;
- f32 advance = 0.0f;
- f32 u0 = 0.0f;
- f32 v0 = 0.0f;
- f32 u1 = 0.0f;
- f32 v1 = 0.0f;
-};
-
-// =============================================================================
-// Font Type
-// =============================================================================
-
-enum class FontType {
- Bitmap,
- SDF,
- MSDF,
- System
-};
-
-// =============================================================================
-// IFont Interface
-// =============================================================================
-
-class IFont {
-public:
- virtual ~IFont() = default;
-
- virtual FontType getType() const = 0;
- virtual const GlyphInfo* getGlyph(u32 codepoint) = 0;
- virtual u32 getTextureId() const = 0;
- virtual f32 getFontSize() const = 0;
- virtual f32 getLineHeight() const = 0;
- virtual f32 getAscent() const = 0;
- virtual f32 getDescent() const = 0;
- virtual glm::vec2 measureText(const std::string& text, f32 fontSize) = 0;
- virtual f32 getCharWidth(u32 codepoint, f32 fontSize) = 0;
- virtual glm::ivec2 getAtlasSize() const = 0;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/MSDFFont.cpp b/src/esengine/ui/font/MSDFFont.cpp
deleted file mode 100644
index 5e324f41b..000000000
--- a/src/esengine/ui/font/MSDFFont.cpp
+++ /dev/null
@@ -1,416 +0,0 @@
-/**
- * @file MSDFFont.cpp
- * @brief MSDF font rendering implementation using msdfgen
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "MSDFFont.hpp"
-#include "../../core/Log.hpp"
-
-#include <msdfgen.h>
-#include <msdfgen-ext.h>
-
-#include <algorithm>
-#include <cstdio>
-#include <cstring>
-#include <fstream>
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
-#ifndef GL_UNPACK_ALIGNMENT
- #define GL_UNPACK_ALIGNMENT 0x0CF5
-#endif
-
-namespace esengine::ui {
-
-// =============================================================================
-// Font Data
-// =============================================================================
-
-struct MSDFFont::FontData {
- msdfgen::FreetypeHandle* ft = nullptr;
- msdfgen::FontHandle* font = nullptr;
- std::vector<u8> fontBuffer;
-};
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-MSDFFont::~MSDFFont() {
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- atlasTextureId_ = 0;
- }
-
- if (fontData_) {
- if (fontData_->font) {
- msdfgen::destroyFont(fontData_->font);
- }
- if (fontData_->ft) {
- msdfgen::deinitializeFreetype(fontData_->ft);
- }
- }
-}
-
-MSDFFont::MSDFFont(MSDFFont&& other) noexcept
- : fontData_(std::move(other.fontData_)),
- fontSize_(other.fontSize_),
- pixelRange_(other.pixelRange_),
- ascent_(other.ascent_),
- descent_(other.descent_),
- lineHeight_(other.lineHeight_),
- atlasTextureId_(other.atlasTextureId_),
- atlasWidth_(other.atlasWidth_),
- atlasHeight_(other.atlasHeight_),
- atlasData_(std::move(other.atlasData_)),
- glyphs_(std::move(other.glyphs_)),
- lruList_(std::move(other.lruList_)),
- lruMap_(std::move(other.lruMap_)),
- maxCachedGlyphs_(other.maxCachedGlyphs_),
- packX_(other.packX_),
- packY_(other.packY_),
- rowHeight_(other.rowHeight_) {
- other.atlasTextureId_ = 0;
-}
-
-MSDFFont& MSDFFont::operator=(MSDFFont&& other) noexcept {
- if (this != &other) {
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- }
- if (fontData_) {
- if (fontData_->font) msdfgen::destroyFont(fontData_->font);
- if (fontData_->ft) msdfgen::deinitializeFreetype(fontData_->ft);
- }
-
- fontData_ = std::move(other.fontData_);
- fontSize_ = other.fontSize_;
- pixelRange_ = other.pixelRange_;
- ascent_ = other.ascent_;
- descent_ = other.descent_;
- lineHeight_ = other.lineHeight_;
- atlasTextureId_ = other.atlasTextureId_;
- atlasWidth_ = other.atlasWidth_;
- atlasHeight_ = other.atlasHeight_;
- atlasData_ = std::move(other.atlasData_);
- glyphs_ = std::move(other.glyphs_);
- lruList_ = std::move(other.lruList_);
- lruMap_ = std::move(other.lruMap_);
- maxCachedGlyphs_ = other.maxCachedGlyphs_;
- packX_ = other.packX_;
- packY_ = other.packY_;
- rowHeight_ = other.rowHeight_;
- other.atlasTextureId_ = 0;
- }
- return *this;
-}
-
-// =============================================================================
-// Factory
-// =============================================================================
-
-Unique<MSDFFont> MSDFFont::create(const std::string& path, f32 fontSize, f32 pixelRange) {
- auto font = Unique<MSDFFont>(new MSDFFont());
- if (!font->loadFromFile(path, fontSize, pixelRange)) {
- return nullptr;
- }
- return font;
-}
-
-// =============================================================================
-// Loading
-// =============================================================================
-
-bool MSDFFont::loadFromFile(const std::string& path, f32 fontSize, f32 pixelRange) {
- fontSize_ = fontSize;
- pixelRange_ = pixelRange;
-
- std::ifstream file(path, std::ios::binary | std::ios::ate);
- if (!file.is_open()) {
- ES_LOG_ERROR("MSDFFont: Failed to open file: {}", path);
- return false;
- }
-
- fontData_ = makeUnique<FontData>();
-
- fontData_->ft = msdfgen::initializeFreetype();
- if (!fontData_->ft) {
- ES_LOG_ERROR("MSDFFont: Failed to initialize FreeType");
- return false;
- }
-
- fontData_->font = msdfgen::loadFont(fontData_->ft, path.c_str());
- if (!fontData_->font) {
- ES_LOG_ERROR("MSDFFont: Failed to load font: {}", path);
- return false;
- }
-
- msdfgen::FontMetrics metrics;
- msdfgen::getFontMetrics(metrics, fontData_->font);
-
- f32 scale = fontSize_ / static_cast<f32>(metrics.emSize);
- ascent_ = static_cast<f32>(metrics.ascenderY) * scale;
- descent_ = static_cast<f32>(-metrics.descenderY) * scale;
- lineHeight_ = static_cast<f32>(metrics.lineHeight) * scale;
-
- atlasData_.resize(atlasWidth_ * atlasHeight_ * 3, 0);
-
- glGenTextures(1, &atlasTextureId_);
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, atlasWidth_, atlasHeight_, 0, GL_RGB, GL_UNSIGNED_BYTE, atlasData_.data());
-
- ES_LOG_INFO("MSDFFont loaded: {} (size={}, range={}, atlas={}x{})",
- path, fontSize_, pixelRange_, atlasWidth_, atlasHeight_);
-
- preloadASCII();
- return true;
-}
-
-// =============================================================================
-// Glyph Loading
-// =============================================================================
-
-MSDFGlyphInfo* MSDFFont::loadGlyph(u32 codepoint) {
- if (!fontData_ || !fontData_->font) return nullptr;
-
- msdfgen::Shape shape;
- double advance;
- if (!msdfgen::loadGlyph(shape, fontData_->font, codepoint, msdfgen::FONT_SCALING_EM_NORMALIZED, &advance)) {
- return nullptr;
- }
-
- if (shape.contours.empty()) {
- MSDFGlyphInfo& info = glyphs_[codepoint];
- info.width = 0;
- info.height = 0;
- info.bearingX = 0;
- info.bearingY = 0;
- info.advance = static_cast<f32>(advance) * fontSize_;
- info.u0 = info.v0 = info.u1 = info.v1 = 0;
- return &info;
- }
-
- shape.normalize();
- shape.orientContours();
- msdfgen::edgeColoringSimple(shape, 3.0);
-
- msdfgen::Shape::Bounds tightBounds = shape.getBounds();
- msdfgen::Shape::Bounds bounds = shape.getBounds(pixelRange_ / fontSize_);
-
- constexpr i32 BITMAP_PADDING = 1;
- i32 glyphWidth = static_cast<i32>(std::ceil((bounds.r - bounds.l) * fontSize_)) + BITMAP_PADDING * 2;
- i32 glyphHeight = static_cast<i32>(std::ceil((bounds.t - bounds.b) * fontSize_)) + BITMAP_PADDING * 2;
-
- glyphWidth = std::max(glyphWidth, 1);
- glyphHeight = std::max(glyphHeight, 1);
-
- if (glyphs_.size() >= maxCachedGlyphs_) {
- evictLRU();
- }
-
- i32 atlasX, atlasY;
- if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {
- ES_LOG_WARN("MSDFFont: Atlas full, clearing cache");
- clearCache();
- packX_ = 1;
- packY_ = 1;
- rowHeight_ = 0;
- if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {
- return nullptr;
- }
- }
-
- msdfgen::Bitmap<float, 3> msdf(glyphWidth, glyphHeight);
-
- msdfgen::Vector2 scale(fontSize_, fontSize_);
- double paddingInEm = BITMAP_PADDING / static_cast<double>(fontSize_);
- msdfgen::Vector2 translate(paddingInEm - bounds.l, paddingInEm - bounds.b);
-
- double rangeInEm = pixelRange_ / fontSize_;
- msdfgen::Range range(-rangeInEm / 2.0, rangeInEm / 2.0);
-
- msdfgen::generateMSDF(msdf, shape, range, scale, translate);
-
- for (i32 y = 0; y < glyphHeight; ++y) {
- for (i32 x = 0; x < glyphWidth; ++x) {
- i32 atlasIdx = ((atlasY + y) * atlasWidth_ + (atlasX + x)) * 3;
- float* pixel = msdf(x, glyphHeight - 1 - y);
- atlasData_[atlasIdx + 0] = static_cast<u8>(std::clamp(pixel[0], 0.0f, 1.0f) * 255.0f);
- atlasData_[atlasIdx + 1] = static_cast<u8>(std::clamp(pixel[1], 0.0f, 1.0f) * 255.0f);
- atlasData_[atlasIdx + 2] = static_cast<u8>(std::clamp(pixel[2], 0.0f, 1.0f) * 255.0f);
- }
- }
-
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
-
- std::vector<u8> subImage(glyphWidth * glyphHeight * 3);
- for (i32 y = 0; y < glyphHeight; ++y) {
- std::memcpy(&subImage[y * glyphWidth * 3],
- &atlasData_[((atlasY + y) * atlasWidth_ + atlasX) * 3],
- glyphWidth * 3);
- }
- glTexSubImage2D(GL_TEXTURE_2D, 0, atlasX, atlasY, glyphWidth, glyphHeight,
- GL_RGB, GL_UNSIGNED_BYTE, subImage.data());
-
- MSDFGlyphInfo& info = glyphs_[codepoint];
- info.width = static_cast<f32>(glyphWidth);
- info.height = static_cast<f32>(glyphHeight);
- f32 spreadPixels = static_cast<f32>(bounds.t - tightBounds.t) * fontSize_;
- info.bearingX = static_cast<f32>(tightBounds.l) * fontSize_ - spreadPixels - BITMAP_PADDING;
- info.bearingY = static_cast<f32>(tightBounds.t) * fontSize_ + spreadPixels + BITMAP_PADDING;
- info.advance = static_cast<f32>(advance) * fontSize_;
-
- info.atlasX = atlasX;
- info.atlasY = atlasY;
- info.atlasWidth = glyphWidth;
- info.atlasHeight = glyphHeight;
-
- info.u0 = static_cast<f32>(atlasX) / atlasWidth_;
- info.v0 = static_cast<f32>(atlasY) / atlasHeight_;
- info.u1 = static_cast<f32>(atlasX + glyphWidth) / atlasWidth_;
- info.v1 = static_cast<f32>(atlasY + glyphHeight) / atlasHeight_;
-
- lruList_.push_front(codepoint);
- lruMap_[codepoint] = lruList_.begin();
-
- return &info;
-}
-
-const MSDFGlyphInfo* MSDFFont::getGlyph(u32 codepoint) {
- auto it = glyphs_.find(codepoint);
- if (it != glyphs_.end()) {
- auto lruIt = lruMap_.find(codepoint);
- if (lruIt != lruMap_.end()) {
- lruList_.erase(lruIt->second);
- lruList_.push_front(codepoint);
- lruMap_[codepoint] = lruList_.begin();
- }
- return &it->second;
- }
- return loadGlyph(codepoint);
-}
-
-void MSDFFont::preloadASCII() {
- for (u32 c = 32; c < 127; ++c) {
- getGlyph(c);
- }
- ES_LOG_DEBUG("MSDFFont: Preloaded {} ASCII glyphs", 127 - 32);
-}
-
-// =============================================================================
-// Cache Management
-// =============================================================================
-
-void MSDFFont::evictLRU() {
- if (lruList_.empty()) return;
-
- u32 lruCodepoint = lruList_.back();
- lruList_.pop_back();
- lruMap_.erase(lruCodepoint);
- glyphs_.erase(lruCodepoint);
-}
-
-void MSDFFont::clearCache() {
- glyphs_.clear();
- lruList_.clear();
- lruMap_.clear();
- std::fill(atlasData_.begin(), atlasData_.end(), 0);
- rebuildAtlasTexture();
-}
-
-void MSDFFont::rebuildAtlasTexture() {
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, atlasWidth_, atlasHeight_,
- GL_RGB, GL_UNSIGNED_BYTE, atlasData_.data());
-}
-
-bool MSDFFont::findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY) {
- if (packX_ + width + 1 > static_cast<i32>(atlasWidth_)) {
- packX_ = 1;
- packY_ += rowHeight_ + 1;
- rowHeight_ = 0;
- }
-
- if (packY_ + height + 1 > static_cast<i32>(atlasHeight_)) {
- return false;
- }
-
- outX = packX_;
- outY = packY_;
- packX_ += width + 1;
- rowHeight_ = std::max(rowHeight_, height);
- return true;
-}
-
-// =============================================================================
-// Text Measurement
-// =============================================================================
-
-glm::vec2 MSDFFont::measureText(const std::string& text, f32 fontSize) {
- f32 scale = fontSize / fontSize_;
- f32 width = 0.0f;
-
- usize i = 0;
- while (i < text.size()) {
- u32 codepoint;
- u8 c = static_cast<u8>(text[i]);
- if ((c & 0x80) == 0) {
- codepoint = c;
- i += 1;
- } else if ((c & 0xE0) == 0xC0) {
- codepoint = (c & 0x1F) << 6;
- if (i + 1 < text.size()) codepoint |= (static_cast<u8>(text[i + 1]) & 0x3F);
- i += 2;
- } else if ((c & 0xF0) == 0xE0) {
- codepoint = (c & 0x0F) << 12;
- if (i + 1 < text.size()) codepoint |= (static_cast<u8>(text[i + 1]) & 0x3F) << 6;
- if (i + 2 < text.size()) codepoint |= (static_cast<u8>(text[i + 2]) & 0x3F);
- i += 3;
- } else if ((c & 0xF8) == 0xF0) {
- codepoint = (c & 0x07) << 18;
- if (i + 1 < text.size()) codepoint |= (static_cast<u8>(text[i + 1]) & 0x3F) << 12;
- if (i + 2 < text.size()) codepoint |= (static_cast<u8>(text[i + 2]) & 0x3F) << 6;
- if (i + 3 < text.size()) codepoint |= (static_cast<u8>(text[i + 3]) & 0x3F);
- i += 4;
- } else {
- i += 1;
- continue;
- }
-
- const MSDFGlyphInfo* glyph = getGlyph(codepoint);
- if (glyph) {
- width += glyph->advance * scale;
- }
- }
-
- return glm::vec2(width, lineHeight_ * scale);
-}
-
-f32 MSDFFont::getCharWidth(u32 codepoint, f32 fontSize) {
- f32 scale = fontSize / fontSize_;
- const MSDFGlyphInfo* glyph = getGlyph(codepoint);
- if (glyph) {
- return glyph->advance * scale;
- }
- return 0.0f;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/MSDFFont.hpp b/src/esengine/ui/font/MSDFFont.hpp
deleted file mode 100644
index 135badf13..000000000
--- a/src/esengine/ui/font/MSDFFont.hpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * @file MSDFFont.hpp
- * @brief MSDF font rendering with msdfgen
- * @details Provides Multi-channel Signed Distance Field font rendering using
- * msdfgen library. Produces sharper text than single-channel SDF.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "../../core/Types.hpp"
-
-#include <glm/glm.hpp>
-
-#include <list>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::ui {
-
-// =============================================================================
-// MSDF Glyph Information
-// =============================================================================
-
-struct MSDFGlyphInfo {
- f32 width = 0.0f;
- f32 height = 0.0f;
- f32 bearingX = 0.0f;
- f32 bearingY = 0.0f;
- f32 advance = 0.0f;
-
- f32 u0 = 0.0f;
- f32 v0 = 0.0f;
- f32 u1 = 0.0f;
- f32 v1 = 0.0f;
-
- i32 atlasX = 0;
- i32 atlasY = 0;
- i32 atlasWidth = 0;
- i32 atlasHeight = 0;
-};
-
-// =============================================================================
-// MSDFFont Class
-// =============================================================================
-
-class MSDFFont {
-public:
- ~MSDFFont();
-
- MSDFFont(const MSDFFont&) = delete;
- MSDFFont& operator=(const MSDFFont&) = delete;
-
- MSDFFont(MSDFFont&& other) noexcept;
- MSDFFont& operator=(MSDFFont&& other) noexcept;
-
- // =========================================================================
- // Factory Methods
- // =========================================================================
-
- static Unique<MSDFFont> create(const std::string& path, f32 fontSize = 32.0f, f32 pixelRange = 4.0f);
-
- // =========================================================================
- // Properties
- // =========================================================================
-
- f32 getFontSize() const { return fontSize_; }
- f32 getPixelRange() const { return pixelRange_; }
- f32 getAscent() const { return ascent_; }
- f32 getDescent() const { return descent_; }
- f32 getLineHeight() const { return lineHeight_; }
- u32 getAtlasTextureId() const { return atlasTextureId_; }
- glm::ivec2 getAtlasSize() const { return {atlasWidth_, atlasHeight_}; }
-
- // =========================================================================
- // Glyph Access
- // =========================================================================
-
- const MSDFGlyphInfo* getGlyph(u32 codepoint);
- void preloadASCII();
-
- // =========================================================================
- // Text Measurement
- // =========================================================================
-
- glm::vec2 measureText(const std::string& text, f32 fontSize);
- f32 getCharWidth(u32 codepoint, f32 fontSize);
-
- // =========================================================================
- // Cache Management
- // =========================================================================
-
- usize getCachedGlyphCount() const { return glyphs_.size(); }
- void setMaxCachedGlyphs(usize maxGlyphs) { maxCachedGlyphs_ = maxGlyphs; }
- void clearCache();
-
-private:
- MSDFFont() = default;
-
- bool loadFromFile(const std::string& path, f32 fontSize, f32 pixelRange);
- MSDFGlyphInfo* loadGlyph(u32 codepoint);
- void evictLRU();
- void rebuildAtlasTexture();
-
- bool findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY);
-
- struct FontData;
- Unique<FontData> fontData_;
-
- f32 fontSize_ = 32.0f;
- f32 pixelRange_ = 4.0f;
- f32 ascent_ = 0.0f;
- f32 descent_ = 0.0f;
- f32 lineHeight_ = 0.0f;
-
- u32 atlasTextureId_ = 0;
- u32 atlasWidth_ = 1024;
- u32 atlasHeight_ = 1024;
- std::vector<u8> atlasData_; // RGB format (3 bytes per pixel)
-
- std::unordered_map<u32, MSDFGlyphInfo> glyphs_;
- std::list<u32> lruList_;
- std::unordered_map<u32, std::list<u32>::iterator> lruMap_;
- usize maxCachedGlyphs_ = 2048;
-
- i32 packX_ = 1;
- i32 packY_ = 1;
- i32 rowHeight_ = 0;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/SDFFont.cpp b/src/esengine/ui/font/SDFFont.cpp
deleted file mode 100644
index d20411f3c..000000000
--- a/src/esengine/ui/font/SDFFont.cpp
+++ /dev/null
@@ -1,500 +0,0 @@
-/**
- * @file SDFFont.cpp
- * @brief SDF font rendering implementation using FreeType
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "SDFFont.hpp"
-#include "../../core/Log.hpp"
-
-#include <ft2build.h>
-#include FT_FREETYPE_H
-#include FT_MODULE_H
-
-#include <algorithm>
-#include <cstring>
-#include <fstream>
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
- #ifndef GL_UNPACK_ALIGNMENT
- #define GL_UNPACK_ALIGNMENT 0x0CF5
- #endif
-#endif
-
-namespace esengine::ui {
-
-// =============================================================================
-// FreeType Data
-// =============================================================================
-
-struct SDFFont::FTData {
- FT_Library library = nullptr;
- FT_Face face = nullptr;
- std::vector<u8> fontBuffer;
-};
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-SDFFont::~SDFFont() {
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- atlasTextureId_ = 0;
- }
-
- if (ftData_) {
- if (ftData_->face) {
- FT_Done_Face(ftData_->face);
- }
- if (ftData_->library) {
- FT_Done_FreeType(ftData_->library);
- }
- }
-}
-
-SDFFont::SDFFont(SDFFont&& other) noexcept
- : ftData_(std::move(other.ftData_)),
- sdfSize_(other.sdfSize_),
- sdfSpread_(other.sdfSpread_),
- ascent_(other.ascent_),
- descent_(other.descent_),
- lineHeight_(other.lineHeight_),
- atlasTextureId_(other.atlasTextureId_),
- atlasWidth_(other.atlasWidth_),
- atlasHeight_(other.atlasHeight_),
- atlasData_(std::move(other.atlasData_)),
- glyphs_(std::move(other.glyphs_)),
- lruList_(std::move(other.lruList_)),
- lruMap_(std::move(other.lruMap_)),
- maxCachedGlyphs_(other.maxCachedGlyphs_),
- packX_(other.packX_),
- packY_(other.packY_),
- rowHeight_(other.rowHeight_) {
- other.atlasTextureId_ = 0;
-}
-
-SDFFont& SDFFont::operator=(SDFFont&& other) noexcept {
- if (this != &other) {
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- }
- if (ftData_) {
- if (ftData_->face) FT_Done_Face(ftData_->face);
- if (ftData_->library) FT_Done_FreeType(ftData_->library);
- }
-
- ftData_ = std::move(other.ftData_);
- sdfSize_ = other.sdfSize_;
- sdfSpread_ = other.sdfSpread_;
- ascent_ = other.ascent_;
- descent_ = other.descent_;
- lineHeight_ = other.lineHeight_;
- atlasTextureId_ = other.atlasTextureId_;
- atlasWidth_ = other.atlasWidth_;
- atlasHeight_ = other.atlasHeight_;
- atlasData_ = std::move(other.atlasData_);
- glyphs_ = std::move(other.glyphs_);
- lruList_ = std::move(other.lruList_);
- lruMap_ = std::move(other.lruMap_);
- maxCachedGlyphs_ = other.maxCachedGlyphs_;
- packX_ = other.packX_;
- packY_ = other.packY_;
- rowHeight_ = other.rowHeight_;
- other.atlasTextureId_ = 0;
- }
- return *this;
-}
-
-// =============================================================================
-// Factory Methods
-// =============================================================================
-
-Unique<SDFFont> SDFFont::create(const std::string& path, f32 sdfSize, f32 sdfSpread) {
- auto font = Unique<SDFFont>(new SDFFont());
- if (!font->loadFromFile(path, sdfSize, sdfSpread)) {
- return nullptr;
- }
- return font;
-}
-
-// =============================================================================
-// Loading
-// =============================================================================
-
-bool SDFFont::loadFromFile(const std::string& path, f32 sdfSize, f32 sdfSpread) {
- sdfSize_ = sdfSize;
- sdfSpread_ = sdfSpread;
-
- std::ifstream file(path, std::ios::binary | std::ios::ate);
- if (!file.is_open()) {
- ES_LOG_ERROR("SDFFont: Failed to open font file: {}", path);
- return false;
- }
-
- auto fileSize = file.tellg();
- file.seekg(0, std::ios::beg);
-
- ftData_ = makeUnique<FTData>();
- ftData_->fontBuffer.resize(static_cast<usize>(fileSize));
-
- if (!file.read(reinterpret_cast<char*>(ftData_->fontBuffer.data()), fileSize)) {
- ES_LOG_ERROR("SDFFont: Failed to read font file: {}", path);
- ftData_.reset();
- return false;
- }
-
- FT_Error error = FT_Init_FreeType(&ftData_->library);
- if (error) {
- ES_LOG_ERROR("SDFFont: Failed to initialize FreeType: {}", error);
- ftData_.reset();
- return false;
- }
-
- error = FT_New_Memory_Face(
- ftData_->library,
- ftData_->fontBuffer.data(),
- static_cast<FT_Long>(ftData_->fontBuffer.size()),
- 0,
- &ftData_->face
- );
-
- if (error) {
- ES_LOG_ERROR("SDFFont: Failed to create font face: {}", error);
- FT_Done_FreeType(ftData_->library);
- ftData_.reset();
- return false;
- }
-
- error = FT_Set_Pixel_Sizes(ftData_->face, 0, static_cast<FT_UInt>(sdfSize_));
- if (error) {
- ES_LOG_ERROR("SDFFont: Failed to set pixel size: {}", error);
- FT_Done_Face(ftData_->face);
- FT_Done_FreeType(ftData_->library);
- ftData_.reset();
- return false;
- }
-
- FT_UInt spread = static_cast<FT_UInt>(sdfSpread_);
- FT_Property_Set(ftData_->library, "sdf", "spread", &spread);
-
- ascent_ = static_cast<f32>(ftData_->face->size->metrics.ascender) / 64.0f;
- descent_ = static_cast<f32>(-ftData_->face->size->metrics.descender) / 64.0f;
- lineHeight_ = static_cast<f32>(ftData_->face->size->metrics.height) / 64.0f;
-
- atlasData_.resize(atlasWidth_ * atlasHeight_, 0);
-
- glGenTextures(1, &atlasTextureId_);
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-
- glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
-#ifdef ES_PLATFORM_WEB
- // WebGL 2 (GLES 3.0) uses GL_R8 format for single-channel textures
- glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, atlasWidth_, atlasHeight_, 0,
- GL_RED, GL_UNSIGNED_BYTE, atlasData_.data());
-#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, atlasWidth_, atlasHeight_, 0,
- GL_RED, GL_UNSIGNED_BYTE, atlasData_.data());
-#endif
-
- glBindTexture(GL_TEXTURE_2D, 0);
-
- ES_LOG_INFO("SDFFont loaded: {} (size={}, spread={}, atlas={}x{})",
- path, sdfSize_, sdfSpread_, atlasWidth_, atlasHeight_);
-
- preloadASCII();
-
- return true;
-}
-
-// =============================================================================
-// Glyph Loading
-// =============================================================================
-
-const SDFGlyphInfo* SDFFont::getGlyph(u32 codepoint) {
- auto it = glyphs_.find(codepoint);
- if (it != glyphs_.end()) {
- auto lruIt = lruMap_.find(codepoint);
- if (lruIt != lruMap_.end()) {
- lruList_.erase(lruIt->second);
- lruList_.push_front(codepoint);
- lruMap_[codepoint] = lruList_.begin();
- }
- return &it->second;
- }
-
- return loadGlyph(codepoint);
-}
-
-SDFGlyphInfo* SDFFont::loadGlyph(u32 codepoint) {
- if (!ftData_ || !ftData_->face) return nullptr;
-
- if (codepoint == 'H') {
- ES_LOG_INFO("SDF: Loading glyph 'H'");
- }
-
- FT_UInt glyphIndex = FT_Get_Char_Index(ftData_->face, codepoint);
- if (glyphIndex == 0 && codepoint != 0) {
- return nullptr;
- }
-
- FT_Error error = FT_Load_Glyph(ftData_->face, glyphIndex, FT_LOAD_DEFAULT);
- if (error) {
- ES_LOG_WARN("SDFFont: Failed to load glyph for codepoint {}: {}", codepoint, error);
- return nullptr;
- }
-
- error = FT_Render_Glyph(ftData_->face->glyph, FT_RENDER_MODE_SDF);
- if (error) {
- error = FT_Render_Glyph(ftData_->face->glyph, FT_RENDER_MODE_NORMAL);
- if (error) {
- ES_LOG_WARN("SDFFont: Failed to render glyph for codepoint {}: {}", codepoint, error);
- return nullptr;
- }
- }
-
- FT_GlyphSlot slot = ftData_->face->glyph;
- FT_Bitmap& bitmap = slot->bitmap;
-
- SDFGlyphInfo glyph;
- glyph.width = static_cast<f32>(bitmap.width);
- glyph.height = static_cast<f32>(bitmap.rows);
- glyph.bearingX = static_cast<f32>(slot->bitmap_left);
- glyph.bearingY = static_cast<f32>(slot->bitmap_top);
- glyph.advance = static_cast<f32>(slot->advance.x) / 64.0f;
-
- if (codepoint == 'H') {
- ES_LOG_INFO("SDF 'H': bearingX={:.1f} bearingY={:.1f} advance={:.1f} w={} h={}",
- glyph.bearingX, glyph.bearingY, glyph.advance,
- bitmap.width, bitmap.rows);
- }
-
- if (bitmap.width > 0 && bitmap.rows > 0) {
- i32 glyphW = static_cast<i32>(bitmap.width);
- i32 glyphH = static_cast<i32>(bitmap.rows);
- i32 padding = 1;
-
- while (glyphs_.size() >= maxCachedGlyphs_) {
- evictLRU();
- }
-
- i32 atlasX, atlasY;
- if (!findAtlasSpace(glyphW + padding, glyphH + padding, atlasX, atlasY)) {
- packX_ = 1;
- packY_ = 1;
- rowHeight_ = 0;
- atlasData_.assign(atlasWidth_ * atlasHeight_, 0);
-
- for (auto& [cp, g] : glyphs_) {
- g.u0 = g.v0 = g.u1 = g.v1 = 0.0f;
- }
- glyphs_.clear();
- lruList_.clear();
- lruMap_.clear();
-
- if (!findAtlasSpace(glyphW + padding, glyphH + padding, atlasX, atlasY)) {
- ES_LOG_ERROR("SDFFont: Glyph too large for atlas");
- return nullptr;
- }
- }
-
- for (i32 row = 0; row < glyphH; ++row) {
- i32 srcOffset = row * static_cast<i32>(bitmap.pitch);
- i32 dstOffset = (atlasY + row) * static_cast<i32>(atlasWidth_) + atlasX;
- std::memcpy(&atlasData_[static_cast<usize>(dstOffset)],
- &bitmap.buffer[srcOffset],
- static_cast<usize>(glyphW));
- }
-
- glyph.atlasX = atlasX;
- glyph.atlasY = atlasY;
- glyph.atlasWidth = glyphW;
- glyph.atlasHeight = glyphH;
-
- glyph.u0 = static_cast<f32>(atlasX) / static_cast<f32>(atlasWidth_);
- glyph.v0 = static_cast<f32>(atlasY) / static_cast<f32>(atlasHeight_);
- glyph.u1 = static_cast<f32>(atlasX + glyphW) / static_cast<f32>(atlasWidth_);
- glyph.v1 = static_cast<f32>(atlasY + glyphH) / static_cast<f32>(atlasHeight_);
-
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
- glTexSubImage2D(GL_TEXTURE_2D, 0, atlasX, atlasY, glyphW, glyphH,
- GL_RED, GL_UNSIGNED_BYTE, bitmap.buffer);
- glBindTexture(GL_TEXTURE_2D, 0);
-
- markAtlasRegionUsed(atlasX, atlasY, glyphW + padding, glyphH + padding);
- }
-
- auto [insertIt, inserted] = glyphs_.emplace(codepoint, glyph);
- if (inserted) {
- lruList_.push_front(codepoint);
- lruMap_[codepoint] = lruList_.begin();
- }
-
- return &insertIt->second;
-}
-
-// =============================================================================
-// LRU Cache Management
-// =============================================================================
-
-void SDFFont::evictLRU() {
- if (lruList_.empty()) return;
-
- u32 evictCodepoint = lruList_.back();
- lruList_.pop_back();
- lruMap_.erase(evictCodepoint);
-
- auto it = glyphs_.find(evictCodepoint);
- if (it != glyphs_.end()) {
- markAtlasRegionFree(it->second.atlasX, it->second.atlasY,
- it->second.atlasWidth, it->second.atlasHeight);
- glyphs_.erase(it);
- }
-}
-
-void SDFFont::clearCache() {
- glyphs_.clear();
- lruList_.clear();
- lruMap_.clear();
- packX_ = 1;
- packY_ = 1;
- rowHeight_ = 0;
- atlasData_.assign(atlasWidth_ * atlasHeight_, 0);
- rebuildAtlasTexture();
-}
-
-// =============================================================================
-// Atlas Space Management
-// =============================================================================
-
-bool SDFFont::findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY) {
- if (packX_ + width > static_cast<i32>(atlasWidth_)) {
- packX_ = 1;
- packY_ += rowHeight_ + 1;
- rowHeight_ = 0;
- }
-
- if (packY_ + height > static_cast<i32>(atlasHeight_)) {
- return false;
- }
-
- outX = packX_;
- outY = packY_;
- packX_ += width;
- rowHeight_ = std::max(rowHeight_, height);
-
- return true;
-}
-
-void SDFFont::markAtlasRegionUsed(i32 x, i32 y, i32 width, i32 height) {
- (void)x; (void)y; (void)width; (void)height;
-}
-
-void SDFFont::markAtlasRegionFree(i32 x, i32 y, i32 width, i32 height) {
- (void)x; (void)y; (void)width; (void)height;
-}
-
-void SDFFont::rebuildAtlasTexture() {
- if (atlasTextureId_ == 0) return;
-
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
-#ifdef ES_PLATFORM_WEB
- glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, atlasWidth_, atlasHeight_, 0,
- GL_RED, GL_UNSIGNED_BYTE, atlasData_.data());
-#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, atlasWidth_, atlasHeight_, 0,
- GL_RED, GL_UNSIGNED_BYTE, atlasData_.data());
-#endif
- glBindTexture(GL_TEXTURE_2D, 0);
-}
-
-// =============================================================================
-// Preloading
-// =============================================================================
-
-void SDFFont::preloadASCII() {
- for (u32 c = 32; c < 127; ++c) {
- loadGlyph(c);
- }
- ES_LOG_DEBUG("SDFFont: Preloaded {} ASCII glyphs", glyphs_.size());
-}
-
-// =============================================================================
-// Text Measurement
-// =============================================================================
-
-glm::vec2 SDFFont::measureText(const std::string& text, f32 fontSize) {
- if (text.empty()) return {0.0f, 0.0f};
-
- f32 scale = fontSize / sdfSize_;
- f32 width = 0.0f;
- f32 maxWidth = 0.0f;
- i32 lines = 1;
-
- const u8* ptr = reinterpret_cast<const u8*>(text.data());
- const u8* end = ptr + text.size();
-
- while (ptr < end) {
- u32 codepoint;
- if ((*ptr & 0x80) == 0) {
- codepoint = *ptr++;
- } else if ((*ptr & 0xE0) == 0xC0) {
- codepoint = (*ptr++ & 0x1F) << 6;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F);
- } else if ((*ptr & 0xF0) == 0xE0) {
- codepoint = (*ptr++ & 0x0F) << 12;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F);
- } else if ((*ptr & 0xF8) == 0xF0) {
- codepoint = (*ptr++ & 0x07) << 18;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 12;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
- if (ptr < end) codepoint |= (*ptr++ & 0x3F);
- } else {
- ptr++;
- continue;
- }
-
- if (codepoint == '\n') {
- maxWidth = std::max(maxWidth, width);
- width = 0.0f;
- lines++;
- continue;
- }
-
- const auto* glyph = getGlyph(codepoint);
- if (glyph) {
- width += glyph->advance * scale;
- }
- }
-
- maxWidth = std::max(maxWidth, width);
- f32 height = static_cast<f32>(lines) * fontSize * 1.2f;
-
- return {maxWidth, height};
-}
-
-f32 SDFFont::getCharWidth(u32 codepoint, f32 fontSize) {
- const auto* glyph = getGlyph(codepoint);
- if (!glyph) return 0.0f;
-
- f32 scale = fontSize / sdfSize_;
- return glyph->advance * scale;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/SDFFont.hpp b/src/esengine/ui/font/SDFFont.hpp
deleted file mode 100644
index 6c1b80b78..000000000
--- a/src/esengine/ui/font/SDFFont.hpp
+++ /dev/null
@@ -1,192 +0,0 @@
-/**
- * @file SDFFont.hpp
- * @brief SDF font rendering with FreeType
- * @details Provides Signed Distance Field font rendering using FreeType's
- * native SDF rasterizer. Supports dynamic glyph loading with LRU
- * cache for efficient CJK text rendering.
- *
- * @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 <list>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::ui {
-
-// =============================================================================
-// SDF Glyph Information
-// =============================================================================
-
-/**
- * @brief Information about a single SDF glyph in the atlas
- */
-struct SDFGlyphInfo {
- f32 width = 0.0f;
- f32 height = 0.0f;
- f32 bearingX = 0.0f;
- f32 bearingY = 0.0f;
- f32 advance = 0.0f;
-
- f32 u0 = 0.0f;
- f32 v0 = 0.0f;
- f32 u1 = 0.0f;
- f32 v1 = 0.0f;
-
- i32 atlasX = 0;
- i32 atlasY = 0;
- i32 atlasWidth = 0;
- i32 atlasHeight = 0;
-};
-
-// =============================================================================
-// SDFFont Class
-// =============================================================================
-
-/**
- * @brief SDF font for high-quality scalable text rendering
- *
- * @details Uses FreeType's native SDF rasterizer to generate distance field
- * glyphs on demand. Features:
- * - Dynamic glyph loading (efficient for CJK)
- * - LRU cache with atlas space reclamation
- * - High quality at any scale
- * - Support for outline and shadow effects
- *
- * @code
- * auto font = SDFFont::create("assets/fonts/NotoSansCJK.ttf", 48.0f);
- * if (font) {
- * // Glyphs are loaded on demand
- * renderer.drawTextSDF("Hello 你好", position, *font, fontSize, color);
- * }
- * @endcode
- */
-class SDFFont {
-public:
- ~SDFFont();
-
- SDFFont(const SDFFont&) = delete;
- SDFFont& operator=(const SDFFont&) = delete;
-
- SDFFont(SDFFont&& other) noexcept;
- SDFFont& operator=(SDFFont&& other) noexcept;
-
- // =========================================================================
- // Factory Methods
- // =========================================================================
-
- /**
- * @brief Creates an SDF font from a file
- * @param path Path to the TTF/OTF font file
- * @param sdfSize SDF glyph size (recommended: 32-64)
- * @param sdfSpread SDF spread in pixels (default: 8)
- * @return Font instance or nullptr on failure
- */
- static Unique<SDFFont> create(const std::string& path, f32 sdfSize = 48.0f, f32 sdfSpread = 8.0f);
-
- // =========================================================================
- // Properties
- // =========================================================================
-
- f32 getSDFSize() const { return sdfSize_; }
- f32 getSDFSpread() const { return sdfSpread_; }
- f32 getAscent() const { return ascent_; }
- f32 getDescent() const { return descent_; }
- f32 getLineHeight() const { return lineHeight_; }
- u32 getAtlasTextureId() const { return atlasTextureId_; }
- glm::ivec2 getAtlasSize() const { return {atlasWidth_, atlasHeight_}; }
-
- // =========================================================================
- // Glyph Access
- // =========================================================================
-
- /**
- * @brief Gets glyph information, loading if necessary
- * @param codepoint Unicode codepoint
- * @return Glyph info or nullptr if unavailable
- */
- const SDFGlyphInfo* getGlyph(u32 codepoint);
-
- /**
- * @brief Preloads ASCII glyphs for common use
- */
- void preloadASCII();
-
- // =========================================================================
- // Text Measurement
- // =========================================================================
-
- glm::vec2 measureText(const std::string& text, f32 fontSize);
- f32 getCharWidth(u32 codepoint, f32 fontSize);
-
- // =========================================================================
- // Cache Management
- // =========================================================================
-
- /**
- * @brief Gets the number of cached glyphs
- */
- usize getCachedGlyphCount() const { return glyphs_.size(); }
-
- /**
- * @brief Sets the maximum number of cached glyphs
- * @param maxGlyphs Maximum glyphs (default: 2048)
- */
- void setMaxCachedGlyphs(usize maxGlyphs) { maxCachedGlyphs_ = maxGlyphs; }
-
- /**
- * @brief Clears all cached glyphs
- */
- void clearCache();
-
-private:
- SDFFont() = default;
-
- bool loadFromFile(const std::string& path, f32 sdfSize, f32 sdfSpread);
- SDFGlyphInfo* loadGlyph(u32 codepoint);
- void evictLRU();
- void rebuildAtlasTexture();
-
- bool findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY);
- void markAtlasRegionUsed(i32 x, i32 y, i32 width, i32 height);
- void markAtlasRegionFree(i32 x, i32 y, i32 width, i32 height);
-
- struct FTData;
- Unique<FTData> ftData_;
-
- f32 sdfSize_ = 48.0f;
- f32 sdfSpread_ = 8.0f;
- f32 ascent_ = 0.0f;
- f32 descent_ = 0.0f;
- f32 lineHeight_ = 0.0f;
-
- u32 atlasTextureId_ = 0;
- u32 atlasWidth_ = 1024;
- u32 atlasHeight_ = 1024;
- std::vector<u8> atlasData_;
-
- std::unordered_map<u32, SDFGlyphInfo> glyphs_;
- std::list<u32> lruList_;
- std::unordered_map<u32, std::list<u32>::iterator> lruMap_;
- usize maxCachedGlyphs_ = 2048;
-
- i32 packX_ = 1;
- i32 packY_ = 1;
- i32 rowHeight_ = 0;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/SystemFont.cpp b/src/esengine/ui/font/SystemFont.cpp
deleted file mode 100644
index 0f19c3696..000000000
--- a/src/esengine/ui/font/SystemFont.cpp
+++ /dev/null
@@ -1,537 +0,0 @@
-/**
- * @file SystemFont.cpp
- * @brief System font rendering implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "SystemFont.hpp"
-#include "../../core/Log.hpp"
-
-#include <algorithm>
-
-#ifdef ES_PLATFORM_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#define NOMINMAX
-#include <windows.h>
-#endif
-
-#ifdef ES_PLATFORM_WEB
-#include <emscripten.h>
-#include <emscripten/html5.h>
-
-EM_JS(void, es_systemfont_init, (const char* fontFamily, int fontSize), {
- if (!Module._systemFontCanvases) Module._systemFontCanvases = {};
- var id = Object.keys(Module._systemFontCanvases).length;
- var canvas = document.createElement('canvas');
- canvas.width = 256;
- canvas.height = 256;
- var ctx = canvas.getContext('2d');
- ctx.font = fontSize + 'px ' + UTF8ToString(fontFamily);
- ctx.textBaseline = 'top';
- ctx.fillStyle = 'white';
- Module._systemFontCanvases[id] = { canvas: canvas, ctx: ctx };
-});
-
-EM_JS(double, es_systemfont_measure_char, (int codepoint), {
- var canvasData = Module._systemFontCanvases[0];
- if (!canvasData) return 0;
- var ctx = canvasData.ctx;
- var char = String.fromCodePoint(codepoint);
- var metrics = ctx.measureText(char);
- return metrics.width;
-});
-
-#endif
-
-#ifndef ES_PLATFORM_WEB
-#include <glad/glad.h>
-#endif
-
-namespace esengine::ui {
-
-// =============================================================================
-// Platform-specific Data
-// =============================================================================
-
-#ifdef ES_PLATFORM_WINDOWS
-struct SystemFont::PlatformData {
- HDC hdc = nullptr;
- HFONT hFont = nullptr;
- HBITMAP hBitmap = nullptr;
- void* bitmapBits = nullptr;
- i32 bitmapWidth = 256;
- i32 bitmapHeight = 256;
- std::string fontFilePath;
-};
-#elif defined(ES_PLATFORM_WEB)
-struct SystemFont::PlatformData {
- i32 canvasId = 0;
-};
-#else
-struct SystemFont::PlatformData {};
-#endif
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-SystemFont::~SystemFont() {
-#ifdef ES_PLATFORM_WINDOWS
- if (platformData_) {
- if (platformData_->hFont) DeleteObject(platformData_->hFont);
- if (platformData_->hBitmap) DeleteObject(platformData_->hBitmap);
- if (platformData_->hdc) DeleteDC(platformData_->hdc);
- if (!platformData_->fontFilePath.empty()) {
- RemoveFontResourceExA(platformData_->fontFilePath.c_str(), FR_PRIVATE, nullptr);
- }
- }
-#endif
-
-#ifndef ES_PLATFORM_WEB
- if (atlasTextureId_) {
- glDeleteTextures(1, &atlasTextureId_);
- }
-#endif
-}
-
-SystemFont::SystemFont(SystemFont&& other) noexcept
- : platformData_(std::move(other.platformData_))
- , fontFamily_(std::move(other.fontFamily_))
- , fontSize_(other.fontSize_)
- , ascent_(other.ascent_)
- , descent_(other.descent_)
- , lineHeight_(other.lineHeight_)
- , atlasTextureId_(other.atlasTextureId_)
- , atlasWidth_(other.atlasWidth_)
- , atlasHeight_(other.atlasHeight_)
- , atlasData_(std::move(other.atlasData_))
- , glyphs_(std::move(other.glyphs_))
- , lruList_(std::move(other.lruList_))
- , lruMap_(std::move(other.lruMap_))
- , maxCachedGlyphs_(other.maxCachedGlyphs_)
- , packX_(other.packX_)
- , packY_(other.packY_)
- , rowHeight_(other.rowHeight_) {
- other.atlasTextureId_ = 0;
-}
-
-SystemFont& SystemFont::operator=(SystemFont&& other) noexcept {
- if (this != &other) {
- platformData_ = std::move(other.platformData_);
- fontFamily_ = std::move(other.fontFamily_);
- fontSize_ = other.fontSize_;
- ascent_ = other.ascent_;
- descent_ = other.descent_;
- lineHeight_ = other.lineHeight_;
- atlasTextureId_ = other.atlasTextureId_;
- atlasWidth_ = other.atlasWidth_;
- atlasHeight_ = other.atlasHeight_;
- atlasData_ = std::move(other.atlasData_);
- glyphs_ = std::move(other.glyphs_);
- lruList_ = std::move(other.lruList_);
- lruMap_ = std::move(other.lruMap_);
- maxCachedGlyphs_ = other.maxCachedGlyphs_;
- packX_ = other.packX_;
- packY_ = other.packY_;
- rowHeight_ = other.rowHeight_;
- other.atlasTextureId_ = 0;
- }
- return *this;
-}
-
-// =============================================================================
-// Factory
-// =============================================================================
-
-Unique<SystemFont> SystemFont::create(const std::string& fontFamily, f32 fontSize) {
- auto font = Unique<SystemFont>(new SystemFont());
- if (!font->init(fontFamily, fontSize)) {
- return nullptr;
- }
- return font;
-}
-
-Unique<SystemFont> SystemFont::createFromFile(const std::string& filePath, f32 fontSize) {
-#ifdef ES_PLATFORM_WINDOWS
- int result = AddFontResourceExA(filePath.c_str(), FR_PRIVATE, nullptr);
- if (result == 0) {
- ES_LOG_ERROR("SystemFont: Failed to load font file '{}'", filePath);
- return nullptr;
- }
-
- std::string fontName;
- size_t lastSlash = filePath.find_last_of("/\\");
- size_t lastDot = filePath.find_last_of('.');
- if (lastSlash != std::string::npos) {
- fontName = filePath.substr(lastSlash + 1, lastDot - lastSlash - 1);
- } else {
- fontName = filePath.substr(0, lastDot);
- }
-
- auto font = Unique<SystemFont>(new SystemFont());
- if (!font->init(fontName, fontSize)) {
- RemoveFontResourceExA(filePath.c_str(), FR_PRIVATE, nullptr);
- return nullptr;
- }
-
- font->platformData_->fontFilePath = filePath;
- ES_LOG_INFO("SystemFont: Loaded font from file '{}' as '{}'", filePath, fontName);
- return font;
-#else
- ES_LOG_WARN("SystemFont::createFromFile not supported on this platform");
- return nullptr;
-#endif
-}
-
-bool SystemFont::init(const std::string& fontFamily, f32 fontSize) {
- fontFamily_ = fontFamily;
- fontSize_ = fontSize;
- platformData_ = std::make_unique<PlatformData>();
-
-#ifdef ES_PLATFORM_WINDOWS
- platformData_->hdc = CreateCompatibleDC(nullptr);
- if (!platformData_->hdc) {
- ES_LOG_ERROR("SystemFont: Failed to create DC");
- return false;
- }
-
- platformData_->hFont = CreateFontA(
- -static_cast<int>(fontSize),
- 0, 0, 0,
- FW_NORMAL,
- FALSE, FALSE, FALSE,
- DEFAULT_CHARSET,
- OUT_TT_PRECIS,
- CLIP_DEFAULT_PRECIS,
- ANTIALIASED_QUALITY,
- DEFAULT_PITCH | FF_DONTCARE,
- fontFamily.c_str()
- );
-
- if (!platformData_->hFont) {
- ES_LOG_ERROR("SystemFont: Failed to create font '{}'", fontFamily);
- return false;
- }
-
- SelectObject(platformData_->hdc, platformData_->hFont);
-
- TEXTMETRICA tm;
- GetTextMetricsA(platformData_->hdc, &tm);
- ascent_ = static_cast<f32>(tm.tmAscent);
- descent_ = static_cast<f32>(tm.tmDescent);
- lineHeight_ = static_cast<f32>(tm.tmHeight);
-
- BITMAPINFO bmi = {};
- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmi.bmiHeader.biWidth = platformData_->bitmapWidth;
- bmi.bmiHeader.biHeight = -platformData_->bitmapHeight;
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
-
- platformData_->hBitmap = CreateDIBSection(
- platformData_->hdc, &bmi, DIB_RGB_COLORS,
- &platformData_->bitmapBits, nullptr, 0
- );
-
- if (!platformData_->hBitmap) {
- ES_LOG_ERROR("SystemFont: Failed to create bitmap");
- return false;
- }
-
- SelectObject(platformData_->hdc, platformData_->hBitmap);
- SetBkMode(platformData_->hdc, TRANSPARENT);
- SetTextColor(platformData_->hdc, RGB(255, 255, 255));
-
-#elif defined(ES_PLATFORM_WEB)
- es_systemfont_init(fontFamily.c_str(), static_cast<int>(fontSize));
- ascent_ = fontSize * 0.8f;
- descent_ = fontSize * 0.2f;
- lineHeight_ = fontSize * 1.2f;
-#endif
-
- atlasData_.resize(static_cast<size_t>(atlasWidth_) * atlasHeight_ * 4, 0);
-
-#ifndef ES_PLATFORM_WEB
- glGenTextures(1, &atlasTextureId_);
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, atlasWidth_, atlasHeight_, 0,
- GL_RGBA, GL_UNSIGNED_BYTE, atlasData_.data());
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-#endif
-
- ES_LOG_INFO("SystemFont: Created '{}' at {}px", fontFamily, fontSize);
- return true;
-}
-
-// =============================================================================
-// Glyph Access
-// =============================================================================
-
-const GlyphInfo* SystemFont::getGlyph(u32 codepoint) {
- auto it = glyphs_.find(codepoint);
- if (it != glyphs_.end()) {
- auto lruIt = lruMap_.find(codepoint);
- if (lruIt != lruMap_.end()) {
- lruList_.erase(lruIt->second);
- lruList_.push_front(codepoint);
- lruMap_[codepoint] = lruList_.begin();
- }
- return &it->second;
- }
-
- return renderGlyph(codepoint);
-}
-
-GlyphInfo* SystemFont::renderGlyph(u32 codepoint) {
- if (glyphs_.size() >= maxCachedGlyphs_) {
- evictLRU();
- }
-
- GlyphInfo glyph;
-
-#ifdef ES_PLATFORM_WINDOWS
- wchar_t wc[2] = { static_cast<wchar_t>(codepoint), 0 };
-
- SIZE size;
- GetTextExtentPoint32W(platformData_->hdc, wc, 1, &size);
-
- i32 glyphWidth = size.cx + 2;
- i32 glyphHeight = size.cy + 2;
-
- if (glyphWidth > platformData_->bitmapWidth || glyphHeight > platformData_->bitmapHeight) {
- return nullptr;
- }
-
- memset(platformData_->bitmapBits, 0,
- static_cast<size_t>(platformData_->bitmapWidth) * platformData_->bitmapHeight * 4);
-
- TextOutW(platformData_->hdc, 1, 1, wc, 1);
-
- i32 atlasX, atlasY;
- if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {
- rebuildAtlasTexture();
- if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {
- return nullptr;
- }
- }
-
- u8* src = static_cast<u8*>(platformData_->bitmapBits);
- for (i32 y = 0; y < glyphHeight; ++y) {
- for (i32 x = 0; x < glyphWidth; ++x) {
- i32 srcIdx = (y * platformData_->bitmapWidth + x) * 4;
- i32 dstIdx = ((atlasY + y) * atlasWidth_ + (atlasX + x)) * 4;
- u8 r = src[srcIdx + 2];
- u8 g = src[srcIdx + 1];
- u8 b = src[srcIdx + 0];
- u8 a = std::max({r, g, b});
- atlasData_[dstIdx + 0] = 255;
- atlasData_[dstIdx + 1] = 255;
- atlasData_[dstIdx + 2] = 255;
- atlasData_[dstIdx + 3] = a;
- }
- }
-
- ABC abc;
- if (GetCharABCWidthsW(platformData_->hdc, codepoint, codepoint, &abc)) {
- glyph.bearingX = static_cast<f32>(abc.abcA);
- glyph.advance = static_cast<f32>(abc.abcA + abc.abcB + abc.abcC);
- } else {
- glyph.bearingX = 0;
- glyph.advance = static_cast<f32>(size.cx);
- }
-
- glyph.width = static_cast<f32>(glyphWidth);
- glyph.height = static_cast<f32>(glyphHeight);
- glyph.bearingY = ascent_;
- glyph.u0 = static_cast<f32>(atlasX) / atlasWidth_;
- glyph.v0 = static_cast<f32>(atlasY) / atlasHeight_;
- glyph.u1 = static_cast<f32>(atlasX + glyphWidth) / atlasWidth_;
- glyph.v1 = static_cast<f32>(atlasY + glyphHeight) / atlasHeight_;
-
-#elif defined(ES_PLATFORM_WEB)
- i32 glyphWidth = static_cast<i32>(fontSize_ * 1.5f);
- i32 glyphHeight = static_cast<i32>(fontSize_ * 1.5f);
-
- i32 atlasX, atlasY;
- if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {
- rebuildAtlasTexture();
- if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {
- return nullptr;
- }
- }
-
- f32 advance = static_cast<f32>(es_systemfont_measure_char(static_cast<int>(codepoint)));
-
- glyph.width = static_cast<f32>(glyphWidth);
- glyph.height = static_cast<f32>(glyphHeight);
- glyph.bearingX = 0;
- glyph.bearingY = ascent_;
- glyph.advance = advance;
- glyph.u0 = static_cast<f32>(atlasX) / atlasWidth_;
- glyph.v0 = static_cast<f32>(atlasY) / atlasHeight_;
- glyph.u1 = static_cast<f32>(atlasX + glyphWidth) / atlasWidth_;
- glyph.v1 = static_cast<f32>(atlasY + glyphHeight) / atlasHeight_;
-#endif
-
- glyphs_[codepoint] = glyph;
- lruList_.push_front(codepoint);
- lruMap_[codepoint] = lruList_.begin();
-
-#ifndef ES_PLATFORM_WEB
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, atlasWidth_, atlasHeight_,
- GL_RGBA, GL_UNSIGNED_BYTE, atlasData_.data());
-#endif
-
- return &glyphs_[codepoint];
-}
-
-// =============================================================================
-// Atlas Management
-// =============================================================================
-
-bool SystemFont::findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY) {
- if (packX_ + width > atlasWidth_) {
- packX_ = 1;
- packY_ += rowHeight_ + 1;
- rowHeight_ = 0;
- }
-
- if (packY_ + height > atlasHeight_) {
- return false;
- }
-
- outX = packX_;
- outY = packY_;
- packX_ += width + 1;
- rowHeight_ = std::max(rowHeight_, height);
- return true;
-}
-
-void SystemFont::rebuildAtlasTexture() {
- glyphs_.clear();
- lruList_.clear();
- lruMap_.clear();
- std::fill(atlasData_.begin(), atlasData_.end(), 0);
- packX_ = 1;
- packY_ = 1;
- rowHeight_ = 0;
-}
-
-void SystemFont::evictLRU() {
- if (lruList_.empty()) return;
-
- u32 oldest = lruList_.back();
- lruList_.pop_back();
- lruMap_.erase(oldest);
- glyphs_.erase(oldest);
-}
-
-void SystemFont::clearCache() {
- rebuildAtlasTexture();
-}
-
-// =============================================================================
-// Text Measurement
-// =============================================================================
-
-glm::vec2 SystemFont::measureText(const std::string& text, f32 fontSize) {
- f32 scale = fontSize / fontSize_;
- f32 width = 0.0f;
- f32 maxHeight = lineHeight_ * scale;
-
- const char* ptr = text.c_str();
- const char* end = ptr + text.size();
-
- while (ptr < end) {
- u32 codepoint = static_cast<u8>(*ptr);
- i32 len = 1;
-
- if ((codepoint & 0x80) == 0) {
- len = 1;
- } else if ((codepoint & 0xE0) == 0xC0) {
- len = 2;
- codepoint = codepoint & 0x1F;
- } else if ((codepoint & 0xF0) == 0xE0) {
- len = 3;
- codepoint = codepoint & 0x0F;
- } else if ((codepoint & 0xF8) == 0xF0) {
- len = 4;
- codepoint = codepoint & 0x07;
- }
-
- for (i32 i = 1; i < len && ptr + i < end; ++i) {
- codepoint = (codepoint << 6) | (static_cast<u8>(ptr[i]) & 0x3F);
- }
- ptr += len;
-
- if (codepoint == '\n') {
- maxHeight += lineHeight_ * scale;
- continue;
- }
-
- const GlyphInfo* glyph = getGlyph(codepoint);
- if (glyph) {
- width += glyph->advance * scale;
- }
- }
-
- return {width, maxHeight};
-}
-
-f32 SystemFont::getCharWidth(u32 codepoint, f32 fontSize) {
- f32 scale = fontSize / fontSize_;
- const GlyphInfo* glyph = getGlyph(codepoint);
- return glyph ? glyph->advance * scale : 0.0f;
-}
-
-// =============================================================================
-// Preloading
-// =============================================================================
-
-void SystemFont::preloadASCII() {
- for (u32 c = 32; c < 127; ++c) {
- getGlyph(c);
- }
-}
-
-void SystemFont::preloadChars(const std::string& chars) {
- const char* ptr = chars.c_str();
- const char* end = ptr + chars.size();
-
- while (ptr < end) {
- u32 codepoint = static_cast<u8>(*ptr);
- i32 len = 1;
-
- if ((codepoint & 0x80) == 0) {
- len = 1;
- } else if ((codepoint & 0xE0) == 0xC0) {
- len = 2;
- codepoint = codepoint & 0x1F;
- } else if ((codepoint & 0xF0) == 0xE0) {
- len = 3;
- codepoint = codepoint & 0x0F;
- } else if ((codepoint & 0xF8) == 0xF0) {
- len = 4;
- codepoint = codepoint & 0x07;
- }
-
- for (i32 i = 1; i < len && ptr + i < end; ++i) {
- codepoint = (codepoint << 6) | (static_cast<u8>(ptr[i]) & 0x3F);
- }
- ptr += len;
-
- getGlyph(codepoint);
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/SystemFont.hpp b/src/esengine/ui/font/SystemFont.hpp
deleted file mode 100644
index 3cd26bdb3..000000000
--- a/src/esengine/ui/font/SystemFont.hpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * @file SystemFont.hpp
- * @brief System font rendering using OS native APIs
- * @details Uses DirectWrite on Windows, CoreText on macOS, Canvas2D on Web.
- * No TTF files needed - uses installed system fonts.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-#include "IFont.hpp"
-#include <list>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::ui {
-
-class SystemFont : public IFont {
-public:
- ~SystemFont() override;
-
- SystemFont(const SystemFont&) = delete;
- SystemFont& operator=(const SystemFont&) = delete;
- SystemFont(SystemFont&& other) noexcept;
- SystemFont& operator=(SystemFont&& other) noexcept;
-
- // =========================================================================
- // Factory
- // =========================================================================
-
- /**
- * @brief Create a system font
- * @param fontFamily Font family name (e.g. "Microsoft YaHei", "Arial", "sans-serif")
- * @param fontSize Base font size in pixels
- * @return Font instance or nullptr on failure
- */
- static Unique<SystemFont> create(const std::string& fontFamily, f32 fontSize = 32.0f);
-
- /**
- * @brief Create a font from TTF file
- * @param filePath Path to TTF font file
- * @param fontSize Base font size in pixels
- * @return Font instance or nullptr on failure
- */
- static Unique<SystemFont> createFromFile(const std::string& filePath, f32 fontSize = 32.0f);
-
- // =========================================================================
- // IFont Interface
- // =========================================================================
-
- FontType getType() const override { return FontType::System; }
- const GlyphInfo* getGlyph(u32 codepoint) override;
- u32 getTextureId() const override { return atlasTextureId_; }
- f32 getFontSize() const override { return fontSize_; }
- f32 getLineHeight() const override { return lineHeight_; }
- f32 getAscent() const override { return ascent_; }
- f32 getDescent() const override { return descent_; }
- glm::vec2 measureText(const std::string& text, f32 fontSize) override;
- f32 getCharWidth(u32 codepoint, f32 fontSize) override;
- glm::ivec2 getAtlasSize() const override { return {atlasWidth_, atlasHeight_}; }
-
- // =========================================================================
- // System Font Specific
- // =========================================================================
-
- const std::string& getFontFamily() const { return fontFamily_; }
- void preloadASCII();
- void preloadChars(const std::string& chars);
- usize getCachedGlyphCount() const { return glyphs_.size(); }
- void setMaxCachedGlyphs(usize maxGlyphs) { maxCachedGlyphs_ = maxGlyphs; }
- void clearCache();
-
-private:
- SystemFont() = default;
-
- bool init(const std::string& fontFamily, f32 fontSize);
- GlyphInfo* renderGlyph(u32 codepoint);
- void evictLRU();
- void rebuildAtlasTexture();
- bool findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY);
-
- struct PlatformData;
- Unique<PlatformData> platformData_;
-
- std::string fontFamily_;
- f32 fontSize_ = 32.0f;
- f32 ascent_ = 0.0f;
- f32 descent_ = 0.0f;
- f32 lineHeight_ = 0.0f;
-
- u32 atlasTextureId_ = 0;
- i32 atlasWidth_ = 1024;
- i32 atlasHeight_ = 1024;
- std::vector<u8> atlasData_;
-
- std::unordered_map<u32, GlyphInfo> glyphs_;
- std::list<u32> lruList_;
- std::unordered_map<u32, std::list<u32>::iterator> lruMap_;
- usize maxCachedGlyphs_ = 2048;
-
- i32 packX_ = 1;
- i32 packY_ = 1;
- i32 rowHeight_ = 0;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/icons/Icons.hpp b/src/esengine/ui/icons/Icons.hpp
deleted file mode 100644
index 5e5d08b17..000000000
--- a/src/esengine/ui/icons/Icons.hpp
+++ /dev/null
@@ -1,252 +0,0 @@
-/**
- * @file Icons.hpp
- * @brief Lucide icon font Unicode constants
- * @details Provides constants for rendering Lucide icons via icon font.
- * Font file: assets/fonts/lucide.ttf
- * Reference: https://lucide.dev/icons/
- * Unicode mapping from: https://unpkg.com/lucide-static@latest/font/lucide.css
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-namespace esengine::ui::icons {
-
-// =============================================================================
-// File & Folder Icons
-// =============================================================================
-
-constexpr const char* Folder = "\ue0d7";
-constexpr const char* FolderOpen = "\ue247";
-constexpr const char* FolderPlus = "\ue0d9";
-constexpr const char* FolderMinus = "\ue0d8";
-constexpr const char* FolderClosed = "\ue330";
-constexpr const char* File = "\ue0c0";
-constexpr const char* FileText = "\ue0cc";
-constexpr const char* FileCode = "\ue0c3";
-constexpr const char* FileImage = "\ue31c";
-constexpr const char* FileAudio = "\ue55e";
-constexpr const char* FileVideo = "\ue32b";
-constexpr const char* FilePlus = "\ue0c9";
-constexpr const char* FileMinus = "\ue0c6";
-constexpr const char* FileX = "\ue0cd";
-constexpr const char* Files = "\ue0cf";
-
-// =============================================================================
-// Navigation & Arrows
-// =============================================================================
-
-constexpr const char* ArrowUp = "\ue04a";
-constexpr const char* ArrowDown = "\ue042";
-constexpr const char* ArrowLeft = "\ue048";
-constexpr const char* ArrowRight = "\ue049";
-constexpr const char* ChevronUp = "\ue070";
-constexpr const char* ChevronDown = "\ue06d";
-constexpr const char* ChevronLeft = "\ue06e";
-constexpr const char* ChevronRight = "\ue06f";
-constexpr const char* ChevronsUp = "\ue074";
-constexpr const char* ChevronsDown = "\ue071";
-constexpr const char* ChevronsLeft = "\ue072";
-constexpr const char* ChevronsRight = "\ue073";
-constexpr const char* CornerDownLeft = "\ue0a1";
-constexpr const char* CornerDownRight = "\ue0a2";
-constexpr const char* CornerUpLeft = "\ue0a7";
-constexpr const char* CornerUpRight = "\ue0a8";
-
-// =============================================================================
-// Actions
-// =============================================================================
-
-constexpr const char* Plus = "\ue13d";
-constexpr const char* Minus = "\ue11c";
-constexpr const char* X = "\ue1b2";
-constexpr const char* Check = "\ue06c";
-constexpr const char* Search = "\ue151";
-constexpr const char* Settings = "\ue154";
-constexpr const char* Trash = "\ue18d";
-constexpr const char* Trash2 = "\ue18e";
-constexpr const char* Edit = "\ue1f9";
-constexpr const char* Edit2 = "\ue172";
-constexpr const char* Edit3 = "\ue4f0";
-constexpr const char* Copy = "\ue09e";
-constexpr const char* Clipboard = "\ue085";
-constexpr const char* Save = "\ue14d";
-constexpr const char* Download = "\ue0b2";
-constexpr const char* Upload = "\ue19e";
-constexpr const char* Refresh = "\ue145";
-constexpr const char* RotateCw = "\ue149";
-constexpr const char* RotateCcw = "\ue148";
-constexpr const char* Undo = "\ue19b";
-constexpr const char* Undo2 = "\ue2a1";
-constexpr const char* Redo = "\ue143";
-constexpr const char* Redo2 = "\ue2a0";
-
-// =============================================================================
-// Media Controls
-// =============================================================================
-
-constexpr const char* Play = "\ue13c";
-constexpr const char* Pause = "\ue12e";
-constexpr const char* Stop = "\ue083";
-constexpr const char* SkipBack = "\ue15f";
-constexpr const char* SkipForward = "\ue160";
-constexpr const char* FastForward = "\ue0bd";
-constexpr const char* Rewind = "\ue147";
-constexpr const char* Volume = "\ue1a9";
-constexpr const char* Volume1 = "\ue1aa";
-constexpr const char* Volume2 = "\ue1ab";
-constexpr const char* VolumeX = "\ue1ac";
-
-// =============================================================================
-// UI Elements
-// =============================================================================
-
-constexpr const char* Menu = "\ue115";
-constexpr const char* MoreHorizontal = "\ue0b6";
-constexpr const char* MoreVertical = "\ue0b7";
-constexpr const char* Grid = "\ue4ff";
-constexpr const char* List = "\ue106";
-constexpr const char* Filter = "\ue460";
-constexpr const char* Layout = "\ue0ff";
-constexpr const char* LayoutGrid = "\ue0ff";
-constexpr const char* Layers = "\ue529";
-constexpr const char* Maximize = "\ue112";
-constexpr const char* Maximize2 = "\ue113";
-constexpr const char* Minimize = "\ue11a";
-constexpr const char* Minimize2 = "\ue11b";
-constexpr const char* PanelLeft = "\ue12a";
-constexpr const char* PanelRight = "\ue431";
-constexpr const char* PanelTop = "\ue435";
-constexpr const char* PanelBottom = "\ue42c";
-constexpr const char* SidebarLeft = "\ue12a";
-constexpr const char* SidebarRight = "\ue431";
-constexpr const char* Columns = "\ue098";
-constexpr const char* Rows = "\ue14c";
-
-// =============================================================================
-// Objects & Shapes
-// =============================================================================
-
-constexpr const char* Box = "\ue061";
-constexpr const char* Cube = "\ue096";
-constexpr const char* Circle = "\ue076";
-constexpr const char* Square = "\ue167";
-constexpr const char* Triangle = "\ue192";
-constexpr const char* Star = "\ue176";
-constexpr const char* Heart = "\ue0f2";
-constexpr const char* Image = "\ue0f6";
-constexpr const char* Camera = "\ue064";
-constexpr const char* Video = "\ue1a5";
-constexpr const char* Music = "\ue122";
-constexpr const char* Mic = "\ue118";
-
-// =============================================================================
-// Tools
-// =============================================================================
-
-constexpr const char* Move = "\ue121";
-constexpr const char* Hand = "\ue1d7";
-constexpr const char* Pointer = "\ue1e8";
-constexpr const char* MousePointer = "\ue11f";
-constexpr const char* Crosshair = "\ue0ac";
-constexpr const char* Target = "\ue180";
-constexpr const char* Zap = "\ue1b4";
-constexpr const char* Wand = "\ue246";
-constexpr const char* Paintbrush = "\ue2e7";
-constexpr const char* Eraser = "\ue28f";
-constexpr const char* Scissors = "\ue14e";
-constexpr const char* Crop = "\ue0ab";
-
-// =============================================================================
-// Development
-// =============================================================================
-
-constexpr const char* Code = "\ue093";
-constexpr const char* Code2 = "\ue206";
-constexpr const char* Terminal = "\ue181";
-constexpr const char* Bug = "\ue20c";
-constexpr const char* GitBranch = "\ue0e2";
-constexpr const char* GitCommit = "\ue0e3";
-constexpr const char* GitMerge = "\ue0e4";
-constexpr const char* Braces = "\ue36a";
-constexpr const char* Brackets = "\ue443";
-constexpr const char* Database = "\ue0ad";
-constexpr const char* Server = "\ue153";
-constexpr const char* Cpu = "\ue0a9";
-
-// =============================================================================
-// Status & Alerts
-// =============================================================================
-
-constexpr const char* Info = "\ue0f9";
-constexpr const char* AlertCircle = "\ue077";
-constexpr const char* AlertTriangle = "\ue193";
-constexpr const char* HelpCircle = "\ue082";
-constexpr const char* CheckCircle = "\ue07c";
-constexpr const char* CheckCircle2 = "\ue226";
-constexpr const char* XCircle = "\ue084";
-constexpr const char* Bell = "\ue059";
-constexpr const char* BellOff = "\ue05a";
-
-// =============================================================================
-// View & Visibility
-// =============================================================================
-
-constexpr const char* Eye = "\ue0ba";
-constexpr const char* EyeOff = "\ue0bb";
-constexpr const char* ZoomIn = "\ue1b6";
-constexpr const char* ZoomOut = "\ue1b7";
-constexpr const char* Focus = "\ue29e";
-constexpr const char* Fullscreen = "\ue534";
-constexpr const char* ShrinkScreen = "\ue220";
-
-// =============================================================================
-// Hierarchy & Structure
-// =============================================================================
-
-constexpr const char* Component = "\ue2ad";
-constexpr const char* Package = "\ue129";
-constexpr const char* Puzzle = "\ue29c";
-constexpr const char* Workflow = "\ue425";
-constexpr const char* Network = "\ue125";
-constexpr const char* Share2 = "\ue156";
-constexpr const char* Link = "\ue102";
-constexpr const char* Unlink = "\ue19c";
-constexpr const char* Lock = "\ue10b";
-constexpr const char* Unlock = "\ue10c";
-
-// =============================================================================
-// Transform
-// =============================================================================
-
-constexpr const char* Move3d = "\ue2e5";
-constexpr const char* Rotate3d = "\ue2ea";
-constexpr const char* Scale3d = "\ue2eb";
-constexpr const char* FlipHorizontal = "\ue35d";
-constexpr const char* FlipVertical = "\ue35f";
-constexpr const char* AlignLeft = "\ue02b";
-constexpr const char* AlignCenter = "\ue029";
-constexpr const char* AlignRight = "\ue02d";
-constexpr const char* AlignJustify = "\ue02c";
-
-// =============================================================================
-// Misc
-// =============================================================================
-
-constexpr const char* Home = "\ue0f5";
-constexpr const char* User = "\ue19f";
-constexpr const char* Users = "\ue1a4";
-constexpr const char* Cog = "\ue30b";
-constexpr const char* Wrench = "\ue1b1";
-constexpr const char* Hammer = "\ue0ec";
-constexpr const char* Globe = "\ue0e8";
-constexpr const char* Sun = "\ue178";
-constexpr const char* Moon = "\ue11e";
-constexpr const char* Cloud = "\ue088";
-constexpr const char* Sparkles = "\ue412";
-
-} // namespace esengine::ui::icons
diff --git a/src/esengine/ui/layout/Layout.hpp b/src/esengine/ui/layout/Layout.hpp
deleted file mode 100644
index e5442724f..000000000
--- a/src/esengine/ui/layout/Layout.hpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * @file Layout.hpp
- * @brief Layout interface for widget arrangement
- * @details Defines the interface for layout managers that arrange child
- * widgets within a container.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-#include "../core/Types.hpp"
-
-#include <glm/glm.hpp>
-
-namespace esengine::ui {
-
-class Widget;
-
-// =============================================================================
-// Layout Interface
-// =============================================================================
-
-/**
- * @brief Interface for layout managers
- *
- * @details Layout managers determine how child widgets are positioned and
- * sized within their parent container.
- */
-class Layout {
-public:
- virtual ~Layout() = default;
-
- /**
- * @brief Measures the preferred size for the layout
- * @param container The container widget
- * @param availableWidth Available width
- * @param availableHeight Available height
- * @return Preferred size for the content
- */
- virtual glm::vec2 measure(Widget& container, f32 availableWidth, f32 availableHeight) = 0;
-
- /**
- * @brief Lays out children within the given bounds
- * @param container The container widget
- * @param bounds Available bounds for children
- */
- virtual void layout(Widget& container, const Rect& bounds) = 0;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/layout/SizeValue.hpp b/src/esengine/ui/layout/SizeValue.hpp
deleted file mode 100644
index 5ed6179d3..000000000
--- a/src/esengine/ui/layout/SizeValue.hpp
+++ /dev/null
@@ -1,283 +0,0 @@
-/**
- * @file SizeValue.hpp
- * @brief Flexible size value types for UI layout
- * @details Provides size values that can be expressed in pixels, percentages,
- * flex units, or auto-sizing for flexible layout systems.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-
-#include <limits>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Size Unit
-// =============================================================================
-
-/**
- * @brief Units for expressing size values
- */
-enum class SizeUnit : u8 {
- Pixels,
- Percent,
- Flex,
- Auto,
- FitContent
-};
-
-// =============================================================================
-// Size Value
-// =============================================================================
-
-/**
- * @brief A size value with unit for flexible layout
- *
- * @details Represents a dimension that can be expressed in different units:
- * - Pixels: Absolute size in pixels
- * - Percent: Percentage of parent's available space
- * - Flex: Flexible space that grows/shrinks relative to siblings
- * - Auto: Size determined by content
- * - FitContent: Shrink to fit content, up to available space
- */
-struct SizeValue {
- f32 value = 0.0f;
- SizeUnit unit = SizeUnit::Auto;
-
- constexpr SizeValue() = default;
- constexpr SizeValue(f32 v, SizeUnit u) : value(v), unit(u) {}
-
- /** @brief Creates an absolute pixel size */
- static constexpr SizeValue px(f32 pixels) { return SizeValue(pixels, SizeUnit::Pixels); }
-
- /** @brief Creates a percentage size (0-100) */
- static constexpr SizeValue percent(f32 pct) { return SizeValue(pct, SizeUnit::Percent); }
-
- /** @brief Creates a flex size (relative weight) */
- static constexpr SizeValue flex(f32 weight = 1.0f) { return SizeValue(weight, SizeUnit::Flex); }
-
- /** @brief Creates an auto size (determined by content) */
- static constexpr SizeValue autoSize() { return SizeValue(0.0f, SizeUnit::Auto); }
-
- /** @brief Creates a fit-content size */
- static constexpr SizeValue fitContent() { return SizeValue(0.0f, SizeUnit::FitContent); }
-
- /** @brief Returns true if this is an absolute pixel value */
- constexpr bool isPixels() const { return unit == SizeUnit::Pixels; }
-
- /** @brief Returns true if this is a percentage value */
- constexpr bool isPercent() const { return unit == SizeUnit::Percent; }
-
- /** @brief Returns true if this is a flex value */
- constexpr bool isFlex() const { return unit == SizeUnit::Flex; }
-
- /** @brief Returns true if this is an auto value */
- constexpr bool isAuto() const { return unit == SizeUnit::Auto; }
-
- /** @brief Returns true if this is a fit-content value */
- constexpr bool isFitContent() const { return unit == SizeUnit::FitContent; }
-
- /**
- * @brief Resolves the size to pixels given available space
- *
- * @param available The available space in pixels
- * @param contentSize The intrinsic content size (for auto/fit-content)
- * @return The resolved size in pixels
- */
- constexpr f32 resolve(f32 available, f32 contentSize = 0.0f) const {
- switch (unit) {
- case SizeUnit::Pixels:
- return value;
- case SizeUnit::Percent:
- return available * (value / 100.0f);
- case SizeUnit::Flex:
- return available;
- case SizeUnit::Auto:
- return contentSize;
- case SizeUnit::FitContent:
- return (contentSize < available) ? contentSize : available;
- }
- return 0.0f;
- }
-
- /**
- * @brief Returns true if this size needs content measurement to resolve
- */
- constexpr bool needsContentSize() const {
- return unit == SizeUnit::Auto || unit == SizeUnit::FitContent;
- }
-
- constexpr bool operator==(const SizeValue& other) const {
- return unit == other.unit && (unit == SizeUnit::Auto || value == other.value);
- }
-
- constexpr bool operator!=(const SizeValue& other) const { return !(*this == other); }
-};
-
-// =============================================================================
-// Size Constraints
-// =============================================================================
-
-/**
- * @brief Size constraints for layout (min/max bounds)
- *
- * @details Defines minimum and maximum size constraints that can be applied
- * during layout calculation.
- */
-struct SizeConstraints {
- f32 minWidth = 0.0f;
- f32 minHeight = 0.0f;
- f32 maxWidth = std::numeric_limits<f32>::max();
- f32 maxHeight = std::numeric_limits<f32>::max();
-
- constexpr SizeConstraints() = default;
-
- constexpr SizeConstraints(f32 minW, f32 minH, f32 maxW, f32 maxH)
- : minWidth(minW), minHeight(minH), maxWidth(maxW), maxHeight(maxH) {}
-
- /** @brief Creates constraints with no limits */
- static constexpr SizeConstraints unconstrained() { return SizeConstraints(); }
-
- /** @brief Creates tight constraints (exact size) */
- static constexpr SizeConstraints exact(f32 width, f32 height) {
- return SizeConstraints(width, height, width, height);
- }
-
- /** @brief Creates constraints with maximum size only */
- static constexpr SizeConstraints maxSize(f32 width, f32 height) {
- return SizeConstraints(0.0f, 0.0f, width, height);
- }
-
- /** @brief Creates constraints with minimum size only */
- static constexpr SizeConstraints minSize(f32 width, f32 height) {
- return SizeConstraints(width, height, std::numeric_limits<f32>::max(),
- std::numeric_limits<f32>::max());
- }
-
- /** @brief Constrains a width value to these constraints */
- constexpr f32 constrainWidth(f32 width) const {
- if (width < minWidth) return minWidth;
- if (width > maxWidth) return maxWidth;
- return width;
- }
-
- /** @brief Constrains a height value to these constraints */
- constexpr f32 constrainHeight(f32 height) const {
- if (height < minHeight) return minHeight;
- if (height > maxHeight) return maxHeight;
- return height;
- }
-
- /** @brief Returns true if these constraints allow any size */
- constexpr bool isUnconstrained() const {
- return minWidth == 0.0f && minHeight == 0.0f &&
- maxWidth == std::numeric_limits<f32>::max() &&
- maxHeight == std::numeric_limits<f32>::max();
- }
-
- /** @brief Returns true if these constraints require an exact size */
- constexpr bool isTight() const {
- return minWidth == maxWidth && minHeight == maxHeight;
- }
-};
-
-// =============================================================================
-// Alignment
-// =============================================================================
-
-/**
- * @brief Horizontal alignment options
- */
-enum class HAlign : u8 {
- Left,
- Center,
- Right,
- Stretch
-};
-
-/**
- * @brief Vertical alignment options
- */
-enum class VAlign : u8 {
- Top,
- Center,
- Bottom,
- Stretch
-};
-
-/**
- * @brief Combined alignment for both axes
- */
-struct Alignment {
- HAlign horizontal = HAlign::Left;
- VAlign vertical = VAlign::Top;
-
- constexpr Alignment() = default;
- constexpr Alignment(HAlign h, VAlign v) : horizontal(h), vertical(v) {}
-
- static constexpr Alignment topLeft() { return {HAlign::Left, VAlign::Top}; }
- static constexpr Alignment topCenter() { return {HAlign::Center, VAlign::Top}; }
- static constexpr Alignment topRight() { return {HAlign::Right, VAlign::Top}; }
- static constexpr Alignment centerLeft() { return {HAlign::Left, VAlign::Center}; }
- static constexpr Alignment center() { return {HAlign::Center, VAlign::Center}; }
- static constexpr Alignment centerRight() { return {HAlign::Right, VAlign::Center}; }
- static constexpr Alignment bottomLeft() { return {HAlign::Left, VAlign::Bottom}; }
- static constexpr Alignment bottomCenter() { return {HAlign::Center, VAlign::Bottom}; }
- static constexpr Alignment bottomRight() { return {HAlign::Right, VAlign::Bottom}; }
- static constexpr Alignment stretch() { return {HAlign::Stretch, VAlign::Stretch}; }
-
- /**
- * @brief Calculates the X offset for aligning content within a container
- *
- * @param containerWidth Width of the container
- * @param contentWidth Width of the content to align
- * @return X offset from container left edge
- */
- constexpr f32 alignX(f32 containerWidth, f32 contentWidth) const {
- switch (horizontal) {
- case HAlign::Left:
- return 0.0f;
- case HAlign::Center:
- return (containerWidth - contentWidth) * 0.5f;
- case HAlign::Right:
- return containerWidth - contentWidth;
- case HAlign::Stretch:
- return 0.0f;
- }
- return 0.0f;
- }
-
- /**
- * @brief Calculates the Y offset for aligning content within a container
- *
- * @param containerHeight Height of the container
- * @param contentHeight Height of the content to align
- * @return Y offset from container top edge
- */
- constexpr f32 alignY(f32 containerHeight, f32 contentHeight) const {
- switch (vertical) {
- case VAlign::Top:
- return 0.0f;
- case VAlign::Center:
- return (containerHeight - contentHeight) * 0.5f;
- case VAlign::Bottom:
- return containerHeight - contentHeight;
- case VAlign::Stretch:
- return 0.0f;
- }
- return 0.0f;
- }
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/layout/StackLayout.cpp b/src/esengine/ui/layout/StackLayout.cpp
deleted file mode 100644
index 8c8b9742d..000000000
--- a/src/esengine/ui/layout/StackLayout.cpp
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- * @file StackLayout.cpp
- * @brief Stack layout implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "StackLayout.hpp"
-#include "../widgets/Widget.hpp"
-
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-StackLayout::StackLayout(StackDirection direction, f32 spacing)
- : direction_(direction), spacing_(spacing) {}
-
-// =============================================================================
-// Measure
-// =============================================================================
-
-glm::vec2 StackLayout::measure(Widget& container, f32 availableWidth, f32 availableHeight) {
- const auto& children = container.getChildren();
-
- f32 mainSize = 0.0f;
- f32 crossSize = 0.0f;
- usize visibleCount = 0;
-
- bool isVertical = (direction_ == StackDirection::Vertical);
-
- for (const auto& child : children) {
- if (!child->isVisible()) continue;
-
- f32 childAvailW = isVertical ? availableWidth : (availableWidth - mainSize);
- f32 childAvailH = isVertical ? (availableHeight - mainSize) : availableHeight;
-
- auto childSize = child->measure(childAvailW, childAvailH);
- const auto& margin = child->getMargin();
-
- f32 childMainSize = isVertical ? (childSize.y + margin.totalVertical())
- : (childSize.x + margin.totalHorizontal());
-
- f32 childCrossSize = isVertical ? (childSize.x + margin.totalHorizontal())
- : (childSize.y + margin.totalVertical());
-
- mainSize += childMainSize;
- crossSize = (childCrossSize > crossSize) ? childCrossSize : crossSize;
- visibleCount++;
- }
-
- if (visibleCount > 1) {
- mainSize += spacing_ * static_cast<f32>(visibleCount - 1);
- }
-
- return isVertical ? glm::vec2{crossSize, mainSize} : glm::vec2{mainSize, crossSize};
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-void StackLayout::layout(Widget& container, const Rect& bounds) {
- const auto& children = container.getChildren();
-
- if (children.empty()) return;
-
- bool isVertical = (direction_ == StackDirection::Vertical);
- f32 mainAvailable = isVertical ? bounds.height : bounds.width;
-
- std::vector<Widget*> visibleChildren;
- std::vector<f32> flexWeights;
- f32 totalFixedSize = 0.0f;
- f32 totalFlexWeight = 0.0f;
-
- for (const auto& child : children) {
- if (!child->isVisible()) continue;
-
- visibleChildren.push_back(child.get());
-
- const SizeValue& mainSizeValue = isVertical ? child->getHeight()
- : child->getWidth();
- const auto& margin = child->getMargin();
- f32 marginMain = isVertical ? margin.totalVertical() : margin.totalHorizontal();
-
- if (mainSizeValue.isFlex()) {
- flexWeights.push_back(mainSizeValue.value);
- totalFlexWeight += mainSizeValue.value;
- totalFixedSize += marginMain;
- } else {
- flexWeights.push_back(0.0f);
-
- f32 childAvailW = isVertical ? bounds.width : mainAvailable;
- f32 childAvailH = isVertical ? mainAvailable : bounds.height;
- auto childSize = child->measure(childAvailW, childAvailH);
-
- f32 childMainSize = isVertical ? childSize.y : childSize.x;
- totalFixedSize += childMainSize + marginMain;
- }
- }
-
- if (visibleChildren.empty()) return;
-
- f32 totalSpacing = spacing_ * static_cast<f32>(visibleChildren.size() - 1);
- f32 flexSpace = mainAvailable - totalFixedSize - totalSpacing;
- if (flexSpace < 0.0f) flexSpace = 0.0f;
-
- std::vector<f32> childMainSizes;
- for (usize i = 0; i < visibleChildren.size(); ++i) {
- Widget* child = visibleChildren[i];
-
- if (flexWeights[i] > 0.0f && totalFlexWeight > 0.0f) {
- f32 flexPortion = (flexWeights[i] / totalFlexWeight) * flexSpace;
- childMainSizes.push_back(flexPortion);
- } else {
- f32 childAvailW = isVertical ? bounds.width : mainAvailable;
- f32 childAvailH = isVertical ? mainAvailable : bounds.height;
- auto childSize = child->measure(childAvailW, childAvailH);
- f32 childMainSize = isVertical ? childSize.y : childSize.x;
- childMainSizes.push_back(childMainSize);
- }
- }
-
- if (reverse_) {
- std::reverse(visibleChildren.begin(), visibleChildren.end());
- std::reverse(childMainSizes.begin(), childMainSizes.end());
- }
-
- f32 position = isVertical ? bounds.y : bounds.x;
-
- for (usize i = 0; i < visibleChildren.size(); ++i) {
- Widget* child = visibleChildren[i];
- f32 childMainSize = childMainSizes[i];
- const auto& margin = child->getMargin();
-
- f32 childAvailW = isVertical ? bounds.width : childMainSize;
- f32 childAvailH = isVertical ? childMainSize : bounds.height;
- auto childMeasured = child->measure(childAvailW, childAvailH);
- f32 childCrossSize = isVertical ? childMeasured.x : childMeasured.y;
-
- f32 crossStart = isVertical ? bounds.x : bounds.y;
- f32 crossAvail = isVertical ? bounds.width : bounds.height;
-
- f32 crossOffset = 0.0f;
- f32 crossFinal = childCrossSize;
-
- if (isVertical) {
- switch (crossHAlign_) {
- case HAlign::Left:
- crossOffset = margin.left;
- break;
- case HAlign::Center:
- crossOffset = (crossAvail - childCrossSize) * 0.5f;
- break;
- case HAlign::Right:
- crossOffset = crossAvail - childCrossSize - margin.right;
- break;
- case HAlign::Stretch:
- crossOffset = margin.left;
- crossFinal = crossAvail - margin.totalHorizontal();
- break;
- }
- } else {
- switch (crossVAlign_) {
- case VAlign::Top:
- crossOffset = margin.top;
- break;
- case VAlign::Center:
- crossOffset = (crossAvail - childCrossSize) * 0.5f;
- break;
- case VAlign::Bottom:
- crossOffset = crossAvail - childCrossSize - margin.bottom;
- break;
- case VAlign::Stretch:
- crossOffset = margin.top;
- crossFinal = crossAvail - margin.totalVertical();
- break;
- }
- }
-
- f32 mainOffset = isVertical ? margin.top : margin.left;
-
- Rect childBounds;
- if (isVertical) {
- childBounds = Rect(crossStart + crossOffset, position + mainOffset, crossFinal,
- childMainSize);
- } else {
- childBounds = Rect(position + mainOffset, crossStart + crossOffset, childMainSize,
- crossFinal);
- }
-
- child->layout(childBounds);
-
- f32 totalMainSize = childMainSize + (isVertical ? margin.totalVertical()
- : margin.totalHorizontal());
-
- position += totalMainSize + spacing_;
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/layout/StackLayout.hpp b/src/esengine/ui/layout/StackLayout.hpp
deleted file mode 100644
index 6bd455bd8..000000000
--- a/src/esengine/ui/layout/StackLayout.hpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * @file StackLayout.hpp
- * @brief Vertical and horizontal stack layout
- * @details Arranges children in a single row or column with configurable
- * spacing and alignment.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Layout.hpp"
-#include "SizeValue.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Stack Direction
-// =============================================================================
-
-/**
- * @brief Direction for stack layout
- */
-enum class StackDirection : u8 {
- Vertical,
- Horizontal
-};
-
-// =============================================================================
-// StackLayout Class
-// =============================================================================
-
-/**
- * @brief Arranges children in a stack (row or column)
- *
- * @details Children are laid out sequentially along the main axis with
- * configurable spacing, padding, and alignment.
- *
- * @code
- * auto panel = makeUnique<Panel>("panel");
- * panel->setLayout(makeUnique<StackLayout>(StackDirection::Vertical, 8.0f));
- * panel->addChild(makeUnique<Label>("label1", "First"));
- * panel->addChild(makeUnique<Label>("label2", "Second"));
- * @endcode
- */
-class StackLayout : public Layout {
-public:
- /**
- * @brief Creates a stack layout
- * @param direction Stack direction (Vertical or Horizontal)
- * @param spacing Space between children in pixels
- */
- explicit StackLayout(StackDirection direction = StackDirection::Vertical, f32 spacing = 0.0f);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Sets the stack direction */
- void setDirection(StackDirection direction) { direction_ = direction; }
-
- /** @brief Gets the stack direction */
- StackDirection getDirection() const { return direction_; }
-
- /** @brief Sets the spacing between children */
- void setSpacing(f32 spacing) { spacing_ = spacing; }
-
- /** @brief Gets the spacing between children */
- f32 getSpacing() const { return spacing_; }
-
- /** @brief Sets the cross-axis alignment */
- void setCrossAlignment(HAlign align) { crossHAlign_ = align; }
-
- /** @brief Sets the cross-axis alignment */
- void setCrossAlignment(VAlign align) { crossVAlign_ = align; }
-
- /** @brief Sets whether to reverse the order */
- void setReverse(bool reverse) { reverse_ = reverse; }
-
- // =========================================================================
- // Layout Interface
- // =========================================================================
-
- glm::vec2 measure(Widget& container, f32 availableWidth, f32 availableHeight) override;
- void layout(Widget& container, const Rect& bounds) override;
-
-private:
- StackDirection direction_ = StackDirection::Vertical;
- f32 spacing_ = 0.0f;
- HAlign crossHAlign_ = HAlign::Stretch;
- VAlign crossVAlign_ = VAlign::Stretch;
- bool reverse_ = false;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/layout/WrapLayout.cpp b/src/esengine/ui/layout/WrapLayout.cpp
deleted file mode 100644
index 621a7992f..000000000
--- a/src/esengine/ui/layout/WrapLayout.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * @file WrapLayout.cpp
- * @brief Wrap layout implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "WrapLayout.hpp"
-#include "../widgets/Widget.hpp"
-
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-WrapLayout::WrapLayout(f32 hSpacing, f32 vSpacing)
- : hSpacing_(hSpacing), vSpacing_(vSpacing) {}
-
-// =============================================================================
-// Measure
-// =============================================================================
-
-glm::vec2 WrapLayout::measure(Widget& container, f32 availableWidth, f32 availableHeight) {
- const auto& children = container.getChildren();
-
- f32 x = 0.0f;
- f32 y = 0.0f;
- f32 rowHeight = 0.0f;
- f32 maxWidth = 0.0f;
-
- f32 effectiveWidth = availableWidth;
- if (effectiveWidth > 10000.0f || effectiveWidth <= 0.0f) {
- effectiveWidth = 800.0f;
- }
-
- for (const auto& child : children) {
- if (!child->isVisible()) continue;
-
- auto childSize = child->measure(effectiveWidth, availableHeight);
-
- if (x + childSize.x > effectiveWidth && x > 0) {
- x = 0;
- y += rowHeight + vSpacing_;
- rowHeight = 0;
- }
-
- x += childSize.x + hSpacing_;
- rowHeight = std::max(rowHeight, childSize.y);
- maxWidth = std::max(maxWidth, x - hSpacing_);
- }
-
- f32 totalHeight = y + rowHeight;
- f32 totalWidth = maxWidth;
-
- return {totalWidth, totalHeight};
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-void WrapLayout::layout(Widget& container, const Rect& bounds) {
- const auto& children = container.getChildren();
-
- if (children.empty()) return;
-
- f32 startX = bounds.x;
- f32 startY = bounds.y;
- f32 contentWidth = bounds.width;
-
- f32 x = startX;
- f32 y = startY;
- f32 rowHeight = 0.0f;
-
- for (const auto& child : children) {
- if (!child->isVisible()) continue;
-
- auto childSize = child->measure(contentWidth, bounds.height);
-
- if (x - startX + childSize.x > contentWidth && x > startX) {
- x = startX;
- y += rowHeight + vSpacing_;
- rowHeight = 0;
- }
-
- child->layout(Rect{x, y, childSize.x, childSize.y});
-
- x += childSize.x + hSpacing_;
- rowHeight = std::max(rowHeight, childSize.y);
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/layout/WrapLayout.hpp b/src/esengine/ui/layout/WrapLayout.hpp
deleted file mode 100644
index 72de541b5..000000000
--- a/src/esengine/ui/layout/WrapLayout.hpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * @file WrapLayout.hpp
- * @brief Flow/wrap layout for grid-like arrangements
- * @details Arranges children in rows that wrap to the next line when
- * the container width is exceeded.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Layout.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// WrapLayout Class
-// =============================================================================
-
-/**
- * @brief Arranges children in a wrapping flow layout
- *
- * @details Children are laid out horizontally and wrap to the next row
- * when they exceed the container width. Useful for grid-like
- * displays such as asset browsers.
- *
- * @code
- * auto panel = makeUnique<Panel>("panel");
- * panel->setLayout(makeUnique<WrapLayout>(8.0f, 8.0f));
- * panel->addChild(makeUnique<AssetItem>("item1"));
- * panel->addChild(makeUnique<AssetItem>("item2"));
- * @endcode
- */
-class WrapLayout : public Layout {
-public:
- /**
- * @brief Creates a wrap layout
- * @param hSpacing Horizontal space between items in pixels
- * @param vSpacing Vertical space between rows in pixels
- */
- explicit WrapLayout(f32 hSpacing = 4.0f, f32 vSpacing = 4.0f);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Sets the horizontal spacing between items */
- void setHorizontalSpacing(f32 spacing) { hSpacing_ = spacing; }
-
- /** @brief Gets the horizontal spacing */
- f32 getHorizontalSpacing() const { return hSpacing_; }
-
- /** @brief Sets the vertical spacing between rows */
- void setVerticalSpacing(f32 spacing) { vSpacing_ = spacing; }
-
- /** @brief Gets the vertical spacing */
- f32 getVerticalSpacing() const { return vSpacing_; }
-
- // =========================================================================
- // Layout Interface
- // =========================================================================
-
- glm::vec2 measure(Widget& container, f32 availableWidth, f32 availableHeight) override;
- void layout(Widget& container, const Rect& bounds) override;
-
-private:
- f32 hSpacing_ = 4.0f;
- f32 vSpacing_ = 4.0f;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/rendering/UIBatchRenderer.cpp b/src/esengine/ui/rendering/UIBatchRenderer.cpp
deleted file mode 100644
index 00a91e17f..000000000
--- a/src/esengine/ui/rendering/UIBatchRenderer.cpp
+++ /dev/null
@@ -1,1323 +0,0 @@
-/**
- * @file UIBatchRenderer.cpp
- * @brief Batched UI rendering implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "UIBatchRenderer.hpp"
-#include "../../core/Log.hpp"
-#include "../../renderer/Buffer.hpp"
-#include "../../renderer/RenderCommand.hpp"
-#include "../../renderer/RenderContext.hpp"
-#include "../../renderer/Shader.hpp"
-#include "../layout/SizeValue.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/SDFFont.hpp"
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-#include <array>
-#include <cmath>
-#include <cstdio>
-#include <vector>
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
- #ifndef GL_VIEWPORT
- #define GL_VIEWPORT 0x0BA2
- #endif
-#endif
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constants
-// =============================================================================
-
-constexpr u32 MAX_QUADS = 5000;
-constexpr u32 MAX_VERTICES = MAX_QUADS * 4;
-constexpr u32 MAX_INDICES = MAX_QUADS * 6;
-constexpr u32 MAX_TEXTURE_SLOTS = 8;
-
-// =============================================================================
-// Vertex Structure
-// =============================================================================
-
-struct UIVertex {
- glm::vec3 position;
- glm::vec4 color;
- glm::vec2 texCoord;
- glm::vec4 cornerRadii;
- glm::vec2 rectSize;
- glm::vec2 localPos;
- f32 texIndex;
- f32 borderThickness;
-};
-
-
-// =============================================================================
-// Shader Sources
-// =============================================================================
-
-#ifdef ES_PLATFORM_WEB
-// WebGL 1.0 shaders (GLSL ES 1.0)
-static const char* UI_VERTEX_SHADER = R"(
- attribute vec3 a_position;
- attribute vec4 a_color;
- attribute vec2 a_texCoord;
- attribute vec4 a_cornerRadii;
- attribute vec2 a_rectSize;
- attribute vec2 a_localPos;
- attribute float a_texIndex;
- attribute float a_borderThickness;
-
- uniform mat4 u_projection;
-
- varying vec4 v_color;
- varying vec2 v_texCoord;
- varying vec4 v_cornerRadii;
- varying vec2 v_rectSize;
- varying vec2 v_localPos;
- varying float v_texIndex;
- varying float v_borderThickness;
-
- void main() {
- gl_Position = u_projection * vec4(a_position, 1.0);
- v_color = a_color;
- v_texCoord = a_texCoord;
- v_cornerRadii = a_cornerRadii;
- v_rectSize = a_rectSize;
- v_localPos = a_localPos;
- v_texIndex = a_texIndex;
- v_borderThickness = a_borderThickness;
- }
-)";
-
-static const char* UI_FRAGMENT_SHADER = R"(
- precision mediump float;
-
- varying vec4 v_color;
- varying vec2 v_texCoord;
- varying vec4 v_cornerRadii;
- varying vec2 v_rectSize;
- varying vec2 v_localPos;
- varying float v_texIndex;
- varying float v_borderThickness;
-
- uniform sampler2D u_textures[8];
-
- float sdRoundedBox(vec2 p, vec2 b, vec4 r) {
- r.xy = (p.x > 0.0) ? r.xy : r.wz;
- r.x = (p.y > 0.0) ? r.x : r.y;
- vec2 q = abs(p) - b + r.x;
- return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r.x;
- }
-
- float median(float r, float g, float b) {
- return max(min(r, g), min(max(r, g), b));
- }
-
- void main() {
- vec4 texColor = vec4(1.0);
- int index = int(v_texIndex);
-
- if (index == 0) texColor = texture2D(u_textures[0], v_texCoord);
- else if (index == 1) texColor = texture2D(u_textures[1], v_texCoord);
- else if (index == 2) texColor = texture2D(u_textures[2], v_texCoord);
- else if (index == 3) texColor = texture2D(u_textures[3], v_texCoord);
- else if (index == 4) texColor = texture2D(u_textures[4], v_texCoord);
- else if (index == 5) texColor = texture2D(u_textures[5], v_texCoord);
- else if (index == 6) texColor = texture2D(u_textures[6], v_texCoord);
- else if (index == 7) texColor = texture2D(u_textures[7], v_texCoord);
-
- vec4 color;
-
- // SystemFont rendering: borderThickness < -200.0 indicates SystemFont mode
- if (v_borderThickness < -200.0) {
- color = vec4(v_color.rgb, texColor.a * v_color.a);
- }
- // MSDF text rendering: borderThickness < -100.0 indicates MSDF mode
- else if (v_borderThickness < -100.0) {
- float screenPxRange = -v_borderThickness - 100.0 - 1.0;
- float sd = median(texColor.r, texColor.g, texColor.b);
- float edgeWidth = 0.5 / max(screenPxRange, 1.0);
- float alpha = smoothstep(0.5 - edgeWidth, 0.5 + edgeWidth, sd);
- color = vec4(v_color.rgb, alpha * v_color.a);
- }
- // SDF text rendering: borderThickness < -1.0 indicates SDF mode
- else if (v_borderThickness < -1.0) {
- float screenPxRange = -v_borderThickness - 1.0;
- float sd = texColor.r;
- float edgeWidth = 0.5 / max(screenPxRange, 1.0);
- float alpha = smoothstep(0.5 - edgeWidth, 0.5 + edgeWidth, sd);
- color = vec4(v_color.rgb, alpha * v_color.a);
- }
- // Bitmap font rendering
- else if (texColor.g == 0.0 && texColor.b == 0.0 && texColor.a == 1.0) {
- color = vec4(v_color.rgb, texColor.r * v_color.a);
- } else {
- color = texColor * v_color;
- }
-
- if (v_cornerRadii.x > 0.0 || v_cornerRadii.y > 0.0 ||
- v_cornerRadii.z > 0.0 || v_cornerRadii.w > 0.0) {
- vec2 halfSize = v_rectSize * 0.5;
- float dist = sdRoundedBox(v_localPos, halfSize, v_cornerRadii);
-
- float smoothing = 1.0;
- float alpha = 1.0 - smoothstep(-smoothing, smoothing, dist);
-
- if (v_borderThickness > 0.0) {
- float innerDist = dist + v_borderThickness;
- float innerAlpha = 1.0 - smoothstep(-smoothing, smoothing, innerDist);
- alpha = alpha - innerAlpha;
- }
-
- color.a *= alpha;
- }
-
- if (color.a < 0.01) discard;
-
- gl_FragColor = color;
- }
-)";
-
-#else
-// OpenGL 3.3 Core shaders
-static const char* UI_VERTEX_SHADER = R"(
- #version 330 core
-
- layout(location = 0) in vec3 a_position;
- layout(location = 1) in vec4 a_color;
- layout(location = 2) in vec2 a_texCoord;
- layout(location = 3) in vec4 a_cornerRadii;
- layout(location = 4) in vec2 a_rectSize;
- layout(location = 5) in vec2 a_localPos;
- layout(location = 6) in float a_texIndex;
- layout(location = 7) in float a_borderThickness;
-
- uniform mat4 u_projection;
-
- out vec4 v_color;
- out vec2 v_texCoord;
- out vec4 v_cornerRadii;
- out vec2 v_rectSize;
- out vec2 v_localPos;
- flat out int v_texIndex;
- out float v_borderThickness;
-
- void main() {
- gl_Position = u_projection * vec4(a_position, 1.0);
- v_color = a_color;
- v_texCoord = a_texCoord;
- v_cornerRadii = a_cornerRadii;
- v_rectSize = a_rectSize;
- v_localPos = a_localPos;
- v_texIndex = int(a_texIndex);
- v_borderThickness = a_borderThickness;
- }
-)";
-
-static const char* UI_FRAGMENT_SHADER = R"(
- #version 330 core
-
- in vec4 v_color;
- in vec2 v_texCoord;
- in vec4 v_cornerRadii;
- in vec2 v_rectSize;
- in vec2 v_localPos;
- flat in int v_texIndex;
- in float v_borderThickness;
-
- uniform sampler2D u_textures[8];
-
- out vec4 fragColor;
-
- float sdRoundedBox(vec2 p, vec2 b, vec4 r) {
- r.xy = (p.x > 0.0) ? r.xy : r.wz;
- r.x = (p.y > 0.0) ? r.x : r.y;
- vec2 q = abs(p) - b + r.x;
- return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r.x;
- }
-
- float median(float r, float g, float b) {
- return max(min(r, g), min(max(r, g), b));
- }
-
- void main() {
- vec4 texColor = texture(u_textures[v_texIndex], v_texCoord);
- vec4 color;
-
- // SystemFont rendering: borderThickness < -200.0 indicates SystemFont mode
- if (v_borderThickness < -200.0) {
- color = vec4(v_color.rgb, texColor.a * v_color.a);
- }
- // MSDF text rendering: borderThickness < -100.0 indicates MSDF mode
- else if (v_borderThickness < -100.0) {
- float screenPxRange = -v_borderThickness - 100.0 - 1.0;
- float sd = median(texColor.r, texColor.g, texColor.b);
- float edgeWidth = 0.5 / max(screenPxRange, 1.0);
- float alpha = smoothstep(0.5 - edgeWidth, 0.5 + edgeWidth, sd);
- color = vec4(v_color.rgb, alpha * v_color.a);
- }
- // SDF text rendering: borderThickness < -1.0 indicates SDF mode
- else if (v_borderThickness < -1.0) {
- float screenPxRange = -v_borderThickness - 1.0;
- float sd = texColor.r;
- float edgeWidth = 0.5 / max(screenPxRange, 1.0);
- float alpha = smoothstep(0.5 - edgeWidth, 0.5 + edgeWidth, sd);
- color = vec4(v_color.rgb, alpha * v_color.a);
- }
- // Bitmap font rendering (R8 texture)
- else if (texColor.g == 0.0 && texColor.b == 0.0 && texColor.a == 1.0) {
- color = vec4(v_color.rgb, texColor.r * v_color.a);
- } else {
- color = texColor * v_color;
- }
-
- if (v_cornerRadii.x > 0.0 || v_cornerRadii.y > 0.0 ||
- v_cornerRadii.z > 0.0 || v_cornerRadii.w > 0.0) {
- vec2 halfSize = v_rectSize * 0.5;
- float dist = sdRoundedBox(v_localPos, halfSize, v_cornerRadii);
-
- float smoothing = 1.0;
- float alpha = 1.0 - smoothstep(-smoothing, smoothing, dist);
-
- if (v_borderThickness > 0.0) {
- float innerDist = dist + v_borderThickness;
- float innerAlpha = 1.0 - smoothstep(-smoothing, smoothing, innerDist);
- alpha = alpha - innerAlpha;
- }
-
- color.a *= alpha;
- }
-
- if (color.a < 0.01) discard;
-
- fragColor = color;
- }
-)";
-#endif
-
-// =============================================================================
-// BatchData Implementation
-// =============================================================================
-
-struct UIBatchRenderer::BatchData {
- Unique<VertexArray> vao;
- Shared<VertexBuffer> vbo;
- Unique<Shader> shader;
-
- std::vector<UIVertex> vertices;
- u32 indexCount = 0;
-
- std::array<u32, MAX_TEXTURE_SLOTS> textureSlots{};
- u32 textureSlotIndex = 1;
-
- glm::mat4 projection{1.0f};
- f32 devicePixelRatio = 1.0f;
-
- std::vector<Rect> clipStack;
- Rect currentClip;
- bool clipEnabled = false;
-
- UIRenderStats stats;
- bool initialized = false;
- bool inFrame = false;
-};
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-UIBatchRenderer::UIBatchRenderer(RenderContext& context)
- : context_(context), data_(makeUnique<BatchData>()) {}
-
-UIBatchRenderer::~UIBatchRenderer() {
- if (data_ && data_->initialized) {
- shutdown();
- }
-}
-
-// =============================================================================
-// Lifecycle
-// =============================================================================
-
-void UIBatchRenderer::init() {
- if (data_->initialized) return;
-
- data_->vertices.reserve(MAX_VERTICES);
-
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- data_->vao = VertexArray::create();
-
- data_->vbo = makeShared<VertexBuffer>();
- *data_->vbo = std::move(*VertexBuffer::create(MAX_VERTICES * sizeof(UIVertex)));
- data_->vbo->setLayout({
- {ShaderDataType::Float3, "a_position"},
- {ShaderDataType::Float4, "a_color"},
- {ShaderDataType::Float2, "a_texCoord"},
- {ShaderDataType::Float4, "a_cornerRadii"},
- {ShaderDataType::Float2, "a_rectSize"},
- {ShaderDataType::Float2, "a_localPos"},
- {ShaderDataType::Float, "a_texIndex"},
- {ShaderDataType::Float, "a_borderThickness"}
- });
-
- data_->vao->addVertexBuffer(data_->vbo);
-
- std::vector<u32> indices(MAX_INDICES);
- u32 offset = 0;
- for (u32 i = 0; i < MAX_INDICES; i += 6) {
- indices[i + 0] = offset + 0;
- indices[i + 1] = offset + 1;
- indices[i + 2] = offset + 2;
- indices[i + 3] = offset + 2;
- indices[i + 4] = offset + 3;
- indices[i + 5] = offset + 0;
- offset += 4;
- }
- auto ibo = IndexBuffer::create(indices.data(), MAX_INDICES);
- data_->vao->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
-
- data_->shader = Shader::create(UI_VERTEX_SHADER, UI_FRAGMENT_SHADER);
- ES_LOG_DEBUG("UIBatchRenderer shader ID: {}", data_->shader ? data_->shader->getProgramId() : 0);
-
- data_->textureSlots[0] = context_.getWhiteTextureId();
- ES_LOG_DEBUG("UIBatchRenderer white texture ID: {}", data_->textureSlots[0]);
- for (u32 i = 1; i < MAX_TEXTURE_SLOTS; ++i) {
- data_->textureSlots[i] = 0;
- }
-#endif
-
- data_->initialized = true;
- ES_LOG_INFO("UIBatchRenderer initialized (max {} quads per batch)", MAX_QUADS);
-}
-
-void UIBatchRenderer::shutdown() {
- if (!data_ || !data_->initialized) return;
-
- data_->vao.reset();
- data_->vbo.reset();
- data_->shader.reset();
- data_->initialized = false;
-
- ES_LOG_INFO("UIBatchRenderer shutdown");
-}
-
-bool UIBatchRenderer::isInitialized() const {
- return data_ && data_->initialized;
-}
-
-// =============================================================================
-// Frame Management
-// =============================================================================
-
-void UIBatchRenderer::begin(const glm::mat4& projection, f32 devicePixelRatio) {
- data_->projection = projection;
- data_->devicePixelRatio = devicePixelRatio > 0.0f ? devicePixelRatio : 1.0f;
- data_->inFrame = true;
- data_->stats.reset();
-
- data_->vertices.clear();
- data_->indexCount = 0;
- data_->textureSlotIndex = 1;
-
- data_->clipStack.clear();
- data_->clipEnabled = false;
-
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- RenderCommand::setDepthTest(false);
- RenderCommand::setBlending(true);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-#endif
-}
-
-void UIBatchRenderer::end() {
- flush();
- data_->inFrame = false;
-
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- glDisable(GL_SCISSOR_TEST);
-#endif
-}
-
-void UIBatchRenderer::flush() {
- flushQuadBatch();
-}
-
-void UIBatchRenderer::flushQuadBatch() {
- if (data_->vertices.empty()) return;
-
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- data_->vbo->setDataRaw(data_->vertices.data(),
- static_cast<u32>(data_->vertices.size() * sizeof(UIVertex)));
-
- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
- glActiveTexture(GL_TEXTURE0 + i);
- glBindTexture(GL_TEXTURE_2D, data_->textureSlots[i]);
- }
-
- data_->shader->bind();
- data_->shader->setUniform("u_projection", data_->projection);
-
- i32 samplers[MAX_TEXTURE_SLOTS] = {0, 1, 2, 3, 4, 5, 6, 7};
- if (!data_->shader) {
- return;
- }
- GLint loc = glGetUniformLocation(data_->shader->getProgramId(), "u_textures");
- glUniform1iv(loc, MAX_TEXTURE_SLOTS, samplers);
-
- RenderCommand::drawIndexed(*data_->vao, data_->indexCount);
-
- data_->stats.drawCalls++;
-#endif
-
- data_->vertices.clear();
- data_->indexCount = 0;
- data_->textureSlotIndex = 1;
-}
-
-void UIBatchRenderer::flushTextBatch() {
- flushQuadBatch();
-}
-
-// =============================================================================
-// Clipping
-// =============================================================================
-
-void UIBatchRenderer::pushClipRect(const Rect& rect) {
- flush();
-
- Rect newClip = rect;
- if (!data_->clipStack.empty()) {
- newClip = data_->currentClip.intersect(rect);
- }
-
- data_->clipStack.push_back(rect);
- data_->currentClip = newClip;
- data_->clipEnabled = true;
- data_->stats.clipChanges++;
-
- applyScissor();
-}
-
-void UIBatchRenderer::popClipRect() {
- if (data_->clipStack.empty()) return;
-
- flush();
-
- data_->clipStack.pop_back();
- data_->stats.clipChanges++;
-
- if (data_->clipStack.empty()) {
- data_->clipEnabled = false;
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- glDisable(GL_SCISSOR_TEST);
-#endif
- } else {
- data_->currentClip = data_->clipStack[0];
- for (usize i = 1; i < data_->clipStack.size(); ++i) {
- data_->currentClip = data_->currentClip.intersect(data_->clipStack[i]);
- }
- applyScissor();
- }
-}
-
-Rect UIBatchRenderer::getCurrentClipRect() const {
- return data_->clipEnabled ? data_->currentClip : Rect();
-}
-
-void UIBatchRenderer::applyScissor() {
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- if (!data_->clipEnabled || data_->currentClip.isEmpty()) {
- glDisable(GL_SCISSOR_TEST);
- return;
- }
-
- glEnable(GL_SCISSOR_TEST);
-
- f32 dpr = data_->devicePixelRatio;
- i32 x = static_cast<i32>(data_->currentClip.x * dpr);
- i32 y = static_cast<i32>(data_->currentClip.y * dpr);
- i32 w = static_cast<i32>(data_->currentClip.width * dpr);
- i32 h = static_cast<i32>(data_->currentClip.height * dpr);
-
- GLint viewport[4];
- glGetIntegerv(GL_VIEWPORT, viewport);
- i32 viewportHeight = viewport[3];
-
- glScissor(x, viewportHeight - y - h, w, h);
-#endif
-}
-
-// =============================================================================
-// Primitive Drawing
-// =============================================================================
-
-void UIBatchRenderer::addQuadVertices(const Rect& rect, const glm::vec4& color,
- const glm::vec4& radii, f32 borderThickness,
- u32 textureIndex, const glm::vec2& uvMin,
- const glm::vec2& uvMax) {
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- f32 texIdx = static_cast<f32>(textureIndex);
- glm::vec2 rectSize = {rect.width, rect.height};
- glm::vec2 halfSize = rectSize * 0.5f;
-
- UIVertex vertices[4];
-
- vertices[0].position = {rect.x, rect.y, 0.0f};
- vertices[0].texCoord = uvMin;
- vertices[0].localPos = {-halfSize.x, -halfSize.y};
-
- vertices[1].position = {rect.right(), rect.y, 0.0f};
- vertices[1].texCoord = {uvMax.x, uvMin.y};
- vertices[1].localPos = {halfSize.x, -halfSize.y};
-
- vertices[2].position = {rect.right(), rect.bottom(), 0.0f};
- vertices[2].texCoord = uvMax;
- vertices[2].localPos = halfSize;
-
- vertices[3].position = {rect.x, rect.bottom(), 0.0f};
- vertices[3].texCoord = {uvMin.x, uvMax.y};
- vertices[3].localPos = {-halfSize.x, halfSize.y};
-
- for (auto& v : vertices) {
- v.color = color;
- v.cornerRadii = radii;
- v.rectSize = rectSize;
- v.texIndex = texIdx;
- v.borderThickness = borderThickness;
- data_->vertices.push_back(v);
- }
-
- data_->indexCount += 6;
- data_->stats.quadCount++;
-}
-
-void UIBatchRenderer::drawRect(const Rect& rect, const glm::vec4& color) {
- addQuadVertices(rect, color, {0, 0, 0, 0}, 0.0f, 0, {0, 0}, {1, 1});
-}
-
-void UIBatchRenderer::drawRoundedRect(const Rect& rect, const glm::vec4& color,
- const CornerRadii& radii) {
- addQuadVertices(rect, color, radii.toVec4(), 0.0f, 0, {0, 0}, {1, 1});
-}
-
-void UIBatchRenderer::drawRoundedRectOutline(const Rect& rect, const glm::vec4& color,
- const CornerRadii& radii, f32 thickness) {
- addQuadVertices(rect, color, radii.toVec4(), thickness, 0, {0, 0}, {1, 1});
-}
-
-void UIBatchRenderer::drawTexturedRect(const Rect& rect, u32 textureId, const glm::vec4& tint,
- const glm::vec2& uvMin, const glm::vec2& uvMax) {
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- u32 texIndex = 0;
- if (textureId != 0) {
- bool found = false;
- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
- if (data_->textureSlots[i] == textureId) {
- texIndex = i;
- found = true;
- break;
- }
- }
- if (!found) {
- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
- flush();
- }
- data_->textureSlots[data_->textureSlotIndex] = textureId;
- texIndex = data_->textureSlotIndex;
- data_->textureSlotIndex++;
- }
- }
-
- addQuadVertices(rect, tint, {0, 0, 0, 0}, 0.0f, texIndex, uvMin, uvMax);
-}
-
-void UIBatchRenderer::drawLine(const glm::vec2& p1, const glm::vec2& p2, const glm::vec4& color,
- f32 thickness) {
- glm::vec2 dir = p2 - p1;
- f32 length = glm::length(dir);
- if (length < 0.001f) return;
-
- dir /= length;
- glm::vec2 normal = {-dir.y, dir.x};
-
- glm::vec2 offset = normal * (thickness * 0.5f);
-
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- UIVertex vertices[4];
-
- vertices[0].position = {p1.x - offset.x, p1.y - offset.y, 0.0f};
- vertices[0].texCoord = {0, 0};
- vertices[0].localPos = {0, 0};
-
- vertices[1].position = {p1.x + offset.x, p1.y + offset.y, 0.0f};
- vertices[1].texCoord = {0, 1};
- vertices[1].localPos = {0, 0};
-
- vertices[2].position = {p2.x + offset.x, p2.y + offset.y, 0.0f};
- vertices[2].texCoord = {1, 1};
- vertices[2].localPos = {0, 0};
-
- vertices[3].position = {p2.x - offset.x, p2.y - offset.y, 0.0f};
- vertices[3].texCoord = {1, 0};
- vertices[3].localPos = {0, 0};
-
- for (auto& v : vertices) {
- v.color = color;
- v.cornerRadii = {0, 0, 0, 0};
- v.rectSize = {0, 0};
- v.texIndex = 0;
- v.borderThickness = 0;
- data_->vertices.push_back(v);
- }
-
- data_->indexCount += 6;
- data_->stats.quadCount++;
-}
-
-// =============================================================================
-// Text Drawing
-// =============================================================================
-
-namespace {
-
-u32 nextCodepoint(const std::string& text, usize& i) {
- u8 c = static_cast<u8>(text[i]);
- u32 codepoint = 0;
-
- if ((c & 0x80) == 0) {
- codepoint = c;
- i += 1;
- } else if ((c & 0xE0) == 0xC0) {
- codepoint = c & 0x1F;
- if (i + 1 < text.size()) {
- codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 1]) & 0x3F);
- }
- i += 2;
- } else if ((c & 0xF0) == 0xE0) {
- codepoint = c & 0x0F;
- if (i + 2 < text.size()) {
- codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 1]) & 0x3F);
- codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 2]) & 0x3F);
- }
- i += 3;
- } else if ((c & 0xF8) == 0xF0) {
- codepoint = c & 0x07;
- if (i + 3 < text.size()) {
- codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 1]) & 0x3F);
- codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 2]) & 0x3F);
- codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 3]) & 0x3F);
- }
- i += 4;
- } else {
- i += 1;
- }
- return codepoint;
-}
-
-} // namespace
-
-#if ES_FEATURE_SDF_FONT
-void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
- SDFFont& font, f32 fontSize, const glm::vec4& color) {
- if (text.empty()) return;
-
- f32 x = position.x;
- f32 y = position.y;
- f32 scale = fontSize / font.getSDFSize();
-
- u32 atlasTexture = font.getAtlasTextureId();
- if (atlasTexture == 0) return;
-
- u32 texIndex = 0;
- bool found = false;
- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
- if (data_->textureSlots[i] == atlasTexture) {
- texIndex = i;
- found = true;
- break;
- }
- }
- if (!found) {
- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
- flush();
- }
- data_->textureSlots[data_->textureSlotIndex] = atlasTexture;
- texIndex = data_->textureSlotIndex;
- data_->textureSlotIndex++;
- }
-
- f32 screenPxRange = fontSize / font.getSDFSize() * font.getSDFSpread();
- f32 sdfBorderFlag = -(screenPxRange + 1.0f);
-
- usize i = 0;
- while (i < text.size()) {
- u32 codepoint = nextCodepoint(text, i);
-
- if (codepoint == '\n') {
- x = position.x;
- y += fontSize * 1.2f;
- continue;
- }
-
- const auto* glyph = font.getGlyph(codepoint);
- if (!glyph) continue;
-
- f32 xPos = std::round(x + glyph->bearingX * scale);
- f32 yPos = std::round(y + (font.getAscent() - glyph->bearingY) * scale);
- f32 w = glyph->width * scale;
- f32 h = glyph->height * scale;
-
- if (w > 0 && h > 0) {
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- f32 texIdx = static_cast<f32>(texIndex);
- Rect glyphRect(xPos, yPos, w, h);
- glm::vec2 rectSize = {w, h};
- glm::vec2 halfSize = rectSize * 0.5f;
-
- UIVertex vertices[4];
-
- vertices[0].position = {glyphRect.x, glyphRect.y, 0.0f};
- vertices[0].texCoord = {glyph->u0, glyph->v0};
- vertices[0].localPos = {-halfSize.x, -halfSize.y};
-
- vertices[1].position = {glyphRect.right(), glyphRect.y, 0.0f};
- vertices[1].texCoord = {glyph->u1, glyph->v0};
- vertices[1].localPos = {halfSize.x, -halfSize.y};
-
- vertices[2].position = {glyphRect.right(), glyphRect.bottom(), 0.0f};
- vertices[2].texCoord = {glyph->u1, glyph->v1};
- vertices[2].localPos = halfSize;
-
- vertices[3].position = {glyphRect.x, glyphRect.bottom(), 0.0f};
- vertices[3].texCoord = {glyph->u0, glyph->v1};
- vertices[3].localPos = {-halfSize.x, halfSize.y};
-
- for (auto& v : vertices) {
- v.color = color;
- v.cornerRadii = {0, 0, 0, 0};
- v.rectSize = rectSize;
- v.texIndex = texIdx;
- v.borderThickness = sdfBorderFlag;
- data_->vertices.push_back(v);
- }
-
- data_->indexCount += 6;
- data_->stats.textQuadCount++;
- }
-
- x += glyph->advance * scale;
- }
-}
-
-void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds,
- SDFFont& font, f32 fontSize, const glm::vec4& color,
- HAlign hAlign, VAlign vAlign) {
- if (text.empty()) return;
-
- glm::vec2 textSize = font.measureText(text, fontSize);
- f32 scale = fontSize / font.getSDFSize();
- f32 ascent = font.getAscent() * scale;
- f32 descent = font.getDescent() * scale;
- f32 visualHeight = ascent + descent;
-
- f32 x = bounds.x;
- f32 y = bounds.y;
-
- switch (hAlign) {
- case HAlign::Left:
- break;
- case HAlign::Center:
- x += (bounds.width - textSize.x) * 0.5f;
- break;
- case HAlign::Right:
- x += bounds.width - textSize.x;
- break;
- case HAlign::Stretch:
- break;
- }
-
- switch (vAlign) {
- case VAlign::Top:
- break;
- case VAlign::Center:
- y += (bounds.height - visualHeight) * 0.5f;
- break;
- case VAlign::Bottom:
- y += bounds.height - visualHeight;
- break;
- case VAlign::Stretch:
- break;
- }
-
- x = std::round(x);
- y = std::round(y);
- drawText(text, {x, y}, font, fontSize, color);
-}
-
-void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
- MSDFFont& font, f32 fontSize, const glm::vec4& color) {
- if (text.empty()) return;
-
- f32 x = position.x;
- f32 y = position.y;
- f32 scale = fontSize / font.getFontSize();
-
- u32 atlasTexture = font.getAtlasTextureId();
- if (atlasTexture == 0) return;
-
- u32 texIndex = 0;
- bool found = false;
- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
- if (data_->textureSlots[i] == atlasTexture) {
- texIndex = i;
- found = true;
- break;
- }
- }
- if (!found) {
- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
- flush();
- }
- data_->textureSlots[data_->textureSlotIndex] = atlasTexture;
- texIndex = data_->textureSlotIndex;
- data_->textureSlotIndex++;
- }
-
- f32 screenPxRange = fontSize / font.getFontSize() * font.getPixelRange();
- f32 msdfBorderFlag = -(screenPxRange + 100.0f + 1.0f);
-
- usize i = 0;
- while (i < text.size()) {
- u32 codepoint = nextCodepoint(text, i);
-
- if (codepoint == '\n') {
- x = position.x;
- y += fontSize * 1.2f;
- continue;
- }
-
- const auto* glyph = font.getGlyph(codepoint);
- if (!glyph) continue;
-
- f32 xPos = std::round(x + glyph->bearingX * scale);
- f32 yPos = std::round(y + (font.getAscent() - glyph->bearingY) * scale);
- f32 w = glyph->width * scale;
- f32 h = glyph->height * scale;
-
- if (w > 0 && h > 0) {
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- f32 texIdx = static_cast<f32>(texIndex);
- Rect glyphRect(xPos, yPos, w, h);
- glm::vec2 rectSize = {w, h};
- glm::vec2 halfSize = rectSize * 0.5f;
-
- UIVertex vertices[4];
-
- vertices[0].position = {glyphRect.x, glyphRect.y, 0.0f};
- vertices[0].texCoord = {glyph->u0, glyph->v0};
- vertices[0].localPos = {-halfSize.x, -halfSize.y};
-
- vertices[1].position = {glyphRect.right(), glyphRect.y, 0.0f};
- vertices[1].texCoord = {glyph->u1, glyph->v0};
- vertices[1].localPos = {halfSize.x, -halfSize.y};
-
- vertices[2].position = {glyphRect.right(), glyphRect.bottom(), 0.0f};
- vertices[2].texCoord = {glyph->u1, glyph->v1};
- vertices[2].localPos = halfSize;
-
- vertices[3].position = {glyphRect.x, glyphRect.bottom(), 0.0f};
- vertices[3].texCoord = {glyph->u0, glyph->v1};
- vertices[3].localPos = {-halfSize.x, halfSize.y};
-
- for (auto& v : vertices) {
- v.color = color;
- v.cornerRadii = {0, 0, 0, 0};
- v.rectSize = rectSize;
- v.texIndex = texIdx;
- v.borderThickness = msdfBorderFlag;
- data_->vertices.push_back(v);
- }
-
- data_->indexCount += 6;
- data_->stats.textQuadCount++;
- }
-
- x += glyph->advance * scale;
- }
-}
-
-void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds,
- MSDFFont& font, f32 fontSize, const glm::vec4& color,
- HAlign hAlign, VAlign vAlign) {
- if (text.empty()) return;
-
- glm::vec2 textSize = font.measureText(text, fontSize);
- f32 scale = fontSize / font.getFontSize();
- f32 ascent = font.getAscent() * scale;
- f32 descent = font.getDescent() * scale;
- f32 visualHeight = ascent + descent;
-
- f32 x = bounds.x;
- f32 y = bounds.y;
-
- switch (hAlign) {
- case HAlign::Left:
- break;
- case HAlign::Center:
- x += (bounds.width - textSize.x) * 0.5f;
- break;
- case HAlign::Right:
- x += bounds.width - textSize.x;
- break;
- case HAlign::Stretch:
- break;
- }
-
- switch (vAlign) {
- case VAlign::Top:
- break;
- case VAlign::Center:
- y += (bounds.height - visualHeight) * 0.5f;
- break;
- case VAlign::Bottom:
- y += bounds.height - visualHeight;
- break;
- case VAlign::Stretch:
- break;
- }
-
- x = std::round(x);
- y = std::round(y);
- drawText(text, {x, y}, font, fontSize, color);
-}
-#endif // ES_FEATURE_SDF_FONT
-
-#if ES_FEATURE_BITMAP_FONT
-void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
- BitmapFont& font, f32 fontSize, const glm::vec4& color) {
- if (text.empty()) return;
-
- f32 x = position.x;
- f32 y = position.y;
- f32 scale = fontSize / font.getFontSize();
-
- u32 atlasTexture = font.getTextureId();
- if (atlasTexture == 0) return;
-
- u32 texIndex = 0;
- bool found = false;
- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
- if (data_->textureSlots[i] == atlasTexture) {
- texIndex = i;
- found = true;
- break;
- }
- }
- if (!found) {
- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
- flush();
- }
- data_->textureSlots[data_->textureSlotIndex] = atlasTexture;
- texIndex = data_->textureSlotIndex;
- data_->textureSlotIndex++;
- }
-
- usize i = 0;
- while (i < text.size()) {
- u32 codepoint = nextCodepoint(text, i);
-
- if (codepoint == '\n') {
- x = position.x;
- y += fontSize * 1.2f;
- continue;
- }
-
- const auto* glyph = font.getGlyph(codepoint);
- if (!glyph) continue;
-
- f32 xPos = std::round(x + glyph->bearingX * scale);
- f32 yPos = std::round(y + (font.getAscent() - glyph->bearingY) * scale);
- f32 w = glyph->width * scale;
- f32 h = glyph->height * scale;
-
- if (w > 0 && h > 0) {
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- f32 texIdx = static_cast<f32>(texIndex);
- Rect glyphRect(xPos, yPos, w, h);
- glm::vec2 rectSize = {w, h};
- glm::vec2 halfSize = rectSize * 0.5f;
-
- UIVertex vertices[4];
-
- vertices[0].position = {glyphRect.x, glyphRect.y, 0.0f};
- vertices[0].texCoord = {glyph->u0, glyph->v0};
- vertices[0].localPos = {-halfSize.x, -halfSize.y};
-
- vertices[1].position = {glyphRect.right(), glyphRect.y, 0.0f};
- vertices[1].texCoord = {glyph->u1, glyph->v0};
- vertices[1].localPos = {halfSize.x, -halfSize.y};
-
- vertices[2].position = {glyphRect.right(), glyphRect.bottom(), 0.0f};
- vertices[2].texCoord = {glyph->u1, glyph->v1};
- vertices[2].localPos = halfSize;
-
- vertices[3].position = {glyphRect.x, glyphRect.bottom(), 0.0f};
- vertices[3].texCoord = {glyph->u0, glyph->v1};
- vertices[3].localPos = {-halfSize.x, halfSize.y};
-
- for (auto& v : vertices) {
- v.color = color;
- v.cornerRadii = {0, 0, 0, 0};
- v.rectSize = rectSize;
- v.texIndex = texIdx;
- v.borderThickness = 0.0f; // Bitmap font uses regular texture sampling
- data_->vertices.push_back(v);
- }
-
- data_->indexCount += 6;
- data_->stats.textQuadCount++;
- }
-
- x += glyph->advance * scale;
- }
-}
-
-void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds,
- BitmapFont& font, f32 fontSize, const glm::vec4& color,
- HAlign hAlign, VAlign vAlign) {
- if (text.empty()) return;
-
- glm::vec2 textSize = font.measureText(text, fontSize);
- f32 scale = fontSize / font.getFontSize();
- f32 ascent = font.getAscent() * scale;
- f32 descent = font.getDescent() * scale;
- f32 visualHeight = ascent + descent;
-
- f32 x = bounds.x;
- f32 y = bounds.y;
-
- switch (hAlign) {
- case HAlign::Left:
- break;
- case HAlign::Center:
- x += (bounds.width - textSize.x) * 0.5f;
- break;
- case HAlign::Right:
- x += bounds.width - textSize.x;
- break;
- case HAlign::Stretch:
- break;
- }
-
- switch (vAlign) {
- case VAlign::Top:
- break;
- case VAlign::Center:
- y += (bounds.height - visualHeight) * 0.5f;
- break;
- case VAlign::Bottom:
- y += bounds.height - visualHeight;
- break;
- case VAlign::Stretch:
- break;
- }
-
- x = std::round(x);
- y = std::round(y);
- drawText(text, {x, y}, font, fontSize, color);
-}
-#endif // ES_FEATURE_BITMAP_FONT
-
-// =============================================================================
-// SystemFont Text Drawing
-// =============================================================================
-
-void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
- SystemFont& font, f32 fontSize, const glm::vec4& color) {
- if (text.empty()) return;
-
- f32 x = position.x;
- f32 y = position.y;
- f32 scale = fontSize / font.getFontSize();
-
- u32 atlasTexture = font.getTextureId();
- if (atlasTexture == 0) return;
-
- u32 texIndex = 0;
- bool found = false;
- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
- if (data_->textureSlots[i] == atlasTexture) {
- texIndex = i;
- found = true;
- break;
- }
- }
- if (!found) {
- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
- flush();
- }
- data_->textureSlots[data_->textureSlotIndex] = atlasTexture;
- texIndex = data_->textureSlotIndex;
- data_->textureSlotIndex++;
- }
-
- usize i = 0;
- while (i < text.size()) {
- u32 codepoint = nextCodepoint(text, i);
-
- if (codepoint == '\n') {
- x = position.x;
- y += fontSize * 1.2f;
- continue;
- }
-
- const auto* glyph = font.getGlyph(codepoint);
- if (!glyph) continue;
-
- f32 xPos = std::round(x + glyph->bearingX * scale);
- f32 yPos = std::round(y + (font.getAscent() - glyph->bearingY) * scale);
- f32 w = glyph->width * scale;
- f32 h = glyph->height * scale;
-
- if (w > 0 && h > 0) {
- if (data_->vertices.size() >= MAX_VERTICES) {
- flush();
- }
-
- f32 texIdx = static_cast<f32>(texIndex);
- Rect glyphRect(xPos, yPos, w, h);
- glm::vec2 rectSize = {w, h};
- glm::vec2 halfSize = rectSize * 0.5f;
-
- UIVertex vertices[4];
-
- vertices[0].position = {glyphRect.x, glyphRect.y, 0.0f};
- vertices[0].texCoord = {glyph->u0, glyph->v0};
- vertices[0].localPos = {-halfSize.x, -halfSize.y};
-
- vertices[1].position = {glyphRect.right(), glyphRect.y, 0.0f};
- vertices[1].texCoord = {glyph->u1, glyph->v0};
- vertices[1].localPos = {halfSize.x, -halfSize.y};
-
- vertices[2].position = {glyphRect.right(), glyphRect.bottom(), 0.0f};
- vertices[2].texCoord = {glyph->u1, glyph->v1};
- vertices[2].localPos = halfSize;
-
- vertices[3].position = {glyphRect.x, glyphRect.bottom(), 0.0f};
- vertices[3].texCoord = {glyph->u0, glyph->v1};
- vertices[3].localPos = {-halfSize.x, halfSize.y};
-
- for (auto& v : vertices) {
- v.color = color;
- v.cornerRadii = {0, 0, 0, 0};
- v.rectSize = rectSize;
- v.texIndex = texIdx;
- v.borderThickness = -300.0f; // SystemFont mode marker
- data_->vertices.push_back(v);
- }
-
- data_->indexCount += 6;
- data_->stats.textQuadCount++;
- }
-
- x += glyph->advance * scale;
- }
-}
-
-void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds,
- SystemFont& font, f32 fontSize, const glm::vec4& color,
- HAlign hAlign, VAlign vAlign) {
- if (text.empty()) return;
-
- glm::vec2 textSize = font.measureText(text, fontSize);
- f32 scale = fontSize / font.getFontSize();
- f32 ascent = font.getAscent() * scale;
- f32 descent = font.getDescent() * scale;
- f32 visualHeight = ascent + descent;
-
- f32 x = bounds.x;
- f32 y = bounds.y;
-
- switch (hAlign) {
- case HAlign::Left:
- break;
- case HAlign::Center:
- x += (bounds.width - textSize.x) * 0.5f;
- break;
- case HAlign::Right:
- x += bounds.width - textSize.x;
- break;
- case HAlign::Stretch:
- break;
- }
-
- switch (vAlign) {
- case VAlign::Top:
- break;
- case VAlign::Center:
- y += (bounds.height - visualHeight) * 0.5f;
- break;
- case VAlign::Bottom:
- y += bounds.height - visualHeight;
- break;
- case VAlign::Stretch:
- break;
- }
-
- x = std::round(x);
- y = std::round(y);
- drawText(text, {x, y}, font, fontSize, color);
-}
-
-// =============================================================================
-// Statistics
-// =============================================================================
-
-const UIRenderStats& UIBatchRenderer::getStats() const {
- return data_->stats;
-}
-
-void UIBatchRenderer::resetStats() {
- data_->stats.reset();
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/rendering/UIBatchRenderer.hpp b/src/esengine/ui/rendering/UIBatchRenderer.hpp
deleted file mode 100644
index 05034de2e..000000000
--- a/src/esengine/ui/rendering/UIBatchRenderer.hpp
+++ /dev/null
@@ -1,289 +0,0 @@
-/**
- * @file UIBatchRenderer.hpp
- * @brief Batched UI rendering with SDF primitives
- * @details Provides efficient batched rendering of UI elements including
- * rounded rectangles, text, and textured quads with scissor support.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-#include "../core/Types.hpp"
-#include "../layout/SizeValue.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-#include <vector>
-
-namespace esengine {
-
-class RenderContext;
-
-namespace ui {
-
-#if ES_FEATURE_SDF_FONT
-class SDFFont;
-class MSDFFont;
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-class BitmapFont;
-#endif
-
-class SystemFont;
-
-#if ES_FEATURE_SDF_FONT
-using Font = SDFFont;
-#elif ES_FEATURE_BITMAP_FONT
-using Font = BitmapFont;
-#endif
-
-// =============================================================================
-// UI Render Statistics
-// =============================================================================
-
-/**
- * @brief Statistics for UI rendering performance analysis
- */
-struct UIRenderStats {
- u32 drawCalls = 0;
- u32 quadCount = 0;
- u32 textQuadCount = 0;
- u32 clipChanges = 0;
-
- void reset() {
- drawCalls = 0;
- quadCount = 0;
- textQuadCount = 0;
- clipChanges = 0;
- }
-};
-
-// =============================================================================
-// UIBatchRenderer Class
-// =============================================================================
-
-/**
- * @brief High-performance batched UI renderer
- *
- * @details Renders UI primitives efficiently using batching and SDF techniques
- * for smooth rounded rectangles. Supports scissor-based clipping for
- * nested UI elements.
- *
- * @code
- * UIBatchRenderer renderer(context);
- * renderer.init();
- *
- * renderer.begin(projection);
- * renderer.pushClipRect(panelBounds);
- * renderer.drawRoundedRect(buttonBounds, buttonColor, CornerRadii::all(4.0f));
- * renderer.drawText("Click Me", textPos, font, 14.0f, textColor);
- * renderer.popClipRect();
- * renderer.end();
- * @endcode
- */
-class UIBatchRenderer {
-public:
- explicit UIBatchRenderer(RenderContext& context);
- ~UIBatchRenderer();
-
- // Non-copyable
- UIBatchRenderer(const UIBatchRenderer&) = delete;
- UIBatchRenderer& operator=(const UIBatchRenderer&) = delete;
-
- // =========================================================================
- // Lifecycle
- // =========================================================================
-
- /**
- * @brief Initializes rendering resources
- */
- void init();
-
- /**
- * @brief Releases rendering resources
- */
- void shutdown();
-
- /**
- * @brief Checks if initialized
- */
- bool isInitialized() const;
-
- // =========================================================================
- // Frame Management
- // =========================================================================
-
- /**
- * @brief Begins a UI rendering frame
- * @param projection Orthographic projection matrix
- * @param devicePixelRatio Scale factor for high-DPI displays (default 1.0)
- */
- void begin(const glm::mat4& projection, f32 devicePixelRatio = 1.0f);
-
- /**
- * @brief Ends the UI rendering frame and flushes all batches
- */
- void end();
-
- /**
- * @brief Flushes the current batch to the GPU
- */
- void flush();
-
- // =========================================================================
- // Clipping
- // =========================================================================
-
- /**
- * @brief Pushes a clip rectangle onto the stack
- * @param rect The clip region (intersected with current clip)
- */
- void pushClipRect(const Rect& rect);
-
- /**
- * @brief Pops the top clip rectangle from the stack
- */
- void popClipRect();
-
- /**
- * @brief Gets the current clip rectangle
- * @return Current clip rect (empty if no clipping)
- */
- Rect getCurrentClipRect() const;
-
- // =========================================================================
- // Primitive Drawing
- // =========================================================================
-
- /**
- * @brief Draws a solid rectangle
- * @param rect Rectangle bounds
- * @param color Fill color (RGBA)
- */
- void drawRect(const Rect& rect, const glm::vec4& color);
-
- /**
- * @brief Draws a rounded rectangle
- * @param rect Rectangle bounds
- * @param color Fill color (RGBA)
- * @param radii Corner radii
- */
- void drawRoundedRect(const Rect& rect, const glm::vec4& color, const CornerRadii& radii);
-
- /**
- * @brief Draws a rounded rectangle outline
- * @param rect Rectangle bounds
- * @param color Stroke color (RGBA)
- * @param radii Corner radii
- * @param thickness Border thickness in pixels
- */
- void drawRoundedRectOutline(const Rect& rect, const glm::vec4& color, const CornerRadii& radii,
- f32 thickness);
-
- /**
- * @brief Draws a textured rectangle
- * @param rect Rectangle bounds
- * @param textureId GPU texture handle
- * @param tint Tint color (default white)
- * @param uvMin UV coordinates for top-left (default 0,0)
- * @param uvMax UV coordinates for bottom-right (default 1,1)
- */
- void drawTexturedRect(const Rect& rect, u32 textureId, const glm::vec4& tint = {1, 1, 1, 1},
- const glm::vec2& uvMin = {0, 0}, const glm::vec2& uvMax = {1, 1});
-
- /**
- * @brief Draws a line between two points
- * @param p1 Start point
- * @param p2 End point
- * @param color Line color
- * @param thickness Line thickness
- */
- void drawLine(const glm::vec2& p1, const glm::vec2& p2, const glm::vec4& color,
- f32 thickness = 1.0f);
-
- // =========================================================================
- // Text Drawing
- // =========================================================================
-
-#if ES_FEATURE_SDF_FONT
- /**
- * @brief Draws text using SDF font (UTF-8 supported)
- */
- void drawText(const std::string& text, const glm::vec2& position, SDFFont& font, f32 fontSize,
- const glm::vec4& color);
-
- void drawTextInBounds(const std::string& text, const Rect& bounds, SDFFont& font, f32 fontSize,
- const glm::vec4& color, HAlign hAlign = HAlign::Left,
- VAlign vAlign = VAlign::Top);
-
- /**
- * @brief Draws text using MSDF font for sharper rendering (UTF-8 supported)
- */
- void drawText(const std::string& text, const glm::vec2& position, MSDFFont& font, f32 fontSize,
- const glm::vec4& color);
-
- void drawTextInBounds(const std::string& text, const Rect& bounds, MSDFFont& font, f32 fontSize,
- const glm::vec4& color, HAlign hAlign = HAlign::Left,
- VAlign vAlign = VAlign::Top);
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
- /**
- * @brief Draws text using bitmap font (UTF-8 supported)
- */
- void drawText(const std::string& text, const glm::vec2& position, BitmapFont& font, f32 fontSize,
- const glm::vec4& color);
-
- void drawTextInBounds(const std::string& text, const Rect& bounds, BitmapFont& font, f32 fontSize,
- const glm::vec4& color, HAlign hAlign = HAlign::Left,
- VAlign vAlign = VAlign::Top);
-#endif
-
- void drawText(const std::string& text, const glm::vec2& position, SystemFont& font, f32 fontSize,
- const glm::vec4& color);
-
- void drawTextInBounds(const std::string& text, const Rect& bounds, SystemFont& font, f32 fontSize,
- const glm::vec4& color, HAlign hAlign = HAlign::Left,
- VAlign vAlign = VAlign::Top);
-
- // =========================================================================
- // Statistics
- // =========================================================================
-
- /**
- * @brief Gets rendering statistics for the current frame
- */
- const UIRenderStats& getStats() const;
-
- /**
- * @brief Resets statistics counters
- */
- void resetStats();
-
-private:
- struct BatchData;
-
- void flushQuadBatch();
- void flushTextBatch();
- void applyScissor();
- void addQuadVertices(const Rect& rect, const glm::vec4& color, const glm::vec4& radii,
- f32 borderThickness, u32 textureIndex, const glm::vec2& uvMin,
- const glm::vec2& uvMax);
-
- RenderContext& context_;
- Unique<BatchData> data_;
-};
-
-} // namespace ui
-} // namespace esengine
diff --git a/src/esengine/ui/text/TextMeasureHelper.cpp b/src/esengine/ui/text/TextMeasureHelper.cpp
deleted file mode 100644
index 08dcee39e..000000000
--- a/src/esengine/ui/text/TextMeasureHelper.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * @file TextMeasureHelper.cpp
- * @brief TextMeasureHelper implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "TextMeasureHelper.hpp"
-#include "../UIContext.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Font Resolution
-// =============================================================================
-
-#if ES_FEATURE_SDF_FONT
-MSDFFont* TextMeasureHelper::resolveFont(UIContext* ctx, const std::string& fontName,
- bool useIconFont) {
- if (!ctx) return nullptr;
-
- if (!fontName.empty()) {
- return ctx->getMSDFFont(fontName);
- }
-
- if (useIconFont) {
- return ctx->getIconMSDFFont();
- }
-
- return ctx->getDefaultMSDFFont();
-}
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-BitmapFont* TextMeasureHelper::resolveBitmapFont(UIContext* ctx, const std::string& fontName) {
- if (!ctx) return nullptr;
-
- if (!fontName.empty()) {
- return ctx->getBitmapFont(fontName);
- }
-
- return ctx->getDefaultBitmapFont();
-}
-#endif
-
-// =============================================================================
-// Icon Detection
-// =============================================================================
-
-bool TextMeasureHelper::isIconText(const std::string& text) {
- if (text.empty()) return false;
-
- u8 firstByte = static_cast<u8>(text[0]);
- if ((firstByte & 0xF0) == 0xE0 && text.size() >= 3) {
- u32 codepoint = ((firstByte & 0x0F) << 12) |
- ((static_cast<u8>(text[1]) & 0x3F) << 6) |
- (static_cast<u8>(text[2]) & 0x3F);
- return (codepoint >= 0xE000 && codepoint <= 0xF8FF);
- }
- return false;
-}
-
-// =============================================================================
-// Text Measurement
-// =============================================================================
-
-glm::vec2 TextMeasureHelper::measureText(UIContext* ctx, const std::string& text, f32 fontSize,
- const std::string& fontName, bool useIconFont) {
- if (!ctx || text.empty()) return {0.0f, 0.0f};
-
-#if ES_FEATURE_SDF_FONT
- bool isIcon = useIconFont || (fontName.empty() && isIconText(text));
- MSDFFont* font = resolveFont(ctx, fontName, isIcon);
- if (font) {
- return font->measureText(text, fontSize);
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = resolveBitmapFont(ctx, fontName);
- if (font) {
- return font->measureText(text, fontSize);
- }
-#else
- bool isIcon = useIconFont || (fontName.empty() && isIconText(text));
- SystemFont* font = nullptr;
- if (!fontName.empty()) {
- font = ctx->getSystemFont(fontName);
- } else if (isIcon) {
- font = ctx->getIconSystemFont();
- } else {
- font = ctx->getDefaultSystemFont();
- }
- if (font) {
- return font->measureText(text, fontSize);
- }
-#endif
-
- return {0.0f, 0.0f};
-}
-
-glm::vec2 TextMeasureHelper::measureTextCached(UIContext* ctx, const std::string& text,
- f32 fontSize, MeasureCache& cache,
- const std::string& fontName, bool useIconFont) {
- if (cache.isValid(text, fontSize)) {
- return cache.cachedSize;
- }
-
- glm::vec2 size = measureText(ctx, text, fontSize, fontName, useIconFont);
- cache.update(text, fontSize, size);
- return size;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/text/TextMeasureHelper.hpp b/src/esengine/ui/text/TextMeasureHelper.hpp
deleted file mode 100644
index 2d89c586d..000000000
--- a/src/esengine/ui/text/TextMeasureHelper.hpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * @file TextMeasureHelper.hpp
- * @brief Helper utilities for text measurement and font resolution
- * @details Provides centralized text measurement with caching and font
- * resolution logic for UI widgets.
- *
- * @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/vec2.hpp>
-
-#include <string>
-
-namespace esengine::ui {
-
-class UIContext;
-
-#if ES_FEATURE_SDF_FONT
-class MSDFFont;
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-class BitmapFont;
-#endif
-
-// =============================================================================
-// TextMeasureHelper
-// =============================================================================
-
-/**
- * @brief Helper for text measurement and font resolution
- */
-class TextMeasureHelper {
-public:
- /**
- * @brief Resolves the appropriate font from the context
- * @param ctx UI context
- * @param fontName Optional font name (empty for default)
- * @param useIconFont Whether to use icon font
- * @return Font pointer or nullptr if not found
- */
-#if ES_FEATURE_SDF_FONT
- static MSDFFont* resolveFont(UIContext* ctx, const std::string& fontName = "",
- bool useIconFont = false);
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
- static BitmapFont* resolveBitmapFont(UIContext* ctx, const std::string& fontName = "");
-#endif
-
- /**
- * @brief Checks if text starts with an icon codepoint (Private Use Area)
- * @param text Text to check
- * @return true if text starts with an icon character
- */
- static bool isIconText(const std::string& text);
-
- /**
- * @brief Measures text size using the appropriate font
- * @param ctx UI context
- * @param text Text to measure
- * @param fontSize Font size
- * @param fontName Optional font name
- * @param useIconFont Whether to use icon font
- * @return Measured text size
- */
- static glm::vec2 measureText(UIContext* ctx, const std::string& text, f32 fontSize,
- const std::string& fontName = "", bool useIconFont = false);
-
- /**
- * @brief Cache for text measurement
- */
- struct MeasureCache {
- std::string cachedText;
- f32 cachedFontSize = 0.0f;
- glm::vec2 cachedSize{0.0f};
- bool dirty = true;
-
- void invalidate() { dirty = true; }
-
- bool isValid(const std::string& text, f32 fontSize) const {
- return !dirty && cachedText == text && cachedFontSize == fontSize;
- }
-
- void update(const std::string& text, f32 fontSize, glm::vec2 size) {
- cachedText = text;
- cachedFontSize = fontSize;
- cachedSize = size;
- dirty = false;
- }
- };
-
- /**
- * @brief Measures text with caching support
- * @param ctx UI context
- * @param text Text to measure
- * @param fontSize Font size
- * @param cache Cache to use/update
- * @param fontName Optional font name
- * @param useIconFont Whether to use icon font
- * @return Measured text size
- */
- static glm::vec2 measureTextCached(UIContext* ctx, const std::string& text, f32 fontSize,
- MeasureCache& cache, const std::string& fontName = "",
- bool useIconFont = false);
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Button.cpp b/src/esengine/ui/widgets/Button.cpp
deleted file mode 100644
index 1d16e44b2..000000000
--- a/src/esengine/ui/widgets/Button.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-/**
- * @file Button.cpp
- * @brief Button widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Button.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Button::Button(const WidgetId& id, const std::string& text)
- : Widget(id), text_(text) {}
-
-// =============================================================================
-// Text
-// =============================================================================
-
-void Button::setText(const std::string& text) {
- if (text_ != text) {
- text_ = text;
- textSizeDirty_ = true;
- invalidateLayout();
- }
-}
-
-// =============================================================================
-// State
-// =============================================================================
-
-void Button::onStateChanged() {
- Widget::onStateChanged();
-}
-
-// =============================================================================
-// Measurement
-// =============================================================================
-
-glm::vec2 Button::measure(f32 availableWidth, f32 availableHeight) {
- UIContext* ctx = getContext();
- if (!ctx) {
- return Widget::measure(availableWidth, availableHeight);
- }
-
- WidgetStyle style = (buttonStyle_ == ButtonStyle::Primary)
- ? ctx->getTheme().getPrimaryButtonStyle()
- : ctx->getTheme().getButtonStyle();
-
- if (textSizeDirty_) {
- bool isIcon = false;
- if (!text_.empty()) {
- u8 firstByte = static_cast<u8>(text_[0]);
- if ((firstByte & 0xF0) == 0xE0 && text_.size() >= 3) {
- u32 codepoint = ((firstByte & 0x0F) << 12) |
- ((static_cast<u8>(text_[1]) & 0x3F) << 6) |
- (static_cast<u8>(text_[2]) & 0x3F);
- isIcon = (codepoint >= 0xE000 && codepoint <= 0xF8FF);
- }
- }
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = nullptr;
- if (!fontName_.empty()) {
- font = ctx->getMSDFFont(fontName_);
- } else if (isIcon) {
- font = ctx->getMSDFFont("icons");
- } else {
- font = ctx->getDefaultMSDFFont();
- }
- if (font) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = fontName_.empty() ? ctx->getDefaultBitmapFont() : ctx->getBitmapFont(fontName_);
- if (font) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
- }
-#else
- SystemFont* font = nullptr;
- if (!fontName_.empty()) {
- font = ctx->getSystemFont(fontName_);
- } else if (isIcon) {
- font = ctx->getSystemFont("icons");
- } else {
- font = ctx->getDefaultSystemFont();
- }
- if (font) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
- }
-#endif
- }
-
- f32 contentWidth = cachedTextSize_.x + style.padding.totalHorizontal() +
- getPadding().totalHorizontal();
- f32 contentHeight = cachedTextSize_.y + style.padding.totalVertical() +
- getPadding().totalVertical();
-
- contentHeight = (contentHeight < 32.0f) ? 32.0f : contentHeight;
-
- f32 width = getWidth().resolve(availableWidth, contentWidth);
- f32 height = getHeight().resolve(availableHeight, contentHeight);
-
- width = getConstraints().constrainWidth(width);
- height = getConstraints().constrainHeight(height);
-
- return {width, height};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void Button::render(UIBatchRenderer& renderer) {
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- WidgetStyle style = (buttonStyle_ == ButtonStyle::Primary)
- ? ctx->getTheme().getPrimaryButtonStyle()
- : ctx->getTheme().getButtonStyle();
-
- const Rect& bounds = getBounds();
- const WidgetState& state = getState();
-
- glm::vec4 bgColor;
- glm::vec4 textColor;
-
- if (useCustomColors_) {
- if (state.pressed && customPressedColor_.a > 0.0f) {
- bgColor = customPressedColor_;
- } else if (state.hovered && customHoverColor_.a > 0.0f) {
- bgColor = customHoverColor_;
- } else {
- bgColor = customBgColor_;
- }
- textColor = customTextColor_;
- } else {
- bgColor = style.getBackgroundColor(state);
- textColor = style.getTextColor(state);
- }
-
- CornerRadii radii = cornerRadii_.isZero() ? style.cornerRadii : cornerRadii_;
-
- bool drawBackground = true;
- if (!useCustomColors_) {
- if (buttonStyle_ == ButtonStyle::Text) {
- drawBackground = false;
- } else if (buttonStyle_ == ButtonStyle::Ghost) {
- drawBackground = state.hovered || state.pressed;
- if (drawBackground) {
- bgColor = ctx->getTheme().colors.buttonHover;
- }
- }
- } else {
- drawBackground = (bgColor.a > 0.0f);
- }
-
- if (drawBackground) {
- if (radii.isZero()) {
- renderer.drawRect(bounds, bgColor);
- } else {
- renderer.drawRoundedRect(bounds, bgColor, radii);
- }
- }
-
- if (state.focused && buttonStyle_ != ButtonStyle::Text && buttonStyle_ != ButtonStyle::Ghost) {
- glm::vec4 focusColor = ctx->getTheme().colors.accent;
- focusColor.a = 0.3f;
- renderer.drawRoundedRectOutline(bounds, focusColor, radii, 2.0f);
- }
-
- if (!text_.empty()) {
- Rect textBounds = style.padding.shrink(bounds);
-
- bool isIcon = false;
- if (!text_.empty()) {
- u8 firstByte = static_cast<u8>(text_[0]);
- if ((firstByte & 0xF0) == 0xE0 && text_.size() >= 3) {
- u32 codepoint = ((firstByte & 0x0F) << 12) |
- ((static_cast<u8>(text_[1]) & 0x3F) << 6) |
- (static_cast<u8>(text_[2]) & 0x3F);
- isIcon = (codepoint >= 0xE000 && codepoint <= 0xF8FF);
- }
- }
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = nullptr;
- if (!fontName_.empty()) {
- font = ctx->getMSDFFont(fontName_);
- } else if (isIcon) {
- font = ctx->getMSDFFont("icons");
- } else {
- font = ctx->getDefaultMSDFFont();
- }
- if (font) {
- renderer.drawTextInBounds(text_, textBounds, *font, fontSize_, textColor,
- textAlign_, VAlign::Center);
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = fontName_.empty() ? ctx->getDefaultBitmapFont() : ctx->getBitmapFont(fontName_);
- if (font) {
- renderer.drawTextInBounds(text_, textBounds, *font, fontSize_, textColor,
- textAlign_, VAlign::Center);
- }
-#else
- SystemFont* font = nullptr;
- if (!fontName_.empty()) {
- font = ctx->getSystemFont(fontName_);
- } else if (isIcon) {
- font = ctx->getSystemFont("icons");
- } else {
- font = ctx->getDefaultSystemFont();
- }
- if (font) {
- renderer.drawTextInBounds(text_, textBounds, *font, fontSize_, textColor,
- textAlign_, VAlign::Center);
- }
-#endif
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool Button::onMouseDown(const MouseButtonEvent& event) {
- if (event.button == MouseButton::Left && getState().isInteractive()) {
- setState(true, true);
- return true;
- }
- return false;
-}
-
-bool Button::onMouseUp(const MouseButtonEvent& event) {
- if (event.button == MouseButton::Left && getState().pressed) {
- bool wasPressed = getState().pressed;
- setState(getState().hovered, false);
-
- if (wasPressed && containsPoint(event.x, event.y)) {
- onClick.publish();
- }
- return true;
- }
- return false;
-}
-
-bool Button::onMouseEnter(const MouseEnterEvent& event) {
- (void)event;
- if (getState().isInteractive()) {
- setState(true, getState().pressed);
- return true;
- }
- return false;
-}
-
-bool Button::onMouseLeave(const MouseLeaveEvent& event) {
- (void)event;
- setState(false, getState().pressed);
- return true;
-}
-
-bool Button::onKeyDown(const KeyEvent& event) {
- if ((event.key == KeyCode::Space || event.key == KeyCode::Enter) &&
- getState().focused && getState().isInteractive()) {
- onClick.publish();
- return true;
- }
- return false;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Button.hpp b/src/esengine/ui/widgets/Button.hpp
deleted file mode 100644
index 8f6517cdd..000000000
--- a/src/esengine/ui/widgets/Button.hpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/**
- * @file Button.hpp
- * @brief Clickable button widget
- * @details A button widget that responds to mouse/touch input and
- * triggers an onClick callback.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <functional>
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Button Style
-// =============================================================================
-
-/**
- * @brief Visual style variant for buttons
- */
-enum class ButtonStyle : u8 {
- Default,
- Primary,
- Secondary,
- Text,
- Ghost
-};
-
-// =============================================================================
-// Button Class
-// =============================================================================
-
-/**
- * @brief Clickable button widget
- *
- * @details Renders a button with text and responds to mouse/touch
- * interactions. Emits a signal when clicked.
- *
- * @code
- * auto button = makeUnique<Button>(WidgetId("submit"), "Submit");
- * button->onClick.connect([]() {
- * ES_LOG_INFO("Button clicked!");
- * });
- * @endcode
- */
-class Button : public Widget {
-public:
- /**
- * @brief Creates a button with text
- * @param id Widget identifier
- * @param text Button label text
- */
- Button(const WidgetId& id, const std::string& text = "");
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /** @brief Signal emitted when the button is clicked */
- Signal<void()> onClick;
-
- // =========================================================================
- // Text
- // =========================================================================
-
- /** @brief Sets the button label text */
- void setText(const std::string& text);
-
- /** @brief Gets the button label text */
- const std::string& getText() const { return text_; }
-
- // =========================================================================
- // Appearance
- // =========================================================================
-
- /** @brief Sets the button style variant */
- void setButtonStyle(ButtonStyle style) { buttonStyle_ = style; }
-
- /** @brief Gets the button style variant */
- ButtonStyle getButtonStyle() const { return buttonStyle_; }
-
- /** @brief Sets the font size in pixels */
- void setFontSize(f32 size) { fontSize_ = size; invalidateLayout(); }
-
- /** @brief Gets the font size */
- f32 getFontSize() const { return fontSize_; }
-
- /** @brief Sets the font name */
- void setFontName(const std::string& name) { fontName_ = name; }
-
- /** @brief Gets the font name */
- const std::string& getFontName() const { return fontName_; }
-
- /** @brief Sets the corner radii */
- void setCornerRadii(const CornerRadii& radii) { cornerRadii_ = radii; }
-
- /** @brief Gets the corner radii */
- const CornerRadii& getCornerRadii() const { return cornerRadii_; }
-
- /** @brief Sets the text horizontal alignment */
- void setTextAlignment(HAlign align) { textAlign_ = align; }
-
- /** @brief Gets the text horizontal alignment */
- HAlign getTextAlignment() const { return textAlign_; }
-
- /** @brief Sets custom background color (overrides style) */
- void setBackgroundColor(const glm::vec4& color) {
- customBgColor_ = color;
- useCustomColors_ = true;
- }
-
- /** @brief Sets custom hover color (overrides style) */
- void setHoverColor(const glm::vec4& color) {
- customHoverColor_ = color;
- useCustomColors_ = true;
- }
-
- /** @brief Sets custom pressed color (overrides style) */
- void setPressedColor(const glm::vec4& color) {
- customPressedColor_ = color;
- useCustomColors_ = true;
- }
-
- /** @brief Sets custom text color (overrides style) */
- void setTextColor(const glm::vec4& color) {
- customTextColor_ = color;
- useCustomColors_ = true;
- }
-
- /** @brief Clears custom colors and uses theme styles */
- void clearCustomColors() { useCustomColors_ = false; }
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- bool isFocusable() const override { return true; }
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
- bool onMouseEnter(const MouseEnterEvent& event) override;
- bool onMouseLeave(const MouseLeaveEvent& event) override;
- bool onKeyDown(const KeyEvent& event) override;
-
-protected:
- void onStateChanged() override;
-
-private:
- std::string text_;
- std::string fontName_;
- f32 fontSize_ = 14.0f;
- ButtonStyle buttonStyle_ = ButtonStyle::Default;
- CornerRadii cornerRadii_;
- HAlign textAlign_ = HAlign::Center;
-
- bool useCustomColors_ = false;
- glm::vec4 customBgColor_{0.0f};
- glm::vec4 customHoverColor_{0.0f};
- glm::vec4 customPressedColor_{0.0f};
- glm::vec4 customTextColor_{1.0f};
-
- glm::vec2 cachedTextSize_{0.0f};
- bool textSizeDirty_ = true;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Checkbox.cpp b/src/esengine/ui/widgets/Checkbox.cpp
deleted file mode 100644
index 7a95944d0..000000000
--- a/src/esengine/ui/widgets/Checkbox.cpp
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * @file Checkbox.cpp
- * @brief Checkbox widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Checkbox.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../../math/Math.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Checkbox::Checkbox(const WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// State Management
-// =============================================================================
-
-void Checkbox::setChecked(bool checked) {
- if (checked_ == checked) {
- return;
- }
-
- checked_ = checked;
- onChanged.publish(checked_);
-}
-
-void Checkbox::toggle() {
- setChecked(!checked_);
-}
-
-// =============================================================================
-// Label
-// =============================================================================
-
-void Checkbox::setLabel(const std::string& label) {
- if (label_ == label) {
- return;
- }
-
- label_ = label;
- invalidateLayout();
-}
-
-// =============================================================================
-// Appearance
-// =============================================================================
-
-void Checkbox::setCheckboxSize(f32 size) {
- if (checkboxSize_ == size) {
- return;
- }
-
- checkboxSize_ = size;
- invalidateLayout();
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 Checkbox::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- f32 width = checkboxSize_;
- f32 height = checkboxSize_;
-
- if (!label_.empty() && getContext()) {
- f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
- f32 labelWidth = static_cast<f32>(label_.length()) * fontSize * 0.6f;
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = getContext()->getDefaultMSDFFont();
- if (font) {
- labelWidth = font->measureText(label_, fontSize).x;
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = getContext()->getDefaultBitmapFont();
- if (font) {
- labelWidth = font->measureText(label_, fontSize).x;
- }
-#else
- SystemFont* font = getContext()->getDefaultSystemFont();
- if (font) {
- labelWidth = font->measureText(label_, fontSize).x;
- }
-#endif
-
- width += LABEL_SPACING + labelWidth;
- height = glm::max(height, fontSize);
- }
-
- const SizeConstraints& constraints = getConstraints();
- width = glm::clamp(width, constraints.minWidth, constraints.maxWidth);
- height = glm::clamp(height, constraints.minHeight, constraints.maxHeight);
-
- return glm::vec2(width, height);
-}
-
-void Checkbox::render(UIBatchRenderer& renderer) {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- WidgetStyle style;
- if (getContext()) {
- style = getContext()->getTheme().getButtonStyle();
- }
-
- WidgetState state{
- .hovered = isHovered(),
- .pressed = isPressed(),
- .focused = false,
- .disabled = !isEnabled(),
- .visible = true
- };
-
- f32 checkboxX = bounds.x + padding.left;
- f32 checkboxY = bounds.y + (bounds.height - checkboxSize_) * 0.5f;
-
- Rect checkboxBounds{checkboxX, checkboxY, checkboxSize_, checkboxSize_};
-
- glm::vec4 bgColor = checked_ ? style.getBackgroundColor(state) : glm::vec4(0.12f, 0.12f, 0.12f, 1.0f);
- glm::vec4 borderColor = state.hovered ? glm::vec4(0.4f, 0.4f, 0.4f, 1.0f) : glm::vec4(0.3f, 0.3f, 0.3f, 1.0f);
-
- if (getContext()) {
- if (checked_) {
- bgColor = getContext()->getTheme().colors.accent;
- } else {
- bgColor = getContext()->getTheme().colors.input;
- }
- borderColor = state.hovered
- ? getContext()->getTheme().colors.inputBorderFocused
- : getContext()->getTheme().colors.inputBorder;
- }
-
- CornerRadii radii = CornerRadii::all(4.0f);
- renderer.drawRoundedRect(checkboxBounds, bgColor, radii);
- renderer.drawRoundedRectOutline(checkboxBounds, borderColor, radii, 1.0f);
-
- if (checked_) {
- glm::vec4 checkColor = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
- if (getContext()) {
- checkColor = getContext()->getTheme().colors.textPrimary;
- }
-
- f32 checkSize = checkboxSize_ * 0.6f;
- f32 checkX = checkboxX + (checkboxSize_ - checkSize) * 0.5f;
- f32 checkY = checkboxY + (checkboxSize_ - checkSize) * 0.5f;
-
- f32 x1 = checkX + checkSize * 0.2f;
- f32 y1 = checkY + checkSize * 0.5f;
- f32 x2 = checkX + checkSize * 0.45f;
- f32 y2 = checkY + checkSize * 0.8f;
- f32 x3 = checkX + checkSize * 0.9f;
- f32 y3 = checkY + checkSize * 0.2f;
-
- renderer.drawLine(glm::vec2(x1, y1), glm::vec2(x2, y2), checkColor, 2.0f);
- renderer.drawLine(glm::vec2(x2, y2), glm::vec2(x3, y3), checkColor, 2.0f);
- }
-
- if (!label_.empty()) {
- f32 fontSize = 14.0f;
- glm::vec4 textColor = glm::vec4(0.95f, 0.95f, 0.95f, 1.0f);
-
- if (getContext()) {
- fontSize = getContext()->getTheme().typography.fontSizeNormal;
- textColor = state.disabled
- ? getContext()->getTheme().colors.textDisabled
- : getContext()->getTheme().colors.textPrimary;
- }
-
- f32 labelX = checkboxX + checkboxSize_ + LABEL_SPACING;
- f32 labelY = bounds.y + (bounds.height - fontSize) * 0.5f;
-
-#if ES_FEATURE_SDF_FONT
- if (getContext() && getContext()->getDefaultMSDFFont()) {
- renderer.drawText(label_, glm::vec2(labelX, labelY),
- *getContext()->getDefaultMSDFFont(), fontSize, textColor);
- }
-#elif ES_FEATURE_BITMAP_FONT
- if (getContext() && getContext()->getDefaultBitmapFont()) {
- renderer.drawText(label_, glm::vec2(labelX, labelY),
- *getContext()->getDefaultBitmapFont(), fontSize, textColor);
- }
-#else
- if (getContext() && getContext()->getDefaultSystemFont()) {
- renderer.drawText(label_, glm::vec2(labelX, labelY),
- *getContext()->getDefaultSystemFont(), fontSize, textColor);
- }
-#endif
- }
-}
-
-bool Checkbox::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- const Rect& bounds = getBounds();
- if (!bounds.contains(event.x, event.y)) {
- return false;
- }
-
- toggle();
- return true;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Checkbox.hpp b/src/esengine/ui/widgets/Checkbox.hpp
deleted file mode 100644
index 58d3cdb88..000000000
--- a/src/esengine/ui/widgets/Checkbox.hpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * @file Checkbox.hpp
- * @brief Checkbox widget for boolean input
- * @details Provides a clickable checkbox with optional label text.
- * Emits onChanged signal when the checked state toggles.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Checkbox Class
-// =============================================================================
-
-/**
- * @brief Checkbox widget for boolean selection
- *
- * @details Renders a checkbox with optional label. Clicking toggles the
- * checked state and emits the onChanged signal.
- *
- * @code
- * auto checkbox = makeUnique<Checkbox>(WidgetId("show_grid"));
- * checkbox->setLabel("Show Grid");
- * checkbox->setChecked(true);
- * checkbox->onChanged.connect([](bool checked) {
- * ES_LOG_INFO("Grid visibility: {}", checked);
- * });
- * @endcode
- */
-class Checkbox : public Widget {
-public:
- /**
- * @brief Constructs a checkbox widget
- * @param id Unique widget identifier
- */
- explicit Checkbox(const WidgetId& id);
-
- ~Checkbox() override = default;
-
- // =========================================================================
- // State Management
- // =========================================================================
-
- /**
- * @brief Sets the checked state
- * @param checked True to check, false to uncheck
- */
- void setChecked(bool checked);
-
- /**
- * @brief Gets the checked state
- * @return True if checked
- */
- bool isChecked() const { return checked_; }
-
- /**
- * @brief Toggles the checked state
- */
- void toggle();
-
- // =========================================================================
- // Label
- // =========================================================================
-
- /**
- * @brief Sets the label text
- * @param label Text to display next to checkbox
- */
- void setLabel(const std::string& label);
-
- /**
- * @brief Gets the label text
- * @return Current label text
- */
- const std::string& getLabel() const { return label_; }
-
- // =========================================================================
- // Appearance
- // =========================================================================
-
- /**
- * @brief Sets the checkbox size
- * @param size Size in pixels (default 16.0f)
- */
- void setCheckboxSize(f32 size);
-
- /**
- * @brief Gets the checkbox size
- * @return Checkbox size in pixels
- */
- f32 getCheckboxSize() const { return checkboxSize_; }
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(class UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const MouseButtonEvent& event) override;
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /**
- * @brief Emitted when the checked state changes
- * @param checked New checked state
- */
- Signal<void(bool)> onChanged;
-
-private:
- bool checked_ = false;
- std::string label_;
- f32 checkboxSize_ = 16.0f;
- static constexpr f32 LABEL_SPACING = 8.0f;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/ClickablePanel.cpp b/src/esengine/ui/widgets/ClickablePanel.cpp
deleted file mode 100644
index 3196978ef..000000000
--- a/src/esengine/ui/widgets/ClickablePanel.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * @file ClickablePanel.cpp
- * @brief ClickablePanel implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ClickablePanel.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-ClickablePanel::ClickablePanel(const WidgetId& id)
- : Panel(id) {
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool ClickablePanel::onMouseDown(const MouseButtonEvent& event) {
- onClick.publish(event);
- return true;
-}
-
-Widget* ClickablePanel::hitTest(f32 x, f32 y) {
- if (!getState().visible || getState().disabled) {
- return nullptr;
- }
-
- if (!containsPoint(x, y)) {
- return nullptr;
- }
-
- for (auto it = getChildren().rbegin(); it != getChildren().rend(); ++it) {
- if (auto* hit = (*it)->hitTest(x, y)) {
- if (hit->isFocusable()) {
- return hit;
- }
- }
- }
-
- return this;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/ClickablePanel.hpp b/src/esengine/ui/widgets/ClickablePanel.hpp
deleted file mode 100644
index b24acfa9b..000000000
--- a/src/esengine/ui/widgets/ClickablePanel.hpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * @file ClickablePanel.hpp
- * @brief Clickable panel widget
- * @details A panel that can respond to mouse click events.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Panel.hpp"
-#include "../../events/Signal.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// ClickablePanel Class
-// =============================================================================
-
-/**
- * @brief Panel that responds to mouse clicks
- *
- * @details Extends Panel with click handling capabilities and an onClick signal.
- */
-class ClickablePanel : public Panel {
-public:
- explicit ClickablePanel(const WidgetId& id);
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /** @brief Signal emitted when the panel is clicked */
- Signal<void(const MouseButtonEvent&)> onClick;
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- bool onMouseDown(const MouseButtonEvent& event) override;
- Widget* hitTest(f32 x, f32 y) override;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/ContextMenu.cpp b/src/esengine/ui/widgets/ContextMenu.cpp
deleted file mode 100644
index 658e85336..000000000
--- a/src/esengine/ui/widgets/ContextMenu.cpp
+++ /dev/null
@@ -1,417 +0,0 @@
-/**
- * @file ContextMenu.cpp
- * @brief Context menu widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ContextMenu.hpp"
-#include "../UIContext.hpp"
-#include "../icons/Icons.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../../math/Math.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-ContextMenu::ContextMenu(const WidgetId& id) : Widget(id) {
- setVisible(false);
-}
-
-// =============================================================================
-// Menu Items
-// =============================================================================
-
-void ContextMenu::addItem(const MenuItem& item) {
- items_.push_back(item);
- invalidateLayout();
-}
-
-void ContextMenu::addItems(const std::vector<MenuItem>& items) {
- items_.insert(items_.end(), items.begin(), items.end());
- invalidateLayout();
-}
-
-void ContextMenu::clearItems() {
- items_.clear();
- invalidateLayout();
-}
-
-// =============================================================================
-// Visibility
-// =============================================================================
-
-void ContextMenu::show(f32 x, f32 y) {
- menuX_ = x;
- menuY_ = y;
- isOpen_ = true;
- hoveredIndex_ = -1;
- setVisible(true);
- invalidateLayout();
-}
-
-void ContextMenu::hide() {
- if (isOpen_) {
- isOpen_ = false;
- setVisible(false);
- onClosed.publish();
- }
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 ContextMenu::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableWidth;
- (void)availableHeight;
-
- f32 width = MIN_WIDTH;
- f32 height = calculateMenuHeight();
-
-#if ES_FEATURE_SDF_FONT
- UIContext* ctx = getContext();
- MSDFFont* font = ctx ? ctx->getDefaultMSDFFont() : nullptr;
- if (font) {
- for (const auto& item : items_) {
- if (item.separator) continue;
-
- f32 textWidth = font->measureText(item.label, 13.0f).x;
- f32 shortcutWidth = item.shortcut.empty() ? 0.0f
- : font->measureText(item.shortcut, 12.0f).x + 32.0f;
- f32 itemWidth = PADDING_X * 2 + ICON_SIZE + 8.0f + textWidth + shortcutWidth + 8.0f;
- width = glm::max(width, itemWidth);
- }
- }
-#else
- UIContext* ctx = getContext();
- SystemFont* font = ctx ? ctx->getDefaultSystemFont() : nullptr;
- if (font) {
- for (const auto& item : items_) {
- if (item.separator) continue;
-
- f32 textWidth = font->measureText(item.label, 13.0f).x;
- f32 shortcutWidth = item.shortcut.empty() ? 0.0f
- : font->measureText(item.shortcut, 12.0f).x + 32.0f;
- f32 itemWidth = PADDING_X * 2 + ICON_SIZE + 8.0f + textWidth + shortcutWidth + 8.0f;
- width = glm::max(width, itemWidth);
- }
- }
-#endif
-
- return {width, height};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void ContextMenu::render(UIBatchRenderer& renderer) {
- if (!isOpen_) return;
-
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- constexpr glm::vec4 bgColor{0.188f, 0.188f, 0.188f, 1.0f}; // #303030
- constexpr glm::vec4 borderColor{0.275f, 0.275f, 0.275f, 1.0f}; // #464646
- constexpr glm::vec4 hoverBg{0.094f, 0.420f, 0.788f, 1.0f}; // #186cb9
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 disabledColor{0.5f, 0.5f, 0.5f, 1.0f};
- constexpr glm::vec4 shortcutColor{0.6f, 0.6f, 0.6f, 1.0f};
- constexpr glm::vec4 separatorColor{0.275f, 0.275f, 0.275f, 1.0f};
-
- glm::vec2 size = measure(0.0f, 0.0f);
-
- glm::vec2 viewportSize = ctx->getViewportSize();
- f32 x = menuX_;
- f32 y = menuY_;
-
- if (x + size.x > viewportSize.x) {
- x = viewportSize.x - size.x - 4.0f;
- }
- if (y + size.y > viewportSize.y) {
- y = viewportSize.y - size.y - 4.0f;
- }
-
- Rect menuBounds{x, y, size.x, size.y};
-
- renderer.drawRoundedRect(menuBounds, bgColor, CornerRadii::all(4.0f));
- renderer.drawRoundedRectOutline(menuBounds, borderColor, CornerRadii::all(4.0f), 1.0f);
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* textFont = ctx->getDefaultMSDFFont();
- MSDFFont* iconFont = ctx->getIconMSDFFont();
-
- if (!textFont) return;
-
- f32 itemY = y + PADDING_Y;
-
- for (usize i = 0; i < items_.size(); ++i) {
- const MenuItem& item = items_[i];
-
- if (item.separator) {
- f32 sepY = itemY + SEPARATOR_HEIGHT * 0.5f;
- Rect sepLine{x + 8.0f, sepY, size.x - 16.0f, 1.0f};
- renderer.drawRect(sepLine, separatorColor);
- itemY += SEPARATOR_HEIGHT;
- continue;
- }
-
- Rect itemBounds{x + 4.0f, itemY, size.x - 8.0f, ITEM_HEIGHT};
-
- bool isHovered = (static_cast<i32>(i) == hoveredIndex_) && item.enabled;
- if (isHovered) {
- renderer.drawRoundedRect(itemBounds, hoverBg, CornerRadii::all(3.0f));
- }
-
- glm::vec4 color = item.enabled ? textColor : disabledColor;
-
- f32 iconX = x + PADDING_X;
- if (iconFont && !item.icon.empty()) {
- Rect iconBounds{iconX, itemY + (ITEM_HEIGHT - ICON_SIZE) * 0.5f,
- ICON_SIZE, ICON_SIZE};
- renderer.drawTextInBounds(item.icon, iconBounds, *iconFont, 14.0f, color,
- HAlign::Center, VAlign::Center);
- }
-
- f32 textX = iconX + ICON_SIZE + 8.0f;
- f32 textY = itemY + (ITEM_HEIGHT - 13.0f) * 0.5f;
- renderer.drawText(item.label, {textX, textY}, *textFont, 13.0f, color);
-
- if (!item.shortcut.empty()) {
- f32 shortcutWidth = textFont->measureText(item.shortcut, 12.0f).x;
- f32 shortcutX = x + size.x - PADDING_X - shortcutWidth;
- f32 shortcutY = itemY + (ITEM_HEIGHT - 12.0f) * 0.5f;
- renderer.drawText(item.shortcut, {shortcutX, shortcutY}, *textFont, 12.0f, shortcutColor);
- }
-
- itemY += ITEM_HEIGHT;
- }
-#else
- SystemFont* textFont = ctx->getDefaultSystemFont();
- SystemFont* iconFont = ctx->getIconSystemFont();
-
- if (!textFont) return;
-
- f32 itemY = y + PADDING_Y;
-
- for (usize i = 0; i < items_.size(); ++i) {
- const MenuItem& item = items_[i];
-
- if (item.separator) {
- f32 sepY = itemY + SEPARATOR_HEIGHT * 0.5f;
- Rect sepLine{x + 8.0f, sepY, size.x - 16.0f, 1.0f};
- renderer.drawRect(sepLine, separatorColor);
- itemY += SEPARATOR_HEIGHT;
- continue;
- }
-
- Rect itemBounds{x + 4.0f, itemY, size.x - 8.0f, ITEM_HEIGHT};
-
- bool isHovered = (static_cast<i32>(i) == hoveredIndex_) && item.enabled;
- if (isHovered) {
- renderer.drawRoundedRect(itemBounds, hoverBg, CornerRadii::all(3.0f));
- }
-
- glm::vec4 color = item.enabled ? textColor : disabledColor;
-
- f32 iconX = x + PADDING_X;
- if (iconFont && !item.icon.empty()) {
- Rect iconBounds{iconX, itemY + (ITEM_HEIGHT - ICON_SIZE) * 0.5f,
- ICON_SIZE, ICON_SIZE};
- renderer.drawTextInBounds(item.icon, iconBounds, *iconFont, 14.0f, color,
- HAlign::Center, VAlign::Center);
- }
-
- f32 textX = iconX + ICON_SIZE + 8.0f;
- f32 textY = itemY + (ITEM_HEIGHT - 13.0f) * 0.5f;
- renderer.drawText(item.label, {textX, textY}, *textFont, 13.0f, color);
-
- if (!item.shortcut.empty()) {
- f32 shortcutWidth = textFont->measureText(item.shortcut, 12.0f).x;
- f32 shortcutX = x + size.x - PADDING_X - shortcutWidth;
- f32 shortcutY = itemY + (ITEM_HEIGHT - 12.0f) * 0.5f;
- renderer.drawText(item.shortcut, {shortcutX, shortcutY}, *textFont, 12.0f, shortcutColor);
- }
-
- itemY += ITEM_HEIGHT;
- }
-#endif
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool ContextMenu::onMouseDown(const MouseButtonEvent& event) {
- if (!isOpen_) return false;
-
- glm::vec2 size = measure(0.0f, 0.0f);
-
- UIContext* ctx = getContext();
- glm::vec2 viewportSize = ctx ? ctx->getViewportSize() : glm::vec2(9999.0f);
-
- f32 x = menuX_;
- f32 y = menuY_;
- if (x + size.x > viewportSize.x) {
- x = viewportSize.x - size.x - 4.0f;
- }
- if (y + size.y > viewportSize.y) {
- y = viewportSize.y - size.y - 4.0f;
- }
-
- Rect menuBounds{x, y, size.x, size.y};
-
- if (!menuBounds.contains(event.x, event.y)) {
- hide();
- return false;
- }
-
- if (event.button == MouseButton::Left && hoveredIndex_ >= 0) {
- selectItem(hoveredIndex_);
- return true;
- }
-
- return true;
-}
-
-bool ContextMenu::onMouseMove(const MouseMoveEvent& event) {
- if (!isOpen_) return false;
-
- glm::vec2 size = measure(0.0f, 0.0f);
-
- UIContext* ctx = getContext();
- glm::vec2 viewportSize = ctx ? ctx->getViewportSize() : glm::vec2(9999.0f);
-
- f32 x = menuX_;
- f32 y = menuY_;
- if (x + size.x > viewportSize.x) {
- x = viewportSize.x - size.x - 4.0f;
- }
- if (y + size.y > viewportSize.y) {
- y = viewportSize.y - size.y - 4.0f;
- }
-
- Rect menuBounds{x, y, size.x, size.y};
- if (menuBounds.contains(event.x, event.y)) {
- hoveredIndex_ = getItemAtY(event.y - y);
- } else {
- hoveredIndex_ = -1;
- }
-
- return false;
-}
-
-bool ContextMenu::onKeyDown(const KeyEvent& event) {
- if (!isOpen_) return false;
-
- if (event.key == KeyCode::Escape) {
- hide();
- return true;
- }
-
- if (event.key == KeyCode::Enter && hoveredIndex_ >= 0) {
- selectItem(hoveredIndex_);
- return true;
- }
-
- if (event.key == KeyCode::Up) {
- i32 start = hoveredIndex_ < 0 ? static_cast<i32>(items_.size()) : hoveredIndex_;
- for (i32 i = start - 1; i >= 0; --i) {
- if (!items_[i].separator && items_[i].enabled) {
- hoveredIndex_ = i;
- break;
- }
- }
- return true;
- }
-
- if (event.key == KeyCode::Down) {
- i32 start = hoveredIndex_;
- for (i32 i = start + 1; i < static_cast<i32>(items_.size()); ++i) {
- if (!items_[i].separator && items_[i].enabled) {
- hoveredIndex_ = i;
- break;
- }
- }
- return true;
- }
-
- return false;
-}
-
-Widget* ContextMenu::hitTest(f32 x, f32 y) {
- (void)x;
- (void)y;
-
- if (!isOpen_) return nullptr;
-
- return this;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-f32 ContextMenu::calculateMenuHeight() const {
- f32 height = PADDING_Y * 2;
-
- for (const auto& item : items_) {
- if (item.separator) {
- height += SEPARATOR_HEIGHT;
- } else {
- height += ITEM_HEIGHT;
- }
- }
-
- return height;
-}
-
-i32 ContextMenu::getItemAtY(f32 y) const {
- f32 itemY = PADDING_Y;
-
- for (usize i = 0; i < items_.size(); ++i) {
- const MenuItem& item = items_[i];
- f32 itemHeight = item.separator ? SEPARATOR_HEIGHT : ITEM_HEIGHT;
-
- if (y >= itemY && y < itemY + itemHeight) {
- if (item.separator || !item.enabled) {
- return -1;
- }
- return static_cast<i32>(i);
- }
-
- itemY += itemHeight;
- }
-
- return -1;
-}
-
-void ContextMenu::selectItem(i32 index) {
- if (index < 0 || index >= static_cast<i32>(items_.size())) {
- return;
- }
-
- const MenuItem& item = items_[index];
- if (item.separator || !item.enabled) {
- return;
- }
-
- hide();
- onItemSelected.publish(item.id);
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/ContextMenu.hpp b/src/esengine/ui/widgets/ContextMenu.hpp
deleted file mode 100644
index c765ce9a7..000000000
--- a/src/esengine/ui/widgets/ContextMenu.hpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/**
- * @file ContextMenu.hpp
- * @brief Context menu widget for right-click menus
- * @details A popup menu that displays a list of selectable items.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <functional>
-#include <string>
-#include <vector>
-
-namespace esengine::ui {
-
-// =============================================================================
-// MenuItem
-// =============================================================================
-
-struct MenuItem {
- std::string id;
- std::string label;
- std::string icon;
- std::string shortcut;
- bool enabled = true;
- bool separator = false;
- std::vector<MenuItem> submenu;
-
- static MenuItem action(const std::string& id, const std::string& label,
- const std::string& icon = "", const std::string& shortcut = "") {
- MenuItem item;
- item.id = id;
- item.label = label;
- item.icon = icon;
- item.shortcut = shortcut;
- return item;
- }
-
- static MenuItem divider() {
- MenuItem item;
- item.separator = true;
- return item;
- }
-};
-
-// =============================================================================
-// ContextMenu Class
-// =============================================================================
-
-/**
- * @brief Popup context menu widget
- *
- * @details Displays a list of menu items at a specific position.
- * Automatically closes when an item is selected or when
- * clicking outside the menu.
- *
- * @code
- * auto menu = makeUnique<ContextMenu>(WidgetId("context"));
- * menu->addItem(MenuItem::action("create", "Create Entity", icons::Plus));
- * menu->addItem(MenuItem::divider());
- * menu->addItem(MenuItem::action("delete", "Delete", icons::Trash));
- * menu->onItemSelected.connect([](const std::string& id) {
- * ES_LOG_INFO("Selected: {}", id);
- * });
- * menu->show(mouseX, mouseY);
- * @endcode
- */
-class ContextMenu : public Widget {
-public:
- static constexpr f32 ITEM_HEIGHT = 28.0f;
- static constexpr f32 SEPARATOR_HEIGHT = 9.0f;
- static constexpr f32 MIN_WIDTH = 180.0f;
- static constexpr f32 ICON_SIZE = 16.0f;
- static constexpr f32 PADDING_X = 8.0f;
- static constexpr f32 PADDING_Y = 4.0f;
-
- explicit ContextMenu(const WidgetId& id);
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- Signal<void(const std::string&)> onItemSelected;
- Signal<void()> onClosed;
-
- // =========================================================================
- // Menu Items
- // =========================================================================
-
- void addItem(const MenuItem& item);
- void addItems(const std::vector<MenuItem>& items);
- void clearItems();
-
- const std::vector<MenuItem>& getItems() const { return items_; }
-
- // =========================================================================
- // Visibility
- // =========================================================================
-
- void show(f32 x, f32 y);
- void hide();
- bool isOpen() const { return isOpen_; }
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
- bool onKeyDown(const KeyEvent& event) override;
-
- Widget* hitTest(f32 x, f32 y) override;
-
-private:
- f32 calculateMenuHeight() const;
- i32 getItemAtY(f32 y) const;
- void selectItem(i32 index);
-
- std::vector<MenuItem> items_;
- f32 menuX_ = 0.0f;
- f32 menuY_ = 0.0f;
- i32 hoveredIndex_ = -1;
- bool isOpen_ = false;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Dropdown.cpp b/src/esengine/ui/widgets/Dropdown.cpp
deleted file mode 100644
index 3a1730d69..000000000
--- a/src/esengine/ui/widgets/Dropdown.cpp
+++ /dev/null
@@ -1,506 +0,0 @@
-/**
- * @file Dropdown.cpp
- * @brief Dropdown widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Dropdown.hpp"
-#include "../UIContext.hpp"
-#include "../icons/Icons.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Dropdown::Dropdown(const WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// Items
-// =============================================================================
-
-void Dropdown::addItem(const DropdownItem& item) {
- items_.push_back(item);
- textSizeDirty_ = true;
- invalidateLayout();
-}
-
-void Dropdown::addItems(const std::vector<DropdownItem>& items) {
- items_.insert(items_.end(), items.begin(), items.end());
- textSizeDirty_ = true;
- invalidateLayout();
-}
-
-void Dropdown::clearItems() {
- items_.clear();
- selectedIndex_ = -1;
- textSizeDirty_ = true;
- invalidateLayout();
-}
-
-// =============================================================================
-// Selection
-// =============================================================================
-
-void Dropdown::setSelectedIndex(i32 index) {
- if (index < -1 || index >= static_cast<i32>(items_.size())) {
- return;
- }
-
- if (selectedIndex_ != index) {
- selectedIndex_ = index;
- textSizeDirty_ = true;
- invalidateLayout();
- }
-}
-
-void Dropdown::setSelectedValue(i32 value) {
- for (i32 i = 0; i < static_cast<i32>(items_.size()); ++i) {
- if (items_[i].value == value) {
- setSelectedIndex(i);
- return;
- }
- }
-}
-
-i32 Dropdown::getSelectedValue() const {
- if (selectedIndex_ >= 0 && selectedIndex_ < static_cast<i32>(items_.size())) {
- return items_[selectedIndex_].value;
- }
- return -1;
-}
-
-const DropdownItem* Dropdown::getSelectedItem() const {
- if (selectedIndex_ >= 0 && selectedIndex_ < static_cast<i32>(items_.size())) {
- return &items_[selectedIndex_];
- }
- return nullptr;
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 Dropdown::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- UIContext* ctx = getContext();
- if (!ctx) {
- return Widget::measure(availableWidth, availableHeight);
- }
-
- f32 maxTextWidth = 0.0f;
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = ctx->getDefaultMSDFFont();
- if (font) {
- for (const auto& item : items_) {
- f32 textWidth = font->measureText(item.label, fontSize_).x;
- maxTextWidth = glm::max(maxTextWidth, textWidth);
- }
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = ctx->getDefaultBitmapFont();
- if (font) {
- for (const auto& item : items_) {
- f32 textWidth = font->measureText(item.label, fontSize_).x;
- maxTextWidth = glm::max(maxTextWidth, textWidth);
- }
- }
-#else
- SystemFont* font = ctx->getDefaultSystemFont();
- if (font) {
- for (const auto& item : items_) {
- f32 textWidth = font->measureText(item.label, fontSize_).x;
- maxTextWidth = glm::max(maxTextWidth, textWidth);
- }
- }
-#endif
-
- f32 contentWidth = PADDING_X * 2 + maxTextWidth + ARROW_WIDTH;
- contentWidth = glm::max(contentWidth, MIN_WIDTH);
-
- f32 width = getWidth().resolve(availableWidth, contentWidth);
- f32 height = getHeight().resolve(availableHeight, 24.0f);
-
- width = getConstraints().constrainWidth(width);
- height = getConstraints().constrainHeight(height);
-
- return {width, height};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void Dropdown::render(UIBatchRenderer& renderer) {
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- const Rect& bounds = getBounds();
- const WidgetState& state = getState();
-
- constexpr glm::vec4 bgColor{0.165f, 0.165f, 0.165f, 1.0f}; // #2a2a2a
- constexpr glm::vec4 bgHoverColor{0.2f, 0.2f, 0.2f, 1.0f}; // #333333
- constexpr glm::vec4 borderColor{0.275f, 0.275f, 0.275f, 1.0f}; // #464646
- constexpr glm::vec4 textColor{0.878f, 0.878f, 0.878f, 1.0f}; // #e0e0e0
- constexpr glm::vec4 arrowColor{0.6f, 0.6f, 0.6f, 1.0f};
- constexpr glm::vec4 popupBgColor{0.188f, 0.188f, 0.188f, 1.0f}; // #303030
- constexpr glm::vec4 hoverBgColor{0.094f, 0.420f, 0.788f, 1.0f}; // #186cb9
-
- glm::vec4 currentBg = (state.hovered || isOpen_) ? bgHoverColor : bgColor;
- renderer.drawRoundedRect(bounds, currentBg, CornerRadii::all(3.0f));
- renderer.drawRoundedRectOutline(bounds, borderColor, CornerRadii::all(3.0f), 1.0f);
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* textFont = ctx->getDefaultMSDFFont();
- MSDFFont* iconFont = ctx->getIconMSDFFont();
-
- if (textFont) {
- const DropdownItem* selected = getSelectedItem();
- std::string displayText = selected ? selected->label : "";
-
- f32 textX = bounds.x + PADDING_X;
- f32 textY = bounds.y + (bounds.height - fontSize_) * 0.5f;
- renderer.drawText(displayText, {textX, textY}, *textFont, fontSize_, textColor);
- }
-
- if (iconFont) {
- f32 arrowX = bounds.x + bounds.width - ARROW_WIDTH;
- Rect arrowBounds{arrowX, bounds.y, ARROW_WIDTH, bounds.height};
- std::string arrowIcon = isOpen_ ? icons::ChevronUp : icons::ChevronDown;
- renderer.drawTextInBounds(arrowIcon, arrowBounds, *iconFont, 12.0f, arrowColor,
- HAlign::Center, VAlign::Center);
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* textFont = ctx->getDefaultBitmapFont();
-
- if (textFont) {
- const DropdownItem* selected = getSelectedItem();
- std::string displayText = selected ? selected->label : "";
-
- f32 textX = bounds.x + PADDING_X;
- f32 textY = bounds.y + (bounds.height - fontSize_) * 0.5f;
- renderer.drawText(displayText, {textX, textY}, *textFont, fontSize_, textColor);
- }
-#else
- SystemFont* textFont = ctx->getDefaultSystemFont();
- SystemFont* iconFont = ctx->getIconSystemFont();
-
- if (textFont) {
- const DropdownItem* selected = getSelectedItem();
- std::string displayText = selected ? selected->label : "";
-
- f32 textX = bounds.x + PADDING_X;
- f32 textY = bounds.y + (bounds.height - fontSize_) * 0.5f;
- renderer.drawText(displayText, {textX, textY}, *textFont, fontSize_, textColor);
- }
-
- if (iconFont) {
- f32 arrowX = bounds.x + bounds.width - ARROW_WIDTH;
- Rect arrowBounds{arrowX, bounds.y, ARROW_WIDTH, bounds.height};
- std::string arrowIcon = isOpen_ ? icons::ChevronUp : icons::ChevronDown;
- renderer.drawTextInBounds(arrowIcon, arrowBounds, *iconFont, 12.0f, arrowColor,
- HAlign::Center, VAlign::Center);
- }
-#endif
-
- if (isOpen_) {
- Rect popupBounds = getPopupBounds();
-
- renderer.drawRoundedRect(popupBounds, popupBgColor, CornerRadii::all(3.0f));
- renderer.drawRoundedRectOutline(popupBounds, borderColor, CornerRadii::all(3.0f), 1.0f);
-
-#if ES_FEATURE_SDF_FONT
- if (textFont) {
- f32 itemY = popupBounds.y + PADDING_Y;
-
- for (i32 i = 0; i < static_cast<i32>(items_.size()); ++i) {
- const DropdownItem& item = items_[i];
- Rect itemBounds{popupBounds.x + 4.0f, itemY, popupBounds.width - 8.0f, ITEM_HEIGHT};
-
- bool isHovered = (i == hoveredIndex_) && item.enabled;
- bool isSelected = (i == selectedIndex_);
-
- if (isHovered || isSelected) {
- glm::vec4 highlightColor = isHovered ? hoverBgColor : glm::vec4{0.25f, 0.25f, 0.25f, 1.0f};
- renderer.drawRoundedRect(itemBounds, highlightColor, CornerRadii::all(2.0f));
- }
-
- glm::vec4 itemTextColor = item.enabled ? textColor : glm::vec4{0.5f, 0.5f, 0.5f, 1.0f};
- f32 textX = popupBounds.x + PADDING_X;
- f32 textY = itemY + (ITEM_HEIGHT - fontSize_) * 0.5f;
- renderer.drawText(item.label, {textX, textY}, *textFont, fontSize_, itemTextColor);
-
- itemY += ITEM_HEIGHT;
- }
- }
-#elif ES_FEATURE_BITMAP_FONT
- if (textFont) {
- f32 itemY = popupBounds.y + PADDING_Y;
-
- for (i32 i = 0; i < static_cast<i32>(items_.size()); ++i) {
- const DropdownItem& item = items_[i];
- Rect itemBounds{popupBounds.x + 4.0f, itemY, popupBounds.width - 8.0f, ITEM_HEIGHT};
-
- bool isHovered = (i == hoveredIndex_) && item.enabled;
- bool isSelected = (i == selectedIndex_);
-
- if (isHovered || isSelected) {
- glm::vec4 highlightColor = isHovered ? hoverBgColor : glm::vec4{0.25f, 0.25f, 0.25f, 1.0f};
- renderer.drawRoundedRect(itemBounds, highlightColor, CornerRadii::all(2.0f));
- }
-
- glm::vec4 itemTextColor = item.enabled ? textColor : glm::vec4{0.5f, 0.5f, 0.5f, 1.0f};
- f32 textX = popupBounds.x + PADDING_X;
- f32 textY = itemY + (ITEM_HEIGHT - fontSize_) * 0.5f;
- renderer.drawText(item.label, {textX, textY}, *textFont, fontSize_, itemTextColor);
-
- itemY += ITEM_HEIGHT;
- }
- }
-#else
- if (textFont) {
- f32 itemY = popupBounds.y + PADDING_Y;
-
- for (i32 i = 0; i < static_cast<i32>(items_.size()); ++i) {
- const DropdownItem& item = items_[i];
- Rect itemBounds{popupBounds.x + 4.0f, itemY, popupBounds.width - 8.0f, ITEM_HEIGHT};
-
- bool isHovered = (i == hoveredIndex_) && item.enabled;
- bool isSelected = (i == selectedIndex_);
-
- if (isHovered || isSelected) {
- glm::vec4 highlightColor = isHovered ? hoverBgColor : glm::vec4{0.25f, 0.25f, 0.25f, 1.0f};
- renderer.drawRoundedRect(itemBounds, highlightColor, CornerRadii::all(2.0f));
- }
-
- glm::vec4 itemTextColor = item.enabled ? textColor : glm::vec4{0.5f, 0.5f, 0.5f, 1.0f};
- f32 textX = popupBounds.x + PADDING_X;
- f32 textY = itemY + (ITEM_HEIGHT - fontSize_) * 0.5f;
- renderer.drawText(item.label, {textX, textY}, *textFont, fontSize_, itemTextColor);
-
- itemY += ITEM_HEIGHT;
- }
- }
-#endif
- }
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool Dropdown::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- const Rect& bounds = getBounds();
-
- if (isOpen_) {
- Rect popupBounds = getPopupBounds();
- if (popupBounds.contains(event.x, event.y)) {
- if (hoveredIndex_ >= 0) {
- selectItem(hoveredIndex_);
- }
- return true;
- } else if (bounds.contains(event.x, event.y)) {
- closePopup();
- return true;
- } else {
- closePopup();
- return false;
- }
- }
-
- if (bounds.contains(event.x, event.y)) {
- openPopup();
- return true;
- }
-
- return false;
-}
-
-bool Dropdown::onMouseUp(const MouseButtonEvent& event) {
- (void)event;
- return false;
-}
-
-bool Dropdown::onMouseEnter(const MouseEnterEvent& event) {
- (void)event;
- if (getState().isInteractive()) {
- setState(true, getState().pressed);
- return true;
- }
- return false;
-}
-
-bool Dropdown::onMouseLeave(const MouseLeaveEvent& event) {
- (void)event;
- if (!isOpen_) {
- setState(false, getState().pressed);
- }
- return true;
-}
-
-bool Dropdown::onMouseMove(const MouseMoveEvent& event) {
- if (!isOpen_) return false;
-
- Rect popupBounds = getPopupBounds();
- if (popupBounds.contains(event.x, event.y)) {
- hoveredIndex_ = getItemAtY(event.y - popupBounds.y);
- } else {
- hoveredIndex_ = -1;
- }
-
- return false;
-}
-
-bool Dropdown::onKeyDown(const KeyEvent& event) {
- if (!isOpen_) {
- if (event.key == KeyCode::Space || event.key == KeyCode::Enter) {
- openPopup();
- return true;
- }
- return false;
- }
-
- if (event.key == KeyCode::Escape) {
- closePopup();
- return true;
- }
-
- if (event.key == KeyCode::Enter && hoveredIndex_ >= 0) {
- selectItem(hoveredIndex_);
- return true;
- }
-
- if (event.key == KeyCode::Up) {
- i32 start = hoveredIndex_ < 0 ? static_cast<i32>(items_.size()) : hoveredIndex_;
- for (i32 i = start - 1; i >= 0; --i) {
- if (items_[i].enabled) {
- hoveredIndex_ = i;
- break;
- }
- }
- return true;
- }
-
- if (event.key == KeyCode::Down) {
- i32 start = hoveredIndex_;
- for (i32 i = start + 1; i < static_cast<i32>(items_.size()); ++i) {
- if (items_[i].enabled) {
- hoveredIndex_ = i;
- break;
- }
- }
- return true;
- }
-
- return false;
-}
-
-Widget* Dropdown::hitTest(f32 x, f32 y) {
- if (isOpen_) {
- Rect popupBounds = getPopupBounds();
- if (popupBounds.contains(x, y)) {
- return this;
- }
- }
-
- const Rect& bounds = getBounds();
- if (bounds.contains(x, y)) {
- return this;
- }
-
- if (isOpen_) {
- return this;
- }
-
- return nullptr;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void Dropdown::openPopup() {
- isOpen_ = true;
- hoveredIndex_ = selectedIndex_;
-}
-
-void Dropdown::closePopup() {
- isOpen_ = false;
- hoveredIndex_ = -1;
-}
-
-void Dropdown::selectItem(i32 index) {
- if (index < 0 || index >= static_cast<i32>(items_.size())) {
- return;
- }
-
- const DropdownItem& item = items_[index];
- if (!item.enabled) {
- return;
- }
-
- i32 oldValue = getSelectedValue();
- selectedIndex_ = index;
- closePopup();
-
- if (oldValue != item.value) {
- onSelectionChanged.publish(item.value);
- }
-}
-
-f32 Dropdown::calculatePopupHeight() const {
- return PADDING_Y * 2 + static_cast<f32>(items_.size()) * ITEM_HEIGHT;
-}
-
-i32 Dropdown::getItemAtY(f32 y) const {
- f32 itemY = PADDING_Y;
-
- for (i32 i = 0; i < static_cast<i32>(items_.size()); ++i) {
- if (y >= itemY && y < itemY + ITEM_HEIGHT) {
- return i;
- }
- itemY += ITEM_HEIGHT;
- }
-
- return -1;
-}
-
-Rect Dropdown::getPopupBounds() const {
- const Rect& bounds = getBounds();
- f32 popupHeight = calculatePopupHeight();
-
- UIContext* ctx = getContext();
- glm::vec2 viewportSize = ctx ? ctx->getViewportSize() : glm::vec2(9999.0f);
-
- f32 popupY = bounds.y + bounds.height + 2.0f;
- if (popupY + popupHeight > viewportSize.y) {
- popupY = bounds.y - popupHeight - 2.0f;
- }
-
- return Rect{bounds.x, popupY, bounds.width, popupHeight};
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Dropdown.hpp b/src/esengine/ui/widgets/Dropdown.hpp
deleted file mode 100644
index 23ca368fa..000000000
--- a/src/esengine/ui/widgets/Dropdown.hpp
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * @file Dropdown.hpp
- * @brief Dropdown selection widget
- * @details A dropdown/combobox widget that displays a list of selectable items.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <functional>
-#include <string>
-#include <vector>
-
-namespace esengine::ui {
-
-// =============================================================================
-// DropdownItem
-// =============================================================================
-
-struct DropdownItem {
- i32 value = 0;
- std::string label;
- std::string icon;
- bool enabled = true;
-
- static DropdownItem create(i32 value, const std::string& label, const std::string& icon = "") {
- DropdownItem item;
- item.value = value;
- item.label = label;
- item.icon = icon;
- return item;
- }
-};
-
-// =============================================================================
-// Dropdown Class
-// =============================================================================
-
-/**
- * @brief Dropdown selection widget
- *
- * @details Displays a button showing the current selection. When clicked,
- * shows a popup list of options for selection.
- *
- * @code
- * auto dropdown = makeUnique<Dropdown>(WidgetId("type"));
- * dropdown->addItem(DropdownItem::create(0, "Perspective"));
- * dropdown->addItem(DropdownItem::create(1, "Orthographic"));
- * dropdown->setSelectedIndex(0);
- * dropdown->onSelectionChanged.connect([](i32 value) {
- * ES_LOG_INFO("Selected: {}", value);
- * });
- * @endcode
- */
-class Dropdown : public Widget {
-public:
- static constexpr f32 ITEM_HEIGHT = 24.0f;
- static constexpr f32 PADDING_X = 8.0f;
- static constexpr f32 PADDING_Y = 4.0f;
- static constexpr f32 ARROW_WIDTH = 20.0f;
- static constexpr f32 MIN_WIDTH = 80.0f;
-
- explicit Dropdown(const WidgetId& id);
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- Signal<void(i32)> onSelectionChanged;
-
- // =========================================================================
- // Items
- // =========================================================================
-
- void addItem(const DropdownItem& item);
- void addItems(const std::vector<DropdownItem>& items);
- void clearItems();
-
- const std::vector<DropdownItem>& getItems() const { return items_; }
-
- // =========================================================================
- // Selection
- // =========================================================================
-
- void setSelectedIndex(i32 index);
- i32 getSelectedIndex() const { return selectedIndex_; }
-
- void setSelectedValue(i32 value);
- i32 getSelectedValue() const;
-
- const DropdownItem* getSelectedItem() const;
-
- // =========================================================================
- // Appearance
- // =========================================================================
-
- void setFontSize(f32 size) { fontSize_ = size; invalidateLayout(); }
- f32 getFontSize() const { return fontSize_; }
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- bool isFocusable() const override { return true; }
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
- bool onMouseEnter(const MouseEnterEvent& event) override;
- bool onMouseLeave(const MouseLeaveEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
- bool onKeyDown(const KeyEvent& event) override;
-
- Widget* hitTest(f32 x, f32 y) override;
-
-private:
- void openPopup();
- void closePopup();
- void selectItem(i32 index);
-
- f32 calculatePopupHeight() const;
- i32 getItemAtY(f32 y) const;
- Rect getPopupBounds() const;
-
- std::vector<DropdownItem> items_;
- i32 selectedIndex_ = -1;
- i32 hoveredIndex_ = -1;
- f32 fontSize_ = 12.0f;
- bool isOpen_ = false;
-
- glm::vec2 cachedTextSize_{0.0f};
- bool textSizeDirty_ = true;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Label.cpp b/src/esengine/ui/widgets/Label.cpp
deleted file mode 100644
index e4d796e9a..000000000
--- a/src/esengine/ui/widgets/Label.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * @file Label.cpp
- * @brief Label widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Label.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Label::Label(const WidgetId& id, const std::string& text)
- : Widget(id), text_(text) {}
-
-// =============================================================================
-// Text
-// =============================================================================
-
-void Label::setText(const std::string& text) {
- if (text_ != text) {
- text_ = text;
- textSizeDirty_ = true;
- invalidateLayout();
- }
-}
-
-// =============================================================================
-// Appearance
-// =============================================================================
-
-void Label::setColor(const glm::vec4& color) {
- color_ = color;
- customColor_ = true;
-}
-
-// =============================================================================
-// Measurement
-// =============================================================================
-
-glm::vec2 Label::measure(f32 availableWidth, f32 availableHeight) {
- if (!getContext()) {
- return Widget::measure(availableWidth, availableHeight);
- }
-
- if (textSizeDirty_) {
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = nullptr;
- if (useIconFont_) {
- font = getContext()->getIconMSDFFont();
- } else {
- font = fontName_.empty() ? getContext()->getDefaultMSDFFont()
- : getContext()->getMSDFFont(fontName_);
- }
- if (font) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = fontName_.empty() ? getContext()->getDefaultBitmapFont()
- : getContext()->getBitmapFont(fontName_);
- if (font) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
- }
-#else
- SystemFont* font = nullptr;
- if (useIconFont_) {
- font = getContext()->getIconSystemFont();
- } else {
- font = fontName_.empty() ? getContext()->getDefaultSystemFont()
- : getContext()->getSystemFont(fontName_);
- }
- if (font) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
- }
-#endif
- }
-
- f32 contentWidth = cachedTextSize_.x + getPadding().totalHorizontal();
- f32 contentHeight = cachedTextSize_.y + getPadding().totalVertical();
-
- f32 width = getWidth().resolve(availableWidth, contentWidth);
- f32 height = getHeight().resolve(availableHeight, contentHeight);
-
- width = getConstraints().constrainWidth(width);
- height = getConstraints().constrainHeight(height);
-
- return {width, height};
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void Label::render(UIBatchRenderer& renderer) {
- if (text_.empty()) return;
-
- UIContext* ctx = getContext();
- if (!ctx) return;
-
- WidgetStyle style = ctx->getTheme().getLabelStyle();
- glm::vec4 textColor = customColor_ ? color_ : style.getTextColor(getState());
- Rect contentBounds = getContentBounds();
-
- if (clipContent_) {
- renderer.pushClipRect(contentBounds);
- }
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = nullptr;
- if (useIconFont_) {
- font = ctx->getIconMSDFFont();
- } else {
- font = fontName_.empty() ? ctx->getDefaultMSDFFont() : ctx->getMSDFFont(fontName_);
- }
- if (font) {
- renderer.drawTextInBounds(text_, contentBounds, *font, fontSize_, textColor, hAlign_, vAlign_);
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = fontName_.empty() ? ctx->getDefaultBitmapFont() : ctx->getBitmapFont(fontName_);
- if (font) {
- renderer.drawTextInBounds(text_, contentBounds, *font, fontSize_, textColor, hAlign_, vAlign_);
- }
-#else
- SystemFont* font = nullptr;
- if (useIconFont_) {
- font = ctx->getIconSystemFont();
- } else {
- font = fontName_.empty() ? ctx->getDefaultSystemFont() : ctx->getSystemFont(fontName_);
- }
- if (font) {
- renderer.drawTextInBounds(text_, contentBounds, *font, fontSize_, textColor, hAlign_, vAlign_);
- }
-#endif
-
- if (clipContent_) {
- renderer.popClipRect();
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Label.hpp b/src/esengine/ui/widgets/Label.hpp
deleted file mode 100644
index 376c14016..000000000
--- a/src/esengine/ui/widgets/Label.hpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * @file Label.hpp
- * @brief Text label widget
- * @details A simple widget for displaying static text.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../layout/SizeValue.hpp"
-
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Label Class
-// =============================================================================
-
-/**
- * @brief Widget for displaying text
- *
- * @details Renders a single line or multi-line text with configurable
- * font, size, color, and alignment.
- *
- * @code
- * auto label = makeUnique<Label>(WidgetId("title"), "Hello World");
- * label->setFontSize(18.0f);
- * label->setColor({1.0f, 1.0f, 0.0f, 1.0f});
- * @endcode
- */
-class Label : public Widget {
-public:
- /**
- * @brief Creates a label with text
- * @param id Widget identifier
- * @param text Initial text to display
- */
- Label(const WidgetId& id, const std::string& text = "");
-
- // =========================================================================
- // Text
- // =========================================================================
-
- /** @brief Sets the displayed text */
- void setText(const std::string& text);
-
- /** @brief Gets the displayed text */
- const std::string& getText() const { return text_; }
-
- // =========================================================================
- // Font
- // =========================================================================
-
- /** @brief Sets the font name (must be loaded in UIContext) */
- void setFontName(const std::string& name) { fontName_ = name; }
-
- /** @brief Gets the font name */
- const std::string& getFontName() const { return fontName_; }
-
- /** @brief Sets the font size in pixels */
- void setFontSize(f32 size) { fontSize_ = size; invalidateLayout(); }
-
- /** @brief Gets the font size */
- f32 getFontSize() const { return fontSize_; }
-
- // =========================================================================
- // Appearance
- // =========================================================================
-
- /** @brief Sets a custom text color (overrides theme) */
- void setColor(const glm::vec4& color);
-
- /** @brief Clears the custom color (use theme) */
- void clearColor() { customColor_ = false; }
-
- /** @brief Sets whether to use icon font instead of text font */
- void setIsIconFont(bool isIcon) { useIconFont_ = isIcon; }
-
- /** @brief Returns true if using icon font */
- bool isIconFont() const { return useIconFont_; }
-
- // =========================================================================
- // Alignment
- // =========================================================================
-
- /** @brief Sets horizontal text alignment */
- void setHAlign(HAlign align) { hAlign_ = align; }
-
- /** @brief Gets horizontal text alignment */
- HAlign getHAlign() const { return hAlign_; }
-
- /** @brief Sets vertical text alignment */
- void setVAlign(VAlign align) { vAlign_ = align; }
-
- /** @brief Gets vertical text alignment */
- VAlign getVAlign() const { return vAlign_; }
-
- /** @brief Sets whether to clip text to bounds */
- void setClipContent(bool clip) { clipContent_ = clip; }
-
- /** @brief Returns true if content is clipped */
- bool getClipContent() const { return clipContent_; }
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
-
-private:
- std::string text_;
- std::string fontName_;
- f32 fontSize_ = 14.0f;
-
- bool customColor_ = false;
- glm::vec4 color_{1.0f};
- bool useIconFont_ = false;
-
- HAlign hAlign_ = HAlign::Left;
- VAlign vAlign_ = VAlign::Center;
- bool clipContent_ = false;
-
- glm::vec2 cachedTextSize_{0.0f};
- bool textSizeDirty_ = true;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Panel.cpp b/src/esengine/ui/widgets/Panel.cpp
deleted file mode 100644
index b75f4073d..000000000
--- a/src/esengine/ui/widgets/Panel.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * @file Panel.cpp
- * @brief Panel widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Panel.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Panel::Panel(const WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// Configuration
-// =============================================================================
-
-void Panel::setBackgroundColor(const glm::vec4& color) {
- backgroundColor_ = color;
- customBackground_ = true;
-}
-
-void Panel::setBorderColor(const glm::vec4& color) {
- borderColor_ = color;
- customBorder_ = true;
-}
-
-void Panel::setBorderWidth(const BorderWidth& width) {
- borderWidth_ = width;
- drawBorder_ = width.hasAny();
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void Panel::render(UIBatchRenderer& renderer) {
- if (!drawBackground_ && !drawBorder_) return;
-
- WidgetStyle style;
- if (getContext()) {
- style = getContext()->getTheme().getPanelStyle();
- }
-
- const Rect& bounds = getBounds();
-
- if (drawBackground_) {
- glm::vec4 bgColor = customBackground_ ? backgroundColor_
- : style.getBackgroundColor(getState());
-
- CornerRadii radii = cornerRadii_.isZero() ? style.cornerRadii : cornerRadii_;
-
- if (radii.isZero()) {
- renderer.drawRect(bounds, bgColor);
- } else {
- renderer.drawRoundedRect(bounds, bgColor, radii);
- }
- }
-
- if (drawBorder_) {
- glm::vec4 brColor = customBorder_ ? borderColor_ : style.getBorderColor(getState());
-
- if (borderWidth_.hasAny()) {
- if (borderWidth_.top > 0.0f) {
- Rect topBorder{bounds.x, bounds.y, bounds.width, borderWidth_.top};
- renderer.drawRect(topBorder, brColor);
- }
- if (borderWidth_.right > 0.0f) {
- Rect rightBorder{bounds.x + bounds.width - borderWidth_.right, bounds.y,
- borderWidth_.right, bounds.height};
- renderer.drawRect(rightBorder, brColor);
- }
- if (borderWidth_.bottom > 0.0f) {
- Rect bottomBorder{bounds.x, bounds.y + bounds.height - borderWidth_.bottom,
- bounds.width, borderWidth_.bottom};
- renderer.drawRect(bottomBorder, brColor);
- }
- if (borderWidth_.left > 0.0f) {
- Rect leftBorder{bounds.x, bounds.y, borderWidth_.left, bounds.height};
- renderer.drawRect(leftBorder, brColor);
- }
- } else if (style.borderWidth > 0.0f) {
- CornerRadii radii = cornerRadii_.isZero() ? style.cornerRadii : cornerRadii_;
- renderer.drawRoundedRectOutline(bounds, brColor, radii, style.borderWidth);
- }
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Panel.hpp b/src/esengine/ui/widgets/Panel.hpp
deleted file mode 100644
index 957f1f2c2..000000000
--- a/src/esengine/ui/widgets/Panel.hpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/**
- * @file Panel.hpp
- * @brief Panel container widget
- * @details A simple container widget that renders a background and
- * contains child widgets.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// BorderWidth Struct
-// =============================================================================
-
-struct BorderWidth {
- f32 top = 0.0f;
- f32 right = 0.0f;
- f32 bottom = 0.0f;
- f32 left = 0.0f;
-
- constexpr BorderWidth() = default;
- constexpr BorderWidth(f32 t, f32 r, f32 b, f32 l) : top(t), right(r), bottom(b), left(l) {}
- static constexpr BorderWidth all(f32 v) { return {v, v, v, v}; }
- [[nodiscard]] bool isZero() const { return top == 0 && right == 0 && bottom == 0 && left == 0; }
- [[nodiscard]] bool hasAny() const { return top > 0 || right > 0 || bottom > 0 || left > 0; }
-};
-
-// =============================================================================
-// Panel Class
-// =============================================================================
-
-/**
- * @brief Container widget with styled background
- *
- * @details Panel provides a container for other widgets with a styled
- * background that can be customized using themes.
- *
- * @code
- * auto panel = makeUnique<Panel>(WidgetId("myPanel"));
- * panel->setLayout(makeUnique<StackLayout>(StackDirection::Vertical, 8.0f));
- * panel->addChild(makeUnique<Label>(WidgetId("label"), "Hello"));
- * panel->addChild(makeUnique<Button>(WidgetId("btn"), "Click"));
- * @endcode
- */
-class Panel : public Widget {
-public:
- /**
- * @brief Creates a panel
- * @param id Widget identifier
- */
- explicit Panel(const WidgetId& id);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /** @brief Sets whether to draw the background */
- void setDrawBackground(bool draw) { drawBackground_ = draw; }
-
- /** @brief Returns true if background is drawn */
- bool isDrawingBackground() const { return drawBackground_; }
-
- /** @brief Sets whether to draw the border */
- void setDrawBorder(bool draw) { drawBorder_ = draw; }
-
- /** @brief Returns true if border is drawn */
- bool isDrawingBorder() const { return drawBorder_; }
-
- /** @brief Sets a custom background color (overrides theme) */
- void setBackgroundColor(const glm::vec4& color);
-
- /** @brief Clears the custom background color (use theme) */
- void clearBackgroundColor() { customBackground_ = false; }
-
- /** @brief Sets a custom border color (overrides theme) */
- void setBorderColor(const glm::vec4& color);
-
- /** @brief Sets per-side border widths */
- void setBorderWidth(const BorderWidth& width);
-
- /** @brief Gets the border width */
- const BorderWidth& getBorderWidth() const { return borderWidth_; }
-
- /** @brief Sets the corner radii */
- void setCornerRadii(const CornerRadii& radii) { cornerRadii_ = radii; }
-
- /** @brief Gets the corner radii */
- const CornerRadii& getCornerRadii() const { return cornerRadii_; }
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- void render(UIBatchRenderer& renderer) override;
-
-private:
- bool drawBackground_ = true;
- bool drawBorder_ = false;
- bool customBackground_ = false;
- bool customBorder_ = false;
-
- glm::vec4 backgroundColor_{0.0f};
- glm::vec4 borderColor_{0.0f};
- CornerRadii cornerRadii_;
- BorderWidth borderWidth_;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/ScrollView.cpp b/src/esengine/ui/widgets/ScrollView.cpp
deleted file mode 100644
index cf312da3f..000000000
--- a/src/esengine/ui/widgets/ScrollView.cpp
+++ /dev/null
@@ -1,528 +0,0 @@
-/**
- * @file ScrollView.cpp
- * @brief Scrollable container widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "ScrollView.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../../math/Math.hpp"
-
-#include <limits>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-ScrollView::ScrollView(const WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// Content Management
-// =============================================================================
-
-void ScrollView::setContent(Unique<Widget> content) {
- if (content_) {
- removeChild(content_);
- }
-
- if (content) {
- content_ = content.get();
- addChild(std::move(content));
- invalidateLayout();
- } else {
- content_ = nullptr;
- }
-}
-
-// =============================================================================
-// Scroll Position
-// =============================================================================
-
-void ScrollView::setScrollOffset(const glm::vec2& offset) {
- scrollOffset_ = offset;
- clampScrollOffset();
- updateContentLayout();
-}
-
-void ScrollView::scrollBy(const glm::vec2& delta) {
- setScrollOffset(scrollOffset_ + delta);
-}
-
-void ScrollView::scrollToWidget(const Widget* widget) {
- if (!widget || !content_) return;
-
- const Rect& widgetBounds = widget->getBounds();
- const Rect& viewBounds = getBounds();
-
- glm::vec2 newOffset = scrollOffset_;
-
- if (scrollDirection_ & ScrollDirection::Vertical) {
- f32 widgetTop = widgetBounds.y;
- f32 widgetBottom = widgetBounds.y + widgetBounds.height;
- f32 viewTop = viewBounds.y + scrollOffset_.y;
- f32 viewBottom = viewTop + viewportSize_.y;
-
- if (widgetTop < viewTop) {
- newOffset.y = widgetTop - viewBounds.y;
- } else if (widgetBottom > viewBottom) {
- newOffset.y = widgetBottom - viewBounds.y - viewportSize_.y;
- }
- }
-
- if (scrollDirection_ & ScrollDirection::Horizontal) {
- f32 widgetLeft = widgetBounds.x;
- f32 widgetRight = widgetBounds.x + widgetBounds.width;
- f32 viewLeft = viewBounds.x + scrollOffset_.x;
- f32 viewRight = viewLeft + viewportSize_.x;
-
- if (widgetLeft < viewLeft) {
- newOffset.x = widgetLeft - viewBounds.x;
- } else if (widgetRight > viewRight) {
- newOffset.x = widgetRight - viewBounds.x - viewportSize_.x;
- }
- }
-
- setScrollOffset(newOffset);
-}
-
-glm::vec2 ScrollView::getMaxScrollOffset() const {
- glm::vec2 maxOffset{0.0f, 0.0f};
-
- if (scrollDirection_ & ScrollDirection::Vertical) {
- maxOffset.y = glm::max(0.0f, contentSize_.y - viewportSize_.y);
- }
-
- if (scrollDirection_ & ScrollDirection::Horizontal) {
- maxOffset.x = glm::max(0.0f, contentSize_.x - viewportSize_.x);
- }
-
- return maxOffset;
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 ScrollView::measure(f32 availableWidth, f32 availableHeight) {
- glm::vec2 size = Widget::measure(availableWidth, availableHeight);
-
- if (content_) {
- f32 contentAvailableWidth = availableWidth;
- f32 contentAvailableHeight = availableHeight;
-
- if (showScrollbars_) {
- if (scrollDirection_ & ScrollDirection::Vertical) {
- contentAvailableWidth -= scrollbarWidth_;
- }
- if (scrollDirection_ & ScrollDirection::Horizontal) {
- contentAvailableHeight -= scrollbarWidth_;
- }
- }
-
- f32 measureWidth = contentAvailableWidth;
- f32 measureHeight = contentAvailableHeight;
-
- if (scrollDirection_ == ScrollDirection::Vertical) {
- measureHeight = std::numeric_limits<f32>::infinity();
- } else if (scrollDirection_ == ScrollDirection::Horizontal) {
- measureWidth = std::numeric_limits<f32>::infinity();
- } else if (scrollDirection_ == ScrollDirection::Both) {
- measureWidth = std::numeric_limits<f32>::infinity();
- measureHeight = std::numeric_limits<f32>::infinity();
- }
-
- contentSize_ = content_->measure(measureWidth, measureHeight);
- }
-
- return size;
-}
-
-void ScrollView::layout(const Rect& bounds) {
- Widget::layout(bounds);
-
- const Insets& padding = getPadding();
- viewportSize_ = glm::vec2(
- bounds.width - padding.left - padding.right,
- bounds.height - padding.top - padding.bottom
- );
-
- if (showScrollbars_) {
- if (scrollDirection_ & ScrollDirection::Vertical) {
- viewportSize_.x -= scrollbarWidth_;
- }
- if (scrollDirection_ & ScrollDirection::Horizontal) {
- viewportSize_.y -= scrollbarWidth_;
- }
- }
-
- clampScrollOffset();
- updateContentLayout();
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void ScrollView::renderTree(UIBatchRenderer& renderer) {
- if (!isVisible()) return;
-
- render(renderer);
-}
-
-void ScrollView::render(UIBatchRenderer& renderer) {
- if (!content_) return;
-
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- Rect viewportRect{
- bounds.x + padding.left,
- bounds.y + padding.top,
- viewportSize_.x,
- viewportSize_.y
- };
-
- // Save original content bounds for hitTest (not offset)
- Rect originalBounds = content_->getBounds();
-
- // Temporarily offset content bounds for rendering
- Rect renderBounds{
- originalBounds.x - scrollOffset_.x,
- originalBounds.y - scrollOffset_.y,
- originalBounds.width,
- originalBounds.height
- };
- content_->layout(renderBounds);
-
- renderer.pushClipRect(viewportRect);
- content_->renderTree(renderer);
- renderer.popClipRect();
-
- // Restore original bounds for hitTest
- content_->layout(originalBounds);
-
- if (showScrollbars_) {
- if (canScrollVertically()) {
- renderVerticalScrollbar(renderer);
- }
- if (canScrollHorizontally()) {
- renderHorizontalScrollbar(renderer);
- }
- }
-}
-
-Widget* ScrollView::hitTest(f32 x, f32 y) {
- if (!containsPoint(x, y)) {
- return nullptr;
- }
-
- if (showScrollbars_) {
- if (canScrollVertically()) {
- Rect vScrollbarBounds = getVerticalScrollbarBounds();
- if (vScrollbarBounds.contains(x, y)) {
- return this;
- }
- }
-
- if (canScrollHorizontally()) {
- Rect hScrollbarBounds = getHorizontalScrollbarBounds();
- if (hScrollbarBounds.contains(x, y)) {
- return this;
- }
- }
- }
-
- if (content_) {
- // Content bounds are not offset (offset is applied only during render).
- // We need to check if the click is within the viewport, then transform
- // coordinates to content's local coordinate system.
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- Rect viewportRect{
- bounds.x + padding.left,
- bounds.y + padding.top,
- viewportSize_.x,
- viewportSize_.y
- };
-
- if (viewportRect.contains(x, y)) {
- // Transform screen coordinates to content coordinates
- // by adding scroll offset
- f32 contentX = x + scrollOffset_.x;
- f32 contentY = y + scrollOffset_.y;
-
- Widget* hit = content_->hitTest(contentX, contentY);
- if (hit) {
- return hit;
- }
- }
- }
-
- return this;
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool ScrollView::onScroll(const ScrollEvent& event) {
- glm::vec2 delta{0.0f, 0.0f};
-
- if (scrollDirection_ & ScrollDirection::Vertical) {
- delta.y = -event.deltaY * scrollSpeed_;
- }
-
- if (scrollDirection_ & ScrollDirection::Horizontal) {
- delta.x = -event.deltaX * scrollSpeed_;
- }
-
- if (glm::length(delta) > 0.0f) {
- scrollBy(delta);
- return true;
- }
-
- return false;
-}
-
-bool ScrollView::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- if (showScrollbars_ && canScrollVertically()) {
- Rect thumbBounds = getVerticalScrollbarThumbBounds();
- if (thumbBounds.contains(event.x, event.y)) {
- draggingVerticalScrollbar_ = true;
- dragStartMousePos_ = glm::vec2(event.x, event.y);
- dragStartScrollOffset_ = scrollOffset_;
- return true;
- }
- }
-
- if (showScrollbars_ && canScrollHorizontally()) {
- Rect thumbBounds = getHorizontalScrollbarThumbBounds();
- if (thumbBounds.contains(event.x, event.y)) {
- draggingHorizontalScrollbar_ = true;
- dragStartMousePos_ = glm::vec2(event.x, event.y);
- dragStartScrollOffset_ = scrollOffset_;
- return true;
- }
- }
-
- return false;
-}
-
-bool ScrollView::onMouseUp(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- bool wasDragging = draggingVerticalScrollbar_ || draggingHorizontalScrollbar_;
- draggingVerticalScrollbar_ = false;
- draggingHorizontalScrollbar_ = false;
-
- return wasDragging;
-}
-
-bool ScrollView::onMouseMove(const MouseMoveEvent& event) {
- if (draggingVerticalScrollbar_) {
- f32 mouseDelta = event.y - dragStartMousePos_.y;
- f32 trackHeight = viewportSize_.y;
- f32 maxScroll = getMaxScrollOffset().y;
-
- if (trackHeight > 0.0f) {
- f32 scrollRatio = maxScroll / trackHeight;
- f32 scrollDelta = mouseDelta * scrollRatio;
-
- glm::vec2 newOffset = dragStartScrollOffset_;
- newOffset.y += scrollDelta;
- setScrollOffset(newOffset);
- }
-
- return true;
- }
-
- if (draggingHorizontalScrollbar_) {
- f32 mouseDelta = event.x - dragStartMousePos_.x;
- f32 trackWidth = viewportSize_.x;
- f32 maxScroll = getMaxScrollOffset().x;
-
- if (trackWidth > 0.0f) {
- f32 scrollRatio = maxScroll / trackWidth;
- f32 scrollDelta = mouseDelta * scrollRatio;
-
- glm::vec2 newOffset = dragStartScrollOffset_;
- newOffset.x += scrollDelta;
- setScrollOffset(newOffset);
- }
-
- return true;
- }
-
- return false;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void ScrollView::clampScrollOffset() {
- glm::vec2 maxOffset = getMaxScrollOffset();
- scrollOffset_.x = glm::clamp(scrollOffset_.x, 0.0f, maxOffset.x);
- scrollOffset_.y = glm::clamp(scrollOffset_.y, 0.0f, maxOffset.y);
-}
-
-void ScrollView::updateContentLayout() {
- if (!content_) return;
-
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- f32 measureWidth = viewportSize_.x;
- f32 measureHeight = std::numeric_limits<f32>::infinity();
-
- if (scrollDirection_ == ScrollDirection::Horizontal) {
- measureWidth = std::numeric_limits<f32>::infinity();
- measureHeight = viewportSize_.y;
- } else if (scrollDirection_ == ScrollDirection::Both) {
- measureWidth = std::numeric_limits<f32>::infinity();
- measureHeight = std::numeric_limits<f32>::infinity();
- }
-
- contentSize_ = content_->measure(measureWidth, measureHeight);
-
- f32 contentWidth = contentSize_.x;
- f32 contentHeight = contentSize_.y;
-
- if (scrollDirection_ == ScrollDirection::Vertical) {
- contentWidth = viewportSize_.x;
- } else if (scrollDirection_ == ScrollDirection::Horizontal) {
- contentHeight = viewportSize_.y;
- }
-
- // Content bounds are NOT offset by scrollOffset_ for correct hitTest.
- // The scroll offset is applied during rendering only.
- Rect contentBounds{
- bounds.x + padding.left,
- bounds.y + padding.top,
- contentWidth,
- contentHeight
- };
-
- content_->layout(contentBounds);
-}
-
-void ScrollView::renderVerticalScrollbar(UIBatchRenderer& renderer) {
- Rect trackBounds = getVerticalScrollbarBounds();
- Rect thumbBounds = getVerticalScrollbarThumbBounds();
-
- WidgetStyle style;
- if (getContext()) {
- style = getContext()->getTheme().getScrollbarStyle();
- }
-
- glm::vec4 trackColor = style.getBackgroundColor(getState());
- glm::vec4 thumbColor = style.getForegroundColor(getState());
-
- renderer.drawRect(trackBounds, trackColor);
- renderer.drawRoundedRect(thumbBounds, thumbColor, CornerRadii::all(4.0f));
-}
-
-void ScrollView::renderHorizontalScrollbar(UIBatchRenderer& renderer) {
- Rect trackBounds = getHorizontalScrollbarBounds();
- Rect thumbBounds = getHorizontalScrollbarThumbBounds();
-
- WidgetStyle style;
- if (getContext()) {
- style = getContext()->getTheme().getScrollbarStyle();
- }
-
- glm::vec4 trackColor = style.getBackgroundColor(getState());
- glm::vec4 thumbColor = style.getForegroundColor(getState());
-
- renderer.drawRect(trackBounds, trackColor);
- renderer.drawRoundedRect(thumbBounds, thumbColor, CornerRadii::all(4.0f));
-}
-
-Rect ScrollView::getVerticalScrollbarBounds() const {
- const Rect& bounds = getBounds();
- return Rect{
- bounds.x + bounds.width - scrollbarWidth_,
- bounds.y,
- scrollbarWidth_,
- viewportSize_.y
- };
-}
-
-Rect ScrollView::getHorizontalScrollbarBounds() const {
- const Rect& bounds = getBounds();
- return Rect{
- bounds.x,
- bounds.y + bounds.height - scrollbarWidth_,
- viewportSize_.x,
- scrollbarWidth_
- };
-}
-
-Rect ScrollView::getVerticalScrollbarThumbBounds() const {
- Rect trackBounds = getVerticalScrollbarBounds();
- f32 maxScroll = getMaxScrollOffset().y;
-
- if (maxScroll <= 0.0f) {
- return trackBounds;
- }
-
- f32 visibleRatio = viewportSize_.y / contentSize_.y;
- f32 thumbHeight = glm::max(20.0f, trackBounds.height * visibleRatio);
- f32 scrollRatio = scrollOffset_.y / maxScroll;
- f32 thumbY = trackBounds.y + scrollRatio * (trackBounds.height - thumbHeight);
-
- return Rect{
- trackBounds.x + 2.0f,
- thumbY,
- scrollbarWidth_ - 4.0f,
- thumbHeight
- };
-}
-
-Rect ScrollView::getHorizontalScrollbarThumbBounds() const {
- Rect trackBounds = getHorizontalScrollbarBounds();
- f32 maxScroll = getMaxScrollOffset().x;
-
- if (maxScroll <= 0.0f) {
- return trackBounds;
- }
-
- f32 visibleRatio = viewportSize_.x / contentSize_.x;
- f32 thumbWidth = glm::max(20.0f, trackBounds.width * visibleRatio);
- f32 scrollRatio = scrollOffset_.x / maxScroll;
- f32 thumbX = trackBounds.x + scrollRatio * (trackBounds.width - thumbWidth);
-
- return Rect{
- thumbX,
- trackBounds.y + 2.0f,
- thumbWidth,
- scrollbarWidth_ - 4.0f
- };
-}
-
-bool ScrollView::canScrollVertically() const {
- return (scrollDirection_ & ScrollDirection::Vertical) &&
- contentSize_.y > viewportSize_.y;
-}
-
-bool ScrollView::canScrollHorizontally() const {
- return (scrollDirection_ & ScrollDirection::Horizontal) &&
- contentSize_.x > viewportSize_.x;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/ScrollView.hpp b/src/esengine/ui/widgets/ScrollView.hpp
deleted file mode 100644
index a7e6e91a2..000000000
--- a/src/esengine/ui/widgets/ScrollView.hpp
+++ /dev/null
@@ -1,261 +0,0 @@
-/**
- * @file ScrollView.hpp
- * @brief Scrollable container widget
- * @details A container widget that provides scrolling for content larger
- * than its visible area. Supports vertical and horizontal scrolling
- * with optional scrollbars.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// ScrollDirection Enum
-// =============================================================================
-
-/**
- * @brief Scroll direction flags
- */
-enum class ScrollDirection : u8 {
- None = 0,
- Vertical = 1 << 0,
- Horizontal = 1 << 1,
- Both = Vertical | Horizontal
-};
-
-inline ScrollDirection operator|(ScrollDirection a, ScrollDirection b) {
- return static_cast<ScrollDirection>(static_cast<u8>(a) | static_cast<u8>(b));
-}
-
-inline bool operator&(ScrollDirection a, ScrollDirection b) {
- return (static_cast<u8>(a) & static_cast<u8>(b)) != 0;
-}
-
-// =============================================================================
-// ScrollView Class
-// =============================================================================
-
-/**
- * @brief Scrollable container widget
- *
- * @details ScrollView provides a scrollable viewport for content that exceeds
- * the available space. Features:
- * - Vertical and/or horizontal scrolling
- * - Mouse wheel support
- * - Optional scrollbar rendering
- * - Smooth scrolling with configurable speed
- *
- * @code
- * auto scroll = makeUnique<ScrollView>(WidgetId("scroll"));
- * scroll->setScrollDirection(ScrollDirection::Vertical);
- * scroll->setShowScrollbars(true);
- *
- * auto content = makeUnique<Panel>(WidgetId("content"));
- * content->setHeight(SizeValue::pixels(2000.0f)); // Tall content
- * scroll->setContent(std::move(content));
- * @endcode
- */
-class ScrollView : public Widget {
-public:
- /**
- * @brief Creates a scroll view
- * @param id Widget identifier
- */
- explicit ScrollView(const WidgetId& id);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /**
- * @brief Sets the scroll direction
- * @param direction Vertical, Horizontal, or Both
- */
- void setScrollDirection(ScrollDirection direction) { scrollDirection_ = direction; }
-
- /**
- * @brief Gets the scroll direction
- */
- ScrollDirection getScrollDirection() const { return scrollDirection_; }
-
- /**
- * @brief Sets whether to show scrollbars
- * @param show True to show scrollbars
- */
- void setShowScrollbars(bool show) { showScrollbars_ = show; }
-
- /**
- * @brief Returns true if scrollbars are shown
- */
- bool isShowingScrollbars() const { return showScrollbars_; }
-
- /**
- * @brief Sets the scrollbar width
- * @param width Scrollbar width in pixels
- */
- void setScrollbarWidth(f32 width) { scrollbarWidth_ = width; }
-
- /**
- * @brief Gets the scrollbar width
- */
- f32 getScrollbarWidth() const { return scrollbarWidth_; }
-
- /**
- * @brief Sets the scroll speed multiplier
- * @param speed Scroll speed (default 1.0)
- */
- void setScrollSpeed(f32 speed) { scrollSpeed_ = speed; }
-
- /**
- * @brief Gets the scroll speed
- */
- f32 getScrollSpeed() const { return scrollSpeed_; }
-
- // =========================================================================
- // Content
- // =========================================================================
-
- /**
- * @brief Sets the scrollable content
- * @param content Widget to scroll (ownership transferred)
- */
- void setContent(Unique<Widget> content);
-
- /**
- * @brief Gets the content widget
- */
- Widget* getContent() const { return content_; }
-
- // =========================================================================
- // Scroll Position
- // =========================================================================
-
- /**
- * @brief Gets the current scroll offset
- * @return Scroll offset (x, y)
- */
- glm::vec2 getScrollOffset() const { return scrollOffset_; }
-
- /**
- * @brief Sets the scroll offset
- * @param offset New scroll offset (will be clamped)
- */
- void setScrollOffset(const glm::vec2& offset);
-
- /**
- * @brief Scrolls by a delta amount
- * @param delta Amount to scroll (x, y)
- */
- void scrollBy(const glm::vec2& delta);
-
- /**
- * @brief Scrolls to make a widget visible
- * @param widget Widget to scroll to
- */
- void scrollToWidget(const Widget* widget);
-
- /**
- * @brief Gets the maximum scroll offset
- */
- glm::vec2 getMaxScrollOffset() const;
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void layout(const Rect& bounds) override;
- void render(UIBatchRenderer& renderer) override;
- void renderTree(UIBatchRenderer& renderer) override;
- Widget* hitTest(f32 x, f32 y) override;
-
- bool onScroll(const ScrollEvent& event) override;
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
-
-private:
- // =========================================================================
- // Private Methods
- // =========================================================================
-
- /**
- * @brief Clamps scroll offset to valid range
- */
- void clampScrollOffset();
-
- /**
- * @brief Updates content layout based on scroll offset
- */
- void updateContentLayout();
-
- /**
- * @brief Renders the vertical scrollbar
- */
- void renderVerticalScrollbar(UIBatchRenderer& renderer);
-
- /**
- * @brief Renders the horizontal scrollbar
- */
- void renderHorizontalScrollbar(UIBatchRenderer& renderer);
-
- /**
- * @brief Gets the vertical scrollbar bounds
- */
- Rect getVerticalScrollbarBounds() const;
-
- /**
- * @brief Gets the horizontal scrollbar bounds
- */
- Rect getHorizontalScrollbarBounds() const;
-
- /**
- * @brief Gets the vertical scrollbar thumb bounds
- */
- Rect getVerticalScrollbarThumbBounds() const;
-
- /**
- * @brief Gets the horizontal scrollbar thumb bounds
- */
- Rect getHorizontalScrollbarThumbBounds() const;
-
- /**
- * @brief Checks if scrolling is possible in a direction
- */
- bool canScrollVertically() const;
- bool canScrollHorizontally() const;
-
- // =========================================================================
- // Member Variables
- // =========================================================================
-
- Widget* content_ = nullptr; ///< Scrollable content
- ScrollDirection scrollDirection_ = ScrollDirection::Vertical;
- bool showScrollbars_ = true;
- f32 scrollbarWidth_ = 12.0f;
- f32 scrollSpeed_ = 20.0f;
-
- glm::vec2 scrollOffset_{0.0f, 0.0f}; ///< Current scroll position
- glm::vec2 contentSize_{0.0f, 0.0f}; ///< Size of content
- glm::vec2 viewportSize_{0.0f, 0.0f}; ///< Size of visible area
-
- // Scrollbar dragging state
- bool draggingVerticalScrollbar_ = false;
- bool draggingHorizontalScrollbar_ = false;
- glm::vec2 dragStartMousePos_{0.0f, 0.0f};
- glm::vec2 dragStartScrollOffset_{0.0f, 0.0f};
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Slider.cpp b/src/esengine/ui/widgets/Slider.cpp
deleted file mode 100644
index 6c541ffaf..000000000
--- a/src/esengine/ui/widgets/Slider.cpp
+++ /dev/null
@@ -1,253 +0,0 @@
-/**
- * @file Slider.cpp
- * @brief Slider widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Slider.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../../math/Math.hpp"
-
-#include <cmath>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-Slider::Slider(const WidgetId& id, SliderOrientation orientation)
- : Widget(id), orientation_(orientation) {}
-
-// =============================================================================
-// Value Management
-// =============================================================================
-
-void Slider::setValue(f32 value) {
- f32 clampedValue = glm::clamp(value, min_, max_);
- clampedValue = quantizeValue(clampedValue);
-
- if (value_ == clampedValue) {
- return;
- }
-
- value_ = clampedValue;
- onValueChanged.publish(value_);
-}
-
-void Slider::setRange(f32 min, f32 max) {
- min_ = min;
- max_ = max;
-
- if (max_ < min_) {
- std::swap(min_, max_);
- }
-
- setValue(value_);
-}
-
-void Slider::setStep(f32 step) {
- step_ = glm::max(0.0f, step);
- setValue(value_);
-}
-
-// =============================================================================
-// Orientation
-// =============================================================================
-
-void Slider::setOrientation(SliderOrientation orientation) {
- if (orientation_ == orientation) {
- return;
- }
-
- orientation_ = orientation;
- invalidateLayout();
-}
-
-// =============================================================================
-// Appearance
-// =============================================================================
-
-void Slider::setTrackThickness(f32 thickness) {
- if (trackThickness_ == thickness) {
- return;
- }
-
- trackThickness_ = thickness;
- invalidateLayout();
-}
-
-void Slider::setThumbSize(f32 size) {
- if (thumbSize_ == size) {
- return;
- }
-
- thumbSize_ = size;
- invalidateLayout();
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 Slider::measure(f32 availableWidth, f32 availableHeight) {
- f32 width = 0.0f;
- f32 height = 0.0f;
-
- if (orientation_ == SliderOrientation::Horizontal) {
- width = availableWidth;
- height = thumbSize_;
- } else {
- width = thumbSize_;
- height = availableHeight;
- }
-
- const SizeConstraints& constraints = getConstraints();
- width = glm::clamp(width, constraints.minWidth, constraints.maxWidth);
- height = glm::clamp(height, constraints.minHeight, constraints.maxHeight);
-
- return glm::vec2(width, height);
-}
-
-void Slider::render(UIBatchRenderer& renderer) {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- WidgetStyle trackStyle;
- WidgetStyle thumbStyle;
- if (getContext()) {
- trackStyle = getContext()->getTheme().getSliderTrackStyle();
- thumbStyle = getContext()->getTheme().getSliderThumbStyle();
- }
-
- WidgetState state{
- .hovered = isHovered(),
- .pressed = isPressed(),
- .focused = false,
- .disabled = !isEnabled(),
- .visible = true
- };
-
- f32 normalizedValue = getNormalizedValue();
-
- if (orientation_ == SliderOrientation::Horizontal) {
- f32 trackWidth = bounds.width - padding.left - padding.right - thumbSize_;
- f32 trackHeight = trackThickness_;
- f32 trackX = bounds.x + padding.left + thumbSize_ * 0.5f;
- f32 trackY = bounds.y + (bounds.height - trackHeight) * 0.5f;
-
- Rect trackBounds{trackX, trackY, trackWidth, trackHeight};
- glm::vec4 trackColor = trackStyle.getBackgroundColor(state);
- renderer.drawRoundedRect(trackBounds, trackColor, trackStyle.cornerRadii);
-
- f32 thumbX = trackX + normalizedValue * trackWidth - thumbSize_ * 0.5f;
- f32 thumbY = bounds.y + (bounds.height - thumbSize_) * 0.5f;
-
- Rect thumbBounds{thumbX, thumbY, thumbSize_, thumbSize_};
- glm::vec4 thumbColor = thumbStyle.getBackgroundColor(state);
- renderer.drawRoundedRect(thumbBounds, thumbColor, thumbStyle.cornerRadii);
- } else {
- f32 trackWidth = trackThickness_;
- f32 trackHeight = bounds.height - padding.top - padding.bottom - thumbSize_;
- f32 trackX = bounds.x + (bounds.width - trackWidth) * 0.5f;
- f32 trackY = bounds.y + padding.top + thumbSize_ * 0.5f;
-
- Rect trackBounds{trackX, trackY, trackWidth, trackHeight};
- glm::vec4 trackColor = trackStyle.getBackgroundColor(state);
- renderer.drawRoundedRect(trackBounds, trackColor, trackStyle.cornerRadii);
-
- f32 thumbX = bounds.x + (bounds.width - thumbSize_) * 0.5f;
- f32 thumbY = trackY + (1.0f - normalizedValue) * trackHeight - thumbSize_ * 0.5f;
-
- Rect thumbBounds{thumbX, thumbY, thumbSize_, thumbSize_};
- glm::vec4 thumbColor = thumbStyle.getBackgroundColor(state);
- renderer.drawRoundedRect(thumbBounds, thumbColor, thumbStyle.cornerRadii);
- }
-}
-
-bool Slider::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- const Rect& bounds = getBounds();
- if (!bounds.contains(event.x, event.y)) {
- return false;
- }
-
- dragging_ = true;
- updateValueFromPosition(event.x, event.y);
-
- return true;
-}
-
-bool Slider::onMouseMove(const MouseMoveEvent& event) {
- if (!dragging_) {
- return false;
- }
-
- updateValueFromPosition(event.x, event.y);
- return true;
-}
-
-bool Slider::onMouseUp(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- dragging_ = false;
- return true;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-void Slider::updateValueFromPosition(f32 x, f32 y) {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- f32 normalizedValue = 0.0f;
-
- if (orientation_ == SliderOrientation::Horizontal) {
- f32 trackWidth = bounds.width - padding.left - padding.right - thumbSize_;
- f32 trackX = bounds.x + padding.left + thumbSize_ * 0.5f;
-
- f32 relativeX = x - trackX;
- normalizedValue = glm::clamp(relativeX / trackWidth, 0.0f, 1.0f);
- } else {
- f32 trackHeight = bounds.height - padding.top - padding.bottom - thumbSize_;
- f32 trackY = bounds.y + padding.top + thumbSize_ * 0.5f;
-
- f32 relativeY = y - trackY;
- normalizedValue = 1.0f - glm::clamp(relativeY / trackHeight, 0.0f, 1.0f);
- }
-
- f32 newValue = min_ + normalizedValue * (max_ - min_);
- setValue(newValue);
-}
-
-f32 Slider::quantizeValue(f32 value) const {
- if (step_ <= 0.0f) {
- return value;
- }
-
- f32 steps = std::round((value - min_) / step_);
- return min_ + steps * step_;
-}
-
-f32 Slider::getNormalizedValue() const {
- if (max_ <= min_) {
- return 0.0f;
- }
-
- return (value_ - min_) / (max_ - min_);
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Slider.hpp b/src/esengine/ui/widgets/Slider.hpp
deleted file mode 100644
index ab69f8fa7..000000000
--- a/src/esengine/ui/widgets/Slider.hpp
+++ /dev/null
@@ -1,212 +0,0 @@
-/**
- * @file Slider.hpp
- * @brief Slider widget for numeric input
- * @details Provides a draggable slider for selecting values within a range.
- * Supports both horizontal and vertical orientations with optional
- * step quantization.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../../events/Signal.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Slider Orientation
-// =============================================================================
-
-/**
- * @brief Slider orientation
- */
-enum class SliderOrientation : u8 {
- Horizontal,
- Vertical
-};
-
-// =============================================================================
-// Slider Class
-// =============================================================================
-
-/**
- * @brief Slider widget for numeric value selection
- *
- * @details Renders a track with a draggable thumb. Clicking the track
- * jumps the value to that position. Dragging adjusts continuously.
- *
- * @code
- * auto slider = makeUnique<Slider>(WidgetId("volume"));
- * slider->setRange(0.0f, 1.0f);
- * slider->setValue(0.5f);
- * slider->onValueChanged.connect([](f32 value) {
- * ES_LOG_INFO("Volume: {}", value);
- * });
- * @endcode
- */
-class Slider : public Widget {
-public:
- /**
- * @brief Constructs a slider widget
- * @param id Unique widget identifier
- * @param orientation Slider orientation (default horizontal)
- */
- explicit Slider(const WidgetId& id, SliderOrientation orientation = SliderOrientation::Horizontal);
-
- ~Slider() override = default;
-
- // =========================================================================
- // Value Management
- // =========================================================================
-
- /**
- * @brief Sets the current value
- * @param value New value (clamped to range)
- */
- void setValue(f32 value);
-
- /**
- * @brief Gets the current value
- * @return Current value
- */
- f32 getValue() const { return value_; }
-
- /**
- * @brief Sets the value range
- * @param min Minimum value
- * @param max Maximum value
- */
- void setRange(f32 min, f32 max);
-
- /**
- * @brief Gets the minimum value
- * @return Minimum value
- */
- f32 getMin() const { return min_; }
-
- /**
- * @brief Gets the maximum value
- * @return Maximum value
- */
- f32 getMax() const { return max_; }
-
- /**
- * @brief Sets the step size for quantization
- * @param step Step size (0 for continuous)
- */
- void setStep(f32 step);
-
- /**
- * @brief Gets the step size
- * @return Step size
- */
- f32 getStep() const { return step_; }
-
- // =========================================================================
- // Orientation
- // =========================================================================
-
- /**
- * @brief Sets the slider orientation
- * @param orientation Horizontal or Vertical
- */
- void setOrientation(SliderOrientation orientation);
-
- /**
- * @brief Gets the slider orientation
- * @return Current orientation
- */
- SliderOrientation getOrientation() const { return orientation_; }
-
- // =========================================================================
- // Appearance
- // =========================================================================
-
- /**
- * @brief Sets the track thickness
- * @param thickness Track thickness in pixels (default 4.0f)
- */
- void setTrackThickness(f32 thickness);
-
- /**
- * @brief Gets the track thickness
- * @return Track thickness in pixels
- */
- f32 getTrackThickness() const { return trackThickness_; }
-
- /**
- * @brief Sets the thumb size
- * @param size Thumb diameter in pixels (default 16.0f)
- */
- void setThumbSize(f32 size);
-
- /**
- * @brief Gets the thumb size
- * @return Thumb diameter in pixels
- */
- f32 getThumbSize() const { return thumbSize_; }
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(class UIBatchRenderer& renderer) override;
-
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /**
- * @brief Emitted when the value changes
- * @param value New value
- */
- Signal<void(f32)> onValueChanged;
-
-private:
- /**
- * @brief Updates value from mouse position
- * @param x Mouse X coordinate
- * @param y Mouse Y coordinate
- */
- void updateValueFromPosition(f32 x, f32 y);
-
- /**
- * @brief Quantizes value to step size
- * @param value Raw value
- * @return Quantized value
- */
- f32 quantizeValue(f32 value) const;
-
- /**
- * @brief Gets the normalized value (0-1)
- * @return Normalized value
- */
- f32 getNormalizedValue() const;
-
- f32 value_ = 0.0f;
- f32 min_ = 0.0f;
- f32 max_ = 1.0f;
- f32 step_ = 0.0f;
-
- SliderOrientation orientation_ = SliderOrientation::Horizontal;
- f32 trackThickness_ = 4.0f;
- f32 thumbSize_ = 16.0f;
-
- bool dragging_ = false;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/TextField.cpp b/src/esengine/ui/widgets/TextField.cpp
deleted file mode 100644
index 7bd4a3b15..000000000
--- a/src/esengine/ui/widgets/TextField.cpp
+++ /dev/null
@@ -1,657 +0,0 @@
-/**
- * @file TextField.cpp
- * @brief Single-line text input widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "TextField.hpp"
-#include "../UIContext.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../../core/Log.hpp"
-#include "../../math/Math.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-TextField::TextField(const WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// Text Management
-// =============================================================================
-
-void TextField::setText(const std::string& text) {
- if (text_ == text) {
- return;
- }
-
- text_ = text;
- cursorPos_ = text_.size();
- clearSelection();
- clampCursor();
-
- onTextChanged.publish(text_);
-}
-
-void TextField::setPlaceholder(const std::string& placeholder) {
- placeholder_ = placeholder;
-}
-
-// =============================================================================
-// Cursor & Selection
-// =============================================================================
-
-void TextField::setCursorPosition(usize position) {
- cursorPos_ = glm::min(position, text_.size());
- clearSelection();
-}
-
-void TextField::setSelection(usize start, usize end) {
- selectionStart_ = glm::min(start, text_.size());
- selectionEnd_ = glm::min(end, text_.size());
-
- if (selectionStart_ > selectionEnd_) {
- std::swap(selectionStart_, selectionEnd_);
- }
-
- cursorPos_ = selectionEnd_;
-}
-
-void TextField::clearSelection() {
- selectionStart_ = cursorPos_;
- selectionEnd_ = cursorPos_;
-}
-
-std::string TextField::getSelectedText() const {
- if (!hasSelection()) {
- return "";
- }
-
- usize start = glm::min(selectionStart_, selectionEnd_);
- usize end = glm::max(selectionStart_, selectionEnd_);
-
- return text_.substr(start, end - start);
-}
-
-// =============================================================================
-// Widget Interface
-// =============================================================================
-
-glm::vec2 TextField::measure(f32 availableWidth, f32 availableHeight) {
- f32 fontSize = 14.0f;
- if (getContext()) {
- fontSize = getContext()->getTheme().typography.fontSizeNormal;
- }
-
- f32 contentHeight = fontSize + TEXT_PADDING * 2.0f;
-
- f32 width = getWidth().resolve(availableWidth, availableWidth);
- f32 height = getHeight().resolve(availableHeight, contentHeight);
-
- const SizeConstraints& constraints = getConstraints();
- width = constraints.constrainWidth(width);
- height = constraints.constrainHeight(height);
-
- return glm::vec2(width, height);
-}
-
-void TextField::render(UIBatchRenderer& renderer) {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- WidgetStyle style;
- if (getContext()) {
- style = getContext()->getTheme().getTextInputStyle();
- }
-
- WidgetState state{
- .hovered = isHovered(),
- .pressed = false,
- .focused = isFocused(),
- .disabled = !isEnabled(),
- .visible = true
- };
-
- glm::vec4 bgColor = style.getBackgroundColor(state);
- glm::vec4 borderColor = style.getBorderColor(state);
- glm::vec4 textColor = style.getTextColor(state);
-
- renderer.drawRect(bounds, bgColor);
-
- if (style.borderWidth > 0.0f) {
- renderer.drawRoundedRectOutline(bounds, borderColor, style.cornerRadii, style.borderWidth);
- }
-
- f32 fontSize = style.fontSize;
- if (getContext()) {
- fontSize = getContext()->getTheme().typography.fontSizeNormal;
- }
-
- f32 textX = bounds.x + padding.left + TEXT_PADDING - textOffsetX_;
-
- f32 lineHeight = fontSize;
-#if ES_FEATURE_SDF_FONT
- if (getContext() && getContext()->getDefaultMSDFFont()) {
- MSDFFont* font = getContext()->getDefaultMSDFFont();
- f32 scale = fontSize / font->getFontSize();
- lineHeight = font->getLineHeight() * scale;
- }
-#elif !ES_FEATURE_BITMAP_FONT
- if (getContext() && getContext()->getDefaultSystemFont()) {
- SystemFont* font = getContext()->getDefaultSystemFont();
- f32 scale = fontSize / font->getFontSize();
- lineHeight = font->getLineHeight() * scale;
- }
-#endif
- f32 textY = bounds.y + (bounds.height - lineHeight) * 0.5f;
-
- Rect contentArea{
- bounds.x + padding.left,
- bounds.y + padding.top,
- bounds.width - padding.left - padding.right,
- bounds.height - padding.top - padding.bottom
- };
- renderer.pushClipRect(contentArea);
-
- if (text_.empty() && !isFocused() && !placeholder_.empty()) {
- glm::vec4 placeholderColor = textColor;
- placeholderColor.a *= 0.5f;
-
-#if ES_FEATURE_SDF_FONT
- if (getContext() && getContext()->getDefaultMSDFFont()) {
- renderer.drawText(placeholder_, glm::vec2(textX, textY),
- *getContext()->getDefaultMSDFFont(), fontSize, placeholderColor);
- }
-#elif ES_FEATURE_BITMAP_FONT
- if (getContext() && getContext()->getDefaultBitmapFont()) {
- renderer.drawText(placeholder_, glm::vec2(textX, textY),
- *getContext()->getDefaultBitmapFont(), fontSize, placeholderColor);
- }
-#else
- if (getContext() && getContext()->getDefaultSystemFont()) {
- renderer.drawText(placeholder_, glm::vec2(textX, textY),
- *getContext()->getDefaultSystemFont(), fontSize, placeholderColor);
- }
-#endif
- } else if (!text_.empty()) {
- if (hasSelection()) {
- usize start = glm::min(selectionStart_, selectionEnd_);
- usize end = glm::max(selectionStart_, selectionEnd_);
-
- f32 selStartX = getXForCharIndex(start);
- f32 selEndX = getXForCharIndex(end);
-
- glm::vec4 selectionColor = glm::vec4(0.3f, 0.5f, 0.8f, 0.4f);
- if (getContext()) {
- selectionColor = getContext()->getTheme().colors.selection;
- }
-
- Rect selRect{
- bounds.x + padding.left + TEXT_PADDING + selStartX - textOffsetX_,
- bounds.y + padding.top,
- selEndX - selStartX,
- bounds.height - padding.top - padding.bottom
- };
- renderer.drawRect(selRect, selectionColor);
- }
-
-#if ES_FEATURE_SDF_FONT
- if (getContext() && getContext()->getDefaultMSDFFont()) {
- renderer.drawText(text_, glm::vec2(textX, textY),
- *getContext()->getDefaultMSDFFont(), fontSize, textColor);
- }
-#elif ES_FEATURE_BITMAP_FONT
- if (getContext() && getContext()->getDefaultBitmapFont()) {
- renderer.drawText(text_, glm::vec2(textX, textY),
- *getContext()->getDefaultBitmapFont(), fontSize, textColor);
- }
-#else
- if (getContext() && getContext()->getDefaultSystemFont()) {
- renderer.drawText(text_, glm::vec2(textX, textY),
- *getContext()->getDefaultSystemFont(), fontSize, textColor);
- }
-#endif
- }
-
- if (isFocused()) {
- f32 cursorX = getXForCharIndex(cursorPos_);
- cursorX = bounds.x + padding.left + TEXT_PADDING + cursorX - textOffsetX_;
-
- Rect cursorRect{
- cursorX,
- bounds.y + padding.top + 2.0f,
- CURSOR_WIDTH,
- bounds.height - padding.top - padding.bottom - 4.0f
- };
-
- renderer.drawRect(cursorRect, textColor);
- }
-
- renderer.popClipRect();
-}
-
-bool TextField::onMouseDown(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- const Rect& bounds = getBounds();
- if (!bounds.contains(event.x, event.y)) {
- return false;
- }
-
- usize clickPos = getCharIndexAtX(event.x);
- cursorPos_ = clickPos;
-
- if (!event.shift) {
- clearSelection();
- dragStartPos_ = cursorPos_;
- } else {
- selectionEnd_ = cursorPos_;
- }
-
- isDragging_ = true;
-
- return true;
-}
-
-bool TextField::onMouseMove(const MouseMoveEvent& event) {
- if (!isDragging_) {
- return false;
- }
-
- usize movePos = getCharIndexAtX(event.x);
- cursorPos_ = movePos;
-
- selectionStart_ = glm::min(dragStartPos_, cursorPos_);
- selectionEnd_ = glm::max(dragStartPos_, cursorPos_);
-
- return true;
-}
-
-bool TextField::onMouseUp(const MouseButtonEvent& event) {
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- isDragging_ = false;
- return true;
-}
-
-bool TextField::onKeyDown(const KeyEvent& event) {
- if (!isFocused()) {
- return false;
- }
-
- bool ctrl = event.ctrl;
- bool shift = event.shift;
-
- switch (event.key) {
- case KeyCode::Left:
- if (ctrl) {
- moveCursorByWord(false, shift);
- } else {
- moveCursor(-1, shift);
- }
- return true;
-
- case KeyCode::Right:
- if (ctrl) {
- moveCursorByWord(true, shift);
- } else {
- moveCursor(1, shift);
- }
- return true;
-
- case KeyCode::Home:
- moveCursorToLineEdge(false, shift);
- return true;
-
- case KeyCode::End:
- moveCursorToLineEdge(true, shift);
- return true;
-
- case KeyCode::Backspace:
- deleteText(false);
- return true;
-
- case KeyCode::Delete:
- deleteText(true);
- return true;
-
- case KeyCode::Enter:
- onSubmit.publish(text_);
- return true;
-
- case KeyCode::A:
- if (ctrl) {
- setSelection(0, text_.size());
- return true;
- }
- break;
-
- case KeyCode::C:
- if (ctrl) {
- copyToClipboard();
- return true;
- }
- break;
-
- case KeyCode::V:
- if (ctrl) {
- pasteFromClipboard();
- return true;
- }
- break;
-
- case KeyCode::X:
- if (ctrl) {
- cutToClipboard();
- return true;
- }
- break;
-
- default:
- break;
- }
-
- return false;
-}
-
-bool TextField::onTextInput(const TextInputEvent& event) {
- if (!isFocused()) {
- return false;
- }
-
- insertText(event.text);
- return true;
-}
-
-// =============================================================================
-// Internal Methods
-// =============================================================================
-
-void TextField::insertText(const std::string& text) {
- if (text.empty()) {
- return;
- }
-
- if (hasSelection()) {
- usize start = glm::min(selectionStart_, selectionEnd_);
- usize end = glm::max(selectionStart_, selectionEnd_);
-
- text_.erase(start, end - start);
- cursorPos_ = start;
- clearSelection();
- }
-
- text_.insert(cursorPos_, text);
- cursorPos_ += text.size();
-
- onTextChanged.publish(text_);
-}
-
-void TextField::deleteText(bool deleteForward) {
- if (hasSelection()) {
- usize start = glm::min(selectionStart_, selectionEnd_);
- usize end = glm::max(selectionStart_, selectionEnd_);
-
- text_.erase(start, end - start);
- cursorPos_ = start;
- clearSelection();
-
- onTextChanged.publish(text_);
- return;
- }
-
- if (deleteForward) {
- if (cursorPos_ < text_.size()) {
- text_.erase(cursorPos_, 1);
- onTextChanged.publish(text_);
- }
- } else {
- if (cursorPos_ > 0) {
- text_.erase(cursorPos_ - 1, 1);
- cursorPos_--;
- onTextChanged.publish(text_);
- }
- }
-}
-
-void TextField::moveCursor(i32 offset, bool extendSelection) {
- if (!extendSelection && hasSelection() && offset != 0) {
- if (offset < 0) {
- cursorPos_ = glm::min(selectionStart_, selectionEnd_);
- } else {
- cursorPos_ = glm::max(selectionStart_, selectionEnd_);
- }
- clearSelection();
- return;
- }
-
- usize oldPos = cursorPos_;
-
- if (offset < 0) {
- usize absOffset = static_cast<usize>(-offset);
- if (cursorPos_ >= absOffset) {
- cursorPos_ -= absOffset;
- } else {
- cursorPos_ = 0;
- }
- } else {
- cursorPos_ += static_cast<usize>(offset);
- }
-
- clampCursor();
-
- if (extendSelection) {
- if (!hasSelection()) {
- selectionStart_ = oldPos;
- }
- selectionEnd_ = cursorPos_;
- } else {
- clearSelection();
- }
-}
-
-void TextField::moveCursorByWord(bool forward, bool extendSelection) {
- if (text_.empty()) {
- return;
- }
-
- usize oldPos = cursorPos_;
-
- if (forward) {
- while (cursorPos_ < text_.size() && std::isspace(text_[cursorPos_])) {
- cursorPos_++;
- }
-
- while (cursorPos_ < text_.size() && !std::isspace(text_[cursorPos_])) {
- cursorPos_++;
- }
- } else {
- if (cursorPos_ > 0) {
- cursorPos_--;
- }
-
- while (cursorPos_ > 0 && std::isspace(text_[cursorPos_])) {
- cursorPos_--;
- }
-
- while (cursorPos_ > 0 && !std::isspace(text_[cursorPos_ - 1])) {
- cursorPos_--;
- }
- }
-
- if (extendSelection) {
- if (!hasSelection()) {
- selectionStart_ = oldPos;
- }
- selectionEnd_ = cursorPos_;
- } else {
- clearSelection();
- }
-}
-
-void TextField::moveCursorToLineEdge(bool toEnd, bool extendSelection) {
- usize oldPos = cursorPos_;
-
- cursorPos_ = toEnd ? text_.size() : 0;
-
- if (extendSelection) {
- if (!hasSelection()) {
- selectionStart_ = oldPos;
- }
- selectionEnd_ = cursorPos_;
- } else {
- clearSelection();
- }
-}
-
-void TextField::copyToClipboard() {
- if (!hasSelection()) {
- return;
- }
-
- std::string selectedText = getSelectedText();
- if (getContext()) {
- getContext()->setClipboardText(selectedText);
- }
-}
-
-void TextField::pasteFromClipboard() {
- if (!getContext()) {
- return;
- }
-
- std::string clipboardText = getContext()->getClipboardText();
- if (!clipboardText.empty()) {
- insertText(clipboardText);
- }
-}
-
-void TextField::cutToClipboard() {
- if (!hasSelection()) {
- return;
- }
-
- copyToClipboard();
- deleteText(true);
-}
-
-usize TextField::getCharIndexAtX(f32 x) const {
- if (!getContext()) {
- return 0;
- }
-
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- f32 relativeX = x - bounds.x - padding.left - TEXT_PADDING + textOffsetX_;
-
- if (relativeX <= 0.0f) {
- return 0;
- }
-
- f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
-
- f32 currentX = 0.0f;
- for (usize i = 0; i < text_.size(); ++i) {
- f32 charWidth = fontSize * 0.6f;
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = getContext()->getDefaultMSDFFont();
- if (font) {
- charWidth = font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = getContext()->getDefaultBitmapFont();
- if (font) {
- charWidth = font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- }
-#else
- SystemFont* font = getContext()->getDefaultSystemFont();
- if (font) {
- charWidth = font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- }
-#endif
-
- if (relativeX < currentX + charWidth * 0.5f) {
- return i;
- }
-
- currentX += charWidth;
- }
-
- return text_.size();
-}
-
-f32 TextField::getXForCharIndex(usize index) const {
- if (index == 0 || !getContext()) {
- return 0.0f;
- }
-
- f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* font = getContext()->getDefaultMSDFFont();
- if (font) {
- f32 currentX = 0.0f;
- for (usize i = 0; i < index && i < text_.size(); ++i) {
- currentX += font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- }
- return currentX;
- }
-#elif ES_FEATURE_BITMAP_FONT
- BitmapFont* font = getContext()->getDefaultBitmapFont();
- if (font) {
- f32 currentX = 0.0f;
- for (usize i = 0; i < index && i < text_.size(); ++i) {
- currentX += font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- }
- return currentX;
- }
-#else
- SystemFont* font = getContext()->getDefaultSystemFont();
- if (font) {
- f32 currentX = 0.0f;
- for (usize i = 0; i < index && i < text_.size(); ++i) {
- currentX += font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- }
- return currentX;
- }
-#endif
-
- f32 charWidth = fontSize * 0.6f;
- return static_cast<f32>(index) * charWidth;
-}
-
-void TextField::clampCursor() {
- cursorPos_ = glm::min(cursorPos_, text_.size());
-}
-
-void TextField::updateSelectionAnchor() {
- if (!hasSelection()) {
- selectionStart_ = cursorPos_;
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/TextField.hpp b/src/esengine/ui/widgets/TextField.hpp
deleted file mode 100644
index 26139e057..000000000
--- a/src/esengine/ui/widgets/TextField.hpp
+++ /dev/null
@@ -1,260 +0,0 @@
-/**
- * @file TextField.hpp
- * @brief Single-line text input widget
- * @details Provides text editing with cursor, selection, and clipboard support.
- * Features:
- * - Cursor positioning with blinking animation
- * - Text selection via mouse drag or Shift+arrows
- * - Clipboard operations (Ctrl+C/V/X)
- * - Cursor navigation (arrows, Home/End, Ctrl+left/right)
- * - Placeholder text for empty state
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../events/UIEvent.hpp"
-#include "../../events/Signal.hpp"
-
-#include <string>
-
-namespace esengine::ui {
-
-// =============================================================================
-// TextField Class
-// =============================================================================
-
-/**
- * @brief Single-line text input widget
- *
- * @details TextField provides a complete text editing experience with:
- * - Visual cursor with blinking animation (0.5s interval)
- * - Text selection (mouse drag or keyboard)
- * - Clipboard integration (copy/paste/cut)
- * - Keyboard navigation
- * - Placeholder text when empty
- *
- * @code
- * auto textField = makeUnique<TextField>(WidgetId("username"));
- * textField->setPlaceholder("Enter username...");
- * textField->onTextChanged.connect([](const std::string& text) {
- * ES_LOG_INFO("Text changed: {}", text);
- * });
- * textField->onSubmit.connect([](const std::string& text) {
- * ES_LOG_INFO("Submitted: {}", text);
- * });
- * @endcode
- */
-class TextField : public Widget {
-public:
- /**
- * @brief Constructs a text field widget
- * @param id Unique widget identifier
- */
- explicit TextField(const WidgetId& id);
-
- ~TextField() override = default;
-
- // =========================================================================
- // Text Management
- // =========================================================================
-
- /**
- * @brief Sets the text content
- * @param text New text value
- */
- void setText(const std::string& text);
-
- /**
- * @brief Gets the current text content
- * @return Current text value
- */
- const std::string& getText() const { return text_; }
-
- /**
- * @brief Sets the placeholder text shown when empty
- * @param placeholder Placeholder text
- */
- void setPlaceholder(const std::string& placeholder);
-
- /**
- * @brief Gets the placeholder text
- * @return Placeholder text
- */
- const std::string& getPlaceholder() const { return placeholder_; }
-
- // =========================================================================
- // Cursor & Selection
- // =========================================================================
-
- /**
- * @brief Sets the cursor position
- * @param position Character index (0-based)
- */
- void setCursorPosition(usize position);
-
- /**
- * @brief Gets the cursor position
- * @return Cursor character index
- */
- usize getCursorPosition() const { return cursorPos_; }
-
- /**
- * @brief Selects a range of text
- * @param start Start index (inclusive)
- * @param end End index (exclusive)
- */
- void setSelection(usize start, usize end);
-
- /**
- * @brief Clears the current selection
- */
- void clearSelection();
-
- /**
- * @brief Checks if there is a text selection
- * @return True if text is selected
- */
- bool hasSelection() const { return selectionStart_ != selectionEnd_; }
-
- /**
- * @brief Gets the selected text
- * @return Selected text or empty string if no selection
- */
- std::string getSelectedText() const;
-
- // =========================================================================
- // Widget Interface
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(class UIBatchRenderer& renderer) override;
-
- bool isFocusable() const override { return true; }
-
- bool onMouseDown(const MouseButtonEvent& event) override;
- bool onMouseMove(const MouseMoveEvent& event) override;
- bool onMouseUp(const MouseButtonEvent& event) override;
- bool onKeyDown(const KeyEvent& event) override;
- bool onTextInput(const TextInputEvent& event) override;
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /**
- * @brief Emitted when text content changes
- */
- Signal<void(const std::string&)> onTextChanged;
-
- /**
- * @brief Emitted when Enter key is pressed
- */
- Signal<void(const std::string&)> onSubmit;
-
-private:
- // =========================================================================
- // Internal Methods
- // =========================================================================
-
- /**
- * @brief Inserts text at cursor position
- * @param text Text to insert
- */
- void insertText(const std::string& text);
-
- /**
- * @brief Deletes selected text or character at cursor
- * @param deleteForward True to delete forward, false for backspace
- */
- void deleteText(bool deleteForward);
-
- /**
- * @brief Moves cursor by offset
- * @param offset Character offset (negative = left, positive = right)
- * @param extendSelection True to extend selection
- */
- void moveCursor(i32 offset, bool extendSelection);
-
- /**
- * @brief Moves cursor to word boundary
- * @param forward True to move forward, false for backward
- * @param extendSelection True to extend selection
- */
- void moveCursorByWord(bool forward, bool extendSelection);
-
- /**
- * @brief Moves cursor to line start or end
- * @param toEnd True to move to end, false for start
- * @param extendSelection True to extend selection
- */
- void moveCursorToLineEdge(bool toEnd, bool extendSelection);
-
- /**
- * @brief Copies selected text to clipboard
- */
- void copyToClipboard();
-
- /**
- * @brief Pastes text from clipboard
- */
- void pasteFromClipboard();
-
- /**
- * @brief Cuts selected text to clipboard
- */
- void cutToClipboard();
-
- /**
- * @brief Gets character index at screen position
- * @param x Screen X coordinate
- * @return Character index
- */
- usize getCharIndexAtX(f32 x) const;
-
- /**
- * @brief Gets screen X position for character index
- * @param index Character index
- * @return Screen X coordinate
- */
- f32 getXForCharIndex(usize index) const;
-
- /**
- * @brief Clamps cursor position to valid range
- */
- void clampCursor();
-
- /**
- * @brief Updates selection anchor when extending selection
- */
- void updateSelectionAnchor();
-
- // =========================================================================
- // Member Variables
- // =========================================================================
-
- std::string text_;
- std::string placeholder_;
-
- usize cursorPos_ = 0;
- usize selectionStart_ = 0;
- usize selectionEnd_ = 0;
-
- bool isDragging_ = false;
- usize dragStartPos_ = 0;
-
- f32 textOffsetX_ = 0.0f; // Horizontal scroll offset
- static constexpr f32 TEXT_PADDING = 8.0f;
- static constexpr f32 CURSOR_WIDTH = 1.0f;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/TreeView.cpp b/src/esengine/ui/widgets/TreeView.cpp
deleted file mode 100644
index a0370c516..000000000
--- a/src/esengine/ui/widgets/TreeView.cpp
+++ /dev/null
@@ -1,603 +0,0 @@
-/**
- * @file TreeView.cpp
- * @brief Tree view widget implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "TreeView.hpp"
-#include "../UIContext.hpp"
-#include "../icons/Icons.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../../core/Log.hpp"
-#include "../../math/Math.hpp"
-
-#if ES_FEATURE_SDF_FONT
-#include "../font/MSDFFont.hpp"
-#endif
-
-#if ES_FEATURE_BITMAP_FONT
-#include "../font/BitmapFont.hpp"
-#endif
-
-#include "../font/SystemFont.hpp"
-
-#include <algorithm>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor
-// =============================================================================
-
-TreeView::TreeView(const WidgetId& id) : Widget(id) {}
-
-// =============================================================================
-// Node Management
-// =============================================================================
-
-TreeNodeId TreeView::addNode(TreeNodeId parentId, const std::string& label) {
- TreeNodeId newId = generateNodeId();
-
- TreeNode node;
- node.id = newId;
- node.parentId = parentId;
- node.label = label;
- node.expanded = false;
-
- if (parentId == INVALID_TREE_NODE) {
- node.depth = 0;
- rootNodes_.push_back(newId);
- } else {
- TreeNode* parent = getNode(parentId);
- if (parent) {
- node.depth = parent->depth + 1;
- parent->children.push_back(newId);
- } else {
- ES_LOG_WARN("TreeView: Parent node {} not found", parentId);
- node.depth = 0;
- rootNodes_.push_back(newId);
- }
- }
-
- nodes_[newId] = node;
- visibleNodesDirty_ = true;
- invalidateLayout();
-
- return newId;
-}
-
-void TreeView::removeNode(TreeNodeId nodeId) {
- TreeNode* node = getNode(nodeId);
- if (!node) {
- return;
- }
-
- // Remove from parent's children
- if (node->parentId != INVALID_TREE_NODE) {
- TreeNode* parent = getNode(node->parentId);
- if (parent) {
- auto& children = parent->children;
- children.erase(std::remove(children.begin(), children.end(), nodeId), children.end());
- }
- } else {
- // Remove from root nodes
- rootNodes_.erase(std::remove(rootNodes_.begin(), rootNodes_.end(), nodeId),
- rootNodes_.end());
- }
-
- // Recursively remove children
- std::vector<TreeNodeId> childrenCopy = node->children;
- for (TreeNodeId childId : childrenCopy) {
- removeNode(childId);
- }
-
- // Remove from selection
- selectedNodes_.erase(nodeId);
-
- // Remove node
- nodes_.erase(nodeId);
-
- visibleNodesDirty_ = true;
- invalidateLayout();
-}
-
-void TreeView::clear() {
- nodes_.clear();
- rootNodes_.clear();
- visibleNodes_.clear();
- selectedNodes_.clear();
- visibleNodesDirty_ = true;
- invalidateLayout();
-}
-
-TreeNode* TreeView::getNode(TreeNodeId nodeId) {
- auto it = nodes_.find(nodeId);
- return it != nodes_.end() ? &it->second : nullptr;
-}
-
-const TreeNode* TreeView::getNode(TreeNodeId nodeId) const {
- auto it = nodes_.find(nodeId);
- return it != nodes_.end() ? &it->second : nullptr;
-}
-
-void TreeView::setNodeLabel(TreeNodeId nodeId, const std::string& label) {
- TreeNode* node = getNode(nodeId);
- if (node) {
- node->label = label;
- }
-}
-
-void TreeView::setNodeIcon(TreeNodeId nodeId, const std::string& icon) {
- TreeNode* node = getNode(nodeId);
- if (node) {
- node->icon = icon;
- }
-}
-
-void TreeView::setNodeType(TreeNodeId nodeId, const std::string& type) {
- TreeNode* node = getNode(nodeId);
- if (node) {
- node->type = type;
- }
-}
-
-void TreeView::setNodeVisible(TreeNodeId nodeId, bool visible) {
- TreeNode* node = getNode(nodeId);
- if (node) {
- node->visible = visible;
- }
-}
-
-// =============================================================================
-// Expand/Collapse
-// =============================================================================
-
-void TreeView::setNodeExpanded(TreeNodeId nodeId, bool expanded) {
- TreeNode* node = getNode(nodeId);
- if (!node || node->expanded == expanded) {
- return;
- }
-
- node->expanded = expanded;
- visibleNodesDirty_ = true;
- invalidateLayout();
-
- if (expanded) {
- onNodeExpanded.publish(nodeId);
- } else {
- onNodeCollapsed.publish(nodeId);
- }
-}
-
-void TreeView::toggleNodeExpanded(TreeNodeId nodeId) {
- TreeNode* node = getNode(nodeId);
- if (node) {
- setNodeExpanded(nodeId, !node->expanded);
- }
-}
-
-bool TreeView::isNodeExpanded(TreeNodeId nodeId) const {
- const TreeNode* node = getNode(nodeId);
- return node && node->expanded;
-}
-
-void TreeView::expandAll() {
- for (auto& pair : nodes_) {
- pair.second.expanded = true;
- }
- visibleNodesDirty_ = true;
- invalidateLayout();
-}
-
-void TreeView::collapseAll() {
- for (auto& pair : nodes_) {
- pair.second.expanded = false;
- }
- visibleNodesDirty_ = true;
- invalidateLayout();
-}
-
-// =============================================================================
-// Selection
-// =============================================================================
-
-void TreeView::selectNode(TreeNodeId nodeId, bool clearPrevious) {
- if (!getNode(nodeId)) {
- return;
- }
-
- if (clearPrevious && !multiSelect_) {
- auto previousSelection = selectedNodes_;
- selectedNodes_.clear();
-
- for (TreeNodeId prevId : previousSelection) {
- onNodeDeselected.publish(prevId);
- }
- }
-
- if (selectedNodes_.insert(nodeId).second) {
- onNodeSelected.publish(nodeId);
- }
-}
-
-void TreeView::deselectNode(TreeNodeId nodeId) {
- if (selectedNodes_.erase(nodeId) > 0) {
- onNodeDeselected.publish(nodeId);
- }
-}
-
-void TreeView::clearSelection() {
- auto previousSelection = selectedNodes_;
- selectedNodes_.clear();
-
- for (TreeNodeId nodeId : previousSelection) {
- onNodeDeselected.publish(nodeId);
- }
-}
-
-bool TreeView::isNodeSelected(TreeNodeId nodeId) const {
- return selectedNodes_.count(nodeId) > 0;
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-glm::vec2 TreeView::measure(f32 availableWidth, f32 availableHeight) {
- (void)availableHeight;
-
- if (visibleNodesDirty_) {
- rebuildVisibleNodes();
- }
-
- f32 contentHeight = static_cast<f32>(visibleNodes_.size()) * rowHeight_;
-
- const SizeConstraints& constraints = getConstraints();
- f32 width = glm::clamp(availableWidth, constraints.minWidth, constraints.maxWidth);
- f32 height = glm::clamp(contentHeight, constraints.minHeight, constraints.maxHeight);
-
- return glm::vec2(width, height);
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void TreeView::render(UIBatchRenderer& renderer) {
- if (visibleNodesDirty_) {
- rebuildVisibleNodes();
- }
-
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- f32 y = bounds.y + padding.top;
-
- for (TreeNodeId nodeId : visibleNodes_) {
- const TreeNode* node = getNode(nodeId);
- if (!node) {
- continue;
- }
-
- bool isHovered = (hoveredNode_ == nodeId);
- renderNode(renderer, *node, y, isHovered);
-
- y += rowHeight_;
- }
-}
-
-void TreeView::renderNode(UIBatchRenderer& renderer, const TreeNode& node, f32 y,
- bool isHovered) {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- constexpr f32 ROW_PADDING_X = 8.0f;
- constexpr f32 ICON_SIZE = 14.0f;
- constexpr f32 ARROW_SIZE = 16.0f;
- constexpr f32 FONT_SIZE = 12.0f;
- constexpr f32 TYPE_COLUMN_WIDTH = 80.0f;
- constexpr f32 VISIBILITY_COLUMN_WIDTH = 20.0f;
-
- constexpr glm::vec4 hoverBg{0.165f, 0.176f, 0.180f, 1.0f};
- constexpr glm::vec4 selectedBg{0.216f, 0.216f, 0.239f, 1.0f};
- constexpr glm::vec4 textColor{0.8f, 0.8f, 0.8f, 1.0f};
- constexpr glm::vec4 dimTextColor{0.5f, 0.5f, 0.5f, 1.0f};
- constexpr glm::vec4 arrowColor{0.8f, 0.8f, 0.8f, 1.0f};
- constexpr glm::vec4 folderColor{0.863f, 0.714f, 0.478f, 1.0f};
- constexpr glm::vec4 entityIconColor{0.525f, 0.725f, 0.855f, 1.0f};
- constexpr glm::vec4 visibleIconColor{0.5f, 0.5f, 0.5f, 1.0f};
- constexpr glm::vec4 hiddenIconColor{0.3f, 0.3f, 0.3f, 1.0f};
-
- f32 rowWidth = bounds.width - padding.left - padding.right;
- Rect rowBounds{bounds.x + padding.left, y, rowWidth, rowHeight_};
-
- bool isSelected = isNodeSelected(node.id);
-
- if (isSelected) {
- renderer.drawRect(rowBounds, selectedBg);
- } else if (isHovered) {
- renderer.drawRect(rowBounds, hoverBg);
- }
-
-#if ES_FEATURE_SDF_FONT
- MSDFFont* iconFont = getContext() ? getContext()->getIconMSDFFont() : nullptr;
- MSDFFont* textFont = getContext() ? getContext()->getDefaultMSDFFont() : nullptr;
-
- f32 x = bounds.x + padding.left + ROW_PADDING_X;
-
- if (showVisibilityColumn_) {
- if (iconFont) {
- Rect eyeBounds{x, y + (rowHeight_ - ICON_SIZE) * 0.5f, ICON_SIZE, ICON_SIZE};
- const char* eyeIcon = node.visible ? icons::Eye : icons::EyeOff;
- glm::vec4 eyeColor = node.visible ? visibleIconColor : hiddenIconColor;
- renderer.drawTextInBounds(eyeIcon, eyeBounds, *iconFont, 12.0f, eyeColor,
- HAlign::Center, VAlign::Center);
- }
- x += VISIBILITY_COLUMN_WIDTH;
- }
-
- // Indent + expand arrow
- x += static_cast<f32>(node.depth) * indentSize_;
-
- bool hasChild = hasChildren(node);
- Rect arrowBounds{x, y + (rowHeight_ - ARROW_SIZE) * 0.5f, ARROW_SIZE, ARROW_SIZE};
-
- if (iconFont && hasChild) {
- const char* arrowIcon = node.expanded ? icons::ChevronDown : icons::ChevronRight;
- renderer.drawTextInBounds(arrowIcon, arrowBounds, *iconFont, 12.0f, arrowColor,
- HAlign::Center, VAlign::Center);
- }
- x += ARROW_SIZE + 2.0f;
-
- // Entity icon
- if (iconFont) {
- Rect iconBounds{x, y + (rowHeight_ - ICON_SIZE) * 0.5f, ICON_SIZE, ICON_SIZE};
-
- if (!node.icon.empty()) {
- renderer.drawTextInBounds(node.icon, iconBounds, *iconFont, 14.0f, entityIconColor,
- HAlign::Center, VAlign::Center);
- } else {
- const char* folderIcon = hasChild && node.expanded ? icons::FolderOpen : icons::Folder;
- renderer.drawTextInBounds(folderIcon, iconBounds, *iconFont, 14.0f, folderColor,
- HAlign::Center, VAlign::Center);
- }
- }
- x += ICON_SIZE + 6.0f;
-
- // Label
- f32 typeColumnSpace = showTypeColumn_ ? TYPE_COLUMN_WIDTH : 0.0f;
- f32 labelMaxWidth = bounds.x + bounds.width - padding.right - typeColumnSpace - x;
- f32 textY = y + (rowHeight_ - FONT_SIZE) * 0.5f;
-
- if (textFont && labelMaxWidth > 0) {
- Rect labelClipRect{x, y, labelMaxWidth, rowHeight_};
- renderer.pushClipRect(labelClipRect);
- renderer.drawText(node.label, glm::vec2(x, textY), *textFont, FONT_SIZE, textColor);
- renderer.popClipRect();
- }
-
- if (showTypeColumn_ && textFont && !node.type.empty()) {
- f32 typeX = bounds.x + bounds.width - padding.right - TYPE_COLUMN_WIDTH;
- renderer.drawText(node.type, glm::vec2(typeX, textY), *textFont, 11.0f, dimTextColor);
- }
-
-#elif ES_FEATURE_BITMAP_FONT
- f32 x = bounds.x + padding.left + ROW_PADDING_X + static_cast<f32>(node.depth) * indentSize_;
- f32 textY = y + (rowHeight_ - FONT_SIZE) * 0.5f;
- if (getContext() && getContext()->getDefaultBitmapFont()) {
- renderer.drawText(node.label, glm::vec2(x, textY), *getContext()->getDefaultBitmapFont(),
- FONT_SIZE, textColor);
- }
-#else
- SystemFont* iconFont = getContext() ? getContext()->getIconSystemFont() : nullptr;
- SystemFont* textFont = getContext() ? getContext()->getDefaultSystemFont() : nullptr;
-
- f32 x = bounds.x + padding.left + ROW_PADDING_X;
-
- if (showVisibilityColumn_) {
- if (iconFont) {
- Rect eyeBounds{x, y + (rowHeight_ - ICON_SIZE) * 0.5f, ICON_SIZE, ICON_SIZE};
- const char* eyeIcon = node.visible ? icons::Eye : icons::EyeOff;
- glm::vec4 eyeColor = node.visible ? visibleIconColor : hiddenIconColor;
- renderer.drawTextInBounds(eyeIcon, eyeBounds, *iconFont, 12.0f, eyeColor,
- HAlign::Center, VAlign::Center);
- }
- x += VISIBILITY_COLUMN_WIDTH;
- }
-
- x += static_cast<f32>(node.depth) * indentSize_;
-
- bool hasChild = hasChildren(node);
- Rect arrowBounds{x, y + (rowHeight_ - ARROW_SIZE) * 0.5f, ARROW_SIZE, ARROW_SIZE};
-
- if (iconFont && hasChild) {
- const char* arrowIcon = node.expanded ? icons::ChevronDown : icons::ChevronRight;
- renderer.drawTextInBounds(arrowIcon, arrowBounds, *iconFont, 12.0f, arrowColor,
- HAlign::Center, VAlign::Center);
- }
- x += ARROW_SIZE + 2.0f;
-
- if (iconFont) {
- Rect iconBounds{x, y + (rowHeight_ - ICON_SIZE) * 0.5f, ICON_SIZE, ICON_SIZE};
-
- if (!node.icon.empty()) {
- renderer.drawTextInBounds(node.icon, iconBounds, *iconFont, 14.0f, entityIconColor,
- HAlign::Center, VAlign::Center);
- } else {
- const char* folderIcon = hasChild && node.expanded ? icons::FolderOpen : icons::Folder;
- renderer.drawTextInBounds(folderIcon, iconBounds, *iconFont, 14.0f, folderColor,
- HAlign::Center, VAlign::Center);
- }
- }
- x += ICON_SIZE + 6.0f;
-
- f32 typeColumnSpace = showTypeColumn_ ? TYPE_COLUMN_WIDTH : 0.0f;
- f32 labelMaxWidth = bounds.x + bounds.width - padding.right - typeColumnSpace - x;
- f32 textY = y + (rowHeight_ - FONT_SIZE) * 0.5f;
-
- if (textFont && labelMaxWidth > 0) {
- Rect labelClipRect{x, y, labelMaxWidth, rowHeight_};
- renderer.pushClipRect(labelClipRect);
- renderer.drawText(node.label, glm::vec2(x, textY), *textFont, FONT_SIZE, textColor);
- renderer.popClipRect();
- }
-
- if (showTypeColumn_ && textFont && !node.type.empty()) {
- f32 typeX = bounds.x + bounds.width - padding.right - TYPE_COLUMN_WIDTH;
- renderer.drawText(node.type, glm::vec2(typeX, textY), *textFont, 11.0f, dimTextColor);
- }
-#endif
-}
-
-// =============================================================================
-// Event Handling
-// =============================================================================
-
-bool TreeView::onMouseDown(const MouseButtonEvent& event) {
- if (visibleNodesDirty_) {
- rebuildVisibleNodes();
- }
-
- TreeNodeId clickedNode = getNodeAtY(event.y);
- if (clickedNode == INVALID_TREE_NODE) {
- return false;
- }
-
- const TreeNode* node = getNode(clickedNode);
- if (!node) {
- return false;
- }
-
- if (event.button == MouseButton::Right) {
- selectNode(clickedNode, true);
- onNodeRightClicked.publish(clickedNode, event.x, event.y);
- return true;
- }
-
- if (event.button != MouseButton::Left) {
- return false;
- }
-
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- usize index = 0;
- for (; index < visibleNodes_.size(); ++index) {
- if (visibleNodes_[index] == clickedNode) {
- break;
- }
- }
-
- if (index >= visibleNodes_.size()) {
- return false;
- }
-
- f32 y = bounds.y + padding.top + static_cast<f32>(index) * rowHeight_;
-
- if (hasChildren(*node)) {
- Rect iconBounds = getIconBounds(*node, y);
- if (iconBounds.contains(event.x, event.y)) {
- toggleNodeExpanded(clickedNode);
- return true;
- }
- }
-
- bool isDoubleClick = (clickedNode == lastClickedNode_);
-
- if (isDoubleClick) {
- onNodeDoubleClicked.publish(clickedNode);
-
- if (hasChildren(*node)) {
- toggleNodeExpanded(clickedNode);
- }
-
- lastClickedNode_ = INVALID_TREE_NODE;
- } else {
- selectNode(clickedNode, true);
- onNodeClicked.publish(clickedNode);
-
- lastClickedNode_ = clickedNode;
- }
-
- return true;
-}
-
-// =============================================================================
-// Private Methods
-// =============================================================================
-
-TreeNodeId TreeView::generateNodeId() {
- return nextNodeId_++;
-}
-
-void TreeView::rebuildVisibleNodes() {
- visibleNodes_.clear();
-
- for (TreeNodeId rootId : rootNodes_) {
- addVisibleNodesRecursive(rootId);
- }
-
- visibleNodesDirty_ = false;
-}
-
-void TreeView::addVisibleNodesRecursive(TreeNodeId nodeId) {
- visibleNodes_.push_back(nodeId);
-
- const TreeNode* node = getNode(nodeId);
- if (!node || !node->expanded) {
- return;
- }
-
- for (TreeNodeId childId : node->children) {
- addVisibleNodesRecursive(childId);
- }
-}
-
-TreeNodeId TreeView::getNodeAtY(f32 y) const {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- f32 relativeY = y - bounds.y - padding.top;
-
- if (relativeY < 0.0f) {
- return INVALID_TREE_NODE;
- }
-
- usize index = static_cast<usize>(relativeY / rowHeight_);
-
- if (index >= visibleNodes_.size()) {
- return INVALID_TREE_NODE;
- }
-
- return visibleNodes_[index];
-}
-
-Rect TreeView::getIconBounds(const TreeNode& node, f32 y) const {
- const Rect& bounds = getBounds();
- const Insets& padding = getPadding();
-
- constexpr f32 ROW_PADDING_X = 8.0f;
- constexpr f32 ARROW_SIZE = 16.0f;
- constexpr f32 VISIBILITY_COLUMN_WIDTH = 20.0f;
-
- f32 x = bounds.x + padding.left + ROW_PADDING_X + VISIBILITY_COLUMN_WIDTH
- + static_cast<f32>(node.depth) * indentSize_;
-
- return Rect{
- x,
- y + (rowHeight_ - ARROW_SIZE) * 0.5f,
- ARROW_SIZE,
- ARROW_SIZE
- };
-}
-
-bool TreeView::hasChildren(const TreeNode& node) const {
- return !node.children.empty();
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/TreeView.hpp b/src/esengine/ui/widgets/TreeView.hpp
deleted file mode 100644
index 06ae4d2fa..000000000
--- a/src/esengine/ui/widgets/TreeView.hpp
+++ /dev/null
@@ -1,397 +0,0 @@
-/**
- * @file TreeView.hpp
- * @brief Tree view widget for hierarchical data
- * @details A widget that displays hierarchical data in a tree structure with
- * expandable/collapsible nodes, selection, and customizable rendering.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "Widget.hpp"
-#include "../../events/Signal.hpp"
-
-#include <functional>
-#include <unordered_set>
-#include <vector>
-
-namespace esengine::ui {
-
-// =============================================================================
-// TreeNodeId
-// =============================================================================
-
-/**
- * @brief Unique identifier for tree nodes
- */
-using TreeNodeId = u64;
-
-constexpr TreeNodeId INVALID_TREE_NODE = 0;
-
-// =============================================================================
-// TreeNode
-// =============================================================================
-
-/**
- * @brief Represents a node in the tree
- *
- * @details TreeNode is a lightweight value type that represents a node's
- * identity and state. The actual data is stored externally and
- * accessed via callbacks.
- */
-struct TreeNode {
- TreeNodeId id = INVALID_TREE_NODE; ///< Unique node identifier
- TreeNodeId parentId = INVALID_TREE_NODE; ///< Parent node ID
- std::string label; ///< Display label
- std::string icon; ///< Icon Unicode character
- std::string type; ///< Type label for right column
- std::vector<TreeNodeId> children; ///< Child node IDs
- bool expanded = false; ///< Expanded state
- bool visible = true; ///< Visibility state for eye icon
- u32 depth = 0; ///< Depth in tree (0 = root)
-};
-
-// =============================================================================
-// TreeView Class
-// =============================================================================
-
-/**
- * @brief Tree view widget for displaying hierarchical data
- *
- * @details TreeView displays hierarchical data with expand/collapse functionality.
- * It supports:
- * - Single and multi-selection
- * - Expand/collapse with visual indicators
- * - Customizable node rendering
- * - Click and double-click events
- * - Keyboard navigation (future)
- *
- * @code
- * auto tree = makeUnique<TreeView>(WidgetId("tree"));
- *
- * // Add root node
- * TreeNodeId root = tree->addNode(INVALID_TREE_NODE, "Root");
- * tree->addNode(root, "Child 1");
- * tree->addNode(root, "Child 2");
- *
- * // Handle selection
- * tree->onNodeSelected.connect([](TreeNodeId nodeId) {
- * ES_LOG_INFO("Selected: {}", nodeId);
- * });
- *
- * // Expand root
- * tree->setNodeExpanded(root, true);
- * @endcode
- */
-class TreeView : public Widget {
-public:
- /**
- * @brief Creates a tree view
- * @param id Widget identifier
- */
- explicit TreeView(const WidgetId& id);
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /**
- * @brief Sets whether multiple nodes can be selected
- * @param multiSelect True to enable multi-selection
- */
- void setMultiSelect(bool multiSelect) { multiSelect_ = multiSelect; }
-
- /**
- * @brief Returns true if multi-selection is enabled
- */
- bool isMultiSelect() const { return multiSelect_; }
-
- /**
- * @brief Sets the indent size per level
- * @param indent Indent in pixels
- */
- void setIndentSize(f32 indent) { indentSize_ = indent; invalidateLayout(); }
-
- /**
- * @brief Gets the indent size
- */
- f32 getIndentSize() const { return indentSize_; }
-
- /**
- * @brief Sets the row height
- * @param height Row height in pixels
- */
- void setRowHeight(f32 height) { rowHeight_ = height; invalidateLayout(); }
-
- /**
- * @brief Gets the row height
- */
- f32 getRowHeight() const { return rowHeight_; }
-
- /**
- * @brief Sets the expand/collapse icon size
- * @param size Icon size in pixels
- */
- void setIconSize(f32 size) { iconSize_ = size; }
-
- /**
- * @brief Gets the icon size
- */
- f32 getIconSize() const { return iconSize_; }
-
- /** @brief Sets whether to show the visibility column */
- void setShowVisibilityColumn(bool show) { showVisibilityColumn_ = show; }
-
- /** @brief Returns true if the visibility column is shown */
- bool getShowVisibilityColumn() const { return showVisibilityColumn_; }
-
- /** @brief Sets whether to show the type column */
- void setShowTypeColumn(bool show) { showTypeColumn_ = show; }
-
- /** @brief Returns true if the type column is shown */
- bool getShowTypeColumn() const { return showTypeColumn_; }
-
- // =========================================================================
- // Node Management
- // =========================================================================
-
- /**
- * @brief Adds a new node
- * @param parentId Parent node ID (INVALID_TREE_NODE for root)
- * @param label Node label
- * @return The new node's ID
- */
- TreeNodeId addNode(TreeNodeId parentId, const std::string& label);
-
- /**
- * @brief Removes a node and all its children
- * @param nodeId Node to remove
- */
- void removeNode(TreeNodeId nodeId);
-
- /**
- * @brief Removes all nodes
- */
- void clear();
-
- /**
- * @brief Gets a node by ID
- * @param nodeId Node ID
- * @return Pointer to node, or nullptr if not found
- */
- TreeNode* getNode(TreeNodeId nodeId);
-
- /**
- * @brief Gets a node by ID (const)
- * @param nodeId Node ID
- * @return Const pointer to node, or nullptr if not found
- */
- const TreeNode* getNode(TreeNodeId nodeId) const;
-
- /**
- * @brief Sets a node's label
- * @param nodeId Node ID
- * @param label New label
- */
- void setNodeLabel(TreeNodeId nodeId, const std::string& label);
-
- /** @brief Sets a node's icon */
- void setNodeIcon(TreeNodeId nodeId, const std::string& icon);
-
- /** @brief Sets a node's type label */
- void setNodeType(TreeNodeId nodeId, const std::string& type);
-
- /** @brief Sets a node's visibility state */
- void setNodeVisible(TreeNodeId nodeId, bool visible);
-
- /** @brief Gets all root nodes */
- const std::vector<TreeNodeId>& getRootNodes() const { return rootNodes_; }
-
- // =========================================================================
- // Expand/Collapse
- // =========================================================================
-
- /**
- * @brief Sets a node's expanded state
- * @param nodeId Node ID
- * @param expanded True to expand, false to collapse
- */
- void setNodeExpanded(TreeNodeId nodeId, bool expanded);
-
- /**
- * @brief Toggles a node's expanded state
- * @param nodeId Node ID
- */
- void toggleNodeExpanded(TreeNodeId nodeId);
-
- /**
- * @brief Returns true if a node is expanded
- * @param nodeId Node ID
- */
- bool isNodeExpanded(TreeNodeId nodeId) const;
-
- /**
- * @brief Expands all nodes
- */
- void expandAll();
-
- /**
- * @brief Collapses all nodes
- */
- void collapseAll();
-
- // =========================================================================
- // Selection
- // =========================================================================
-
- /**
- * @brief Selects a node
- * @param nodeId Node ID
- * @param clearPrevious True to clear previous selection (default)
- */
- void selectNode(TreeNodeId nodeId, bool clearPrevious = true);
-
- /**
- * @brief Deselects a node
- * @param nodeId Node ID
- */
- void deselectNode(TreeNodeId nodeId);
-
- /**
- * @brief Clears all selection
- */
- void clearSelection();
-
- /**
- * @brief Returns true if a node is selected
- * @param nodeId Node ID
- */
- bool isNodeSelected(TreeNodeId nodeId) const;
-
- /**
- * @brief Gets all selected nodes
- * @return Set of selected node IDs
- */
- const std::unordered_set<TreeNodeId>& getSelectedNodes() const { return selectedNodes_; }
-
- // =========================================================================
- // Signals
- // =========================================================================
-
- /** @brief Emitted when a node is selected */
- Signal<void(TreeNodeId)> onNodeSelected;
-
- /** @brief Emitted when a node is deselected */
- Signal<void(TreeNodeId)> onNodeDeselected;
-
- /** @brief Emitted when a node is clicked */
- Signal<void(TreeNodeId)> onNodeClicked;
-
- /** @brief Emitted when a node is double-clicked */
- Signal<void(TreeNodeId)> onNodeDoubleClicked;
-
- /** @brief Emitted when a node is expanded */
- Signal<void(TreeNodeId)> onNodeExpanded;
-
- /** @brief Emitted when a node is collapsed */
- Signal<void(TreeNodeId)> onNodeCollapsed;
-
- /** @brief Emitted when a node is right-clicked (with screen coordinates) */
- Signal<void(TreeNodeId, f32, f32)> onNodeRightClicked;
-
- // =========================================================================
- // Widget Overrides
- // =========================================================================
-
- glm::vec2 measure(f32 availableWidth, f32 availableHeight) override;
- void render(UIBatchRenderer& renderer) override;
- bool onMouseDown(const MouseButtonEvent& event) override;
-
-protected:
- /**
- * @brief Renders a single node row
- * @param renderer Batch renderer
- * @param node Node to render
- * @param y Y position
- * @param isHovered True if mouse is over this row
- */
- virtual void renderNode(UIBatchRenderer& renderer, const TreeNode& node, f32 y, bool isHovered);
-
-private:
- // =========================================================================
- // Private Methods
- // =========================================================================
-
- /**
- * @brief Generates a unique node ID
- */
- TreeNodeId generateNodeId();
-
- /**
- * @brief Rebuilds the visible node list
- */
- void rebuildVisibleNodes();
-
- /**
- * @brief Recursively adds visible nodes
- */
- void addVisibleNodesRecursive(TreeNodeId nodeId);
-
- /**
- * @brief Finds the node at a screen Y coordinate
- * @param y Y coordinate
- * @return Node ID, or INVALID_TREE_NODE if none
- */
- TreeNodeId getNodeAtY(f32 y) const;
-
- /**
- * @brief Gets the expand/collapse icon bounds for a node
- * @param node Node
- * @param y Y position
- * @return Icon bounds
- */
- Rect getIconBounds(const TreeNode& node, f32 y) const;
-
- /**
- * @brief Checks if a node has children
- */
- bool hasChildren(const TreeNode& node) const;
-
- // =========================================================================
- // Member Variables
- // =========================================================================
-
- // Node storage
- std::unordered_map<TreeNodeId, TreeNode> nodes_;
- std::vector<TreeNodeId> rootNodes_;
- std::vector<TreeNodeId> visibleNodes_; ///< Flattened list of visible nodes
- bool visibleNodesDirty_ = true;
-
- // Selection
- std::unordered_set<TreeNodeId> selectedNodes_;
- bool multiSelect_ = false;
-
- // Layout
- f32 indentSize_ = 20.0f;
- f32 rowHeight_ = 24.0f;
- f32 iconSize_ = 12.0f;
- bool showVisibilityColumn_ = true;
- bool showTypeColumn_ = true;
-
- // ID generation
- TreeNodeId nextNodeId_ = 1;
-
- // Interaction state
- TreeNodeId hoveredNode_ = INVALID_TREE_NODE;
- TreeNodeId lastClickedNode_ = INVALID_TREE_NODE;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Widget.cpp b/src/esengine/ui/widgets/Widget.cpp
deleted file mode 100644
index ec44f8e98..000000000
--- a/src/esengine/ui/widgets/Widget.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/**
- * @file Widget.cpp
- * @brief Widget base class implementation
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Widget.hpp"
-#include "../layout/Layout.hpp"
-#include "../rendering/UIBatchRenderer.hpp"
-#include "../UIContext.hpp"
-
-namespace esengine::ui {
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-Widget::Widget(const WidgetId& id) : id_(id), name_(id.name()) {}
-
-Widget::~Widget() = default;
-
-// =============================================================================
-// Hierarchy
-// =============================================================================
-
-Widget* Widget::getChild(usize index) const {
- if (index >= children_.size()) {
- return nullptr;
- }
- return children_[index].get();
-}
-
-Widget* Widget::findChild(const WidgetId& id) const {
- for (const auto& child : children_) {
- if (child->getId() == id) {
- return child.get();
- }
- if (auto* found = child->findChild(id)) {
- return found;
- }
- }
- return nullptr;
-}
-
-void Widget::addChild(Unique<Widget> child) {
- if (!child) return;
-
- child->parent_ = this;
- child->setContext(context_);
- children_.push_back(std::move(child));
- invalidateLayout();
-}
-
-Unique<Widget> Widget::removeChild(Widget* child) {
- for (auto it = children_.begin(); it != children_.end(); ++it) {
- if (it->get() == child) {
- auto removed = std::move(*it);
- children_.erase(it);
- removed->parent_ = nullptr;
- removed->setContext(nullptr);
- invalidateLayout();
- return removed;
- }
- }
- return nullptr;
-}
-
-void Widget::clearChildren() {
- for (auto& child : children_) {
- child->parent_ = nullptr;
- child->setContext(nullptr);
- }
- children_.clear();
- invalidateLayout();
-}
-
-// =============================================================================
-// Layout
-// =============================================================================
-
-void Widget::setLayout(Unique<Layout> layout) {
- layout_ = std::move(layout);
- invalidateLayout();
-}
-
-void Widget::setSize(const SizeValue& width, const SizeValue& height) {
- width_ = width;
- height_ = height;
- invalidateLayout();
-}
-
-void Widget::setMinSize(f32 minWidth, f32 minHeight) {
- constraints_.minWidth = minWidth;
- constraints_.minHeight = minHeight;
- invalidateLayout();
-}
-
-void Widget::setMaxSize(f32 maxWidth, f32 maxHeight) {
- constraints_.maxWidth = maxWidth;
- constraints_.maxHeight = maxHeight;
- invalidateLayout();
-}
-
-glm::vec2 Widget::measure(f32 availableWidth, f32 availableHeight) {
- if (!measureDirty_ &&
- lastAvailableWidth_ == availableWidth &&
- lastAvailableHeight_ == availableHeight) {
- return {cachedMeasureWidth_, cachedMeasureHeight_};
- }
-
- f32 contentWidth = 0.0f;
- f32 contentHeight = 0.0f;
-
- if (layout_) {
- auto size = layout_->measure(*this, availableWidth, availableHeight);
- contentWidth = size.x;
- contentHeight = size.y;
- } else {
- for (const auto& child : children_) {
- auto childSize = child->measure(availableWidth, availableHeight);
- contentWidth = (childSize.x > contentWidth) ? childSize.x : contentWidth;
- contentHeight = (childSize.y > contentHeight) ? childSize.y : contentHeight;
- }
- }
-
- contentWidth += padding_.totalHorizontal();
- contentHeight += padding_.totalVertical();
-
- f32 width = width_.resolve(availableWidth, contentWidth);
- f32 height = height_.resolve(availableHeight, contentHeight);
-
- width = constraints_.constrainWidth(width);
- height = constraints_.constrainHeight(height);
-
- cachedMeasureWidth_ = width;
- cachedMeasureHeight_ = height;
- lastAvailableWidth_ = availableWidth;
- lastAvailableHeight_ = availableHeight;
- measureDirty_ = false;
-
- return {width, height};
-}
-
-void Widget::layout(const Rect& bounds) {
- bounds_ = bounds;
- layoutDirty_ = false;
-
- if (layout_) {
- layout_->layout(*this, getContentBounds());
- } else {
- Rect content = getContentBounds();
- for (auto& child : children_) {
- auto childSize = child->measure(content.width, content.height);
- Rect childBounds(content.x, content.y, childSize.x, childSize.y);
- child->layout(childBounds);
- }
- }
-}
-
-Rect Widget::getContentBounds() const {
- return padding_.shrink(bounds_);
-}
-
-void Widget::invalidateLayout() {
- if (layoutDirty_) return;
- layoutDirty_ = true;
- measureDirty_ = true;
- if (parent_) {
- parent_->invalidateLayout();
- }
-}
-
-void Widget::invalidateMeasure() {
- if (measureDirty_) return;
- measureDirty_ = true;
- layoutDirty_ = true;
- if (parent_) {
- parent_->invalidateMeasure();
- }
-}
-
-// =============================================================================
-// State
-// =============================================================================
-
-void Widget::setVisible(bool visible) {
- if (state_.visible != visible) {
- state_.visible = visible;
- onStateChanged();
- invalidateLayout();
- }
-}
-
-void Widget::setEnabled(bool enabled) {
- bool disabled = !enabled;
- if (state_.disabled != disabled) {
- state_.disabled = disabled;
- if (disabled) {
- state_.hovered = false;
- state_.pressed = false;
- }
- onStateChanged();
- }
-}
-
-void Widget::setState(bool hovered, bool pressed) {
- if (state_.hovered != hovered || state_.pressed != pressed) {
- state_.hovered = hovered;
- state_.pressed = pressed;
- onStateChanged();
- }
-}
-
-void Widget::setFocused(bool focused) {
- if (state_.focused != focused) {
- state_.focused = focused;
- onStateChanged();
- }
-}
-
-// =============================================================================
-// Rendering
-// =============================================================================
-
-void Widget::render(UIBatchRenderer& renderer) {
- (void)renderer;
-}
-
-void Widget::renderTree(UIBatchRenderer& renderer) {
- if (!state_.visible) return;
-
- render(renderer);
-
- for (auto& child : children_) {
- child->renderTree(renderer);
- }
-}
-
-// =============================================================================
-// Hit Testing
-// =============================================================================
-
-Widget* Widget::hitTest(f32 x, f32 y) {
- if (!state_.visible || state_.disabled) {
- return nullptr;
- }
-
- if (!containsPoint(x, y)) {
- return nullptr;
- }
-
- for (auto it = children_.rbegin(); it != children_.rend(); ++it) {
- if (auto* hit = (*it)->hitTest(x, y)) {
- return hit;
- }
- }
-
- return this;
-}
-
-bool Widget::containsPoint(f32 x, f32 y) const {
- return bounds_.contains(x, y);
-}
-
-// =============================================================================
-// Context
-// =============================================================================
-
-void Widget::setContext(UIContext* context) {
- if (context_ && context_ != context) {
- context_->clearWidgetReferences(this);
- }
- context_ = context;
- for (auto& child : children_) {
- child->setContext(context);
- }
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/Widget.hpp b/src/esengine/ui/widgets/Widget.hpp
deleted file mode 100644
index 5d2b75595..000000000
--- a/src/esengine/ui/widgets/Widget.hpp
+++ /dev/null
@@ -1,363 +0,0 @@
-/**
- * @file Widget.hpp
- * @brief Base widget class for the UI system
- * @details Provides the foundation for all UI widgets including hierarchy
- * management, layout, state tracking, and event handling.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-#include "../core/Theme.hpp"
-#include "../core/Types.hpp"
-#include "../events/UIEvent.hpp"
-#include "../layout/SizeValue.hpp"
-
-#include <functional>
-#include <string>
-#include <vector>
-
-namespace esengine::ui {
-
-class Layout;
-class UIBatchRenderer;
-class UIContext;
-
-// =============================================================================
-// Widget Class
-// =============================================================================
-
-/**
- * @brief Base class for all UI widgets
- *
- * @details Provides hierarchy management, layout integration, state tracking,
- * event handling, and rendering for UI elements.
- *
- * @code
- * class MyButton : public Widget {
- * public:
- * MyButton(const WidgetId& id, const std::string& text)
- * : Widget(id), text_(text) {}
- *
- * void render(UIBatchRenderer& renderer) override {
- * auto style = getContext()->getTheme().getButtonStyle();
- * renderer.drawRoundedRect(getBounds(), style.getBackgroundColor(getState()),
- * style.cornerRadii);
- * // Draw text...
- * }
- *
- * bool onMouseDown(const MouseButtonEvent& e) override {
- * onClick();
- * return true;
- * }
- *
- * std::function<void()> onClick;
- *
- * private:
- * std::string text_;
- * };
- * @endcode
- */
-class Widget {
-public:
- explicit Widget(const WidgetId& id);
- virtual ~Widget();
-
- // Non-copyable
- Widget(const Widget&) = delete;
- Widget& operator=(const Widget&) = delete;
-
- // =========================================================================
- // Identity
- // =========================================================================
-
- /** @brief Gets the widget's unique identifier */
- const WidgetId& getId() const { return id_; }
-
- /** @brief Gets the widget's display name */
- const std::string& getName() const { return name_; }
-
- /** @brief Sets the widget's display name */
- void setName(const std::string& name) { name_ = name; }
-
- // =========================================================================
- // Hierarchy
- // =========================================================================
-
- /** @brief Gets the parent widget */
- Widget* getParent() const { return parent_; }
-
- /** @brief Gets the list of child widgets */
- const std::vector<Unique<Widget>>& getChildren() const { return children_; }
-
- /** @brief Gets the number of children */
- usize getChildCount() const { return children_.size(); }
-
- /** @brief Gets a child by index */
- Widget* getChild(usize index) const;
-
- /** @brief Finds a child by ID */
- Widget* findChild(const WidgetId& id) const;
-
- /**
- * @brief Adds a child widget
- * @param child Widget to add (ownership transferred)
- */
- void addChild(Unique<Widget> child);
-
- /**
- * @brief Removes a child widget
- * @param child Widget to remove
- * @return The removed widget (ownership returned)
- */
- Unique<Widget> removeChild(Widget* child);
-
- /**
- * @brief Removes all children
- */
- void clearChildren();
-
- // =========================================================================
- // Layout
- // =========================================================================
-
- /** @brief Sets the layout manager for children */
- void setLayout(Unique<Layout> layout);
-
- /** @brief Gets the current layout manager */
- Layout* getLayout() const { return layout_.get(); }
-
- /** @brief Sets the desired width */
- void setWidth(const SizeValue& width) { width_ = width; invalidateLayout(); }
-
- /** @brief Sets the desired height */
- void setHeight(const SizeValue& height) { height_ = height; invalidateLayout(); }
-
- /** @brief Sets both width and height */
- void setSize(const SizeValue& width, const SizeValue& height);
-
- /** @brief Gets the desired width */
- const SizeValue& getWidth() const { return width_; }
-
- /** @brief Gets the desired height */
- const SizeValue& getHeight() const { return height_; }
-
- /** @brief Sets the padding inside the widget */
- void setPadding(const Insets& padding) { padding_ = padding; invalidateLayout(); }
-
- /** @brief Gets the padding */
- const Insets& getPadding() const { return padding_; }
-
- /** @brief Sets the margin outside the widget */
- void setMargin(const Insets& margin) { margin_ = margin; invalidateLayout(); }
-
- /** @brief Gets the margin */
- const Insets& getMargin() const { return margin_; }
-
- /** @brief Sets the minimum size constraints */
- void setMinSize(f32 minWidth, f32 minHeight);
-
- /** @brief Sets the maximum size constraints */
- void setMaxSize(f32 maxWidth, f32 maxHeight);
-
- /** @brief Gets the size constraints */
- const SizeConstraints& getConstraints() const { return constraints_; }
-
- /**
- * @brief Measures the preferred size of this widget
- * @param availableWidth Available width for layout
- * @param availableHeight Available height for layout
- * @return Preferred size
- */
- virtual glm::vec2 measure(f32 availableWidth, f32 availableHeight);
-
- /**
- * @brief Lays out this widget and its children
- * @param bounds The assigned bounds for this widget
- */
- virtual void layout(const Rect& bounds);
-
- /** @brief Gets the current bounds */
- const Rect& getBounds() const { return bounds_; }
-
- /** @brief Gets the content bounds (bounds minus padding) */
- Rect getContentBounds() const;
-
- /** @brief Marks layout as needing recalculation */
- void invalidateLayout();
-
- /** @brief Marks measure cache as dirty (called when content changes) */
- void invalidateMeasure();
-
- /** @brief Returns true if layout needs recalculation */
- bool isLayoutDirty() const { return layoutDirty_; }
-
- /** @brief Returns true if measure cache is dirty */
- bool isMeasureDirty() const { return measureDirty_; }
-
- // =========================================================================
- // State
- // =========================================================================
-
- /** @brief Gets the current widget state */
- const WidgetState& getState() const { return state_; }
-
- /** @brief Returns true if the widget is visible */
- bool isVisible() const { return state_.visible; }
-
- /** @brief Sets visibility */
- void setVisible(bool visible);
-
- /** @brief Returns true if the widget is enabled */
- bool isEnabled() const { return !state_.disabled; }
-
- /** @brief Sets enabled state */
- void setEnabled(bool enabled);
-
- /** @brief Returns true if the widget is hovered */
- bool isHovered() const { return state_.hovered; }
-
- /** @brief Returns true if the widget is pressed */
- bool isPressed() const { return state_.pressed; }
-
- /** @brief Returns true if the widget is focused */
- bool isFocused() const { return state_.focused; }
-
- /** @brief Returns true if the widget can receive focus */
- virtual bool isFocusable() const { return false; }
-
- // =========================================================================
- // Rendering
- // =========================================================================
-
- /**
- * @brief Renders this widget
- * @param renderer The batch renderer to use
- */
- virtual void render(UIBatchRenderer& renderer);
-
- /**
- * @brief Renders this widget and all children
- * @param renderer The batch renderer to use
- */
- virtual void renderTree(UIBatchRenderer& renderer);
-
- // =========================================================================
- // Event Handling
- // =========================================================================
-
- /** @brief Called when mouse button is pressed */
- virtual bool onMouseDown(const MouseButtonEvent& event) { (void)event; return false; }
-
- /** @brief Called when mouse button is released */
- virtual bool onMouseUp(const MouseButtonEvent& event) { (void)event; return false; }
-
- /** @brief Called when mouse enters the widget */
- virtual bool onMouseEnter(const MouseEnterEvent& event) { (void)event; return false; }
-
- /** @brief Called when mouse leaves the widget */
- virtual bool onMouseLeave(const MouseLeaveEvent& event) { (void)event; return false; }
-
- /** @brief Called when mouse moves over the widget */
- virtual bool onMouseMove(const MouseMoveEvent& event) { (void)event; return false; }
-
- /** @brief Called when scroll occurs over the widget */
- virtual bool onScroll(const ScrollEvent& event) { (void)event; return false; }
-
- /** @brief Called when a key is pressed */
- virtual bool onKeyDown(const KeyEvent& event) { (void)event; return false; }
-
- /** @brief Called when a key is released */
- virtual bool onKeyUp(const KeyEvent& event) { (void)event; return false; }
-
- /** @brief Called when text is input */
- virtual bool onTextInput(const TextInputEvent& event) { (void)event; return false; }
-
- /** @brief Called when widget gains focus */
- virtual void onFocus(const FocusEvent& event) { (void)event; }
-
- /** @brief Called when widget loses focus */
- virtual void onBlur(const BlurEvent& event) { (void)event; }
-
- // =========================================================================
- // Hit Testing
- // =========================================================================
-
- /**
- * @brief Tests if a point hits this widget
- * @param x X coordinate
- * @param y Y coordinate
- * @return The deepest widget hit, or nullptr
- */
- virtual Widget* hitTest(f32 x, f32 y);
-
- /**
- * @brief Returns true if the point is within bounds
- */
- bool containsPoint(f32 x, f32 y) const;
-
- // =========================================================================
- // Context
- // =========================================================================
-
- /** @brief Gets the UI context */
- UIContext* getContext() const { return context_; }
-
- /** @brief Sets the UI context (called internally) */
- void setContext(UIContext* context);
-
-protected:
- /**
- * @brief Called when state changes
- */
- virtual void onStateChanged() {}
-
- /**
- * @brief Updates the internal state
- */
- void setState(bool hovered, bool pressed);
-
- /**
- * @brief Sets focused state (called by UIContext)
- */
- void setFocused(bool focused);
-
- friend class UIContext;
-
-private:
- WidgetId id_;
- std::string name_;
-
- Widget* parent_ = nullptr;
- std::vector<Unique<Widget>> children_;
- Unique<Layout> layout_;
-
- SizeValue width_ = SizeValue::autoSize();
- SizeValue height_ = SizeValue::autoSize();
- Insets padding_;
- Insets margin_;
- SizeConstraints constraints_;
-
- Rect bounds_;
- WidgetState state_;
- bool layoutDirty_ = true;
- bool measureDirty_ = true;
-
- f32 cachedMeasureWidth_ = 0.0f;
- f32 cachedMeasureHeight_ = 0.0f;
- f32 lastAvailableWidth_ = -1.0f;
- f32 lastAvailableHeight_ = -1.0f;
-
- UIContext* context_ = nullptr;
-};
-
-} // namespace esengine::ui
diff --git a/assets/templates/.gitignore b/templates/.gitignore
similarity index 100%
rename from assets/templates/.gitignore
rename to templates/.gitignore
diff --git a/assets/templates/package.json b/templates/package.json
similarity index 100%
rename from assets/templates/package.json
rename to templates/package.json
diff --git a/templates/src/main.ts b/templates/src/main.ts
new file mode 100644
index 000000000..c996c9159
--- /dev/null
+++ b/templates/src/main.ts
@@ -0,0 +1,97 @@
+/**
+ * ESEngine Project Entry Point
+ *
+ * This file is the main entry point for your game logic.
+ * Press F5 in the editor to run, or use Web Preview for browser testing.
+ */
+import type { ESEngineModule } from 'esengine/wasm';
+import {
+ App,
+ createWebApp,
+ defineSystem,
+ Schedule,
+ Commands,
+ LocalTransform,
+ Sprite,
+ Camera,
+ Canvas,
+ Res,
+ Time,
+ Query,
+ type Entity
+} from 'esengine/ecs';
+
+// =============================================================================
+// Main Entry Point
+// =============================================================================
+
+export async function main(Module: ESEngineModule): Promise<void> {
+ console.log('ESEngine starting...');
+
+ // Create the app with WASM module (handles renderer init + render loop)
+ const app = createWebApp(Module);
+
+ // Add startup system - runs once at beginning
+ app.addSystemToSchedule(Schedule.Startup, defineSystem(
+ [Commands()],
+ (cmds) => {
+ console.log('Startup: Creating entities...');
+
+ // Create camera
+ const camera = cmds.spawn()
+ .insert(Camera, {
+ projectionType: 1, // Orthographic
+ fov: 60,
+ orthoSize: 400,
+ nearPlane: 0.1,
+ farPlane: 1000,
+ aspectRatio: 1,
+ isActive: true,
+ priority: 0
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 10 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+ })
+ .id();
+
+ // Create a test sprite
+ const sprite = cmds.spawn()
+ .insert(Sprite, {
+ texture: 0,
+ color: { x: 1, y: 0.5, z: 0.2, w: 1 },
+ size: { x: 100, y: 100 },
+ uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 },
+ layer: 0,
+ flipX: false,
+ flipY: false
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+ })
+ .id();
+
+ console.log(`Created camera: ${camera}, sprite: ${sprite}`);
+ }
+ ));
+
+ // Add update system - runs every frame
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Query(LocalTransform, Sprite)],
+ (time, query) => {
+ for (const [entity, transform, sprite] of query) {
+ // Move the sprite in a circle
+ transform.position.x = Math.sin(time.elapsed) * 100;
+ transform.position.y = Math.cos(time.elapsed) * 100;
+ }
+ }
+ ));
+
+ // Start the game loop
+ console.log('Starting game loop...');
+ app.run();
+}
diff --git a/sdk/examples/hello-game/tsconfig.json b/templates/tsconfig.json
similarity index 61%
rename from sdk/examples/hello-game/tsconfig.json
rename to templates/tsconfig.json
index 14f6736d5..84d188ba9 100644
--- a/sdk/examples/hello-game/tsconfig.json
+++ b/templates/tsconfig.json
@@ -3,13 +3,13 @@
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM"],
- "strict": true,
"moduleResolution": "node",
+ "strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
- "outDir": ".",
- "rootDir": "../.."
+ "forceConsistentCasingInFileNames": true,
+ "noEmit": true
},
- "include": ["*.ts", "../../src/**/*.ts"],
- "exclude": ["node_modules"]
+ "include": ["src/**/*.ts"],
+ "exclude": ["node_modules", "build"]
}
diff --git a/assets/templates/web/index.html b/templates/web/index.html
similarity index 100%
rename from assets/templates/web/index.html
rename to templates/web/index.html
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 7b69b68ab..43ab89782 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -1,7 +1,5 @@
# ESEngine Tests
-# Simple test framework (minimal, no external dependencies)
-
# ECS tests
add_executable(test_ecs
ecs/test_registry.cpp
@@ -15,24 +13,3 @@ add_executable(test_events
)
target_link_libraries(test_events PRIVATE esengine)
add_test(NAME test_events COMMAND test_events)
-
-# Editor command system tests
-add_executable(test_commands
- editor/test_commands.cpp
-)
-target_link_libraries(test_commands PRIVATE esengine)
-add_test(NAME test_commands COMMAND test_commands)
-
-# UI layout tests
-add_executable(test_layout
- ui/test_layout.cpp
-)
-target_link_libraries(test_layout PRIVATE esengine)
-add_test(NAME test_layout COMMAND test_layout)
-
-# UI layout debug tool
-add_executable(test_layout_debug
- ui/test_layout_debug.cpp
-)
-target_link_libraries(test_layout_debug PRIVATE esengine)
-
diff --git a/tests/editor/test_commands.cpp b/tests/editor/test_commands.cpp
deleted file mode 100644
index c3a1ef0c8..000000000
--- a/tests/editor/test_commands.cpp
+++ /dev/null
@@ -1,376 +0,0 @@
-/**
- * @file test_commands.cpp
- * @brief Unit tests for the command system
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include <esengine/editor/command/Command.hpp>
-#include <esengine/editor/command/CommandHistory.hpp>
-#include <esengine/editor/command/MacroCommand.hpp>
-#include <esengine/editor/command/PropertyCommand.hpp>
-#include <iostream>
-#include <cassert>
-
-using namespace esengine;
-using namespace esengine::editor;
-
-// Simple test macros
-#define TEST(name) void test_##name()
-#define RUN_TEST(name) do { \
- std::cout << "Running " #name "... "; \
- test_##name(); \
- std::cout << "PASSED" << std::endl; \
- passed++; \
-} while(0)
-
-#define ASSERT_TRUE(cond) do { \
- if (!(cond)) { \
- std::cerr << "FAILED: " #cond << " at line " << __LINE__ << std::endl; \
- failed++; \
- return; \
- } \
-} while(0)
-
-#define ASSERT_EQ(a, b) ASSERT_TRUE((a) == (b))
-#define ASSERT_NE(a, b) ASSERT_TRUE((a) != (b))
-
-static int passed = 0;
-static int failed = 0;
-
-// Test command that increments a counter
-class IncrementCommand : public Command {
-public:
- IncrementCommand(int& counter, int amount = 1)
- : counter_(counter), amount_(amount) {}
-
- CommandResult execute() override {
- counter_ += amount_;
- return CommandResult::Success;
- }
-
- void undo() override {
- counter_ -= amount_;
- }
-
- std::string getDescription() const override {
- return "Increment by " + std::to_string(amount_);
- }
-
-private:
- int& counter_;
- int amount_;
-};
-
-// Test command that sets a value
-class SetValueCommand : public Command {
-public:
- SetValueCommand(int& value, int newValue)
- : value_(value), oldValue_(value), newValue_(newValue) {}
-
- CommandResult execute() override {
- value_ = newValue_;
- return CommandResult::Success;
- }
-
- void undo() override {
- value_ = oldValue_;
- }
-
- std::string getDescription() const override {
- return "Set value to " + std::to_string(newValue_);
- }
-
-private:
- int& value_;
- int oldValue_;
- int newValue_;
-};
-
-// Test command that can fail
-class FailingCommand : public Command {
-public:
- CommandResult execute() override {
- return CommandResult::Failed;
- }
-
- void undo() override {}
-
- std::string getDescription() const override {
- return "Failing command";
- }
-};
-
-// Command tests
-TEST(command_execute_undo) {
- int counter = 0;
- IncrementCommand cmd(counter, 5);
-
- cmd.execute();
- ASSERT_EQ(counter, 5);
-
- cmd.undo();
- ASSERT_EQ(counter, 0);
-}
-
-TEST(command_redo) {
- int counter = 0;
- IncrementCommand cmd(counter, 3);
-
- cmd.execute();
- ASSERT_EQ(counter, 3);
-
- cmd.undo();
- ASSERT_EQ(counter, 0);
-
- cmd.redo();
- ASSERT_EQ(counter, 3);
-}
-
-// CommandHistory tests
-TEST(history_basic) {
- int counter = 0;
- CommandHistory history;
-
- history.execute(makeUnique<IncrementCommand>(counter, 10));
- ASSERT_EQ(counter, 10);
- ASSERT_TRUE(history.canUndo());
- ASSERT_TRUE(!history.canRedo());
-}
-
-TEST(history_undo) {
- int counter = 0;
- CommandHistory history;
-
- history.execute(makeUnique<IncrementCommand>(counter, 10));
- ASSERT_EQ(counter, 10);
-
- history.undo();
- ASSERT_EQ(counter, 0);
- ASSERT_TRUE(!history.canUndo());
- ASSERT_TRUE(history.canRedo());
-}
-
-TEST(history_redo) {
- int counter = 0;
- CommandHistory history;
-
- history.execute(makeUnique<IncrementCommand>(counter, 10));
- history.undo();
- ASSERT_EQ(counter, 0);
-
- history.redo();
- ASSERT_EQ(counter, 10);
- ASSERT_TRUE(history.canUndo());
- ASSERT_TRUE(!history.canRedo());
-}
-
-TEST(history_multiple_undo_redo) {
- int counter = 0;
- CommandHistory history;
-
- history.execute(makeUnique<IncrementCommand>(counter, 1));
- history.execute(makeUnique<IncrementCommand>(counter, 2));
- history.execute(makeUnique<IncrementCommand>(counter, 3));
- ASSERT_EQ(counter, 6);
-
- history.undo(); // 6 - 3 = 3
- ASSERT_EQ(counter, 3);
-
- history.undo(); // 3 - 2 = 1
- ASSERT_EQ(counter, 1);
-
- history.redo(); // 1 + 2 = 3
- ASSERT_EQ(counter, 3);
-
- history.redo(); // 3 + 3 = 6
- ASSERT_EQ(counter, 6);
-}
-
-TEST(history_undo_clears_redo) {
- int counter = 0;
- CommandHistory history;
-
- history.execute(makeUnique<IncrementCommand>(counter, 1));
- history.execute(makeUnique<IncrementCommand>(counter, 2));
- ASSERT_EQ(counter, 3);
-
- history.undo(); // Can redo now
- ASSERT_TRUE(history.canRedo());
-
- history.execute(makeUnique<IncrementCommand>(counter, 10));
- ASSERT_TRUE(!history.canRedo()); // Redo cleared
-}
-
-TEST(history_failed_command) {
- CommandHistory history;
-
- auto result = history.execute(makeUnique<FailingCommand>());
- ASSERT_EQ(result, CommandResult::Failed);
- ASSERT_TRUE(!history.canUndo());
-}
-
-TEST(history_dirty_flag) {
- int counter = 0;
- CommandHistory history;
-
- ASSERT_TRUE(!history.isDirty());
-
- history.execute(makeUnique<IncrementCommand>(counter, 1));
- ASSERT_TRUE(history.isDirty());
-
- history.markSaved();
- ASSERT_TRUE(!history.isDirty());
-
- history.execute(makeUnique<IncrementCommand>(counter, 1));
- ASSERT_TRUE(history.isDirty());
-}
-
-TEST(history_description) {
- int counter = 0;
- CommandHistory history;
-
- history.execute(makeUnique<IncrementCommand>(counter, 5));
-
- ASSERT_EQ(history.getUndoDescription(), "Increment by 5");
-}
-
-// MacroCommand tests
-TEST(macro_basic) {
- int counter = 0;
- auto macro = makeUnique<MacroCommand>("Batch increment");
-
- macro->add(makeUnique<IncrementCommand>(counter, 1));
- macro->add(makeUnique<IncrementCommand>(counter, 2));
- macro->add(makeUnique<IncrementCommand>(counter, 3));
-
- macro->execute();
- ASSERT_EQ(counter, 6);
-
- macro->undo();
- ASSERT_EQ(counter, 0);
-}
-
-TEST(macro_partial_failure) {
- int counter = 0;
- auto macro = makeUnique<MacroCommand>("Batch with failure");
-
- macro->add(makeUnique<IncrementCommand>(counter, 5));
- macro->add(makeUnique<FailingCommand>());
- macro->add(makeUnique<IncrementCommand>(counter, 10));
-
- auto result = macro->execute();
- ASSERT_EQ(result, CommandResult::Failed);
- ASSERT_EQ(counter, 0); // Should rollback first command
-}
-
-TEST(macro_with_history) {
- int counter = 0;
- CommandHistory history;
-
- auto macro = makeUnique<MacroCommand>("Batch increment");
- macro->add(makeUnique<IncrementCommand>(counter, 1));
- macro->add(makeUnique<IncrementCommand>(counter, 2));
-
- history.execute(std::move(macro));
- ASSERT_EQ(counter, 3);
-
- history.undo();
- ASSERT_EQ(counter, 0); // Single undo undoes entire macro
-
- history.redo();
- ASSERT_EQ(counter, 3);
-}
-
-// Transaction tests
-TEST(transaction_basic) {
- int counter = 0;
- CommandHistory history;
-
- {
- TransactionGuard guard(history, "Transaction");
- history.execute(makeUnique<IncrementCommand>(counter, 1));
- history.execute(makeUnique<IncrementCommand>(counter, 2));
- } // Auto-commit
-
- ASSERT_EQ(counter, 3);
- ASSERT_EQ(history.getUndoCount(), 1u); // Single undo entry
-
- history.undo();
- ASSERT_EQ(counter, 0);
-}
-
-// Lambda command tests
-TEST(lambda_command) {
- int value = 0;
-
- auto cmd = makeUnique<LambdaCommand>(
- "Set to 42",
- [&value]() { value = 42; return CommandResult::Success; },
- [&value]() { value = 0; }
- );
-
- cmd->execute();
- ASSERT_EQ(value, 42);
-
- cmd->undo();
- ASSERT_EQ(value, 0);
-}
-
-// SimpleValueCommand tests
-TEST(simple_value_command) {
- int value = 10;
-
- auto cmd = makeUnique<SimpleValueCommand<int>>(&value, 20, "Set to 20");
-
- cmd->execute();
- ASSERT_EQ(value, 20);
-
- cmd->undo();
- ASSERT_EQ(value, 10);
-
- cmd->redo();
- ASSERT_EQ(value, 20);
-}
-
-int main() {
- std::cout << "ESEngine Command System Unit Tests" << std::endl;
- std::cout << "====================================" << std::endl;
-
- // Command tests
- RUN_TEST(command_execute_undo);
- RUN_TEST(command_redo);
-
- // CommandHistory tests
- RUN_TEST(history_basic);
- RUN_TEST(history_undo);
- RUN_TEST(history_redo);
- RUN_TEST(history_multiple_undo_redo);
- RUN_TEST(history_undo_clears_redo);
- RUN_TEST(history_failed_command);
- RUN_TEST(history_dirty_flag);
- RUN_TEST(history_description);
-
- // MacroCommand tests
- RUN_TEST(macro_basic);
- RUN_TEST(macro_partial_failure);
- RUN_TEST(macro_with_history);
-
- // Transaction tests
- RUN_TEST(transaction_basic);
-
- // Lambda command tests
- RUN_TEST(lambda_command);
-
- // SimpleValueCommand tests
- RUN_TEST(simple_value_command);
-
- std::cout << "====================================" << std::endl;
- std::cout << "Results: " << passed << " passed, " << failed << " failed" << std::endl;
-
- return failed > 0 ? 1 : 0;
-}
diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt
index eed210bad..0b0cdbf3f 100644
--- a/third_party/CMakeLists.txt
+++ b/third_party/CMakeLists.txt
@@ -1,12 +1,9 @@
-# Third-party libraries for ESEngine
-
# =============================================================================
-# GLM - OpenGL Mathematics Library (Header-only)
+# GLM - OpenGL Mathematics Library
# =============================================================================
+
add_library(glm INTERFACE)
target_include_directories(glm INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/glm)
-
-# Define GLM options
target_compile_definitions(glm INTERFACE
GLM_FORCE_RADIANS
GLM_FORCE_DEPTH_ZERO_TO_ONE
@@ -14,112 +11,16 @@ target_compile_definitions(glm INTERFACE
)
# =============================================================================
-# Native Platform Dependencies (GLFW, GLAD)
+# Native Platform Dependencies
# =============================================================================
+
if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
- # GLFW - Window and input library
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GLFW_INSTALL OFF CACHE BOOL "" FORCE)
add_subdirectory(glfw)
- # GLAD - OpenGL function loader
- add_library(glad STATIC
- ${CMAKE_CURRENT_SOURCE_DIR}/glad/src/glad.c
- )
- target_include_directories(glad PUBLIC
- ${CMAKE_CURRENT_SOURCE_DIR}/glad/include
- )
-
- # =============================================================================
- # QuickJS - JavaScript Engine (Native Platform Only)
- # =============================================================================
- # QuickJS uses Unix APIs and requires MinGW on Windows (not MSVC)
-
- # Check compiler compatibility
- include(${CMAKE_SOURCE_DIR}/cmake/QuickJSMinGW.cmake)
-
- set(QUICKJS_SOURCES
- ${CMAKE_CURRENT_SOURCE_DIR}/quickjs/quickjs.c
- ${CMAKE_CURRENT_SOURCE_DIR}/quickjs/libregexp.c
- ${CMAKE_CURRENT_SOURCE_DIR}/quickjs/libunicode.c
- ${CMAKE_CURRENT_SOURCE_DIR}/quickjs/cutils.c
- ${CMAKE_CURRENT_SOURCE_DIR}/quickjs/quickjs-libc.c
- )
-
- add_library(quickjs STATIC ${QUICKJS_SOURCES})
-
- # QuickJS internal include (PRIVATE - contains VERSION file and internal headers)
- target_include_directories(quickjs PRIVATE
- ${CMAKE_CURRENT_SOURCE_DIR}/quickjs
- )
-
- # Create a clean include directory with only public headers
- # This avoids exposing internal files like VERSION to consumers
- set(QUICKJS_PUBLIC_INCLUDE_DIR "${CMAKE_BINARY_DIR}/quickjs_headers")
- file(MAKE_DIRECTORY "${QUICKJS_PUBLIC_INCLUDE_DIR}")
-
- # Copy only the public header files (exclude VERSION and internal files)
- configure_file(
- "${CMAKE_CURRENT_SOURCE_DIR}/quickjs/quickjs.h"
- "${QUICKJS_PUBLIC_INCLUDE_DIR}/quickjs.h"
- COPYONLY
- )
- configure_file(
- "${CMAKE_CURRENT_SOURCE_DIR}/quickjs/quickjs-libc.h"
- "${QUICKJS_PUBLIC_INCLUDE_DIR}/quickjs-libc.h"
- COPYONLY
- )
-
- # Export the clean include directory for consumers
- set(QUICKJS_INCLUDE_DIR "${QUICKJS_PUBLIC_INCLUDE_DIR}" PARENT_SCOPE)
-
- # QuickJS specific settings
- if(WIN32)
- # On Windows, QuickJS requires MinGW (GCC), not MSVC
- # CMake will automatically use MinGW if available
- target_compile_definitions(quickjs PRIVATE
- _GNU_SOURCE
- CONFIG_VERSION="2025-09-13"
- )
- else()
- target_compile_definitions(quickjs PRIVATE
- _GNU_SOURCE
- CONFIG_VERSION="2025-09-13"
- )
- endif()
-
- target_compile_definitions(quickjs PUBLIC ES_SCRIPTING_ENABLED)
-
-endif()
-
-# =============================================================================
-# FreeType - Font rendering library (All platforms including Web)
-# =============================================================================
-set(FT_DISABLE_ZLIB ON CACHE BOOL "" FORCE)
-set(FT_DISABLE_BZIP2 ON CACHE BOOL "" FORCE)
-set(FT_DISABLE_PNG ON CACHE BOOL "" FORCE)
-set(FT_DISABLE_HARFBUZZ ON CACHE BOOL "" FORCE)
-set(FT_DISABLE_BROTLI ON CACHE BOOL "" FORCE)
-add_subdirectory(freetype)
-
-# Create alias for FreeType to match msdfgen's expected target name
-if(NOT TARGET Freetype::Freetype)
- add_library(Freetype::Freetype ALIAS freetype)
-endif()
-
-# =============================================================================
-# msdfgen - Multi-channel Signed Distance Field generator
-# =============================================================================
-if(ES_FEATURE_SDF_FONT)
- set(MSDFGEN_CORE_ONLY OFF CACHE BOOL "" FORCE)
- set(MSDFGEN_BUILD_STANDALONE OFF CACHE BOOL "" FORCE)
- set(MSDFGEN_USE_VCPKG OFF CACHE BOOL "" FORCE)
- set(MSDFGEN_USE_OPENMP OFF CACHE BOOL "" FORCE)
- set(MSDFGEN_USE_SKIA OFF CACHE BOOL "" FORCE)
- set(MSDFGEN_DISABLE_SVG ON CACHE BOOL "" FORCE)
- set(MSDFGEN_DISABLE_PNG ON CACHE BOOL "" FORCE)
- set(MSDFGEN_INSTALL OFF CACHE BOOL "" FORCE)
- add_subdirectory(msdfgen)
+ add_library(glad STATIC ${CMAKE_CURRENT_SOURCE_DIR}/glad/src/glad.c)
+ target_include_directories(glad PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/glad/include)
endif()
diff --git a/third_party/freetype b/third_party/freetype
deleted file mode 160000
index 42608f77f..000000000
--- a/third_party/freetype
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 42608f77f20749dd6ddc9e0536788eaad70ea4b5
diff --git a/third_party/msdfgen b/third_party/msdfgen
deleted file mode 160000
index 1874bcf7d..000000000
--- a/third_party/msdfgen
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 1874bcf7d9624ccc85b4bc9a85d78116f690f35b
diff --git a/third_party/quickjs b/third_party/quickjs
deleted file mode 160000
index f1139494d..000000000
--- a/third_party/quickjs
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit f1139494d18a2053630c5ed3384a42bb70db3c53
diff --git a/tools/eht.py b/tools/eht.py
index 3a012db26..747830368 100644
--- a/tools/eht.py
+++ b/tools/eht.py
@@ -15,7 +15,7 @@ import re
import argparse
from pathlib import Path
from dataclasses import dataclass, field
-from typing import List, Dict, Optional
+from typing import List, Dict, Optional, Set
# =============================================================================
@@ -29,20 +29,11 @@ class Property:
default_value: Optional[str] = None
-@dataclass
-class Method:
- name: str
- return_type: str
- params: List[tuple]
- is_const: bool = False
-
-
@dataclass
class Component:
name: str
namespace: str
properties: List[Property] = field(default_factory=list)
- methods: List[Method] = field(default_factory=list)
header_path: str = ""
@@ -54,6 +45,82 @@ class Enum:
underlying_type: str = "int"
+# =============================================================================
+# Type System
+# =============================================================================
+
+class TypeSystem:
+ """Manages type mappings and conversions."""
+
+ # Types that can be directly bound with value_object
+ PRIMITIVE_TYPES = {
+ 'bool', 'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64',
+ 'f32', 'f64', 'float', 'double', 'int', 'unsigned'
+ }
+
+ # GLM types that are bound as value_objects
+ GLM_TYPES = {'glm::vec2', 'glm::vec3', 'glm::vec4', 'glm::quat', 'glm::uvec2'}
+
+ # Types that should be skipped entirely (too complex to bind)
+ SKIP_TYPES = {'glm::mat4', 'std::vector', 'std::function'}
+
+ # C++ to TypeScript type mapping
+ CPP_TO_TS = {
+ 'bool': 'boolean',
+ 'i8': 'number', 'i16': 'number', 'i32': 'number', 'i64': 'number',
+ 'u8': 'number', 'u16': 'number', 'u32': 'number', 'u64': 'number',
+ 'f32': 'number', 'f64': 'number', 'float': 'number', 'double': 'number',
+ 'int': 'number', 'unsigned': 'number',
+ 'std::string': 'string', 'Entity': 'number',
+ 'glm::vec2': 'Vec2', 'glm::vec3': 'Vec3', 'glm::vec4': 'Vec4',
+ 'glm::quat': 'Quat', 'glm::uvec2': 'UVec2',
+ }
+
+ def __init__(self, enums: List[Enum]):
+ self.enums = enums
+ self.enum_names = set()
+ for e in enums:
+ self.enum_names.add(e.name)
+ if e.namespace:
+ self.enum_names.add(f'{e.namespace}::{e.name}')
+
+ def clean_type(self, cpp_type: str) -> str:
+ return cpp_type.replace('const', '').replace('&', '').strip()
+
+ def is_enum(self, cpp_type: str) -> bool:
+ return self.clean_type(cpp_type) in self.enum_names
+
+ def is_handle(self, cpp_type: str) -> bool:
+ t = self.clean_type(cpp_type)
+ return 'Handle' in t or t.startswith('resource::')
+
+ def is_skip(self, cpp_type: str) -> bool:
+ t = self.clean_type(cpp_type)
+ return any(skip in t for skip in self.SKIP_TYPES)
+
+ def needs_wrapper(self, comp: Component) -> bool:
+ for prop in comp.properties:
+ if self.is_enum(prop.cpp_type) or self.is_handle(prop.cpp_type):
+ return True
+ return False
+
+ def get_js_type(self, cpp_type: str) -> str:
+ t = self.clean_type(cpp_type)
+ if self.is_handle(t):
+ return 'u32'
+ if self.is_enum(t):
+ return 'i32'
+ return t
+
+ def to_typescript(self, cpp_type: str) -> str:
+ t = self.clean_type(cpp_type)
+ if t in self.CPP_TO_TS:
+ return self.CPP_TO_TS[t]
+ if self.is_enum(t) or self.is_handle(t):
+ return 'number'
+ return 'any'
+
+
# =============================================================================
# C++ Parser
# =============================================================================
@@ -67,10 +134,6 @@ class CppParser:
r'([^;]+?)\s+(\w+)\s*'
r'(?:\{([^}]*)\}|=\s*([^;]+))?;'
)
- RE_METHOD = re.compile(
- r'ES_METHOD\s*\(([^)]*)\)\s*'
- r'(\w+(?:\s*[*&])?)\s+(\w+)\s*\(([^)]*)\)'
- )
RE_ENUM_VALUE = re.compile(r'(\w+)\s*(?:=\s*\d+)?\s*,?')
def __init__(self):
@@ -81,41 +144,33 @@ class CppParser:
content = filepath.read_text(encoding='utf-8')
ns_match = self.RE_NAMESPACE.search(content)
namespace = ns_match.group(1) if ns_match else ""
- self._parse_enums(content, namespace, filepath)
+ self._parse_enums(content, namespace)
self._parse_components(content, namespace, filepath)
- def _parse_enums(self, content: str, namespace: str, filepath: Path) -> None:
+ def _parse_enums(self, content: str, namespace: str) -> None:
for match in self.RE_ENUM.finditer(content):
enum_name = match.group(1)
underlying = match.group(2) or "int"
- start = match.end()
- brace_start = content.find('{', start)
+ brace_start = content.find('{', match.end())
if brace_start == -1:
continue
-
brace_end = content.find('};', brace_start)
if brace_end == -1:
continue
enum_body = content[brace_start + 1:brace_end]
- clean_body = re.sub(r'ES_ENUM_VALUE\s*\([^)]*\)', '', enum_body)
- values = [m.group(1) for m in self.RE_ENUM_VALUE.finditer(clean_body)]
- values = [v for v in values if v]
+ values = [m.group(1) for m in self.RE_ENUM_VALUE.finditer(enum_body) if m.group(1)]
self.enums.append(Enum(
- name=enum_name,
- namespace=namespace,
- values=values,
- underlying_type=underlying
+ name=enum_name, namespace=namespace,
+ values=values, underlying_type=underlying
))
def _parse_components(self, content: str, namespace: str, filepath: Path) -> None:
for match in self.RE_COMPONENT.finditer(content):
comp_name = match.group(1)
- comp_start = match.end()
-
- body_start = content.find('{', comp_start)
+ body_start = content.find('{', match.end())
if body_start == -1:
continue
@@ -130,8 +185,7 @@ class CppParser:
body = content[body_start:body_end]
component = Component(
- name=comp_name,
- namespace=namespace,
+ name=comp_name, namespace=namespace,
header_path=str(filepath.as_posix())
)
@@ -139,35 +193,11 @@ class CppParser:
cpp_type = prop_match.group(1).strip()
prop_name = prop_match.group(2).strip()
default = prop_match.group(3) or prop_match.group(4)
-
component.properties.append(Property(
- name=prop_name,
- cpp_type=cpp_type,
+ name=prop_name, cpp_type=cpp_type,
default_value=default.strip() if default else None
))
- for method_match in self.RE_METHOD.finditer(body):
- attrs = method_match.group(1).strip()
- ret_type = method_match.group(2).strip()
- method_name = method_match.group(3).strip()
- params_str = method_match.group(4).strip()
-
- params = []
- if params_str:
- for p in params_str.split(','):
- p = p.strip()
- if p:
- parts = p.rsplit(None, 1)
- if len(parts) == 2:
- params.append((parts[0], parts[1]))
-
- component.methods.append(Method(
- name=method_name,
- return_type=ret_type,
- params=params,
- is_const='const' in attrs
- ))
-
self.components.append(component)
def parse_directory(self, dirpath: Path) -> None:
@@ -179,63 +209,35 @@ class CppParser:
# =============================================================================
-# Type Mapping
-# =============================================================================
-
-class TypeMapper:
- CPP_TO_TS = {
- 'bool': 'boolean',
- 'i8': 'number', 'i16': 'number', 'i32': 'number', 'i64': 'number',
- 'u8': 'number', 'u16': 'number', 'u32': 'number', 'u64': 'number',
- 'f32': 'number', 'f64': 'number',
- 'float': 'number', 'double': 'number',
- 'int': 'number', 'unsigned': 'number',
- 'std::string': 'string',
- 'Entity': 'number',
- 'glm::vec2': 'Vec2',
- 'glm::vec3': 'Vec3',
- 'glm::vec4': 'Vec4',
- 'glm::quat': 'Quat',
- 'glm::mat4': 'Mat4',
- 'glm::uvec2': 'UVec2',
- 'glm::ivec2': 'Vec2',
- }
-
- EMBIND_VALUE_TYPES = {'glm::vec2', 'glm::vec3', 'glm::vec4', 'glm::quat'}
- OPAQUE_TYPES = {'glm::mat4', 'glm::uvec2', 'resource::TextureHandle'}
-
- @classmethod
- def to_typescript(cls, cpp_type: str) -> str:
- cpp_type = cpp_type.replace('const', '').replace('&', '').strip()
- return cls.CPP_TO_TS.get(cpp_type, 'any')
-
- @classmethod
- def is_opaque(cls, cpp_type: str) -> bool:
- cpp_type = cpp_type.replace('const', '').replace('&', '').strip()
- return cpp_type in cls.OPAQUE_TYPES
-
-
-# =============================================================================
-# Code Generators
+# Embind Generator
# =============================================================================
class EmbindGenerator:
def __init__(self, components: List[Component], enums: List[Enum]):
self.components = components
self.enums = enums
+ self.types = TypeSystem(enums)
def generate(self) -> str:
- lines = [
+ lines = self._gen_header()
+ lines.extend(self._gen_includes())
+ lines.extend(self._gen_math_types())
+ lines.extend(self._gen_enums())
+ lines.extend(self._gen_components())
+ lines.extend(self._gen_registry())
+ lines.append('')
+ lines.append('#endif // ES_PLATFORM_WEB')
+ lines.append('')
+ return '\n'.join(lines)
+
+ def _gen_header(self) -> List[str]:
+ return [
'/**',
' * @file WebBindings.generated.cpp',
' * @brief Auto-generated Emscripten embind bindings',
- ' * @details Generated by EHT (ESEngine Header Tool) - DO NOT EDIT',
- ' *',
- ' * @author ESEngine Team',
- ' * @date 2026',
+ ' * @details Generated by EHT - DO NOT EDIT',
' *',
' * @copyright Copyright (c) 2026 ESEngine Team',
- ' * Licensed under the MIT License.',
' */',
'',
'#ifdef ES_PLATFORM_WEB',
@@ -243,20 +245,15 @@ class EmbindGenerator:
'#include <emscripten/bind.h>',
'#include "../ecs/Registry.hpp"',
'#include "../math/Math.hpp"',
- '',
]
- # Include component headers
+ def _gen_includes(self) -> List[str]:
headers = set()
for comp in self.components:
- if comp.header_path:
- # Convert to relative include path (always use forward slashes)
- rel = comp.header_path.replace('\\', '/')
- if 'src/esengine/' in rel:
- rel = '../' + rel.split('src/esengine/')[-1]
+ if comp.header_path and 'src/esengine/' in comp.header_path:
+ rel = '../' + comp.header_path.replace('\\', '/').split('src/esengine/')[-1]
headers.add(f'#include "{rel}"')
-
- lines.extend(sorted(headers))
+ lines = sorted(headers)
lines.extend([
'',
'using namespace emscripten;',
@@ -264,26 +261,7 @@ class EmbindGenerator:
'using namespace esengine::ecs;',
'',
])
-
- # Generate math type bindings
- lines.extend(self._gen_math_types())
-
- # Generate enum bindings
- lines.extend(self._gen_enums())
-
- # Generate component bindings
- lines.extend(self._gen_components())
-
- # Generate Registry bindings
- lines.extend(self._gen_registry())
-
- lines.extend([
- '',
- '#endif // ES_PLATFORM_WEB',
- ''
- ])
-
- return '\n'.join(lines)
+ return lines
def _gen_math_types(self) -> List[str]:
return [
@@ -323,7 +301,6 @@ class EmbindGenerator:
def _gen_enums(self) -> List[str]:
if not self.enums:
return []
-
lines = [
'// =============================================================================',
'// Enums',
@@ -331,15 +308,13 @@ class EmbindGenerator:
'',
'EMSCRIPTEN_BINDINGS(esengine_enums) {',
]
-
for enum in self.enums:
- full_name = f'{enum.namespace}::{enum.name}' if enum.namespace else enum.name
- lines.append(f' enum_<{full_name}>("{enum.name}")')
- for value in enum.values:
- lines.append(f' .value("{value}", {full_name}::{value})')
+ full = f'{enum.namespace}::{enum.name}' if enum.namespace else enum.name
+ lines.append(f' enum_<{full}>("{enum.name}")')
+ for val in enum.values:
+ lines.append(f' .value("{val}", {full}::{val})')
lines[-1] += ';'
lines.append('')
-
lines.append('}')
lines.append('')
return lines
@@ -350,22 +325,73 @@ class EmbindGenerator:
'// Components',
'// =============================================================================',
'',
- 'EMSCRIPTEN_BINDINGS(esengine_components) {',
]
+ # Generate JS wrappers for components that need them
for comp in self.components:
- full_name = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
- lines.append(f' // {comp.name}')
- lines.append(f' value_object<{full_name}>("{comp.name}")')
+ if not self.types.needs_wrapper(comp):
+ continue
+
+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
+ js = f'{comp.name}JS'
+ # JS struct
+ lines.append(f'struct {js} {{')
for prop in comp.properties:
- if TypeMapper.is_opaque(prop.cpp_type):
+ if self.types.is_skip(prop.cpp_type):
continue
- lines.append(f' .field("{prop.name}", &{full_name}::{prop.name})')
+ js_type = self.types.get_js_type(prop.cpp_type)
+ lines.append(f' {js_type} {prop.name};')
+ lines.append('};')
+ lines.append('')
- lines[-1] += ';'
+ # fromJS
+ lines.append(f'{full} {comp.name.lower()}FromJS(const {js}& js) {{')
+ lines.append(f' {full} c;')
+ for prop in comp.properties:
+ if self.types.is_skip(prop.cpp_type):
+ continue
+ t = self.types.clean_type(prop.cpp_type)
+ if self.types.is_handle(t):
+ lines.append(f' c.{prop.name} = {t}(js.{prop.name});')
+ elif self.types.is_enum(t):
+ lines.append(f' c.{prop.name} = static_cast<{t}>(js.{prop.name});')
+ else:
+ lines.append(f' c.{prop.name} = js.{prop.name};')
+ lines.append(' return c;')
+ lines.append('}')
lines.append('')
+ # toJS
+ lines.append(f'{js} {comp.name.lower()}ToJS(const {full}& c) {{')
+ lines.append(f' {js} js;')
+ for prop in comp.properties:
+ if self.types.is_skip(prop.cpp_type):
+ continue
+ if self.types.is_handle(prop.cpp_type):
+ lines.append(f' js.{prop.name} = c.{prop.name}.id();')
+ elif self.types.is_enum(prop.cpp_type):
+ lines.append(f' js.{prop.name} = static_cast<i32>(c.{prop.name});')
+ else:
+ lines.append(f' js.{prop.name} = c.{prop.name};')
+ lines.append(' return js;')
+ lines.append('}')
+ lines.append('')
+
+ # value_object bindings
+ lines.append('EMSCRIPTEN_BINDINGS(esengine_components) {')
+ for comp in self.components:
+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
+ needs_wrap = self.types.needs_wrapper(comp)
+ bind = f'{comp.name}JS' if needs_wrap else full
+
+ lines.append(f' value_object<{bind}>("{comp.name}")')
+ for prop in comp.properties:
+ if self.types.is_skip(prop.cpp_type):
+ continue
+ lines.append(f' .field("{prop.name}", &{bind}::{prop.name})')
+ lines[-1] += ';'
+ lines.append('')
lines.append('}')
lines.append('')
return lines
@@ -393,60 +419,75 @@ class EmbindGenerator:
]
for comp in self.components:
- full_name = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
name = comp.name
-
- lines.extend([
- f' // {name}',
- f' .function("has{name}", optional_override([](Registry& r, u32 e) {{',
- f' return r.has<{full_name}>(static_cast<Entity>(e));',
- ' }))',
- f' .function("get{name}", optional_override([](Registry& r, u32 e) -> {full_name}& {{',
- f' return r.get<{full_name}>(static_cast<Entity>(e));',
- ' }), allow_raw_pointers())',
- f' .function("add{name}", optional_override([](Registry& r, u32 e, const {full_name}& c) {{',
- f' r.emplaceOrReplace<{full_name}>(static_cast<Entity>(e), c);',
- ' }))',
- f' .function("remove{name}", optional_override([](Registry& r, u32 e) {{',
- f' r.remove<{full_name}>(static_cast<Entity>(e));',
- ' }))',
- '',
- ])
+ needs_wrap = self.types.needs_wrapper(comp)
+ js = f'{name}JS'
+ from_js = f'{name.lower()}FromJS'
+ to_js = f'{name.lower()}ToJS'
+
+ lines.append(f' // {name}')
+ lines.append(f' .function("has{name}", optional_override([](Registry& r, u32 e) {{')
+ lines.append(f' return r.has<{full}>(static_cast<Entity>(e));')
+ lines.append(' }))')
+
+ if needs_wrap:
+ lines.append(f' .function("get{name}", optional_override([](Registry& r, u32 e) {{')
+ lines.append(f' return {to_js}(r.get<{full}>(static_cast<Entity>(e)));')
+ lines.append(' }))')
+ lines.append(f' .function("add{name}", optional_override([](Registry& r, u32 e, const {js}& js) {{')
+ lines.append(f' r.emplaceOrReplace<{full}>(static_cast<Entity>(e), {from_js}(js));')
+ lines.append(' }))')
+ else:
+ lines.append(f' .function("get{name}", optional_override([](Registry& r, u32 e) -> {full}& {{')
+ lines.append(f' return r.get<{full}>(static_cast<Entity>(e));')
+ lines.append(' }), allow_raw_pointers())')
+ lines.append(f' .function("add{name}", optional_override([](Registry& r, u32 e, const {full}& c) {{')
+ lines.append(f' r.emplaceOrReplace<{full}>(static_cast<Entity>(e), c);')
+ lines.append(' }))')
+
+ lines.append(f' .function("remove{name}", optional_override([](Registry& r, u32 e) {{')
+ lines.append(f' r.remove<{full}>(static_cast<Entity>(e));')
+ lines.append(' }))')
+ lines.append('')
lines.append(' ;')
lines.append('}')
return lines
+# =============================================================================
+# TypeScript Generator
+# =============================================================================
+
class TypeScriptGenerator:
def __init__(self, components: List[Component], enums: List[Enum]):
self.components = components
self.enums = enums
+ self.types = TypeSystem(enums)
def generate(self) -> str:
- lines = [
+ lines = self._gen_header()
+ lines.extend(self._gen_enums())
+ lines.extend(self._gen_components())
+ lines.extend(self._gen_registry())
+ lines.extend(self._gen_module())
+ return '\n'.join(lines)
+
+ def _gen_header(self) -> List[str]:
+ return [
'/**',
' * @file esengine.d.ts',
' * @brief ESEngine TypeScript Definitions',
- ' * @details Generated by EHT (ESEngine Header Tool) - DO NOT EDIT',
- ' *',
- ' * @author ESEngine Team',
- ' * @date 2026',
+ ' * @details Generated by EHT - DO NOT EDIT',
' *',
' * @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; }',
@@ -456,71 +497,59 @@ class TypeScriptGenerator:
'',
]
- # Generate enums
- if self.enums:
- lines.extend([
- '// =============================================================================',
- '// Enums',
- '// =============================================================================',
- '',
- ])
- for enum in self.enums:
- lines.append(f'export enum {enum.name} {{')
- for i, value in enumerate(enum.values):
- lines.append(f' {value} = {i},')
- lines.append('}')
- lines.append('')
-
- # Generate components
- lines.extend([
- '// =============================================================================',
- '// Components',
- '// =============================================================================',
- '',
- ])
+ def _gen_enums(self) -> List[str]:
+ if not self.enums:
+ return []
+ lines = ['// Enums', '']
+ for enum in self.enums:
+ lines.append(f'export enum {enum.name} {{')
+ for i, val in enumerate(enum.values):
+ lines.append(f' {val} = {i},')
+ lines.append('}')
+ lines.append('')
+ return lines
+
+ def _gen_components(self) -> List[str]:
+ lines = ['// Components', '']
for comp in self.components:
lines.append(f'export interface {comp.name} {{')
for prop in comp.properties:
- ts_type = TypeMapper.to_typescript(prop.cpp_type)
- lines.append(f' {prop.name}: {ts_type};')
+ if self.types.is_skip(prop.cpp_type):
+ continue
+ ts = self.types.to_typescript(prop.cpp_type)
+ lines.append(f' {prop.name}: {ts};')
lines.append('}')
lines.append('')
+ return lines
- # Generate Registry interface
- lines.extend([
- '// =============================================================================',
+ def _gen_registry(self) -> List[str]:
+ lines = [
'// Registry',
- '// =============================================================================',
- '',
'export interface Registry {',
' create(): Entity;',
' destroy(entity: Entity): void;',
' valid(entity: Entity): boolean;',
' entityCount(): number;',
'',
- ])
-
+ ]
for comp in self.components:
- name = comp.name
+ n = comp.name
lines.extend([
- f' has{name}(entity: Entity): boolean;',
- f' get{name}(entity: Entity): {name};',
- f' add{name}(entity: Entity, component: {name}): void;',
- f' remove{name}(entity: Entity): void;',
+ f' has{n}(entity: Entity): boolean;',
+ f' get{n}(entity: Entity): {n};',
+ f' add{n}(entity: Entity, component: {n}): void;',
+ f' remove{n}(entity: Entity): void;',
])
-
lines.append('}')
lines.append('')
+ return lines
- # Module interface
- lines.extend([
- '// =============================================================================',
+ def _gen_module(self) -> List[str]:
+ lines = [
'// Module',
- '// =============================================================================',
- '',
'export interface ESEngineModule {',
' Registry: new () => Registry;',
- ])
+ ]
for comp in self.components:
lines.append(f' {comp.name}: new () => {comp.name};')
lines.extend([
@@ -529,8 +558,7 @@ class TypeScriptGenerator:
'export default function createModule(): Promise<ESEngineModule>;',
''
])
-
- return '\n'.join(lines)
+ return lines
# =============================================================================
@@ -538,43 +566,24 @@ class TypeScriptGenerator:
# =============================================================================
def main():
- parser = argparse.ArgumentParser(
- description='EHT - ESEngine Header Tool',
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog=__doc__
- )
- parser.add_argument(
- '--input', '-i',
- type=Path,
- default=Path('src/esengine/ecs/components'),
- help='Input directory containing component headers'
- )
- parser.add_argument(
- '--output', '-o',
- type=Path,
- default=Path('src/esengine/bindings'),
- help='Output directory for generated C++ bindings'
- )
- parser.add_argument(
- '--ts-output',
- type=Path,
- default=Path('bindings'),
- help='Output directory for TypeScript definitions'
- )
- parser.add_argument(
- '--verbose', '-v',
- action='store_true',
- help='Verbose output'
- )
-
+ parser = argparse.ArgumentParser(description='EHT - ESEngine Header Tool')
+ parser.add_argument('--input', '-i', type=Path, nargs='+',
+ default=[Path('src/esengine/ecs/components')],
+ help='Input directories')
+ parser.add_argument('--output', '-o', type=Path,
+ default=Path('src/esengine/bindings'),
+ help='Output directory for C++ bindings')
+ parser.add_argument('--ts-output', type=Path, default=Path('sdk'),
+ help='Output directory for TypeScript')
+ parser.add_argument('--verbose', '-v', action='store_true')
args = parser.parse_args()
- print(f"EHT - ESEngine Header Tool")
- print(f"Parsing: {args.input}")
+ print("EHT - ESEngine Header Tool")
- # Parse headers
cpp_parser = CppParser()
- cpp_parser.parse_directory(args.input)
+ for input_dir in args.input:
+ print(f"Parsing: {input_dir}")
+ cpp_parser.parse_directory(input_dir)
if args.verbose:
print(f" Found {len(cpp_parser.enums)} enums")
@@ -586,23 +595,19 @@ def main():
print("Warning: No components found!")
return 1
- # Generate embind bindings
args.output.mkdir(parents=True, exist_ok=True)
embind_path = args.output / 'WebBindings.generated.cpp'
-
print(f"Generating: {embind_path}")
embind_gen = EmbindGenerator(cpp_parser.components, cpp_parser.enums)
embind_path.write_text(embind_gen.generate(), encoding='utf-8')
- # Generate TypeScript definitions
args.ts_output.mkdir(parents=True, exist_ok=True)
ts_path = args.ts_output / 'esengine.d.ts'
-
print(f"Generating: {ts_path}")
ts_gen = TypeScriptGenerator(cpp_parser.components, cpp_parser.enums)
ts_path.write_text(ts_gen.generate(), encoding='utf-8')
- print("[OK] EHT complete!")
+ print("[OK] Done!")
return 0