A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: Add event system, command pattern, and selection management
esengine0a7d3c3ec2b4
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 9e1fff5fc..41a89b739 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -63,6 +63,12 @@ set(ESENGINE_HEADERSsrc/esengine/renderer/RenderCommand.hppsrc/esengine/platform/Platform.hppsrc/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)# Platform-specific sourcesdiff --git a/src/esengine/editor/CMakeLists.txt b/src/esengine/editor/CMakeLists.txtindex b19385b9e..6cbca8364 100644--- a/src/esengine/editor/CMakeLists.txt+++ b/src/esengine/editor/CMakeLists.txt@@ -7,6 +7,17 @@ set(EDITOR_SOURCESset(EDITOR_HEADERSEditorApplication.hpp++ # Core subsystem+ core/EditorEvents.hpp+ core/Selection.hpp++ # Command subsystem+ command/Command.hpp+ command/CommandHistory.hpp+ command/MacroCommand.hpp+ command/PropertyCommand.hpp+ command/EditorCommands.hpp)# Create editor executablediff --git a/src/esengine/editor/EditorApplication.cpp b/src/esengine/editor/EditorApplication.cppindex 5cd3fba51..c4503ae7a 100644--- a/src/esengine/editor/EditorApplication.cpp+++ b/src/esengine/editor/EditorApplication.cpp@@ -13,6 +13,7 @@#include "../core/Log.hpp"#include "../renderer/RenderCommand.hpp"#include "../math/Math.hpp"+#include "core/EditorEvents.hpp"namespace esengine {namespace editor {@@ -27,6 +28,8 @@ EditorApplication::EditorApplication().width = 1280,.height = 720}) {+ commandHistory_.setDispatcher(&dispatcher_);+ selection_.setDispatcher(&dispatcher_);}// =============================================================================@@ -35,14 +38,14 @@ EditorApplication::EditorApplication()void EditorApplication::onInit() {ES_LOG_INFO("ESEngine Editor started");- ES_LOG_INFO("Press ESC to exit");+ ES_LOG_INFO("Press ESC to exit, Ctrl+Z to undo, Ctrl+Y to redo");- // Set initial clear color (dark gray)RenderCommand::setClearColor(clearColor_);++ setupEventListeners();}void EditorApplication::onUpdate(f32 deltaTime) {- // Update FPS counterframeTime_ += deltaTime;frameCount_++;@@ -52,24 +55,60 @@ void EditorApplication::onUpdate(f32 deltaTime) {frameTime_ = 0.0;frameCount_ = 0;}++ dispatcher_.update();}void EditorApplication::onRender() {- // Clear the screenRenderCommand::clear();-- // TODO: Render editor UI- // For now, just show a blank window with the editor background color}void EditorApplication::onShutdown() {ES_LOG_INFO("ESEngine Editor shutting down");++ commandHistory_.clear();+ selection_.clear();+ dispatcher_.clear();}void EditorApplication::onKey(KeyCode key, bool pressed) {- if (pressed && key == KeyCode::Escape) {+ if (key == KeyCode::LeftControl || key == KeyCode::RightControl) {+ ctrlPressed_ = pressed;+ return;+ }++ if (key == KeyCode::LeftShift || key == KeyCode::RightShift) {+ shiftPressed_ = pressed;+ return;+ }++ 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;++ default:+ break;+ }}}@@ -77,5 +116,56 @@ void EditorApplication::onResize(u32 width, u32 height) {ES_LOG_DEBUG("Editor window resized to {}x{}", width, height);}+// =============================================================================+// 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::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);+ }));+}+} // namespace editor} // namespace esenginediff --git a/src/esengine/editor/EditorApplication.hpp b/src/esengine/editor/EditorApplication.hppindex 2bce14720..46ebe1640 100644--- a/src/esengine/editor/EditorApplication.hpp+++ b/src/esengine/editor/EditorApplication.hpp@@ -19,6 +19,9 @@// Project includes#include "../core/Application.hpp"#include "../math/Math.hpp"+#include "../events/Dispatcher.hpp"+#include "command/CommandHistory.hpp"+#include "core/Selection.hpp"namespace esengine {namespace editor {@@ -32,6 +35,9 @@ namespace editor {** @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@@ -56,6 +62,28 @@ public:*/~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_; }+protected:// =========================================================================// Application Lifecycle Overrides@@ -99,6 +127,25 @@ protected:void onResize(u32 width, u32 height) 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();+// =========================================================================// Constants// =========================================================================@@ -107,13 +154,29 @@ private:static constexpr f64 FPS_UPDATE_INTERVAL = 1.0;// =========================================================================- // Member Variables+ // Core Editor Systems+ // =========================================================================++ Dispatcher dispatcher_; ///< Central event bus+ CommandHistory commandHistory_; ///< Undo/redo history+ EntitySelection selection_; ///< Entity selection manager++ // =========================================================================+ // State// =========================================================================glm::vec4 clearColor_{0.15f, 0.15f, 0.15f, 1.0f}; ///< Editor background colorf64 frameTime_ = 0.0; ///< Accumulated frame timeu32 frameCount_ = 0; ///< Frame counter for FPSf32 fps_ = 0.0f; ///< Frames per second+ bool ctrlPressed_ = false; ///< Ctrl key state+ bool shiftPressed_ = false; ///< Shift key state++ // =========================================================================+ // Event Connections+ // =========================================================================++ ConnectionHolder eventConnections_; ///< Holds event subscriptions};} // namespace editordiff --git a/src/esengine/editor/command/Command.hpp b/src/esengine/editor/command/Command.hppnew file mode 100644index 000000000..a0007044a--- /dev/null+++ b/src/esengine/editor/command/Command.hpp@@ -0,0 +1,215 @@+/**+ * @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::editordiff --git a/src/esengine/editor/command/CommandHistory.hpp b/src/esengine/editor/command/CommandHistory.hppnew file mode 100644index 000000000..9f47f8874--- /dev/null+++ b/src/esengine/editor/command/CommandHistory.hpp@@ -0,0 +1,552 @@+/**+ * @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::editordiff --git a/src/esengine/editor/command/EditorCommands.hpp b/src/esengine/editor/command/EditorCommands.hppnew file mode 100644index 000000000..fe1bef699--- /dev/null+++ b/src/esengine/editor/command/EditorCommands.hpp@@ -0,0 +1,435 @@+/**+ * @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::editordiff --git a/src/esengine/editor/command/MacroCommand.hpp b/src/esengine/editor/command/MacroCommand.hppnew file mode 100644index 000000000..895758a11--- /dev/null+++ b/src/esengine/editor/command/MacroCommand.hpp@@ -0,0 +1,203 @@+/**+ * @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::editordiff --git a/src/esengine/editor/command/PropertyCommand.hpp b/src/esengine/editor/command/PropertyCommand.hppnew file mode 100644index 000000000..9ae41bf9a--- /dev/null+++ b/src/esengine/editor/command/PropertyCommand.hpp@@ -0,0 +1,319 @@+/**+ * @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::editordiff --git a/src/esengine/editor/core/EditorEvents.hpp b/src/esengine/editor/core/EditorEvents.hppnew file mode 100644index 000000000..9ab47cd91--- /dev/null+++ b/src/esengine/editor/core/EditorEvents.hpp@@ -0,0 +1,342 @@+/**+ * @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::editordiff --git a/src/esengine/editor/core/Selection.hpp b/src/esengine/editor/core/Selection.hppnew file mode 100644index 000000000..a2bddd696--- /dev/null+++ b/src/esengine/editor/core/Selection.hpp@@ -0,0 +1,588 @@+/**+ * @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>) {+ id.rawId = reinterpret_cast<u64>(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::editordiff --git a/src/esengine/events/Connection.hpp b/src/esengine/events/Connection.hppnew file mode 100644index 000000000..bcdc66c22--- /dev/null+++ b/src/esengine/events/Connection.hpp@@ -0,0 +1,238 @@+/**+ * @file Connection.hpp+ * @brief RAII connection handle for event system+ * @details Manages the lifetime of signal connections. When destroyed,+ * automatically disconnects from the signal to prevent dangling+ * callbacks.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../core/Types.hpp"++#include <functional>++namespace esengine {++// =============================================================================+// Type Definitions+// =============================================================================++using CallbackId = u64;+constexpr CallbackId INVALID_CALLBACK_ID = 0;++// =============================================================================+// Connection Class+// =============================================================================++/**+ * @brief RAII handle for signal connections+ *+ * @details Connection manages the lifetime of a callback registration.+ * When the Connection object is destroyed, it automatically+ * disconnects from the signal, preventing memory leaks and+ * dangling callback issues.+ *+ * @note Connection is move-only to prevent accidental disconnection+ * through copies.+ *+ * @code+ * auto conn = signal.connect([](int x) { ... });+ * // Connection is active+ * conn.disconnect(); // Or let conn go out of scope+ * @endcode+ */+class Connection {+public:+ using DisconnectFunc = std::function<void(CallbackId)>;++ /**+ * @brief Default constructor creates an empty connection+ */+ Connection() = default;++ /**+ * @brief Constructs a connection with disconnect callback+ * @param id The callback identifier+ * @param disconnectFunc Function to call when disconnecting+ */+ Connection(CallbackId id, DisconnectFunc disconnectFunc)+ : id_(id), disconnectFunc_(std::move(disconnectFunc)) {}++ /**+ * @brief Destructor automatically disconnects+ */+ ~Connection() {+ disconnect();+ }++ /**+ * @brief Move constructor transfers ownership+ * @param other Connection to move from+ */+ Connection(Connection&& other) noexcept+ : id_(other.id_), disconnectFunc_(std::move(other.disconnectFunc_)) {+ other.id_ = INVALID_CALLBACK_ID;+ other.disconnectFunc_ = nullptr;+ }++ /**+ * @brief Move assignment transfers ownership+ * @param other Connection to move from+ * @return Reference to this+ */+ Connection& operator=(Connection&& other) noexcept {+ if (this != &other) {+ disconnect();+ id_ = other.id_;+ disconnectFunc_ = std::move(other.disconnectFunc_);+ other.id_ = INVALID_CALLBACK_ID;+ other.disconnectFunc_ = nullptr;+ }+ return *this;+ }++ Connection(const Connection&) = delete;+ Connection& operator=(const Connection&) = delete;++ /**+ * @brief Manually disconnect from the signal+ */+ void disconnect() {+ if (isConnected() && disconnectFunc_) {+ disconnectFunc_(id_);+ id_ = INVALID_CALLBACK_ID;+ disconnectFunc_ = nullptr;+ }+ }++ /**+ * @brief Check if still connected+ * @return true if connected, false otherwise+ */+ [[nodiscard]] bool isConnected() const {+ return id_ != INVALID_CALLBACK_ID;+ }++ /**+ * @brief Get the callback ID+ * @return The callback identifier+ */+ [[nodiscard]] CallbackId getId() const {+ return id_;+ }++ /**+ * @brief Release ownership without disconnecting+ * @return The callback ID+ */+ CallbackId release() {+ CallbackId id = id_;+ id_ = INVALID_CALLBACK_ID;+ disconnectFunc_ = nullptr;+ return id;+ }++private:+ CallbackId id_ = INVALID_CALLBACK_ID;+ DisconnectFunc disconnectFunc_ = nullptr;+};++/**+ * @brief Scoped connection that auto-disconnects in a specific scope+ *+ * @details ScopedConnection is similar to Connection but provides+ * explicit scope-based lifetime management.+ */+class ScopedConnection {+public:+ ScopedConnection() = default;++ explicit ScopedConnection(Connection&& conn)+ : connection_(std::move(conn)) {}++ ScopedConnection(ScopedConnection&&) noexcept = default;+ ScopedConnection& operator=(ScopedConnection&&) noexcept = default;++ ScopedConnection(const ScopedConnection&) = delete;+ ScopedConnection& operator=(const ScopedConnection&) = delete;++ [[nodiscard]] bool isConnected() const {+ return connection_.isConnected();+ }++ void disconnect() {+ connection_.disconnect();+ }++ Connection& get() {+ return connection_;+ }++private:+ Connection connection_;+};++/**+ * @brief Container for managing multiple connections+ *+ * @details ConnectionHolder manages a group of connections that should+ * be disconnected together, typically when an object is destroyed.+ */+class ConnectionHolder {+public:+ ConnectionHolder() = default;+ ~ConnectionHolder() = default;++ ConnectionHolder(ConnectionHolder&&) noexcept = default;+ ConnectionHolder& operator=(ConnectionHolder&&) noexcept = default;++ ConnectionHolder(const ConnectionHolder&) = delete;+ ConnectionHolder& operator=(const ConnectionHolder&) = delete;++ /**+ * @brief Add a connection to manage+ * @param conn Connection to add+ */+ void add(Connection&& conn) {+ connections_.push_back(std::move(conn));+ }++ /**+ * @brief Disconnect all managed connections+ */+ void disconnectAll() {+ connections_.clear();+ }++ /**+ * @brief Get the number of active connections+ * @return Number of connections+ */+ [[nodiscard]] usize size() const {+ return connections_.size();+ }++ /**+ * @brief Check if there are any connections+ * @return true if empty+ */+ [[nodiscard]] bool empty() const {+ return connections_.empty();+ }++private:+ std::vector<Connection> connections_;+};++} // namespace esenginediff --git a/src/esengine/events/Dispatcher.hpp b/src/esengine/events/Dispatcher.hppnew file mode 100644index 000000000..9a0abff90--- /dev/null+++ b/src/esengine/events/Dispatcher.hpp@@ -0,0 +1,286 @@+/**+ * @file Dispatcher.hpp+ * @brief Central event dispatcher using type-indexed signals+ * @details Provides a type-safe event bus that routes events to+ * registered handlers based on event type. Supports both+ * immediate triggering and queued event processing.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "Connection.hpp"+#include "Signal.hpp"+#include "Sink.hpp"+#include "../core/Types.hpp"++#include <any>+#include <functional>+#include <memory>+#include <queue>+#include <typeindex>+#include <unordered_map>++namespace esengine {++// =============================================================================+// Dispatcher Class+// =============================================================================++/**+ * @brief Central event dispatcher for the application+ *+ * @details Dispatcher manages signals for different event types and provides+ * a unified interface for event subscription and publication.+ * Events are identified by their C++ type, providing compile-time+ * type safety.+ *+ * @code+ * struct PlayerDied { Entity player; };+ * struct ScoreChanged { int newScore; };+ *+ * Dispatcher dispatcher;+ *+ * // Subscribe+ * auto conn = dispatcher.sink<PlayerDied>().connect(+ * [](const PlayerDied& e) { handlePlayerDeath(e); });+ *+ * // Trigger immediately+ * dispatcher.trigger(PlayerDied{playerEntity});+ *+ * // Queue for later+ * dispatcher.enqueue(ScoreChanged{100});+ * dispatcher.update();+ * @endcode+ */+class Dispatcher {+public:+ Dispatcher() = default;+ ~Dispatcher() = default;++ Dispatcher(Dispatcher&&) = default;+ Dispatcher& operator=(Dispatcher&&) = default;++ Dispatcher(const Dispatcher&) = delete;+ Dispatcher& operator=(const Dispatcher&) = delete;++ /**+ * @brief Get a sink for subscribing to an event type+ *+ * @tparam Event The event type to subscribe to+ * @return Sink for connecting callbacks+ *+ * @code+ * auto conn = dispatcher.sink<MyEvent>().connect(handler);+ * @endcode+ */+ template<typename Event>+ auto sink() -> Sink<Signal<void(const Event&)>> {+ return Sink<Signal<void(const Event&)>>(assure<Event>());+ }++ /**+ * @brief Trigger an event immediately+ *+ * @tparam Event The event type+ * @param event The event to trigger+ *+ * @details All registered handlers are called synchronously+ * in the order they were registered.+ */+ template<typename Event>+ void trigger(const Event& event) {+ auto* signal = find<Event>();+ if (signal) {+ signal->publish(event);+ }+ }++ /**+ * @brief Trigger an event constructed in-place+ *+ * @tparam Event The event type+ * @tparam Args Constructor argument types+ * @param args Arguments to construct the event+ */+ template<typename Event, typename... Args>+ void trigger(Args&&... args) {+ trigger(Event{std::forward<Args>(args)...});+ }++ /**+ * @brief Queue an event for later processing+ *+ * @tparam Event The event type+ * @param event The event to queue+ *+ * @details Events are processed when update() is called.+ */+ template<typename Event>+ void enqueue(const Event& event) {+ assure<Event>();+ auto typeId = std::type_index(typeid(Event));+ eventQueue_.push({typeId, std::any(event)});+ }++ /**+ * @brief Queue an event constructed in-place+ *+ * @tparam Event The event type+ * @tparam Args Constructor argument types+ * @param args Arguments to construct the event+ */+ template<typename Event, typename... Args>+ void enqueue(Args&&... args) {+ enqueue(Event{std::forward<Args>(args)...});+ }++ /**+ * @brief Process all queued events+ *+ * @details Call this once per frame to process queued events.+ * Events are processed in FIFO order.+ */+ void update() {+ while (!eventQueue_.empty()) {+ auto& [typeId, eventData] = eventQueue_.front();++ auto handlerIt = queueHandlers_.find(typeId);+ if (handlerIt != queueHandlers_.end()) {+ handlerIt->second(eventData);+ }++ eventQueue_.pop();+ }+ }++ /**+ * @brief Clear all queued events without processing+ */+ void clearQueue() {+ std::queue<QueuedEvent> empty;+ std::swap(eventQueue_, empty);+ }++ /**+ * @brief Check if there are queued events+ * @return true if the queue is not empty+ */+ [[nodiscard]] bool hasQueuedEvents() const {+ return !eventQueue_.empty();+ }++ /**+ * @brief Get the number of queued events+ * @return Number of events in queue+ */+ [[nodiscard]] usize queueSize() const {+ return eventQueue_.size();+ }++ /**+ * @brief Clear all signals and handlers+ */+ void clear() {+ signals_.clear();+ queueHandlers_.clear();+ clearQueue();+ }++ /**+ * @brief Check if there are subscribers for an event type+ *+ * @tparam Event The event type+ * @return true if there are subscribers+ */+ template<typename Event>+ [[nodiscard]] bool hasSubscribers() const {+ auto* signal = find<Event>();+ return signal && !signal->empty();+ }++ /**+ * @brief Get the number of subscribers for an event type+ *+ * @tparam Event The event type+ * @return Number of subscribers+ */+ template<typename Event>+ [[nodiscard]] usize subscriberCount() const {+ auto* signal = find<Event>();+ return signal ? signal->size() : 0;+ }++private:+ using QueueHandler = std::function<void(const std::any&)>;++ struct QueuedEvent {+ std::type_index typeId;+ std::any data;+ };++ struct SignalWrapperBase {+ virtual ~SignalWrapperBase() = default;+ };++ template<typename Event>+ struct SignalWrapperTyped : SignalWrapperBase {+ Signal<void(const Event&)> signal;+ };++ template<typename Event>+ Signal<void(const Event&)>& assure() {+ auto typeId = std::type_index(typeid(Event));+ auto it = signals_.find(typeId);++ if (it == signals_.end()) {+ auto wrapper = makeUnique<SignalWrapperTyped<Event>>();+ auto* ptr = &wrapper->signal;++ signals_.emplace(typeId, std::move(wrapper));++ queueHandlers_.emplace(typeId, [ptr](const std::any& data) {+ ptr->publish(std::any_cast<const Event&>(data));+ });++ return *ptr;+ }++ return static_cast<SignalWrapperTyped<Event>*>(it->second.get())->signal;+ }++ template<typename Event>+ Signal<void(const Event&)>* find() {+ auto typeId = std::type_index(typeid(Event));+ auto it = signals_.find(typeId);+ if (it != signals_.end()) {+ return &static_cast<SignalWrapperTyped<Event>*>(it->second.get())->signal;+ }+ return nullptr;+ }++ template<typename Event>+ const Signal<void(const Event&)>* find() const {+ auto typeId = std::type_index(typeid(Event));+ auto it = signals_.find(typeId);+ if (it != signals_.end()) {+ return &static_cast<const SignalWrapperTyped<Event>*>(it->second.get())->signal;+ }+ return nullptr;+ }++ std::unordered_map<std::type_index, Unique<SignalWrapperBase>> signals_;+ std::unordered_map<std::type_index, QueueHandler> queueHandlers_;+ std::queue<QueuedEvent> eventQueue_;+};++} // namespace esenginediff --git a/src/esengine/events/Events.hpp b/src/esengine/events/Events.hppnew file mode 100644index 000000000..e2f623d61--- /dev/null+++ b/src/esengine/events/Events.hpp@@ -0,0 +1,18 @@+/**+ * @file Events.hpp+ * @brief Aggregate header for the event system+ * @details Includes all event system components for convenient import.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#pragma once++#include "Connection.hpp"+#include "Signal.hpp"+#include "Sink.hpp"+#include "Dispatcher.hpp"diff --git a/src/esengine/events/Signal.hpp b/src/esengine/events/Signal.hppnew file mode 100644index 000000000..c147bee0b--- /dev/null+++ b/src/esengine/events/Signal.hpp@@ -0,0 +1,280 @@+/**+ * @file Signal.hpp+ * @brief Type-safe signal implementation for event system+ * @details Provides a publish-subscribe mechanism with type safety at+ * compile time. Signals can have multiple subscribers and+ * support both free functions and member functions.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "Connection.hpp"+#include "../core/Types.hpp"++#include <functional>+#include <unordered_map>+#include <vector>+#include <algorithm>++namespace esengine {++// Forward declaration+template<typename Signature>+class Signal;++template<typename Signature>+class Sink;++// =============================================================================+// Signal Class (void return)+// =============================================================================++/**+ * @brief Type-safe signal for event publishing+ *+ * @details Signal<void(Args...)> allows publishing events to multiple+ * subscribers. Connections are managed through the Sink interface+ * which returns RAII Connection handles.+ *+ * @tparam Args The argument types for the callback+ *+ * @code+ * Signal<void(int, float)> signal;+ * auto conn = Sink(signal).connect([](int a, float b) {+ * // Handle event+ * });+ * signal.publish(42, 3.14f);+ * @endcode+ */+template<typename... Args>+class Signal<void(Args...)> {+public:+ using Callback = std::function<void(Args...)>;++ Signal() = default;+ ~Signal() = default;++ Signal(Signal&&) noexcept = default;+ Signal& operator=(Signal&&) noexcept = default;++ Signal(const Signal&) = delete;+ Signal& operator=(const Signal&) = delete;++ /**+ * @brief Publish an event to all subscribers+ * @param args Arguments to pass to callbacks+ */+ void publish(Args... args) {+ if (publishing_) {+ for (const auto& [id, callback] : callbacks_) {+ if (callback) {+ callback(args...);+ }+ }+ } else {+ publishing_ = true;+ for (const auto& [id, callback] : callbacks_) {+ if (callback) {+ callback(args...);+ }+ }+ publishing_ = false;+ processPendingOperations();+ }+ }++ /**+ * @brief Get the number of active subscribers+ * @return Number of subscribers+ */+ [[nodiscard]] usize size() const {+ return callbacks_.size();+ }++ /**+ * @brief Check if there are any subscribers+ * @return true if no subscribers+ */+ [[nodiscard]] bool empty() const {+ return callbacks_.empty();+ }++private:+ friend class Sink<Signal<void(Args...)>>;++ /**+ * @brief Connect a callback (called by Sink)+ * @param callback The callback to connect+ * @return Callback ID for disconnection+ */+ CallbackId connect(Callback callback) {+ CallbackId id = nextId_++;+ if (publishing_) {+ pendingAdds_.emplace_back(id, std::move(callback));+ } else {+ callbacks_.emplace(id, std::move(callback));+ }+ return id;+ }++ /**+ * @brief Disconnect a callback (called by Connection)+ * @param id The callback ID to disconnect+ */+ void disconnect(CallbackId id) {+ if (publishing_) {+ pendingRemoves_.push_back(id);+ } else {+ callbacks_.erase(id);+ }+ }++ /**+ * @brief Process pending add/remove operations after publishing+ */+ void processPendingOperations() {+ for (auto id : pendingRemoves_) {+ callbacks_.erase(id);+ }+ pendingRemoves_.clear();++ for (auto& [id, callback] : pendingAdds_) {+ callbacks_.emplace(id, std::move(callback));+ }+ pendingAdds_.clear();+ }++ std::unordered_map<CallbackId, Callback> callbacks_;+ std::vector<std::pair<CallbackId, Callback>> pendingAdds_;+ std::vector<CallbackId> pendingRemoves_;+ CallbackId nextId_ = 1;+ bool publishing_ = false;+};++/**+ * @brief Specialization for signals with return values+ *+ * @details This specialization collects return values from all callbacks.+ * Useful for query-style events where multiple handlers can+ * contribute results.+ *+ * @tparam Ret The return type+ * @tparam Args The argument types+ */+template<typename Ret, typename... Args>+class Signal<Ret(Args...)> {+public:+ using Callback = std::function<Ret(Args...)>;++ Signal() = default;+ ~Signal() = default;++ Signal(Signal&&) noexcept = default;+ Signal& operator=(Signal&&) noexcept = default;++ Signal(const Signal&) = delete;+ Signal& operator=(const Signal&) = delete;++ /**+ * @brief Publish an event and collect results+ * @param args Arguments to pass to callbacks+ * @return Vector of results from all callbacks+ */+ std::vector<Ret> publish(Args... args) {+ std::vector<Ret> results;+ results.reserve(callbacks_.size());++ publishing_ = true;+ for (const auto& [id, callback] : callbacks_) {+ if (callback) {+ results.push_back(callback(args...));+ }+ }+ publishing_ = false;+ processPendingOperations();++ return results;+ }++ /**+ * @brief Publish and return first non-default result+ * @param defaultValue Value to return if no results+ * @param args Arguments to pass to callbacks+ * @return First result or default+ */+ Ret publishFirst(Ret defaultValue, Args... args) {+ publishing_ = true;+ for (const auto& [id, callback] : callbacks_) {+ if (callback) {+ Ret result = callback(args...);+ if (result != defaultValue) {+ publishing_ = false;+ processPendingOperations();+ return result;+ }+ }+ }+ publishing_ = false;+ processPendingOperations();+ return defaultValue;+ }++ [[nodiscard]] usize size() const {+ return callbacks_.size();+ }++ [[nodiscard]] bool empty() const {+ return callbacks_.empty();+ }++private:+ friend class Sink<Signal<Ret(Args...)>>;++ CallbackId connect(Callback callback) {+ CallbackId id = nextId_++;+ if (publishing_) {+ pendingAdds_.emplace_back(id, std::move(callback));+ } else {+ callbacks_.emplace(id, std::move(callback));+ }+ return id;+ }++ void disconnect(CallbackId id) {+ if (publishing_) {+ pendingRemoves_.push_back(id);+ } else {+ callbacks_.erase(id);+ }+ }++ void processPendingOperations() {+ for (auto id : pendingRemoves_) {+ callbacks_.erase(id);+ }+ pendingRemoves_.clear();++ for (auto& [id, callback] : pendingAdds_) {+ callbacks_.emplace(id, std::move(callback));+ }+ pendingAdds_.clear();+ }++ std::unordered_map<CallbackId, Callback> callbacks_;+ std::vector<std::pair<CallbackId, Callback>> pendingAdds_;+ std::vector<CallbackId> pendingRemoves_;+ CallbackId nextId_ = 1;+ bool publishing_ = false;+};++} // namespace esenginediff --git a/src/esengine/events/Sink.hpp b/src/esengine/events/Sink.hppnew file mode 100644index 000000000..56898af96--- /dev/null+++ b/src/esengine/events/Sink.hpp@@ -0,0 +1,171 @@+/**+ * @file Sink.hpp+ * @brief Connection interface for signals+ * @details Provides a safe interface for connecting callbacks to signals.+ * Returns RAII Connection handles that automatically disconnect+ * when destroyed.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "Connection.hpp"+#include "Signal.hpp"++#include <type_traits>++namespace esengine {++// =============================================================================+// Sink Class for void(Args...)+// =============================================================================++/**+ * @brief Connection interface for Signal<void(Args...)>+ *+ * @details Sink provides a safe way to connect callbacks to signals.+ * All connect methods return Connection objects that manage+ * the callback lifetime.+ *+ * @tparam Args The signal's argument types+ *+ * @code+ * Signal<void(int)> signal;+ * Sink sink(signal);+ *+ * // Lambda+ * auto conn1 = sink.connect([](int x) { ... });+ *+ * // Member function+ * auto conn2 = sink.connect<&MyClass::onEvent>(instance);+ * @endcode+ */+template<typename... Args>+class Sink<Signal<void(Args...)>> {+public:+ using SignalType = Signal<void(Args...)>;+ using Callback = typename SignalType::Callback;++ /**+ * @brief Construct a sink for the given signal+ * @param signal The signal to connect to+ */+ explicit Sink(SignalType& signal) : signal_(&signal) {}++ /**+ * @brief Connect a callback function+ * @param callback The callback to connect+ * @return RAII Connection handle+ */+ [[nodiscard]] Connection connect(Callback callback) {+ CallbackId id = signal_->connect(std::move(callback));+ return Connection(id, [signal = signal_](CallbackId callbackId) {+ signal->disconnect(callbackId);+ });+ }++ /**+ * @brief Connect a member function+ *+ * @tparam Func Pointer to member function+ * @tparam T Instance type+ * @param instance The object instance+ * @return RAII Connection handle+ *+ * @code+ * sink.connect<&MyClass::onEvent>(myInstance);+ * @endcode+ */+ template<auto Func, typename T>+ [[nodiscard]] Connection connect(T& instance) {+ return connect([&instance](Args... args) {+ (instance.*Func)(args...);+ });+ }++ /**+ * @brief Connect a member function with pointer+ *+ * @tparam Func Pointer to member function+ * @tparam T Instance type+ * @param instance Pointer to the object+ * @return RAII Connection handle+ */+ template<auto Func, typename T>+ [[nodiscard]] Connection connect(T* instance) {+ return connect([instance](Args... args) {+ (instance->*Func)(args...);+ });+ }++private:+ SignalType* signal_;+};++// =============================================================================+// Sink Class for Ret(Args...)+// =============================================================================++/**+ * @brief Connection interface for Signal<Ret(Args...)>+ *+ * @tparam Ret The return type+ * @tparam Args The argument types+ */+template<typename Ret, typename... Args>+class Sink<Signal<Ret(Args...)>> {+public:+ using SignalType = Signal<Ret(Args...)>;+ using Callback = typename SignalType::Callback;++ explicit Sink(SignalType& signal) : signal_(&signal) {}++ [[nodiscard]] Connection connect(Callback callback) {+ CallbackId id = signal_->connect(std::move(callback));+ return Connection(id, [signal = signal_](CallbackId callbackId) {+ signal->disconnect(callbackId);+ });+ }++ template<auto Func, typename T>+ [[nodiscard]] Connection connect(T& instance) {+ return connect([&instance](Args... args) -> Ret {+ return (instance.*Func)(args...);+ });+ }++ template<auto Func, typename T>+ [[nodiscard]] Connection connect(T* instance) {+ return connect([instance](Args... args) -> Ret {+ return (instance->*Func)(args...);+ });+ }++private:+ SignalType* signal_;+};++// =============================================================================+// Helper Functions+// =============================================================================++/**+ * @brief Create a sink for a signal+ * @param signal The signal to create a sink for+ * @return Sink object+ */+template<typename SignalType>+auto sink(SignalType& signal) {+ return Sink<SignalType>(signal);+}++} // namespace esenginediff --git a/src/esengine/platform/Platform.hpp b/src/esengine/platform/Platform.hppindex 0b0becf0e..b788f75d2 100644--- a/src/esengine/platform/Platform.hpp+++ b/src/esengine/platform/Platform.hpp@@ -65,17 +65,29 @@ struct TouchPoint {*/enum class KeyCode : u32 {Unknown = 0,- Space = 32, ///< Spacebar- Enter = 13, ///< Enter/Return- Escape = 27, ///< Escape key- Left = 37, ///< Left arrow- Up = 38, ///< Up arrow- Right = 39, ///< Right arrow- Down = 40, ///< Down arrow- A = 65, ///< A key- D = 68, ///< D key- S = 83, ///< S key- W = 87 ///< W key+ Space = 32, ///< Spacebar+ Enter = 13, ///< Enter/Return+ Escape = 27, ///< Escape key+ Left = 37, ///< Left arrow+ Up = 38, ///< Up arrow+ Right = 39, ///< Right arrow+ Down = 40, ///< Down arrow++ // Letter keys+ A = 65, ///< A key+ D = 68, ///< D key+ S = 83, ///< S key+ W = 87, ///< W key+ Y = 89, ///< Y key+ Z = 90, ///< Z key++ // Modifier keys+ LeftShift = 16, ///< Left Shift key+ RightShift = 161, ///< Right Shift key+ LeftControl = 17, ///< Left Control key+ RightControl = 162, ///< Right Control key+ LeftAlt = 18, ///< Left Alt key+ RightAlt = 165 ///< Right Alt key};// =============================================================================diff --git a/src/esengine/platform/native/NativePlatform.cpp b/src/esengine/platform/native/NativePlatform.cppindex 444f7cd6d..f849e09d9 100644--- a/src/esengine/platform/native/NativePlatform.cpp+++ b/src/esengine/platform/native/NativePlatform.cpp@@ -362,18 +362,26 @@ void NativePlatform::glfwWindowCloseCallback(GLFWwindow* window) {KeyCode NativePlatform::convertKeyCode(int glfwKey) {switch (glfwKey) {- case GLFW_KEY_SPACE: return KeyCode::Space;- case GLFW_KEY_ENTER: return KeyCode::Enter;- case GLFW_KEY_ESCAPE: return KeyCode::Escape;- case GLFW_KEY_LEFT: return KeyCode::Left;- case GLFW_KEY_UP: return KeyCode::Up;- case GLFW_KEY_RIGHT: return KeyCode::Right;- case GLFW_KEY_DOWN: return KeyCode::Down;- case GLFW_KEY_A: return KeyCode::A;- case GLFW_KEY_D: return KeyCode::D;- case GLFW_KEY_S: return KeyCode::S;- case GLFW_KEY_W: return KeyCode::W;- default: return KeyCode::Unknown;+ case GLFW_KEY_SPACE: return KeyCode::Space;+ case GLFW_KEY_ENTER: return KeyCode::Enter;+ case GLFW_KEY_ESCAPE: return KeyCode::Escape;+ case GLFW_KEY_LEFT: return KeyCode::Left;+ case GLFW_KEY_UP: return KeyCode::Up;+ case GLFW_KEY_RIGHT: return KeyCode::Right;+ case GLFW_KEY_DOWN: return KeyCode::Down;+ case GLFW_KEY_A: return KeyCode::A;+ case GLFW_KEY_D: return KeyCode::D;+ case GLFW_KEY_S: return KeyCode::S;+ case GLFW_KEY_W: return KeyCode::W;+ case GLFW_KEY_Y: return KeyCode::Y;+ case GLFW_KEY_Z: return KeyCode::Z;+ case GLFW_KEY_LEFT_SHIFT: return KeyCode::LeftShift;+ case GLFW_KEY_RIGHT_SHIFT: return KeyCode::RightShift;+ case GLFW_KEY_LEFT_CONTROL: return KeyCode::LeftControl;+ case GLFW_KEY_RIGHT_CONTROL: return KeyCode::RightControl;+ case GLFW_KEY_LEFT_ALT: return KeyCode::LeftAlt;+ case GLFW_KEY_RIGHT_ALT: return KeyCode::RightAlt;+ default: return KeyCode::Unknown;}}diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex f9dbfd857..f2f237634 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -1,10 +1,24 @@# ESEngine Tests# Simple test framework (minimal, no external dependencies)++# ECS testsadd_executable(test_ecsecs/test_registry.cpp)target_link_libraries(test_ecs PRIVATE esengine)--# Add testadd_test(NAME test_ecs COMMAND test_ecs)++# Event system tests+add_executable(test_events+ events/test_events.cpp+)+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)diff --git a/tests/editor/test_commands.cpp b/tests/editor/test_commands.cppnew file mode 100644index 000000000..c3a1ef0c8--- /dev/null+++ b/tests/editor/test_commands.cpp@@ -0,0 +1,376 @@+/**+ * @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/tests/events/test_events.cpp b/tests/events/test_events.cppnew file mode 100644index 000000000..f71e1d56d--- /dev/null+++ b/tests/events/test_events.cpp@@ -0,0 +1,260 @@+/**+ * @file test_events.cpp+ * @brief Unit tests for the event system+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#include <esengine/events/Events.hpp>+#include <iostream>+#include <cassert>++// 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 events+struct TestEvent {+ int value;+};++struct AnotherEvent {+ std::string message;+};++// Signal Tests+TEST(signal_basic) {+ esengine::Signal<void(int)> signal;+ int received = 0;++ auto conn = esengine::sink(signal).connect([&received](int x) {+ received = x;+ });++ signal.publish(42);+ ASSERT_EQ(received, 42);+}++TEST(signal_multiple_subscribers) {+ esengine::Signal<void(int)> signal;+ int sum = 0;++ auto conn1 = esengine::sink(signal).connect([&sum](int x) {+ sum += x;+ });++ auto conn2 = esengine::sink(signal).connect([&sum](int x) {+ sum += x * 2;+ });++ signal.publish(10);+ ASSERT_EQ(sum, 30); // 10 + 20+}++TEST(signal_disconnect) {+ esengine::Signal<void(int)> signal;+ int count = 0;++ auto conn = esengine::sink(signal).connect([&count](int) {+ count++;+ });++ signal.publish(1);+ ASSERT_EQ(count, 1);++ conn.disconnect();++ signal.publish(1);+ ASSERT_EQ(count, 1); // No change after disconnect+}++TEST(signal_raii_disconnect) {+ esengine::Signal<void(int)> signal;+ int count = 0;++ {+ auto conn = esengine::sink(signal).connect([&count](int) {+ count++;+ });++ signal.publish(1);+ ASSERT_EQ(count, 1);+ } // conn goes out of scope, auto-disconnect++ signal.publish(1);+ ASSERT_EQ(count, 1); // No change after auto-disconnect+}++TEST(connection_holder) {+ esengine::Signal<void(int)> signal;+ int count = 0;++ esengine::ConnectionHolder holder;++ holder.add(esengine::sink(signal).connect([&count](int) {+ count++;+ }));++ holder.add(esengine::sink(signal).connect([&count](int) {+ count++;+ }));++ signal.publish(1);+ ASSERT_EQ(count, 2);++ holder.disconnectAll();++ signal.publish(1);+ ASSERT_EQ(count, 2); // No change after disconnect+}++// Dispatcher Tests+TEST(dispatcher_trigger) {+ esengine::Dispatcher dispatcher;+ int received = 0;++ auto conn = dispatcher.sink<TestEvent>().connect([&received](const TestEvent& e) {+ received = e.value;+ });++ dispatcher.trigger(TestEvent{42});+ ASSERT_EQ(received, 42);+}++TEST(dispatcher_multiple_event_types) {+ esengine::Dispatcher dispatcher;+ int intValue = 0;+ std::string strValue;++ auto conn1 = dispatcher.sink<TestEvent>().connect([&intValue](const TestEvent& e) {+ intValue = e.value;+ });++ auto conn2 = dispatcher.sink<AnotherEvent>().connect([&strValue](const AnotherEvent& e) {+ strValue = e.message;+ });++ dispatcher.trigger(TestEvent{123});+ dispatcher.trigger(AnotherEvent{"hello"});++ ASSERT_EQ(intValue, 123);+ ASSERT_EQ(strValue, "hello");+}++TEST(dispatcher_queue) {+ esengine::Dispatcher dispatcher;+ int received = 0;++ auto conn = dispatcher.sink<TestEvent>().connect([&received](const TestEvent& e) {+ received = e.value;+ });++ dispatcher.enqueue(TestEvent{99});+ ASSERT_EQ(received, 0); // Not yet processed++ dispatcher.update();+ ASSERT_EQ(received, 99); // Now processed+}++TEST(dispatcher_queue_multiple) {+ esengine::Dispatcher dispatcher;+ std::vector<int> values;++ auto conn = dispatcher.sink<TestEvent>().connect([&values](const TestEvent& e) {+ values.push_back(e.value);+ });++ dispatcher.enqueue(TestEvent{1});+ dispatcher.enqueue(TestEvent{2});+ dispatcher.enqueue(TestEvent{3});++ ASSERT_TRUE(values.empty());++ dispatcher.update();++ ASSERT_EQ(values.size(), 3u);+ ASSERT_EQ(values[0], 1);+ ASSERT_EQ(values[1], 2);+ ASSERT_EQ(values[2], 3);+}++TEST(dispatcher_has_subscribers) {+ esengine::Dispatcher dispatcher;++ ASSERT_TRUE(!dispatcher.hasSubscribers<TestEvent>());++ {+ auto conn = dispatcher.sink<TestEvent>().connect([](const TestEvent&) {});+ ASSERT_TRUE(dispatcher.hasSubscribers<TestEvent>());+ conn.disconnect();+ }++ ASSERT_TRUE(!dispatcher.hasSubscribers<TestEvent>());+}++TEST(dispatcher_clear) {+ esengine::Dispatcher dispatcher;+ int count = 0;++ auto conn = dispatcher.sink<TestEvent>().connect([&count](const TestEvent&) {+ count++;+ });++ dispatcher.enqueue(TestEvent{1});+ dispatcher.enqueue(TestEvent{2});++ // Must disconnect before clear() to avoid dangling pointer in Connection+ conn.disconnect();++ dispatcher.clear();++ ASSERT_EQ(dispatcher.queueSize(), 0u);+}++int main() {+ std::cout << "ESEngine Events Unit Tests" << std::endl;+ std::cout << "===========================" << std::endl;++ // Signal tests+ RUN_TEST(signal_basic);+ RUN_TEST(signal_multiple_subscribers);+ RUN_TEST(signal_disconnect);+ RUN_TEST(signal_raii_disconnect);+ RUN_TEST(connection_holder);++ // Dispatcher tests+ RUN_TEST(dispatcher_trigger);+ RUN_TEST(dispatcher_multiple_event_types);+ RUN_TEST(dispatcher_queue);+ RUN_TEST(dispatcher_queue_multiple);+ RUN_TEST(dispatcher_has_subscribers);+ RUN_TEST(dispatcher_clear);++ std::cout << "===========================" << std::endl;+ std::cout << "Results: " << passed << " passed, " << failed << " failed" << std::endl;++ return failed > 0 ? 1 : 0;+}