Files
OpenRCT2-Web/src/openrct2/scripting/ScriptEngine.h
T

394 lines
14 KiB
C++
Raw Normal View History

/*****************************************************************************
2026-01-05 14:42:59 +01:00
* Copyright (c) 2014-2026 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#ifdef ENABLE_SCRIPTING
2018-07-31 17:59:48 +02:00
#include "../actions/general/CustomAction.h"
#include "../management/Finance.h"
#include "HookEngine.h"
#include "Plugin.h"
2020-02-23 12:55:48 +00:00
#include <future>
#include <memory>
#include <mutex>
#include <queue>
2025-09-29 02:05:00 +10:00
#include <quickjs.h>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace OpenRCT2::GameActions
{
class GameAction;
class Result;
} // namespace OpenRCT2::GameActions
2018-03-31 00:08:59 +01:00
class FileWatcher;
class InteractiveConsole;
namespace OpenRCT2
{
struct IPlatformEnvironment;
}
namespace OpenRCT2::Scripting
{
static constexpr int32_t kPluginApiVersion = 112;
2021-08-07 20:14:06 +03:00
// Versions marking breaking changes.
2025-01-19 16:59:45 +01:00
static constexpr int32_t kApiVersionPeepDeprecation = 33;
static constexpr int32_t kApiVersionG2Reorder = 63;
static constexpr int32_t kApiVersionCustomActionArgs = 68;
static constexpr int32_t kApiVersionNetworkIDs = 77;
2021-08-07 20:14:06 +03:00
#ifndef DISABLE_NETWORK
2025-09-29 02:05:00 +10:00
struct SocketDataBase;
#endif
2020-08-17 03:53:37 +01:00
2018-03-18 23:35:58 +00:00
class ScriptExecutionInfo
{
private:
2018-03-23 22:39:12 +00:00
std::shared_ptr<Plugin> _plugin;
2020-02-23 02:00:22 +00:00
bool _isGameStateMutable{};
2018-03-18 23:35:58 +00:00
public:
2018-03-23 23:24:36 +00:00
class PluginScope
{
private:
ScriptExecutionInfo& _execInfo;
std::shared_ptr<Plugin> _plugin;
std::shared_ptr<Plugin> _backupPlugin;
bool _backupIsGameStateMutable;
2018-03-23 23:24:36 +00:00
public:
2020-02-23 02:00:22 +00:00
PluginScope(ScriptExecutionInfo& execInfo, std::shared_ptr<Plugin> plugin, bool isGameStateMutable)
2018-07-31 17:59:48 +02:00
: _execInfo(execInfo)
, _plugin(plugin)
2018-03-23 23:24:36 +00:00
{
_backupPlugin = _execInfo._plugin;
_backupIsGameStateMutable = _execInfo._isGameStateMutable;
_execInfo._plugin = std::move(plugin);
2020-02-23 02:00:22 +00:00
_execInfo._isGameStateMutable = isGameStateMutable;
2018-03-23 23:24:36 +00:00
}
PluginScope(const PluginScope&) = delete;
~PluginScope()
{
_execInfo._plugin = _backupPlugin;
_execInfo._isGameStateMutable = _backupIsGameStateMutable;
2018-03-23 23:24:36 +00:00
}
};
2018-07-31 17:59:48 +02:00
std::shared_ptr<Plugin> GetCurrentPlugin()
{
return _plugin;
}
2020-02-23 02:00:22 +00:00
bool IsGameStateMutable()
{
return _isGameStateMutable;
}
2018-03-18 23:35:58 +00:00
};
using IntervalHandle = uint32_t;
struct ScriptInterval
{
std::shared_ptr<Plugin> Owner;
uint32_t Delay{};
int64_t LastTimestamp{};
2025-09-29 02:05:00 +10:00
JSCallback Callback;
bool Repeat{};
bool Deleted{};
};
class ScriptEngine
{
private:
InteractiveConsole& _console;
IPlatformEnvironment& _env;
2025-09-29 02:05:00 +10:00
static JSRuntime* _runtime;
JSContext* _replContext = nullptr;
2018-03-17 23:26:55 +00:00
bool _initialised{};
bool _hotReloadingInitialised{};
bool _transientPluginsEnabled{};
bool _transientPluginsStarted{};
2022-02-27 15:48:43 +00:00
bool _intransientPluginsStarted{};
std::queue<std::tuple<std::promise<void>, std::string>> _evalQueue;
2018-03-23 22:39:12 +00:00
std::vector<std::shared_ptr<Plugin>> _plugins;
2018-07-31 16:25:50 +02:00
uint32_t _lastHotReloadCheckTick{};
2018-03-18 23:35:58 +00:00
HookEngine _hookEngine;
ScriptExecutionInfo _execInfo;
2025-09-29 02:05:00 +10:00
JSValue _sharedStorage = JS_UNDEFINED;
JSValue _parkStorage = JS_UNDEFINED;
uint32_t _lastIntervalTimestamp{};
std::map<IntervalHandle, ScriptInterval> _intervals;
IntervalHandle _nextIntervalHandle = 1;
2018-03-31 00:08:59 +01:00
std::unique_ptr<FileWatcher> _pluginFileWatcher;
std::unordered_set<std::string> _changedPluginFiles;
2018-03-31 00:08:59 +01:00
std::mutex _changedPluginFilesMutex;
2020-02-11 21:26:05 +00:00
std::vector<std::function<void(std::shared_ptr<Plugin>)>> _pluginStoppedSubscriptions;
2018-03-31 00:08:59 +01:00
2025-09-29 02:05:00 +10:00
struct ExtensionCallbacks
{
std::function<void(JSContext*)> newContext;
std::function<void()> unregister;
};
std::vector<ExtensionCallbacks> _extensions;
struct CustomActionInfo
2020-03-02 23:55:18 +00:00
{
2020-03-04 00:01:17 +00:00
std::shared_ptr<Plugin> Owner;
2020-03-02 23:55:18 +00:00
std::string Name;
2025-09-29 02:05:00 +10:00
JSCallback Query;
JSCallback Execute;
2020-03-02 23:55:18 +00:00
};
std::unordered_map<std::string, CustomActionInfo> _customActions;
#ifndef DISABLE_NETWORK
2026-03-09 00:01:33 +11:00
std::vector<std::shared_ptr<SocketDataBase>> _sockets;
#endif
2020-03-02 23:55:18 +00:00
2025-09-29 02:05:00 +10:00
void InitialiseContext(JSContext* ctx) const;
public:
ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env);
2018-03-18 16:27:48 +00:00
ScriptEngine(ScriptEngine&) = delete;
2025-09-29 02:05:00 +10:00
~ScriptEngine();
2025-09-29 02:05:00 +10:00
JSContext* GetContext()
2018-07-31 17:59:48 +02:00
{
2025-09-29 02:05:00 +10:00
return _replContext;
2018-07-31 17:59:48 +02:00
}
HookEngine& GetHookEngine()
{
return _hookEngine;
}
ScriptExecutionInfo& GetExecInfo()
{
return _execInfo;
}
2025-09-29 02:05:00 +10:00
JSValue GetSharedStorage()
2020-03-06 20:17:15 +00:00
{
return _sharedStorage;
}
2025-09-29 02:05:00 +10:00
JSValue GetParkStorage()
{
return _parkStorage;
}
2020-02-22 22:18:22 +00:00
std::vector<std::shared_ptr<Plugin>>& GetPlugins()
{
return _plugins;
}
2018-03-18 23:35:58 +00:00
std::vector<std::shared_ptr<Plugin>> GetRemotePlugins()
{
std::vector<std::shared_ptr<Plugin>> res;
for (const auto& plugin : _plugins)
{
const auto& metadata = plugin->GetMetadata();
if (metadata.Type == PluginType::Remote)
{
res.push_back(plugin);
}
}
return res;
}
void ClearParkStorage();
std::string GetParkStorageAsJSON();
2025-09-29 02:05:00 +10:00
void SetParkStorageFromJSON(const std::string& value, const std::string& filename);
2022-02-27 15:48:43 +00:00
void Initialise();
2025-09-29 02:05:00 +10:00
JSContext* CreateContext() const;
void LoadTransientPlugins();
void UnloadTransientPlugins();
2022-02-27 15:48:43 +00:00
void StopUnloadRegisterAllPlugins();
2021-12-02 17:35:31 +02:00
void Tick();
2018-07-31 17:59:48 +02:00
std::future<void> Eval(const std::string& s);
2025-09-29 02:05:00 +10:00
void ExecutePluginCall(
const std::shared_ptr<Plugin>& plugin, JSValue func, const std::vector<JSValue>& args, bool isGameStateMutable,
bool keepArgsAlive = false);
JSValue ExecutePluginCall(
const std::shared_ptr<Plugin>& plugin, JSValue func, JSValue thisValue, const std::vector<JSValue>& args,
bool isGameStateMutable, bool keepArgsAlive = false, bool keepRetValueAlive = false);
2018-03-18 16:27:48 +00:00
void LogPluginInfo(std::string_view message);
2021-01-07 01:22:22 +09:00
void LogPluginInfo(const std::shared_ptr<Plugin>& plugin, std::string_view message);
2020-02-06 23:15:20 +00:00
2020-02-11 21:26:05 +00:00
void SubscribeToPluginStoppedEvent(std::function<void(std::shared_ptr<Plugin>)> callback)
{
_pluginStoppedSubscriptions.push_back(callback);
}
2025-09-29 02:05:00 +10:00
void RegisterExtension(std::function<void(JSContext*)> newContext, std::function<void()> unregister)
{
_extensions.emplace_back(newContext, unregister);
newContext(_replContext);
}
2021-01-07 01:22:22 +09:00
void AddNetworkPlugin(std::string_view code);
2022-03-21 22:56:21 +00:00
void RemoveNetworkPlugins();
2020-02-22 22:18:22 +00:00
[[nodiscard]] GameActions::Result QueryOrExecuteCustomGameAction(
const GameActions::CustomAction& action, bool isExecute);
2020-03-02 23:55:18 +00:00
bool RegisterCustomAction(
2025-09-29 02:05:00 +10:00
const std::shared_ptr<Plugin>& plugin, std::string_view action, const JSCallback& query, const JSCallback& execute);
void RunGameActionHooks(const GameActions::GameAction& action, GameActions::Result& result, bool isExecute);
2025-09-29 02:05:00 +10:00
[[nodiscard]] std::pair<std::unique_ptr<GameActions::GameAction>, bool> CreateGameAction(
JSContext* ctx, const std::string& actionid, JSValue args, const std::string& pluginName);
[[nodiscard]] JSValue GameActionResultToJS(
JSContext* ctx, const GameActions::GameAction& action, const GameActions::Result& result);
2020-03-01 21:56:49 +00:00
2020-03-06 20:17:15 +00:00
void SaveSharedStorage();
2025-09-29 02:05:00 +10:00
IntervalHandle AddInterval(
const std::shared_ptr<Plugin>& plugin, int32_t delay, bool repeat, const JSCallback& callback);
void RemoveInterval(const std::shared_ptr<Plugin>& plugin, IntervalHandle handle);
static std::string_view ExpenditureTypeToString(ExpenditureType expenditureType);
static ExpenditureType StringToExpenditureType(std::string_view expenditureType);
#ifndef DISABLE_NETWORK
2026-03-09 00:01:33 +11:00
void AddSocket(const std::shared_ptr<SocketDataBase>& data);
#endif
2020-08-17 03:53:37 +01:00
2018-03-18 16:27:48 +00:00
private:
2025-09-29 02:05:00 +10:00
static void RegisterClasses(JSContext* ctx);
static void UnregisterClasses();
static void RegisterConstants(JSContext* ctx);
2021-03-02 00:17:13 +00:00
void RefreshPlugins();
std::vector<std::string> GetPluginFiles() const;
void UnregisterPlugin(std::string_view path);
void RegisterPlugin(std::string_view path);
2022-02-27 15:48:43 +00:00
void CheckAndStartPlugins();
2021-03-02 00:17:13 +00:00
void StartIntransientPlugins();
void StartTransientPlugins();
void LoadPlugin(const std::string& path);
2020-02-22 22:18:22 +00:00
void LoadPlugin(std::shared_ptr<Plugin>& plugin);
2021-03-02 00:17:13 +00:00
void UnloadPlugin(std::shared_ptr<Plugin>& plugin);
void StartPlugin(std::shared_ptr<Plugin> plugin);
2025-09-29 02:05:00 +10:00
void StopPlugin(std::shared_ptr<Plugin> plugin, bool unregistering = false);
2022-02-20 00:23:15 +00:00
void ReloadPlugin(std::shared_ptr<Plugin> plugin);
2021-03-02 00:17:13 +00:00
static bool ShouldLoadScript(std::string_view path);
2020-02-23 02:00:22 +00:00
bool ShouldStartPlugin(const std::shared_ptr<Plugin>& plugin);
void SetupHotReloading();
void DoAutoReloadPluginCheck();
2018-03-18 17:43:47 +00:00
void AutoReloadPlugins();
2020-02-06 23:15:20 +00:00
void ProcessREPL();
2020-03-02 23:55:18 +00:00
void RemoveCustomGameActions(const std::shared_ptr<Plugin>& plugin);
2025-09-29 02:05:00 +10:00
[[nodiscard]] static GameActions::Result JSToGameActionResult(JSContext* ctx, JSValue d);
2020-03-06 20:17:15 +00:00
2020-03-07 12:37:07 +00:00
void InitSharedStorage();
2020-03-06 20:17:15 +00:00
void LoadSharedStorage();
2020-08-17 03:53:37 +01:00
IntervalHandle AllocateHandle();
void UpdateIntervals();
void RemoveIntervals(const std::shared_ptr<Plugin>& plugin);
2020-08-17 03:53:37 +01:00
void UpdateSockets();
void RemoveSockets(const std::shared_ptr<Plugin>& plugin);
};
2020-02-23 02:00:22 +00:00
bool IsGameStateMutable();
int32_t GetTargetAPIVersion();
2025-09-29 02:05:00 +10:00
std::string Stringify(JSContext* context, JSValue value);
class ScBase
{
private:
2026-03-02 00:48:18 +11:00
JSValue proto = JS_NULL;
JSContext* protoCtx = nullptr;
2025-09-29 02:05:00 +10:00
JSClassID classId = JS_INVALID_CLASS_ID;
2026-03-02 00:48:18 +11:00
bool hasFinalizer = false;
2025-09-29 02:05:00 +10:00
public:
void Unregister()
{
classId = JS_INVALID_CLASS_ID;
2026-03-02 00:48:18 +11:00
if (protoCtx != nullptr)
JS_FreeValue(protoCtx, proto);
2025-09-29 02:05:00 +10:00
}
[[nodiscard]] JSValue GetProto() const
{
return proto;
}
void RegisterDerived(JSContext* ctx, const ScBase& parent, std::span<const JSCFunctionListEntry> classFuncs)
{
proto = JS_NewObject(ctx);
protoCtx = ctx;
JS_SetPrototype(ctx, proto, parent.GetProto());
JS_SetPropertyFunctionList(ctx, proto, classFuncs.data(), static_cast<int>(classFuncs.size()));
}
2025-09-29 02:05:00 +10:00
protected:
[[nodiscard]] JSValue MakeWithOpaqueAndProto(JSContext* ctx, void* opaque, JSValue customProto) const
{
assert(opaque == nullptr || hasFinalizer);
JSValue obj = JS_NewObjectProtoClass(ctx, customProto, classId);
if (JS_IsException(obj))
throw std::runtime_error("Failed to create new object for class.");
JS_SetOpaque(obj, opaque);
return obj;
}
2026-03-02 00:48:18 +11:00
[[nodiscard]] JSValue MakeWithOpaque(JSContext* ctx, void* opaque) const
2025-09-29 02:05:00 +10:00
{
2026-03-02 00:48:18 +11:00
// If you fail this assert you probably need a finalizer to free the opaque ptr.
assert(opaque == nullptr || hasFinalizer);
// TODO: the class proto could be set once per context rather than here on every object creation.
JS_SetClassProto(ctx, classId, JS_DupValue(ctx, proto));
2025-09-29 02:05:00 +10:00
JSValue obj = JS_NewObjectClass(ctx, classId);
if (JS_IsException(obj))
throw std::runtime_error("Failed to create new object for class.");
JS_SetOpaque(obj, opaque);
return obj;
}
template<typename T>
[[nodiscard]] T GetOpaque(JSValue obj) const
{
return static_cast<T>(JS_GetOpaque(obj, classId));
}
2026-03-02 00:48:18 +11:00
void RegisterBase(
JSContext* ctx, const char* className, JSClassFinalizer* finalizer,
std::span<const JSCFunctionListEntry> classFuncs)
2025-09-29 02:05:00 +10:00
{
2026-03-02 00:48:18 +11:00
assert(classId == JS_INVALID_CLASS_ID);
2025-09-29 02:05:00 +10:00
// Note: Technically JS_NewClassID is meant to be called once during the lifetime of the program
// whereas JS_NewClass is meant to be called for each runtime.
// If we ever have any more runtimes, this flow would be wrong.
// More runtimes would also require refactoring the way values are passed to the JS code when
// calling callbacks.
JSRuntime* rt = JS_GetRuntime(ctx);
JS_NewClassID(rt, &classId);
2026-03-02 00:48:18 +11:00
JSClassDef classDef = { className, finalizer, nullptr, nullptr, nullptr };
2025-09-29 02:05:00 +10:00
JS_NewClass(rt, classId, &classDef);
2026-03-02 00:48:18 +11:00
proto = JS_NewObject(ctx);
protoCtx = ctx;
JS_SetPropertyFunctionList(ctx, proto, classFuncs.data(), static_cast<int>(classFuncs.size()));
2025-09-29 02:05:00 +10:00
2026-03-02 00:48:18 +11:00
hasFinalizer = finalizer != nullptr;
2025-09-29 02:05:00 +10:00
}
};
2020-02-23 02:00:22 +00:00
2018-07-31 17:59:48 +02:00
} // namespace OpenRCT2::Scripting
2020-02-23 12:55:48 +00:00
#endif