]> git.tdb.fi Git - libs/game.git/commitdiff
Add a way for systems to do things at the end of a tick
authorMikko Rasa <tdb@tdb.fi>
Fri, 4 Nov 2022 22:40:55 +0000 (00:40 +0200)
committerMikko Rasa <tdb@tdb.fi>
Fri, 4 Nov 2022 22:40:55 +0000 (00:40 +0200)
Objects should not be created or destroyed mid-tick.

source/game/stage.cpp
source/game/system.cpp [new file with mode: 0644]
source/game/system.h

index 1c56c7e8a159abe3e41f32bb3b4b629eb4ffb533..83176104348538a148d667c9126fff11107e7a8b 100644 (file)
@@ -39,6 +39,8 @@ void Stage::tick(Time::TimeDelta dt)
 {
        for(const auto &s: systems)
                s->tick(dt);
+       for(const auto &s: systems)
+               s->deferred_tick();
 }
 
 } // namespace Msp::Game
diff --git a/source/game/system.cpp b/source/game/system.cpp
new file mode 100644 (file)
index 0000000..87ba3b6
--- /dev/null
@@ -0,0 +1,12 @@
+#include "system.h"
+
+namespace Msp::Game {
+
+void System::deferred_tick()
+{
+       for(const auto &f: deferred_queue)
+               f();
+       deferred_queue.clear();
+}
+
+} // namespace Msp::Game
index 9e6ec2a6e923e7ca6befd3f66ae0c67aa0119099..3b379178c1b6e27972cd60f9bfa31441bafbebe2 100644 (file)
@@ -1,6 +1,7 @@
 #ifndef MSP_GAME_SYSTEM_H_
 #define MSP_GAME_SYSTEM_H_
 
+#include <functional>
 #include <msp/time/timedelta.h>
 
 namespace Msp::Game {
@@ -11,6 +12,7 @@ class System
 {
 protected:
        Stage &stage;
+       std::vector<std::function<void()>> deferred_queue;
 
        System(Stage &s): stage(s) { }
 public:
@@ -19,6 +21,11 @@ public:
        Stage &get_stage() const { return stage; }
 
        virtual void tick(Time::TimeDelta) = 0;
+       virtual void deferred_tick();
+
+protected:
+       template<typename F>
+       void defer(F &&f) { deferred_queue.emplace_back(std::forward<F>(f)); }
 };
 
 } // namespace Msp::Game