diff options
author | Kae <80987908+Novaenia@users.noreply.github.com> | 2025-02-11 08:20:00 +1100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-02-11 08:20:00 +1100 |
commit | 345865931c3c36b4c467e5366ef36611f996acb1 (patch) | |
tree | 6552c16524f3e756140d7c2a5bfde15c2faaa810 /source/game/scripting/StarScriptableThread.hpp | |
parent | 9eae03a968d0b2294d09d831a972cc3bbcae59c6 (diff) | |
parent | c6c46faf7c9f0db31f26c2745f561fea2fb96a3e (diff) |
Merge pull request #182 from Bottinator22/scriptablethreads
Scriptable threads
Diffstat (limited to 'source/game/scripting/StarScriptableThread.hpp')
-rw-r--r-- | source/game/scripting/StarScriptableThread.hpp | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/source/game/scripting/StarScriptableThread.hpp b/source/game/scripting/StarScriptableThread.hpp new file mode 100644 index 0000000..65f007e --- /dev/null +++ b/source/game/scripting/StarScriptableThread.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "StarThread.hpp" +#include "StarLuaRoot.hpp" +#include "StarLuaComponents.hpp" +#include "StarRpcThreadPromise.hpp" + +namespace Star { + +STAR_CLASS(ScriptableThread); + +// Runs a Lua in a separate thread and guards exceptions that occur in +// it. All methods are designed to not throw exceptions, but will instead log +// the error and trigger the ScriptableThread error state. +class ScriptableThread : public Thread { +public: + struct Message { + String message; + JsonArray args; + RpcThreadPromiseKeeper<Json> promise; + }; + + typedef LuaMessageHandlingComponent<LuaUpdatableComponent<LuaBaseComponent>> ScriptComponent; + typedef shared_ptr<ScriptComponent> ScriptComponentPtr; + + ScriptableThread(Json parameters); + ~ScriptableThread(); + + void start(); + // Signals the ScriptableThread to stop and then joins it + void stop(); + void setPause(bool pause); + + // An exception occurred and the + // ScriptableThread has stopped running. + bool errorOccurred(); + bool shouldExpire(); + + // + void passMessage(Message&& message); + +protected: + virtual void run(); + +private: + void update(); + Maybe<Json> receiveMessage(String const& message, JsonArray const& args); + + mutable RecursiveMutex m_mutex; + + LuaRootPtr m_luaRoot; + StringMap<ScriptComponentPtr> m_scriptContexts; + + Json m_parameters; + String m_name; + + float m_timestep; + + mutable RecursiveMutex m_messageMutex; + List<Message> m_messages; + + atomic<bool> m_stop; + atomic<bool> m_pause; + mutable atomic<bool> m_errorOccurred; + mutable atomic<bool> m_shouldExpire; + + LuaCallbacks makeThreadCallbacks(); + Json configValue(String const& name, Json def) const; +}; + +} |