Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit 11e09b08d13299d90bc0fb98d99e7f78b02b7961
parent 7d8d486e594a98b57a490373258d429d9fdc1e1b
Author: sentomk <sentomk@proton.me>
Date:   Tue, 24 Nov 2026 21:42:37 +0800

feat: add ECS World and migrate demo to ECS

Diffstat:
Asrc/ecs/world.h | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/main.cpp | 146++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Atests/unit/world_test.cpp | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 546 insertions(+), 45 deletions(-)

diff --git a/src/ecs/world.h b/src/ecs/world.h @@ -0,0 +1,266 @@ +/// @file ecs/world.h +/// @brief Entity registry and per-component SparseSet storage without RTTI. +#pragma once + +#include <cassert> +#include <memory> +#include <tuple> +#include <type_traits> +#include <utility> +#include <vector> + +#include "core/types.h" +#include "ecs/entity.h" +#include "ecs/sparse_set.h" + +namespace kumo { + +using ComponentId = uint32_t; + +namespace detail { + +inline ComponentId next_component_id() { + static ComponentId next = 0; + return next++; +} + +template <typename T> +ComponentId raw_component_id() { + static const ComponentId id = next_component_id(); + return id; +} + +} // namespace detail + +/// @brief Returns a unique, dense integer ID for component type @p T. +/// +/// Strips cv-qualifiers so `const T` and `T` share the same pool without RTTI. +template <typename T> +ComponentId component_id() { + return detail::raw_component_id<std::remove_cv_t<T>>(); +} + +/// @brief Owns all entities and component pools for one simulation world. +class World { + public: + World() = default; + World(const World&) = delete; + World& operator=(const World&) = delete; + World(World&&) = default; + World& operator=(World&&) = default; + + /// @brief Allocates a new live entity, recycling freed slots when available. + Entity create() { + if (!free_indices_.empty()) { + const uint32_t idx = free_indices_.back(); + free_indices_.pop_back(); + alive_[idx] = 1; + ++alive_count_; + return Entity::make(idx, generations_[idx]); + } + + const uint32_t idx = static_cast<uint32_t>(generations_.size()); + assert(idx <= Entity::kMaxIndex); + generations_.push_back(1); + alive_.push_back(1); + ++alive_count_; + return Entity::make(idx, 1); + } + + /// @brief Returns whether @p entity is currently alive in this world. + bool alive(Entity entity) const { + if (!entity.valid()) return false; + const uint32_t idx = entity.index(); + return idx < generations_.size() && alive_[idx] != 0 && + generations_[idx] == entity.generation(); + } + + /// @brief Immediately destroys @p entity and removes all of its components. + /// + /// Do not call while iterating a pool that contains @p entity; use + /// destroy_deferred() and flush_destroyed() instead. + /// @return `true` if @p entity was alive and has been destroyed. + bool destroy(Entity entity) { + if (!alive(entity)) return false; + for (const std::unique_ptr<PoolBase>& pool : pools_) { + if (pool != nullptr) pool->remove(entity); + } + const uint32_t idx = entity.index(); + alive_[idx] = 0; + generations_[idx] = next_generation(generations_[idx]); + free_indices_.push_back(idx); + --alive_count_; + return true; + } + + /// @brief Marks @p entity to be destroyed when flush_destroyed() is called. + void destroy_deferred(Entity entity) { + if (alive(entity)) pending_destroy_.push_back(entity); + } + + /// @brief Destroys all entities queued by destroy_deferred(). + void flush_destroyed() { + for (const Entity entity : pending_destroy_) { + destroy(entity); + } + pending_destroy_.clear(); + } + + /// @brief Removes all entities and components from the world. + void clear() { + for (const std::unique_ptr<PoolBase>& pool : pools_) { + if (pool != nullptr) pool->clear(); + } + generations_.clear(); + alive_.clear(); + free_indices_.clear(); + pending_destroy_.clear(); + alive_count_ = 0; + } + + size_t alive_count() const { return alive_count_; } + + /// @brief Adds or replaces component @p T on a live @p entity. + template <typename T, typename... Args> + T& emplace(Entity entity, Args&&... args) { + assert(alive(entity)); + return get_or_create_pool<T>().emplace(entity, std::forward<Args>(args)...); + } + + /// @brief Removes component @p T from @p entity if present. + template <typename T> + bool remove(Entity entity) { + auto* pool = find_pool<T>(); + return pool != nullptr && pool->remove(entity); + } + + template <typename T> + bool has(Entity entity) const { + const auto* pool = find_pool<T>(); + return pool != nullptr && pool->has(entity); + } + + template <typename T> + T& get(Entity entity) { + auto* pool = find_pool<T>(); + assert(pool != nullptr); + return pool->get(entity); + } + + template <typename T> + const T& get(Entity entity) const { + const auto* pool = find_pool<T>(); + assert(pool != nullptr); + return pool->get(entity); + } + + template <typename T> + T* try_get(Entity entity) { + auto* pool = find_pool<T>(); + return pool != nullptr ? pool->try_get(entity) : nullptr; + } + template <typename T> + const T* try_get(Entity entity) const { + const auto* pool = find_pool<T>(); + return pool != nullptr ? pool->try_get(entity) : nullptr; + } + /// @brief Number of live entities that currently have component @p T. + template <typename T> + size_t count() const { + const auto* pool = find_pool<T>(); + return pool != nullptr ? pool->size() : 0; + } + /// @brief Invokes `fn(Entity, Ts&...)` for every entity having all of @p Ts. + /// + /// Drives iteration from the smallest component pool among @p Ts. + template <typename... Ts, typename Fn> + void each(Fn&& fn) { + static_assert(sizeof...(Ts) > 0, + "World::each requires at least one component type"); + auto pools = std::make_tuple(find_pool<Ts>()...); + const PoolBase* smallest = smallest_pool(pools); + if (smallest == nullptr) return; + for (const Entity entity : smallest->entities()) { + const bool has_all = std::apply( + [entity](auto*... p) { return (p->has(entity) && ...); }, pools); + if (has_all) { + std::apply([&](auto*... p) { fn(entity, p->get(entity)...); }, pools); + } + } + } + /// @brief Const overload: invokes `fn(Entity, const Ts&...)`. + template <typename... Ts, typename Fn> + void each(Fn&& fn) const { + static_assert(sizeof...(Ts) > 0, + "World::each requires at least one component type"); + auto pools = std::make_tuple(find_pool<Ts>()...); + const PoolBase* smallest = smallest_pool(pools); + if (smallest == nullptr) return; + for (const Entity entity : smallest->entities()) { + const bool has_all = std::apply( + [entity](const auto*... p) { return (p->has(entity) && ...); }, + pools); + if (has_all) { + std::apply([&](const auto*... p) { fn(entity, p->get(entity)...); }, + pools); + } + } + } + + private: + template <typename T> + using PoolType = SparseSet<std::remove_cv_t<T>>; + + template <typename T> + PoolType<T>& get_or_create_pool() { + const ComponentId id = component_id<T>(); + if (id >= pools_.size()) { + pools_.resize(static_cast<size_t>(id) + 1); + } + if (pools_[id] == nullptr) { + pools_[id] = std::make_unique<PoolType<T>>(); + } + return *static_cast<PoolType<T>*>(pools_[id].get()); + } + + template <typename T> + PoolType<T>* find_pool() { + const ComponentId id = component_id<T>(); + if (id >= pools_.size() || pools_[id] == nullptr) return nullptr; + return static_cast<PoolType<T>*>(pools_[id].get()); + } + + template <typename T> + const PoolType<T>* find_pool() const { + const ComponentId id = component_id<T>(); + if (id >= pools_.size() || pools_[id] == nullptr) return nullptr; + return static_cast<const PoolType<T>*>(pools_[id].get()); + } + + template <typename... PoolPtrs> + static const PoolBase* smallest_pool(const std::tuple<PoolPtrs...>& pools) { + const PoolBase* best = nullptr; + bool empty = false; + std::apply( + [&](auto*... p) { + for (const PoolBase* cur : {static_cast<const PoolBase*>(p)...}) { + if (cur == nullptr || cur->size() == 0) { + empty = true; + return; + } + if (best == nullptr || cur->size() < best->size()) best = cur; + } + }, + pools); + return empty ? nullptr : best; + } + + std::vector<uint32_t> generations_; + std::vector<uint8_t> alive_; + std::vector<uint32_t> free_indices_; + std::vector<Entity> pending_destroy_; + std::vector<std::unique_ptr<PoolBase>> pools_; + size_t alive_count_ = 0; +}; + +} // namespace kumo diff --git a/src/main.cpp b/src/main.cpp @@ -2,12 +2,13 @@ #include <cstdio> #include <cstdlib> #include <ptn/patternia.hpp> -#include <vector> #include "core/clock.h" #include "core/fixed.h" #include "core/types.h" #include "core/vec2.h" +#include "ecs/entity.h" +#include "ecs/world.h" #include "platform/keyboard.h" #include "platform/window.h" #include "render/frame_buffer.h" @@ -25,13 +26,27 @@ constexpr int kBoxLifetimeTicks = 180; constexpr size_t kMaxSpawnedBoxes = 32; constexpr auto kPlayerSpeed = kumo::Fixed::from_int(2); // Pixels per tick. -struct BouncingBox { +struct Transform { kumo::Vec2 position; kumo::Vec2 previous; - kumo::Vec2 velocity; +}; + +struct Velocity { + kumo::Vec2 value; +}; + +struct BoxSprite { + int size; + kumo::Color color; +}; + +struct Lifetime { int ticks_left; }; +struct PlayerTag {}; +struct BounceTag {}; + /// @brief Advances one axis and reflects any overshoot at either boundary. void advance_axis(kumo::Fixed& position, kumo::Fixed& velocity, kumo::Fixed limit) { @@ -51,72 +66,113 @@ void advance_axis(kumo::Fixed& position, kumo::Fixed& velocity, $ >> [](kumo::Fixed next) { return next; }); } -void draw_box(kumo::FrameBuffer& frame, kumo::Vec2 previous, - kumo::Vec2 position, kumo::Fixed alpha, int size, - kumo::Color color) { - const kumo::Vec2 drawn = kumo::lerp(previous, position, alpha); - kumo::fill_rect(frame, drawn.x.round(), drawn.y.round(), size, size, color); +void save_previous_transforms(kumo::World& world) { + world.each<Transform>( + [](kumo::Entity /*e*/, Transform& t) { t.previous = t.position; }); +} + +void player_input_system(kumo::World& world, const kumo::Keyboard& keyboard) { + using kumo::Fixed; + using kumo::Key; + + const int dx = keyboard.is_down(Key::Right) - keyboard.is_down(Key::Left); + const int dy = keyboard.is_down(Key::Down) - keyboard.is_down(Key::Up); + + world.each<PlayerTag, Transform, BoxSprite>( + [dx, dy](kumo::Entity /*e*/, PlayerTag&, Transform& t, + const BoxSprite& sprite) { + t.position.x = + std::clamp(t.position.x + kPlayerSpeed * Fixed::from_int(dx), + Fixed{}, Fixed::from_int(kScreenWidth - sprite.size)); + t.position.y = + std::clamp(t.position.y + kPlayerSpeed * Fixed::from_int(dy), + Fixed{}, Fixed::from_int(kScreenHeight - sprite.size)); + }); } -/// @brief Exercises keyboard input, fixed updates and interpolation. +void bounce_movement_system(kumo::World& world) { + using kumo::Fixed; + + world.each<BounceTag, Transform, Velocity, BoxSprite>( + [](kumo::Entity /*e*/, BounceTag&, Transform& t, Velocity& v, + const BoxSprite& sprite) { + advance_axis(t.position.x, v.value.x, + Fixed::from_int(kScreenWidth - sprite.size)); + advance_axis(t.position.y, v.value.y, + Fixed::from_int(kScreenHeight - sprite.size)); + }); +} + +void lifetime_system(kumo::World& world) { + world.each<Lifetime>([&world](kumo::Entity e, Lifetime& life) { + --life.ticks_left; + if (life.ticks_left <= 0) world.destroy_deferred(e); + }); + world.flush_destroyed(); +} + +void draw_sprite(kumo::FrameBuffer& frame, const Transform& t, + const BoxSprite& sprite, kumo::Fixed alpha) { + const kumo::Vec2 drawn = kumo::lerp(t.previous, t.position, alpha); + kumo::fill_rect(frame, drawn.x.round(), drawn.y.round(), sprite.size, + sprite.size, sprite.color); +} + +/// @brief Exercises ECS, keyboard input, fixed updates and interpolation. class DemoGame final : public kumo::Game { public: - explicit DemoGame(kumo::Keyboard& keyboard) : keyboard_(keyboard) {} + explicit DemoGame(kumo::Keyboard& keyboard) : keyboard_(keyboard) { + player_ = world_.create(); + const kumo::Vec2 start = kumo::Vec2::from_ints(40, 40); + world_.emplace<PlayerTag>(player_); + world_.emplace<Transform>(player_, start, start); + world_.emplace<BoxSprite>(player_, kPlayerSize, + kumo::make_color(250, 210, 70)); + } void fixed_update(const kumo::Tick& /*tick*/) override { using kumo::Fixed; using kumo::Key; - previous_ = position_; - const int dx = keyboard_.is_down(Key::Right) - keyboard_.is_down(Key::Left); - const int dy = keyboard_.is_down(Key::Down) - keyboard_.is_down(Key::Up); - position_.x = - std::clamp(position_.x + kPlayerSpeed * Fixed::from_int(dx), Fixed{}, - Fixed::from_int(kScreenWidth - kPlayerSize)); - position_.y = - std::clamp(position_.y + kPlayerSpeed * Fixed::from_int(dy), Fixed{}, - Fixed::from_int(kScreenHeight - kPlayerSize)); - - for (BouncingBox& box : boxes_) { - box.previous = box.position; - advance_axis(box.position.x, box.velocity.x, - Fixed::from_int(kScreenWidth - kSpawnedBoxSize)); - advance_axis(box.position.y, box.velocity.y, - Fixed::from_int(kScreenHeight - kSpawnedBoxSize)); - --box.ticks_left; - } - std::erase_if(boxes_, - [](const BouncingBox& box) { return box.ticks_left == 0; }); + save_previous_transforms(world_); + player_input_system(world_, keyboard_); + bounce_movement_system(world_); + lifetime_system(world_); // Consume press edges here so a frame with several ticks spawns each once. constexpr auto offset = Fixed::from_int((kPlayerSize - kSpawnedBoxSize) / 2); - const kumo::Vec2 origin{position_.x + offset, position_.y + offset}; + const kumo::Vec2 player_pos = world_.get<Transform>(player_).position; + const kumo::Vec2 origin{player_pos.x + offset, player_pos.y + offset}; for (uint32_t presses = keyboard_.take_presses(Key::Space); - presses > 0 && boxes_.size() < kMaxSpawnedBoxes; --presses) { - boxes_.push_back({origin, - origin, - {Fixed::ratio(5, 2), Fixed::ratio(7, 4)}, - kBoxLifetimeTicks}); + presses > 0 && world_.count<BounceTag>() < kMaxSpawnedBoxes; + --presses) { + const kumo::Entity box = world_.create(); + world_.emplace<BounceTag>(box); + world_.emplace<Transform>(box, origin, origin); + world_.emplace<Velocity>( + box, kumo::Vec2{Fixed::ratio(5, 2), Fixed::ratio(7, 4)}); + world_.emplace<BoxSprite>(box, kSpawnedBoxSize, + kumo::make_color(100, 195, 250)); + world_.emplace<Lifetime>(box, kBoxLifetimeTicks); } } void render(kumo::FrameBuffer& frame, kumo::Fixed alpha) const override { kumo::clear(frame, kumo::make_color(24, 28, 40)); - draw_box(frame, previous_, position_, alpha, kPlayerSize, - kumo::make_color(250, 210, 70)); - for (const BouncingBox& box : boxes_) { - draw_box(frame, box.previous, box.position, alpha, kSpawnedBoxSize, - kumo::make_color(100, 195, 250)); - } + world_.each<PlayerTag, Transform, BoxSprite>( + [&](kumo::Entity /*e*/, const PlayerTag&, const Transform& t, + const BoxSprite& sprite) { draw_sprite(frame, t, sprite, alpha); }); + world_.each<BounceTag, Transform, BoxSprite>( + [&](kumo::Entity /*e*/, const BounceTag&, const Transform& t, + const BoxSprite& sprite) { draw_sprite(frame, t, sprite, alpha); }); } private: kumo::Keyboard& keyboard_; - kumo::Vec2 position_ = kumo::Vec2::from_ints(40, 40); - kumo::Vec2 previous_ = position_; - std::vector<BouncingBox> boxes_; + kumo::World world_; + kumo::Entity player_; }; } // namespace diff --git a/tests/unit/world_test.cpp b/tests/unit/world_test.cpp @@ -0,0 +1,179 @@ +#include "ecs/world.h" + +#include "check.h" +#include "core/types.h" +#include "ecs/entity.h" + +using kumo::Entity; +using kumo::World; + +namespace { + +struct Position { + int x = 0; + int y = 0; +}; + +struct Velocity { + int vx = 0; + int vy = 0; +}; + +struct Health { + int hp = 0; +}; + +struct PlayerTag {}; + +} // namespace + +TEST(world_create_destroy_and_recycle_with_generations) { + World world; + CHECK_EQ(world.alive_count(), 0u); + CHECK(!world.alive(Entity::null())); + + const Entity a = world.create(); + const Entity b = world.create(); + CHECK(world.alive(a)); + CHECK(world.alive(b)); + CHECK_EQ(world.alive_count(), 2u); + CHECK_EQ(a.index(), 0u); + CHECK_EQ(a.generation(), 1u); + CHECK_EQ(b.index(), 1u); + + CHECK(world.destroy(a)); + CHECK(!world.destroy(a)); + CHECK(!world.alive(a)); + CHECK(world.alive(b)); + CHECK_EQ(world.alive_count(), 1u); + + // Next create reuses slot 0 with generation 2; old handle `a` stays dead. + const Entity c = world.create(); + CHECK_EQ(c.index(), a.index()); + CHECK_EQ(c.generation(), 2u); + CHECK(world.alive(c)); + CHECK(!world.alive(a)); + CHECK_EQ(world.alive_count(), 2u); +} + +TEST(world_emplace_get_has_remove_and_const_access) { + World world; + const Entity e = world.create(); + + CHECK_EQ(kumo::component_id<Position>(), + kumo::component_id<const Position>()); + CHECK(!world.has<Position>(e)); + CHECK(world.try_get<Position>(e) == nullptr); + CHECK_EQ(world.count<Position>(), 0u); + + Position& pos = world.emplace<Position>(e, 10, 20); + CHECK_EQ(pos.x, 10); + CHECK_EQ(pos.y, 20); + CHECK(world.has<Position>(e)); + CHECK_EQ(world.count<Position>(), 1u); + + const World& const_world = world; + CHECK(const_world.has<Position>(e)); + CHECK_EQ(const_world.get<Position>(e).x, 10); + CHECK(const_world.try_get<Position>(e) != nullptr); + CHECK(const_world.try_get<Velocity>(e) == nullptr); + + CHECK(world.remove<Position>(e)); + CHECK(!world.remove<Position>(e)); + CHECK(!world.has<Position>(e)); + CHECK_EQ(world.count<Position>(), 0u); +} + +TEST(world_destroy_removes_all_components) { + World world; + const Entity e = world.create(); + world.emplace<Position>(e, 3, 4); + world.emplace<Velocity>(e, 1, -1); + world.emplace<PlayerTag>(e); + + CHECK(world.destroy(e)); + CHECK(!world.has<Position>(e)); + CHECK(!world.has<Velocity>(e)); + CHECK(!world.has<PlayerTag>(e)); + CHECK_EQ(world.count<Position>(), 0u); + CHECK_EQ(world.count<Velocity>(), 0u); + CHECK_EQ(world.count<PlayerTag>(), 0u); +} + +TEST(world_each_visits_only_matching_entities) { + World world; + const Entity movable = world.create(); + world.emplace<Position>(movable, 1, 2); + world.emplace<Velocity>(movable, 3, 4); + + const Entity static_box = world.create(); + world.emplace<Position>(static_box, 10, 20); + + const Entity ghost = world.create(); + world.emplace<Velocity>(ghost, 5, 6); + + int visited = 0; + world.each<Position, Velocity>([&](Entity e, Position& p, Velocity& v) { + CHECK_EQ(e, movable); + p.x += v.vx; + p.y += v.vy; + ++visited; + }); + CHECK_EQ(visited, 1); + CHECK_EQ(world.get<Position>(movable).x, 4); + CHECK_EQ(world.get<Position>(movable).y, 6); + + // Const world iteration and missing-pool queries work cleanly. + const World& const_world = world; + int sum_x = 0; + const_world.each<Position>( + [&](Entity /*e*/, const Position& p) { sum_x += p.x; }); + CHECK_EQ(sum_x, 14); + + int health_visited = 0; + const_world.each<Position, Health>( + [&](Entity /*e*/, const Position&, const Health&) { ++health_visited; }); + CHECK_EQ(health_visited, 0); +} + +TEST(world_destroy_deferred_is_safe_during_each) { + World world; + const Entity a = world.create(); + const Entity b = world.create(); + const Entity c = world.create(); + world.emplace<Health>(a, 0); + world.emplace<Health>(b, 5); + world.emplace<Health>(c, 0); + + world.each<Health>([&](Entity e, Health& h) { + if (h.hp <= 0) { + world.destroy_deferred(e); + world.destroy_deferred(e); // duplicate queue must be harmless + } + }); + + // Entities remain alive until flush_destroyed() runs. + CHECK_EQ(world.alive_count(), 3u); + world.flush_destroyed(); + + CHECK_EQ(world.alive_count(), 1u); + CHECK(!world.alive(a)); + CHECK(world.alive(b)); + CHECK(!world.alive(c)); + CHECK_EQ(world.count<Health>(), 1u); +} + +TEST(world_clear_resets_entities_and_components) { + World world; + const Entity e = world.create(); + world.emplace<Position>(e, 7, 8); + + world.clear(); + CHECK_EQ(world.alive_count(), 0u); + CHECK_EQ(world.count<Position>(), 0u); + CHECK(!world.alive(e)); + + const Entity fresh = world.create(); + CHECK(world.alive(fresh)); + CHECK_EQ(world.alive_count(), 1u); +}