Skip to content

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

docs: Add comprehensive Doxygen documentation to all header files

esenginee9619d9925b3
diff --git a/src/esengine/ESEngine.hpp b/src/esengine/ESEngine.hpp
index d22313d9f..b4ac33314 100644
--- a/src/esengine/ESEngine.hpp
+++ b/src/esengine/ESEngine.hpp
@@ -1,7 +1,21 @@
+/**
+ * @file ESEngine.hpp
+ * @brief Main header file for ESEngine - includes all public API
+ * @details ESEngine is a lightweight game engine designed for WebAssembly
+ * and WeChat MiniGames. This umbrella header provides convenient
+ * access to all engine subsystems.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
-// ESEngine - Game Engine for WebAssembly and WeChat MiniGames
-// Main header file - includes all public API
+// =============================================================================
+// Includes
+// =============================================================================
// Core
#include "core/Types.hpp"
@@ -31,15 +45,41 @@
#include "platform/Platform.hpp"
#include "platform/input/Input.hpp"
-// Version info
+// =============================================================================
+// Version Information
+// =============================================================================
+
+/** @brief Major version number */
#define ESENGINE_VERSION_MAJOR 0
+/** @brief Minor version number */
#define ESENGINE_VERSION_MINOR 1
+/** @brief Patch version number */
#define ESENGINE_VERSION_PATCH 0
+/** @brief Full version string */
#define ESENGINE_VERSION_STRING "0.1.0"
-// Entry point macro for applications
+// =============================================================================
+// Entry Point Macro
+// =============================================================================
+
+/**
+ * @brief Application entry point macro
+ * @details Defines the appropriate entry point based on the target platform.
+ * - Web: Uses Emscripten exports for JavaScript interop
+ * - Native: Standard main() function
+ *
+ * @param AppClass The user's Application-derived class
+ *
+ * @code
+ * class MyGame : public esengine::Application {
+ * void onInit() override { ... }
+ * void onUpdate(f32 dt) override { ... }
+ * };
+ * ES_MAIN(MyGame)
+ * @endcode
+ */
#ifdef ES_PLATFORM_WEB
- // Web: No main needed, entry is through es_init
+ #include <emscripten.h>
#define ES_MAIN(AppClass) \
extern "C" { \
static AppClass* g_app = nullptr; \
@@ -49,7 +89,6 @@
} \
}
#else
- // Native: Standard main
#define ES_MAIN(AppClass) \
int main(int argc, char** argv) { \
(void)argc; (void)argv; \
diff --git a/src/esengine/core/Application.hpp b/src/esengine/core/Application.hpp
index 0204414c8..67cf5900a 100644
--- a/src/esengine/core/Application.hpp
+++ b/src/esengine/core/Application.hpp
@@ -1,5 +1,22 @@
+/**
+ * @file Application.hpp
+ * @brief Base application class for ESEngine applications
+ * @details Provides the main application framework including lifecycle
+ * management, event handling, and access to engine subsystems.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "Types.hpp"
#include "../platform/Platform.hpp"
#include "../ecs/Registry.hpp"
@@ -7,62 +24,214 @@
namespace esengine {
-// Application configuration
+// =============================================================================
+// Application Configuration
+// =============================================================================
+
+/**
+ * @brief Configuration settings for Application initialization
+ *
+ * @details Controls window properties and rendering settings.
+ * Pass to Application constructor to customize behavior.
+ *
+ * @code
+ * ApplicationConfig config;
+ * config.title = "My Game";
+ * config.width = 1280;
+ * config.height = 720;
+ * MyApp app(config);
+ * @endcode
+ */
struct ApplicationConfig {
+ /** @brief Window title (native) or canvas title (web) */
std::string title = "ESEngine Application";
+ /** @brief Initial viewport width in pixels */
u32 width = 800;
+ /** @brief Initial viewport height in pixels */
u32 height = 600;
+ /** @brief Enable vertical sync */
bool vsync = true;
};
-// Base application class - users derive from this
+// =============================================================================
+// Application Class
+// =============================================================================
+
+/**
+ * @brief Base class for ESEngine applications
+ *
+ * @details Users derive from this class and override lifecycle hooks
+ * to implement game logic. The Application manages:
+ * - Platform abstraction and window/context creation
+ * - Main game loop with fixed timestep
+ * - ECS Registry for entity/component management
+ * - Event dispatching (input, resize, etc.)
+ *
+ * @code
+ * class MyGame : public esengine::Application {
+ * public:
+ * MyGame() : Application({.title = "My Game", .width = 1280}) {}
+ *
+ * protected:
+ * void onInit() override {
+ * // Load assets, create entities
+ * }
+ *
+ * void onUpdate(f32 deltaTime) override {
+ * // Game logic, physics, AI
+ * }
+ *
+ * void onRender() override {
+ * // Drawing code
+ * }
+ * };
+ *
+ * ES_MAIN(MyGame)
+ * @endcode
+ *
+ * @note Application is a singleton - only one instance can exist.
+ */
class Application {
public:
+ /**
+ * @brief Constructs the application with given configuration
+ * @param config Application settings (window size, title, etc.)
+ */
Application(const ApplicationConfig& config = {});
+
+ /** @brief Virtual destructor for proper cleanup */
virtual ~Application();
// Non-copyable
Application(const Application&) = delete;
Application& operator=(const Application&) = delete;
- // Main entry point
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
+
+ /**
+ * @brief Starts the main application loop
+ * @details Initializes subsystems, enters the main loop, and handles
+ * shutdown when complete. On web platforms, this sets up
+ * the Emscripten main loop.
+ */
void run();
- // Request application to close
+ /**
+ * @brief Requests the application to close
+ * @details Sets a flag that causes the main loop to exit gracefully
+ * after the current frame completes.
+ */
void quit();
+ // =========================================================================
// Accessors
+ // =========================================================================
+
+ /**
+ * @brief Gets the platform abstraction layer
+ * @return Reference to the Platform instance
+ */
Platform& getPlatform() { return *platform_; }
+
+ /**
+ * @brief Gets the ECS registry
+ * @return Reference to the Registry for entity/component management
+ */
ecs::Registry& getRegistry() { return registry_; }
+ /** @brief Gets the current viewport width in pixels */
u32 getWidth() const { return config_.width; }
+
+ /** @brief Gets the current viewport height in pixels */
u32 getHeight() const { return config_.height; }
+
+ /**
+ * @brief Gets the time elapsed since last frame
+ * @return Delta time in seconds
+ */
f32 getDeltaTime() const { return static_cast<f32>(deltaTime_); }
- // Singleton access
+ /**
+ * @brief Gets the singleton Application instance
+ * @return Reference to the current Application
+ * @note Asserts if called before Application construction
+ */
static Application& get() { return *instance_; }
protected:
- // Lifecycle hooks - override these in derived class
+ // =========================================================================
+ // Lifecycle Hooks (Override in Derived Class)
+ // =========================================================================
+
+ /**
+ * @brief Called once after engine initialization
+ * @details Override to load assets, create initial entities, etc.
+ */
virtual void onInit() {}
+
+ /**
+ * @brief Called every frame for game logic
+ * @param deltaTime Time since last frame in seconds
+ * @details Override to update game state, physics, AI, etc.
+ */
virtual void onUpdate(f32 deltaTime) { (void)deltaTime; }
+
+ /**
+ * @brief Called every frame for rendering
+ * @details Override to submit draw calls. Called after onUpdate().
+ */
virtual void onRender() {}
+
+ /**
+ * @brief Called before application shutdown
+ * @details Override to save state or cleanup resources.
+ */
virtual void onShutdown() {}
- // Event callbacks
+ // =========================================================================
+ // Event Callbacks (Override in Derived Class)
+ // =========================================================================
+
+ /**
+ * @brief Called on touch/mouse input
+ * @param type The type of touch event (down, up, move)
+ * @param point Touch position and identifier
+ */
virtual void onTouch(TouchType type, const TouchPoint& point) {
(void)type; (void)point;
}
+
+ /**
+ * @brief Called on keyboard input
+ * @param key The key code
+ * @param pressed True if pressed, false if released
+ */
virtual void onKey(KeyCode key, bool pressed) {
(void)key; (void)pressed;
}
+
+ /**
+ * @brief Called when viewport is resized
+ * @param width New width in pixels
+ * @param height New height in pixels
+ */
virtual void onResize(u32 width, u32 height) {
(void)width; (void)height;
}
+ // =========================================================================
+ // Protected Members
+ // =========================================================================
+
+ /** @brief Application configuration */
ApplicationConfig config_;
+ /** @brief Platform abstraction layer */
Unique<Platform> platform_;
+ /** @brief ECS entity/component registry */
ecs::Registry registry_;
+ /** @brief System execution group */
ecs::SystemGroup systems_;
private:
diff --git a/src/esengine/core/Engine.hpp b/src/esengine/core/Engine.hpp
index c0e82d19a..330dfd97e 100644
--- a/src/esengine/core/Engine.hpp
+++ b/src/esengine/core/Engine.hpp
@@ -1,16 +1,51 @@
+/**
+ * @file Engine.hpp
+ * @brief Engine information and capabilities
+ * @details Provides engine version information, platform detection,
+ * and feature capability queries.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "Types.hpp"
+
+// Standard library
#include <string>
namespace esengine {
-// Engine version info
+// =============================================================================
+// Engine Version
+// =============================================================================
+
+/**
+ * @brief Engine version information
+ *
+ * @details Provides compile-time version constants and a utility
+ * function for retrieving the version string.
+ */
struct EngineVersion {
+ /** @brief Major version number (breaking changes) */
static constexpr u32 MAJOR = 0;
+ /** @brief Minor version number (new features) */
static constexpr u32 MINOR = 1;
+ /** @brief Patch version number (bug fixes) */
static constexpr u32 PATCH = 0;
+ /**
+ * @brief Gets the version as a string
+ * @return Version in "MAJOR.MINOR.PATCH" format
+ */
static std::string toString() {
return std::to_string(MAJOR) + "." +
std::to_string(MINOR) + "." +
@@ -18,28 +53,95 @@ struct EngineVersion {
}
};
-// Engine singleton - manages global engine state
+// =============================================================================
+// Engine Class
+// =============================================================================
+
+/**
+ * @brief Global engine information and capability queries
+ *
+ * @details Provides static methods for querying engine metadata,
+ * platform information, and graphics capabilities.
+ *
+ * @code
+ * std::cout << Engine::getName() << " v" << Engine::getVersion() << std::endl;
+ *
+ * if (Engine::isWebPlatform()) {
+ * // Web-specific code
+ * }
+ *
+ * if (Engine::hasWebGL2()) {
+ * // Use WebGL 2 features
+ * }
+ * @endcode
+ */
class Engine {
public:
- // Get engine instance
+ // =========================================================================
+ // Instance Access
+ // =========================================================================
+
+ /**
+ * @brief Gets the engine singleton instance
+ * @return Reference to the engine instance
+ */
static Engine& get();
- // Engine info
+ // =========================================================================
+ // Engine Information
+ // =========================================================================
+
+ /**
+ * @brief Gets the engine name
+ * @return "ESEngine"
+ */
static const char* getName() { return "ESEngine"; }
+
+ /**
+ * @brief Gets the engine version string
+ * @return Version in "MAJOR.MINOR.PATCH" format
+ */
static std::string getVersion() { return EngineVersion::toString(); }
- // Platform info
+ // =========================================================================
+ // Platform Information
+ // =========================================================================
+
+ /**
+ * @brief Gets the current platform name
+ * @return Platform identifier (e.g., "Web", "Windows", "Linux")
+ */
static const char* getPlatformName();
+
+ /**
+ * @brief Checks if running on a web platform
+ * @return True if ES_PLATFORM_WEB is defined
+ */
static bool isWebPlatform();
- // Feature queries
+ // =========================================================================
+ // Capability Queries
+ // =========================================================================
+
+ /**
+ * @brief Checks if WebGL 2.0 is available
+ * @return True if WebGL 2.0 context is active
+ *
+ * @note Only meaningful on web platforms.
+ */
static bool hasWebGL2();
+
+ /**
+ * @brief Gets the maximum supported texture size
+ * @return Maximum width/height in pixels
+ */
static u32 getMaxTextureSize();
private:
Engine() = default;
~Engine() = default;
+ // Non-copyable
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
};
diff --git a/src/esengine/core/Log.hpp b/src/esengine/core/Log.hpp
index 764b6d822..2809f8fe2 100644
--- a/src/esengine/core/Log.hpp
+++ b/src/esengine/core/Log.hpp
@@ -1,54 +1,157 @@
+/**
+ * @file Log.hpp
+ * @brief Logging utilities for ESEngine
+ * @details Provides a lightweight logging system with multiple severity levels,
+ * format string support, and convenience macros.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "Types.hpp"
+
+// Standard library
#include <iostream>
#include <sstream>
#include <string>
namespace esengine {
+// =============================================================================
+// Log Level
+// =============================================================================
+
+/**
+ * @brief Logging severity levels
+ *
+ * @details Messages with a level below the current threshold are filtered out.
+ * Levels are ordered from most verbose (Trace) to most severe (Fatal).
+ */
enum class LogLevel : u8 {
- Trace = 0,
- Debug = 1,
- Info = 2,
- Warn = 3,
- Error = 4,
- Fatal = 5
+ Trace = 0, ///< Detailed debugging information
+ Debug = 1, ///< Debug information
+ Info = 2, ///< General information
+ Warn = 3, ///< Warning messages
+ Error = 4, ///< Error messages
+ Fatal = 5 ///< Fatal errors (application cannot continue)
};
+// =============================================================================
+// Log Class
+// =============================================================================
+
+/**
+ * @brief Static logging interface
+ *
+ * @details Provides formatted logging with severity levels. Uses a simple
+ * `{}` placeholder syntax for formatting arguments.
+ *
+ * @code
+ * Log::info("Player {} scored {} points", playerName, score);
+ * Log::error("Failed to load: {}", filename);
+ * @endcode
+ *
+ * @note For convenience, use the ES_LOG_* macros which provide the same
+ * functionality with automatic debug stripping.
+ */
class Log {
public:
+ /**
+ * @brief Initializes the logging system
+ */
static void init();
+
+ /**
+ * @brief Shuts down the logging system
+ */
static void shutdown();
+ /**
+ * @brief Sets the minimum log level
+ * @param level Messages below this level are filtered
+ */
static void setLevel(LogLevel level);
+
+ /**
+ * @brief Gets the current minimum log level
+ * @return The current log level threshold
+ */
static LogLevel getLevel();
+ // =========================================================================
+ // Logging Methods
+ // =========================================================================
+
+ /**
+ * @brief Logs a trace message
+ * @tparam Args Format argument types
+ * @param fmt Format string with {} placeholders
+ * @param args Format arguments
+ */
template<typename... Args>
static void trace(const char* fmt, Args&&... args) {
log(LogLevel::Trace, fmt, std::forward<Args>(args)...);
}
+ /**
+ * @brief Logs a debug message
+ * @tparam Args Format argument types
+ * @param fmt Format string with {} placeholders
+ * @param args Format arguments
+ */
template<typename... Args>
static void debug(const char* fmt, Args&&... args) {
log(LogLevel::Debug, fmt, std::forward<Args>(args)...);
}
+ /**
+ * @brief Logs an info message
+ * @tparam Args Format argument types
+ * @param fmt Format string with {} placeholders
+ * @param args Format arguments
+ */
template<typename... Args>
static void info(const char* fmt, Args&&... args) {
log(LogLevel::Info, fmt, std::forward<Args>(args)...);
}
+ /**
+ * @brief Logs a warning message
+ * @tparam Args Format argument types
+ * @param fmt Format string with {} placeholders
+ * @param args Format arguments
+ */
template<typename... Args>
static void warn(const char* fmt, Args&&... args) {
log(LogLevel::Warn, fmt, std::forward<Args>(args)...);
}
+ /**
+ * @brief Logs an error message
+ * @tparam Args Format argument types
+ * @param fmt Format string with {} placeholders
+ * @param args Format arguments
+ */
template<typename... Args>
static void error(const char* fmt, Args&&... args) {
log(LogLevel::Error, fmt, std::forward<Args>(args)...);
}
+ /**
+ * @brief Logs a fatal error message
+ * @tparam Args Format argument types
+ * @param fmt Format string with {} placeholders
+ * @param args Format arguments
+ */
template<typename... Args>
static void fatal(const char* fmt, Args&&... args) {
log(LogLevel::Fatal, fmt, std::forward<Args>(args)...);
@@ -75,7 +178,7 @@ private:
static const char* levelToString(LogLevel level);
- // Simple format implementation
+ // Simple format implementation with {} placeholders
static void formatTo(std::ostringstream& oss, const char* fmt) {
oss << fmt;
}
@@ -93,21 +196,59 @@ private:
}
};
-// Convenience macros
+// =============================================================================
+// Logging Macros
+// =============================================================================
+
+/**
+ * @name Debug Logging Macros
+ * @brief Macros that are stripped in release builds
+ * @{
+ */
#ifdef ES_DEBUG
+ /** @brief Logs a trace message (debug builds only) */
#define ES_LOG_TRACE(...) ::esengine::Log::trace(__VA_ARGS__)
+ /** @brief Logs a debug message (debug builds only) */
#define ES_LOG_DEBUG(...) ::esengine::Log::debug(__VA_ARGS__)
#else
#define ES_LOG_TRACE(...) ((void)0)
#define ES_LOG_DEBUG(...) ((void)0)
#endif
+/** @} */
+/**
+ * @name Release Logging Macros
+ * @brief Macros that are always active
+ * @{
+ */
+/** @brief Logs an info message */
#define ES_LOG_INFO(...) ::esengine::Log::info(__VA_ARGS__)
+/** @brief Logs a warning message */
#define ES_LOG_WARN(...) ::esengine::Log::warn(__VA_ARGS__)
+/** @brief Logs an error message */
#define ES_LOG_ERROR(...) ::esengine::Log::error(__VA_ARGS__)
+/** @brief Logs a fatal error message */
#define ES_LOG_FATAL(...) ::esengine::Log::fatal(__VA_ARGS__)
+/** @} */
+
+// =============================================================================
+// Assert Macro
+// =============================================================================
-// Assert macro
+/**
+ * @brief Assert macro (debug builds only)
+ *
+ * @details Checks a condition and aborts with a message if it fails.
+ * Stripped in release builds for performance.
+ *
+ * @param condition Boolean expression to test
+ * @param message Error message if assertion fails
+ *
+ * @code
+ * ES_ASSERT(ptr != nullptr, "Pointer must not be null");
+ * ES_ASSERT(index < size, "Index out of bounds");
+ * @endcode
+ */
#ifdef ES_DEBUG
#define ES_ASSERT(condition, message) \
do { \
diff --git a/src/esengine/core/Types.hpp b/src/esengine/core/Types.hpp
index d7b11e6ec..3dfca49b0 100644
--- a/src/esengine/core/Types.hpp
+++ b/src/esengine/core/Types.hpp
@@ -1,5 +1,23 @@
+/**
+ * @file Types.hpp
+ * @brief Core type definitions and utilities for ESEngine
+ * @details Provides standardized type aliases, smart pointer helpers,
+ * entity types, type ID generation, and a Result type for
+ * error handling.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Standard library
#include <cstdint>
#include <limits>
#include <memory>
@@ -8,78 +26,200 @@
namespace esengine {
-// Integer types
+// =============================================================================
+// Integer Types
+// =============================================================================
+
+/** @brief Unsigned 8-bit integer */
using u8 = std::uint8_t;
+/** @brief Unsigned 16-bit integer */
using u16 = std::uint16_t;
+/** @brief Unsigned 32-bit integer */
using u32 = std::uint32_t;
+/** @brief Unsigned 64-bit integer */
using u64 = std::uint64_t;
+/** @brief Signed 8-bit integer */
using i8 = std::int8_t;
+/** @brief Signed 16-bit integer */
using i16 = std::int16_t;
+/** @brief Signed 32-bit integer */
using i32 = std::int32_t;
+/** @brief Signed 64-bit integer */
using i64 = std::int64_t;
+/** @brief 32-bit floating point */
using f32 = float;
+/** @brief 64-bit floating point */
using f64 = double;
-// Size type
+/** @brief Size type for indexing and sizes */
using usize = std::size_t;
-// Smart pointer aliases
+// =============================================================================
+// Smart Pointer Aliases
+// =============================================================================
+
+/**
+ * @brief Unique ownership smart pointer
+ * @tparam T The managed object type
+ */
template<typename T>
using Unique = std::unique_ptr<T>;
+/**
+ * @brief Shared ownership smart pointer
+ * @tparam T The managed object type
+ */
template<typename T>
using Shared = std::shared_ptr<T>;
+/**
+ * @brief Weak reference smart pointer
+ * @tparam T The managed object type
+ */
template<typename T>
using Weak = std::weak_ptr<T>;
-// Helper functions for creating smart pointers
+/**
+ * @brief Creates a Unique pointer with the given arguments
+ * @tparam T The type to construct
+ * @tparam Args Constructor argument types
+ * @param args Arguments forwarded to T's constructor
+ * @return A Unique<T> owning the new object
+ */
template<typename T, typename... Args>
constexpr Unique<T> makeUnique(Args&&... args) {
return std::make_unique<T>(std::forward<Args>(args)...);
}
+/**
+ * @brief Creates a Shared pointer with the given arguments
+ * @tparam T The type to construct
+ * @tparam Args Constructor argument types
+ * @param args Arguments forwarded to T's constructor
+ * @return A Shared<T> owning the new object
+ */
template<typename T, typename... Args>
constexpr Shared<T> makeShared(Args&&... args) {
return std::make_shared<T>(std::forward<Args>(args)...);
}
-// Entity type (ECS core)
+// =============================================================================
+// Entity Types (ECS Core)
+// =============================================================================
+
+/**
+ * @brief Entity identifier type
+ * @details Entities are simple integer IDs used as keys in the ECS system.
+ * Components are associated with entities via the Registry.
+ */
using Entity = u32;
+
+/**
+ * @brief Invalid entity sentinel value
+ * @details Used to represent null/invalid entity references
+ */
constexpr Entity INVALID_ENTITY = std::numeric_limits<Entity>::max();
-// Type ID generation
+// =============================================================================
+// Type ID System
+// =============================================================================
+
+/**
+ * @brief Runtime type identifier
+ * @details Used internally by the ECS to identify component types
+ */
using TypeId = u32;
namespace detail {
+ /**
+ * @brief Generates sequential type IDs
+ * @return The next available TypeId
+ * @note Internal use only
+ */
inline TypeId nextTypeId() {
static TypeId counter = 0;
return counter++;
}
} // namespace detail
+/**
+ * @brief Gets the unique runtime TypeId for a type
+ * @tparam T The type to get an ID for
+ * @return The TypeId associated with type T
+ *
+ * @details Each unique type T receives a unique ID on first call.
+ * Subsequent calls return the same ID.
+ *
+ * @code
+ * TypeId posId = getTypeId<Position>();
+ * TypeId velId = getTypeId<Velocity>();
+ * assert(posId != velId);
+ * @endcode
+ */
template<typename T>
inline TypeId getTypeId() {
static const TypeId id = detail::nextTypeId();
return id;
}
-// Result type for operations that can fail
+// =============================================================================
+// Result Type
+// =============================================================================
+
+/**
+ * @brief Result type for operations that can fail
+ *
+ * @tparam T The success value type
+ * @tparam E The error type (defaults to std::string)
+ *
+ * @details Provides a type-safe way to return either a success value
+ * or an error without using exceptions.
+ *
+ * @code
+ * Result<int> divide(int a, int b) {
+ * if (b == 0) return Result<int>::err("Division by zero");
+ * return Result<int>::ok(a / b);
+ * }
+ *
+ * auto result = divide(10, 2);
+ * if (result.isOk()) {
+ * std::cout << result.value() << std::endl;
+ * }
+ * @endcode
+ */
template<typename T, typename E = std::string>
class Result {
public:
+ /**
+ * @brief Creates a successful result
+ * @param value The success value
+ * @return Result containing the value
+ */
static Result ok(T value) { return Result(std::move(value), {}, true); }
+
+ /**
+ * @brief Creates an error result
+ * @param error The error value
+ * @return Result containing the error
+ */
static Result err(E error) { return Result({}, std::move(error), false); }
+ /** @brief Returns true if the result is successful */
bool isOk() const { return success_; }
+
+ /** @brief Returns true if the result is an error */
bool isErr() const { return !success_; }
+ /** @brief Gets the success value (undefined if isErr()) */
T& value() { return value_; }
+ /** @brief Gets the success value (undefined if isErr()) */
const T& value() const { return value_; }
+ /** @brief Gets the error value (undefined if isOk()) */
E& error() { return error_; }
+ /** @brief Gets the error value (undefined if isOk()) */
const E& error() const { return error_; }
private:
diff --git a/src/esengine/ecs/Component.hpp b/src/esengine/ecs/Component.hpp
index 6ff52509b..a3c9e02eb 100644
--- a/src/esengine/ecs/Component.hpp
+++ b/src/esengine/ecs/Component.hpp
@@ -1,25 +1,79 @@
+/**
+ * @file Component.hpp
+ * @brief Built-in ECS components for ESEngine
+ * @details Provides common components used in game development including
+ * Transform, Velocity, Sprite, and tag components. Components
+ * are plain data structures that contain no logic.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
#include "../math/Math.hpp"
namespace esengine::ecs {
-// Components are plain data structures
-// They should not contain logic, only data
+// =============================================================================
+// Transform Component
+// =============================================================================
-// Transform component - position, rotation, scale
+/**
+ * @brief 3D transform component for position, rotation, and scale
+ *
+ * @details Stores spatial transformation data for an entity.
+ * Rotation is stored as Euler angles in radians (XYZ order).
+ *
+ * @code
+ * Entity e = registry.create();
+ * registry.emplace<Transform>(e, glm::vec3(10.0f, 0.0f, 0.0f));
+ *
+ * auto& transform = registry.get<Transform>(e);
+ * transform.rotation.y = glm::radians(45.0f);
+ * glm::mat4 model = transform.getMatrix();
+ * @endcode
+ */
struct Transform {
+ /** @brief World position */
glm::vec3 position{0.0f, 0.0f, 0.0f};
- glm::vec3 rotation{0.0f, 0.0f, 0.0f}; // Euler angles in radians
+ /** @brief Rotation as Euler angles in radians (pitch, yaw, roll) */
+ glm::vec3 rotation{0.0f, 0.0f, 0.0f};
+ /** @brief Scale factors */
glm::vec3 scale{1.0f, 1.0f, 1.0f};
+ /** @brief Default constructor (identity transform) */
Transform() = default;
+
+ /**
+ * @brief Constructs transform with position only
+ * @param pos Initial position
+ */
Transform(const glm::vec3& pos) : position(pos) {}
+
+ /**
+ * @brief Constructs transform with full parameters
+ * @param pos Initial position
+ * @param rot Initial rotation (Euler angles in radians)
+ * @param scl Initial scale
+ */
Transform(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl)
: position(pos), rotation(rot), scale(scl) {}
- // Get model matrix
+ /**
+ * @brief Computes the 4x4 model matrix
+ * @return Combined translation * rotation * scale matrix
+ *
+ * @details Rotation order is X (pitch), Y (yaw), Z (roll).
+ */
glm::mat4 getMatrix() const {
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, position);
@@ -31,41 +85,145 @@ struct Transform {
}
};
-// Velocity component for physics
+// =============================================================================
+// Velocity Component
+// =============================================================================
+
+/**
+ * @brief Velocity component for physics simulation
+ *
+ * @details Stores linear and angular velocity for movement and rotation.
+ * Used by physics systems to update Transform components.
+ */
struct Velocity {
+ /** @brief Linear velocity (units per second) */
glm::vec3 linear{0.0f};
+ /** @brief Angular velocity (radians per second) */
glm::vec3 angular{0.0f};
+ /** @brief Default constructor (zero velocity) */
Velocity() = default;
+
+ /**
+ * @brief Constructs with linear velocity only
+ * @param lin Linear velocity vector
+ */
Velocity(const glm::vec3& lin) : linear(lin) {}
+
+ /**
+ * @brief Constructs with both linear and angular velocity
+ * @param lin Linear velocity vector
+ * @param ang Angular velocity vector
+ */
Velocity(const glm::vec3& lin, const glm::vec3& ang) : linear(lin), angular(ang) {}
};
-// Sprite component for 2D rendering
+// =============================================================================
+// Sprite Component
+// =============================================================================
+
+/**
+ * @brief 2D sprite component for rendering
+ *
+ * @details Contains all data needed to render a 2D sprite including
+ * texture reference, color tint, size, UV coordinates, and
+ * sorting layer.
+ *
+ * @code
+ * Entity e = registry.create();
+ * auto& sprite = registry.emplace<Sprite>(e, textureId);
+ * sprite.color = glm::vec4(1.0f, 0.5f, 0.5f, 1.0f); // Red tint
+ * sprite.layer = 10; // Render on top
+ * @endcode
+ */
struct Sprite {
+ /** @brief GPU texture handle (0 for no texture) */
u32 textureId{0};
+ /** @brief Color tint (RGBA, 0-1 range) */
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
+ /** @brief Sprite size in world units */
glm::vec2 size{1.0f, 1.0f};
+ /** @brief UV coordinate offset for sprite sheets */
glm::vec2 uvOffset{0.0f, 0.0f};
+ /** @brief UV coordinate scale for sprite sheets */
glm::vec2 uvScale{1.0f, 1.0f};
+ /** @brief Sorting layer (higher = rendered on top) */
i32 layer{0};
+ /** @brief Default constructor (white, no texture) */
Sprite() = default;
+
+ /**
+ * @brief Constructs sprite with texture
+ * @param texId GPU texture handle
+ */
Sprite(u32 texId) : textureId(texId) {}
+
+ /**
+ * @brief Constructs sprite with texture and color tint
+ * @param texId GPU texture handle
+ * @param col Color tint
+ */
Sprite(u32 texId, const glm::vec4& col) : textureId(texId), color(col) {}
};
-// Tag components (empty, just for marking entities)
+// =============================================================================
+// Tag Components
+// =============================================================================
+
+/**
+ * @brief Tag component marking an entity as active
+ * @details Empty component used for filtering. Entities without this
+ * tag may be skipped by certain systems.
+ */
struct Active {};
+
+/**
+ * @brief Tag component marking an entity as visible
+ * @details Empty component used for filtering. Rendering systems
+ * typically only process entities with this tag.
+ */
struct Visible {};
+
+/**
+ * @brief Tag component marking an entity as static (non-moving)
+ * @details Empty component used for filtering. Physics and transform
+ * systems may skip entities with this tag for optimization.
+ */
struct Static {};
-// Name component for debugging
+// =============================================================================
+// Name Component
+// =============================================================================
+
+/**
+ * @brief Name component for debugging and identification
+ *
+ * @details Attaches a human-readable name to an entity for debugging,
+ * editor display, or lookup purposes.
+ *
+ * @code
+ * Entity player = registry.create();
+ * registry.emplace<Name>(player, "Player");
+ * @endcode
+ */
struct Name {
+ /** @brief The entity's name */
std::string value;
+ /** @brief Default constructor (empty name) */
Name() = default;
+
+ /**
+ * @brief Constructs with name (copy)
+ * @param name The name string
+ */
Name(const std::string& name) : value(name) {}
+
+ /**
+ * @brief Constructs with name (move)
+ * @param name The name string (moved)
+ */
Name(std::string&& name) : value(std::move(name)) {}
};
diff --git a/src/esengine/ecs/Entity.hpp b/src/esengine/ecs/Entity.hpp
index 352d558d8..619943be9 100644
--- a/src/esengine/ecs/Entity.hpp
+++ b/src/esengine/ecs/Entity.hpp
@@ -1,34 +1,106 @@
+/**
+ * @file Entity.hpp
+ * @brief Entity types and utilities for the ECS system
+ * @details Provides entity versioning, handle encoding/decoding,
+ * and entity traits. The core Entity type is defined in Types.hpp.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
namespace esengine::ecs {
-// Entity is just an ID - defined in Types.hpp
-// This file provides entity-related utilities
+// =============================================================================
+// Entity Versioning
+// =============================================================================
-// Entity version for entity recycling
+/**
+ * @brief Entity with version information for safe recycling
+ *
+ * @details When entities are destroyed and recycled, the version
+ * is incremented. This allows detecting stale entity references.
+ */
struct EntityVersion {
+ /** @brief The entity ID */
Entity id;
+ /** @brief Version number (incremented on recycle) */
u32 version;
};
-// Combine entity ID and version into a single value
+// =============================================================================
+// Entity Handle Functions
+// =============================================================================
+
+/**
+ * @brief Combines entity ID and version into a single 64-bit handle
+ * @param id The entity ID (lower 32 bits)
+ * @param version The version number (upper 32 bits)
+ * @return A packed 64-bit handle
+ *
+ * @see getEntityId(), getEntityVersion()
+ */
inline constexpr u64 makeEntityHandle(Entity id, u32 version) {
return (static_cast<u64>(version) << 32) | static_cast<u64>(id);
}
+/**
+ * @brief Extracts the entity ID from a packed handle
+ * @param handle The 64-bit entity handle
+ * @return The entity ID
+ */
inline constexpr Entity getEntityId(u64 handle) {
return static_cast<Entity>(handle & 0xFFFFFFFF);
}
+/**
+ * @brief Extracts the version from a packed handle
+ * @param handle The 64-bit entity handle
+ * @return The version number
+ */
inline constexpr u32 getEntityVersion(u64 handle) {
return static_cast<u32>(handle >> 32);
}
-// Entity traits
+// =============================================================================
+// Entity Traits
+// =============================================================================
+
+/**
+ * @brief Utility traits for working with entities
+ *
+ * @details Provides static helper functions for common entity operations.
+ *
+ * @code
+ * Entity e = registry.create();
+ * if (EntityTraits::isValid(e)) {
+ * // Use entity
+ * }
+ * @endcode
+ */
struct EntityTraits {
+ /**
+ * @brief Returns the null/invalid entity value
+ * @return INVALID_ENTITY constant
+ */
static constexpr Entity null() { return INVALID_ENTITY; }
+
+ /**
+ * @brief Checks if an entity ID is valid (not null)
+ * @param entity The entity to check
+ * @return True if entity != INVALID_ENTITY
+ * @note This only checks the ID value, not registry validity
+ */
static constexpr bool isValid(Entity entity) { return entity != INVALID_ENTITY; }
};
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 22a977bf8..af18d0aed 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -1,18 +1,63 @@
+/**
+ * @file Registry.hpp
+ * @brief Central ECS registry for entity and component management
+ * @details The Registry is the core container for the ECS system. It manages
+ * entity creation/destruction, component storage, and provides
+ * query functionality through Views.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Log.hpp"
#include "../core/Types.hpp"
#include "Entity.hpp"
#include "SparseSet.hpp"
#include "View.hpp"
+
+// Standard library
#include <any>
#include <functional>
-#include <unordered_map>
#include <queue>
+#include <unordered_map>
namespace esengine::ecs {
-// Registry - The main container for all entities and components
+// =============================================================================
+// Registry Class
+// =============================================================================
+
+/**
+ * @brief Central container for all entities and components
+ *
+ * @details The Registry provides:
+ * - Entity lifecycle management (create, destroy, recycle)
+ * - Component storage with O(1) access via SparseSet pools
+ * - View-based queries for iterating entities with specific components
+ *
+ * @code
+ * Registry registry;
+ *
+ * // Create entities and add components
+ * Entity player = registry.create();
+ * registry.emplace<Position>(player, 0.0f, 0.0f);
+ * registry.emplace<Velocity>(player, 1.0f, 0.0f);
+ *
+ * // Query and iterate
+ * for (auto [entity, pos, vel] : registry.view<Position, Velocity>().each()) {
+ * pos.x += vel.x * deltaTime;
+ * }
+ * @endcode
+ */
class Registry {
public:
Registry() = default;
@@ -24,11 +69,18 @@ public:
Registry(Registry&&) noexcept = default;
Registry& operator=(Registry&&) noexcept = default;
- // ========================================
+ // =========================================================================
// Entity Management
- // ========================================
-
- // Create a new entity
+ // =========================================================================
+
+ /**
+ * @brief Creates a new entity
+ * @return A valid entity ID
+ *
+ * @details Recycles previously destroyed entities when available.
+ * New entities are allocated sequentially when no recycled
+ * entities exist.
+ */
Entity create() {
Entity entity;
if (!recycled_.empty()) {
@@ -47,7 +99,11 @@ public:
return entity;
}
- // Create multiple entities
+ /**
+ * @brief Creates multiple entities at once
+ * @param count Number of entities to create
+ * @return Vector containing all created entity IDs
+ */
std::vector<Entity> create(usize count) {
std::vector<Entity> entities;
entities.reserve(count);
@@ -57,7 +113,13 @@ public:
return entities;
}
- // Destroy an entity
+ /**
+ * @brief Destroys an entity and removes all its components
+ * @param entity The entity to destroy
+ *
+ * @details The entity ID is recycled for future use.
+ * All components attached to the entity are removed.
+ */
void destroy(Entity entity) {
if (!valid(entity)) return;
@@ -72,12 +134,19 @@ public:
ES_LOG_TRACE("Destroyed entity {}", entity);
}
- // Check if entity is valid
+ /**
+ * @brief Checks if an entity is currently valid
+ * @param entity The entity to check
+ * @return True if the entity exists and is not destroyed
+ */
bool valid(Entity entity) const {
return entity < entityValid_.size() && entityValid_[entity];
}
- // Get number of active entities
+ /**
+ * @brief Gets the number of active (non-destroyed) entities
+ * @return Count of valid entities
+ */
usize entityCount() const {
usize count = 0;
for (bool valid : entityValid_) {
@@ -86,11 +155,20 @@ public:
return count;
}
- // ========================================
+ // =========================================================================
// Component Management
- // ========================================
-
- // Add component to entity (in-place construction)
+ // =========================================================================
+
+ /**
+ * @brief Adds a component to an entity with in-place construction
+ * @tparam T The component type
+ * @tparam Args Constructor argument types
+ * @param entity The target entity
+ * @param args Arguments forwarded to T's constructor
+ * @return Reference to the newly created component
+ *
+ * @note Asserts if entity is invalid or already has the component
+ */
template<typename T, typename... Args>
T& emplace(Entity entity, Args&&... args) {
ES_ASSERT(valid(entity), "Invalid entity");
@@ -98,7 +176,16 @@ public:
return pool.emplace(entity, std::forward<Args>(args)...);
}
- // Add or replace component
+ /**
+ * @brief Adds or replaces a component on an entity
+ * @tparam T The component type
+ * @tparam Args Constructor argument types
+ * @param entity The target entity
+ * @param args Arguments forwarded to T's constructor
+ * @return Reference to the component
+ *
+ * @details If the entity already has the component, it is replaced.
+ */
template<typename T, typename... Args>
T& emplaceOrReplace(Entity entity, Args&&... args) {
ES_ASSERT(valid(entity), "Invalid entity");
@@ -111,7 +198,13 @@ public:
return pool.emplace(entity, std::forward<Args>(args)...);
}
- // Remove component from entity
+ /**
+ * @brief Removes a component from an entity
+ * @tparam T The component type to remove
+ * @param entity The target entity
+ *
+ * @details No-op if the entity doesn't have the component.
+ */
template<typename T>
void remove(Entity entity) {
auto* pool = getPool<T>();
@@ -120,7 +213,14 @@ public:
}
}
- // Get component (must exist)
+ /**
+ * @brief Gets a component from an entity (must exist)
+ * @tparam T The component type
+ * @param entity The target entity
+ * @return Reference to the component
+ *
+ * @note Asserts if the entity doesn't have the component
+ */
template<typename T>
T& get(Entity entity) {
auto* pool = getPool<T>();
@@ -128,6 +228,7 @@ public:
return pool->get(entity);
}
+ /** @copydoc get() */
template<typename T>
const T& get(Entity entity) const {
auto* pool = getPool<T>();
@@ -135,20 +236,33 @@ public:
return pool->get(entity);
}
- // Try to get component (may return nullptr)
+ /**
+ * @brief Tries to get a component from an entity
+ * @tparam T The component type
+ * @param entity The target entity
+ * @return Pointer to the component, or nullptr if not found
+ */
template<typename T>
T* tryGet(Entity entity) {
auto* pool = getPool<T>();
return pool ? pool->tryGet(entity) : nullptr;
}
+ /** @copydoc tryGet() */
template<typename T>
const T* tryGet(Entity entity) const {
auto* pool = getPool<T>();
return pool ? pool->tryGet(entity) : nullptr;
}
- // Get or add component
+ /**
+ * @brief Gets an existing component or creates a new one
+ * @tparam T The component type
+ * @tparam Args Constructor argument types (for new component)
+ * @param entity The target entity
+ * @param args Arguments forwarded to T's constructor if creating
+ * @return Reference to the component
+ */
template<typename T, typename... Args>
T& getOrEmplace(Entity entity, Args&&... args) {
auto& pool = assurePool<T>();
@@ -158,30 +272,61 @@ public:
return pool.emplace(entity, std::forward<Args>(args)...);
}
- // Check if entity has component
+ /**
+ * @brief Checks if an entity has a specific component
+ * @tparam T The component type to check
+ * @param entity The entity to check
+ * @return True if the entity has the component
+ */
template<typename T>
bool has(Entity entity) const {
auto* pool = getPool<T>();
return pool && pool->contains(entity);
}
- // Check if entity has all specified components
+ /**
+ * @brief Checks if an entity has all specified components
+ * @tparam Ts The component types to check
+ * @param entity The entity to check
+ * @return True if the entity has all components
+ */
template<typename... Ts>
bool hasAll(Entity entity) const {
return (has<Ts>(entity) && ...);
}
- // Check if entity has any of specified components
+ /**
+ * @brief Checks if an entity has any of the specified components
+ * @tparam Ts The component types to check
+ * @param entity The entity to check
+ * @return True if the entity has at least one component
+ */
template<typename... Ts>
bool hasAny(Entity entity) const {
return (has<Ts>(entity) || ...);
}
- // ========================================
+ // =========================================================================
// View (Query) System
- // ========================================
-
- // Get view for iterating entities with specific components
+ // =========================================================================
+
+ /**
+ * @brief Creates a view for iterating entities with specific components
+ * @tparam Components The component types to query
+ * @return A View for iterating matching entities
+ *
+ * @code
+ * // Single component view
+ * for (auto entity : registry.view<Position>()) {
+ * auto& pos = registry.get<Position>(entity);
+ * }
+ *
+ * // Multi-component view with structured bindings
+ * for (auto [entity, pos, vel] : registry.view<Position, Velocity>().each()) {
+ * pos.x += vel.x * dt;
+ * }
+ * @endcode
+ */
template<typename... Components>
View<Components...> view() {
if constexpr (sizeof...(Components) == 1) {
@@ -192,11 +337,14 @@ public:
}
}
- // ========================================
+ // =========================================================================
// Utility
- // ========================================
+ // =========================================================================
- // Clear all entities and components
+ /**
+ * @brief Clears all entities and components
+ * @details Resets the registry to its initial empty state.
+ */
void clear() {
for (auto& [typeId, pool] : pools_) {
pool->clear();
@@ -206,20 +354,38 @@ public:
nextEntity_ = 0;
}
- // Execute function for each entity with components
+ /**
+ * @brief Executes a function for each entity with specified components
+ * @tparam Components The required component types
+ * @tparam Func The callback type
+ * @param func Callback receiving (Entity, Component&...)
+ *
+ * @code
+ * registry.each<Position, Velocity>([](Entity e, Position& p, Velocity& v) {
+ * p.x += v.x;
+ * });
+ * @endcode
+ */
template<typename... Components, typename Func>
void each(Func&& func) {
view<Components...>().each(std::forward<Func>(func));
}
- // Sort components by entity order
+ /**
+ * @brief Sorts components by a comparison function
+ * @tparam T The component type to sort
+ * @tparam Compare The comparison function type
+ * @param compare Comparison function returning true if first < second
+ *
+ * @details Sorts the component pool so iteration order matches
+ * the comparison result.
+ */
template<typename T, typename Compare>
void sort(Compare compare) {
auto* pool = getPool<T>();
if (!pool) return;
- // Simple selection sort for now
- // Could be optimized with more sophisticated algorithms
+ // Selection sort (could be optimized)
auto& entities = const_cast<std::vector<Entity>&>(pool->entities());
auto& components = pool->components();
@@ -238,7 +404,15 @@ public:
}
private:
- // Get or create component pool
+ // =========================================================================
+ // Private Helpers
+ // =========================================================================
+
+ /**
+ * @brief Gets or creates a component pool for type T
+ * @tparam T The component type
+ * @return Reference to the SparseSet for type T
+ */
template<typename T>
SparseSet<T>& assurePool() {
TypeId typeId = getTypeId<T>();
@@ -252,7 +426,11 @@ private:
return *static_cast<SparseSet<T>*>(it->second.get());
}
- // Get existing pool (may return nullptr)
+ /**
+ * @brief Gets an existing component pool (may return nullptr)
+ * @tparam T The component type
+ * @return Pointer to the SparseSet, or nullptr if not found
+ */
template<typename T>
SparseSet<T>* getPool() {
TypeId typeId = getTypeId<T>();
@@ -269,12 +447,18 @@ private:
return static_cast<const SparseSet<T>*>(it->second.get());
}
- // Entity storage
+ // =========================================================================
+ // Data Members
+ // =========================================================================
+
+ /** @brief Validity flags for each entity ID */
std::vector<bool> entityValid_;
+ /** @brief Queue of recycled entity IDs */
std::queue<Entity> recycled_;
+ /** @brief Next entity ID to allocate */
Entity nextEntity_ = 0;
- // Component pools (type-erased)
+ /** @brief Type-erased component pools indexed by TypeId */
std::unordered_map<TypeId, Unique<SparseSetBase>> pools_;
};
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index 8412aa9b0..31f9ae530 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -1,32 +1,134 @@
+/**
+ * @file SparseSet.hpp
+ * @brief Sparse set data structure for efficient ECS component storage
+ * @details Implements a sparse set providing O(1) insertion, deletion,
+ * and lookup while maintaining cache-friendly dense iteration.
+ * This is the core data structure behind the ECS component pools.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
#include "Entity.hpp"
+
+// Standard library
#include <algorithm>
#include <vector>
namespace esengine::ecs {
-// Base class for type-erased sparse set operations
+// =============================================================================
+// SparseSetBase
+// =============================================================================
+
+/**
+ * @brief Type-erased base class for sparse set operations
+ *
+ * @details Provides a common interface for type-erased operations on
+ * component pools. Used by Registry to manage pools of different
+ * component types uniformly.
+ */
class SparseSetBase {
public:
+ /** @brief Virtual destructor for proper cleanup */
virtual ~SparseSetBase() = default;
+ /**
+ * @brief Checks if an entity exists in the set
+ * @param entity The entity to check
+ * @return True if the entity has a component in this pool
+ */
virtual bool contains(Entity entity) const = 0;
+
+ /**
+ * @brief Removes an entity's component from the set
+ * @param entity The entity whose component to remove
+ */
virtual void remove(Entity entity) = 0;
+
+ /**
+ * @brief Gets the number of components in the set
+ * @return Number of stored components
+ */
virtual usize size() const = 0;
+
+ /**
+ * @brief Checks if the set is empty
+ * @return True if no components are stored
+ */
virtual bool empty() const = 0;
+
+ /**
+ * @brief Removes all components from the set
+ */
virtual void clear() = 0;
+
+ /**
+ * @brief Gets the dense entity array for iteration
+ * @return Const reference to the entity vector
+ */
virtual const std::vector<Entity>& entities() const = 0;
};
-// SparseSet: O(1) insertion, deletion, lookup with cache-friendly iteration
+// =============================================================================
+// SparseSet
+// =============================================================================
+
+/**
+ * @brief Sparse set container for efficient entity-component storage
+ *
+ * @tparam T The component type to store
+ *
+ * @details The sparse set uses two arrays:
+ * - **Sparse array**: Maps entity IDs to dense array indices
+ * - **Dense array**: Stores entities and components contiguously
+ *
+ * This provides:
+ * - O(1) insertion, deletion, and lookup
+ * - Cache-friendly iteration over components
+ * - Stable component pointers during iteration
+ *
+ * The "swap and pop" deletion strategy maintains density
+ * without gaps, at the cost of unstable ordering.
+ *
+ * @code
+ * SparseSet<Position> positions;
+ *
+ * // Add components
+ * positions.emplace(entity1, 0.0f, 0.0f);
+ * positions.emplace(entity2, 10.0f, 5.0f);
+ *
+ * // Access component
+ * if (positions.contains(entity1)) {
+ * Position& pos = positions.get(entity1);
+ * }
+ *
+ * // Iterate all
+ * for (Entity e : positions) {
+ * Position& pos = positions.get(e);
+ * }
+ * @endcode
+ */
template<typename T>
class SparseSet : public SparseSetBase {
public:
+ /** @brief Iterator type for entity iteration */
using Iterator = typename std::vector<Entity>::const_iterator;
+ /** @brief Default constructor */
SparseSet() = default;
+
+ /** @brief Destructor */
~SparseSet() override = default;
// Non-copyable, movable
@@ -35,36 +137,72 @@ public:
SparseSet(SparseSet&&) noexcept = default;
SparseSet& operator=(SparseSet&&) noexcept = default;
- // Check if entity exists in set
+ // =========================================================================
+ // Lookup Operations
+ // =========================================================================
+
+ /**
+ * @brief Checks if an entity has a component in this set
+ * @param entity The entity to check
+ * @return True if the entity has a component
+ *
+ * @details O(1) complexity. Validates the sparse-dense mapping.
+ */
bool contains(Entity entity) const override {
return entity < sparse_.size() &&
sparse_[entity] < dense_.size() &&
dense_[sparse_[entity]] == entity;
}
- // Get component for entity (must exist)
+ /**
+ * @brief Gets the component for an entity (must exist)
+ * @param entity The entity
+ * @return Reference to the component
+ *
+ * @note Asserts if the entity doesn't have a component
+ */
T& get(Entity entity) {
ES_ASSERT(contains(entity), "Entity does not have component");
return components_[sparse_[entity]];
}
+ /** @copydoc get() */
const T& get(Entity entity) const {
ES_ASSERT(contains(entity), "Entity does not have component");
return components_[sparse_[entity]];
}
- // Try to get component, returns nullptr if not found
+ /**
+ * @brief Tries to get a component (returns nullptr if not found)
+ * @param entity The entity
+ * @return Pointer to the component, or nullptr
+ */
T* tryGet(Entity entity) {
if (!contains(entity)) return nullptr;
return &components_[sparse_[entity]];
}
+ /** @copydoc tryGet() */
const T* tryGet(Entity entity) const {
if (!contains(entity)) return nullptr;
return &components_[sparse_[entity]];
}
- // Add component to entity
+ // =========================================================================
+ // Modification Operations
+ // =========================================================================
+
+ /**
+ * @brief Adds a component to an entity with in-place construction
+ * @tparam Args Constructor argument types
+ * @param entity The entity to add a component to
+ * @param args Arguments forwarded to T's constructor
+ * @return Reference to the newly created component
+ *
+ * @note Asserts if the entity already has a component
+ *
+ * @details O(1) amortized complexity. May resize the sparse array.
+ */
template<typename... Args>
T& emplace(Entity entity, Args&&... args) {
ES_ASSERT(!contains(entity), "Entity already has component");
@@ -82,7 +220,14 @@ public:
return components_.back();
}
- // Remove component from entity
+ /**
+ * @brief Removes a component from an entity
+ * @param entity The entity whose component to remove
+ *
+ * @details O(1) complexity using swap-and-pop. The last element
+ * is moved to fill the gap, maintaining density.
+ * No-op if the entity doesn't have a component.
+ */
void remove(Entity entity) override {
if (!contains(entity)) return;
@@ -101,37 +246,101 @@ public:
sparse_[entity] = INVALID_ENTITY;
}
- // Container operations
+ // =========================================================================
+ // Container Operations
+ // =========================================================================
+
+ /**
+ * @brief Gets the number of components in the set
+ * @return Component count
+ */
usize size() const override { return dense_.size(); }
+
+ /**
+ * @brief Checks if the set is empty
+ * @return True if no components are stored
+ */
bool empty() const override { return dense_.empty(); }
+ /**
+ * @brief Removes all components
+ */
void clear() override {
sparse_.clear();
dense_.clear();
components_.clear();
}
- // Iteration - iterate over entities
+ // =========================================================================
+ // Iteration
+ // =========================================================================
+
+ /**
+ * @brief Returns iterator to the first entity
+ * @return Begin iterator
+ */
Iterator begin() const { return dense_.begin(); }
+
+ /**
+ * @brief Returns iterator past the last entity
+ * @return End iterator
+ */
Iterator end() const { return dense_.end(); }
- // Access to dense entity array (for views)
+ /**
+ * @brief Gets the dense entity array
+ * @return Const reference to entity vector
+ */
const std::vector<Entity>& entities() const override { return dense_; }
- // Access to component array (for direct iteration)
+ /**
+ * @brief Gets the component array for direct iteration
+ * @return Reference to component vector
+ *
+ * @details Allows iterating components directly without
+ * looking up by entity. Components are stored in
+ * the same order as entities().
+ */
std::vector<T>& components() { return components_; }
+
+ /** @copydoc components() */
const std::vector<T>& components() const { return components_; }
- // Get index in dense array for entity
+ /**
+ * @brief Gets the dense array index for an entity
+ * @param entity The entity
+ * @return Index in the dense/component arrays
+ *
+ * @note Asserts if the entity is not in the set
+ */
usize indexOf(Entity entity) const {
ES_ASSERT(contains(entity), "Entity not in set");
return sparse_[entity];
}
private:
- std::vector<Entity> sparse_; // Entity -> Dense index
- std::vector<Entity> dense_; // Dense index -> Entity
- std::vector<T> components_; // Dense storage for components
+ // =========================================================================
+ // Data Members
+ // =========================================================================
+
+ /**
+ * @brief Sparse array: maps Entity ID -> index in dense array
+ * @details Indexed directly by entity ID. Contains INVALID_ENTITY
+ * for entities not in the set.
+ */
+ std::vector<Entity> sparse_;
+
+ /**
+ * @brief Dense array: stores entities contiguously
+ * @details Parallel to components_. Enables O(1) reverse lookup.
+ */
+ std::vector<Entity> dense_;
+
+ /**
+ * @brief Component storage: parallel to dense array
+ * @details components_[i] belongs to entity dense_[i].
+ */
+ std::vector<T> components_;
};
} // namespace esengine::ecs
diff --git a/src/esengine/ecs/System.hpp b/src/esengine/ecs/System.hpp
index 71f3f0204..f60c73291 100644
--- a/src/esengine/ecs/System.hpp
+++ b/src/esengine/ecs/System.hpp
@@ -1,5 +1,22 @@
+/**
+ * @file System.hpp
+ * @brief ECS System base class and execution group
+ * @details Provides the System base class for implementing game logic
+ * and SystemGroup for organizing and executing systems in order.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
namespace esengine::ecs {
@@ -7,41 +24,163 @@ namespace esengine::ecs {
// Forward declaration
class Registry;
-// Base class for all systems
+// =============================================================================
+// System Base Class
+// =============================================================================
+
+/**
+ * @brief Base class for all ECS systems
+ *
+ * @details Systems contain the logic that operates on entities with
+ * specific component configurations. Derive from this class
+ * and override update() to implement game logic.
+ *
+ * @code
+ * class MovementSystem : public System {
+ * public:
+ * void update(Registry& registry, f32 deltaTime) override {
+ * registry.each<Transform, Velocity>(
+ * [deltaTime](Entity e, Transform& t, Velocity& v) {
+ * t.position += v.linear * deltaTime;
+ * });
+ * }
+ * };
+ *
+ * // Usage:
+ * systemGroup.createSystem<MovementSystem>();
+ * @endcode
+ */
class System {
public:
+ /** @brief Virtual destructor for proper cleanup */
virtual ~System() = default;
- // Called once when system is added
+ /**
+ * @brief Called once when the system is added to a group
+ * @param registry Reference to the ECS registry
+ *
+ * @details Override to perform one-time initialization such as
+ * caching component pools or loading resources.
+ */
virtual void init(Registry& registry) { (void)registry; }
- // Called every frame
+ /**
+ * @brief Called every frame to execute system logic
+ * @param registry Reference to the ECS registry
+ * @param deltaTime Time since last frame in seconds
+ *
+ * @details Pure virtual - must be overridden. This is where
+ * the main system logic goes.
+ */
virtual void update(Registry& registry, f32 deltaTime) = 0;
- // Called once when system is removed
+ /**
+ * @brief Called once when the system is removed
+ * @param registry Reference to the ECS registry
+ *
+ * @details Override to cleanup resources allocated in init().
+ */
virtual void shutdown(Registry& registry) { (void)registry; }
- // Enable/disable system
+ // =========================================================================
+ // Enable/Disable
+ // =========================================================================
+
+ /**
+ * @brief Enables or disables the system
+ * @param enabled True to enable, false to disable
+ *
+ * @details Disabled systems are skipped during update().
+ */
void setEnabled(bool enabled) { enabled_ = enabled; }
+
+ /**
+ * @brief Checks if the system is enabled
+ * @return True if enabled
+ */
bool isEnabled() const { return enabled_; }
- // Priority for ordering (lower = runs first)
+ // =========================================================================
+ // Priority
+ // =========================================================================
+
+ /**
+ * @brief Sets the system's execution priority
+ * @param priority Lower values execute first
+ *
+ * @details Systems in a SystemGroup are sorted by priority.
+ * Default priority is 0.
+ */
void setPriority(i32 priority) { priority_ = priority; }
+
+ /**
+ * @brief Gets the system's execution priority
+ * @return The priority value
+ */
i32 getPriority() const { return priority_; }
protected:
+ /** @brief Whether the system is enabled */
bool enabled_ = true;
+ /** @brief Execution priority (lower = earlier) */
i32 priority_ = 0;
};
-// System group for organizing systems
+// =============================================================================
+// System Group
+// =============================================================================
+
+/**
+ * @brief Container for organizing and executing systems
+ *
+ * @details Manages a collection of systems, executing them in priority
+ * order during update. Systems with lower priority values
+ * execute first.
+ *
+ * @code
+ * SystemGroup systems;
+ *
+ * // Create systems with different priorities
+ * auto& physics = systems.createSystem<PhysicsSystem>();
+ * physics.setPriority(0); // Runs first
+ *
+ * auto& render = systems.createSystem<RenderSystem>();
+ * render.setPriority(100); // Runs last
+ *
+ * // In game loop:
+ * systems.init(registry);
+ * while (running) {
+ * systems.update(registry, deltaTime);
+ * }
+ * systems.shutdown(registry);
+ * @endcode
+ */
class SystemGroup {
public:
+ /**
+ * @brief Adds an existing system to the group
+ * @param system Unique pointer to the system (ownership transferred)
+ *
+ * @details The group takes ownership of the system. Systems are
+ * automatically sorted by priority after adding.
+ */
void addSystem(Unique<System> system) {
systems_.push_back(std::move(system));
sortSystems();
}
+ /**
+ * @brief Creates and adds a system to the group
+ * @tparam T The system type to create
+ * @tparam Args Constructor argument types
+ * @param args Arguments forwarded to T's constructor
+ * @return Reference to the created system
+ *
+ * @code
+ * auto& mySystem = group.createSystem<MySystem>(arg1, arg2);
+ * mySystem.setPriority(10);
+ * @endcode
+ */
template<typename T, typename... Args>
T& createSystem(Args&&... args) {
auto system = makeUnique<T>(std::forward<Args>(args)...);
@@ -50,12 +189,27 @@ public:
return ref;
}
+ /**
+ * @brief Initializes all systems in the group
+ * @param registry Reference to the ECS registry
+ *
+ * @details Calls init() on each system in priority order.
+ * Should be called once before the main loop.
+ */
void init(Registry& registry) {
for (auto& system : systems_) {
system->init(registry);
}
}
+ /**
+ * @brief Updates all enabled systems
+ * @param registry Reference to the ECS registry
+ * @param deltaTime Time since last frame in seconds
+ *
+ * @details Calls update() on each enabled system in priority order.
+ * Disabled systems are skipped.
+ */
void update(Registry& registry, f32 deltaTime) {
for (auto& system : systems_) {
if (system->isEnabled()) {
@@ -64,6 +218,13 @@ public:
}
}
+ /**
+ * @brief Shuts down all systems
+ * @param registry Reference to the ECS registry
+ *
+ * @details Calls shutdown() on each system in priority order.
+ * Should be called once after the main loop.
+ */
void shutdown(Registry& registry) {
for (auto& system : systems_) {
system->shutdown(registry);
@@ -71,6 +232,9 @@ public:
}
private:
+ /**
+ * @brief Sorts systems by priority (ascending)
+ */
void sortSystems() {
std::sort(systems_.begin(), systems_.end(),
[](const Unique<System>& a, const Unique<System>& b) {
@@ -78,6 +242,7 @@ private:
});
}
+ /** @brief Owned systems sorted by priority */
std::vector<Unique<System>> systems_;
};
diff --git a/src/esengine/ecs/View.hpp b/src/esengine/ecs/View.hpp
index 369db883e..bad2e3417 100644
--- a/src/esengine/ecs/View.hpp
+++ b/src/esengine/ecs/View.hpp
@@ -1,8 +1,27 @@
+/**
+ * @file View.hpp
+ * @brief ECS View for querying entities with specific components
+ * @details Provides efficient iteration over entities that have a specific
+ * set of components. Views are the primary way to query the ECS.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
#include "Entity.hpp"
#include "SparseSet.hpp"
+
+// Standard library
#include <tuple>
namespace esengine::ecs {
@@ -10,12 +29,31 @@ namespace esengine::ecs {
// Forward declaration
class Registry;
-// View iterator - iterates over entities that have all specified components
+// =============================================================================
+// ViewIterator
+// =============================================================================
+
+/**
+ * @brief Iterator for multi-component views
+ *
+ * @tparam Components The component types required
+ *
+ * @details Iterates over entities from the smallest pool while filtering
+ * for entities that have all required components. Automatically
+ * skips entities that don't match the full component set.
+ */
template<typename... Components>
class ViewIterator {
public:
+ /** @brief Tuple type holding pointers to all component pools */
using PoolsTuple = std::tuple<SparseSet<Components>*...>;
+ /**
+ * @brief Constructs an iterator
+ * @param entities Pointer to the entity array being iterated
+ * @param index Current position in the entity array
+ * @param pools Tuple of component pool pointers
+ */
ViewIterator(const std::vector<Entity>* entities, usize index, PoolsTuple pools)
: entities_(entities), index_(index), pools_(pools) {
// Skip to first valid entity
@@ -24,25 +62,49 @@ public:
}
}
+ /**
+ * @brief Dereferences to get the current entity
+ * @return The current entity ID
+ */
Entity operator*() const {
return (*entities_)[index_];
}
+ /**
+ * @brief Advances to the next matching entity
+ * @return Reference to this iterator
+ */
ViewIterator& operator++() {
++index_;
skipInvalid();
return *this;
}
+ /**
+ * @brief Inequality comparison
+ * @param other Iterator to compare with
+ * @return True if iterators are at different positions
+ */
bool operator!=(const ViewIterator& other) const {
return index_ != other.index_;
}
+ /**
+ * @brief Equality comparison
+ * @param other Iterator to compare with
+ * @return True if iterators are at the same position
+ */
bool operator==(const ViewIterator& other) const {
return index_ == other.index_;
}
private:
+ /**
+ * @brief Skips entities that don't have all required components
+ *
+ * @details Advances index_ until we find an entity that has
+ * all components in the view, or we reach the end.
+ */
void skipInvalid() {
while (index_ < entities_->size()) {
Entity entity = (*entities_)[index_];
@@ -53,10 +115,21 @@ private:
}
}
+ /**
+ * @brief Checks if an entity has all required components
+ * @param entity The entity to check
+ * @return True if entity has all components
+ */
bool allHave(Entity entity) const {
return allHaveImpl(entity, std::index_sequence_for<Components...>{});
}
+ /**
+ * @brief Implementation helper using index sequence
+ * @tparam Is Index sequence for component types
+ * @param entity The entity to check
+ * @return True if entity has all components
+ */
template<usize... Is>
bool allHaveImpl(Entity entity, std::index_sequence<Is...>) const {
return (std::get<Is>(pools_)->contains(entity) && ...);
@@ -67,56 +140,150 @@ private:
PoolsTuple pools_;
};
-// View - provides iteration over entities with specific components
+// =============================================================================
+// View (Multi-Component)
+// =============================================================================
+
+/**
+ * @brief View for iterating entities with multiple required components
+ *
+ * @tparam Components The component types that entities must have
+ *
+ * @details Provides iteration over all entities that have ALL of the
+ * specified component types. Optimizes by iterating over the
+ * smallest pool and filtering by other components.
+ *
+ * @code
+ * // Iterate entities with Position AND Velocity
+ * auto view = registry.view<Position, Velocity>();
+ *
+ * // Range-based for loop
+ * for (Entity e : view) {
+ * auto& pos = view.get<Position>(e);
+ * auto& vel = view.get<Velocity>(e);
+ * pos.x += vel.x * dt;
+ * }
+ *
+ * // Each with callback
+ * view.each([&](Entity e, Position& p, Velocity& v) {
+ * p.x += v.x * dt;
+ * });
+ * @endcode
+ */
template<typename... Components>
class View {
public:
+ /** @brief Iterator type */
using Iterator = ViewIterator<Components...>;
+ /** @brief Tuple type for pool pointers */
using PoolsTuple = std::tuple<SparseSet<Components>*...>;
+ /**
+ * @brief Constructs a view from component pools
+ * @param pools Tuple of pointers to component pools
+ */
View(PoolsTuple pools) : pools_(pools) {
// Find the smallest pool to iterate over
findSmallestPool();
}
+ /**
+ * @brief Returns iterator to the first matching entity
+ * @return Begin iterator
+ */
Iterator begin() const {
if (!smallest_) return end();
return Iterator(&smallest_->entities(), 0, pools_);
}
+ /**
+ * @brief Returns iterator past the last entity
+ * @return End iterator
+ */
Iterator end() const {
if (!smallest_) return Iterator(nullptr, 0, pools_);
return Iterator(&smallest_->entities(), smallest_->size(), pools_);
}
- // Get component from view (entity must be valid)
+ // =========================================================================
+ // Component Access
+ // =========================================================================
+
+ /**
+ * @brief Gets a specific component from an entity
+ * @tparam T The component type to get
+ * @param entity The entity (must be valid in view)
+ * @return Reference to the component
+ */
template<typename T>
T& get(Entity entity) {
return std::get<SparseSet<T>*>(pools_)->get(entity);
}
+ /** @copydoc get() */
template<typename T>
const T& get(Entity entity) const {
return std::get<SparseSet<T>*>(pools_)->get(entity);
}
- // Get multiple components at once
+ /**
+ * @brief Gets all components for an entity as a tuple
+ * @param entity The entity
+ * @return Tuple of component references
+ */
std::tuple<Components&...> getAll(Entity entity) {
return std::tuple<Components&...>(
std::get<SparseSet<Components>*>(pools_)->get(entity)...);
}
- // Check if view is empty
+ // =========================================================================
+ // View Properties
+ // =========================================================================
+
+ /**
+ * @brief Checks if the view is empty
+ * @return True if no entities match
+ */
bool empty() const {
return !smallest_ || smallest_->empty();
}
- // Estimate size (upper bound)
+ /**
+ * @brief Gets the estimated number of matching entities
+ * @return Upper bound on entity count (actual may be lower)
+ *
+ * @details Returns the size of the smallest pool. Actual matches
+ * may be fewer due to filtering by other components.
+ */
usize sizeHint() const {
return smallest_ ? smallest_->size() : 0;
}
- // Execute function for each entity
+ // =========================================================================
+ // Functional Iteration
+ // =========================================================================
+
+ /**
+ * @brief Executes a function for each matching entity
+ * @tparam Func Callback type
+ * @param func The callback to invoke
+ *
+ * @details The callback can have one of these signatures:
+ * - `void(Entity, Component&...)` - entity and all components
+ * - `void(Component&...)` - components only
+ * - `void(Entity)` - entity only
+ *
+ * @code
+ * // With entity and components
+ * view.each([](Entity e, Position& p, Velocity& v) { ... });
+ *
+ * // Components only
+ * view.each([](Position& p, Velocity& v) { ... });
+ *
+ * // Entity only
+ * view.each([](Entity e) { ... });
+ * @endcode
+ */
template<typename Func>
void each(Func&& func) {
for (auto entity : *this) {
@@ -131,6 +298,12 @@ public:
}
private:
+ /**
+ * @brief Finds the smallest component pool
+ *
+ * @details The view iterates over the smallest pool for efficiency,
+ * as it minimizes the number of entities to filter.
+ */
void findSmallestPool() {
smallest_ = nullptr;
usize minSize = std::numeric_limits<usize>::max();
@@ -148,31 +321,98 @@ private:
auto* pool = std::get<I>(pools_);
if (pool && pool->size() < minSize) {
minSize = pool->size();
- smallest_ = reinterpret_cast<SparseSetBase*>(pool);
+ smallest_ = static_cast<SparseSetBase*>(pool);
}
}
+ /** @brief Tuple of component pool pointers */
PoolsTuple pools_;
+ /** @brief Pointer to the smallest pool (for iteration) */
SparseSetBase* smallest_ = nullptr;
};
-// Single component view specialization (more efficient)
+// =============================================================================
+// View<T> Specialization (Single Component)
+// =============================================================================
+
+/**
+ * @brief Optimized view for single-component queries
+ *
+ * @tparam T The single component type
+ *
+ * @details When querying for only one component type, no filtering is
+ * needed. This specialization directly iterates the component
+ * pool for maximum efficiency.
+ *
+ * @code
+ * // Iterate all entities with Position
+ * for (Entity e : registry.view<Position>()) {
+ * auto& pos = registry.get<Position>(e);
+ * }
+ *
+ * // Direct component iteration (most efficient)
+ * registry.view<Position>().each([](Entity e, Position& p) {
+ * p.x += 1.0f;
+ * });
+ * @endcode
+ */
template<typename T>
class View<T> {
public:
+ /** @brief Iterator type (directly iterates pool) */
using Iterator = typename std::vector<Entity>::const_iterator;
+ /**
+ * @brief Constructs a single-component view
+ * @param pool Pointer to the component pool
+ */
explicit View(SparseSet<T>* pool) : pool_(pool) {}
+ /**
+ * @brief Returns iterator to the first entity
+ * @return Begin iterator
+ */
Iterator begin() const { return pool_ ? pool_->begin() : Iterator{}; }
+
+ /**
+ * @brief Returns iterator past the last entity
+ * @return End iterator
+ */
Iterator end() const { return pool_ ? pool_->end() : Iterator{}; }
+ /**
+ * @brief Gets the component for an entity
+ * @param entity The entity
+ * @return Reference to the component
+ */
T& get(Entity entity) { return pool_->get(entity); }
+
+ /** @copydoc get() */
const T& get(Entity entity) const { return pool_->get(entity); }
+ /**
+ * @brief Checks if the view is empty
+ * @return True if no entities have this component
+ */
bool empty() const { return !pool_ || pool_->empty(); }
+
+ /**
+ * @brief Gets the exact number of entities in the view
+ * @return Entity count
+ */
usize size() const { return pool_ ? pool_->size() : 0; }
+ /**
+ * @brief Executes a function for each entity
+ * @tparam Func Callback type
+ * @param func The callback to invoke
+ *
+ * @details Optimized direct iteration without any filtering.
+ * Callback signatures:
+ * - `void(Entity, T&)` - entity and component
+ * - `void(T&)` - component only
+ * - `void(Entity)` - entity only
+ */
template<typename Func>
void each(Func&& func) {
if (!pool_) return;
@@ -192,6 +432,7 @@ public:
}
private:
+ /** @brief Pointer to the component pool */
SparseSet<T>* pool_;
};
diff --git a/src/esengine/math/Math.hpp b/src/esengine/math/Math.hpp
index 2a4f9e76d..f8a29aee5 100644
--- a/src/esengine/math/Math.hpp
+++ b/src/esengine/math/Math.hpp
@@ -1,6 +1,21 @@
+/**
+ * @file Math.hpp
+ * @brief Math utilities and GLM configuration for ESEngine
+ * @details Provides GLM configuration, math constants, and utility functions
+ * for common game development operations.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
// GLM Configuration
+// =============================================================================
+
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#endif
@@ -11,7 +26,10 @@
#define GLM_ENABLE_EXPERIMENTAL
#endif
-// GLM Core
+// =============================================================================
+// GLM Includes
+// =============================================================================
+
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
@@ -21,72 +39,200 @@
namespace esengine {
-// Math constants
+// =============================================================================
+// Math Namespace
+// =============================================================================
+
+/**
+ * @brief Math constants and utility functions
+ *
+ * @details Provides common mathematical constants and helper functions
+ * for angles, interpolation, matrix operations, etc.
+ */
namespace math {
+// =============================================================================
+// Constants
+// =============================================================================
+
+/** @brief Pi constant */
constexpr float PI = 3.14159265358979323846f;
+
+/** @brief Two times pi (full circle in radians) */
constexpr float TWO_PI = 2.0f * PI;
+
+/** @brief Half pi (quarter circle in radians) */
constexpr float HALF_PI = 0.5f * PI;
+
+/** @brief Degrees to radians conversion factor */
constexpr float DEG_TO_RAD = PI / 180.0f;
+
+/** @brief Radians to degrees conversion factor */
constexpr float RAD_TO_DEG = 180.0f / PI;
+
+/** @brief Small epsilon for floating-point comparisons */
constexpr float EPSILON = 1e-6f;
-// Utility functions
+// =============================================================================
+// Angle Conversion
+// =============================================================================
+
+/**
+ * @brief Converts degrees to radians
+ * @param degrees Angle in degrees
+ * @return Angle in radians
+ */
inline float toRadians(float degrees) {
return degrees * DEG_TO_RAD;
}
+/**
+ * @brief Converts radians to degrees
+ * @param radians Angle in radians
+ * @return Angle in degrees
+ */
inline float toDegrees(float radians) {
return radians * RAD_TO_DEG;
}
+/**
+ * @brief Converts a vec3 of degrees to radians
+ * @param degrees Euler angles in degrees
+ * @return Euler angles in radians
+ */
inline glm::vec3 toRadians(const glm::vec3& degrees) {
return degrees * DEG_TO_RAD;
}
+/**
+ * @brief Converts a vec3 of radians to degrees
+ * @param radians Euler angles in radians
+ * @return Euler angles in degrees
+ */
inline glm::vec3 toDegrees(const glm::vec3& radians) {
return radians * RAD_TO_DEG;
}
-// Linear interpolation
+// =============================================================================
+// Interpolation
+// =============================================================================
+
+/**
+ * @brief Linear interpolation between two values
+ * @tparam T Value type (float, vec2, vec3, vec4, etc.)
+ * @param a Start value
+ * @param b End value
+ * @param t Interpolation factor (0 = a, 1 = b)
+ * @return Interpolated value
+ *
+ * @code
+ * float val = math::lerp(0.0f, 10.0f, 0.5f); // 5.0f
+ * glm::vec3 pos = math::lerp(startPos, endPos, t);
+ * @endcode
+ */
template<typename T>
inline T lerp(const T& a, const T& b, float t) {
return a + t * (b - a);
}
-// Clamp value
+/**
+ * @brief Clamps a value between min and max
+ * @tparam T Value type
+ * @param value Value to clamp
+ * @param min Minimum bound
+ * @param max Maximum bound
+ * @return Clamped value
+ */
template<typename T>
inline T clamp(const T& value, const T& min, const T& max) {
return glm::clamp(value, min, max);
}
-// Approximately equal for floating point
+// =============================================================================
+// Comparisons
+// =============================================================================
+
+/**
+ * @brief Checks if two floats are approximately equal
+ * @param a First value
+ * @param b Second value
+ * @param epsilon Maximum difference threshold
+ * @return True if |a - b| < epsilon
+ */
inline bool approxEqual(float a, float b, float epsilon = EPSILON) {
return std::abs(a - b) < epsilon;
}
+/**
+ * @brief Checks if two vec3s are approximately equal
+ * @param a First vector
+ * @param b Second vector
+ * @param epsilon Maximum component difference threshold
+ * @return True if all components are approximately equal
+ */
inline bool approxEqual(const glm::vec3& a, const glm::vec3& b, float epsilon = EPSILON) {
return approxEqual(a.x, b.x, epsilon) &&
approxEqual(a.y, b.y, epsilon) &&
approxEqual(a.z, b.z, epsilon);
}
-// Create orthographic projection matrix
+// =============================================================================
+// Projection Matrices
+// =============================================================================
+
+/**
+ * @brief Creates an orthographic projection matrix
+ * @param left Left boundary
+ * @param right Right boundary
+ * @param bottom Bottom boundary
+ * @param top Top boundary
+ * @param near Near plane distance
+ * @param far Far plane distance
+ * @return Orthographic projection matrix
+ */
inline glm::mat4 ortho(float left, float right, float bottom, float top, float near, float far) {
return glm::ortho(left, right, bottom, top, near, far);
}
-// Create perspective projection matrix
+/**
+ * @brief Creates a perspective projection matrix
+ * @param fov Field of view in radians
+ * @param aspect Aspect ratio (width / height)
+ * @param near Near plane distance
+ * @param far Far plane distance
+ * @return Perspective projection matrix
+ */
inline glm::mat4 perspective(float fov, float aspect, float near, float far) {
return glm::perspective(fov, aspect, near, far);
}
-// Create look-at view matrix
+/**
+ * @brief Creates a look-at view matrix
+ * @param eye Camera position
+ * @param center Point to look at
+ * @param up World up vector
+ * @return View matrix
+ */
inline glm::mat4 lookAt(const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up) {
return glm::lookAt(eye, center, up);
}
-// Decompose transformation matrix
+// =============================================================================
+// Matrix Decomposition
+// =============================================================================
+
+/**
+ * @brief Decomposes a transformation matrix into components
+ * @param matrix The transformation matrix to decompose
+ * @param position Output: extracted position
+ * @param rotation Output: extracted Euler angles (radians)
+ * @param scale Output: extracted scale factors
+ *
+ * @code
+ * glm::vec3 pos, rot, scl;
+ * math::decompose(transform, pos, rot, scl);
+ * @endcode
+ */
inline void decompose(const glm::mat4& matrix, glm::vec3& position, glm::vec3& rotation, glm::vec3& scale) {
// Extract position
position = glm::vec3(matrix[3]);
diff --git a/src/esengine/platform/Platform.hpp b/src/esengine/platform/Platform.hpp
index 11f5bfb59..0b0becf0e 100644
--- a/src/esengine/platform/Platform.hpp
+++ b/src/esengine/platform/Platform.hpp
@@ -1,79 +1,269 @@
+/**
+ * @file Platform.hpp
+ * @brief Platform abstraction layer interface
+ * @details Defines the abstract interface for platform-specific functionality
+ * including window management, event handling, and timing.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
+
+// Standard library
#include <functional>
namespace esengine {
-// Touch event types
+// =============================================================================
+// Touch Events
+// =============================================================================
+
+/**
+ * @brief Types of touch events
+ */
enum class TouchType : u8 {
- Begin = 0,
- Move = 1,
- End = 2,
- Cancel = 3
+ Begin = 0, ///< Touch started (finger down)
+ Move = 1, ///< Touch moved (finger dragged)
+ End = 2, ///< Touch ended (finger lifted)
+ Cancel = 3 ///< Touch cancelled (system interrupted)
};
-// Touch point data
+/**
+ * @brief Touch point data
+ *
+ * @details Contains the position and identifier for a single touch point.
+ * The ID is used to track individual fingers in multi-touch.
+ */
struct TouchPoint {
+ /** @brief Unique identifier for this touch (for multi-touch tracking) */
i32 id;
+ /** @brief X position in screen coordinates */
f32 x;
+ /** @brief Y position in screen coordinates */
f32 y;
};
-// Key codes (subset for mobile/web)
+// =============================================================================
+// Key Codes
+// =============================================================================
+
+/**
+ * @brief Keyboard key codes
+ *
+ * @details Subset of key codes suitable for mobile/web platforms.
+ * Maps to standard JavaScript key codes for web compatibility.
+ */
enum class KeyCode : u32 {
Unknown = 0,
- Space = 32,
- Enter = 13,
- Escape = 27,
- Left = 37,
- Up = 38,
- Right = 39,
- Down = 40,
- A = 65,
- D = 68,
- S = 83,
- W = 87
+ 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
};
-// Event callbacks
+// =============================================================================
+// Event Callbacks
+// =============================================================================
+
+/**
+ * @brief Callback type for touch events
+ * @param type The type of touch event
+ * @param point Touch position and identifier
+ */
using TouchCallback = std::function<void(TouchType type, const TouchPoint& point)>;
+
+/**
+ * @brief Callback type for keyboard events
+ * @param key The key code
+ * @param pressed True if pressed, false if released
+ */
using KeyCallback = std::function<void(KeyCode key, bool pressed)>;
+
+/**
+ * @brief Callback type for window resize events
+ * @param width New width in pixels
+ * @param height New height in pixels
+ */
using ResizeCallback = std::function<void(u32 width, u32 height)>;
-// Platform abstraction interface
+// =============================================================================
+// Platform Class
+// =============================================================================
+
+/**
+ * @brief Abstract interface for platform-specific functionality
+ *
+ * @details Provides a common API for window management, event handling,
+ * and timing across different platforms (Web, Native, etc.).
+ * Implementations exist for specific platforms.
+ *
+ * @code
+ * auto platform = Platform::create();
+ * platform->initialize(800, 600);
+ *
+ * platform->setTouchCallback([](TouchType type, const TouchPoint& pt) {
+ * // Handle touch
+ * });
+ *
+ * while (platform->isRunning()) {
+ * platform->pollEvents();
+ * // Update and render
+ * platform->swapBuffers();
+ * }
+ *
+ * platform->shutdown();
+ * @endcode
+ */
class Platform {
public:
+ /** @brief Virtual destructor for proper cleanup */
virtual ~Platform() = default;
+ // =========================================================================
// Lifecycle
+ // =========================================================================
+
+ /**
+ * @brief Initializes the platform
+ * @param width Initial window width in pixels
+ * @param height Initial window height in pixels
+ * @return True on success
+ *
+ * @details Creates window/canvas and initializes graphics context.
+ */
virtual bool initialize(u32 width, u32 height) = 0;
+
+ /**
+ * @brief Shuts down the platform
+ * @details Releases all platform resources and destroys window.
+ */
virtual void shutdown() = 0;
- // Frame handling
+ // =========================================================================
+ // Frame Handling
+ // =========================================================================
+
+ /**
+ * @brief Polls and dispatches pending events
+ * @details Should be called once per frame at the start of the loop.
+ */
virtual void pollEvents() = 0;
+
+ /**
+ * @brief Swaps front and back buffers
+ * @details Presents the rendered frame. Should be called at end of loop.
+ */
virtual void swapBuffers() = 0;
+ // =========================================================================
// Time
+ // =========================================================================
+
+ /**
+ * @brief Gets time since platform initialization
+ * @return Time in seconds (high precision)
+ */
virtual f64 getTime() const = 0;
+
+ /**
+ * @brief Gets time since last frame
+ * @return Delta time in seconds
+ */
virtual f64 getDeltaTime() const = 0;
- // Window properties
+ // =========================================================================
+ // Window Properties
+ // =========================================================================
+
+ /**
+ * @brief Gets the window/canvas width
+ * @return Width in pixels
+ */
virtual u32 getWindowWidth() const = 0;
+
+ /**
+ * @brief Gets the window/canvas height
+ * @return Height in pixels
+ */
virtual u32 getWindowHeight() const = 0;
+
+ /**
+ * @brief Gets the window aspect ratio
+ * @return Width divided by height
+ */
virtual f32 getAspectRatio() const = 0;
+
+ /**
+ * @brief Gets the device pixel ratio
+ * @return Ratio of physical pixels to CSS pixels (for high-DPI displays)
+ */
virtual f32 getDevicePixelRatio() const = 0;
+ // =========================================================================
// State
+ // =========================================================================
+
+ /**
+ * @brief Checks if the application should continue running
+ * @return True if running, false if quit was requested
+ */
virtual bool isRunning() const = 0;
+
+ /**
+ * @brief Requests the application to quit
+ * @details Sets a flag that causes isRunning() to return false.
+ */
virtual void requestQuit() = 0;
- // Callbacks
+ // =========================================================================
+ // Event Callbacks
+ // =========================================================================
+
+ /**
+ * @brief Sets the touch event callback
+ * @param callback Function to call on touch events
+ */
virtual void setTouchCallback(TouchCallback callback) = 0;
+
+ /**
+ * @brief Sets the keyboard event callback
+ * @param callback Function to call on key events
+ */
virtual void setKeyCallback(KeyCallback callback) = 0;
+
+ /**
+ * @brief Sets the window resize callback
+ * @param callback Function to call on resize
+ */
virtual void setResizeCallback(ResizeCallback callback) = 0;
+ // =========================================================================
// Factory
+ // =========================================================================
+
+ /**
+ * @brief Creates a platform-appropriate implementation
+ * @return Unique pointer to the platform instance
+ *
+ * @details Returns WebPlatform for ES_PLATFORM_WEB, NativePlatform otherwise.
+ */
static Unique<Platform> create();
};
diff --git a/src/esengine/platform/input/Input.hpp b/src/esengine/platform/input/Input.hpp
index a2d3e60b8..a5e97252b 100644
--- a/src/esengine/platform/input/Input.hpp
+++ b/src/esengine/platform/input/Input.hpp
@@ -1,61 +1,236 @@
+/**
+ * @file Input.hpp
+ * @brief Input state management for touch and keyboard
+ * @details Provides a static interface for querying touch, keyboard, and
+ * mouse input state. Tracks current and previous frame states
+ * for detecting pressed/released transitions.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../../core/Types.hpp"
#include "../../math/Math.hpp"
#include "../Platform.hpp"
+
+// Standard library
#include <array>
#include <unordered_map>
namespace esengine {
-// Maximum simultaneous touch points
+// =============================================================================
+// Constants
+// =============================================================================
+
+/** @brief Maximum number of simultaneous touch points supported */
constexpr u32 MAX_TOUCH_POINTS = 10;
-// Input state for touch points
+// =============================================================================
+// Touch State
+// =============================================================================
+
+/**
+ * @brief State of a single touch point
+ *
+ * @details Tracks the current position and starting position of a touch
+ * for calculating movement deltas.
+ */
struct TouchState {
+ /** @brief Whether this touch point is currently active */
bool active = false;
+ /** @brief Current X position */
f32 x = 0.0f;
+ /** @brief Current Y position */
f32 y = 0.0f;
+ /** @brief X position when touch began */
f32 startX = 0.0f;
+ /** @brief Y position when touch began */
f32 startY = 0.0f;
};
-// Input manager - handles all input state
+// =============================================================================
+// Input Class
+// =============================================================================
+
+/**
+ * @brief Static input state manager
+ *
+ * @details Provides query methods for touch, keyboard, and mouse input.
+ * State is updated each frame by calling update(). The platform
+ * layer feeds events via onTouchEvent() and onKeyEvent().
+ *
+ * @code
+ * // In game loop
+ * Input::update();
+ *
+ * // Check touch input
+ * if (Input::isTouchPressed()) {
+ * glm::vec2 pos = Input::getTouchPosition();
+ * // Handle tap at pos
+ * }
+ *
+ * // Check keyboard
+ * if (Input::isKeyDown(KeyCode::Space)) {
+ * // Jump
+ * }
+ * @endcode
+ */
class Input {
public:
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
+
+ /**
+ * @brief Initializes the input system
+ * @details Clears all input state. Called automatically by Application.
+ */
static void init();
+
+ /**
+ * @brief Shuts down the input system
+ */
static void shutdown();
+
+ /**
+ * @brief Updates input state for new frame
+ * @details Copies current state to previous state for edge detection.
+ * Must be called once per frame before checking input.
+ */
static void update();
- // Touch input
+ // =========================================================================
+ // Touch Input
+ // =========================================================================
+
+ /**
+ * @brief Checks if a touch point is currently active
+ * @param index Touch point index (0 = primary touch)
+ * @return True if touch is down
+ */
static bool isTouchDown(u32 index = 0);
- static bool isTouchPressed(u32 index = 0); // Just started this frame
- static bool isTouchReleased(u32 index = 0); // Just ended this frame
+ /**
+ * @brief Checks if a touch just started this frame
+ * @param index Touch point index
+ * @return True if touch began this frame
+ */
+ static bool isTouchPressed(u32 index = 0);
+
+ /**
+ * @brief Checks if a touch just ended this frame
+ * @param index Touch point index
+ * @return True if touch ended this frame
+ */
+ static bool isTouchReleased(u32 index = 0);
+
+ /**
+ * @brief Gets the current position of a touch point
+ * @param index Touch point index
+ * @return Position in screen coordinates
+ */
static glm::vec2 getTouchPosition(u32 index = 0);
- static glm::vec2 getTouchDelta(u32 index = 0); // Movement since touch began
+
+ /**
+ * @brief Gets the movement delta since touch began
+ * @param index Touch point index
+ * @return (current position - start position)
+ */
+ static glm::vec2 getTouchDelta(u32 index = 0);
+
+ /**
+ * @brief Gets the number of active touch points
+ * @return Count of currently active touches
+ */
static u32 getTouchCount();
- // Keyboard input
+ // =========================================================================
+ // Keyboard Input
+ // =========================================================================
+
+ /**
+ * @brief Checks if a key is currently held down
+ * @param key The key code
+ * @return True if key is down
+ */
static bool isKeyDown(KeyCode key);
+
+ /**
+ * @brief Checks if a key was just pressed this frame
+ * @param key The key code
+ * @return True if key was just pressed
+ */
static bool isKeyPressed(KeyCode key);
+
+ /**
+ * @brief Checks if a key was just released this frame
+ * @param key The key code
+ * @return True if key was just released
+ */
static bool isKeyReleased(KeyCode key);
- // Mouse input (for web debugging)
+ // =========================================================================
+ // Mouse Input (Web Debugging)
+ // =========================================================================
+
+ /**
+ * @brief Gets the current mouse position
+ * @return Mouse position in screen coordinates
+ *
+ * @note Primarily for web/desktop debugging. On touch devices,
+ * use getTouchPosition() instead.
+ */
static glm::vec2 getMousePosition();
+
+ /**
+ * @brief Checks if a mouse button is held down
+ * @param button Mouse button index (0 = left, 1 = right, 2 = middle)
+ * @return True if button is down
+ */
static bool isMouseButtonDown(u32 button = 0);
- // Internal - called by platform
+ // =========================================================================
+ // Platform Interface (Internal)
+ // =========================================================================
+
+ /**
+ * @brief Called by platform on touch events
+ * @param type Touch event type
+ * @param point Touch point data
+ * @note Internal use only - called by Platform implementation
+ */
static void onTouchEvent(TouchType type, const TouchPoint& point);
+
+ /**
+ * @brief Called by platform on key events
+ * @param key Key code
+ * @param pressed True if pressed, false if released
+ * @note Internal use only - called by Platform implementation
+ */
static void onKeyEvent(KeyCode key, bool pressed);
private:
+ /** @brief Current frame touch states */
static std::array<TouchState, MAX_TOUCH_POINTS> touchStates_;
+ /** @brief Previous frame touch states */
static std::array<TouchState, MAX_TOUCH_POINTS> prevTouchStates_;
+ /** @brief Current frame key states */
static std::unordered_map<u32, bool> keyStates_;
+ /** @brief Previous frame key states */
static std::unordered_map<u32, bool> prevKeyStates_;
+ /** @brief Current mouse position */
static glm::vec2 mousePosition_;
};
diff --git a/src/esengine/renderer/Buffer.hpp b/src/esengine/renderer/Buffer.hpp
index a9a94cfaa..86a9221ed 100644
--- a/src/esengine/renderer/Buffer.hpp
+++ b/src/esengine/renderer/Buffer.hpp
@@ -1,52 +1,155 @@
+/**
+ * @file Buffer.hpp
+ * @brief GPU buffer abstractions for vertex and index data
+ * @details Provides cross-platform abstractions for OpenGL/WebGL buffer
+ * objects including VertexBuffer, IndexBuffer, and VertexArray.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
+
+// Standard library
#include <vector>
namespace esengine {
-// Vertex attribute types
+// =============================================================================
+// Shader Data Types
+// =============================================================================
+
+/**
+ * @brief Vertex attribute data types
+ *
+ * @details Used to describe the data type of each vertex attribute
+ * in the vertex layout. Maps to OpenGL/WebGL types.
+ */
enum class ShaderDataType {
None = 0,
- Float, Float2, Float3, Float4,
- Int, Int2, Int3, Int4,
- Bool
+ Float, ///< Single 32-bit float
+ Float2, ///< vec2 (2 floats)
+ Float3, ///< vec3 (3 floats)
+ Float4, ///< vec4 (4 floats)
+ Int, ///< Single 32-bit integer
+ Int2, ///< ivec2 (2 ints)
+ Int3, ///< ivec3 (3 ints)
+ Int4, ///< ivec4 (4 ints)
+ Bool ///< Boolean (1 byte)
};
+/**
+ * @brief Gets the size in bytes of a shader data type
+ * @param type The shader data type
+ * @return Size in bytes
+ */
u32 shaderDataTypeSize(ShaderDataType type);
+
+/**
+ * @brief Gets the component count of a shader data type
+ * @param type The shader data type
+ * @return Number of components (e.g., 3 for Float3)
+ */
u32 shaderDataTypeComponentCount(ShaderDataType type);
-// Single vertex attribute
+// =============================================================================
+// Vertex Attribute
+// =============================================================================
+
+/**
+ * @brief Describes a single vertex attribute
+ *
+ * @details Contains all information needed to configure a vertex attribute
+ * pointer in OpenGL/WebGL.
+ */
struct VertexAttribute {
+ /** @brief Attribute name (for debugging) */
std::string name;
+ /** @brief Data type of the attribute */
ShaderDataType type;
+ /** @brief Size in bytes */
u32 size;
+ /** @brief Byte offset within the vertex */
u32 offset;
+ /** @brief Whether to normalize integer data to [0,1] or [-1,1] */
bool normalized;
+ /** @brief Default constructor */
VertexAttribute() = default;
+
+ /**
+ * @brief Constructs a vertex attribute
+ * @param type Data type
+ * @param name Attribute name
+ * @param normalized Whether to normalize integer data
+ */
VertexAttribute(ShaderDataType type, const std::string& name, bool normalized = false)
: name(name), type(type), size(shaderDataTypeSize(type)), offset(0), normalized(normalized) {}
};
-// Vertex buffer layout
+// =============================================================================
+// Vertex Layout
+// =============================================================================
+
+/**
+ * @brief Describes the layout of vertex data in a buffer
+ *
+ * @details Specifies the attributes that make up each vertex and their
+ * arrangement in memory. Used to configure vertex attribute pointers.
+ *
+ * @code
+ * VertexLayout layout = {
+ * {ShaderDataType::Float3, "a_position"},
+ * {ShaderDataType::Float2, "a_texCoord"},
+ * {ShaderDataType::Float4, "a_color"}
+ * };
+ * @endcode
+ */
class VertexLayout {
public:
+ /** @brief Default constructor (empty layout) */
VertexLayout() = default;
+
+ /**
+ * @brief Constructs layout from initializer list
+ * @param attributes List of vertex attributes
+ */
VertexLayout(std::initializer_list<VertexAttribute> attributes)
: attributes_(attributes) {
calculateOffsetsAndStride();
}
+ /**
+ * @brief Gets all vertex attributes
+ * @return Const reference to attribute vector
+ */
const std::vector<VertexAttribute>& getAttributes() const { return attributes_; }
+
+ /**
+ * @brief Gets the stride (total size) of one vertex
+ * @return Stride in bytes
+ */
u32 getStride() const { return stride_; }
+ // Iterator support for range-based for loops
std::vector<VertexAttribute>::iterator begin() { return attributes_.begin(); }
std::vector<VertexAttribute>::iterator end() { return attributes_.end(); }
std::vector<VertexAttribute>::const_iterator begin() const { return attributes_.begin(); }
std::vector<VertexAttribute>::const_iterator end() const { return attributes_.end(); }
private:
+ /**
+ * @brief Calculates byte offsets and total stride
+ */
void calculateOffsetsAndStride() {
u32 offset = 0;
stride_ = 0;
@@ -61,7 +164,27 @@ private:
u32 stride_ = 0;
};
+// =============================================================================
// Vertex Buffer (VBO)
+// =============================================================================
+
+/**
+ * @brief GPU buffer for vertex data
+ *
+ * @details Wraps OpenGL/WebGL Vertex Buffer Objects (VBOs). Supports both
+ * static and dynamic buffer usage.
+ *
+ * @code
+ * struct Vertex { float x, y, u, v; };
+ * std::vector<Vertex> vertices = {...};
+ *
+ * auto vbo = VertexBuffer::create(vertices);
+ * vbo->setLayout({
+ * {ShaderDataType::Float2, "a_position"},
+ * {ShaderDataType::Float2, "a_texCoord"}
+ * });
+ * @endcode
+ */
class VertexBuffer {
public:
VertexBuffer() = default;
@@ -73,22 +196,108 @@ public:
VertexBuffer(VertexBuffer&& other) noexcept;
VertexBuffer& operator=(VertexBuffer&& other) noexcept;
- // Create static buffer
- static Unique<VertexBuffer> create(const void* data, u32 size);
+ // =========================================================================
+ // Creation
+ // =========================================================================
+
+ /**
+ * @brief Creates a static buffer from a vector
+ * @tparam T Vertex type
+ * @param data Vector of vertex data
+ * @return Unique pointer to the buffer
+ */
+ template<typename T>
+ static Unique<VertexBuffer> create(const std::vector<T>& data) {
+ return createRaw(data.data(), static_cast<u32>(data.size() * sizeof(T)));
+ }
- // Create dynamic buffer
- static Unique<VertexBuffer> create(u32 size);
+ /**
+ * @brief Creates a static buffer from a C array
+ * @tparam T Vertex type
+ * @tparam N Array size
+ * @param data Array of vertex data
+ * @return Unique pointer to the buffer
+ */
+ template<typename T, usize N>
+ static Unique<VertexBuffer> create(const T (&data)[N]) {
+ return createRaw(data, static_cast<u32>(N * sizeof(T)));
+ }
+ /**
+ * @brief Creates a dynamic buffer of specified size
+ * @param sizeBytes Buffer size in bytes
+ * @return Unique pointer to the buffer
+ *
+ * @details Use setData() to upload data later.
+ */
+ static Unique<VertexBuffer> create(u32 sizeBytes);
+
+ /**
+ * @brief Creates a buffer from raw data pointer
+ * @param data Pointer to vertex data
+ * @param sizeBytes Size of data in bytes
+ * @return Unique pointer to the buffer
+ */
+ static Unique<VertexBuffer> createRaw(const void* data, u32 sizeBytes);
+
+ // =========================================================================
+ // Operations
+ // =========================================================================
+
+ /** @brief Binds the buffer for rendering */
void bind() const;
+
+ /** @brief Unbinds the buffer */
void unbind() const;
- // Update data (for dynamic buffers)
- void setData(const void* data, u32 size);
+ /**
+ * @brief Updates buffer data from a vector
+ * @tparam T Vertex type
+ * @param data New vertex data
+ */
+ template<typename T>
+ void setData(const std::vector<T>& data) {
+ setDataRaw(data.data(), static_cast<u32>(data.size() * sizeof(T)));
+ }
+
+ /**
+ * @brief Updates buffer data from a C array
+ * @tparam T Vertex type
+ * @tparam N Array size
+ * @param data New vertex data
+ */
+ template<typename T, usize N>
+ void setData(const T (&data)[N]) {
+ setDataRaw(data, static_cast<u32>(N * sizeof(T)));
+ }
+
+ /**
+ * @brief Updates buffer data from raw pointer
+ * @param data Pointer to new data
+ * @param sizeBytes Size of data in bytes
+ */
+ void setDataRaw(const void* data, u32 sizeBytes);
+ // =========================================================================
// Layout
+ // =========================================================================
+
+ /**
+ * @brief Sets the vertex layout
+ * @param layout The vertex attribute layout
+ */
void setLayout(const VertexLayout& layout) { layout_ = layout; }
+
+ /**
+ * @brief Gets the vertex layout
+ * @return Const reference to the layout
+ */
const VertexLayout& getLayout() const { return layout_; }
+ /**
+ * @brief Gets the GPU buffer ID
+ * @return OpenGL buffer handle
+ */
u32 getId() const { return bufferId_; }
private:
@@ -96,7 +305,21 @@ private:
VertexLayout layout_;
};
+// =============================================================================
// Index Buffer (EBO)
+// =============================================================================
+
+/**
+ * @brief GPU buffer for index data
+ *
+ * @details Wraps OpenGL/WebGL Element Buffer Objects (EBOs). Supports
+ * both 16-bit and 32-bit indices.
+ *
+ * @code
+ * u32 indices[] = {0, 1, 2, 2, 3, 0};
+ * auto ebo = IndexBuffer::create(indices, 6);
+ * @endcode
+ */
class IndexBuffer {
public:
IndexBuffer() = default;
@@ -108,15 +331,38 @@ public:
IndexBuffer(IndexBuffer&& other) noexcept;
IndexBuffer& operator=(IndexBuffer&& other) noexcept;
- // Create from indices
+ /**
+ * @brief Creates an index buffer with 32-bit indices
+ * @param indices Pointer to index data
+ * @param count Number of indices
+ * @return Unique pointer to the buffer
+ */
static Unique<IndexBuffer> create(const u32* indices, u32 count);
+
+ /**
+ * @brief Creates an index buffer with 16-bit indices
+ * @param indices Pointer to index data
+ * @param count Number of indices
+ * @return Unique pointer to the buffer
+ *
+ * @details Use 16-bit indices for better performance when vertex
+ * count is under 65536.
+ */
static Unique<IndexBuffer> create(const u16* indices, u32 count);
+ /** @brief Binds the buffer for rendering */
void bind() const;
+
+ /** @brief Unbinds the buffer */
void unbind() const;
+ /** @brief Gets the number of indices */
u32 getCount() const { return count_; }
+
+ /** @brief Gets the GPU buffer ID */
u32 getId() const { return bufferId_; }
+
+ /** @brief Returns true if using 16-bit indices */
bool is16Bit() const { return is16Bit_; }
private:
@@ -125,7 +371,31 @@ private:
bool is16Bit_ = false;
};
-// Vertex Array Object (VAO) - abstracts vertex attribute configuration
+// =============================================================================
+// Vertex Array Object (VAO)
+// =============================================================================
+
+/**
+ * @brief Encapsulates vertex attribute configuration
+ *
+ * @details Wraps OpenGL/WebGL Vertex Array Objects. Stores the association
+ * between vertex buffers and their attribute layouts.
+ *
+ * @code
+ * auto vao = VertexArray::create();
+ *
+ * auto vbo = VertexBuffer::create(vertices);
+ * vbo->setLayout({...});
+ * vao->addVertexBuffer(std::move(vbo));
+ *
+ * auto ebo = IndexBuffer::create(indices, 6);
+ * vao->setIndexBuffer(std::move(ebo));
+ *
+ * // Rendering
+ * vao->bind();
+ * RenderCommand::drawIndexed(*vao);
+ * @endcode
+ */
class VertexArray {
public:
VertexArray();
@@ -137,15 +407,44 @@ public:
VertexArray(VertexArray&& other) noexcept;
VertexArray& operator=(VertexArray&& other) noexcept;
+ /**
+ * @brief Creates a new vertex array
+ * @return Unique pointer to the VAO
+ */
static Unique<VertexArray> create();
+ /** @brief Binds the VAO for rendering */
void bind() const;
+
+ /** @brief Unbinds the VAO */
void unbind() const;
+ /**
+ * @brief Adds a vertex buffer to the VAO
+ * @param buffer Shared pointer to the vertex buffer
+ *
+ * @details The buffer's layout must be set before adding.
+ * Multiple vertex buffers can be added for interleaved
+ * or separate attribute streams.
+ */
void addVertexBuffer(Shared<VertexBuffer> buffer);
+
+ /**
+ * @brief Sets the index buffer
+ * @param buffer Shared pointer to the index buffer
+ */
void setIndexBuffer(Shared<IndexBuffer> buffer);
+ /**
+ * @brief Gets all attached vertex buffers
+ * @return Const reference to buffer vector
+ */
const std::vector<Shared<VertexBuffer>>& getVertexBuffers() const { return vertexBuffers_; }
+
+ /**
+ * @brief Gets the index buffer
+ * @return Const reference to the index buffer pointer
+ */
const Shared<IndexBuffer>& getIndexBuffer() const { return indexBuffer_; }
private:
diff --git a/src/esengine/renderer/RenderCommand.hpp b/src/esengine/renderer/RenderCommand.hpp
index fb11710c3..abf8db869 100644
--- a/src/esengine/renderer/RenderCommand.hpp
+++ b/src/esengine/renderer/RenderCommand.hpp
@@ -1,38 +1,180 @@
+/**
+ * @file RenderCommand.hpp
+ * @brief Low-level rendering commands
+ * @details Provides a static interface for GPU state management and
+ * draw call submission. Abstracts OpenGL/WebGL calls.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
#include "../math/Math.hpp"
namespace esengine {
+// Forward declaration
class VertexArray;
-// Static class for low-level rendering commands
+// =============================================================================
+// RenderCommand Class
+// =============================================================================
+
+/**
+ * @brief Static interface for low-level rendering operations
+ *
+ * @details Provides direct control over GPU state and draw calls.
+ * All methods are static - no instance needed. Used internally
+ * by the Renderer class and can be used directly for custom
+ * rendering pipelines.
+ *
+ * @code
+ * RenderCommand::init();
+ * RenderCommand::setViewport(0, 0, 800, 600);
+ * RenderCommand::setClearColor({0.1f, 0.1f, 0.1f, 1.0f});
+ * RenderCommand::clear();
+ *
+ * // Enable alpha blending
+ * RenderCommand::setBlending(true);
+ * RenderCommand::setBlendFunc();
+ *
+ * // Draw indexed geometry
+ * vao.bind();
+ * RenderCommand::drawIndexed(vao);
+ * @endcode
+ */
class RenderCommand {
public:
+ // =========================================================================
+ // Initialization
+ // =========================================================================
+
+ /**
+ * @brief Initializes the rendering subsystem
+ * @details Must be called once before any other RenderCommand functions.
+ * Sets up OpenGL/WebGL state and capabilities.
+ */
static void init();
+
+ /**
+ * @brief Shuts down the rendering subsystem
+ * @details Releases any allocated resources. Call once at application exit.
+ */
static void shutdown();
+ // =========================================================================
+ // Viewport and Clearing
+ // =========================================================================
+
+ /**
+ * @brief Sets the rendering viewport
+ * @param x Viewport X origin (pixels from left)
+ * @param y Viewport Y origin (pixels from bottom)
+ * @param width Viewport width in pixels
+ * @param height Viewport height in pixels
+ */
static void setViewport(i32 x, i32 y, u32 width, u32 height);
+
+ /**
+ * @brief Sets the color used by clear()
+ * @param color RGBA color (0-1 range)
+ */
static void setClearColor(const glm::vec4& color);
+
+ /**
+ * @brief Clears the framebuffer
+ * @details Clears both color and depth buffers.
+ */
static void clear();
+ // =========================================================================
+ // Draw Calls
+ // =========================================================================
+
+ /**
+ * @brief Draws indexed geometry
+ * @param vao Vertex array containing geometry and indices
+ * @param indexCount Number of indices to draw (0 = all)
+ *
+ * @details The VAO must be bound and have an index buffer set.
+ */
static void drawIndexed(const VertexArray& vao, u32 indexCount = 0);
+
+ /**
+ * @brief Draws non-indexed geometry
+ * @param vertexCount Number of vertices to draw
+ *
+ * @details Draws vertices as triangles (GL_TRIANGLES).
+ */
static void drawArrays(u32 vertexCount);
- // Depth testing
+ // =========================================================================
+ // Depth Testing
+ // =========================================================================
+
+ /**
+ * @brief Enables or disables depth testing
+ * @param enabled True to enable depth test
+ */
static void setDepthTest(bool enabled);
+
+ /**
+ * @brief Enables or disables depth buffer writes
+ * @param enabled True to allow depth writes
+ */
static void setDepthWrite(bool enabled);
+ // =========================================================================
// Blending
+ // =========================================================================
+
+ /**
+ * @brief Enables or disables alpha blending
+ * @param enabled True to enable blending
+ */
static void setBlending(bool enabled);
- static void setBlendFunc(); // Default: SrcAlpha, OneMinusSrcAlpha
- // Face culling
+ /**
+ * @brief Sets the blend function to standard alpha blending
+ * @details Uses SrcAlpha and OneMinusSrcAlpha factors.
+ */
+ static void setBlendFunc();
+
+ // =========================================================================
+ // Face Culling
+ // =========================================================================
+
+ /**
+ * @brief Enables or disables face culling
+ * @param enabled True to enable culling
+ */
static void setCulling(bool enabled);
- static void setCullFace(bool front); // true = cull front, false = cull back
- // Wireframe mode
+ /**
+ * @brief Sets which face to cull
+ * @param front True to cull front faces, false for back faces
+ */
+ static void setCullFace(bool front);
+
+ // =========================================================================
+ // Debug
+ // =========================================================================
+
+ /**
+ * @brief Enables or disables wireframe rendering
+ * @param enabled True for wireframe mode
+ *
+ * @note May not be supported on WebGL/OpenGL ES.
+ */
static void setWireframe(bool enabled);
};
diff --git a/src/esengine/renderer/Renderer.hpp b/src/esengine/renderer/Renderer.hpp
index 23b1a37d4..b9728deb0 100644
--- a/src/esengine/renderer/Renderer.hpp
+++ b/src/esengine/renderer/Renderer.hpp
@@ -1,5 +1,22 @@
+/**
+ * @file Renderer.hpp
+ * @brief Core rendering functionality for ESEngine
+ * @details Provides both immediate-mode rendering (Renderer) and efficient
+ * batched 2D sprite rendering (BatchRenderer2D) for WebGL/OpenGL ES.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
#include "../math/Math.hpp"
#include "Buffer.hpp"
@@ -8,12 +25,25 @@
namespace esengine {
-// Renderer statistics
+// =============================================================================
+// Renderer Statistics
+// =============================================================================
+
+/**
+ * @brief Statistics for rendering performance analysis
+ *
+ * @details Tracks draw calls and geometry counts per frame.
+ * Use Renderer::getStats() to retrieve current values.
+ */
struct RendererStats {
+ /** @brief Number of draw calls this frame */
u32 drawCalls = 0;
+ /** @brief Number of triangles rendered this frame */
u32 triangleCount = 0;
+ /** @brief Number of vertices processed this frame */
u32 vertexCount = 0;
+ /** @brief Resets all counters to zero */
void reset() {
drawCalls = 0;
triangleCount = 0;
@@ -21,44 +51,148 @@ struct RendererStats {
}
};
-// Static renderer class
+// =============================================================================
+// Renderer Class
+// =============================================================================
+
+/**
+ * @brief Static renderer for immediate-mode drawing
+ *
+ * @details Provides low-level rendering operations and a simple 2D quad
+ * drawing API. For performance-critical sprite rendering, prefer
+ * BatchRenderer2D.
+ *
+ * @code
+ * // Initialization (called by Application)
+ * Renderer::init();
+ *
+ * // Frame rendering
+ * Renderer::beginFrame();
+ * Renderer::clear();
+ * Renderer::beginScene(camera.getViewProjection());
+ *
+ * Renderer::drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1}); // Red quad
+ *
+ * Renderer::endScene();
+ * Renderer::endFrame();
+ * @endcode
+ */
class Renderer {
public:
+ /** @brief Initializes the renderer (call once at startup) */
static void init();
+
+ /** @brief Shuts down the renderer and releases resources */
static void shutdown();
+ /** @brief Begins a new frame */
static void beginFrame();
+
+ /** @brief Ends the current frame */
static void endFrame();
- // Set viewport and clear color
+ // =========================================================================
+ // Viewport and Clearing
+ // =========================================================================
+
+ /**
+ * @brief Sets the rendering viewport
+ * @param x Viewport X origin in pixels
+ * @param y Viewport Y origin in pixels
+ * @param width Viewport width in pixels
+ * @param height Viewport height in pixels
+ */
static void setViewport(i32 x, i32 y, u32 width, u32 height);
+
+ /**
+ * @brief Sets the clear color for subsequent clear() calls
+ * @param color RGBA color (0-1 range)
+ */
static void setClearColor(const glm::vec4& color);
+
+ /** @brief Clears the color and depth buffers */
static void clear();
- // Camera / Projection
+ // =========================================================================
+ // Scene Management
+ // =========================================================================
+
+ /**
+ * @brief Begins a scene with the given camera transform
+ * @param viewProjection Combined view-projection matrix
+ */
static void beginScene(const glm::mat4& viewProjection);
+
+ /** @brief Ends the current scene */
static void endScene();
- // Submit draw calls
+ // =========================================================================
+ // Draw Submission
+ // =========================================================================
+
+ /**
+ * @brief Submits geometry for rendering with a shader
+ * @param shader The shader program to use
+ * @param vao The vertex array containing geometry
+ * @param transform Model transform matrix (defaults to identity)
+ */
static void submit(const Shader& shader,
const VertexArray& vao,
const glm::mat4& transform = glm::mat4(1.0f));
- // 2D Rendering helpers
+ // =========================================================================
+ // 2D Rendering Helpers
+ // =========================================================================
+
+ /**
+ * @brief Draws a colored quad at a 2D position
+ * @param position Center position (x, y)
+ * @param size Width and height
+ * @param color RGBA color
+ */
static void drawQuad(const glm::vec2& position, const glm::vec2& size,
const glm::vec4& color);
+ /**
+ * @brief Draws a textured quad at a 2D position
+ * @param position Center position (x, y)
+ * @param size Width and height
+ * @param texture Texture to apply
+ * @param tintColor Optional color tint (defaults to white)
+ */
static void drawQuad(const glm::vec2& position, const glm::vec2& size,
const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
+ /**
+ * @brief Draws a colored quad at a 3D position
+ * @param position Center position (x, y, z)
+ * @param size Width and height
+ * @param color RGBA color
+ */
static void drawQuad(const glm::vec3& position, const glm::vec2& size,
const glm::vec4& color);
+ /**
+ * @brief Draws a textured quad at a 3D position
+ * @param position Center position (x, y, z)
+ * @param size Width and height
+ * @param texture Texture to apply
+ * @param tintColor Optional color tint (defaults to white)
+ */
static void drawQuad(const glm::vec3& position, const glm::vec2& size,
const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
+ // =========================================================================
// Statistics
+ // =========================================================================
+
+ /**
+ * @brief Gets the current frame's rendering statistics
+ * @return RendererStats with draw call and geometry counts
+ */
static RendererStats getStats();
+
+ /** @brief Resets statistics counters (call at frame start) */
static void resetStats();
private:
@@ -66,40 +200,129 @@ private:
static void flushBatch();
};
-// 2D Batch Renderer for efficient sprite rendering
+// =============================================================================
+// BatchRenderer2D Class
+// =============================================================================
+
+/**
+ * @brief High-performance batched 2D sprite renderer
+ *
+ * @details Batches multiple quads into single draw calls for optimal
+ * performance. Supports textured and colored quads with rotation.
+ *
+ * @code
+ * BatchRenderer2D::init();
+ * BatchRenderer2D::setProjection(orthoMatrix);
+ *
+ * BatchRenderer2D::beginBatch();
+ * for (auto& sprite : sprites) {
+ * BatchRenderer2D::drawQuad(sprite.pos, sprite.size, sprite.textureId);
+ * }
+ * BatchRenderer2D::endBatch();
+ * BatchRenderer2D::flush();
+ * @endcode
+ *
+ * @note The batch is automatically flushed when full or when texture
+ * slots are exhausted.
+ */
class BatchRenderer2D {
public:
+ /** @brief Initializes the batch renderer */
static void init();
+
+ /** @brief Shuts down and releases batch renderer resources */
static void shutdown();
+ /** @brief Begins a new batch */
static void beginBatch();
+
+ /** @brief Ends the current batch (prepares for flush) */
static void endBatch();
+
+ /** @brief Flushes the batch to the GPU (issues draw call) */
static void flush();
- // Draw textured quad
+ // =========================================================================
+ // Textured Quads
+ // =========================================================================
+
+ /**
+ * @brief Draws a textured quad at a 2D position
+ * @param position Position (x, y)
+ * @param size Width and height
+ * @param textureId GPU texture handle
+ * @param color Color tint (defaults to white)
+ */
static void drawQuad(const glm::vec2& position, const glm::vec2& size,
u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
+ /**
+ * @brief Draws a textured quad at a 3D position
+ * @param position Position (x, y, z)
+ * @param size Width and height
+ * @param textureId GPU texture handle
+ * @param color Color tint (defaults to white)
+ */
static void drawQuad(const glm::vec3& position, const glm::vec2& size,
u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
- // Draw colored quad (no texture)
+ // =========================================================================
+ // Colored Quads
+ // =========================================================================
+
+ /**
+ * @brief Draws a solid colored quad (no texture)
+ * @param position Position (x, y)
+ * @param size Width and height
+ * @param color RGBA color
+ */
static void drawQuad(const glm::vec2& position, const glm::vec2& size,
const glm::vec4& color);
- // Draw rotated quad
+ // =========================================================================
+ // Rotated Quads
+ // =========================================================================
+
+ /**
+ * @brief Draws a rotated colored quad
+ * @param position Position (x, y)
+ * @param size Width and height
+ * @param rotation Rotation angle in radians
+ * @param color RGBA color
+ */
static void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
f32 rotation, const glm::vec4& color);
+ /**
+ * @brief Draws a rotated textured quad
+ * @param position Position (x, y)
+ * @param size Width and height
+ * @param rotation Rotation angle in radians
+ * @param textureId GPU texture handle
+ * @param tintColor Color tint (defaults to white)
+ */
static void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
f32 rotation, u32 textureId,
const glm::vec4& tintColor = glm::vec4(1.0f));
- // Set projection matrix
+ // =========================================================================
+ // Configuration
+ // =========================================================================
+
+ /**
+ * @brief Sets the projection matrix for 2D rendering
+ * @param projection Orthographic projection matrix
+ */
static void setProjection(const glm::mat4& projection);
+ // =========================================================================
// Statistics
+ // =========================================================================
+
+ /** @brief Gets the number of draw calls in the current/last frame */
static u32 getDrawCallCount();
+
+ /** @brief Gets the number of quads rendered in the current/last frame */
static u32 getQuadCount();
};
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
index 4cd9d7b96..20dfbfe00 100644
--- a/src/esengine/renderer/Shader.hpp
+++ b/src/esengine/renderer/Shader.hpp
@@ -1,12 +1,49 @@
+/**
+ * @file Shader.hpp
+ * @brief GPU shader program abstraction
+ * @details Provides a cross-platform shader abstraction for OpenGL ES/WebGL
+ * including compilation, linking, and uniform management.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
#include "../math/Math.hpp"
+
+// Standard library
#include <string>
#include <unordered_map>
namespace esengine {
+// =============================================================================
+// Shader Class
+// =============================================================================
+
+/**
+ * @brief GPU shader program for rendering
+ *
+ * @details Encapsulates an OpenGL/WebGL shader program consisting of
+ * a vertex shader and fragment shader. Provides uniform setting
+ * with location caching for performance.
+ *
+ * @code
+ * auto shader = Shader::create(vertexSource, fragmentSource);
+ * shader->bind();
+ * shader->setUniform("u_projection", projectionMatrix);
+ * shader->setUniform("u_color", glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
+ * @endcode
+ */
class Shader {
public:
Shader() = default;
@@ -20,41 +57,154 @@ public:
Shader(Shader&& other) noexcept;
Shader& operator=(Shader&& other) noexcept;
- // Create shader from source code
+ // =========================================================================
+ // Creation
+ // =========================================================================
+
+ /**
+ * @brief Creates a shader from source code strings
+ * @param vertexSrc Vertex shader GLSL source
+ * @param fragmentSrc Fragment shader GLSL source
+ * @return Unique pointer to the shader, or nullptr on failure
+ */
static Unique<Shader> create(const std::string& vertexSrc, const std::string& fragmentSrc);
- // Create shader from files
+ /**
+ * @brief Creates a shader from file paths
+ * @param vertexPath Path to vertex shader file
+ * @param fragmentPath Path to fragment shader file
+ * @return Unique pointer to the shader, or nullptr on failure
+ */
static Unique<Shader> createFromFile(const std::string& vertexPath, const std::string& fragmentPath);
- // Bind/unbind shader
+ // =========================================================================
+ // Operations
+ // =========================================================================
+
+ /** @brief Binds the shader for rendering */
void bind() const;
+
+ /** @brief Unbinds the shader */
void unbind() const;
- // Uniform setters
- void setUniform(const std::string& name, i32 value);
- void setUniform(const std::string& name, f32 value);
- void setUniform(const std::string& name, const glm::vec2& value);
- void setUniform(const std::string& name, const glm::vec3& value);
- void setUniform(const std::string& name, const glm::vec4& value);
- void setUniform(const std::string& name, const glm::mat3& value);
- void setUniform(const std::string& name, const glm::mat4& value);
+ // =========================================================================
+ // Uniforms
+ // =========================================================================
+
+ /**
+ * @brief Sets an integer uniform
+ * @param name Uniform name in shader
+ * @param value Integer value
+ */
+ void setUniform(const std::string& name, i32 value) const;
+
+ /**
+ * @brief Sets a float uniform
+ * @param name Uniform name in shader
+ * @param value Float value
+ */
+ void setUniform(const std::string& name, f32 value) const;
+
+ /**
+ * @brief Sets a vec2 uniform
+ * @param name Uniform name in shader
+ * @param value Vector value
+ */
+ void setUniform(const std::string& name, const glm::vec2& value) const;
- // Check if shader is valid
+ /**
+ * @brief Sets a vec3 uniform
+ * @param name Uniform name in shader
+ * @param value Vector value
+ */
+ void setUniform(const std::string& name, const glm::vec3& value) const;
+
+ /**
+ * @brief Sets a vec4 uniform
+ * @param name Uniform name in shader
+ * @param value Vector value
+ */
+ void setUniform(const std::string& name, const glm::vec4& value) const;
+
+ /**
+ * @brief Sets a mat3 uniform
+ * @param name Uniform name in shader
+ * @param value Matrix value
+ */
+ void setUniform(const std::string& name, const glm::mat3& value) const;
+
+ /**
+ * @brief Sets a mat4 uniform
+ * @param name Uniform name in shader
+ * @param value Matrix value
+ */
+ void setUniform(const std::string& name, const glm::mat4& value) const;
+
+ // =========================================================================
+ // State
+ // =========================================================================
+
+ /**
+ * @brief Checks if the shader compiled and linked successfully
+ * @return True if the shader is usable
+ */
bool isValid() const { return programId_ != 0; }
+
+ /**
+ * @brief Gets the OpenGL program ID
+ * @return GPU program handle
+ */
u32 getProgramId() const { return programId_; }
private:
+ /**
+ * @brief Compiles and links shader sources
+ * @param vertexSrc Vertex shader source
+ * @param fragmentSrc Fragment shader source
+ * @return True on success
+ */
bool compile(const std::string& vertexSrc, const std::string& fragmentSrc);
- i32 getUniformLocation(const std::string& name);
+ /**
+ * @brief Gets uniform location with caching
+ * @param name Uniform name
+ * @return Location, or -1 if not found
+ */
+ i32 getUniformLocation(const std::string& name) const;
+
+ /** @brief OpenGL program handle */
u32 programId_ = 0;
- std::unordered_map<std::string, i32> uniformCache_;
+
+ /** @brief Cached uniform locations (mutable for const uniform setters) */
+ mutable std::unordered_map<std::string, i32> uniformCache_;
};
-// Common shader sources for 2D rendering
+// =============================================================================
+// Built-in Shader Sources
+// =============================================================================
+
+/**
+ * @brief Common shader source code for 2D rendering
+ *
+ * @details Provides ready-to-use GLSL ES shader sources for common
+ * 2D rendering tasks. Compatible with WebGL and OpenGL ES 2.0.
+ */
namespace ShaderSources {
-// Basic 2D sprite vertex shader
+/**
+ * @brief Vertex shader for textured sprites
+ *
+ * @details Uniforms:
+ * - u_projection: Projection matrix
+ * - u_model: Model transform matrix
+ *
+ * Attributes:
+ * - a_position: Vertex position (vec2)
+ * - a_texCoord: Texture coordinates (vec2)
+ *
+ * Outputs:
+ * - v_texCoord: Interpolated texture coordinates
+ */
inline const char* SPRITE_VERTEX = R"(
attribute vec2 a_position;
attribute vec2 a_texCoord;
@@ -70,7 +220,16 @@ inline const char* SPRITE_VERTEX = R"(
}
)";
-// Basic 2D sprite fragment shader
+/**
+ * @brief Fragment shader for textured sprites
+ *
+ * @details Uniforms:
+ * - u_texture: Texture sampler
+ * - u_color: Color tint
+ *
+ * Inputs:
+ * - v_texCoord: Texture coordinates
+ */
inline const char* SPRITE_FRAGMENT = R"(
precision mediump float;
@@ -85,7 +244,16 @@ inline const char* SPRITE_FRAGMENT = R"(
}
)";
-// Simple color vertex shader
+/**
+ * @brief Vertex shader for solid color shapes
+ *
+ * @details Uniforms:
+ * - u_projection: Projection matrix
+ * - u_model: Model transform matrix
+ *
+ * Attributes:
+ * - a_position: Vertex position (vec2)
+ */
inline const char* COLOR_VERTEX = R"(
attribute vec2 a_position;
@@ -97,7 +265,12 @@ inline const char* COLOR_VERTEX = R"(
}
)";
-// Simple color fragment shader
+/**
+ * @brief Fragment shader for solid color shapes
+ *
+ * @details Uniforms:
+ * - u_color: Fill color
+ */
inline const char* COLOR_FRAGMENT = R"(
precision mediump float;
diff --git a/src/esengine/renderer/Texture.hpp b/src/esengine/renderer/Texture.hpp
index 43dc0f368..caad9aa07 100644
--- a/src/esengine/renderer/Texture.hpp
+++ b/src/esengine/renderer/Texture.hpp
@@ -1,39 +1,126 @@
+/**
+ * @file Texture.hpp
+ * @brief GPU texture abstraction for 2D images
+ * @details Provides cross-platform texture handling for OpenGL ES/WebGL
+ * including creation, binding, and pixel data management.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
#pragma once
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
#include "../core/Types.hpp"
+
+// Standard library
#include <string>
+#include <vector>
namespace esengine {
+// =============================================================================
+// Texture Enums
+// =============================================================================
+
+/**
+ * @brief Texture pixel format
+ */
enum class TextureFormat {
None = 0,
- RGB8,
- RGBA8,
- Depth24
+ RGB8, ///< 3 channels, 8 bits each (24 bpp)
+ RGBA8, ///< 4 channels, 8 bits each (32 bpp)
+ Depth24 ///< Depth buffer format (24 bits)
};
+/**
+ * @brief Texture filtering mode
+ *
+ * @details Controls how texels are sampled when the texture is
+ * scaled up or down.
+ */
enum class TextureFilter {
- Nearest,
- Linear
+ Nearest, ///< No interpolation (pixelated look)
+ Linear ///< Bilinear interpolation (smooth)
};
+/**
+ * @brief Texture wrapping mode
+ *
+ * @details Controls behavior when sampling outside [0,1] UV range.
+ */
enum class TextureWrap {
- Repeat,
- ClampToEdge,
- MirroredRepeat
+ Repeat, ///< Tile the texture
+ ClampToEdge, ///< Clamp to edge pixels
+ MirroredRepeat ///< Tile with mirroring
};
+// =============================================================================
+// Texture Specification
+// =============================================================================
+
+/**
+ * @brief Texture creation parameters
+ *
+ * @details Specifies all properties for texture creation including
+ * dimensions, format, filtering, and wrapping.
+ *
+ * @code
+ * TextureSpecification spec;
+ * spec.width = 256;
+ * spec.height = 256;
+ * spec.format = TextureFormat::RGBA8;
+ * spec.minFilter = TextureFilter::Nearest;
+ * auto texture = Texture::create(spec);
+ * @endcode
+ */
struct TextureSpecification {
+ /** @brief Texture width in pixels */
u32 width = 1;
+ /** @brief Texture height in pixels */
u32 height = 1;
+ /** @brief Pixel format */
TextureFormat format = TextureFormat::RGBA8;
+ /** @brief Minification filter */
TextureFilter minFilter = TextureFilter::Linear;
+ /** @brief Magnification filter */
TextureFilter magFilter = TextureFilter::Linear;
+ /** @brief Horizontal wrap mode */
TextureWrap wrapS = TextureWrap::Repeat;
+ /** @brief Vertical wrap mode */
TextureWrap wrapT = TextureWrap::Repeat;
+ /** @brief Generate mipmaps automatically */
bool generateMips = true;
};
+// =============================================================================
+// Texture Class
+// =============================================================================
+
+/**
+ * @brief 2D texture for GPU rendering
+ *
+ * @details Encapsulates an OpenGL/WebGL texture object. Supports
+ * creation from pixel data, files, or empty specifications.
+ *
+ * @code
+ * // Create from file
+ * auto texture = Texture::createFromFile("assets/player.png");
+ *
+ * // Create from pixel data
+ * std::vector<u8> pixels = {...}; // RGBA data
+ * auto texture = Texture::create(64, 64, pixels);
+ *
+ * // Bind for rendering
+ * texture->bind(0); // Bind to texture unit 0
+ * @endcode
+ */
class Texture {
public:
Texture() = default;
@@ -45,34 +132,108 @@ public:
Texture(Texture&& other) noexcept;
Texture& operator=(Texture&& other) noexcept;
- // Create from specification (empty texture)
+ // =========================================================================
+ // Creation
+ // =========================================================================
+
+ /**
+ * @brief Creates an empty texture from specification
+ * @param spec Texture parameters
+ * @return Unique pointer to the texture
+ *
+ * @details Creates a texture with uninitialized pixel data.
+ * Use setData() to upload pixels later.
+ */
static Unique<Texture> create(const TextureSpecification& spec);
- // Create from raw data
- static Unique<Texture> create(u32 width, u32 height, const void* data,
+ /**
+ * @brief Creates a texture from pixel vector
+ * @param width Texture width in pixels
+ * @param height Texture height in pixels
+ * @param pixels Pixel data (size must match width*height*channels)
+ * @param format Pixel format (default RGBA8)
+ * @return Unique pointer to the texture
+ */
+ static Unique<Texture> create(u32 width, u32 height, const std::vector<u8>& pixels,
TextureFormat format = TextureFormat::RGBA8);
- // Create from file (requires file loading implementation)
+ /**
+ * @brief Creates a texture from raw pixel pointer
+ * @param width Texture width in pixels
+ * @param height Texture height in pixels
+ * @param data Pointer to pixel data
+ * @param format Pixel format (default RGBA8)
+ * @return Unique pointer to the texture
+ */
+ static Unique<Texture> createRaw(u32 width, u32 height, const void* data,
+ TextureFormat format = TextureFormat::RGBA8);
+
+ /**
+ * @brief Creates a texture from an image file
+ * @param path Path to the image file
+ * @return Unique pointer to the texture, or nullptr on failure
+ *
+ * @note Supported formats depend on the image loading implementation.
+ */
static Unique<Texture> createFromFile(const std::string& path);
- // Bind to texture unit
+ // =========================================================================
+ // Operations
+ // =========================================================================
+
+ /**
+ * @brief Binds the texture to a texture unit
+ * @param slot Texture unit index (0-7 typical for WebGL)
+ */
void bind(u32 slot = 0) const;
+
+ /** @brief Unbinds the texture */
void unbind() const;
- // Update texture data
- void setData(const void* data, u32 size);
+ /**
+ * @brief Updates texture pixel data from vector
+ * @param pixels New pixel data
+ */
+ void setData(const std::vector<u8>& pixels);
- // Getters
+ /**
+ * @brief Updates texture pixel data from raw pointer
+ * @param data Pointer to pixel data
+ * @param sizeBytes Size of data in bytes
+ */
+ void setDataRaw(const void* data, u32 sizeBytes);
+
+ // =========================================================================
+ // Properties
+ // =========================================================================
+
+ /** @brief Gets the OpenGL texture ID */
u32 getId() const { return textureId_; }
+
+ /** @brief Gets the texture width in pixels */
u32 getWidth() const { return width_; }
+
+ /** @brief Gets the texture height in pixels */
u32 getHeight() const { return height_; }
+
+ /** @brief Gets the pixel format */
TextureFormat getFormat() const { return format_; }
+ /**
+ * @brief Compares textures by GPU ID
+ * @param other Texture to compare with
+ * @return True if same GPU texture
+ */
bool operator==(const Texture& other) const {
return textureId_ == other.textureId_;
}
private:
+ /**
+ * @brief Initializes the texture on GPU
+ * @param spec Texture parameters
+ * @return True on success
+ */
bool initialize(const TextureSpecification& spec);
u32 textureId_ = 0;