From 085777706e0862cd6655377643b03dbe9c81b53b Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Thu, 10 Oct 2024 23:05:38 -0400 Subject: [PATCH] A few more little features like facts and the ability to store a system for later running. --- scratchpad/myecstest.cpp | 57 ++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/scratchpad/myecstest.cpp b/scratchpad/myecstest.cpp index 395678f..6a0701a 100644 --- a/scratchpad/myecstest.cpp +++ b/scratchpad/myecstest.cpp @@ -7,15 +7,6 @@ #include using namespace fmt; - -struct Position { - double x, y; -}; - -struct Velocity { - double x, y; -}; - typedef unsigned long Entity; typedef std::unordered_map EntityMap; @@ -23,6 +14,7 @@ typedef std::unordered_map EntityMap; struct World { unsigned long entity_count = 0; std::unordered_map $components; + std::unordered_map $facts; Entity entity() { return ++entity_count; @@ -33,6 +25,18 @@ struct World { return $components[std::type_index(typeid(Comp))]; } + template + void set(Comp val) { + $facts[std::type_index(typeid(Comp))] = val; + } + + template + Comp &get() { + // use .at to get std::out_of_range if fact not set + std::any &res = $facts.at(std::type_index(typeid(Comp))); + return std::any_cast(res); + } + template void assign(Entity ent, Comp val) { EntityMap &map = entity_map_for(); @@ -42,7 +46,8 @@ struct World { template Comp &component(Entity ent) { EntityMap &map = entity_map_for(); - std::any &res = map[ent]; + // use .at for bounds checking + std::any &res = map.at(ent); return std::any_cast(res); } @@ -74,6 +79,25 @@ struct World { } } } + + template + std::function runner(std::function cb) { + return [&]{ + system(cb); + }; + } +}; + +struct Position { + double x, y; +}; + +struct Velocity { + double x, y; +}; + +struct Gravity { + double level; }; int main() { @@ -110,9 +134,13 @@ int main() { println("entity={}, vel.x, vel.y, pos.x={}, pos.y={}", ent, vel.x, vel.y, pos.x, pos.y); }); + println("--- Creating facts (singletons)"); + me.set({0.9}); + println("--- Query only entities with Position and Velocity:"); me.system([&](const auto &ent, auto &pos, auto &vel) { - println("entity={}, vel.x, vel.y, pos.x={}, pos.y={}", ent, vel.x, vel.y, pos.x, pos.y); + Gravity &grav = me.get(); + println("grav={}, entity={}, vel.x, vel.y, pos.x={}, pos.y={}", grav.level, ent, vel.x, vel.y, pos.x, pos.y); }); // now remove Velocity @@ -123,5 +151,12 @@ int main() { println("entity={}, vel.x, vel.y, pos.x={}, pos.y={}", ent, vel.x, vel.y, pos.x, pos.y); }); + println("--- Create a stored system you can save for later."); + auto movementSystem = me.runner([&](const auto &ent, auto &pos, auto &vel) { + println("entity={}, vel.x, vel.y, pos.x={}, pos.y={}", ent, vel.x, vel.y, pos.x, pos.y); + }); + + movementSystem(); + return 0; }