From 0c718869419687c8816de2bf8bef7f4f5e578792 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 6 Mar 2020 20:17:15 +0000 Subject: [PATCH] Implement shared storage --- distribution/openrct2.d.ts | 2 +- src/openrct2/scripting/ScConfiguration.hpp | 258 +++++++++++++++++++++ src/openrct2/scripting/ScContext.hpp | 14 ++ src/openrct2/scripting/ScriptEngine.cpp | 39 +++- src/openrct2/scripting/ScriptEngine.h | 9 + src/thirdparty/dukglue/dukvalue.h | 4 +- 6 files changed, 322 insertions(+), 4 deletions(-) create mode 100644 src/openrct2/scripting/ScConfiguration.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 9c8c2014bc..13b4cf10cc 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -33,7 +33,7 @@ declare global { } interface Configuration { - getAll(pattern: string): { [name: string]: any }; + getAll(namespace: string): { [name: string]: any }; get(key: string): T | undefined; get(key: string, defaultValue: T): T; set(key: string, value: T): void; diff --git a/src/openrct2/scripting/ScConfiguration.hpp b/src/openrct2/scripting/ScConfiguration.hpp new file mode 100644 index 0000000000..f621fcb600 --- /dev/null +++ b/src/openrct2/scripting/ScConfiguration.hpp @@ -0,0 +1,258 @@ +/***************************************************************************** + * Copyright (c) 2020 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__ + +# include "../Context.h" +# include "../config/Config.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" + +namespace OpenRCT2::Scripting +{ + class ScConfiguration + { + private: + bool _isUserConfig{}; + DukValue _backingObject; + + public: + ScConfiguration() + : _isUserConfig(true) + { + } + + ScConfiguration(const DukValue& backingObject) + : _backingObject(backingObject) + { + } + + static void Register(duk_context* ctx) + { + dukglue_register_method(ctx, &ScConfiguration::getAll, "getAll"); + dukglue_register_method(ctx, &ScConfiguration::get, "get"); + dukglue_register_method(ctx, &ScConfiguration::set, "set"); + dukglue_register_method(ctx, &ScConfiguration::has, "has"); + } + + private: + std::pair GetNextNamespace(const std::string_view& input) + { + auto pos = input.find('.'); + if (pos == std::string_view::npos) + { + return std::make_pair(input, std::string_view()); + } + else + { + return std::make_pair(input.substr(0, pos), input.substr(pos + 1)); + } + } + + std::pair GetNamespaceAndKey(const std::string_view& input) + { + auto pos = input.find_last_of('.'); + return pos == std::string_view::npos ? std::make_pair(std::string_view(), input) + : std::make_pair(input.substr(0, pos), input.substr(pos + 1)); + } + + std::optional GetNamespaceObject(const std::string_view& ns) + { + auto store = _backingObject; + auto k = ns; + bool end; + do + { + auto [next, remainder] = GetNextNamespace(k); + store = store[next]; + k = remainder; + end = store.type() == DukValue::Type::UNDEFINED || remainder.empty(); + } while (!end); + return store.type() == DukValue::OBJECT ? std::make_optional(store) : std::nullopt; + } + + DukValue GetOrCreateNamespaceObject(duk_context* ctx, const std::string_view& ns) + { + auto store = _backingObject; + if (!ns.empty()) + { + std::string_view k = ns; + bool end; + do + { + auto [next, remainder] = GetNextNamespace(k); + auto subStore = store[next]; + k = remainder; + if (subStore.type() == DukValue::Type::UNDEFINED) + { + store.push(); + duk_push_object(ctx); + store = DukValue::copy_from_stack(ctx); + duk_put_prop_lstring(ctx, -2, next.data(), next.size()); + duk_pop(ctx); + } + else + { + store = subStore; + } + end = remainder.empty(); + } while (!end); + } + return store; + } + + bool IsValidNamespace(const std::string_view& ns) + { + if (ns.empty() || ns[0] == '.' || ns[ns.size() - 1] == '.') + { + return false; + } + for (size_t i = 1; i < ns.size() - 1; i++) + { + if (ns[i - 1] == '.' && ns[i] == '.') + { + return false; + } + } + return true; + } + + bool IsValidKey(const std::string_view& key) + { + return !key.empty() && key.find('.') == std::string_view::npos; + } + + DukValue getAll(const std::string& ns) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + if (IsValidNamespace(ns)) + { + if (_isUserConfig) + { + DukObject obj(ctx); + if (ns == "general") + { + obj.Set("general.showFps", gConfigGeneral.show_fps); + } + return obj.Take(); + } + else + { + auto obj = GetNamespaceObject(ns); + return obj ? *obj : DukObject(ctx).Take(); + } + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Namespace was invalid."); + } + } + + DukValue get(const std::string& key, const DukValue& defaultValue) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + if (_isUserConfig) + { + if (key == "general.showFps") + { + duk_push_boolean(ctx, gConfigGeneral.show_fps); + return DukValue::take_from_stack(ctx); + } + } + else + { + auto [ns, n] = GetNamespaceAndKey(key); + if (!IsValidNamespace(ns)) + { + duk_error(ctx, DUK_ERR_ERROR, "Namespace was invalid."); + } + else if (!IsValidKey(n)) + { + duk_error(ctx, DUK_ERR_ERROR, "Key was invalid."); + } + else + { + auto obj = GetNamespaceObject(ns); + if (obj) + { + auto val = (*obj)[n]; + if (val.type() != DukValue::Type::UNDEFINED) + { + return val; + } + } + } + } + return defaultValue; + } + + void set(const std::string& key, const DukValue& value) + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto ctx = scriptEngine.GetContext(); + if (_isUserConfig) + { + try + { + if (key == "general.showFps") + { + gConfigGeneral.show_fps = value.as_bool(); + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Property does not exist."); + } + } + catch (const DukException&) + { + duk_error(ctx, DUK_ERR_ERROR, "Invalid value for this property."); + } + } + else + { + auto [ns, n] = GetNamespaceAndKey(key); + if (!IsValidNamespace(ns)) + { + duk_error(ctx, DUK_ERR_ERROR, "Namespace was invalid."); + } + else if (!IsValidKey(n)) + { + duk_error(ctx, DUK_ERR_ERROR, "Key was invalid."); + } + else + { + auto obj = GetOrCreateNamespaceObject(ctx, ns); + obj.push(); + if (value.type() == DukValue::Type::UNDEFINED) + { + duk_del_prop_string(ctx, -1, key.c_str()); + } + else + { + value.push(); + duk_put_prop_lstring(ctx, -2, n.data(), n.size()); + } + duk_pop(ctx); + + scriptEngine.SaveSharedStorage(); + } + } + } + + bool has(const std::string& key) + { + auto val = get(key, DukValue()); + return val.type() != DukValue::Type::UNDEFINED; + } + }; +} // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 4e2c43cd3e..c32e9df045 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -17,6 +17,7 @@ # include "../scenario/Scenario.h" # include "Duktape.hpp" # include "HookEngine.h" +# include "ScConfiguration.hpp" # include "ScDisposable.hpp" # include "ScriptEngine.h" @@ -39,6 +40,17 @@ namespace OpenRCT2::Scripting } private: + std::shared_ptr configuration_get() + { + return std::make_shared(); + } + + std::shared_ptr sharedStorage_get() + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + return std::make_shared(scriptEngine.GetSharedStorage()); + } + void registerIntent(const DukValue& desc) { } @@ -216,6 +228,8 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { + dukglue_register_property(ctx, &ScContext::configuration_get, nullptr, "configuration"); + dukglue_register_property(ctx, &ScContext::sharedStorage_get, nullptr, "sharedStorage"); dukglue_register_method(ctx, &ScContext::getRandom, "getRandom"); dukglue_register_method(ctx, &ScContext::registerIntent, "registerIntent"); dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 2a2c09046f..dbfa8fdd45 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -15,6 +15,7 @@ # include "../actions/GameAction.h" # include "../actions/RideCreateAction.hpp" # include "../config/Config.h" +# include "../core/File.h" # include "../core/FileScanner.h" # include "../core/Path.hpp" # include "../interface/InteractiveConsole.h" @@ -365,6 +366,7 @@ ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& en void ScriptEngine::Initialise() { auto ctx = (duk_context*)_context; + ScConfiguration::Register(ctx); ScConsole::Register(ctx); ScContext::Register(ctx); ScDate::Register(ctx); @@ -391,6 +393,10 @@ void ScriptEngine::Initialise() _initialised = true; _pluginsLoaded = false; _pluginsStarted = false; + + duk_push_object(ctx); + _sharedStorage = std::move(DukValue::take_from_stack(ctx)); + LoadSharedStorage(); } void ScriptEngine::LoadPlugins() @@ -820,7 +826,6 @@ void ScriptEngine::RemoveCustomGameActions(const std::shared_ptr& plugin } } -# pragma warning(disable : 4189) void ScriptEngine::RunGameActionHooks(const GameAction& action, std::unique_ptr& result, bool isExecute) { DukStackFrame frame(_context); @@ -859,6 +864,38 @@ void ScriptEngine::RunGameActionHooks(const GameAction& action, std::unique_ptr< } } +void ScriptEngine::LoadSharedStorage() +{ + std::string path = "C:\\Users\\Ted\\Documents\\OpenRCT2\\plugin.json"; + try + { + auto data = File::ReadAllBytes(path); + duk_push_lstring(_context, (const char*)data.data(), data.size()); + duk_json_decode(_context, -1); + _sharedStorage = std::move(DukValue::take_from_stack(_context)); + } + catch (const std::exception&) + { + } +} + +void ScriptEngine::SaveSharedStorage() +{ + _sharedStorage.push(); + auto json = std::string(duk_json_encode(_context, -1)); + duk_pop(_context); + + std::string path = "C:\\Users\\Ted\\Documents\\OpenRCT2\\plugin.json"; + try + { + File::WriteAllBytes(path, json.c_str(), json.size()); + } + catch (const std::exception&) + { + fprintf(stderr, "Unable to write to '%s'\n", path.c_str()); + } +} + std::string OpenRCT2::Scripting::Stringify(const DukValue& val) { return ExpressionStringifier::StringifyExpression(val); diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 7ad4f91232..c390b3220a 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -115,6 +115,7 @@ namespace OpenRCT2::Scripting uint32_t _lastHotReloadCheckTick{}; HookEngine _hookEngine; ScriptExecutionInfo _execInfo; + DukValue _sharedStorage; std::unique_ptr _pluginFileWatcher; std::unordered_set _changedPluginFiles; @@ -147,6 +148,10 @@ namespace OpenRCT2::Scripting { return _execInfo; } + DukValue GetSharedStorage() + { + return _sharedStorage; + } std::vector>& GetPlugins() { return _plugins; @@ -176,6 +181,8 @@ namespace OpenRCT2::Scripting const DukValue& execute); void RunGameActionHooks(const GameAction& action, std::unique_ptr& result, bool isExecute); + void SaveSharedStorage(); + private: void Initialise(); void StartPlugins(); @@ -192,6 +199,8 @@ namespace OpenRCT2::Scripting std::unique_ptr DukToGameActionResult(const DukValue& d); DukValue GameActionResultToDuk(const GameAction& action, const std::unique_ptr& result); DukValue PositionToDuk(const CoordsXYZ& position); + + void LoadSharedStorage(); }; bool IsGameStateMutable(); diff --git a/src/thirdparty/dukglue/dukvalue.h b/src/thirdparty/dukglue/dukvalue.h index 59092244c5..a70ad115ea 100644 --- a/src/thirdparty/dukglue/dukvalue.h +++ b/src/thirdparty/dukglue/dukvalue.h @@ -589,10 +589,10 @@ private: int* mRefCount; // if mType == OBJECT and we're sharing, this will point to our ref counter public: - DukValue operator [](const std::string &key) const + DukValue operator [](const std::string_view &key) const { push(); - duk_get_prop_string(mContext, -1, key.c_str()); + duk_get_prop_lstring(mContext, -1, key.data(), key.size()); auto result = DukValue::take_from_stack(mContext); duk_pop(mContext); return result;