From a1ebcdea5ce67620e11a1a1d1846a98254aede13 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 17 Mar 2018 18:37:30 +0000 Subject: [PATCH 001/159] Add duktape library --- openrct2.common.props | 4 ++-- src/openrct2/CMakeLists.txt | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/openrct2.common.props b/openrct2.common.props index 205501951b..f897da6b04 100644 --- a/openrct2.common.props +++ b/openrct2.common.props @@ -76,7 +76,7 @@ DebugFull - benchmarkd.lib;libbreakpadd.lib;libbreakpad_clientd.lib;bz2d.lib;discord-rpc.lib;freetyped.lib;jansson_d.lib;libpng16d.lib;libspeexdsp.lib;SDL2d.lib;zip.lib;zlibd.lib;%(AdditionalDependencies) + benchmarkd.lib;libbreakpadd.lib;libbreakpad_clientd.lib;bz2d.lib;discord-rpc.lib;duktape.lib;freetyped.lib;jansson_d.lib;libpng16d.lib;libspeexdsp.lib;SDL2d.lib;zip.lib;zlibd.lib;%(AdditionalDependencies) @@ -94,7 +94,7 @@ DebugFull true true - benchmark.lib;libbreakpad.lib;libbreakpad_client.lib;bz2.lib;discord-rpc.lib;freetype.lib;jansson.lib;libpng16.lib;libspeexdsp.lib;SDL2.lib;zip.lib;zlib.lib;%(AdditionalDependencies) + benchmark.lib;libbreakpad.lib;libbreakpad_client.lib;bz2.lib;discord-rpc.lib;duktape.lib;freetype.lib;jansson.lib;libpng16.lib;libspeexdsp.lib;SDL2.lib;zip.lib;zlib.lib;%(AdditionalDependencies) diff --git a/src/openrct2/CMakeLists.txt b/src/openrct2/CMakeLists.txt index b0bd3e9bff..75471fafe7 100644 --- a/src/openrct2/CMakeLists.txt +++ b/src/openrct2/CMakeLists.txt @@ -102,6 +102,7 @@ endif () # Third party libraries if (MSVC) + find_package(duktape REQUIRED) find_package(jansson CONFIG REQUIRED) set(JANSSON_LIBRARIES "jansson::jansson") find_package(png 1.6 REQUIRED) @@ -110,6 +111,7 @@ if (MSVC) find_path(LIBZIP_INCLUDE_DIRS zip.h) find_library(LIBZIP_LIBRARIES zip) else () + PKG_CHECK_MODULES(DUKTAPE REQUIRED duktape) PKG_CHECK_MODULES(JANSSON REQUIRED jansson>=2.5) PKG_CHECK_MODULES(LIBZIP REQUIRED libzip>=1.0) PKG_CHECK_MODULES(ZLIB REQUIRED zlib) @@ -128,11 +130,13 @@ endif () if (STATIC) target_link_libraries(${PROJECT_NAME} ${JANSSON_STATIC_LIBRARIES} + ${DUKTAPE_STATIC_LIBRARIES} ${PNG_STATIC_LIBRARIES} ${ZLIB_STATIC_LIBRARIES} ${LIBZIP_STATIC_LIBRARIES}) else () target_link_libraries(${PROJECT_NAME} ${JANSSON_LIBRARIES} + ${DUKTAPE_LIBRARIES} ${PNG_LIBRARIES} ${ZLIB_LIBRARIES} ${LIBZIP_LIBRARIES}) @@ -196,6 +200,7 @@ endif() target_include_directories(${PROJECT_NAME} PRIVATE ${LIBZIP_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PUBLIC ${JANSSON_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PRIVATE ${PNG_INCLUDE_DIRS} + ${DUKTAPE_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIRS}) # To avoid unnecessary rebuilds set the current branch and From 27a859721478294c6320cf26bd0e1cf951a87282 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 17 Mar 2018 18:37:46 +0000 Subject: [PATCH 002/159] Add scripting API definition file --- distribution/openrct2.d.ts | 94 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 distribution/openrct2.d.ts diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts new file mode 100644 index 0000000000..57ed804cce --- /dev/null +++ b/distribution/openrct2.d.ts @@ -0,0 +1,94 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + +// OpenRCT2 Scripting API definition file + +export interface Console { + log(message?: any, ...optionalParams: any[]): void; +} + +export interface Configuration { + getAll(pattern: string): { [name: string]: any }; + get(key: string): T | undefined; + get(key: string, defaultValue: T): T; + set(key: string, value: T): void; + has(key: string): boolean; +} + +export interface Context { + /** + * The user's current configuration. + */ + configuration: Configuration; + /** + * Subscribes to the given hook. + */ + subscribe: (hook: string, callback: Function) => void; +} + +export interface Ride { + name: string; + excitement: number; + intensity: number; + nausea: number; + totalCustomers: number; +} + +export interface Map { + getRide(id: number): Ride; +} + +export type ParkMessageType = + "attraction" | "peep_on_attraction" | "peep" | "money" | "blank" | "research" | "guests" | "award" | "chart"; + +export interface ParkMessage { + type: ParkMessageType; + text: string; +} + +export interface Park { + cash: number; + rating: number; + bankLoan: number; + maxBankLoan: number; + + postMessage(message: ParkMessage): void; +} + +export interface Window { + id: number; + classification: string; + x: number; + y: number; + width: number; + height: number; + title: string; +} + +export interface WindowDesc { + classification: string; + x?: number; + y?: number; + width: number; + height: number; + title: string; + id?: number; +} + +export interface Ui { + openWindow(desc: WindowDesc): Window; + closeWindow(window: Window); + closeWindows(classification: string, id?: number): void; + closeAllWindows(): void; +} + +declare var context: Context; +declare var map: Map; +declare var park: Park; +declare var ui: Ui; From 43508e040259d20e292b1c236e522d0507e9b1d2 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 17 Mar 2018 19:31:06 +0000 Subject: [PATCH 003/159] Add script engine and connect to std console --- src/openrct2/Context.cpp | 11 ++- src/openrct2/Context.h | 6 ++ src/openrct2/interface/InteractiveConsole.h | 7 -- src/openrct2/interface/StdInOutConsole.cpp | 28 ++------ src/openrct2/scripting/ScriptEngine.cpp | 79 +++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.h | 45 ++++++++++++ 6 files changed, 146 insertions(+), 30 deletions(-) create mode 100644 src/openrct2/scripting/ScriptEngine.cpp create mode 100644 src/openrct2/scripting/ScriptEngine.h diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 1e91933e97..027396a382 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -57,6 +57,7 @@ #include "ride/TrackDesignRepository.h" #include "scenario/Scenario.h" #include "scenario/ScenarioRepository.h" +#include "scripting/ScriptEngine.h" #include "title/TitleScreen.h" #include "title/TitleSequenceManager.h" #include "ui/UiContext.h" @@ -76,6 +77,7 @@ using namespace OpenRCT2::Audio; using namespace OpenRCT2::Drawing; using namespace OpenRCT2::Localisation; using namespace OpenRCT2::Paint; +using namespace OpenRCT2::Scripting; using namespace OpenRCT2::Ui; namespace OpenRCT2 @@ -100,6 +102,7 @@ namespace OpenRCT2 std::unique_ptr _discordService; #endif StdInOutConsole _stdInOutConsole; + ScriptEngine _scriptEngine; // Game states std::unique_ptr _titleScreen; @@ -135,6 +138,7 @@ namespace OpenRCT2 , _uiContext(uiContext) , _localisationService(std::make_unique(env)) , _painter(std::make_unique(uiContext)) + , _scriptEngine(_stdInOutConsole, *env) { // Can't have more than one context currently. Guard::Assert(Instance == nullptr); @@ -176,6 +180,11 @@ namespace OpenRCT2 return _uiContext; } + Scripting::ScriptEngine& GetScriptEngine() override + { + return _scriptEngine; + } + GameState* GetGameState() override { return _gameState.get(); @@ -1015,7 +1024,7 @@ namespace OpenRCT2 Twitch::Update(); chat_update(); - _stdInOutConsole.ProcessEvalQueue(); + _scriptEngine.Update(); _uiContext->Update(); } diff --git a/src/openrct2/Context.h b/src/openrct2/Context.h index 4b4193e652..c8ee6181ed 100644 --- a/src/openrct2/Context.h +++ b/src/openrct2/Context.h @@ -85,6 +85,11 @@ namespace OpenRCT2 class LocalisationService; } + namespace Scripting + { + class ScriptEngine; + } + namespace Ui { interface IUiContext; @@ -109,6 +114,7 @@ namespace OpenRCT2 virtual Localisation::LocalisationService& GetLocalisationService() abstract; virtual IObjectManager& GetObjectManager() abstract; virtual IObjectRepository& GetObjectRepository() abstract; + virtual Scripting::ScriptEngine& GetScriptEngine() abstract; virtual ITrackDesignRepository* GetTrackDesignRepository() abstract; virtual IScenarioRepository* GetScenarioRepository() abstract; virtual IReplayManager* GetReplayManager() abstract; diff --git a/src/openrct2/interface/InteractiveConsole.h b/src/openrct2/interface/InteractiveConsole.h index ec1a3181d4..ce35d74e1d 100644 --- a/src/openrct2/interface/InteractiveConsole.h +++ b/src/openrct2/interface/InteractiveConsole.h @@ -12,11 +12,8 @@ #include "../common.h" #include "../localisation/FormatCodes.h" -#include #include -#include #include -#include struct rct_drawpixelinfo; struct TextInputSession; @@ -53,13 +50,9 @@ public: class StdInOutConsole final : public InteractiveConsole { -private: - std::queue, std::string>> _evalQueue; - public: void Start(); std::future Eval(const std::string& s); - void ProcessEvalQueue(); void Clear() override; void Close() override; diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index df6c2359f3..9491b00cd7 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -7,11 +7,15 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ +#include "../Context.h" #include "../OpenRCT2.h" #include "../platform/Platform2.h" +#include "../scripting/ScriptEngine.h" #include "../thirdparty/linenoise.hpp" #include "InteractiveConsole.h" +using namespace OpenRCT2; + void StdInOutConsole::Start() { std::thread replThread([this]() -> void { @@ -51,28 +55,8 @@ void StdInOutConsole::Start() std::future StdInOutConsole::Eval(const std::string& s) { - // Push on-demand evaluations onto a queue so that it can be processed deterministically - // on the main thead at the right time. - std::promise barrier; - auto future = barrier.get_future(); - _evalQueue.emplace(std::move(barrier), s); - return future; -} - -void StdInOutConsole::ProcessEvalQueue() -{ - while (_evalQueue.size() > 0) - { - auto item = std::move(_evalQueue.front()); - _evalQueue.pop(); - auto promise = std::move(std::get<0>(item)); - auto command = std::move(std::get<1>(item)); - - Execute(command); - - // Signal the promise so caller can continue - promise.set_value(); - } + auto& scriptEngine = GetContext()->GetScriptEngine(); + return scriptEngine.Eval(s); } void StdInOutConsole::Clear() diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp new file mode 100644 index 0000000000..e3b6f89959 --- /dev/null +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -0,0 +1,79 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + +#include "ScriptEngine.h" +#include "../interface/InteractiveConsole.h" +#include +#include + +using namespace OpenRCT2; +using namespace OpenRCT2::Scripting; + +static std::string Stringify(duk_context * ctx, duk_idx_t idx); + +ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) : + _console(console), + _env(env) +{ + _context = duk_create_heap_default(); + if (_context == nullptr) + { + throw std::runtime_error("Unable to initialise duktape context."); + } +} + +ScriptEngine::~ScriptEngine() +{ + duk_destroy_heap(_context); +} + +void ScriptEngine::Update() +{ + while (_evalQueue.size() > 0) + { + auto item = std::move(_evalQueue.front()); + _evalQueue.pop(); + auto promise = std::move(std::get<0>(item)); + auto command = std::move(std::get<1>(item)); + if (duk_peval_string(_context, command.c_str()) != 0) + { + std::string result = std::string(duk_safe_to_string(_context, -1)); + _console.WriteLineError(result); + } + else + { + std::string result = Stringify(_context, -1); + _console.WriteLine(result); + } + duk_pop(_context); + // Signal the promise so caller can continue + promise.set_value(); + } +} + +std::future ScriptEngine::Eval(const std::string &s) +{ + std::promise barrier; + auto future = barrier.get_future(); + _evalQueue.emplace(std::move(barrier), s); + return future; +} + +static std::string Stringify(duk_context * ctx, duk_idx_t idx) +{ + auto type = duk_get_type(ctx, idx); + if (type == DUK_TYPE_OBJECT && !duk_is_function(ctx, idx)) + { + return duk_json_encode(ctx, idx); + } + else + { + return duk_safe_to_string(ctx, idx); + } +} diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h new file mode 100644 index 0000000000..e04550da91 --- /dev/null +++ b/src/openrct2/scripting/ScriptEngine.h @@ -0,0 +1,45 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 + +#include "../common.h" +#include +#include +#include + +struct duk_hthread; +typedef struct duk_hthread duk_context; + +class InteractiveConsole; + +namespace OpenRCT2 +{ + interface IPlatformEnvironment; +} + +namespace OpenRCT2::Scripting +{ + class ScriptEngine + { + private: + InteractiveConsole& _console; + IPlatformEnvironment& _env; + duk_context * _context; + std::queue, std::string>> _evalQueue; + + public: + ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); + ScriptEngine(ScriptEngine&&) = delete; + ~ScriptEngine(); + + void Update(); + std::future Eval(const std::string &s); + }; +} From f0de6533a032102b441b9af6ccf3f67e01dff3e6 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 17 Mar 2018 23:26:38 +0000 Subject: [PATCH 004/159] Add dukglue --- .../thirdparty/dukglue/detail_class_proto.h | 201 ++++++ .../thirdparty/dukglue/detail_constructor.h | 73 +++ .../thirdparty/dukglue/detail_function.h | 100 +++ .../thirdparty/dukglue/detail_method.h | 183 ++++++ .../dukglue/detail_primitive_types.h | 252 ++++++++ src/openrct2/thirdparty/dukglue/detail_refs.h | 199 ++++++ .../thirdparty/dukglue/detail_stack.h | 51 ++ .../thirdparty/dukglue/detail_traits.h | 122 ++++ .../thirdparty/dukglue/detail_typeinfo.h | 63 ++ .../thirdparty/dukglue/detail_types.h | 160 +++++ .../thirdparty/dukglue/dukexception.h | 40 ++ src/openrct2/thirdparty/dukglue/dukglue.h | 7 + src/openrct2/thirdparty/dukglue/dukvalue.h | 590 ++++++++++++++++++ src/openrct2/thirdparty/dukglue/public_util.h | 315 ++++++++++ .../thirdparty/dukglue/register_class.h | 202 ++++++ .../thirdparty/dukglue/register_function.h | 35 ++ .../thirdparty/dukglue/register_property.h | 123 ++++ 17 files changed, 2716 insertions(+) create mode 100644 src/openrct2/thirdparty/dukglue/detail_class_proto.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_constructor.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_function.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_method.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_primitive_types.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_refs.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_stack.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_traits.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_typeinfo.h create mode 100644 src/openrct2/thirdparty/dukglue/detail_types.h create mode 100644 src/openrct2/thirdparty/dukglue/dukexception.h create mode 100644 src/openrct2/thirdparty/dukglue/dukglue.h create mode 100644 src/openrct2/thirdparty/dukglue/dukvalue.h create mode 100644 src/openrct2/thirdparty/dukglue/public_util.h create mode 100644 src/openrct2/thirdparty/dukglue/register_class.h create mode 100644 src/openrct2/thirdparty/dukglue/register_function.h create mode 100644 src/openrct2/thirdparty/dukglue/register_property.h diff --git a/src/openrct2/thirdparty/dukglue/detail_class_proto.h b/src/openrct2/thirdparty/dukglue/detail_class_proto.h new file mode 100644 index 0000000000..7b008fccd1 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_class_proto.h @@ -0,0 +1,201 @@ +#pragma once + +#include "detail_typeinfo.h" +#include + +namespace dukglue { + namespace detail { + + struct ProtoManager + { + public: + template + static void push_prototype(duk_context* ctx) + { + push_prototype(ctx, TypeInfo(typeid(Cls))); + } + + static void push_prototype(duk_context* ctx, const TypeInfo& check_info) + { + if (!find_and_push_prototype(ctx, check_info)) { + // nope, need to create our prototype object + duk_push_object(ctx); + + // add reference to this class' info object so we can do type checking + // when trying to pass this object into method calls + typedef dukglue::detail::TypeInfo TypeInfo; + TypeInfo* info = new TypeInfo(check_info); + + duk_push_pointer(ctx, info); + duk_put_prop_string(ctx, -2, "\xFF" "type_info"); + + // Clean up the TypeInfo object when this prototype is destroyed. + // We can't put a finalizer directly on this prototype, because it + // will be run whenever the wrapper for an object of this class is + // destroyed; instead, we make a dummy object and put the finalizer + // on that. + // If you're memory paranoid: this duplicates the type_info pointer + // once per registered class. If you don't care about freeing memory + // during shutdown, you can probably comment out this part. + duk_push_object(ctx); + duk_push_pointer(ctx, info); + duk_put_prop_string(ctx, -2, "\xFF" "type_info"); + duk_push_c_function(ctx, type_info_finalizer, 1); + duk_set_finalizer(ctx, -2); + duk_put_prop_string(ctx, -2, "\xFF" "type_info_finalizer"); + + // register it in the stash + register_prototype(ctx, info); + } + } + + template + static void make_script_object(duk_context* ctx, Cls* obj) + { + assert(obj != NULL); + + duk_push_object(ctx); + duk_push_pointer(ctx, obj); + duk_put_prop_string(ctx, -2, "\xFF" "obj_ptr"); + + // push the appropriate prototype +#ifdef DUKGLUE_INFER_BASE_CLASS + // In the "infer base class" case, we push the prototype + // corresponding to the compile-time class if no prototype + // for the run-time type has been defined. This allows us to + // skip calling dukglue_set_base_class() for every derived class, + // so long as we: + // (1) Always use the derived class as a pointer typed as the base class + // (2) Do not create a prototype for the derived class + // (i.e. do not register any functions on the derived class). + + // For big projects with hundreds of derived classes, this is preferrable + // to registering each type's base class individually. However, + // registering a native method on a derived class will cause the + // base class's methods to disappear until dukglue_set_base_class() is + // also called (because registering the native method causes a prototype + // to be created for the run-time type). This behavior may be unexpected, + // and for "small" projects it is reasonable to require + // dukglue_set_base_class() to be called, so it is opt-in via an ifdef. + + // does a prototype exist for the run-time type? if so, push it + if (!find_and_push_prototype(ctx, TypeInfo(typeid(*obj)))) { + // nope, find or create the prototype for the compile-time type + // and push that + push_prototype(ctx); + } +#else + // always use the prototype for the run-time type + push_prototype(ctx, TypeInfo(typeid(*obj))); +#endif + + duk_set_prototype(ctx, -2); + } + + private: + static duk_ret_t type_info_finalizer(duk_context* ctx) + { + duk_get_prop_string(ctx, 0, "\xFF" "type_info"); + dukglue::detail::TypeInfo* info = static_cast(duk_require_pointer(ctx, -1)); + delete info; + + // set pointer to NULL in case this finalizer runs again + duk_push_pointer(ctx, NULL); + duk_put_prop_string(ctx, 0, "\xFF" "type_info"); + + return 0; + } + + // puts heap_stash["dukglue_prototypes"] on the stack, + // or creates it if it doesn't exist + static void push_prototypes_array(duk_context* ctx) + { + static const char* DUKGLUE_PROTOTYPES = "dukglue_prototypes"; + + duk_push_heap_stash(ctx); + + // does the prototype array already exist? + if (!duk_has_prop_string(ctx, -1, DUKGLUE_PROTOTYPES)) { + // nope, we need to create it + duk_push_array(ctx); + duk_put_prop_string(ctx, -2, DUKGLUE_PROTOTYPES); + } + + duk_get_prop_string(ctx, -1, DUKGLUE_PROTOTYPES); + + // remove the heap stash from the stack + duk_remove(ctx, -2); + } + + // Stack: ... [proto] -> ... [proto] + static void register_prototype(duk_context* ctx, const TypeInfo* info) { + // 1. We assume info is not in the prototype array already + // 2. Duktape has no efficient "shift array indices" operation (at least publicly) + // 3. This method doesn't need to be fast, it's only called during registration + + // Work from high to low in the prototypes array, shifting as we go, + // until we find the spot for info. + + push_prototypes_array(ctx); + duk_size_t i = duk_get_length(ctx, -1); + while (i > 0) { + duk_get_prop_index(ctx, -1, i - 1); + + duk_get_prop_string(ctx, -1, "\xFF" "type_info"); + const TypeInfo* chk_info = static_cast(duk_require_pointer(ctx, -1)); + duk_pop(ctx); // pop type_info + + if (*chk_info > *info) { + duk_put_prop_index(ctx, -2, i); + i--; + } else { + duk_pop(ctx); // pop prototypes_array[i] + break; + } + } + + //std::cout << "Registering prototype for " << typeid(Cls).name() << " at " << i << std::endl; + + duk_dup(ctx, -2); // copy proto to top + duk_put_prop_index(ctx, -2, i); + duk_pop(ctx); // pop prototypes_array + } + + static bool find_and_push_prototype(duk_context* ctx, const TypeInfo& search_info) { + push_prototypes_array(ctx); + + // these are ints and not duk_size_t to deal with negative indices + int min = 0; + int max = duk_get_length(ctx, -1) - 1; + + while (min <= max) { + int mid = (max - min) / 2 + min; + + duk_get_prop_index(ctx, -1, mid); + + duk_get_prop_string(ctx, -1, "\xFF" "type_info"); + TypeInfo* mid_info = static_cast(duk_require_pointer(ctx, -1)); + duk_pop(ctx); // pop type_info pointer + + if (*mid_info == search_info) { + // found it + duk_remove(ctx, -2); // pop prototypes_array + return true; + } + else if (*mid_info < search_info) { + min = mid + 1; + } + else { + max = mid - 1; + } + + duk_pop(ctx); // pop prototypes_array[mid] + } + + duk_pop(ctx); // pop prototypes_array + return false; + } + + }; + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_constructor.h b/src/openrct2/thirdparty/dukglue/detail_constructor.h new file mode 100644 index 0000000000..de68e85d5e --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_constructor.h @@ -0,0 +1,73 @@ +#pragma once + +#include "detail_stack.h" +#include "detail_traits.h" + +namespace dukglue { + namespace detail { + + template + static duk_ret_t call_native_constructor(duk_context* ctx) + { + if (!duk_is_constructor_call(ctx)) { + duk_error(ctx, DUK_RET_TYPE_ERROR, "Constructor must be called with new T()."); + return DUK_RET_TYPE_ERROR; + } + + // construct the new instance + auto constructor_args = dukglue::detail::get_stack_values(ctx); + Cls* obj = dukglue::detail::apply_constructor(std::move(constructor_args)); + + duk_push_this(ctx); + + // make the new script object keep the pointer to the new object instance + duk_push_pointer(ctx, obj); + duk_put_prop_string(ctx, -2, "\xFF" "obj_ptr"); + + // register it + if (!managed) + dukglue::detail::RefManager::register_native_object(ctx, obj); + + duk_pop(ctx); // pop this + + return 0; + } + + template + static duk_ret_t managed_finalizer(duk_context* ctx) + { + duk_get_prop_string(ctx, 0, "\xFF" "obj_ptr"); + Cls* obj = (Cls*) duk_require_pointer(ctx, -1); + duk_pop(ctx); // pop obj_ptr + + if (obj != NULL) { + delete obj; + + // for safety, set the pointer to undefined + duk_push_undefined(ctx); + duk_put_prop_string(ctx, 0, "\xFF" "obj_ptr"); + } + + return 0; + } + + template + static duk_ret_t call_native_deleter(duk_context* ctx) + { + duk_push_this(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "obj_ptr"); + + if (!duk_is_pointer(ctx, -1)) { + duk_error(ctx, DUK_RET_REFERENCE_ERROR, "Object has already been invalidated; cannot delete."); + return DUK_RET_REFERENCE_ERROR; + } + + Cls* obj = static_cast(duk_require_pointer(ctx, -1)); + dukglue_invalidate_object(ctx, obj); + delete obj; + + duk_pop_2(ctx); + return 0; + } + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_function.h b/src/openrct2/thirdparty/dukglue/detail_function.h new file mode 100644 index 0000000000..3d715884d3 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_function.h @@ -0,0 +1,100 @@ +#pragma once + +#include "detail_stack.h" + +namespace dukglue +{ + namespace detail + { + // This struct can be used to generate a Duktape C function that + // pulls the argument values off the stack (with type checking), + // calls the appropriate function with them, and puts the function's + // return value (if any) onto the stack. + template + struct FuncInfoHolder + { + typedef RetType(*FuncType)(Ts...); + + template + struct FuncCompiletime + { + // The function to call is embedded into call_native_function at + // compile-time through template magic. + // Performance is so similar to run-time function calls that + // this is not recommended due to the ugly syntax it requires. + static duk_ret_t call_native_function(duk_context* ctx) + { + auto bakedArgs = dukglue::detail::get_stack_values(ctx); + actually_call(ctx, bakedArgs); + return std::is_void::value ? 0 : 1; + } + + private: + // this mess is to support functions with void return values + + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, const std::tuple& args) + { + // ArgStorage has some static_asserts in it that validate value types, + // so we typedef it to force ArgStorage to compile and run the asserts + typedef typename dukglue::types::ArgStorage::type ValidateReturnType; + + RetType return_val = dukglue::detail::apply_fp(funcToCall, args); + + using namespace dukglue::types; + DukType::type>::template push(ctx, std::move(return_val)); + } + + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, const std::tuple& args) + { + dukglue::detail::apply_fp(funcToCall, args); + } + }; + + struct FuncRuntime + { + // Pull the address of the function to call from the + // Duktape function object at run time. + static duk_ret_t call_native_function(duk_context* ctx) + { + duk_push_current_function(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "func_ptr"); + void* fp_void = duk_require_pointer(ctx, -1); + if (fp_void == NULL) { + duk_error(ctx, DUK_RET_TYPE_ERROR, "what even"); + return DUK_RET_TYPE_ERROR; + } + + duk_pop_2(ctx); + + static_assert(sizeof(RetType(*)(Ts...)) == sizeof(void*), "Function pointer and data pointer are different sizes"); + RetType(*funcToCall)(Ts...) = reinterpret_cast(fp_void); + + actually_call(ctx, funcToCall, dukglue::detail::get_stack_values(ctx)); + return std::is_void::value ? 0 : 1; + } + + // this mess is to support functions with void return values + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, RetType(*funcToCall)(Ts...), const std::tuple& args) + { + // ArgStorage has some static_asserts in it that validate value types, + // so we typedef it to force ArgStorage to compile and run the asserts + typedef typename dukglue::types::ArgStorage::type ValidateReturnType; + + RetType return_val = dukglue::detail::apply_fp(funcToCall, args); + + using namespace dukglue::types; + DukType::type>::template push(ctx, std::move(return_val)); + } + + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, RetType(*funcToCall)(Ts...), const std::tuple& args) + { + dukglue::detail::apply_fp(funcToCall, args); + } + }; + }; + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_method.h b/src/openrct2/thirdparty/dukglue/detail_method.h new file mode 100644 index 0000000000..d3e929034d --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_method.h @@ -0,0 +1,183 @@ +#pragma once + +#include "detail_stack.h" + +namespace dukglue +{ + namespace detail + { + template + struct MethodInfo + { + typedef typename std::conditional::type MethodType; + + // The size of a method pointer is not guaranteed to be the same size as a function pointer. + // This means we can't just use duk_push_pointer(ctx, &MyClass::method) to store the method at run time. + // To get around this, we wrap the method pointer in a MethodHolder (on the heap), and push a pointer to + // that. The MethodHolder is cleaned up by the finalizer. + struct MethodHolder + { + MethodType method; + }; + + template + struct MethodCompiletime + { + static duk_ret_t call_native_method(duk_context* ctx) + { + // get this.obj_ptr + duk_push_this(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "obj_ptr"); + void* obj_void = duk_require_pointer(ctx, -1); + if (obj_void == nullptr) { + duk_error(ctx, DUK_RET_REFERENCE_ERROR, "Native object missing."); + return DUK_RET_REFERENCE_ERROR; + } + + duk_pop_2(ctx); + + // (should always be valid unless someone is intentionally messing with this.obj_ptr...) + Cls* obj = static_cast(obj_void); + + // read arguments and call function + auto bakedArgs = dukglue::detail::get_stack_values(ctx); + actually_call(ctx, obj, bakedArgs); + return std::is_void::value ? 0 : 1; + } + + // this mess is to support functions with void return values + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, Cls* obj, const std::tuple& args) + { + // ArgStorage has some static_asserts in it that validate value types, + // so we typedef it to force ArgStorage to compile and run the asserts + typedef typename dukglue::types::ArgStorage::type ValidateReturnType; + + RetType return_val = dukglue::detail::apply_method(methodToCall, obj, args); + + using namespace dukglue::types; + DukType::type>::template push(ctx, std::move(return_val)); + } + + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, Cls* obj, const std::tuple& args) + { + dukglue::detail::apply_method(methodToCall, obj, args); + } + }; + + + struct MethodRuntime + { + static duk_ret_t finalize_method(duk_context* ctx) + { + // clean up the MethodHolder reference + duk_get_prop_string(ctx, 0, "\xFF" "method_holder"); + + void* method_holder_void = duk_require_pointer(ctx, -1); + MethodHolder* method_holder = static_cast(method_holder_void); + delete method_holder; + + return 0; + } + + static duk_ret_t call_native_method(duk_context* ctx) + { + // get this.obj_ptr + duk_push_this(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "obj_ptr"); + void* obj_void = duk_get_pointer(ctx, -1); + if (obj_void == nullptr) { + duk_error(ctx, DUK_RET_REFERENCE_ERROR, "Invalid native object for 'this'"); + return DUK_RET_REFERENCE_ERROR; + } + + duk_pop_2(ctx); // pop this.obj_ptr and this + + // get current_function.method_info + duk_push_current_function(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "method_holder"); + void* method_holder_void = duk_require_pointer(ctx, -1); + if (method_holder_void == nullptr) { + duk_error(ctx, DUK_RET_TYPE_ERROR, "Method pointer missing?!"); + return DUK_RET_TYPE_ERROR; + } + + duk_pop_2(ctx); + + // (should always be valid unless someone is intentionally messing with this.obj_ptr...) + Cls* obj = static_cast(obj_void); + MethodHolder* method_holder = static_cast(method_holder_void); + + // read arguments and call method + auto bakedArgs = dukglue::detail::get_stack_values(ctx); + actually_call(ctx, method_holder->method, obj, bakedArgs); + return std::is_void::value ? 0 : 1; + } + + // this mess is to support functions with void return values + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, MethodType method, Cls* obj, const std::tuple& args) + { + // ArgStorage has some static_asserts in it that validate value types, + // so we typedef it to force ArgStorage to compile and run the asserts + typedef typename dukglue::types::ArgStorage::type ValidateReturnType; + + RetType return_val = dukglue::detail::apply_method(method, obj, args); + + using namespace dukglue::types; + DukType::type>::template push(ctx, std::move(return_val)); + } + + template + static typename std::enable_if::value>::type actually_call(duk_context* ctx, MethodType method, Cls* obj, const std::tuple& args) + { + dukglue::detail::apply_method(method, obj, args); + } + }; + }; + + template + struct MethodVariadicRuntime + { + typedef MethodInfo MethodInfoVariadic; + typedef typename MethodInfoVariadic::MethodHolder MethodHolderVariadic; + + static duk_ret_t finalize_method(duk_context* ctx) + { + return MethodInfoVariadic::MethodRuntime::finalize_method(ctx); + } + + static duk_ret_t call_native_method(duk_context* ctx) + { + // get this.obj_ptr + duk_push_this(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "obj_ptr"); + void* obj_void = duk_get_pointer(ctx, -1); + if (obj_void == nullptr) { + duk_error(ctx, DUK_RET_REFERENCE_ERROR, "Invalid native object for 'this'"); + return DUK_RET_REFERENCE_ERROR; + } + + duk_pop_2(ctx); // pop this.obj_ptr and this + + // get current_function.method_info + duk_push_current_function(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "method_holder"); + void* method_holder_void = duk_require_pointer(ctx, -1); + if (method_holder_void == nullptr) { + duk_error(ctx, DUK_RET_TYPE_ERROR, "Method pointer missing?!"); + return DUK_RET_TYPE_ERROR; + } + + duk_pop_2(ctx); + + // (should always be valid unless someone is intentionally messing with this.obj_ptr...) + Cls* obj = static_cast(obj_void); + MethodHolderVariadic* method_holder = static_cast(method_holder_void); + + return (*obj.*method_holder->method)(ctx); + } + }; + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_primitive_types.h b/src/openrct2/thirdparty/dukglue/detail_primitive_types.h new file mode 100644 index 0000000000..ebba1ad80a --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_primitive_types.h @@ -0,0 +1,252 @@ +#pragma once + +#include "detail_types.h" +#include "detail_typeinfo.h" +#include "dukvalue.h" + +#include +#include +#include // for std::shared_ptr + +namespace dukglue { + namespace types { + +#define DUKGLUE_SIMPLE_VALUE_TYPE(TYPE, DUK_IS_FUNC, DUK_GET_FUNC, DUK_PUSH_FUNC, PUSH_VALUE) \ + template<> \ + struct DukType { \ + typedef std::true_type IsValueType; \ + \ + template \ + static TYPE read(duk_context* ctx, duk_idx_t arg_idx) { \ + if (DUK_IS_FUNC(ctx, arg_idx)) { \ + return static_cast(DUK_GET_FUNC(ctx, arg_idx)); \ + } else { \ + duk_int_t type_idx = duk_get_type(ctx, arg_idx); \ + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected " #TYPE ", got %s", arg_idx, detail::get_type_name(type_idx)); \ + } \ + } \ + \ + template \ + static void push(duk_context* ctx, TYPE value) { \ + DUK_PUSH_FUNC(ctx, PUSH_VALUE); \ + } \ + }; + + DUKGLUE_SIMPLE_VALUE_TYPE(bool, duk_is_boolean, 0 != duk_get_boolean, duk_push_boolean, value) + + DUKGLUE_SIMPLE_VALUE_TYPE(uint8_t, duk_is_number, duk_get_uint, duk_push_uint, value) + DUKGLUE_SIMPLE_VALUE_TYPE(uint16_t, duk_is_number, duk_get_uint, duk_push_uint, value) + DUKGLUE_SIMPLE_VALUE_TYPE(uint32_t, duk_is_number, duk_get_uint, duk_push_uint, value) + DUKGLUE_SIMPLE_VALUE_TYPE(uint64_t, duk_is_number, duk_get_number, duk_push_number, value) // have to cast to double + + DUKGLUE_SIMPLE_VALUE_TYPE(int8_t, duk_is_number, duk_get_int, duk_push_int, value) + DUKGLUE_SIMPLE_VALUE_TYPE(int16_t, duk_is_number, duk_get_int, duk_push_int, value) + DUKGLUE_SIMPLE_VALUE_TYPE(int32_t, duk_is_number, duk_get_int, duk_push_int, value) + DUKGLUE_SIMPLE_VALUE_TYPE(int64_t, duk_is_number, duk_get_number, duk_push_number, value) // have to cast to double + + // signed char and unsigned char are surprisingly *both* different from char, at least in MSVC + DUKGLUE_SIMPLE_VALUE_TYPE(char, duk_is_number, duk_get_int, duk_push_int, value) + + DUKGLUE_SIMPLE_VALUE_TYPE(float, duk_is_number, duk_get_number, duk_push_number, value) + DUKGLUE_SIMPLE_VALUE_TYPE(double, duk_is_number, duk_get_number, duk_push_number, value) + + DUKGLUE_SIMPLE_VALUE_TYPE(std::string, duk_is_string, duk_get_string, duk_push_string, value.c_str()) + + // We have to do some magic for const char* to work correctly. + // We override the "bare type" and "storage type" to both be const char*. + // char* is a bit tricky because its "bare type" should still be const char*, to differentiate it from just char + template<> + struct Bare { + typedef const char* type; + }; + template<> + struct Bare { + typedef const char* type; + }; + + // the storage type should also be const char* - if we don't do this, it will end up as just "char" + template<> + struct ArgStorage { + typedef const char* type; + }; + + template<> + struct DukType { + typedef std::true_type IsValueType; + + template + static const char* read(duk_context* ctx, duk_idx_t arg_idx) { + if (duk_is_string(ctx, arg_idx)) { + return duk_get_string(ctx, arg_idx); + } else { + duk_int_t type_idx = duk_get_type(ctx, arg_idx); + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected string, got %s", arg_idx, detail::get_type_name(type_idx)); + } + } + + template + static void push(duk_context* ctx, const char* value) { + duk_push_string(ctx, value); + } + }; + + // DukValue + template<> + struct DukType { + typedef std::true_type IsValueType; + + template + static DukValue read(duk_context* ctx, duk_idx_t arg_idx) { + try { + return DukValue::copy_from_stack(ctx, arg_idx); + } catch (DukException& e) { + // only DukException can be thrown by DukValue::copy_from_stack + duk_error(ctx, DUK_ERR_ERROR, e.what()); + } + } + + template + static void push(duk_context* ctx, const DukValue& value) { + if (value.context() == NULL) { + duk_error(ctx, DUK_ERR_ERROR, "DukValue is uninitialized"); + return; + } + + if (value.context() != ctx) { + duk_error(ctx, DUK_ERR_ERROR, "DukValue comes from a different context"); + return; + } + + try { + value.push(); + } catch (DukException& e) { + // only DukException can be thrown by DukValue::copy_from_stack + duk_error(ctx, DUK_ERR_ERROR, e.what()); + } + } + }; + + // std::vector (as value) + template + struct DukType< std::vector > { + typedef std::true_type IsValueType; + + template + static std::vector read(duk_context* ctx, duk_idx_t arg_idx) { + if (!duk_is_array(ctx, arg_idx)) { + duk_int_t type_idx = duk_get_type(ctx, arg_idx); + duk_error(ctx, DUK_ERR_TYPE_ERROR, "Argument %d: expected array, got %s", arg_idx, detail::get_type_name(type_idx)); + } + + duk_size_t len = duk_get_length(ctx, arg_idx); + const duk_idx_t elem_idx = duk_get_top(ctx); + + std::vector vec; + vec.reserve(len); + for (duk_size_t i = 0; i < len; i++) { + duk_get_prop_index(ctx, arg_idx, i); + vec.push_back(DukType< typename Bare::type >::template read(ctx, elem_idx)); + duk_pop(ctx); + } + return vec; + } + + template + static void push(duk_context* ctx, const std::vector& value) { + duk_idx_t obj_idx = duk_push_array(ctx); + + for (size_t i = 0; i < value.size(); i++) { + DukType< typename Bare::type >::template push(ctx, value[i]); + duk_put_prop_index(ctx, obj_idx, i); + } + } + }; + + // std::shared_ptr (as value) + template + struct DukType< std::shared_ptr > { + typedef std::true_type IsValueType; + + static_assert(std::is_same::IsValueType, std::false_type>::value, "Dukglue can only use std::shared_ptr to non-value types!"); + + template + static std::shared_ptr read(duk_context* ctx, duk_idx_t arg_idx) { + if (duk_is_null(ctx, arg_idx)) + return nullptr; + + if (!duk_is_object(ctx, arg_idx)) { + duk_int_t type_idx = duk_get_type(ctx, arg_idx); + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected shared_ptr object, got ", arg_idx, detail::get_type_name(type_idx)); + } + + duk_get_prop_string(ctx, arg_idx, "\xFF" "type_info"); + if (!duk_is_pointer(ctx, -1)) // missing type_info, must not be a native object + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected shared_ptr object (missing type_info)", arg_idx); + + // make sure this object can be safely returned as a T* + dukglue::detail::TypeInfo* info = static_cast(duk_get_pointer(ctx, -1)); + if (!info->can_cast()) + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: wrong type of shared_ptr object", arg_idx); + duk_pop(ctx); // pop type_info + + duk_get_prop_string(ctx, arg_idx, "\xFF" "shared_ptr"); + if (!duk_is_pointer(ctx, -1)) + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: not a shared_ptr object (missing shared_ptr)", arg_idx); + void* ptr = duk_get_pointer(ctx, -1); + duk_pop(ctx); // pop pointer to shared_ptr + + return *((std::shared_ptr*) ptr); + } + + static duk_ret_t shared_ptr_finalizer(duk_context* ctx) + { + duk_get_prop_string(ctx, 0, "\xFF" "shared_ptr"); + std::shared_ptr* ptr = (std::shared_ptr*) duk_require_pointer(ctx, -1); + duk_pop(ctx); // pop shared_ptr ptr + + if (ptr != NULL) { + delete ptr; + + // for safety, set the pointer to undefined + // (finalizers can run multiple times) + duk_push_undefined(ctx); + duk_put_prop_string(ctx, 0, "\xFF" "shared_ptr"); + } + + return 0; + } + + template + static void push(duk_context* ctx, const std::shared_ptr& value) { + dukglue::detail::ProtoManager::make_script_object(ctx, value.get()); + + // create + set shared_ptr + duk_push_pointer(ctx, new std::shared_ptr(value)); + duk_put_prop_string(ctx, -2, "\xFF" "shared_ptr"); + + // set shared_ptr finalizer + duk_push_c_function(ctx, &shared_ptr_finalizer, 1); + duk_set_finalizer(ctx, -2); + } + }; + + // std::function + /*template + struct DukType< std::function > { + typedef std::true_type IsValueType; + + template + static std::function read(duk_context* ctx, duk_idx_t arg_idx) { + DukValue callable = DukValue::copy_from_stack(ctx, -1, DUK_TYPE_MASK_OBJECT); + return [ctx, callable] (ArgTs... args) -> RetT { + dukglue_call(ctx, callable, args...); + }; + } + + template + static void push(duk_context* ctx, std::function value) { + static_assert(false, "Pushing an std::function has not been implemented yet. Sorry!"); + } + };*/ + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_refs.h b/src/openrct2/thirdparty/dukglue/detail_refs.h new file mode 100644 index 0000000000..67ad671639 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_refs.h @@ -0,0 +1,199 @@ +#pragma once + +#include + +#include + +namespace dukglue +{ + namespace detail + { + // This class handles keeping a map of void* -> script object. + // It also prevents script objects from being GC'd until someone + // explicitly frees the underlying native object. + + // Implemented by keeping an array of script objects in the heap stash. + // An std::unordered_map maps pointer -> array index. + // Thanks to std::unordered_map, lookup time is O(1) on average. + + // Using std::unordered_map has some memory overhead (~32 bytes per object), + // which could be removed by using a different data structure: + + // 1. Use no data structure. Blindly scan through the reference registry, + // checking \xFFobj_ptr on every object until you find yours. + // Performance when returning native objects from functions when a lot + // of native objects are registered will suffer. + + // 2. Implement a self-balancing binary tree on top of a Duktape array + // for the registry. Still fast - O(log(N)) - and no memory overhead. + + // 3. A sorted list would work too, though insertion speed might be worse + // than a binary tree. + + struct RefManager + { + public: + + // Find the script object corresponding to obj_ptr and push it. + // Returns true if successful, false if obj_ptr has not been registered. + // Stack: ... -> ... (if object has been registered before) + // ... -> ... [object] (if object has not been registered) + static bool find_and_push_native_object(duk_context* ctx, void* obj_ptr) + { + RefMap* ref_map = get_ref_map(ctx); + + const auto it = ref_map->find(obj_ptr); + + if (it == ref_map->end()) { + return false; + } else { + push_ref_array(ctx); + duk_get_prop_index(ctx, -1, it->second); + duk_remove(ctx, -2); + return true; + } + } + + // Takes a script object and adds it to the registry, associating + // it with obj_ptr. unregistered_object is not modified. + // If obj_ptr has already been registered with another object, + // the old registry entry will be overidden. + // Does nothing if obj_ptr is NULL. + // Stack: ... [object] -> ... [object] + static void register_native_object(duk_context* ctx, void* obj_ptr) + { + if (obj_ptr == NULL) + return; + + RefMap* ref_map = get_ref_map(ctx); + + push_ref_array(ctx); + + // find next free index + // free indices are kept in a linked list, starting at ref_array[0] + duk_get_prop_index(ctx, -1, 0); + duk_uarridx_t next_free_idx = duk_get_uint(ctx, -1); + duk_pop(ctx); + + if (next_free_idx == 0) { + // no free spots in the array, make a new one at arr.length + next_free_idx = duk_get_length(ctx, -1); + } else { + // free spot found, need to remove it from the free list + // ref_array[0] = ref_array[next_free_idx] + duk_get_prop_index(ctx, -1, next_free_idx); + duk_put_prop_index(ctx, -2, 0); + } + + // std::cout << "putting reference at ref_array[" << next_free_idx << "]" << std::endl; + (*ref_map)[obj_ptr] = next_free_idx; + + duk_dup(ctx, -2); // put object on top + + // ... [object] [ref_array] [object] + duk_put_prop_index(ctx, -2, next_free_idx); + + duk_pop(ctx); // pop ref_array + } + + // Remove the object associated with obj_ptr from the registry + // and invalidate the object's internal native pointer (by setting it to undefined). + // Does nothing if obj_ptr if object was never registered or obj_ptr is NULL. + // Does not affect the stack. + static void find_and_invalidate_native_object(duk_context* ctx, void* obj_ptr) + { + if (obj_ptr == NULL) + return; + + RefMap* ref_map = get_ref_map(ctx); + auto it = ref_map->find(obj_ptr); + if (it == ref_map->end()) // was never registered + return; + + push_ref_array(ctx); + duk_get_prop_index(ctx, -1, it->second); + + // invalidate internal pointer + duk_push_undefined(ctx); + duk_put_prop_string(ctx, -2, "\xFF" "obj_ptr"); + duk_pop(ctx); // pop object + + // remove from references array and add the space it was in to free list + // (refs[0] -> tail) -> (refs[0] -> old_obj_idx -> tail) + + // refs[old_obj_idx] = refs[0] + duk_get_prop_index(ctx, -1, 0); + duk_put_prop_index(ctx, -2, it->second); + + // refs[0] = old_obj_idx + duk_push_uint(ctx, it->second); + duk_put_prop_index(ctx, -2, 0); + + duk_pop(ctx); // pop ref_array + + // also remove from map + // std::cout << "Freeing ref_array[" << it->second << "]" << std::endl; + ref_map->erase(it); + } + + private: + typedef std::unordered_map RefMap; + + static RefMap* get_ref_map(duk_context* ctx) + { + static const char* DUKGLUE_REF_MAP = "dukglue_ref_map"; + static const char* PTR = "ptr"; + + duk_push_heap_stash(ctx); + + if (!duk_has_prop_string(ctx, -1, DUKGLUE_REF_MAP)) { + // doesn't exist yet, need to create it + duk_push_object(ctx); + + duk_push_pointer(ctx, new RefMap()); + duk_put_prop_string(ctx, -2, PTR); + + duk_push_c_function(ctx, ref_map_finalizer, 1); + duk_set_finalizer(ctx, -2); + + duk_put_prop_string(ctx, -2, DUKGLUE_REF_MAP); + } + + duk_get_prop_string(ctx, -1, DUKGLUE_REF_MAP); + duk_get_prop_string(ctx, -1, PTR); + RefMap* map = static_cast(duk_require_pointer(ctx, -1)); + duk_pop_3(ctx); + + return map; + } + + static duk_ret_t ref_map_finalizer(duk_context* ctx) + { + duk_get_prop_string(ctx, 0, "ptr"); + RefMap* map = static_cast(duk_require_pointer(ctx, -1)); + delete map; + + return 0; + } + + static void push_ref_array(duk_context* ctx) + { + static const char* DUKGLUE_REF_ARRAY = "dukglue_ref_array"; + duk_push_heap_stash(ctx); + + if (!duk_has_prop_string(ctx, -1, DUKGLUE_REF_ARRAY)) { + duk_push_array(ctx); + + // ref_array[0] = 0 (initialize free list as empty) + duk_push_int(ctx, 0); + duk_put_prop_index(ctx, -2, 0); + + duk_put_prop_string(ctx, -2, DUKGLUE_REF_ARRAY); + } + + duk_get_prop_string(ctx, -1, DUKGLUE_REF_ARRAY); + duk_remove(ctx, -2); // pop heap stash + } + }; + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_stack.h b/src/openrct2/thirdparty/dukglue/detail_stack.h new file mode 100644 index 0000000000..f5382ab898 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_stack.h @@ -0,0 +1,51 @@ +#pragma once + +#include + +#include "detail_traits.h" +#include "detail_types.h" + +#include + +namespace dukglue +{ + namespace detail + { + // Helper to get the argument tuple type, with correct storage types. + template + struct ArgsTuple { + typedef std::tuple::type...> type; + }; + + // Helper to get argument indices. + // Call read for every Ts[i], for matching argument index Index[i]. + // The traits::index_tuple is used for type inference. + // A concrete example: + // get_values(duktape_context) + // get_values_helper<{int, bool}, {0, 1}>(ctx, ignored) + // std::make_tuple(read(ctx, 0), read(ctx, 1)) + template + typename ArgsTuple::type get_stack_values_helper(duk_context* ctx, dukglue::detail::index_tuple) + { + using namespace dukglue::types; + return std::forward_as_tuple(DukType::type>::template read::type>(ctx, Indexes)...); + } + + // Returns an std::tuple of the values asked for in the template parameters. + // Values will remain on the stack. + // Values are indexed from the bottom of the stack up (0, 1, ...). + // If a value does not exist or does not have the expected type, an error is thrown + // through Duktape (with duk_error(...)), and the function does not return + template + typename ArgsTuple::type get_stack_values(duk_context* ctx) + { + // We need the argument indices for read_value, and we need to be able + // to unpack them as a template argument to match Ts. + // So, we use traits::make_indexes, which returns a traits::index_tuple<0, 1, 2, ...> object. + // We pass that into a helper function so we can put a name to that <0, 1, ...> template argument. + // Here, the type of Args isn't important, the length of it is. + auto indices = typename dukglue::detail::make_indexes::type(); + return get_stack_values_helper(ctx, indices); + } + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_traits.h b/src/openrct2/thirdparty/dukglue/detail_traits.h new file mode 100644 index 0000000000..247e2e52bf --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_traits.h @@ -0,0 +1,122 @@ +#pragma once + +#include + +namespace dukglue +{ + namespace detail + { + ////////////////////////////////////////////////////////////////////////////////////////////// + + // Credit to LuaState for this code: + // https://github.com/AdUki/LuaState/blob/master/include/Traits.h + + template struct index_tuple {}; + + template + struct make_indexes_impl; + + template + struct make_indexes_impl, T, Types...> + { + typedef typename make_indexes_impl, Types...>::type type; + }; + + template + struct make_indexes_impl > + { + typedef index_tuple type; + }; + + template + struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> + {}; + + ////////////////////////////////////////////////////////////////////////////////////////////// + + template + struct indexes {}; + + template + struct indexes_builder : indexes_builder {}; + + template + struct indexes_builder<0, Is...> { + typedef indexes index; + }; + + ////////////////////////////////////////////////////////////////////////////////////////////// + + // This mess is used to use function arugments stored in an std::tuple to an + // std::function, function pointer, or method. + + // std::function + template + Ret apply_helper(std::function pf, index_tuple< Indexes... >, std::tuple&& tup) + { + return pf(std::forward(std::get(tup))...); + } + + template + Ret apply(std::function pf, const std::tuple& tup) + { + return apply_helper(pf, typename make_indexes::type(), std::tuple(tup)); + } + + // function pointer + template + Ret apply_fp_helper(Ret(*pf)(Args...), index_tuple< Indexes... >, std::tuple&& tup) + { + return pf(std::forward(std::get(tup))...); + } + + template + Ret apply_fp(Ret(*pf)(Args...), const std::tuple& tup) + { + return apply_fp_helper(pf, typename make_indexes::type(), std::tuple(tup)); + } + + // method pointer + template + Ret apply_method_helper(Ret(Cls::*pf)(Args...), index_tuple< Indexes... >, Cls* obj, std::tuple&& tup) + { + return (*obj.*pf)(std::forward(std::get(tup))...); + } + + template + Ret apply_method(Ret(Cls::*pf)(Args...), Cls* obj, const std::tuple& tup) + { + return apply_method_helper(pf, typename make_indexes::type(), obj, std::tuple(tup)); + } + + // const method pointer + template + Ret apply_method_helper(Ret(Cls::*pf)(Args...) const, index_tuple< Indexes... >, Cls* obj, std::tuple&& tup) + { + return (*obj.*pf)(std::forward(std::get(tup))...); + } + + template + Ret apply_method(Ret(Cls::*pf)(Args...) const, Cls* obj, const std::tuple& tup) + { + return apply_method_helper(pf, typename make_indexes::type(), obj, std::tuple(tup)); + } + + // constructor + template + Cls* apply_constructor_helper(index_tuple< Indexes... >, std::tuple&& tup) + { + return new Cls(std::forward(std::get(tup))...); + } + + template + Cls* apply_constructor(const std::tuple& tup) + { + return apply_constructor_helper(typename make_indexes::type(), std::tuple(tup)); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + + + } +} \ No newline at end of file diff --git a/src/openrct2/thirdparty/dukglue/detail_typeinfo.h b/src/openrct2/thirdparty/dukglue/detail_typeinfo.h new file mode 100644 index 0000000000..5626c64c5a --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_typeinfo.h @@ -0,0 +1,63 @@ +#pragma once + +#include + +namespace dukglue +{ + namespace detail + { + // same as duk_get_type_name, which is private for some reason *shakes fist* + static const char* get_type_name(duk_int_t type_idx) { + static const char* names[] = { + "none", + "undefined", + "null", + "boolean", + "number", + "string", + "object", + "buffer", + "pointer", + "lightfunc" + }; + + if (type_idx >= 0 && type_idx < sizeof(names) / sizeof(names[0])) + return names[type_idx]; + else + return "unknown"; + } + + class TypeInfo + { + public: + TypeInfo(std::type_index&& idx) : index_(idx), base_(nullptr) {} + TypeInfo(const TypeInfo& rhs) : index_(rhs.index_), base_(rhs.base_) {} + + inline void set_base(TypeInfo* base) { + base_ = base; + } + + template + bool can_cast() const { + if (index_ == typeid(T)) + return true; + + if (base_) + return base_->can_cast(); + + return false; + } + + inline bool operator<(const TypeInfo& rhs) const { return index_ < rhs.index_; } + inline bool operator<=(const TypeInfo& rhs) const { return index_ <= rhs.index_; } + inline bool operator>(const TypeInfo& rhs) const { return index_ > rhs.index_; } + inline bool operator>=(const TypeInfo& rhs) const { return index_ >= rhs.index_; } + inline bool operator==(const TypeInfo& rhs) const { return index_ == rhs.index_; } + inline bool operator!=(const TypeInfo& rhs) const { return index_ != rhs.index_; } + + private: + std::type_index index_; + TypeInfo* base_; + }; + } +} diff --git a/src/openrct2/thirdparty/dukglue/detail_types.h b/src/openrct2/thirdparty/dukglue/detail_types.h new file mode 100644 index 0000000000..de86afe414 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/detail_types.h @@ -0,0 +1,160 @@ +#pragma once + +#include + +#include "detail_refs.h" +#include "detail_typeinfo.h" +#include "detail_class_proto.h" + +// TODO try adding a using namespace std in here if I can scope it to just this file + +namespace dukglue { + namespace types { + + // Bare::type is T stripped of reference, pointer, and const off a type, like so: + // Bare::type = Dog + // Bare::type = Dog + // Bare::type = Dog + // Bare::type = Dog + // Bare::type = Dog + // Bare::type = Dog + template + struct Bare { + typedef typename std::remove_const::type>::type>::type type; + }; + + // DukType provides functions for reading and writing T from the Duktape stack. + // T is always a "bare type," i.e. "Dog" rather than "Dog*". + + // There are two kinds of DukTypes: + // 1. "Native" DukTypes. This is the default. + // These types use an underlying native object allocated on the heap. + // A pointer to the object (of type T*) is expected at script_object.\xFFobj_ptr. + // "Native" DukTypes can return a value (returns a copy-constructed T from the native object), + // a pointer (just returns script_object.\xFFobj_ptr), or a reference (dereferences script_object.\xFFobj_ptr if it is not null). + + // 2. "Value" DukTypes. These are implemented through template specialization. + // This is how primitive types are implemented (int, float, const char*). + // These types can only be returned by value (T) or by const reference (const T&). + // Attempting to read a pointer (T*) or non-const reference (T&) will give a compile-time error. + // You can also use this to implement your own lightweight types, such as a 3D vector. + // (Strictly speaking, non-const references (T&) *could* be returned, but any changes to the reference would + // be discarded. So, I wrote a static assert to disable the option. If you understand the implications, + // you should be able to safely comment out the static_assert in ArgStorage.) + template + struct DukType { + static_assert(std::is_same::type >::value, "Invalid base type, expected bare type"); + + typedef std::false_type IsValueType; + + // read pointer + template::value>::type > + static T* read(duk_context* ctx, duk_idx_t arg_idx) { + using namespace dukglue::detail; + + if (duk_is_null(ctx, arg_idx)) + return nullptr; + + if (!duk_is_object(ctx, arg_idx)) { + duk_int_t type_idx = duk_get_type(ctx, arg_idx); + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected native object, got %s", arg_idx, get_type_name(type_idx)); + } + + duk_get_prop_string(ctx, arg_idx, "\xFF" "type_info"); + if (!duk_is_pointer(ctx, -1)) // missing type_info, must not be a native object + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected native object (missing type_info)", arg_idx); + + // make sure this object can be safely returned as a T* + TypeInfo* info = static_cast(duk_get_pointer(ctx, -1)); + if (!info->can_cast()) + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: wrong type of native object", arg_idx); + + duk_pop(ctx); // pop type_info + + duk_get_prop_string(ctx, arg_idx, "\xFF" "obj_ptr"); + if (!duk_is_pointer(ctx, -1)) + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: invalid native object.", arg_idx); + + T* obj = static_cast(duk_get_pointer(ctx, -1)); + + duk_pop(ctx); // pop obj_ptr + + return obj; + } + + // read reference + template::value>::type > + static T& read(duk_context* ctx, duk_idx_t arg_idx) { + T* obj = read(ctx, arg_idx); + if (obj == nullptr) + duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: cannot be null (native function expects reference)", arg_idx); + + return *obj; + } + + // read value + // commented out because it breaks for abstract classes + /*template::type >::value>::type > + static T read(duk_context* ctx, duk_idx_t arg_idx) { + static_assert(std::is_copy_constructible::value, "Reading a value requires a copy-constructable type"); + const T& obj = read(ctx, arg_idx); + return T(obj); + }*/ + + // ----------------------------------------------------- + // Writing + + // Reference + template::value>::type > + static void push(duk_context* ctx, T& value) { + using namespace dukglue::detail; + + if (!RefManager::find_and_push_native_object(ctx, &value)) { + // need to create new script object + ProtoManager::make_script_object(ctx, &value); + RefManager::register_native_object(ctx, &value); + } + } + + // Pointer + template::value>::type > + static void push(duk_context* ctx, T* value) { + if (value == nullptr) + duk_push_null(ctx); + else + push(ctx, *value); + } + + // Value (create new instance on the heap) + // commented out because this is an easy way to accidentally cause a memory leak + /*template::type >::value>::type > + static void push(duk_context* ctx, T value) { + static_assert(std::is_copy_constructible::value, "Cannot push value for non-copy-constructable type."); + return push(ctx, new T(value)); + }*/ + }; + + // Figure out what the type for an argument should be inside the tuple. + // If a function expects a reference to a value type, we need temporary storage for the value. + // For example, a reference to a value type (const int&) will need to be temporarily + // stored in the tuple, so ArgStorage::type == int. + // Native objects are already allocated on the heap, so there's no problem storing, say, const Dog& in the tuple. + template + struct ArgStorage { + private: + typedef typename Bare::type BareType; + //typedef DukType ThisDukType; + typedef typename DukType::IsValueType IsValueType; + + static_assert(!IsValueType::value || !std::is_pointer::value, "Cannot return pointer to value type."); + static_assert(!IsValueType::value || + (!std::is_reference::value || std::is_const::type>::value), + "Value types can only be returned as const references."); + + public: + typedef typename std::conditional::type type; + }; + } +} + +#include "detail_primitive_types.h" diff --git a/src/openrct2/thirdparty/dukglue/dukexception.h b/src/openrct2/thirdparty/dukglue/dukexception.h new file mode 100644 index 0000000000..7d42768ebe --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/dukexception.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +class DukException : public std::exception +{ +public: + virtual const char* what() const noexcept override + { + return mMsg.c_str(); + } + + template + DukException& operator<<(T rhs) + { + std::stringstream ss; + ss << mMsg << rhs; + mMsg = ss.str(); + return *this; + } + +protected: + std::string mMsg; +}; + +class DukErrorException : public DukException +{ +public: + DukErrorException(duk_context* ctx, int return_code, bool pop_error = true) { + if (return_code != 0) { + duk_get_prop_string(ctx, -1, "stack"); + mMsg = duk_safe_to_string(ctx, -1); + duk_pop(ctx); + + if (pop_error) + duk_pop(ctx); + } + } +}; \ No newline at end of file diff --git a/src/openrct2/thirdparty/dukglue/dukglue.h b/src/openrct2/thirdparty/dukglue/dukglue.h new file mode 100644 index 0000000000..1b62f7b9d4 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/dukglue.h @@ -0,0 +1,7 @@ +#pragma once + +#include "register_function.h" +#include "register_class.h" +#include "register_property.h" +#include "public_util.h" +#include "dukvalue.h" \ No newline at end of file diff --git a/src/openrct2/thirdparty/dukglue/dukvalue.h b/src/openrct2/thirdparty/dukglue/dukvalue.h new file mode 100644 index 0000000000..67d17da9b5 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/dukvalue.h @@ -0,0 +1,590 @@ +#pragma once + +#include +#include +#include +#include + +#include "dukexception.h" + +// A variant class for Duktape values. +// This class is not really dependant on the rest of dukglue, but the rest of dukglue is integrated to support it. +// Script objects are persisted by copying a reference to the object into an array in the heap stash. +// When we need to push a reference to the object, we just look up that reference in the stash. + +// DukValues can be copied freely. We use reference counting behind the scenes to keep track of when we need +// to remove our reference from the heap stash. Memory for reference counting is only allocated once a DukValue +// is copied (either by copy constructor or operator=). std::move can be used if you are trying to avoid ref counting +// for some reason. + +// One script object can have multiple, completely separate DukValues "pointing" to it - in this case, there will be +// multiple entries in the "ref array" that point to the same object. This will happen if the same script object is +// put on the stack and turned into a DukValue multiple times independently (copy-constructing/operator=-ing +// DukValues will not do this!). This is okay, as we are only keeping track of these objects to prevent garbage +// collection (and access them later). This could be changed to use a map structure to look up one canonical entry per +// script object in the "ref array" (I guess it would be more like a ref map in this case), but this would require a map +// lookup every time we construct a DukValue. The performance difference probably isn't *that* noticeable (a good map +// would probably be amortized constant-time lookup), but I am guessing constructing many separate DukValues that point +// to the same script object isn't a very common thing. +class DukValue { +public: + enum Type : uint8_t { + //NONE = DUK_TYPE_NONE, + UNDEFINED = DUK_TYPE_UNDEFINED, + NULLREF = DUK_TYPE_NULL, + BOOLEAN = DUK_TYPE_BOOLEAN, + NUMBER = DUK_TYPE_NUMBER, + STRING = DUK_TYPE_STRING, + OBJECT = DUK_TYPE_OBJECT, + BUFFER = DUK_TYPE_BUFFER, // not implemented + POINTER = DUK_TYPE_POINTER, + LIGHTFUNC = DUK_TYPE_LIGHTFUNC // not implemented + }; + + // default constructor just makes an undefined-type DukValue + inline DukValue() : mContext(NULL), mType(UNDEFINED), mRefCount(NULL) {} + + virtual ~DukValue() { + // release any references we have + release_ref_count(); + } + + // move constructor + inline DukValue(DukValue&& move) { + mContext = move.mContext; + mType = move.mType; + mPOD = move.mPOD; + mRefCount = move.mRefCount; + + if (mType == STRING) + mString = std::move(move.mString); + + move.mType = UNDEFINED; + move.mRefCount = NULL; + } + + inline DukValue& operator=(const DukValue& rhs) { + // free whatever we had + release_ref_count(); + + // copy things + mContext = rhs.mContext; + mType = rhs.mType; + mPOD = rhs.mPOD; + + if (mType == STRING) + mString = rhs.mString; + + if (mType == OBJECT) + { + // ref counting increment + if (rhs.mRefCount == NULL) { + // not ref counted before, need to allocate memory + const_cast(rhs).mRefCount = new int(2); + mRefCount = rhs.mRefCount; + } else { + // already refcounting, just increment + mRefCount = rhs.mRefCount; + *mRefCount = *mRefCount + 1; + } + } + + return *this; + } + + // copy constructor + inline DukValue(const DukValue& copy) : DukValue() { + *this = copy; + } + + // equality operator + inline bool operator==(const DukValue& rhs) const + { + if (mType != rhs.mType || mContext != rhs.mContext) + return false; + + switch (mType) { + case UNDEFINED: + case NULLREF: + return true; + case BOOLEAN: + return mPOD.boolean == rhs.mPOD.boolean; + case NUMBER: + return mPOD.number == rhs.mPOD.number; + case STRING: + return mString == rhs.mString; + + case OBJECT: + { + // this could be optimized to only push ref_array once... + this->push(); + rhs.push(); + bool equal = duk_equals(mContext, -1, -2) ? true : false; + duk_pop_2(mContext); + return equal; + } + + case POINTER: + return mPOD.pointer == rhs.mPOD.pointer; + + case BUFFER: + case LIGHTFUNC: + default: + throw DukException() << "operator== not implemented (" << type_name() << ")"; + } + } + + inline bool operator!=(const DukValue& rhs) const { + return !(*this == rhs); + } + + // copies the object at idx on the stack into a new DukValue and returns it + static DukValue copy_from_stack(duk_context* ctx, duk_idx_t idx = -1) { + DukValue value; + value.mContext = ctx; + value.mType = (Type) duk_get_type(ctx, idx); + switch (value.mType) { + case UNDEFINED: + break; + + case NULLREF: + value.mPOD.pointer = NULL; + break; + + case BOOLEAN: + value.mPOD.boolean = duk_require_boolean(ctx, idx) ? true : false; + break; + + case NUMBER: + value.mPOD.number = duk_require_number(ctx, idx); + break; + + case STRING: + { + duk_size_t len; + const char* data = duk_get_lstring(ctx, idx, &len); + value.mString.assign(data, len); + break; + } + + case OBJECT: + value.mPOD.ref_array_idx = stash_ref(ctx, idx); + break; + + case POINTER: + value.mPOD.pointer = duk_require_pointer(ctx, idx); + break; + + case BUFFER: + case LIGHTFUNC: + default: + throw DukException() << "Cannot turn type into DukValue (" << value.type_name() << ")"; + } + + return value; + } + +protected: + static duk_ret_t json_decode_safe(duk_context* ctx, void* user_data) + { + duk_json_decode(ctx, -1); + return 1; + } + +public: + static_assert(sizeof(char) == 1, "Serialization probably broke"); + static DukValue deserialize(duk_context* ctx, const char* data, size_t data_len) { + DukValue v; + v.mContext = ctx; + v.mType = *((Type*)data); + + const char* data_ptr = data + sizeof(Type); + data_len -= sizeof(Type); + + switch (v.mType) { + case UNDEFINED: + case NULLREF: + break; + + case BOOLEAN: + { + if (data_len < 1) + throw DukException() << "Malformed boolean data"; + + v.mPOD.boolean = data[1] == 1 ? true : false; + break; + } + + case NUMBER: + { + if (data_len < sizeof(double)) + throw DukException() << "Malformed number data"; + + v.mPOD.number = *((double*)data_ptr); + break; + } + + case STRING: + { + if (data_len < sizeof(uint32_t)) + throw DukException() << "Malformed string data (no length)"; + uint32_t str_len = *((uint32_t*)data_ptr); + + if (data_len < sizeof(uint32_t) + str_len) + throw DukException() << "Malformed string data (appears truncated)"; + + const char* str_data = (data_ptr + sizeof(uint32_t)); + v.mString.assign(str_data, str_len); + break; + } + + case OBJECT: + { + if (data_len < sizeof(uint32_t)) + throw DukException() << "Malformed object JSON data (no length)"; + uint32_t json_len = *((uint32_t*)data_ptr); + + if (data_len < sizeof(uint32_t) + json_len) + throw DukException() << "Malformed object JSON data (appears truncated)"; + + const char* json_data = (data_ptr + sizeof(uint32_t)); + duk_push_lstring(ctx, json_data, json_len); + int rc = duk_safe_call(ctx, &json_decode_safe, NULL, 1, 1); + if (rc) { + throw DukErrorException(ctx, rc) << "Could not decode JSON"; + } else { + v.mPOD.ref_array_idx = stash_ref(ctx, -1); + duk_pop(ctx); + } + break; + } + + default: + throw DukException() << "not implemented"; + } + + return v; + } + + // same as above (copy_from_stack), but also removes the value we copied from the stack + static DukValue take_from_stack(duk_context* ctx, duk_idx_t idx = -1) { + DukValue val = copy_from_stack(ctx, idx); + duk_remove(ctx, idx); + return val; + } + + // push the value we hold onto the stack + inline void push() const { + duk_context* ctx = mContext; + + switch (mType) { + case UNDEFINED: + duk_push_undefined(ctx); + break; + case NULLREF: + duk_push_null(ctx); + break; + + case BOOLEAN: + duk_push_boolean(ctx, mPOD.boolean); + break; + + case NUMBER: + duk_push_number(ctx, mPOD.number); + break; + + case STRING: + duk_push_lstring(ctx, mString.data(), mString.size()); + break; + + case OBJECT: + push_ref_array(ctx); + duk_get_prop_index(ctx, -1, mPOD.ref_array_idx); + duk_remove(ctx, -2); + break; + + case POINTER: + duk_push_pointer(ctx, mPOD.pointer); + break; + + case BUFFER: + case LIGHTFUNC: + default: + throw DukException() << "DukValue.push() not implemented for type (" << type_name() << ")"; + } + } + + // various (type-safe) getters + inline bool as_bool() const { + if (mType != BOOLEAN) + throw DukException() << "Expected boolean, got " << type_name(); + return mPOD.boolean; + } + + inline double as_double() const { + if (mType != NUMBER) + throw DukException() << "Expected number, got " << type_name(); + return mPOD.number; + } + + inline float as_float() const { + if (mType != NUMBER) + throw DukException() << "Expected number, got " << type_name(); + return static_cast(mPOD.number); + } + + inline duk_int_t as_int() const { + if (mType != NUMBER) + throw DukException() << "Expected number, got " << type_name(); + return static_cast(mPOD.number); + } + + inline duk_uint_t as_uint() const { + if (mType != NUMBER) + throw DukException() << "Expected number, got " << type_name(); + return static_cast(mPOD.number); + } + + inline void* as_pointer() const { + if (mType != POINTER && mType != NULLREF) + throw DukException() << "Expected pointer or null, got " << type_name(); + return mPOD.pointer; + } + + inline const std::string& as_string() const { + if (mType != STRING) + throw DukException() << "Expected string, got " << type_name(); + return mString; + } + + inline const char* as_c_string() const { + if (mType != STRING) + throw DukException() << "Expected string, got " << type_name(); + return mString.data(); + } + + inline Type type() const { + return mType; + } + + // same as duk_get_type_name(), but that's internal to Duktape, so we shouldn't use it + inline const char* type_name() const { + switch (mType) { + case UNDEFINED: return "undefined"; + case NULLREF: return "null"; + case BOOLEAN: return "boolean"; + case NUMBER: return "number"; + case STRING: return "string"; + case OBJECT: return "object"; + case BUFFER: return "buffer"; + case POINTER: return "pointer"; + case LIGHTFUNC: return "lightfunc"; + } + return "?"; + } + + inline duk_context* context() const { + return mContext; + } + + // Important limitations: + // - The returned value is binary and will not behave well if you treat it like a string (it will almost certainly contain '\0'). + // If you need to transport it like a string, maybe try encoding it as base64. + // - Strings longer than 2^32 (UINT32_MAX) characters will throw an exception. You can raise this to be a uint64_t if you need + // really long strings for some reason (be sure to change DukValue::deserialize() as well). + // - Objects are encoded to JSON and then sent like a string. If your object can't be encoded as JSON (i.e. it's a function), + // this will not work. This can be done, but I chose not to because it poses a security issue if you deserializing untrusted data. + // If you require this functionality, you'll have to add it yourself with using duk_dump_function(...). + static_assert(sizeof(char) == 1, "Serialization probably broke"); + std::vector serialize() const { + std::vector buff; + buff.resize(sizeof(Type)); + *((Type*)buff.data()) = mType; + + switch (mType) { + case UNDEFINED: + case NULLREF: + break; + + case BOOLEAN: + { + buff.push_back(mPOD.boolean ? 1 : 0); + break; + } + + case NUMBER: + { + buff.resize(buff.size() + sizeof(double)); + *((double*)(buff.data() + sizeof(Type))) = mPOD.number; + break; + } + + case STRING: + { + if (mString.length() > static_cast(UINT32_MAX)) + throw DukException() << "String length larger than uint32_t max"; + + uint32_t len = mString.length(); + buff.resize(buff.size() + sizeof(uint32_t) + len); + + uint32_t* len_ptr = (uint32_t*)(buff.data() + sizeof(Type)); + *len_ptr = len; + + char* out_ptr = (char*)(buff.data() + sizeof(Type) + sizeof(uint32_t)); + strncpy(out_ptr, mString.data(), len); // note: this will NOT be null-terminated + break; + } + + case OBJECT: + { + push(); + if (duk_is_function(mContext, -1)) { + duk_pop(mContext); + throw DukException() << "Functions cannot be serialized"; + // well, technically they can...see the comments at the start of this method + } + + std::string json = duk_json_encode(mContext, -1); + duk_pop(mContext); + + if (json.length() > static_cast(UINT32_MAX)) + throw DukException() << "JSON length larger than uint32_t max"; + + uint32_t len = json.length(); + buff.resize(buff.size() + sizeof(uint32_t) + len); + + uint32_t* len_ptr = (uint32_t*)(buff.data() + sizeof(Type)); + *len_ptr = len; + + char* out_ptr = (char*)(buff.data() + sizeof(Type) + sizeof(uint32_t)); + strncpy(out_ptr, json.data(), len); // note: this will NOT be null-terminated + break; + } + + default: + throw DukException() << "Type not implemented for serialization."; + } + + return buff; + } + +private: + // THIS IS COMPLETELY UNRELATED TO DETAIL_REFS.H. + // detail_refs.h stores a mapping of native object -> script object. + // This just stores arbitrary script objects (which likely have no native object backing them). + // If I was smarter I might merge the two implementations, but this one is simpler + // (since we don't need the std::map here). + static void push_ref_array(duk_context* ctx) + { + static const char* DUKVALUE_REF_ARRAY = "dukglue_dukvalue_refs"; + duk_push_heap_stash(ctx); + + if (!duk_has_prop_string(ctx, -1, DUKVALUE_REF_ARRAY)) { + duk_push_array(ctx); + + // ref_array[0] = 0 (initialize free list as empty) + duk_push_int(ctx, 0); + duk_put_prop_index(ctx, -2, 0); + + duk_put_prop_string(ctx, -2, DUKVALUE_REF_ARRAY); + } + + duk_get_prop_string(ctx, -1, DUKVALUE_REF_ARRAY); + duk_remove(ctx, -2); // pop heap stash + } + + // put a new reference into the ref array and return its index in the array + static duk_uint_t stash_ref(duk_context* ctx, duk_idx_t idx) + { + push_ref_array(ctx); + + // if idx is relative, we need to adjust it to deal with the array we just pushed + if (idx < 0) + idx--; + + // find next free index + // free indices are kept in a linked list, starting at ref_array[0] + duk_get_prop_index(ctx, -1, 0); + duk_uarridx_t next_free_idx = duk_get_uint(ctx, -1); + duk_pop(ctx); + + if (next_free_idx == 0) { + // no free spots in the array, make a new one at arr.length + next_free_idx = duk_get_length(ctx, -1); + } else { + // free spot found, need to remove it from the free list + // ref_array[0] = ref_array[next_free_idx] + duk_get_prop_index(ctx, -1, next_free_idx); + duk_put_prop_index(ctx, -2, 0); + } + + duk_dup(ctx, idx); // copy value we are storing (since store consumes it) + duk_put_prop_index(ctx, -2, next_free_idx); // store it (consumes duplicated value) + duk_pop(ctx); // pop ref array + + return next_free_idx; + } + + // remove ref_array_idx from the ref array and add its spot to the free list (at refs[0]) + static void free_ref(duk_context* ctx, duk_uarridx_t ref_array_idx) + { + push_ref_array(ctx); + + // add this spot to the free list + // refs[old_obj_idx] = refs[0] (implicitly gives up our reference) + duk_get_prop_index(ctx, -1, 0); + duk_put_prop_index(ctx, -2, ref_array_idx); + + // refs[0] = old_obj_idx + duk_push_uint(ctx, ref_array_idx); + duk_put_prop_index(ctx, -2, 0); + + duk_pop(ctx); // pop ref array + } + + // this is for reference counting - used to release our reference based on the state + // of mRefCount. If mRefCount is NULL, we never got copy constructed, so we have ownership + // of our reference and can free it. If it's not null and above 1, we decrement the counter + // (someone else owns the reference). If it's not null and equal to 1, we are the last owner + // of a previously shared reference, so we can free it. + void release_ref_count() + { + if (mType == OBJECT) + { + if (mRefCount != NULL) + { + // sharing with another DukValue, are we the only one left? + if (*mRefCount > 1) { // still someone else referencing this + *mRefCount = *mRefCount - 1; + } else { + // not sharing anymore, we can free it + free_ref(mContext, mPOD.ref_array_idx); + delete mRefCount; + } + + mRefCount = NULL; + } else { + // not sharing with any other DukValue, free it + free_ref(mContext, mPOD.ref_array_idx); + } + + mType = UNDEFINED; + } + } + + duk_context* mContext; + Type mType; // our type - one of the standard Duktape DUK_TYPE_* values + + // This holds the plain-old-data types. Since this is a variant, + // we hold only one value at a time, so this is a union to save + // a bit of space. + union ValueTypes { + bool boolean; + double number; + void* pointer; // if mType == NULLREF, this is 0 (otherwise holds pointer value when mType == POINTER) + duk_uarridx_t ref_array_idx; + } mPOD; + + std::string mString; // if it's a string, we store it with std::string + int* mRefCount; // if mType == OBJECT and we're sharing, this will point to our ref counter +}; \ No newline at end of file diff --git a/src/openrct2/thirdparty/dukglue/public_util.h b/src/openrct2/thirdparty/dukglue/public_util.h new file mode 100644 index 0000000000..d6ff344d8f --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/public_util.h @@ -0,0 +1,315 @@ +#pragma once + +#include "dukexception.h" +#include "detail_traits.h" // for index_tuple/make_indexes + +// This file has some useful utility functions for users. +// Hopefully this saves you from wading through the implementation. + +/** + * @brief Push a value onto the duktape stack. + * + * WARNING: THIS IS NOT "PROTECTED." If an error occurs when pushing (unlikely, but possible), + * the Duktape fatal error handler will be invoked (and the program will probably terminate). + * + * @param ctx duktape context + * @param[in] val value to push + */ +template +void dukglue_push(duk_context* ctx, const FullT& val) { + // ArgStorage has some static_asserts in it that validate value types, + // so we typedef it to force ArgStorage to compile and run the asserts + typedef typename dukglue::types::ArgStorage::type ValidateReturnType; + + using namespace dukglue::types; + DukType::type>::template push(ctx, std::move(val)); +} + +template +void dukglue_push(duk_context* ctx, const T& arg, ArgTs... args) +{ + dukglue_push(ctx, arg); + dukglue_push(ctx, args...); +} + +inline void dukglue_push(duk_context* ctx) +{ + // no-op +} + + +/** + * WARNING: THIS IS NOT "PROTECTED." If an error occurs while reading (which is possible if you didn't + * explicitly check the type), the fatal Duktape error handler will be invoked, and the program + * will probably abort. + */ +template +void dukglue_read(duk_context* ctx, duk_idx_t arg_idx, RetT* out) +{ + // ArgStorage has some static_asserts in it that validate value types, + // so we typedef it to force ArgStorage to compile and run the asserts + typedef typename dukglue::types::ArgStorage::type ValidateReturnType; + + using namespace dukglue::types; + *out = DukType::type>::template read(ctx, arg_idx); +} + + +// methods + +// leaves return value on stack +template +void dukglue_call_method(duk_context* ctx, const ObjT& obj, const char* method_name, ArgTs... args) +{ + dukglue_push(ctx, obj); + duk_get_prop_string(ctx, -1, method_name); + + if (duk_check_type(ctx, -1, DUK_TYPE_UNDEFINED)) { + duk_error(ctx, DUK_ERR_REFERENCE_ERROR, "Method does not exist", method_name); + return; + } + + if (!duk_is_callable(ctx, -1)) { + duk_error(ctx, DUK_ERR_TYPE_ERROR, "Property is not callable"); + return; + } + + duk_swap_top(ctx, -2); + dukglue_push(ctx, args...); + duk_call_method(ctx, sizeof...(args)); +} + +namespace dukglue { +namespace detail { + +template +struct SafeMethodCallData { + const ObjT* obj; + const char* method_name; + std::tuple args; + RetT* out; +}; + +template +void call_method_safe_helper(duk_context* ctx, const ObjT& obj, const char* method_name, std::tuple& tup, index_tuple indexes) +{ + dukglue_call_method(ctx, obj, method_name, std::forward(std::get(tup))...); +} + +template +typename std::enable_if::value, duk_idx_t>::type call_method_safe(duk_context* ctx, void* udata) +{ + typedef SafeMethodCallData DataT; + DataT* data = (DataT*) udata; + call_method_safe_helper(ctx, *(data->obj), data->method_name, data->args, typename make_indexes::type()); + return 1; +} + +template +typename std::enable_if::value, duk_idx_t>::type call_method_safe(duk_context* ctx, void* udata) +{ + typedef SafeMethodCallData DataT; + DataT* data = (DataT*)udata; + + call_method_safe_helper(ctx, *(data->obj), data->method_name, data->args, typename make_indexes::type()); + dukglue_read(ctx, -1, data->out); + return 1; +} + +} +} + +template +typename std::enable_if::value, RetT>::type dukglue_pcall_method(duk_context* ctx, const ObjT& obj, const char* method_name, ArgTs... args) +{ + dukglue::detail::SafeMethodCallData data { + &obj, method_name, std::tuple(args...), nullptr + }; + + duk_idx_t rc = duk_safe_call(ctx, &dukglue::detail::call_method_safe, (void*) &data, 0, 1); + if (rc != 0) + throw DukErrorException(ctx, rc); + + duk_pop(ctx); // remove result from stack +} + +template +typename std::enable_if::value, RetT>::type dukglue_pcall_method(duk_context* ctx, const ObjT& obj, const char* method_name, ArgTs... args) +{ + RetT out; + dukglue::detail::SafeMethodCallData data { + &obj, method_name, std::tuple(args...), &out + }; + + duk_idx_t rc = duk_safe_call(ctx, &dukglue::detail::call_method_safe, (void*) &data, 0, 1); + if (rc != 0) + throw DukErrorException(ctx, rc); + + duk_pop(ctx); // remove result from stack + return std::move(out); +} + + +// calls + +// leaves return value on the stack +template +void dukglue_call(duk_context* ctx, const ObjT& func, ArgTs... args) +{ + dukglue_push(ctx, func); + if (!duk_is_callable(ctx, -1)) { + duk_pop(ctx); + duk_error(ctx, DUK_ERR_TYPE_ERROR, "Object is not callable"); + return; + } + + dukglue_push(ctx, args...); + duk_call(ctx, sizeof...(args)); +} + + +// safe call +namespace dukglue { +namespace detail { + +template +struct SafeCallData { + const ObjT* obj; + std::tuple args; + RetT* out; +}; + +template +void call_safe_helper(duk_context* ctx, const ObjT& obj, std::tuple& tup, index_tuple indexes) +{ + dukglue_call(ctx, obj, std::forward(std::get(tup))...); +} + +// leaves result on stack +template +typename std::enable_if::value, duk_ret_t>::type call_safe(duk_context* ctx, void* udata) +{ + typedef SafeCallData DataT; + DataT* data = (DataT*)udata; + + call_safe_helper(ctx, *(data->obj), data->args, typename make_indexes::type()); + return 1; +} + +// leaves result on stack +// The result is read into RetT here because it can potentially trigger an error (with duk_error). +// If we did it "above" this function, that error would trigger a panic instead of error handling. +template +typename std::enable_if::value, duk_ret_t>::type call_safe(duk_context* ctx, void* udata) +{ + typedef SafeCallData DataT; + DataT* data = (DataT*)udata; + + call_safe_helper(ctx, *(data->obj), data->args, typename make_indexes::type()); + dukglue_read(ctx, -1, data->out); + return 1; +} + +} +} + +// Unlike duktape, this will remove the return value from the stack! +template +typename std::enable_if::value, RetT>::type dukglue_pcall(duk_context* ctx, const ObjT& obj, ArgTs... args) +{ + dukglue::detail::SafeCallData data{ + &obj, std::tuple(args...), nullptr + }; + + duk_int_t rc = duk_safe_call(ctx, &dukglue::detail::call_safe, (void*) &data, 0, 1); + if (rc != 0) + throw DukErrorException(ctx, rc); + duk_pop(ctx); // remove result from stack +} + +template +typename std::enable_if::value, RetT>::type dukglue_pcall(duk_context* ctx, const ObjT& obj, ArgTs... args) +{ + RetT result; + dukglue::detail::SafeCallData data{ + &obj, std::tuple(args...), &result + }; + + duk_int_t rc = duk_safe_call(ctx, &dukglue::detail::call_safe, (void*) &data, 0, 1); + if (rc != 0) + throw DukErrorException(ctx, rc); + + duk_pop(ctx); // remove result from stack + return std::move(result); +} + +// same as dukglue_pcall, but leaves the result or error on the stack and returns the Duktape return code +template +duk_int_t dukglue_pcall_raw(duk_context* ctx, const ObjT& obj, ArgTs... args) +{ + dukglue::detail::SafeCallData data{ + &obj, std::tuple(args...), nullptr + }; + + return duk_safe_call(ctx, &dukglue::detail::call_safe, (void*)&data, 0, 1); +} + + +// peval +namespace dukglue { +namespace detail { + +template +struct SafeEvalData { + const char* str; + RetT* out; +}; + +template +duk_ret_t eval_safe(duk_context* ctx, void* udata) +{ + SafeEvalData* data = (SafeEvalData*) udata; + + duk_eval_string(ctx, data->str); + dukglue_read(ctx, -1, data->out); + return 1; +} + +} +} + +template +typename std::enable_if::value, RetT>::type dukglue_peval(duk_context* ctx, const char* str) +{ + int prev_top = duk_get_top(ctx); + int rc = duk_peval_string(ctx, str); + if (rc != 0) + throw DukErrorException(ctx, rc); + + duk_pop_n(ctx, duk_get_top(ctx) - prev_top); // pop any results +} + +template +typename std::enable_if::value, RetT>::type dukglue_peval(duk_context* ctx, const char* str) +{ + int prev_top = duk_get_top(ctx); + + RetT ret; + dukglue::detail::SafeEvalData data{ + str, &ret + }; + + int rc = duk_safe_call(ctx, &dukglue::detail::eval_safe, (void*) &data, 0, 1); + if (rc != 0) + throw DukErrorException(ctx, rc); + duk_pop_n(ctx, duk_get_top(ctx) - prev_top); // pop any results + return ret; +} + +// register a global object (very simple helper, but very common for "Hello World"-ish applications) +template +inline void dukglue_register_global(duk_context* ctx, const T& obj, const char* name) +{ + dukglue_push(ctx, obj); + duk_put_global_string(ctx, name); +} \ No newline at end of file diff --git a/src/openrct2/thirdparty/dukglue/register_class.h b/src/openrct2/thirdparty/dukglue/register_class.h new file mode 100644 index 0000000000..bb7669029f --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/register_class.h @@ -0,0 +1,202 @@ +#pragma once + +#include "detail_class_proto.h" +#include "detail_constructor.h" +#include "detail_method.h" + +// Set the constructor for the given type. +template +void dukglue_register_constructor(duk_context* ctx, const char* name) +{ + duk_c_function constructor_func = dukglue::detail::call_native_constructor; + + duk_push_c_function(ctx, constructor_func, sizeof...(Ts)); + + // set constructor_func.prototype + dukglue::detail::ProtoManager::push_prototype(ctx); + duk_put_prop_string(ctx, -2, "prototype"); + + // set name = constructor_func + duk_put_global_string(ctx, name); +} + +template +void dukglue_register_constructor_managed(duk_context* ctx, const char* name) +{ + duk_c_function constructor_func = dukglue::detail::call_native_constructor; + duk_c_function finalizer_func = dukglue::detail::managed_finalizer; + + duk_push_c_function(ctx, constructor_func, sizeof...(Ts)); + + // create new prototype with finalizer + duk_push_object(ctx); + + // set the finalizer + duk_push_c_function(ctx, finalizer_func, 1); + duk_set_finalizer(ctx, -2); + + // hook prototype with finalizer up to real class prototype + // must use duk_set_prototype, not set the .prototype property + dukglue::detail::ProtoManager::push_prototype(ctx); + duk_set_prototype(ctx, -2); + + // set constructor_func.prototype to the prototype with the finalizer + duk_put_prop_string(ctx, -2, "prototype"); + + // set name = constructor_func + duk_put_global_string(ctx, name); +} + +template +void dukglue_set_base_class(duk_context* ctx) +{ + static_assert(!std::is_pointer::value && !std::is_pointer::value + && !std::is_const::value && !std::is_const::value, "Use bare class names."); + static_assert(std::is_base_of::value, "Invalid class hierarchy!"); + + using namespace dukglue::detail; + + // Derived.type_info->set_base(Base.type_info) + ProtoManager::push_prototype(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "type_info"); + TypeInfo* derived_type_info = static_cast(duk_require_pointer(ctx, -1)); + duk_pop_2(ctx); + + ProtoManager::push_prototype(ctx); + duk_get_prop_string(ctx, -1, "\xFF" "type_info"); + TypeInfo* base_type_info = static_cast(duk_require_pointer(ctx, -1)); + duk_pop_2(ctx); + + derived_type_info->set_base(base_type_info); + + // also set up the prototype chain + ProtoManager::push_prototype(ctx); + ProtoManager::push_prototype(ctx); + duk_set_prototype(ctx, -2); + duk_pop(ctx); +} + +// methods +template +void dukglue_register_method_compiletime(duk_context* ctx, RetType(Cls::*method)(Ts...), const char* name) +{ + static_assert(std::is_same::value, "Mismatching method types."); + dukglue_register_method_compiletime(ctx, name); +} + +template +void dukglue_register_method_compiletime(duk_context* ctx, RetType(Cls::*method)(Ts...) const, const char* name) +{ + static_assert(std::is_same::value, "Mismatching method types."); + dukglue_register_method_compiletime(ctx, name); +} + +template +void dukglue_register_method_compiletime(duk_context* ctx, const char* name) +{ + using namespace dukglue::detail; + typedef MethodInfo MethodInfo; + + duk_c_function method_func = MethodInfo::template MethodCompiletime::call_native_method; + + ProtoManager::push_prototype(ctx); + + duk_push_c_function(ctx, method_func, sizeof...(Ts)); + duk_put_prop_string(ctx, -2, name); // consumes func above + + duk_pop(ctx); // pop prototype +} + +template +void dukglue_register_method(duk_context* ctx, RetType(Cls::*method)(Ts...), const char* name) +{ + dukglue_register_method(ctx, method, name); +} + +template +void dukglue_register_method(duk_context* ctx, RetType(Cls::*method)(Ts...) const, const char* name) +{ + dukglue_register_method(ctx, method, name); +} + +// I'm sorry this signature is so long, but I figured it was better than duplicating the method, +// once for const methods and once for non-const methods. +template +void dukglue_register_method(duk_context* ctx, typename std::conditional::type method, const char* name) +{ + using namespace dukglue::detail; + typedef MethodInfo MethodInfo; + + duk_c_function method_func = MethodInfo::MethodRuntime::call_native_method; + + ProtoManager::push_prototype(ctx); + + duk_push_c_function(ctx, method_func, sizeof...(Ts)); + + duk_push_pointer(ctx, new typename MethodInfo::MethodHolder{ method }); + duk_put_prop_string(ctx, -2, "\xFF" "method_holder"); // consumes raw method pointer + + // make sure we free the method_holder when this function is removed + duk_push_c_function(ctx, MethodInfo::MethodRuntime::finalize_method, 1); + duk_set_finalizer(ctx, -2); + + duk_put_prop_string(ctx, -2, name); // consumes method function + + duk_pop(ctx); // pop prototype +} + +// methods with a variable number of (script) arguments +template +inline void dukglue_register_method_varargs(duk_context* ctx, duk_ret_t(Cls::*method)(duk_context*), const char* name) +{ + dukglue_register_method_varargs(ctx, method, name); +} + +template +inline void dukglue_register_method_varargs(duk_context* ctx, duk_ret_t(Cls::*method)(duk_context*) const, const char* name) +{ + dukglue_register_method_varargs(ctx, method, name); +} + +template +void dukglue_register_method_varargs(duk_context* ctx, + typename std::conditional::type method, + const char* name) +{ + using namespace dukglue::detail; + typedef MethodVariadicRuntime MethodVariadicInfo; + + duk_c_function method_func = MethodVariadicInfo::call_native_method; + + ProtoManager::push_prototype(ctx); + + duk_push_c_function(ctx, method_func, DUK_VARARGS); + + duk_push_pointer(ctx, new typename MethodVariadicInfo::MethodHolderVariadic{ method }); + duk_put_prop_string(ctx, -2, "\xFF" "method_holder"); // consumes raw method pointer + + // make sure we free the method_holder when this function is removed + duk_push_c_function(ctx, MethodVariadicInfo::finalize_method, 1); + duk_set_finalizer(ctx, -2); + + duk_put_prop_string(ctx, -2, name); // consumes method function + + duk_pop(ctx); // pop prototype +} + +inline void dukglue_invalidate_object(duk_context* ctx, void* obj_ptr) +{ + dukglue::detail::RefManager::find_and_invalidate_native_object(ctx, obj_ptr); +} + +// register a deleter +template +void dukglue_register_delete(duk_context* ctx) +{ + duk_c_function delete_func = dukglue::detail::call_native_deleter; + + dukglue::detail::ProtoManager::push_prototype(ctx); + duk_push_c_function(ctx, delete_func, 0); + duk_put_prop_string(ctx, -2, "delete"); + duk_pop(ctx); // pop prototype +} \ No newline at end of file diff --git a/src/openrct2/thirdparty/dukglue/register_function.h b/src/openrct2/thirdparty/dukglue/register_function.h new file mode 100644 index 0000000000..77e83aad95 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/register_function.h @@ -0,0 +1,35 @@ +#pragma once + +#include "detail_function.h" + +// Register a function, embedding the function address at compile time. +// According to benchmarks, there's really not much reason to do this +// (inconsistent 2-3% performance improvement for a 10,000 function call stress test averaged over 100 runs), +// since it has much uglier syntax and may bloat executable size if you have many functions with identical signatures. +template +void dukglue_register_function_compiletime(duk_context* ctx, RetType(*)(Ts...), const char* name) +{ + static_assert(std::is_same::value, + "Mismatching function pointer template parameter and function pointer argument types. " + "Try: dukglue_register_function(ctx, \"funcName\", func)"); + + duk_c_function evalFunc = dukglue::detail::FuncInfoHolder::template FuncActual::call_native_function; + + duk_push_c_function(ctx, evalFunc, sizeof...(Ts)); + duk_put_global_string(ctx, name); +} + +// Register a function. +template +void dukglue_register_function(duk_context* ctx, RetType(*funcToCall)(Ts...), const char* name) +{ + duk_c_function evalFunc = dukglue::detail::FuncInfoHolder::FuncRuntime::call_native_function; + + duk_push_c_function(ctx, evalFunc, sizeof...(Ts)); + + static_assert(sizeof(RetType(*)(Ts...)) == sizeof(void*), "Function pointer and data pointer are different sizes"); + duk_push_pointer(ctx, reinterpret_cast(funcToCall)); + duk_put_prop_string(ctx, -2, "\xFF" "func_ptr"); + + duk_put_global_string(ctx, name); +} diff --git a/src/openrct2/thirdparty/dukglue/register_property.h b/src/openrct2/thirdparty/dukglue/register_property.h new file mode 100644 index 0000000000..c4fd8b36b7 --- /dev/null +++ b/src/openrct2/thirdparty/dukglue/register_property.h @@ -0,0 +1,123 @@ +#pragma once + +#include "detail_method.h" + +// const getter, setter +template +void dukglue_register_property(duk_context* ctx, + RetT(Cls::*getter)() const, + void(Cls::*setter)(ArgT), + const char* name) +{ + dukglue_register_property(ctx, getter, setter, name); +} + +// const getter, no setter +template +void dukglue_register_property(duk_context* ctx, + RetT(Cls::*getter)() const, + std::nullptr_t setter, + const char* name) +{ + dukglue_register_property(ctx, getter, setter, name); +} + +// non-const getter, setter +template +void dukglue_register_property(duk_context* ctx, + RetT(Cls::*getter)(), + void(Cls::*setter)(ArgT), + const char* name) +{ + dukglue_register_property(ctx, getter, setter, name); +} + +// non-const getter, no setter +template +void dukglue_register_property(duk_context* ctx, + RetT(Cls::*getter)(), + std::nullptr_t setter, + const char* name) +{ + dukglue_register_property(ctx, getter, setter, name); +} + +// no getter, setter +template +void dukglue_register_property(duk_context* ctx, + std::nullptr_t getter, + void(Cls::*setter)(ArgT), + const char* name) +{ + dukglue_register_property(ctx, getter, setter, name); +} + +// no getter, no setter +template +void dukglue_register_property(duk_context* ctx, std::nullptr_t getter, std::nullptr_t setter, const char* name) +{ + // strictly speaking I think duktape can probably handle neither + // (according to the wonderful API docs), but I don't know why you + // would want to do this in the first place + static_assert(std::is_void::value, "Must have getter or setter"); +} + +inline duk_ret_t dukglue_throw_error(duk_context* ctx) +{ + duk_error(ctx, DUK_ERR_TYPE_ERROR, "Property does not have getter or setter."); +} + +template +void dukglue_register_property(duk_context* ctx, + typename std::conditional::type getter, + void(Cls::*setter)(ArgT), + const char* name) +{ + using namespace dukglue::detail; + typedef MethodInfo GetterMethodInfo; + typedef MethodInfo SetterMethodInfo; + + ProtoManager::push_prototype(ctx); + + // push key + duk_push_string(ctx, name); + + // push getter + if (getter != nullptr) { + duk_c_function method_func = GetterMethodInfo::MethodRuntime::call_native_method; + + duk_push_c_function(ctx, method_func, 0); + + duk_push_pointer(ctx, new typename GetterMethodInfo::MethodHolder{ getter }); + duk_put_prop_string(ctx, -2, "\xFF" "method_holder"); // consumes raw method pointer + + // make sure we free the method_holder when this function is removed + duk_push_c_function(ctx, GetterMethodInfo::MethodRuntime::finalize_method, 1); + duk_set_finalizer(ctx, -2); + } else { + duk_push_c_function(ctx, dukglue_throw_error, 1); + } + + if (setter != nullptr) { + duk_c_function method_func = SetterMethodInfo::MethodRuntime::call_native_method; + + duk_push_c_function(ctx, method_func, 1); + + duk_push_pointer(ctx, new typename SetterMethodInfo::MethodHolder{ setter }); + duk_put_prop_string(ctx, -2, "\xFF" "method_holder"); // consumes raw method pointer + + // make sure we free the method_holder when this function is removed + duk_push_c_function(ctx, SetterMethodInfo::MethodRuntime::finalize_method, 1); + duk_set_finalizer(ctx, -2); + } else { + duk_push_c_function(ctx, dukglue_throw_error, 1); + } + + duk_uint_t flags = DUK_DEFPROP_HAVE_GETTER + | DUK_DEFPROP_HAVE_SETTER + | DUK_DEFPROP_HAVE_CONFIGURABLE /* set not configurable (from JS) */ + | DUK_DEFPROP_FORCE /* allow overriding built-ins and previously defined properties */; + + duk_def_prop(ctx, -4, flags); + duk_pop(ctx); // pop prototype +} From 839dd6842bfb2118ee46d7eca57615e01ce7ccd5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 17 Mar 2018 23:26:55 +0000 Subject: [PATCH 005/159] Add console API using dukglue --- src/openrct2/scripting/ScConsole.hpp | 32 +++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 29 ++++++++++++++++++---- src/openrct2/scripting/ScriptEngine.h | 4 +++- 3 files changed, 59 insertions(+), 6 deletions(-) create mode 100644 src/openrct2/scripting/ScConsole.hpp diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp new file mode 100644 index 0000000000..9d293bacbc --- /dev/null +++ b/src/openrct2/scripting/ScConsole.hpp @@ -0,0 +1,32 @@ +#include +#include "../interface/Console.h" + +namespace OpenRCT2::Scripting +{ + class ScConsole + { + private: + InteractiveConsole& _console; + public: + ScConsole(InteractiveConsole& console) : + _console(console) + { + } + + void clear() + { + _console.Clear(); + } + + void log(const std::string &s) + { + _console.WriteLine(s); + } + + static void Register(duk_context * ctx) + { + dukglue_register_method(ctx, &ScConsole::clear, "clear"); + dukglue_register_method(ctx, &ScConsole::log, "log"); + } + }; +} diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index e3b6f89959..ab250e2ddb 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -9,9 +9,13 @@ #include "ScriptEngine.h" #include "../interface/InteractiveConsole.h" +#include #include +#include #include +#include "ScConsole.hpp" + using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -21,11 +25,6 @@ ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& en _console(console), _env(env) { - _context = duk_create_heap_default(); - if (_context == nullptr) - { - throw std::runtime_error("Unable to initialise duktape context."); - } } ScriptEngine::~ScriptEngine() @@ -33,8 +32,28 @@ ScriptEngine::~ScriptEngine() duk_destroy_heap(_context); } +void ScriptEngine::Initialise() +{ + _context = duk_create_heap_default(); + if (_context == nullptr) + { + throw std::runtime_error("Unable to initialise duktape context."); + } + + auto ctx = _context; + ScConsole::Register(ctx); + + auto scConsole = std::make_shared(_console); + dukglue_register_global(ctx, scConsole, "console"); +} + void ScriptEngine::Update() { + if (!_initialised) + { + Initialise(); + _initialised = true; + } while (_evalQueue.size() > 0) { auto item = std::move(_evalQueue.front()); diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index e04550da91..e7673978a9 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -31,7 +31,8 @@ namespace OpenRCT2::Scripting private: InteractiveConsole& _console; IPlatformEnvironment& _env; - duk_context * _context; + bool _initialised{}; + duk_context * _context{}; std::queue, std::string>> _evalQueue; public: @@ -39,6 +40,7 @@ namespace OpenRCT2::Scripting ScriptEngine(ScriptEngine&&) = delete; ~ScriptEngine(); + void Initialise(); void Update(); std::future Eval(const std::string &s); }; From 1acf1e870a6ce6b9bc590e4cad3fb35d1f5bcde0 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 18 Mar 2018 00:31:02 +0000 Subject: [PATCH 006/159] Add park API --- src/openrct2/Context.cpp | 6 +- src/openrct2/scripting/ScPark.hpp | 103 +++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 6 +- src/openrct2/thirdparty/dukglue/dukvalue.h | 8 ++ 4 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 src/openrct2/scripting/ScPark.hpp diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 027396a382..22f611c03d 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -834,11 +834,7 @@ namespace OpenRCT2 } #endif // DISABLE_NETWORK - // For now, only allow interactive console in headless mode - if (gOpenRCT2Headless) - { - _stdInOutConsole.Start(); - } + _stdInOutConsole.Start(); RunGameLoop(); } diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp new file mode 100644 index 0000000000..b8512d122b --- /dev/null +++ b/src/openrct2/scripting/ScPark.hpp @@ -0,0 +1,103 @@ +#include +#include +#include "../common.h" +#include "../Context.h" +#include "../management/Finance.h" +#include "../management/NewsItem.h" +#include "../windows/Intent.h" +#include "../world/Park.h" + +namespace OpenRCT2::Scripting +{ + class ScPark + { + public: + money32 cash_get() { return gCash; } + void cash_set(money32 value) + { + gCash = value; + auto intent = Intent(INTENT_ACTION_UPDATE_CASH); + context_broadcast_intent(&intent); + } + + sint32 rating_get() { return gParkRating; } + void rating_set(sint32 value) + { + gParkRating = std::min(std::max(0, value), 999); + auto intent = Intent(INTENT_ACTION_UPDATE_PARK_RATING); + context_broadcast_intent(&intent); + } + + money32 bankLoan_get() { return gBankLoan; } + void bankLoan_set(money32 value) + { + gBankLoan = value; + auto intent = Intent(INTENT_ACTION_UPDATE_CASH); + context_broadcast_intent(&intent); + } + + money32 maxBankLoan_get() { return gMaxBankLoan; } + void maxBankLoan_set(money32 value) + { + gMaxBankLoan = value; + auto intent = Intent(INTENT_ACTION_UPDATE_CASH); + context_broadcast_intent(&intent); + } + + void postMessage(DukValue message) + { + try + { + uint8 type = NEWS_ITEM_BLANK; + std::string text; + if (message.type() == DukValue::Type::STRING) + { + text = message.as_string(); + } + else + { + type = GetParkMessageType(message["type"].as_string()); + text = message["text"].as_string(); + } + news_item_add_to_queue_raw(type, text.c_str(), -1); + } + catch (const std::exception&) + { + } + } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScPark::cash_get, &ScPark::cash_set, "cash"); + dukglue_register_property(ctx, &ScPark::rating_get, &ScPark::rating_set, "rating"); + dukglue_register_property(ctx, &ScPark::bankLoan_get, &ScPark::bankLoan_set, "bankLoan"); + dukglue_register_property(ctx, &ScPark::maxBankLoan_get, &ScPark::maxBankLoan_set, "maxBankLoan"); + dukglue_register_method(ctx, &ScPark::postMessage, "postMessage"); + } + + private: + uint8 GetParkMessageType(const std::string& key) + { + static constexpr auto keys = { + "attraction", + "peep_on_attraction", + "peep", + "money", + "blank", + "research", + "guests", + "award", + "chart" }; + uint8 i = 0; + for (const auto& k : keys) + { + if (k == key) + { + return NEWS_ITEM_RIDE + i; + } + i++; + } + return NEWS_ITEM_BLANK; + } + }; +} diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index ab250e2ddb..898fe7d2c2 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -15,6 +15,7 @@ #include #include "ScConsole.hpp" +#include "ScPark.hpp" using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -42,9 +43,10 @@ void ScriptEngine::Initialise() auto ctx = _context; ScConsole::Register(ctx); + ScPark::Register(ctx); - auto scConsole = std::make_shared(_console); - dukglue_register_global(ctx, scConsole, "console"); + dukglue_register_global(ctx, std::make_shared(_console), "console"); + dukglue_register_global(ctx, std::make_shared(), "park"); } void ScriptEngine::Update() diff --git a/src/openrct2/thirdparty/dukglue/dukvalue.h b/src/openrct2/thirdparty/dukglue/dukvalue.h index 67d17da9b5..e0a0782be5 100644 --- a/src/openrct2/thirdparty/dukglue/dukvalue.h +++ b/src/openrct2/thirdparty/dukglue/dukvalue.h @@ -587,4 +587,12 @@ private: std::string mString; // if it's a string, we store it with std::string int* mRefCount; // if mType == OBJECT and we're sharing, this will point to our ref counter + +public: + DukValue operator [](const std::string &key) const + { + push(); + duk_get_prop_string(mContext, -1, key.c_str()); + return DukValue::take_from_stack(mContext); + } }; \ No newline at end of file From 1ae9e531ce9770c0f6a57dbb6fec5f642cd7064e Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 18 Mar 2018 01:55:12 +0000 Subject: [PATCH 007/159] Update plugin definition file --- distribution/openrct2.d.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 57ed804cce..540d01e2de 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -9,7 +9,14 @@ // OpenRCT2 Scripting API definition file +// To enable IntelliSense for your scripts in Visual Studio or Visual Studio Code, +// add the following line to the top of your script and change the path appropriately. +// +// /// +// + export interface Console { + clear(): void; log(message?: any, ...optionalParams: any[]): void; } @@ -83,12 +90,15 @@ export interface WindowDesc { export interface Ui { openWindow(desc: WindowDesc): Window; - closeWindow(window: Window); + closeWindow(window: Window): void; closeWindows(classification: string, id?: number): void; closeAllWindows(): void; } -declare var context: Context; -declare var map: Map; -declare var park: Park; -declare var ui: Ui; +declare global { + var console: Console; + var context: Context; + var map: Map; + var park: Park; + var ui: Ui; +} From de527b3ff7eee294298fdd28251a626513bf2405 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 18 Mar 2018 16:27:48 +0000 Subject: [PATCH 008/159] Add load and start plugin scripts --- src/openrct2/PlatformEnvironment.cpp | 2 + src/openrct2/PlatformEnvironment.h | 1 + src/openrct2/scripting/Plugin.cpp | 110 +++++++++++++++++++++ src/openrct2/scripting/Plugin.h | 52 ++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 35 +++++++ src/openrct2/scripting/ScriptEngine.h | 10 +- src/openrct2/thirdparty/dukglue/dukvalue.h | 30 ++++++ 7 files changed, 238 insertions(+), 2 deletions(-) create mode 100644 src/openrct2/scripting/Plugin.cpp create mode 100644 src/openrct2/scripting/Plugin.h diff --git a/src/openrct2/PlatformEnvironment.cpp b/src/openrct2/PlatformEnvironment.cpp index 98a35f5f4e..8c5f781301 100644 --- a/src/openrct2/PlatformEnvironment.cpp +++ b/src/openrct2/PlatformEnvironment.cpp @@ -194,6 +194,7 @@ const char * PlatformEnvironment::DirectoryNamesRCT2[] = nullptr, // LOG_SERVER nullptr, // NETWORK_KEY "ObjData", // OBJECT + nullptr, // PLUGIN "Saved Games", // SAVE "Scenarios", // SCENARIO nullptr, // SCREENSHOT @@ -212,6 +213,7 @@ const char * PlatformEnvironment::DirectoryNamesOpenRCT2[] = "serverlogs", // LOG_SERVER "keys", // NETWORK_KEY "object", // OBJECT + "plugin", // PLUGIN "save", // SAVE "scenario", // SCENARIO "screenshot", // SCREENSHOT diff --git a/src/openrct2/PlatformEnvironment.h b/src/openrct2/PlatformEnvironment.h index 2df41e60ee..a17974e455 100644 --- a/src/openrct2/PlatformEnvironment.h +++ b/src/openrct2/PlatformEnvironment.h @@ -38,6 +38,7 @@ namespace OpenRCT2 LOG_SERVER, // Contains server logs. NETWORK_KEY, // Contains the user's public and private keys. OBJECT, // Contains objects. + PLUGIN, // Contains plugins (.js). SAVE, // Contains saved games (SV6). SCENARIO, // Contains scenarios (SC6). SCREENSHOT, // Contains screenshots. diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp new file mode 100644 index 0000000000..0da56f3005 --- /dev/null +++ b/src/openrct2/scripting/Plugin.cpp @@ -0,0 +1,110 @@ +#pragma region Copyright (c) 2014-2018 OpenRCT2 Developers +/***************************************************************************** + * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. + * + * OpenRCT2 is the work of many authors, a full list can be found in contributors.md + * For more information, visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * A full copy of the GNU General Public License can be found in licence.txt + *****************************************************************************/ +#pragma endregion + +#include "Plugin.h" +#include +#include +#include +#include +#include + +using namespace OpenRCT2::Scripting; + +Plugin::Plugin(duk_context * context, const std::string &path) + : _context(context), + _path(path) +{ +} + +Plugin::Plugin(const Plugin&& src) + : _context(src._context), + _path(src._path), + _metadata(src._metadata) +{ +} + +void Plugin::Load() +{ + std::string projectedVariables = "console,park"; + std::string code; + { + std::ifstream fs(_path); + if (fs.is_open()) + { + fs.seekg(0, std::ios::end); + code.reserve(fs.tellg()); + fs.seekg(0, std::ios::beg); + code.assign( + std::istreambuf_iterator(fs), + std::istreambuf_iterator()); + } + } + // Wrap the script in a function and pass the global objects as variables + // so that if the script modifies them, they are not modified for other scripts. + code = "(function(" + projectedVariables + "){" + code + "})(" + projectedVariables + ");"; + auto flags = DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NOFILENAME; + auto result = duk_eval_raw(_context, code.c_str(), code.size(), flags); + if (result != DUK_ERR_NONE) + { + auto val = std::string(duk_safe_to_string(_context, -1)); + duk_pop(_context); + throw std::runtime_error("Failed to load plug-in script: " + val); + } + + _metadata = GetMetadata(DukValue::take_from_stack(_context)); +} + +void Plugin::Start() +{ + const auto& mainFunc = _metadata.Main; + mainFunc.push(); + auto result = duk_pcall(_context, 0); + if (result != DUK_ERR_NONE) + { + auto val = std::string(duk_safe_to_string(_context, -1)); + duk_pop(_context); + throw std::runtime_error("[" + _metadata.Name + "] " + val); + } + duk_pop(_context); +} + +PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) +{ + PluginMetadata metadata; + if (dukMetadata.type() == DukValue::Type::OBJECT) + { + metadata.Name = dukMetadata["name"].as_string(); + metadata.Version = dukMetadata["version"].as_string(); + + auto dukAuthors = dukMetadata["authors"]; + dukAuthors.push(); + if (dukAuthors.is_array()) + { + auto elements = dukAuthors.as_array(); + std::transform( + elements.begin(), + elements.end(), + std::back_inserter(metadata.Authors), + [](const DukValue& v) { return v.as_string(); }); + } + else + { + metadata.Authors = { dukAuthors.as_string() }; + } + metadata.Main = dukMetadata["main"]; + } + return metadata; +} diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h new file mode 100644 index 0000000000..207eff783a --- /dev/null +++ b/src/openrct2/scripting/Plugin.h @@ -0,0 +1,52 @@ +#pragma region Copyright (c) 2014-2018 OpenRCT2 Developers +/***************************************************************************** + * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. + * + * OpenRCT2 is the work of many authors, a full list can be found in contributors.md + * For more information, visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * A full copy of the GNU General Public License can be found in licence.txt + *****************************************************************************/ +#pragma endregion + +#pragma once + +#include +#include +#include +#include + +namespace OpenRCT2::Scripting +{ + struct PluginMetadata + { + std::string Name; + std::string Version; + std::vector Authors; + DukValue Main; + }; + + class Plugin + { + private: + duk_context * const _context; + std::string const _path; + PluginMetadata _metadata; + + public: + Plugin(duk_context * context, const std::string &path); + Plugin(const Plugin&) = delete; + Plugin(const Plugin&&); + + void Load(); + void Start(); + + private: + static PluginMetadata GetMetadata(const DukValue& dukMetadata); + }; +} diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 898fe7d2c2..bed35d9ca2 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -8,7 +8,10 @@ *****************************************************************************/ #include "ScriptEngine.h" +#include "../core/FileScanner.h" +#include "../core/Path.hpp" #include "../interface/InteractiveConsole.h" +#include "../PlatformEnvironment.h" #include #include #include @@ -47,6 +50,38 @@ void ScriptEngine::Initialise() dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(), "park"); + + LoadPlugins(); + StartPlugins(); +} + +void ScriptEngine::LoadPlugins() +{ + auto base = _env.GetDirectoryPath(DIRBASE::USER, DIRID::PLUGIN); + auto pattern = Path::Combine(base, "*.js"); + auto scanner = std::unique_ptr(Path::ScanDirectory(pattern, true)); + while (scanner->Next()) + { + auto path = std::string(scanner->GetPath()); + try + { + Plugin p(_context, path); + p.Load(); + _plugins.push_back(std::move(p)); + } + catch (const std::exception &e) + { + _console.WriteLineError(e.what()); + } + } +} + +void ScriptEngine::StartPlugins() +{ + for (auto& plugin : _plugins) + { + plugin.Start(); + } } void ScriptEngine::Update() diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index e7673978a9..c978703b29 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -10,6 +10,7 @@ #pragma once #include "../common.h" +#include "Plugin.h" #include #include #include @@ -34,14 +35,19 @@ namespace OpenRCT2::Scripting bool _initialised{}; duk_context * _context{}; std::queue, std::string>> _evalQueue; + std::vector _plugins; public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); - ScriptEngine(ScriptEngine&&) = delete; + ScriptEngine(ScriptEngine&) = delete; ~ScriptEngine(); - void Initialise(); void Update(); std::future Eval(const std::string &s); + + private: + void Initialise(); + void LoadPlugins(); + void StartPlugins(); }; } diff --git a/src/openrct2/thirdparty/dukglue/dukvalue.h b/src/openrct2/thirdparty/dukglue/dukvalue.h index e0a0782be5..982bad1496 100644 --- a/src/openrct2/thirdparty/dukglue/dukvalue.h +++ b/src/openrct2/thirdparty/dukglue/dukvalue.h @@ -595,4 +595,34 @@ public: duk_get_prop_string(mContext, -1, key.c_str()); return DukValue::take_from_stack(mContext); } + + bool is_array() const + { + push(); + bool result = duk_is_array(mContext, -1); + duk_pop(mContext); + return result; + } + + std::vector as_array() const + { + push(); + if (!duk_is_array(mContext, -1)) + { + duk_pop(mContext); + throw DukException() << "Expected array, got " << type_name(); + } + + auto arrayLength = duk_get_length(mContext, -1); + std::vector result; + result.reserve(arrayLength); + for (size_t i = 0; i < arrayLength; i++) + { + duk_get_prop_index(mContext, -1, i); + result.push_back(take_from_stack(mContext)); + } + + duk_pop(mContext); + return result; + } }; \ No newline at end of file From 3556dead7436d65cae824ac0476f03f5f4635a87 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 18 Mar 2018 17:43:47 +0000 Subject: [PATCH 009/159] Add hot reloading support --- src/openrct2/scripting/Plugin.cpp | 86 ++++++++++++++++++++++++- src/openrct2/scripting/Plugin.h | 21 +++++- src/openrct2/scripting/ScriptEngine.cpp | 28 ++++++++ src/openrct2/scripting/ScriptEngine.h | 2 + 4 files changed, 132 insertions(+), 5 deletions(-) diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 0da56f3005..8ab7954dd3 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -21,6 +21,11 @@ #include #include +#include +#include +#include +#include + using namespace OpenRCT2::Scripting; Plugin::Plugin(duk_context * context, const std::string &path) @@ -29,11 +34,23 @@ Plugin::Plugin(duk_context * context, const std::string &path) { } -Plugin::Plugin(const Plugin&& src) +Plugin::Plugin(Plugin&& src) : _context(src._context), _path(src._path), - _metadata(src._metadata) + _metadata(src._metadata), + _hotReloadData(src._hotReloadData), + _hotReloadEnabled(src._hotReloadEnabled) { + src._context = nullptr; + src._path = std::string(); + src._metadata = PluginMetadata(); + src._hotReloadData = HotReloadData(); + src._hotReloadEnabled = false; +} + +Plugin::~Plugin() +{ + DisableHotReload(); } void Plugin::Load() @@ -70,6 +87,11 @@ void Plugin::Load() void Plugin::Start() { const auto& mainFunc = _metadata.Main; + if (mainFunc.context() == nullptr) + { + throw std::runtime_error("No main function specified."); + } + mainFunc.push(); auto result = duk_pcall(_context, 0); if (result != DUK_ERR_NONE) @@ -81,6 +103,66 @@ void Plugin::Start() duk_pop(_context); } +void Plugin::Update() +{ +} + +void Plugin::EnableHotReload() +{ + auto fd = inotify_init(); + if (fd >= 0) + { + // Mark file as non-blocking + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + + auto wd = inotify_add_watch(fd, _path.c_str(), IN_CLOSE_WRITE); + if (wd >= 0) + { + _hotReloadData.FileDesc = fd; + _hotReloadData.WatchDesc = wd; + _hotReloadEnabled = true; + } + else + { + close(fd); + } + } +} + +bool Plugin::ShouldHotReload() +{ + if (_hotReloadEnabled) + { + std::vector eventData; + eventData.resize(1024); + + auto length = read(_hotReloadData.FileDesc, eventData.data(), eventData.size()); + int offset = 0; + while (offset < length) + { + auto e = (inotify_event*)&eventData[offset]; + if ((e->mask & IN_CLOSE_WRITE) && !(e->mask & IN_ISDIR)) + { + return true; + } + offset += sizeof(inotify_event) + e->len; + } + } + return false; +} + +void Plugin::DisableHotReload() +{ + if (_hotReloadEnabled) + { + inotify_rm_watch(_hotReloadData.FileDesc, _hotReloadData.WatchDesc); + close(_hotReloadData.FileDesc); + _hotReloadData = HotReloadData(); + _hotReloadEnabled = false; + } +} + PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) { PluginMetadata metadata; diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 207eff783a..675a985308 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -34,17 +34,32 @@ namespace OpenRCT2::Scripting class Plugin { private: - duk_context * const _context; - std::string const _path; + struct HotReloadData + { + int FileDesc{}; + int WatchDesc{}; + }; + + duk_context * _context; + std::string _path; PluginMetadata _metadata; + HotReloadData _hotReloadData; + bool _hotReloadEnabled{}; public: + Plugin() { } Plugin(duk_context * context, const std::string &path); Plugin(const Plugin&) = delete; - Plugin(const Plugin&&); + Plugin(Plugin&&); + ~Plugin(); void Load(); void Start(); + void Update(); + + void EnableHotReload(); + bool ShouldHotReload(); + void DisableHotReload(); private: static PluginMetadata GetMetadata(const DukValue& dukMetadata); diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index bed35d9ca2..3e940fe70f 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -11,6 +11,7 @@ #include "../core/FileScanner.h" #include "../core/Path.hpp" #include "../interface/InteractiveConsole.h" +#include "../platform/Platform2.h" #include "../PlatformEnvironment.h" #include #include @@ -67,6 +68,7 @@ void ScriptEngine::LoadPlugins() { Plugin p(_context, path); p.Load(); + p.EnableHotReload(); _plugins.push_back(std::move(p)); } catch (const std::exception &e) @@ -76,6 +78,25 @@ void ScriptEngine::LoadPlugins() } } +void ScriptEngine::AutoReloadPlugins() +{ + for (auto& plugin : _plugins) + { + if (plugin.ShouldHotReload()) + { + try + { + plugin.Load(); + plugin.Start(); + } + catch (const std::exception &e) + { + _console.WriteLineError(e.what()); + } + } + } +} + void ScriptEngine::StartPlugins() { for (auto& plugin : _plugins) @@ -111,6 +132,13 @@ void ScriptEngine::Update() // Signal the promise so caller can continue promise.set_value(); } + + auto tick = Platform::GetTicks(); + if (tick - _lastHotReloadCheckTick > 1000) + { + AutoReloadPlugins(); + _lastHotReloadCheckTick = tick; + } } std::future ScriptEngine::Eval(const std::string &s) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index c978703b29..2aaca3195a 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -36,6 +36,7 @@ namespace OpenRCT2::Scripting duk_context * _context{}; std::queue, std::string>> _evalQueue; std::vector _plugins; + uint32 _lastHotReloadCheckTick{}; public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); @@ -49,5 +50,6 @@ namespace OpenRCT2::Scripting void Initialise(); void LoadPlugins(); void StartPlugins(); + void AutoReloadPlugins(); }; } From 4a575975f6a0166b50c66db49e62258b1372dc7e Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 18 Mar 2018 23:35:58 +0000 Subject: [PATCH 010/159] Add hook system --- distribution/openrct2.d.ts | 6 +- src/openrct2/Context.cpp | 1 + src/openrct2/GameState.cpp | 5 ++ src/openrct2/scripting/HookEngine.cpp | 99 ++++++++++++++++++++++ src/openrct2/scripting/HookEngine.h | 81 ++++++++++++++++++ src/openrct2/scripting/ScConsole.hpp | 2 + src/openrct2/scripting/ScContext.hpp | 57 +++++++++++++ src/openrct2/scripting/ScDisposable.hpp | 32 +++++++ src/openrct2/scripting/ScPark.hpp | 2 + src/openrct2/scripting/ScriptEngine.cpp | 24 +++++- src/openrct2/scripting/ScriptEngine.h | 15 ++++ src/openrct2/thirdparty/dukglue/dukvalue.h | 8 ++ 12 files changed, 329 insertions(+), 3 deletions(-) create mode 100644 src/openrct2/scripting/HookEngine.cpp create mode 100644 src/openrct2/scripting/HookEngine.h create mode 100644 src/openrct2/scripting/ScContext.hpp create mode 100644 src/openrct2/scripting/ScDisposable.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 540d01e2de..4c96804d33 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -36,7 +36,11 @@ export interface Context { /** * Subscribes to the given hook. */ - subscribe: (hook: string, callback: Function) => void; + subscribe(hook: string, callback: Function): IDisposable; +} + +export interface IDisposable { + dispose(): void; } export interface Ride { diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 22f611c03d..63597337a9 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -57,6 +57,7 @@ #include "ride/TrackDesignRepository.h" #include "scenario/Scenario.h" #include "scenario/ScenarioRepository.h" +#include "scripting/HookEngine.h" #include "scripting/ScriptEngine.h" #include "title/TitleScreen.h" #include "title/TitleSequenceManager.h" diff --git a/src/openrct2/GameState.cpp b/src/openrct2/GameState.cpp index 4a195010b6..bdeeaff041 100644 --- a/src/openrct2/GameState.cpp +++ b/src/openrct2/GameState.cpp @@ -26,6 +26,7 @@ #include "peep/Staff.h" #include "platform/Platform2.h" #include "scenario/Scenario.h" +#include "scripting/ScriptEngine.h" #include "title/TitleScreen.h" #include "title/TitleSequencePlayer.h" #include "ui/UiContext.h" @@ -38,6 +39,7 @@ #include using namespace OpenRCT2; +using namespace OpenRCT2::Scripting; GameState::GameState() { @@ -267,6 +269,9 @@ void GameState::UpdateLogic() } } + auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + hookEngine.Call(HOOK_TYPE::INTERVAL_TICK); + date_update(); _date = Date(gDateMonthTicks, gDateMonthTicks); diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp new file mode 100644 index 0000000000..4b649b7332 --- /dev/null +++ b/src/openrct2/scripting/HookEngine.cpp @@ -0,0 +1,99 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + +#include +#include "HookEngine.h" +#include "ScriptEngine.h" + +using namespace OpenRCT2::Scripting; + +HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string &name) +{ + static const std::unordered_map LookupTable({ + { "interval.tick", HOOK_TYPE::INTERVAL_TICK }, + { "interval.day", HOOK_TYPE::INTERVAL_DAY }, + }); + auto result = LookupTable.find(name); + return (result != LookupTable.end()) ? + result->second : + HOOK_TYPE::UNDEFINED; +} + +HookEngine::HookEngine(ScriptExecutionInfo& execInfo) : + _execInfo(execInfo) +{ + _hookMap.resize(NUM_HOOK_TYPES); + for (size_t i = 0; i < NUM_HOOK_TYPES; i++) + { + _hookMap[i].Type = static_cast(i); + } +} + +uint32 HookEngine::Subscribe(HOOK_TYPE type, Plugin& owner, const DukValue &function) +{ + auto& hookList = GetHookList(type); + auto cookie = _nextCookie++; + Hook hook(cookie, owner, function); + hookList.Hooks.push_back(hook); + return cookie; +} + +void HookEngine::Unsubscribe(HOOK_TYPE type, uint32 cookie) +{ + auto& hookList = GetHookList(type); + auto& hooks = hookList.Hooks; + for (auto it = hooks.begin(); it != hooks.end(); it++) + { + if (it->Cookie == cookie) + { + hooks.erase(it); + break; + } + } +} + +void HookEngine::UnsubscribeAll(const Plugin& owner) +{ + for (auto& hookList : _hookMap) + { + auto& hooks = hookList.Hooks; + for (auto it = hooks.begin(); it != hooks.end();) + { + if (it->Owner == &owner) + { + it = hooks.erase(it); + } + else + { + it++; + } + } + } +} + +void HookEngine::Call(HOOK_TYPE type) +{ + auto& hookList = GetHookList(type); + for (auto& hook : hookList.Hooks) + { + _execInfo.SetCurrentPlugin(hook.Owner); + + const auto& function = hook.Function; + function.push(); + duk_pcall(function.context(), 0); + duk_pop(function.context()); + } + _execInfo.SetCurrentPlugin(nullptr); +} + +HookList& HookEngine::GetHookList(HOOK_TYPE type) +{ + auto index = static_cast(type); + return _hookMap[index]; +} diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h new file mode 100644 index 0000000000..12058aea2a --- /dev/null +++ b/src/openrct2/scripting/HookEngine.h @@ -0,0 +1,81 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 + +#include "../common.h" +#include +#include +#include +#include + +namespace OpenRCT2::Scripting +{ + class ScriptExecutionInfo; + class Plugin; + + enum class HOOK_TYPE + { + INTERVAL_TICK, + INTERVAL_DAY, + COUNT, + UNDEFINED = -1, + }; + constexpr size_t NUM_HOOK_TYPES = static_cast(HOOK_TYPE::COUNT); + HOOK_TYPE GetHookType(const std::string &name); + + struct Hook + { + uint32 Cookie; + Plugin * Owner; + DukValue Function; + + Hook(); + Hook(uint32 cookie, Plugin& owner, const DukValue &function) + : Cookie(cookie), + Owner(&owner), + Function(function) + { + } + }; + + struct HookList + { + HOOK_TYPE Type; + std::vector Hooks; + + HookList() {} + HookList(const HookList&) = delete; + HookList(HookList&& src) + : Type(std::move(src.Type)), + Hooks(std::move(src.Hooks)) + { + } + }; + + class HookEngine + { + private: + ScriptExecutionInfo& _execInfo; + std::vector _hookMap; + size_t _numHooks{}; + uint32_t _nextCookie = 1; + + public: + HookEngine(ScriptExecutionInfo& execInfo); + HookEngine(const HookEngine&) = delete; + uint32 Subscribe(HOOK_TYPE type, Plugin& owner, const DukValue &function); + void Unsubscribe(HOOK_TYPE type, uint32 cookie); + void UnsubscribeAll(const Plugin& owner); + void Call(HOOK_TYPE type); + + private: + HookList& GetHookList(HOOK_TYPE type); + }; +} diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index 9d293bacbc..10f5916de9 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -1,3 +1,5 @@ +#pragma once + #include #include "../interface/Console.h" diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp new file mode 100644 index 0000000000..c533cab3ed --- /dev/null +++ b/src/openrct2/scripting/ScContext.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include +#include "HookEngine.h" +#include "ScDisposable.hpp" +#include "ScriptEngine.h" +#include +#include + +namespace OpenRCT2::Scripting +{ + class ScContext + { + private: + ScriptExecutionInfo& _execInfo; + HookEngine& _hookEngine; + + public: + ScContext(ScriptExecutionInfo& execInfo, HookEngine& hookEngine) + : _execInfo(execInfo), + _hookEngine(hookEngine) + { + } + + std::shared_ptr subscribe(const std::string &hook, const DukValue &callback) + { + auto hookType = GetHookType(hook); + if (hookType == HOOK_TYPE::UNDEFINED) + { + throw DukException() << "Unknown hook type: " << hook; + } + + if (!callback.is_function()) + { + throw DukException() << "Expected function for callback"; + } + + auto owner = _execInfo.GetCurrentPlugin(); + if (owner == nullptr) + { + throw DukException() << "Not in a plugin context"; + } + + auto cookie = _hookEngine.Subscribe(hookType, *owner, callback); + return std::make_shared( + [this, hookType, cookie]() + { + _hookEngine.Unsubscribe(hookType, cookie); + }); + } + + static void Register(duk_context * ctx) + { + dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); + } + }; +} diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp new file mode 100644 index 0000000000..eb3b58782a --- /dev/null +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include +#include + +namespace OpenRCT2::Scripting +{ + class ScDisposable + { + private: + std::function _onDispose; + + public: + ScDisposable(std::function onDispose) : + _onDispose(onDispose) + { + } + + void dispose() + { + if (_onDispose) + { + _onDispose(); + } + } + + static void Register(duk_context * ctx) + { + dukglue_register_method(ctx, &ScDisposable::dispose, "dispose"); + } + }; +} diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index b8512d122b..3bbab2db7d 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -1,3 +1,5 @@ +#pragma once + #include #include #include "../common.h" diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 3e940fe70f..d5f854107c 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -19,6 +19,8 @@ #include #include "ScConsole.hpp" +#include "ScContext.hpp" +#include "ScDisposable.hpp" #include "ScPark.hpp" using namespace OpenRCT2; @@ -28,7 +30,8 @@ static std::string Stringify(duk_context * ctx, duk_idx_t idx); ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) : _console(console), - _env(env) + _env(env), + _hookEngine(_execInfo) { } @@ -47,9 +50,12 @@ void ScriptEngine::Initialise() auto ctx = _context; ScConsole::Register(ctx); + ScContext::Register(ctx); + ScDisposable::Register(ctx); ScPark::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); + dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); dukglue_register_global(ctx, std::make_shared(), "park"); LoadPlugins(); @@ -67,6 +73,7 @@ void ScriptEngine::LoadPlugins() try { Plugin p(_context, path); + _execInfo.SetCurrentPlugin(&p); p.Load(); p.EnableHotReload(); _plugins.push_back(std::move(p)); @@ -76,6 +83,7 @@ void ScriptEngine::LoadPlugins() _console.WriteLineError(e.what()); } } + _execInfo.SetCurrentPlugin(nullptr); } void ScriptEngine::AutoReloadPlugins() @@ -86,6 +94,8 @@ void ScriptEngine::AutoReloadPlugins() { try { + _hookEngine.UnsubscribeAll(plugin); + _execInfo.SetCurrentPlugin(&plugin); plugin.Load(); plugin.Start(); } @@ -95,14 +105,24 @@ void ScriptEngine::AutoReloadPlugins() } } } + _execInfo.SetCurrentPlugin(nullptr); } void ScriptEngine::StartPlugins() { for (auto& plugin : _plugins) { - plugin.Start(); + _execInfo.SetCurrentPlugin(&plugin); + try + { + plugin.Start(); + } + catch (const std::exception &e) + { + _console.WriteLineError(e.what()); + } } + _execInfo.SetCurrentPlugin(nullptr); } void ScriptEngine::Update() diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 2aaca3195a..d8f81b089c 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -10,6 +10,7 @@ #pragma once #include "../common.h" +#include "HookEngine.h" #include "Plugin.h" #include #include @@ -27,6 +28,16 @@ namespace OpenRCT2 namespace OpenRCT2::Scripting { + class ScriptExecutionInfo + { + private: + Plugin * _plugin; + + public: + Plugin * GetCurrentPlugin() { return _plugin; } + void SetCurrentPlugin(Plugin * value) { _plugin = value; } + }; + class ScriptEngine { private: @@ -37,12 +48,16 @@ namespace OpenRCT2::Scripting std::queue, std::string>> _evalQueue; std::vector _plugins; uint32 _lastHotReloadCheckTick{}; + HookEngine _hookEngine; + ScriptExecutionInfo _execInfo; public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); ScriptEngine(ScriptEngine&) = delete; ~ScriptEngine(); + HookEngine& GetHookEngine() { return _hookEngine; } + void Update(); std::future Eval(const std::string &s); diff --git a/src/openrct2/thirdparty/dukglue/dukvalue.h b/src/openrct2/thirdparty/dukglue/dukvalue.h index 982bad1496..4e505cce05 100644 --- a/src/openrct2/thirdparty/dukglue/dukvalue.h +++ b/src/openrct2/thirdparty/dukglue/dukvalue.h @@ -625,4 +625,12 @@ public: duk_pop(mContext); return result; } + + bool is_function() const + { + push(); + bool result = duk_is_function(mContext, -1); + duk_pop(mContext); + return result; + } }; \ No newline at end of file From 5697bcf0bdcf34b1d58e5457c053019eea161fba Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 20 Mar 2018 19:40:38 +0000 Subject: [PATCH 011/159] Add basic map and thing support --- distribution/openrct2.d.ts | 53 +++++++++++++++ src/openrct2/scripting/Plugin.cpp | 2 +- src/openrct2/scripting/ScContext.hpp | 5 ++ src/openrct2/scripting/ScMap.hpp | 64 +++++++++++++++++++ src/openrct2/scripting/ScThing.hpp | 48 ++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 5 ++ .../dukglue/detail_primitive_types.h | 18 ++++-- 7 files changed, 187 insertions(+), 8 deletions(-) create mode 100644 src/openrct2/scripting/ScMap.hpp create mode 100644 src/openrct2/scripting/ScThing.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 4c96804d33..bc4c716fef 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -33,16 +33,49 @@ export interface Context { * The user's current configuration. */ configuration: Configuration; + + /** + * Registers a new intent (command) that can be mapped to a shortcut. + */ + registerIntent(desc: IntentDesc); + /** * Subscribes to the given hook. */ subscribe(hook: string, callback: Function): IDisposable; } +export interface IntentDesc +{ + key: string; + title?: string; + shortcut?: string; + action: Function; +} + export interface IDisposable { dispose(): void; } +export type TileElementType = + "surface" | "footpath-item"; + +export interface TileElement { + type: TileElementType; + zBase: number; + zClearance: number; + + // footpath-item: + broken: boolean; +} + +export interface Tile { + x: number; + y: number; + type: TileType; + elements: TileElement[]; +} + export interface Ride { name: string; excitement: number; @@ -51,8 +84,28 @@ export interface Ride { totalCustomers: number; } +export type TileElementType = + "car" | "duck" | "peep"; + +export interface Thing { + type: ThingType; + x: number; + y: number; + z: number; + + // Peep + tshirt: number; + trousers: number; +} + export interface Map { + size: { x: number; y: number; }; + rides: number; + things: number; + getRide(id: number): Ride; + getTile(x: number, y: number): Tile; + getThing(id: number): Thing; } export type ParkMessageType = diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 8ab7954dd3..201749ec57 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -55,7 +55,7 @@ Plugin::~Plugin() void Plugin::Load() { - std::string projectedVariables = "console,park"; + std::string projectedVariables = "console,context,map,park"; std::string code; { std::ifstream fs(_path); diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index c533cab3ed..864979054c 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -22,6 +22,10 @@ namespace OpenRCT2::Scripting { } + void registerIntent(const DukValue& desc) + { + } + std::shared_ptr subscribe(const std::string &hook, const DukValue &callback) { auto hookType = GetHookType(hook); @@ -51,6 +55,7 @@ namespace OpenRCT2::Scripting static void Register(duk_context * ctx) { + dukglue_register_method(ctx, &ScContext::registerIntent, "registerIntent"); dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); } }; diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp new file mode 100644 index 0000000000..c4f69e16ae --- /dev/null +++ b/src/openrct2/scripting/ScMap.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include +#include "../common.h" +#include "../ride/Ride.h" +#include "../world/Map.h" +#include "ScThing.hpp" + +namespace OpenRCT2::Scripting +{ + class ScMap + { + private: + duk_context * _context; + + public: + ScMap(duk_context * ctx) + : _context(ctx) + { + } + + DukValue size_get() + { + auto ctx = _context; + auto objIdx = duk_push_object(ctx); + duk_push_number(ctx, gMapSize); + duk_put_prop_string(ctx, objIdx, "x"); + duk_push_number(ctx, gMapSize); + duk_put_prop_string(ctx, objIdx, "y"); + return DukValue::take_from_stack(ctx); + } + + sint32 rides_get() + { + return MAX_RIDES; + } + + sint32 things_get() + { + return MAX_SPRITES; + } + + std::shared_ptr getThing(sint32 id) + { + if (id >= 0 && id < MAX_SPRITES) + { + auto sprite = get_sprite(id); + if (sprite != nullptr && sprite->unknown.sprite_identifier != SPRITE_IDENTIFIER_NULL) + { + return std::make_shared(sprite); + } + } + return nullptr; + } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScMap::size_get, nullptr, "size"); + dukglue_register_property(ctx, &ScMap::rides_get, nullptr, "rides"); + dukglue_register_property(ctx, &ScMap::things_get, nullptr, "things"); + dukglue_register_method(ctx, &ScMap::getThing, "getThing"); + } + }; +} diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp new file mode 100644 index 0000000000..980ce1d2b2 --- /dev/null +++ b/src/openrct2/scripting/ScThing.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include +#include "../common.h" +#include "../world/Sprite.h" + +namespace OpenRCT2::Scripting +{ + class ScThing + { + private: + rct_sprite * _sprite; + + public: + ScThing(rct_sprite * sprite) + : _sprite(sprite) + { + } + + std::string type_get() + { + if (_sprite->unknown.sprite_identifier == SPRITE_IDENTIFIER_PEEP) + { + return "peep"; + } + return "unknown"; + } + + sint32 x_get() { return _sprite->unknown.x; } + sint32 y_get() { return _sprite->unknown.y; } + sint32 z_get() { return _sprite->unknown.z; } + + uint8 tshirtColour_get() { return _sprite->peep.tshirt_colour; } + void tshirtColour_set(uint8 value) { _sprite->peep.tshirt_colour = value; } + uint8 trousersColour_get() { return _sprite->peep.trousers_colour; } + void trousersColour_set(uint8 value) { _sprite->peep.trousers_colour = value; } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScThing::x_get, nullptr, "x"); + dukglue_register_property(ctx, &ScThing::y_get, nullptr, "y"); + dukglue_register_property(ctx, &ScThing::z_get, nullptr, "z"); + dukglue_register_property(ctx, &ScThing::tshirtColour_get, &ScThing::tshirtColour_set, "tshirtColour"); + dukglue_register_property(ctx, &ScThing::trousersColour_get, &ScThing::trousersColour_set, "trousersColour"); + } + }; +} diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index d5f854107c..2d641a63fd 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -21,7 +21,9 @@ #include "ScConsole.hpp" #include "ScContext.hpp" #include "ScDisposable.hpp" +#include "ScMap.hpp" #include "ScPark.hpp" +#include "ScThing.hpp" using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -52,10 +54,13 @@ void ScriptEngine::Initialise() ScConsole::Register(ctx); ScContext::Register(ctx); ScDisposable::Register(ctx); + ScMap::Register(ctx); ScPark::Register(ctx); + ScThing::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); + dukglue_register_global(ctx, std::make_shared(ctx), "map"); dukglue_register_global(ctx, std::make_shared(), "park"); LoadPlugins(); diff --git a/src/openrct2/thirdparty/dukglue/detail_primitive_types.h b/src/openrct2/thirdparty/dukglue/detail_primitive_types.h index ebba1ad80a..6ff83c1735 100644 --- a/src/openrct2/thirdparty/dukglue/detail_primitive_types.h +++ b/src/openrct2/thirdparty/dukglue/detail_primitive_types.h @@ -218,15 +218,19 @@ namespace dukglue { template static void push(duk_context* ctx, const std::shared_ptr& value) { - dukglue::detail::ProtoManager::make_script_object(ctx, value.get()); + if (value == nullptr) { + duk_push_null(ctx); + } else { + dukglue::detail::ProtoManager::make_script_object(ctx, value.get()); - // create + set shared_ptr - duk_push_pointer(ctx, new std::shared_ptr(value)); - duk_put_prop_string(ctx, -2, "\xFF" "shared_ptr"); + // create + set shared_ptr + duk_push_pointer(ctx, new std::shared_ptr(value)); + duk_put_prop_string(ctx, -2, "\xFF" "shared_ptr"); - // set shared_ptr finalizer - duk_push_c_function(ctx, &shared_ptr_finalizer, 1); - duk_set_finalizer(ctx, -2); + // set shared_ptr finalizer + duk_push_c_function(ctx, &shared_ptr_finalizer, 1); + duk_set_finalizer(ctx, -2); + } } }; From a6bb9a9b64dd3542efdb87147652db0ab1df580c Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 20 Mar 2018 20:28:15 +0000 Subject: [PATCH 012/159] Add tile element support --- src/openrct2/scripting/ScMap.hpp | 8 ++ src/openrct2/scripting/ScTile.hpp | 99 +++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 3 + 3 files changed, 110 insertions(+) create mode 100644 src/openrct2/scripting/ScTile.hpp diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index c4f69e16ae..86a355535d 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -4,6 +4,7 @@ #include "../common.h" #include "../ride/Ride.h" #include "../world/Map.h" +#include "ScTile.hpp" #include "ScThing.hpp" namespace OpenRCT2::Scripting @@ -40,6 +41,12 @@ namespace OpenRCT2::Scripting return MAX_SPRITES; } + std::shared_ptr getTile(sint32 x, sint32 y) + { + auto firstElement = map_get_first_element_at(x, y); + return std::make_shared(firstElement); + } + std::shared_ptr getThing(sint32 id) { if (id >= 0 && id < MAX_SPRITES) @@ -58,6 +65,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScMap::size_get, nullptr, "size"); dukglue_register_property(ctx, &ScMap::rides_get, nullptr, "rides"); dukglue_register_property(ctx, &ScMap::things_get, nullptr, "things"); + dukglue_register_method(ctx, &ScMap::getTile, "getTile"); dukglue_register_method(ctx, &ScMap::getThing, "getThing"); } }; diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp new file mode 100644 index 0000000000..a3d96a5fdc --- /dev/null +++ b/src/openrct2/scripting/ScTile.hpp @@ -0,0 +1,99 @@ +#pragma once + +#include +#include "../common.h" +#include "../world/Sprite.h" +#include + +namespace OpenRCT2::Scripting +{ + class ScTileElement + { + private: + rct_tile_element * _element; + + public: + ScTileElement(rct_tile_element * element) + : _element(element) + { + } + + std::string type_get() + { + if (tile_element_get_type(_element) == TILE_ELEMENT_TYPE_PATH) + { + return "footpath"; + } + return "unknown"; + } + + bool broken_get() { return _element->flags & TILE_ELEMENT_FLAG_BROKEN; } + void broken_set(bool value) + { + if (value) + { + _element->flags |= TILE_ELEMENT_FLAG_BROKEN; + } + else + { + _element->flags &= ~TILE_ELEMENT_FLAG_BROKEN; + } + } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScTileElement::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + } + }; + + class ScTile + { + private: + rct_tile_element * _first; + size_t _count = 0; + + public: + ScTile(rct_tile_element * first) + : _first(first) + { + _count = 0; + if (first != nullptr) + { + auto element = first; + do + { + _count++; + } + while (!tile_element_is_last_for_tile(element++)); + } + } + + size_t numElements_get() { return _count; } + + std::shared_ptr getElement(size_t index) + { + if (index >= _count) return nullptr; + return std::make_shared(&_first[index]); + } + + // This is not a good idea as the array is generated each time elements is accessed and + // chances are scripts will do tile.elements[0], tile.elements[1]... + // std::vector> elements_get() + // { + // std::vector> elements; + // for (size_t i = 0; i < _count; i++) + // { + // elements.push_back(std::make_shared(&_first[i])); + // } + // return elements; + // } + + static void Register(duk_context * ctx) + { + // dukglue_register_property(ctx, &ScTile::elements_get, nullptr, "elements"); + dukglue_register_property(ctx, &ScTile::numElements_get, nullptr, "numElements"); + dukglue_register_method(ctx, &ScTile::getElement, "getElement"); + } + }; +} diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 2d641a63fd..67a2d3d957 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -23,6 +23,7 @@ #include "ScDisposable.hpp" #include "ScMap.hpp" #include "ScPark.hpp" +#include "ScTile.hpp" #include "ScThing.hpp" using namespace OpenRCT2; @@ -56,6 +57,8 @@ void ScriptEngine::Initialise() ScDisposable::Register(ctx); ScMap::Register(ctx); ScPark::Register(ctx); + ScTile::Register(ctx); + ScTileElement::Register(ctx); ScThing::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); From f54b3efe9ef1e32c5180b1865bd5625575d2fc5a Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 23 Mar 2018 22:39:12 +0000 Subject: [PATCH 013/159] Use shared_ptr for Plugin --- src/openrct2/scripting/HookEngine.cpp | 6 +++--- src/openrct2/scripting/HookEngine.h | 10 +++++----- src/openrct2/scripting/Plugin.cpp | 14 -------------- src/openrct2/scripting/Plugin.h | 2 +- src/openrct2/scripting/ScContext.hpp | 2 +- src/openrct2/scripting/ScriptEngine.cpp | 22 +++++++++++----------- src/openrct2/scripting/ScriptEngine.h | 8 ++++---- 7 files changed, 25 insertions(+), 39 deletions(-) diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 4b649b7332..f364a21d11 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -35,7 +35,7 @@ HookEngine::HookEngine(ScriptExecutionInfo& execInfo) : } } -uint32 HookEngine::Subscribe(HOOK_TYPE type, Plugin& owner, const DukValue &function) +uint32 HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function) { auto& hookList = GetHookList(type); auto cookie = _nextCookie++; @@ -58,14 +58,14 @@ void HookEngine::Unsubscribe(HOOK_TYPE type, uint32 cookie) } } -void HookEngine::UnsubscribeAll(const Plugin& owner) +void HookEngine::UnsubscribeAll(std::shared_ptr owner) { for (auto& hookList : _hookMap) { auto& hooks = hookList.Hooks; for (auto it = hooks.begin(); it != hooks.end();) { - if (it->Owner == &owner) + if (it->Owner == owner) { it = hooks.erase(it); } diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 12058aea2a..8fc3099f9f 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -33,13 +33,13 @@ namespace OpenRCT2::Scripting struct Hook { uint32 Cookie; - Plugin * Owner; + std::shared_ptr Owner; DukValue Function; Hook(); - Hook(uint32 cookie, Plugin& owner, const DukValue &function) + Hook(uint32 cookie, std::shared_ptr owner, const DukValue &function) : Cookie(cookie), - Owner(&owner), + Owner(owner), Function(function) { } @@ -70,9 +70,9 @@ namespace OpenRCT2::Scripting public: HookEngine(ScriptExecutionInfo& execInfo); HookEngine(const HookEngine&) = delete; - uint32 Subscribe(HOOK_TYPE type, Plugin& owner, const DukValue &function); + uint32 Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function); void Unsubscribe(HOOK_TYPE type, uint32 cookie); - void UnsubscribeAll(const Plugin& owner); + void UnsubscribeAll(std::shared_ptr owner); void Call(HOOK_TYPE type); private: diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 201749ec57..d0ea3f1013 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -34,20 +34,6 @@ Plugin::Plugin(duk_context * context, const std::string &path) { } -Plugin::Plugin(Plugin&& src) - : _context(src._context), - _path(src._path), - _metadata(src._metadata), - _hotReloadData(src._hotReloadData), - _hotReloadEnabled(src._hotReloadEnabled) -{ - src._context = nullptr; - src._path = std::string(); - src._metadata = PluginMetadata(); - src._hotReloadData = HotReloadData(); - src._hotReloadEnabled = false; -} - Plugin::~Plugin() { DisableHotReload(); diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 675a985308..d14d125c3a 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -50,7 +50,7 @@ namespace OpenRCT2::Scripting Plugin() { } Plugin(duk_context * context, const std::string &path); Plugin(const Plugin&) = delete; - Plugin(Plugin&&); + Plugin(Plugin&&) = delete; ~Plugin(); void Load(); diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 864979054c..f858cd7232 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -45,7 +45,7 @@ namespace OpenRCT2::Scripting throw DukException() << "Not in a plugin context"; } - auto cookie = _hookEngine.Subscribe(hookType, *owner, callback); + auto cookie = _hookEngine.Subscribe(hookType, owner, callback); return std::make_shared( [this, hookType, cookie]() { diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 67a2d3d957..a68fc3795b 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -80,11 +80,11 @@ void ScriptEngine::LoadPlugins() auto path = std::string(scanner->GetPath()); try { - Plugin p(_context, path); - _execInfo.SetCurrentPlugin(&p); - p.Load(); - p.EnableHotReload(); - _plugins.push_back(std::move(p)); + auto plugin = std::make_shared(_context, path); + _execInfo.SetCurrentPlugin(plugin); + plugin->Load(); + plugin->EnableHotReload(); + _plugins.push_back(std::move(plugin)); } catch (const std::exception &e) { @@ -98,14 +98,14 @@ void ScriptEngine::AutoReloadPlugins() { for (auto& plugin : _plugins) { - if (plugin.ShouldHotReload()) + if (plugin->ShouldHotReload()) { try { _hookEngine.UnsubscribeAll(plugin); - _execInfo.SetCurrentPlugin(&plugin); - plugin.Load(); - plugin.Start(); + _execInfo.SetCurrentPlugin(plugin); + plugin->Load(); + plugin->Start(); } catch (const std::exception &e) { @@ -120,10 +120,10 @@ void ScriptEngine::StartPlugins() { for (auto& plugin : _plugins) { - _execInfo.SetCurrentPlugin(&plugin); + _execInfo.SetCurrentPlugin(plugin); try { - plugin.Start(); + plugin->Start(); } catch (const std::exception &e) { diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index d8f81b089c..b7177524df 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -31,11 +31,11 @@ namespace OpenRCT2::Scripting class ScriptExecutionInfo { private: - Plugin * _plugin; + std::shared_ptr _plugin; public: - Plugin * GetCurrentPlugin() { return _plugin; } - void SetCurrentPlugin(Plugin * value) { _plugin = value; } + std::shared_ptr GetCurrentPlugin() { return _plugin; } + void SetCurrentPlugin(std::shared_ptr value) { _plugin = value; } }; class ScriptEngine @@ -46,7 +46,7 @@ namespace OpenRCT2::Scripting bool _initialised{}; duk_context * _context{}; std::queue, std::string>> _evalQueue; - std::vector _plugins; + std::vector> _plugins; uint32 _lastHotReloadCheckTick{}; HookEngine _hookEngine; ScriptExecutionInfo _execInfo; From d445cfc12557656a3bc66806e8622759af536f4c Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 23 Mar 2018 23:24:36 +0000 Subject: [PATCH 014/159] Refactor plugin scope --- src/openrct2/scripting/HookEngine.cpp | 3 +-- src/openrct2/scripting/ScriptEngine.cpp | 10 ++++------ src/openrct2/scripting/ScriptEngine.h | 22 +++++++++++++++++++++- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index f364a21d11..8dee351c77 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -82,14 +82,13 @@ void HookEngine::Call(HOOK_TYPE type) auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - _execInfo.SetCurrentPlugin(hook.Owner); + ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner); const auto& function = hook.Function; function.push(); duk_pcall(function.context(), 0); duk_pop(function.context()); } - _execInfo.SetCurrentPlugin(nullptr); } HookList& HookEngine::GetHookList(HOOK_TYPE type) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index a68fc3795b..2e5a142f4e 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -81,7 +81,7 @@ void ScriptEngine::LoadPlugins() try { auto plugin = std::make_shared(_context, path); - _execInfo.SetCurrentPlugin(plugin); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); plugin->EnableHotReload(); _plugins.push_back(std::move(plugin)); @@ -91,7 +91,6 @@ void ScriptEngine::LoadPlugins() _console.WriteLineError(e.what()); } } - _execInfo.SetCurrentPlugin(nullptr); } void ScriptEngine::AutoReloadPlugins() @@ -103,7 +102,8 @@ void ScriptEngine::AutoReloadPlugins() try { _hookEngine.UnsubscribeAll(plugin); - _execInfo.SetCurrentPlugin(plugin); + + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); plugin->Start(); } @@ -113,14 +113,13 @@ void ScriptEngine::AutoReloadPlugins() } } } - _execInfo.SetCurrentPlugin(nullptr); } void ScriptEngine::StartPlugins() { for (auto& plugin : _plugins) { - _execInfo.SetCurrentPlugin(plugin); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); try { plugin->Start(); @@ -130,7 +129,6 @@ void ScriptEngine::StartPlugins() _console.WriteLineError(e.what()); } } - _execInfo.SetCurrentPlugin(nullptr); } void ScriptEngine::Update() diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index b7177524df..a3f2cc0386 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -13,6 +13,7 @@ #include "HookEngine.h" #include "Plugin.h" #include +#include #include #include @@ -34,8 +35,27 @@ namespace OpenRCT2::Scripting std::shared_ptr _plugin; public: + class PluginScope + { + private: + ScriptExecutionInfo& _execInfo; + std::shared_ptr _plugin; + + public: + PluginScope(ScriptExecutionInfo& execInfo, std::shared_ptr plugin) + : _execInfo(execInfo), + _plugin(plugin) + { + _execInfo._plugin = plugin; + } + PluginScope(const PluginScope&) = delete; + ~PluginScope() + { + _execInfo._plugin = nullptr; + } + }; + std::shared_ptr GetCurrentPlugin() { return _plugin; } - void SetCurrentPlugin(std::shared_ptr value) { _plugin = value; } }; class ScriptEngine From c340c2abec6ce8ce9f82d4e5a1fac7cc24950089 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 23 Mar 2018 23:39:46 +0000 Subject: [PATCH 015/159] Fix segfault on exit By ensuring duk_context is disposed last in ScriptEngine --- src/openrct2/scripting/ScriptEngine.cpp | 27 ++++++++++++++----------- src/openrct2/scripting/ScriptEngine.h | 20 ++++++++++++++++-- 2 files changed, 33 insertions(+), 14 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 2e5a142f4e..82ba255bf3 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -31,6 +31,20 @@ using namespace OpenRCT2::Scripting; static std::string Stringify(duk_context * ctx, duk_idx_t idx); +DukContext::DukContext() +{ + _context = duk_create_heap_default(); + if (_context == nullptr) + { + throw std::runtime_error("Unable to initialise duktape context."); + } +} + +DukContext::~DukContext() +{ + duk_destroy_heap(_context); +} + ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) : _console(console), _env(env), @@ -38,20 +52,9 @@ ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& en { } -ScriptEngine::~ScriptEngine() -{ - duk_destroy_heap(_context); -} - void ScriptEngine::Initialise() { - _context = duk_create_heap_default(); - if (_context == nullptr) - { - throw std::runtime_error("Unable to initialise duktape context."); - } - - auto ctx = _context; + auto ctx = (duk_context*)_context; ScConsole::Register(ctx); ScContext::Register(ctx); ScDisposable::Register(ctx); diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index a3f2cc0386..8d2f7b36a5 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -58,13 +58,30 @@ namespace OpenRCT2::Scripting std::shared_ptr GetCurrentPlugin() { return _plugin; } }; + class DukContext + { + private: + duk_context * _context{}; + + public: + DukContext(); + DukContext(DukContext&) = delete; + DukContext(DukContext&& src) + : _context(std::move(src._context)) + { + } + ~DukContext(); + + operator duk_context*() { return _context; } + }; + class ScriptEngine { private: InteractiveConsole& _console; IPlatformEnvironment& _env; + DukContext _context; bool _initialised{}; - duk_context * _context{}; std::queue, std::string>> _evalQueue; std::vector> _plugins; uint32 _lastHotReloadCheckTick{}; @@ -74,7 +91,6 @@ namespace OpenRCT2::Scripting public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); ScriptEngine(ScriptEngine&) = delete; - ~ScriptEngine(); HookEngine& GetHookEngine() { return _hookEngine; } From 237e0be7ef6c30dfcbd5a3d2199cf0b436015b07 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 24 Mar 2018 00:40:51 +0000 Subject: [PATCH 016/159] Add basic window API --- distribution/openrct2.d.ts | 10 +- src/openrct2/scripting/Plugin.cpp | 2 +- src/openrct2/scripting/ScUi.hpp | 132 ++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 4 + 4 files changed, 146 insertions(+), 2 deletions(-) create mode 100644 src/openrct2/scripting/ScUi.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index bc4c716fef..610c9c4bfa 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -133,6 +133,9 @@ export interface Window { width: number; height: number; title: string; + isSticky: boolean; + + close(): void; } export interface WindowDesc { @@ -146,8 +149,13 @@ export interface WindowDesc { } export interface Ui { + width: number; + height: number; + windows: number; + + getWindow(id: number): Window; + getWindow(classification: string, id?: number): Window; openWindow(desc: WindowDesc): Window; - closeWindow(window: Window): void; closeWindows(classification: string, id?: number): void; closeAllWindows(): void; } diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index d0ea3f1013..ce482f3267 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -41,7 +41,7 @@ Plugin::~Plugin() void Plugin::Load() { - std::string projectedVariables = "console,context,map,park"; + std::string projectedVariables = "console,context,map,park,ui"; std::string code; { std::ifstream fs(_path); diff --git a/src/openrct2/scripting/ScUi.hpp b/src/openrct2/scripting/ScUi.hpp new file mode 100644 index 0000000000..a503f619e6 --- /dev/null +++ b/src/openrct2/scripting/ScUi.hpp @@ -0,0 +1,132 @@ +#pragma once + +#include +#include +#include +#include "../common.h" +#include "../Context.h" +#include "../interface/Window.h" +#include "../interface/Window_internal.h" +#include "../ui/UiContext.h" +#include "../ui/WindowManager.h" + +namespace OpenRCT2::Scripting +{ + class ScWindow + { + private: + rct_windowclass _class; + rct_windownumber _number; + + public: + ScWindow(rct_windowclass c, rct_windownumber n) + : _class(c), + _number(n) + { + } + + sint32 x_get() { return GetWindow()->x; } + void x_set(sint32 value) + { + auto w = GetWindow(); + window_set_position(w, value, w->y); + } + sint32 y_get() { return GetWindow()->y; } + void y_set(sint32 value) + { + auto w = GetWindow(); + window_set_position(w, w->x, value); + } + sint32 width_get() { return GetWindow()->width; } + sint32 height_get() { return GetWindow()->height; } + bool isSticky_get() + { + auto flags = GetWindow()->flags; + return (flags & (WF_STICK_TO_BACK | WF_STICK_TO_FRONT)) != 0; + } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); + dukglue_register_property(ctx, &ScWindow::y_get, &ScWindow::y_set, "y"); + dukglue_register_property(ctx, &ScWindow::width_get, nullptr, "width"); + dukglue_register_property(ctx, &ScWindow::height_get, nullptr, "height"); + dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); + } + + private: + rct_window * GetWindow() const + { + return window_find_by_number(_class, _number); + } + }; + + class ScUi + { + public: + sint32 width_get() { return context_get_width(); } + sint32 height_get() { return context_get_height(); } + sint32 windows_get() + { + return gWindowNextSlot - g_window_list; + } + + std::shared_ptr openWindow(DukValue desc) + { + return nullptr; + } + + void closeWindows(std::string classification, DukValue id) + { + auto cls = GetClassification(classification); + if (cls != WC_NULL) + { + if (id.type() == DukValue::Type::NUMBER) + { + window_close_by_number(cls, id.as_int()); + } + else + { + window_close_by_class(cls); + } + } + } + + void closeAllWindows() + { + window_close_all(); + } + + std::shared_ptr getWindow(sint32 index) + { + auto windowEnd = gWindowNextSlot; + auto i = 0; + for (auto w = g_window_list; w < windowEnd; w++) + { + if (i == index) + { + return std::make_shared(w->classification, w->number); + } + i++; + } + return nullptr; + } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScUi::height_get, nullptr, "height"); + dukglue_register_property(ctx, &ScUi::width_get, nullptr, "width"); + dukglue_register_property(ctx, &ScUi::windows_get, nullptr, "windows"); + dukglue_register_method(ctx, &ScUi::openWindow, "openWindow"); + dukglue_register_method(ctx, &ScUi::closeWindows, "closeWindows"); + dukglue_register_method(ctx, &ScUi::closeAllWindows, "closeAllWindows"); + dukglue_register_method(ctx, &ScUi::getWindow, "getWindow"); + } + + private: + rct_windowclass GetClassification(const std::string& key) + { + return WC_NULL; + } + }; +} diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 82ba255bf3..ed86d8576e 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -25,6 +25,7 @@ #include "ScPark.hpp" #include "ScTile.hpp" #include "ScThing.hpp" +#include "ScUi.hpp" using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -63,11 +64,14 @@ void ScriptEngine::Initialise() ScTile::Register(ctx); ScTileElement::Register(ctx); ScThing::Register(ctx); + ScUi::Register(ctx); + ScWindow::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); dukglue_register_global(ctx, std::make_shared(ctx), "map"); dukglue_register_global(ctx, std::make_shared(), "park"); + dukglue_register_global(ctx, std::make_shared(), "ui"); LoadPlugins(); StartPlugins(); From b47bcabaf1d87d0e6e26e942d3d2daa57b8672e1 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 24 Mar 2018 19:30:10 +0000 Subject: [PATCH 017/159] Move ui scripting API to libopenrct2ui --- src/openrct2-ui/CMakeLists.txt | 3 +- src/openrct2-ui/UiContext.cpp | 9 +++ .../scripting/ScUi.hpp | 54 +---------------- src/openrct2-ui/scripting/ScWindow.hpp | 58 +++++++++++++++++++ src/openrct2-ui/scripting/UiExtensions.cpp | 16 +++++ src/openrct2-ui/scripting/UiExtensions.h | 12 ++++ src/openrct2/Context.cpp | 1 + src/openrct2/scripting/ScriptEngine.cpp | 4 -- src/openrct2/scripting/ScriptEngine.h | 1 + src/openrct2/ui/DummyUiContext.cpp | 3 + src/openrct2/ui/UiContext.h | 1 + 11 files changed, 104 insertions(+), 58 deletions(-) rename src/{openrct2 => openrct2-ui}/scripting/ScUi.hpp (57%) create mode 100644 src/openrct2-ui/scripting/ScWindow.hpp create mode 100644 src/openrct2-ui/scripting/UiExtensions.cpp create mode 100644 src/openrct2-ui/scripting/UiExtensions.h diff --git a/src/openrct2-ui/CMakeLists.txt b/src/openrct2-ui/CMakeLists.txt index 440441b90c..0ff4920417 100644 --- a/src/openrct2-ui/CMakeLists.txt +++ b/src/openrct2-ui/CMakeLists.txt @@ -64,7 +64,8 @@ endif () # Includes target_include_directories(${PROJECT} PRIVATE "${CMAKE_CURRENT_LIST_DIR}/.." ${SPEEX_INCLUDE_DIRS}) -target_include_directories(${PROJECT} SYSTEM PRIVATE ${SDL2_INCLUDE_DIRS}) +target_include_directories(${PROJECT} SYSTEM PRIVATE ${SDL2_INCLUDE_DIRS} + "${CMAKE_CURRENT_LIST_DIR}/../openrct2/thirdparty") # Compiler flags if (WIN32) diff --git a/src/openrct2-ui/UiContext.cpp b/src/openrct2-ui/UiContext.cpp index 88c15d495d..1f75eac344 100644 --- a/src/openrct2-ui/UiContext.cpp +++ b/src/openrct2-ui/UiContext.cpp @@ -17,6 +17,7 @@ #include "input/KeyboardShortcuts.h" #include "interface/InGameConsole.h" #include "interface/Theme.h" +#include "scripting/UiExtensions.h" #include "title/TitleSequencePlayer.h" #include @@ -38,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -46,6 +48,7 @@ using namespace OpenRCT2; using namespace OpenRCT2::Drawing; using namespace OpenRCT2::Input; +using namespace OpenRCT2::Scripting; using namespace OpenRCT2::Ui; #ifdef __MACOSX__ @@ -115,6 +118,12 @@ public: delete _platformUiContext; } + void Initialise() override + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + UiScriptExtensions::Extend(scriptEngine); + } + void Update() override { _inGameConsole.Update(); diff --git a/src/openrct2/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp similarity index 57% rename from src/openrct2/scripting/ScUi.hpp rename to src/openrct2-ui/scripting/ScUi.hpp index a503f619e6..f3dea76ee1 100644 --- a/src/openrct2/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -5,62 +5,10 @@ #include #include "../common.h" #include "../Context.h" -#include "../interface/Window.h" -#include "../interface/Window_internal.h" -#include "../ui/UiContext.h" -#include "../ui/WindowManager.h" +#include "ScWindow.hpp" namespace OpenRCT2::Scripting { - class ScWindow - { - private: - rct_windowclass _class; - rct_windownumber _number; - - public: - ScWindow(rct_windowclass c, rct_windownumber n) - : _class(c), - _number(n) - { - } - - sint32 x_get() { return GetWindow()->x; } - void x_set(sint32 value) - { - auto w = GetWindow(); - window_set_position(w, value, w->y); - } - sint32 y_get() { return GetWindow()->y; } - void y_set(sint32 value) - { - auto w = GetWindow(); - window_set_position(w, w->x, value); - } - sint32 width_get() { return GetWindow()->width; } - sint32 height_get() { return GetWindow()->height; } - bool isSticky_get() - { - auto flags = GetWindow()->flags; - return (flags & (WF_STICK_TO_BACK | WF_STICK_TO_FRONT)) != 0; - } - - static void Register(duk_context * ctx) - { - dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); - dukglue_register_property(ctx, &ScWindow::y_get, &ScWindow::y_set, "y"); - dukglue_register_property(ctx, &ScWindow::width_get, nullptr, "width"); - dukglue_register_property(ctx, &ScWindow::height_get, nullptr, "height"); - dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); - } - - private: - rct_window * GetWindow() const - { - return window_find_by_number(_class, _number); - } - }; - class ScUi { public: diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp new file mode 100644 index 0000000000..40493029a0 --- /dev/null +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include +#include "../common.h" +#include "../interface/Window.h" +#include "../interface/Window_internal.h" + +namespace OpenRCT2::Scripting +{ + class ScWindow + { + private: + rct_windowclass _class; + rct_windownumber _number; + + public: + ScWindow(rct_windowclass c, rct_windownumber n) + : _class(c), + _number(n) + { + } + + sint32 x_get() { return GetWindow()->x; } + void x_set(sint32 value) + { + auto w = GetWindow(); + window_set_position(w, value, w->y); + } + sint32 y_get() { return GetWindow()->y; } + void y_set(sint32 value) + { + auto w = GetWindow(); + window_set_position(w, w->x, value); + } + sint32 width_get() { return GetWindow()->width; } + sint32 height_get() { return GetWindow()->height; } + bool isSticky_get() + { + auto flags = GetWindow()->flags; + return (flags & (WF_STICK_TO_BACK | WF_STICK_TO_FRONT)) != 0; + } + + static void Register(duk_context * ctx) + { + dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); + dukglue_register_property(ctx, &ScWindow::y_get, &ScWindow::y_set, "y"); + dukglue_register_property(ctx, &ScWindow::width_get, nullptr, "width"); + dukglue_register_property(ctx, &ScWindow::height_get, nullptr, "height"); + dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); + } + + private: + rct_window * GetWindow() const + { + return window_find_by_number(_class, _number); + } + }; +} diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp new file mode 100644 index 0000000000..78e8ee318f --- /dev/null +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -0,0 +1,16 @@ +#include +#include "UiExtensions.h" +#include "ScUi.hpp" +#include "ScWindow.hpp" + +using namespace OpenRCT2::Scripting; + +void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) +{ + auto ctx = scriptEngine.GetContext(); + + dukglue_register_global(ctx, std::make_shared(), "ui"); + + ScUi::Register(ctx); + ScWindow::Register(ctx); +} diff --git a/src/openrct2-ui/scripting/UiExtensions.h b/src/openrct2-ui/scripting/UiExtensions.h new file mode 100644 index 0000000000..08b05edd41 --- /dev/null +++ b/src/openrct2-ui/scripting/UiExtensions.h @@ -0,0 +1,12 @@ +#pragma once + +namespace OpenRCT2::Scripting +{ + class ScriptEngine; + + class UiScriptExtensions + { + public: + static void Extend(ScriptEngine& scriptEngine); + }; +} diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 63597337a9..9e32f46d35 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -464,6 +464,7 @@ namespace OpenRCT2 _gameState->InitAll(150); _titleScreen = std::make_unique(*_gameState); + _uiContext->Initialise(); return true; } diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index ed86d8576e..82ba255bf3 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -25,7 +25,6 @@ #include "ScPark.hpp" #include "ScTile.hpp" #include "ScThing.hpp" -#include "ScUi.hpp" using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -64,14 +63,11 @@ void ScriptEngine::Initialise() ScTile::Register(ctx); ScTileElement::Register(ctx); ScThing::Register(ctx); - ScUi::Register(ctx); - ScWindow::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); dukglue_register_global(ctx, std::make_shared(ctx), "map"); dukglue_register_global(ctx, std::make_shared(), "park"); - dukglue_register_global(ctx, std::make_shared(), "ui"); LoadPlugins(); StartPlugins(); diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 8d2f7b36a5..59457515d1 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -92,6 +92,7 @@ namespace OpenRCT2::Scripting ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); ScriptEngine(ScriptEngine&) = delete; + duk_context * GetContext() { return _context; } HookEngine& GetHookEngine() { return _hookEngine; } void Update(); diff --git a/src/openrct2/ui/DummyUiContext.cpp b/src/openrct2/ui/DummyUiContext.cpp index b81d478557..ceaa7669c0 100644 --- a/src/openrct2/ui/DummyUiContext.cpp +++ b/src/openrct2/ui/DummyUiContext.cpp @@ -24,6 +24,9 @@ namespace OpenRCT2::Ui IWindowManager* const _windowManager = CreateDummyWindowManager(); public: + void Initialise() override + { + } void Update() override { } diff --git a/src/openrct2/ui/UiContext.h b/src/openrct2/ui/UiContext.h index bcf8290421..4be9911130 100644 --- a/src/openrct2/ui/UiContext.h +++ b/src/openrct2/ui/UiContext.h @@ -91,6 +91,7 @@ namespace OpenRCT2 { virtual ~IUiContext() = default; + virtual void Initialise() abstract; virtual void Update() abstract; virtual void Draw(rct_drawpixelinfo * dpi) abstract; From 291143c3cd298342e950473cb3944d783d826762 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 25 Mar 2018 18:23:24 +0100 Subject: [PATCH 018/159] Add opening of a custom window --- distribution/openrct2.d.ts | 2 + src/openrct2-ui/scripting/CustomWindow.cpp | 275 +++++++++++++++++++++ src/openrct2-ui/scripting/ScUi.hpp | 35 ++- src/openrct2-ui/scripting/ScWindow.hpp | 5 + src/openrct2-ui/scripting/UiExtensions.cpp | 2 +- src/openrct2/interface/Window.h | 1 + src/openrct2/interface/Window_internal.h | 1 + src/openrct2/scripting/ScriptEngine.h | 1 + 8 files changed, 318 insertions(+), 4 deletions(-) create mode 100644 src/openrct2-ui/scripting/CustomWindow.cpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 610c9c4bfa..c9974c0dad 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -146,6 +146,8 @@ export interface WindowDesc { height: number; title: string; id?: number; + minWidth?: number; + minHeight?: number; } export interface Ui { diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp new file mode 100644 index 0000000000..14d85bb9e3 --- /dev/null +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -0,0 +1,275 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "ScUi.hpp" +#include "ScWindow.hpp" + +using namespace OpenRCT2; +using namespace OpenRCT2::Scripting; + +namespace OpenRCT2::Ui::Windows +{ + enum + { + WIDX_BACKGROUND, + WIDX_TITLE, + WIDX_CLOSE, + WIDX_CONTENT_PANEL, + }; + + static rct_widget window_custom_widgets[] = { + { WWT_FRAME, 0, 0, 0, 0, 0, 0xFFFFFFFF, STR_NONE }, // panel / background + { WWT_CAPTION, 0, 1, 0, 1, 14, STR_STRING, STR_WINDOW_TITLE_TIP }, // title bar + { WWT_CLOSEBOX, 0, 0, 0, 2, 13, STR_CLOSE_X, STR_CLOSE_WINDOW_TIP }, // close x button + { WWT_RESIZE, 1, 0, 0, 14, 0, 0xFFFFFFFF, STR_NONE }, // content panel + { WIDGETS_END }, + }; + + static void window_custom_close(rct_window *w); + static void window_custom_mouseup(rct_window *w, rct_widgetindex widgetIndex); + static void window_custom_resize(rct_window *w); + static void window_custom_scrollgetsize(rct_window *w, sint32 scrollIndex, sint32 *width, sint32 *height); + static void window_custom_invalidate(rct_window *w); + static void window_custom_paint(rct_window *w, rct_drawpixelinfo *dpi); + static void window_custom_scrollpaint(rct_window *w, rct_drawpixelinfo *dpi, sint32 scrollIndex); + + static rct_window_event_list window_custom_events = + { + window_custom_close, + window_custom_mouseup, + window_custom_resize, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + window_custom_invalidate, + window_custom_paint, + nullptr + }; + + struct CustomWindowDesc + { + std::string Classification; + std::optional X; + std::optional Y; + sint32 Width; + sint32 Height; + std::optional MinWidth; + std::optional MinHeight; + std::optional MaxWidth; + std::optional MaxHeight; + std::string Title; + std::optional Id; + + CustomWindowDesc() = default; + + bool IsResizable() const + { + return MinWidth || MinHeight || MaxWidth || MaxHeight; + } + + static CustomWindowDesc FromDukValue(DukValue desc) + { + CustomWindowDesc result; + result.Classification = desc["classification"].as_string(); + result.X = GetOptionalInt(desc["x"]); + result.Y = GetOptionalInt(desc["y"]); + result.Width = desc["width"].as_int(); + result.Height = desc["height"].as_int(); + result.MinWidth = GetOptionalInt(desc["minWidth"]); + result.MaxWidth = GetOptionalInt(desc["maxWidth"]); + result.MinHeight = GetOptionalInt(desc["minHeight"]); + result.MaxHeight = GetOptionalInt(desc["maxHeight"]); + result.Title = desc["title"].as_string(); + result.Id = GetOptionalInt(desc["id"]); + return std::move(result); + } + + static std::optional GetOptionalInt(DukValue input) + { + return input.type() == DukValue::Type::NUMBER ? + std::make_optional(input.as_int()) : + std::nullopt; + } + }; + + class CustomWindowInfo + { + private: + rct_windowclass _class; + rct_windownumber _number; + + public: + std::shared_ptr Owner; + CustomWindowDesc Desc; + + CustomWindowInfo( + rct_windowclass cls, + rct_windownumber number, + std::shared_ptr owner, + const CustomWindowDesc& desc) + : _class(cls), + _number(number), + Owner(owner), + Desc(desc) + { + } + + CustomWindowInfo(const CustomWindowInfo&) = delete; + }; + + static rct_windownumber _nextWindowNumber; + + static CustomWindowInfo& GetInfo(rct_window * w); + static rct_windownumber GetNewWindowNumber(); + + rct_window * window_custom_open(std::shared_ptr owner, DukValue dukDesc) + { + auto desc = CustomWindowDesc::FromDukValue(dukDesc); + + uint16 windowFlags = 0; + if (desc.IsResizable()) + { + windowFlags |= WF_RESIZABLE; + } + + rct_window * window; + if (desc.X && desc.Y) + { + window = window_create( + desc.X.value(), + desc.Y.value(), + desc.Width, + desc.Height, + &window_custom_events, + WC_CUSTOM, + windowFlags); + } + else + { + window = window_create_auto_pos( + desc.Width, + desc.Height, + &window_custom_events, + WC_CUSTOM, + windowFlags); + } + + window->number = GetNewWindowNumber(); + window->custom_info = new CustomWindowInfo(window->classification, window->number, owner, desc); + window->widgets = window_custom_widgets; + window->enabled_widgets = (1 << WIDX_CLOSE); + window->colours[0] = COLOUR_GREY; + window->colours[1] = COLOUR_GREY; + window->colours[2] = COLOUR_GREY; + if (desc.IsResizable()) + { + window->min_width = desc.MinWidth.value_or(0); + window->min_height = desc.MinHeight.value_or(0); + window->max_width = desc.MaxWidth.value_or(std::numeric_limits::max()); + window->max_height = desc.MaxHeight.value_or(std::numeric_limits::max()); + } + + window_init_scroll_widgets(window); + return window; + } + + static void window_custom_close(rct_window * w) + { + delete static_cast(w->custom_info); + w->custom_info = nullptr; + } + + static void window_custom_mouseup(rct_window * w, rct_widgetindex widgetIndex) + { + switch (widgetIndex) { + case WIDX_CLOSE: + window_close(w); + break; + } + } + + static void window_custom_resize(rct_window * w) + { + const auto& desc = GetInfo(w).Desc; + if (desc.IsResizable()) + { + if (w->width < w->min_width) + { + window_invalidate(w); + w->width = w->min_width; + } + if (w->height < w->min_height) + { + window_invalidate(w); + w->height = w->min_height; + } + } + } + + static void window_custom_invalidate(rct_window * w) + { + window_custom_widgets[WIDX_BACKGROUND].right = w->width - 1; + window_custom_widgets[WIDX_BACKGROUND].bottom = w->height - 1; + window_custom_widgets[WIDX_TITLE].right = w->width - 2; + window_custom_widgets[WIDX_CLOSE].left = w->width - 13; + window_custom_widgets[WIDX_CLOSE].right = w->width - 3; + window_custom_widgets[WIDX_CONTENT_PANEL].right = w->width - 1; + window_custom_widgets[WIDX_CONTENT_PANEL].bottom = w->height - 1; + + const auto& desc = GetInfo(w).Desc; + set_format_arg(0, void *, desc.Title.c_str()); + } + + static void window_custom_paint(rct_window * w, rct_drawpixelinfo * dpi) + { + window_draw_widgets(w, dpi); + } + + static CustomWindowInfo& GetInfo(rct_window * w) + { + return *(static_cast(w->custom_info)); + } + + static rct_windownumber GetNewWindowNumber() + { + auto result = _nextWindowNumber++; + while (window_find_by_number(WC_CUSTOM, result) != nullptr) + { + result++; + } + return result; + } +} diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index f3dea76ee1..04862be3f5 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -1,17 +1,35 @@ #pragma once -#include #include +#include #include +#include #include "../common.h" #include "../Context.h" #include "ScWindow.hpp" +namespace OpenRCT2::Scripting +{ + class Plugin; +} + +namespace OpenRCT2::Ui::Windows +{ + rct_window * window_custom_open(std::shared_ptr owner, DukValue dukDesc); +} + namespace OpenRCT2::Scripting { class ScUi { + private: + ScriptEngine& _scriptEngine; public: + ScUi(ScriptEngine& scriptEngine) + : _scriptEngine(scriptEngine) + { + } + sint32 width_get() { return context_get_width(); } sint32 height_get() { return context_get_height(); } sint32 windows_get() @@ -21,7 +39,18 @@ namespace OpenRCT2::Scripting std::shared_ptr openWindow(DukValue desc) { - return nullptr; + using namespace OpenRCT2::Ui::Windows; + + auto& execInfo = _scriptEngine.GetExecInfo(); + auto owner = execInfo.GetCurrentPlugin(); + + std::shared_ptr scWindow = nullptr; + auto w = window_custom_open(owner, desc); + if (w != nullptr) + { + scWindow = std::make_shared(w); + } + return scWindow; } void closeWindows(std::string classification, DukValue id) @@ -53,7 +82,7 @@ namespace OpenRCT2::Scripting { if (i == index) { - return std::make_shared(w->classification, w->number); + return std::make_shared(w); } i++; } diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 40493029a0..a38b01eaba 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -14,6 +14,11 @@ namespace OpenRCT2::Scripting rct_windownumber _number; public: + ScWindow(rct_window * w) + { + ScWindow(w->classification, w->number); + } + ScWindow(rct_windowclass c, rct_windownumber n) : _class(c), _number(n) diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index 78e8ee318f..e7ea265d9a 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -9,7 +9,7 @@ void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) { auto ctx = scriptEngine.GetContext(); - dukglue_register_global(ctx, std::make_shared(), "ui"); + dukglue_register_global(ctx, std::make_shared(scriptEngine), "ui"); ScUi::Register(ctx); ScWindow::Register(ctx); diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index 07c84854fa..4fd71c4207 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -443,6 +443,7 @@ enum WC_EDITOR_SCENARIO_BOTTOM_TOOLBAR = 222, WC_CHAT = 223, WC_CONSOLE = 224, + WC_CUSTOM = 225, WC_NULL = 255, }; diff --git a/src/openrct2/interface/Window_internal.h b/src/openrct2/interface/Window_internal.h index 7fdcb62c39..1ba55eab3c 100644 --- a/src/openrct2/interface/Window_internal.h +++ b/src/openrct2/interface/Window_internal.h @@ -55,6 +55,7 @@ struct rct_window scenery_variables scenery; track_list_variables track_list; error_variables error; + void * custom_info; }; int16_t page; union diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 59457515d1..5a11d519e5 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -94,6 +94,7 @@ namespace OpenRCT2::Scripting duk_context * GetContext() { return _context; } HookEngine& GetHookEngine() { return _hookEngine; } + ScriptExecutionInfo& GetExecInfo() { return _execInfo; } void Update(); std::future Eval(const std::string &s); From 918022da3ef59a3f25882404ff2b94dc49d44dda Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 25 Mar 2018 22:04:36 +0100 Subject: [PATCH 019/159] Get custom buttons working --- distribution/openrct2.d.ts | 24 +++++ src/openrct2-ui/interface/Widget.cpp | 18 +++- src/openrct2-ui/scripting/CustomWindow.cpp | 120 +++++++++++++++++++-- src/openrct2/interface/Window.h | 9 ++ 4 files changed, 158 insertions(+), 13 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index c9974c0dad..349bcffa70 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -122,6 +122,7 @@ export interface Park { bankLoan: number; maxBankLoan: number; + postMessage(message: string): void; postMessage(message: ParkMessage): void; } @@ -138,6 +139,28 @@ export interface Window { close(): void; } +export type WidgetType = + "button" | "dropdown"; + +export interface Widget { + type: WidgetType; + x: number; + y: number; + width: number; + height: number; +} + +export interface ButtonWidget extends Widget { + text: string; + onClick: () => void; +} + +export interface DropdownWidget extends Widget { + items: string[]; + selectedIndex: number; + onChanged: (index: number) => void; +} + export interface WindowDesc { classification: string; x?: number; @@ -148,6 +171,7 @@ export interface WindowDesc { id?: number; minWidth?: number; minHeight?: number; + widgets?: Widget[]; } export interface Ui { diff --git a/src/openrct2-ui/interface/Widget.cpp b/src/openrct2-ui/interface/Widget.cpp index 8e013ea215..b5cc9cfd16 100644 --- a/src/openrct2-ui/interface/Widget.cpp +++ b/src/openrct2-ui/interface/Widget.cpp @@ -361,8 +361,15 @@ static void widget_text_centred(rct_drawpixelinfo* dpi, rct_window* w, rct_widge else t = w->windowPos.y + widget->top; + auto stringId = widget->text; + void * formatArgs = gCommonFormatArgs; + if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) + { + stringId = STR_STRING; + formatArgs = &widget->string; + } gfx_draw_string_centred_clipped( - dpi, widget->text, gCommonFormatArgs, colour, (l + r + 1) / 2 - 1, t, widget->right - widget->left - 2); + dpi, stringId, formatArgs, colour, (l + r + 1) / 2 - 1, t, widget->right - widget->left - 2); } /** @@ -399,7 +406,14 @@ static void widget_text(rct_drawpixelinfo* dpi, rct_window* w, rct_widgetindex w else t = w->windowPos.y + widget->top; - gfx_draw_string_left_clipped(dpi, widget->text, gCommonFormatArgs, colour, l + 1, t, r - l); + auto stringId = widget->text; + void * formatArgs = gCommonFormatArgs; + if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) + { + stringId = STR_STRING; + formatArgs = &widget->string; + } + gfx_draw_string_left_clipped(dpi, stringId, formatArgs, colour, l + 1, t, r - l); } /** diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 14d85bb9e3..3d4a67f6a1 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -9,6 +9,8 @@ #include #include +#include +#include #include #include #include @@ -29,14 +31,14 @@ namespace OpenRCT2::Ui::Windows WIDX_TITLE, WIDX_CLOSE, WIDX_CONTENT_PANEL, + WIDX_CUSTOM_BEGIN, }; - static rct_widget window_custom_widgets[] = { + static rct_widget CustomDefaultWidgets[] = { { WWT_FRAME, 0, 0, 0, 0, 0, 0xFFFFFFFF, STR_NONE }, // panel / background { WWT_CAPTION, 0, 1, 0, 1, 14, STR_STRING, STR_WINDOW_TITLE_TIP }, // title bar { WWT_CLOSEBOX, 0, 0, 0, 2, 13, STR_CLOSE_X, STR_CLOSE_WINDOW_TIP }, // close x button { WWT_RESIZE, 1, 0, 0, 14, 0, 0xFFFFFFFF, STR_NONE }, // content panel - { WIDGETS_END }, }; static void window_custom_close(rct_window *w); @@ -79,6 +81,33 @@ namespace OpenRCT2::Ui::Windows nullptr }; + struct CustomWidgetDesc + { + // Properties + std::string Type; + sint32 X; + sint32 Y; + sint32 Width; + sint32 Height; + std::string Text; + + // Event handlers + DukValue OnClick; + + static CustomWidgetDesc FromDukValue(DukValue desc) + { + CustomWidgetDesc result; + result.Type = desc["type"].as_string(); + result.X = desc["x"].as_int(); + result.Y = desc["y"].as_int(); + result.Width = desc["width"].as_int(); + result.Height = desc["height"].as_int(); + result.Text = desc["text"].as_string(); + result.OnClick = desc["onClick"]; + return result; + } + }; + struct CustomWindowDesc { std::string Classification; @@ -92,6 +121,7 @@ namespace OpenRCT2::Ui::Windows std::optional MaxHeight; std::string Title; std::optional Id; + std::vector Widgets; CustomWindowDesc() = default; @@ -114,6 +144,14 @@ namespace OpenRCT2::Ui::Windows result.MaxHeight = GetOptionalInt(desc["maxHeight"]); result.Title = desc["title"].as_string(); result.Id = GetOptionalInt(desc["id"]); + + if (desc["widgets"].is_array()) + { + auto dukWidgets = desc["widgets"].as_array(); + std::transform(dukWidgets.begin(), dukWidgets.end(), std::back_inserter(result.Widgets), + [](const DukValue& w) { return CustomWidgetDesc::FromDukValue(w); }); + } + return std::move(result); } @@ -134,6 +172,7 @@ namespace OpenRCT2::Ui::Windows public: std::shared_ptr Owner; CustomWindowDesc Desc; + std::vector Widgets; CustomWindowInfo( rct_windowclass cls, @@ -154,6 +193,8 @@ namespace OpenRCT2::Ui::Windows static CustomWindowInfo& GetInfo(rct_window * w); static rct_windownumber GetNewWindowNumber(); + static void RefreshWidgets(rct_window * w); + static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler); rct_window * window_custom_open(std::shared_ptr owner, DukValue dukDesc) { @@ -189,7 +230,6 @@ namespace OpenRCT2::Ui::Windows window->number = GetNewWindowNumber(); window->custom_info = new CustomWindowInfo(window->classification, window->number, owner, desc); - window->widgets = window_custom_widgets; window->enabled_widgets = (1 << WIDX_CLOSE); window->colours[0] = COLOUR_GREY; window->colours[1] = COLOUR_GREY; @@ -201,7 +241,7 @@ namespace OpenRCT2::Ui::Windows window->max_width = desc.MaxWidth.value_or(std::numeric_limits::max()); window->max_height = desc.MaxHeight.value_or(std::numeric_limits::max()); } - + RefreshWidgets(window); window_init_scroll_widgets(window); return window; } @@ -218,6 +258,13 @@ namespace OpenRCT2::Ui::Windows case WIDX_CLOSE: window_close(w); break; + default: + { + const auto& info = GetInfo(w); + const auto& widgetDesc = info.Desc.Widgets[widgetIndex - WIDX_CUSTOM_BEGIN]; + InvokeEventHandler(info.Owner, widgetDesc.OnClick); + break; + } } } @@ -241,13 +288,13 @@ namespace OpenRCT2::Ui::Windows static void window_custom_invalidate(rct_window * w) { - window_custom_widgets[WIDX_BACKGROUND].right = w->width - 1; - window_custom_widgets[WIDX_BACKGROUND].bottom = w->height - 1; - window_custom_widgets[WIDX_TITLE].right = w->width - 2; - window_custom_widgets[WIDX_CLOSE].left = w->width - 13; - window_custom_widgets[WIDX_CLOSE].right = w->width - 3; - window_custom_widgets[WIDX_CONTENT_PANEL].right = w->width - 1; - window_custom_widgets[WIDX_CONTENT_PANEL].bottom = w->height - 1; + w->widgets[WIDX_BACKGROUND].right = w->width - 1; + w->widgets[WIDX_BACKGROUND].bottom = w->height - 1; + w->widgets[WIDX_TITLE].right = w->width - 2; + w->widgets[WIDX_CLOSE].left = w->width - 13; + w->widgets[WIDX_CLOSE].right = w->width - 3; + w->widgets[WIDX_CONTENT_PANEL].right = w->width - 1; + w->widgets[WIDX_CONTENT_PANEL].bottom = w->height - 1; const auto& desc = GetInfo(w).Desc; set_format_arg(0, void *, desc.Title.c_str()); @@ -272,4 +319,55 @@ namespace OpenRCT2::Ui::Windows } return result; } + + static void RefreshWidgets(rct_window * w) + { + auto& info = GetInfo(w); + auto& widgets = info.Widgets; + + widgets.clear(); + + // Add default widgets (window shim) + widgets.insert(widgets.begin(), std::begin(CustomDefaultWidgets), std::end(CustomDefaultWidgets)); + w->enabled_widgets = 1ULL << WIDX_CLOSE; + + // Add custom widgets + for (const auto& widgetDesc : info.Desc.Widgets) + { + rct_widget widget{}; + widget.type = WWT_BUTTON; + widget.left = widgetDesc.X; + widget.top = widgetDesc.Y; + widget.right = widgetDesc.X + widgetDesc.Width; + widget.bottom = widgetDesc.Y + widgetDesc.Height; + widget.string = (utf8*)widgetDesc.Text.c_str(); + widget.tooltip = STR_NONE; + widget.flags = WIDGET_FLAGS::TEXT_IS_STRING; + widgets.push_back(widget); + + auto widgetIndex = widgets.size() - 1; + if (widgetIndex < 64) + { + w->enabled_widgets |= 1ULL << widgetIndex; + } + } + + widgets.push_back({ WIDGETS_END }); + w->widgets = widgets.data(); + } + + static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler) + { + if (dukHandler.is_function()) + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto& execInfo = scriptEngine.GetExecInfo(); + { + ScriptExecutionInfo::PluginScope scope(execInfo, owner); + dukHandler.push(); + duk_pcall(dukHandler.context(), 0); + duk_pop(dukHandler.context()); + } + } + } } diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index 4fd71c4207..63a6ec4912 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -64,6 +64,12 @@ struct widget_identifier extern widget_identifier gCurrentTextBox; +using WidgetFlags = uint32; +namespace WIDGET_FLAGS +{ + const uint32 TEXT_IS_STRING = 1 << 0; +} + /** * Widget structure * size: 0x10 @@ -84,6 +90,9 @@ struct rct_widget utf8* string; }; rct_string_id tooltip; // 0x0E + + // New properties + WidgetFlags flags; }; /** From 7047dec1d95e809e1b831716c11a1c2d6530edcc Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 25 Mar 2018 23:27:19 +0100 Subject: [PATCH 020/159] Get custom drop downs working Co-authored-by: Hielke Morsink --- src/openrct2-ui/scripting/CustomWindow.cpp | 219 +++++++++++++++++---- src/openrct2-ui/scripting/ScUi.hpp | 7 +- src/openrct2/interface/StdInOutConsole.cpp | 2 +- src/openrct2/interface/Window.h | 3 +- src/openrct2/scripting/Plugin.cpp | 21 +- src/openrct2/scripting/ScConsole.hpp | 2 +- src/openrct2/scripting/ScPark.hpp | 4 +- src/openrct2/scripting/ScTile.hpp | 4 +- src/openrct2/thirdparty/dukglue/dukglue.h | 9 +- 9 files changed, 221 insertions(+), 50 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 3d4a67f6a1..1bfd2de279 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -17,6 +17,7 @@ #include #include #include +#include "../interface/Dropdown.h" #include "ScUi.hpp" #include "ScWindow.hpp" @@ -41,21 +42,21 @@ namespace OpenRCT2::Ui::Windows { WWT_RESIZE, 1, 0, 0, 14, 0, 0xFFFFFFFF, STR_NONE }, // content panel }; - static void window_custom_close(rct_window *w); - static void window_custom_mouseup(rct_window *w, rct_widgetindex widgetIndex); - static void window_custom_resize(rct_window *w); - static void window_custom_scrollgetsize(rct_window *w, sint32 scrollIndex, sint32 *width, sint32 *height); - static void window_custom_invalidate(rct_window *w); - static void window_custom_paint(rct_window *w, rct_drawpixelinfo *dpi); - static void window_custom_scrollpaint(rct_window *w, rct_drawpixelinfo *dpi, sint32 scrollIndex); + static void window_custom_close(rct_window * w); + static void window_custom_mouseup(rct_window * w, rct_widgetindex widgetIndex); + static void window_custom_mousedown(rct_window * w, rct_widgetindex widgetIndex, rct_widget * widget); + static void window_custom_resize(rct_window * w); + static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, sint32 dropdownIndex); + static void window_custom_invalidate(rct_window * w); + static void window_custom_paint(rct_window * w, rct_drawpixelinfo * dpi); static rct_window_event_list window_custom_events = { window_custom_close, window_custom_mouseup, window_custom_resize, - nullptr, - nullptr, + window_custom_mousedown, + window_custom_dropdown, nullptr, nullptr, nullptr, @@ -85,14 +86,17 @@ namespace OpenRCT2::Ui::Windows { // Properties std::string Type; - sint32 X; - sint32 Y; - sint32 Width; - sint32 Height; + sint32 X{}; + sint32 Y{}; + sint32 Width{}; + sint32 Height{}; std::string Text; + std::vector Items; + sint32 SelectedIndex{}; // Event handlers DukValue OnClick; + DukValue OnChange; static CustomWidgetDesc FromDukValue(DukValue desc) { @@ -102,8 +106,21 @@ namespace OpenRCT2::Ui::Windows result.Y = desc["y"].as_int(); result.Width = desc["width"].as_int(); result.Height = desc["height"].as_int(); - result.Text = desc["text"].as_string(); - result.OnClick = desc["onClick"]; + if (result.Type == "button") + { + result.Text = desc["text"].as_string(); + result.OnClick = desc["onClick"]; + } + else if (result.Type == "dropdown") + { + auto dukItems = desc["items"].as_array(); + for (const auto& dukItem : dukItems) + { + result.Items.push_back(dukItem.as_string()); + } + result.SelectedIndex = desc["selectedIndex"].as_int(); + result.OnChange = desc["onChange"]; + } return result; } }; @@ -173,6 +190,7 @@ namespace OpenRCT2::Ui::Windows std::shared_ptr Owner; CustomWindowDesc Desc; std::vector Widgets; + std::vector WidgetIndexMap; CustomWindowInfo( rct_windowclass cls, @@ -187,6 +205,19 @@ namespace OpenRCT2::Ui::Windows } CustomWindowInfo(const CustomWindowInfo&) = delete; + + const CustomWidgetDesc * GetCustomWidgetDesc(size_t widgetIndex) const + { + if (widgetIndex < WidgetIndexMap.size()) + { + auto widgetDescIndex = WidgetIndexMap[widgetIndex]; + if (widgetDescIndex < Desc.Widgets.size()) + { + return &Desc.Widgets[widgetDescIndex]; + } + } + return nullptr; + } }; static rct_windownumber _nextWindowNumber; @@ -195,6 +226,7 @@ namespace OpenRCT2::Ui::Windows static rct_windownumber GetNewWindowNumber(); static void RefreshWidgets(rct_window * w); static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler); + static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args); rct_window * window_custom_open(std::shared_ptr owner, DukValue dukDesc) { @@ -261,8 +293,14 @@ namespace OpenRCT2::Ui::Windows default: { const auto& info = GetInfo(w); - const auto& widgetDesc = info.Desc.Widgets[widgetIndex - WIDX_CUSTOM_BEGIN]; - InvokeEventHandler(info.Owner, widgetDesc.OnClick); + const auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); + if (widgetDesc != nullptr) + { + if (widgetDesc->Type == "button") + { + InvokeEventHandler(info.Owner, widgetDesc->OnClick); + } + } break; } } @@ -286,6 +324,61 @@ namespace OpenRCT2::Ui::Windows } } + static void window_custom_mousedown(rct_window * w, rct_widgetindex widgetIndex, rct_widget * widget) + { + const auto& info = GetInfo(w); + const auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); + if (widgetDesc != nullptr) + { + if (widgetDesc->Type == "dropdown") + { + widget--; + const auto& items = widgetDesc->Items; + const auto numItems = std::min(items.size(), DROPDOWN_ITEMS_MAX_SIZE); + for (size_t i = 0; i < numItems; i++) + { + gDropdownItemsFormat[i] = STR_STRING; + set_format_arg_on((uint8*)&gDropdownItemsArgs[i], 0, const char *, items[i].c_str()); + } + window_dropdown_show_text_custom_width( + w->x + widget->left, + w->y + widget->top, + widget->bottom - widget->top + 1, + w->colours[widget->colour], + 0, + DROPDOWN_FLAG_STAY_OPEN, + numItems, + widget->right - widget->left - 3); + } + } + } + + static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, sint32 dropdownIndex) + { + if (dropdownIndex == -1) + return; + + const auto& info = GetInfo(w); + const auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); + if (widgetDesc != nullptr) + { + if (widgetDesc->Type == "dropdown") + { + if (dropdownIndex >= 0 && (size_t)dropdownIndex < widgetDesc->Items.size()) + { + std::vector args; + auto ctx = widgetDesc->OnChange.context(); + duk_push_int(ctx, dropdownIndex); + args.push_back(DukValue::take_from_stack(ctx)); + InvokeEventHandler(info.Owner, widgetDesc->OnChange, args); + + auto& widget = w->widgets[widgetIndex - 1]; + widget.string = (utf8*)widgetDesc->Items[dropdownIndex].c_str(); + } + } + } + } + static void window_custom_invalidate(rct_window * w) { w->widgets[WIDX_BACKGROUND].right = w->width - 1; @@ -320,6 +413,49 @@ namespace OpenRCT2::Ui::Windows return result; } + static void CreateWidget(std::vector& widgetList, const CustomWidgetDesc &desc) + { + rct_widget widget{}; + widget.colour = 1; + widget.left = desc.X; + widget.top = desc.Y; + widget.right = desc.X + desc.Width; + widget.bottom = desc.Y + desc.Height; + widget.tooltip = STR_NONE; + widget.flags = WIDGET_FLAGS::IS_ENABLED; + + if (desc.Type == "button") + { + widget.type = WWT_BUTTON; + widget.string = (utf8*)desc.Text.c_str(); + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + widgetList.push_back(widget); + } + else if (desc.Type == "dropdown") + { + widget.type = WWT_DROPDOWN; + if (desc.SelectedIndex >= 0 && (size_t)desc.SelectedIndex < desc.Items.size()) + { + widget.string = (utf8*)desc.Items[desc.SelectedIndex].c_str(); + } + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + widgetList.push_back(widget); + + // Add the dropdown button + widget = {}; + widget.type = WWT_BUTTON; + widget.colour = 1; + widget.left = desc.X + desc.Width - 11; + widget.right = desc.X + desc.Width - 1; + widget.top = desc.Y + 1; + widget.bottom = desc.Y + desc.Height - 1; + widget.text = STR_DROPDOWN_GLYPH; + widget.tooltip = STR_NONE; + widget.flags |= WIDGET_FLAGS::IS_ENABLED; + widgetList.push_back(widget); + } + } + static void RefreshWidgets(rct_window * w) { auto& info = GetInfo(w); @@ -329,34 +465,45 @@ namespace OpenRCT2::Ui::Windows // Add default widgets (window shim) widgets.insert(widgets.begin(), std::begin(CustomDefaultWidgets), std::end(CustomDefaultWidgets)); - w->enabled_widgets = 1ULL << WIDX_CLOSE; + for (size_t i = 0; i < widgets.size(); i++) + { + info.WidgetIndexMap.push_back(std::numeric_limits::max()); + } // Add custom widgets - for (const auto& widgetDesc : info.Desc.Widgets) + for (size_t widgetDescIndex = 0; widgetDescIndex < info.Desc.Widgets.size(); widgetDescIndex++) { - rct_widget widget{}; - widget.type = WWT_BUTTON; - widget.left = widgetDesc.X; - widget.top = widgetDesc.Y; - widget.right = widgetDesc.X + widgetDesc.Width; - widget.bottom = widgetDesc.Y + widgetDesc.Height; - widget.string = (utf8*)widgetDesc.Text.c_str(); - widget.tooltip = STR_NONE; - widget.flags = WIDGET_FLAGS::TEXT_IS_STRING; - widgets.push_back(widget); - - auto widgetIndex = widgets.size() - 1; - if (widgetIndex < 64) + const auto& widgetDesc = info.Desc.Widgets[widgetDescIndex]; + auto preWidgetSize = widgets.size(); + CreateWidget(widgets, widgetDesc); + auto numWidetsAdded = widgets.size() - preWidgetSize; + for (size_t i = 0; i < numWidetsAdded; i++) { - w->enabled_widgets |= 1ULL << widgetIndex; + info.WidgetIndexMap.push_back(widgetDescIndex); } } widgets.push_back({ WIDGETS_END }); w->widgets = widgets.data(); + + // Enable widgets + w->enabled_widgets = 1ULL << WIDX_CLOSE; + for (size_t i = 0; i < std::min(widgets.size(), 64); i++) + { + if (widgets[i].flags & WIDGET_FLAGS::IS_ENABLED) + { + w->enabled_widgets |= 1ULL << i; + } + } } static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler) + { + std::vector args; + InvokeEventHandler(owner, dukHandler, args); + } + + static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args) { if (dukHandler.is_function()) { @@ -365,7 +512,11 @@ namespace OpenRCT2::Ui::Windows { ScriptExecutionInfo::PluginScope scope(execInfo, owner); dukHandler.push(); - duk_pcall(dukHandler.context(), 0); + for (const auto& arg : args) + { + arg.push(); + } + duk_pcall(dukHandler.context(), (duk_idx_t)args.size()); duk_pop(dukHandler.context()); } } diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 04862be3f5..28e9852c2a 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -34,7 +34,7 @@ namespace OpenRCT2::Scripting sint32 height_get() { return context_get_height(); } sint32 windows_get() { - return gWindowNextSlot - g_window_list; + return static_cast(g_window_list.size()); } std::shared_ptr openWindow(DukValue desc) @@ -76,12 +76,11 @@ namespace OpenRCT2::Scripting std::shared_ptr getWindow(sint32 index) { - auto windowEnd = gWindowNextSlot; - auto i = 0; - for (auto w = g_window_list; w < windowEnd; w++) + for (sint32 i = 0; i < g_window_list.size(); i++) { if (i == index) { + auto w = g_window_list[i].get(); return std::make_shared(w); } i++; diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index 9491b00cd7..c4338d98bb 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -7,11 +7,11 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ +#include #include "../Context.h" #include "../OpenRCT2.h" #include "../platform/Platform2.h" #include "../scripting/ScriptEngine.h" -#include "../thirdparty/linenoise.hpp" #include "InteractiveConsole.h" using namespace OpenRCT2; diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index 63a6ec4912..5f6e6c36b6 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -67,7 +67,8 @@ extern widget_identifier gCurrentTextBox; using WidgetFlags = uint32; namespace WIDGET_FLAGS { - const uint32 TEXT_IS_STRING = 1 << 0; + const WidgetFlags TEXT_IS_STRING = 1 << 0; + const WidgetFlags IS_ENABLED = 1 << 1; } /** diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index ce482f3267..6b55cda62e 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -21,10 +21,14 @@ #include #include -#include -#include -#include -#include +#ifdef _WIN32 + +#else + #include + #include + #include + #include +#endif using namespace OpenRCT2::Scripting; @@ -95,6 +99,8 @@ void Plugin::Update() void Plugin::EnableHotReload() { +#ifdef _WIN32 +#else auto fd = inotify_init(); if (fd >= 0) { @@ -114,12 +120,15 @@ void Plugin::EnableHotReload() close(fd); } } +#endif } bool Plugin::ShouldHotReload() { if (_hotReloadEnabled) { +#ifdef _WIN32 +#else std::vector eventData; eventData.resize(1024); @@ -134,6 +143,7 @@ bool Plugin::ShouldHotReload() } offset += sizeof(inotify_event) + e->len; } +#endif } return false; } @@ -142,8 +152,11 @@ void Plugin::DisableHotReload() { if (_hotReloadEnabled) { +#ifdef _WIN32 +#else inotify_rm_watch(_hotReloadData.FileDesc, _hotReloadData.WatchDesc); close(_hotReloadData.FileDesc); +#endif _hotReloadData = HotReloadData(); _hotReloadEnabled = false; } diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index 10f5916de9..b3c908b697 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -1,7 +1,7 @@ #pragma once #include -#include "../interface/Console.h" +#include "../interface/InteractiveConsole.h" namespace OpenRCT2::Scripting { diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 3bbab2db7d..656904179a 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -61,7 +61,7 @@ namespace OpenRCT2::Scripting type = GetParkMessageType(message["type"].as_string()); text = message["text"].as_string(); } - news_item_add_to_queue_raw(type, text.c_str(), -1); + news_item_add_to_queue_raw(type, text.c_str(), static_cast(-1)); } catch (const std::exception&) { @@ -80,7 +80,7 @@ namespace OpenRCT2::Scripting private: uint8 GetParkMessageType(const std::string& key) { - static constexpr auto keys = { + static auto keys = { "attraction", "peep_on_attraction", "peep", diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index a3d96a5fdc..c53062b412 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -20,7 +20,7 @@ namespace OpenRCT2::Scripting std::string type_get() { - if (tile_element_get_type(_element) == TILE_ELEMENT_TYPE_PATH) + if (_element->GetType() == TILE_ELEMENT_TYPE_PATH) { return "footpath"; } @@ -65,7 +65,7 @@ namespace OpenRCT2::Scripting { _count++; } - while (!tile_element_is_last_for_tile(element++)); + while (!(element++)->IsLastForTile()); } } diff --git a/src/openrct2/thirdparty/dukglue/dukglue.h b/src/openrct2/thirdparty/dukglue/dukglue.h index 1b62f7b9d4..1e305e91cb 100644 --- a/src/openrct2/thirdparty/dukglue/dukglue.h +++ b/src/openrct2/thirdparty/dukglue/dukglue.h @@ -1,7 +1,14 @@ #pragma once +#pragma warning(push) +#pragma warning(disable : 4267) // conversion from a to b, possible loss of data +#pragma warning(disable : 4505) // unreferenced local function has been removed +#pragma warning(disable : 4702) // unreachable code + #include "register_function.h" #include "register_class.h" #include "register_property.h" #include "public_util.h" -#include "dukvalue.h" \ No newline at end of file +#include "dukvalue.h" + +#pragma warning(pop) From 834cfad50233ded3439a2b7f8f6d293318b35196 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 30 Mar 2018 20:57:05 +0100 Subject: [PATCH 021/159] Create new FileWatcher class --- src/openrct2/core/FileWatcher.cpp | 102 ++++++++++++++++++++++++++++++ src/openrct2/core/FileWatcher.h | 33 ++++++++++ 2 files changed, 135 insertions(+) create mode 100644 src/openrct2/core/FileWatcher.cpp create mode 100644 src/openrct2/core/FileWatcher.h diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp new file mode 100644 index 0000000000..7429ea8c97 --- /dev/null +++ b/src/openrct2/core/FileWatcher.cpp @@ -0,0 +1,102 @@ +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#else +#include +#include +#include +#include +#endif + +#include "../core/String.hpp" +#include "FileWatcher.h" + +FileWatcher::FileWatcher(const std::string &directoryPath) +{ +#ifdef _WIN32 + _directoryHandle = CreateFileA(directoryPath.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (_directoryHandle == INVALID_HANDLE_VALUE) + { + throw std::runtime_error("Unable to open directory '" + directoryPath + "'"); + } +#else + auto fd = inotify_init(); + if (fd >= 0) + { + auto wd = inotify_add_watch(fd, directoryPath.c_str(), IN_CLOSE_WRITE); + if (wd >= 0) + { + _fileDesc = fd; + _watchDesc = wd; + } + else + { + close(fd); + throw std::runtime_error("Unable to watch directory '" + directoryPath + "'"); + } + } +#endif + _watchThread = std::thread(std::bind(&FileWatcher::WatchDirectory, this)); +} + +FileWatcher::~FileWatcher() +{ +#ifdef _WIN32 + CancelIoEx(_directoryHandle, nullptr); + CloseHandle(_directoryHandle); +#else + inotify_rm_watch(_fileDesc, _watchDesc); + close(_fileDesc); +#endif + _watchThread.join(); +} + +void FileWatcher::WatchDirectory() +{ +#ifdef _WIN32 + std::array eventData; + DWORD bytesReturned; + while (ReadDirectoryChangesW(_directoryHandle, eventData.data(), (DWORD)eventData.size(), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE, &bytesReturned, nullptr, nullptr)) + { + auto onFileChanged = OnFileChanged; + if (onFileChanged) + { + FILE_NOTIFY_INFORMATION * notifyInfo; + size_t offset = 0; + do + { + notifyInfo = (FILE_NOTIFY_INFORMATION*)(eventData.data() + offset); + offset += notifyInfo->NextEntryOffset; + + std::wstring fileNameW(notifyInfo->FileName, notifyInfo->FileNameLength / sizeof(wchar_t)); + auto fileName = String::ToUtf8(fileNameW); + onFileChanged(fileName); + } + while (notifyInfo->NextEntryOffset != 0); + } + } +#else + std::array eventData; + auto length = read(_fileDesc, eventData.data(), eventData.size()); + if (length >= 0) + { + auto onFileChanged = OnFileChanged; + if (onFileChanged) + { + int offset = 0; + while (offset < length) + { + auto e = (inotify_event*)(eventData.data() + offset); + if ((e->mask & IN_CLOSE_WRITE) && !(e->mask & IN_ISDIR)) + { + onFileChanged(e->name); + } + offset += sizeof(inotify_event) + e->len; + } + } + } +#endif +} diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h new file mode 100644 index 0000000000..9f923e9e15 --- /dev/null +++ b/src/openrct2/core/FileWatcher.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include + +#ifdef _WIN32 +typedef void * HANDLE; +#endif + +/** + * Creates a new thread that watches a directory tree for file modifications. + */ +class FileWatcher +{ +private: + std::thread _watchThread; +#ifdef _WIN32 + HANDLE _directoryHandle{}; +#else + int _fileDesc{}; + int _watchDesc{}; +#endif + +public: + std::function OnFileChanged; + + FileWatcher(const std::string &directoryPath); + ~FileWatcher(); + +private: + void WatchDirectory(); +}; From 1fd33dd86af01a3ed9561f5f7f697ed7e49efa34 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 31 Mar 2018 00:08:59 +0100 Subject: [PATCH 022/159] Use new FileWatcher class --- src/openrct2/core/FileWatcher.cpp | 122 +++++++++++++++++++----- src/openrct2/core/FileWatcher.h | 26 ++++- src/openrct2/scripting/Plugin.h | 2 + src/openrct2/scripting/ScriptEngine.cpp | 43 ++++++--- src/openrct2/scripting/ScriptEngine.h | 8 ++ 5 files changed, 164 insertions(+), 37 deletions(-) diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index 7429ea8c97..a9b7d853a7 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -1,5 +1,6 @@ #include #include +#include #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN @@ -14,6 +15,65 @@ #include "../core/String.hpp" #include "FileWatcher.h" +namespace fs = std::experimental::filesystem; + +#ifndef _WIN32 +FileWatcher::FileDescriptor::~FileDescriptor() +{ + Close(); +} + +void FileWatcher::FileDescriptor::Initialise() +{ + int fd = inotify_init(); + if (fd >= 0) + { + // Mark file as non-blocking + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + + Fd = fd; + log_verbose("FileWatcher: inotify_init succeeded"); + } + else + { + log_verbose("FileWatcher: inotify_init failed"); + throw std::runtime_error("inotify_init failed"); + } +} + +void FileWatcher::FileDescriptor::Close() +{ + if (Fd != -1) + { + close(Fd); + Fd = -1; + } +} + +FileWatcher::WatchDescriptor::WatchDescriptor(int fd, const std::string& path) + : Fd(fd), + Wd(inotify_add_watch(fd, path.c_str(), IN_CLOSE_WRITE)), + Path(path) +{ + if (Wd >= 0) + { + log_verbose("FileWatcher: inotify watch added for %s", path.c_str()); + } + else + { + log_verbose("FileWatcher: inotify_add_watch failed for %s", path.c_str()); + throw std::runtime_error("inotify_add_watch failed for '" + path + "'"); + } +} + +FileWatcher::WatchDescriptor::~WatchDescriptor() +{ + inotify_rm_watch(Fd, Wd); + log_verbose("FileWatcher: inotify watch removed"); +} +#endif + FileWatcher::FileWatcher(const std::string &directoryPath) { #ifdef _WIN32 @@ -23,19 +83,13 @@ FileWatcher::FileWatcher(const std::string &directoryPath) throw std::runtime_error("Unable to open directory '" + directoryPath + "'"); } #else - auto fd = inotify_init(); - if (fd >= 0) + _fileDesc.Initialise(); + _watchDescs.emplace_back(_fileDesc.Fd, directoryPath); + for (auto& p : fs::recursive_directory_iterator(directoryPath)) { - auto wd = inotify_add_watch(fd, directoryPath.c_str(), IN_CLOSE_WRITE); - if (wd >= 0) + if (p.status().type() == fs::file_type::directory) { - _fileDesc = fd; - _watchDesc = wd; - } - else - { - close(fd); - throw std::runtime_error("Unable to watch directory '" + directoryPath + "'"); + _watchDescs.emplace_back(_fileDesc.Fd, p.path().string()); } } #endif @@ -48,8 +102,8 @@ FileWatcher::~FileWatcher() CancelIoEx(_directoryHandle, nullptr); CloseHandle(_directoryHandle); #else - inotify_rm_watch(_fileDesc, _watchDesc); - close(_fileDesc); + _finished = true; + _fileDesc.Close(); #endif _watchThread.join(); } @@ -79,24 +133,46 @@ void FileWatcher::WatchDirectory() } } #else + log_verbose("FileWatcher: reading event data..."); std::array eventData; - auto length = read(_fileDesc, eventData.data(), eventData.size()); - if (length >= 0) + while (!_finished) { - auto onFileChanged = OnFileChanged; - if (onFileChanged) + int length = read(_fileDesc.Fd, eventData.data(), eventData.size()); + if (length >= 0) { - int offset = 0; - while (offset < length) + log_verbose("FileWatcher: inotify event data received"); + auto onFileChanged = OnFileChanged; + if (onFileChanged) { - auto e = (inotify_event*)(eventData.data() + offset); - if ((e->mask & IN_CLOSE_WRITE) && !(e->mask & IN_ISDIR)) + int offset = 0; + while (offset < length) { - onFileChanged(e->name); + auto e = (inotify_event*)(eventData.data() + offset); + if ((e->mask & IN_CLOSE_WRITE) && !(e->mask & IN_ISDIR)) + { + log_verbose("FileWatcher: inotify event received for %s", e->name); + + // Find watch descriptor + int wd = e->wd; + auto findResult = std::find_if(_watchDescs.begin(), _watchDescs.end(), + [wd](const WatchDescriptor& watchDesc) + { + return wd == watchDesc.Wd; + }); + if (findResult != _watchDescs.end()) + { + auto directory = findResult->Path; + auto path = fs::path(directory) / fs::path(e->name); + onFileChanged(path); + } + } + offset += sizeof(inotify_event) + e->len; } - offset += sizeof(inotify_event) + e->len; } } + + // Sleep for 1/2 second + usleep(500000); } #endif } diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h index 9f923e9e15..0c1dc23750 100644 --- a/src/openrct2/core/FileWatcher.h +++ b/src/openrct2/core/FileWatcher.h @@ -3,6 +3,7 @@ #include #include #include +#include #ifdef _WIN32 typedef void * HANDLE; @@ -18,8 +19,27 @@ private: #ifdef _WIN32 HANDLE _directoryHandle{}; #else - int _fileDesc{}; - int _watchDesc{}; + struct FileDescriptor + { + int Fd = -1; + + ~FileDescriptor(); + void Initialise(); + void Close(); + }; + + struct WatchDescriptor + { + int const Fd; + int const Wd; + std::string const Path; + + WatchDescriptor(int fd, const std::string& path); + ~WatchDescriptor(); + }; + + FileDescriptor _fileDesc; + std::vector _watchDescs; #endif public: @@ -29,5 +49,7 @@ public: ~FileWatcher(); private: + bool _finished{}; + void WatchDirectory(); }; diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index d14d125c3a..21daf557cb 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -47,6 +47,8 @@ namespace OpenRCT2::Scripting bool _hotReloadEnabled{}; public: + std::string GetPath() const { return _path; }; + Plugin() { } Plugin(duk_context * context, const std::string &path); Plugin(const Plugin&) = delete; diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 82ba255bf3..a0f4e7cbdc 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -86,7 +86,6 @@ void ScriptEngine::LoadPlugins() auto plugin = std::make_shared(_context, path); ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); - plugin->EnableHotReload(); _plugins.push_back(std::move(plugin)); } catch (const std::exception &e) @@ -94,27 +93,47 @@ void ScriptEngine::LoadPlugins() _console.WriteLineError(e.what()); } } + + // Enable hot reloading + _pluginFileWatcher = std::make_unique(base); + _pluginFileWatcher->OnFileChanged = + [this](const std::string &path) + { + std::lock_guard guard(_changedPluginFilesMutex); + _changedPluginFiles.push_back(path); + }; } void ScriptEngine::AutoReloadPlugins() { - for (auto& plugin : _plugins) + if (_changedPluginFiles.size() > 0) { - if (plugin->ShouldHotReload()) + std::lock_guard guard(_changedPluginFilesMutex); + for (auto& path : _changedPluginFiles) { - try + auto findResult = std::find_if(_plugins.begin(), _plugins.end(), + [&path](const std::shared_ptr& plugin) + { + return path == plugin->GetPath(); + }); + if (findResult != _plugins.end()) { - _hookEngine.UnsubscribeAll(plugin); + auto& plugin = *findResult; + try + { + _hookEngine.UnsubscribeAll(plugin); - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); - plugin->Load(); - plugin->Start(); - } - catch (const std::exception &e) - { - _console.WriteLineError(e.what()); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + plugin->Load(); + plugin->Start(); + } + catch (const std::exception &e) + { + _console.WriteLineError(e.what()); + } } } + _changedPluginFiles.clear(); } } diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 5a11d519e5..5b808ba356 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -10,16 +10,20 @@ #pragma once #include "../common.h" +#include "../core/FileWatcher.h" #include "HookEngine.h" #include "Plugin.h" #include #include +#include #include #include +#include struct duk_hthread; typedef struct duk_hthread duk_context; +class FileWatcher; class InteractiveConsole; namespace OpenRCT2 @@ -88,6 +92,10 @@ namespace OpenRCT2::Scripting HookEngine _hookEngine; ScriptExecutionInfo _execInfo; + std::unique_ptr _pluginFileWatcher; + std::vector _changedPluginFiles; + std::mutex _changedPluginFilesMutex; + public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); ScriptEngine(ScriptEngine&) = delete; From 26eb91016eb68158246355cdd34215b12ddf5675 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 31 Mar 2018 00:10:30 +0100 Subject: [PATCH 023/159] Remove old hot reload code --- src/openrct2/scripting/Plugin.cpp | 70 ------------------------------- src/openrct2/scripting/Plugin.h | 13 ------ 2 files changed, 83 deletions(-) diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 6b55cda62e..561405e33c 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -38,11 +38,6 @@ Plugin::Plugin(duk_context * context, const std::string &path) { } -Plugin::~Plugin() -{ - DisableHotReload(); -} - void Plugin::Load() { std::string projectedVariables = "console,context,map,park,ui"; @@ -97,71 +92,6 @@ void Plugin::Update() { } -void Plugin::EnableHotReload() -{ -#ifdef _WIN32 -#else - auto fd = inotify_init(); - if (fd >= 0) - { - // Mark file as non-blocking - int flags = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - - auto wd = inotify_add_watch(fd, _path.c_str(), IN_CLOSE_WRITE); - if (wd >= 0) - { - _hotReloadData.FileDesc = fd; - _hotReloadData.WatchDesc = wd; - _hotReloadEnabled = true; - } - else - { - close(fd); - } - } -#endif -} - -bool Plugin::ShouldHotReload() -{ - if (_hotReloadEnabled) - { -#ifdef _WIN32 -#else - std::vector eventData; - eventData.resize(1024); - - auto length = read(_hotReloadData.FileDesc, eventData.data(), eventData.size()); - int offset = 0; - while (offset < length) - { - auto e = (inotify_event*)&eventData[offset]; - if ((e->mask & IN_CLOSE_WRITE) && !(e->mask & IN_ISDIR)) - { - return true; - } - offset += sizeof(inotify_event) + e->len; - } -#endif - } - return false; -} - -void Plugin::DisableHotReload() -{ - if (_hotReloadEnabled) - { -#ifdef _WIN32 -#else - inotify_rm_watch(_hotReloadData.FileDesc, _hotReloadData.WatchDesc); - close(_hotReloadData.FileDesc); -#endif - _hotReloadData = HotReloadData(); - _hotReloadEnabled = false; - } -} - PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) { PluginMetadata metadata; diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 21daf557cb..0c16f0c22b 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -34,17 +34,9 @@ namespace OpenRCT2::Scripting class Plugin { private: - struct HotReloadData - { - int FileDesc{}; - int WatchDesc{}; - }; - duk_context * _context; std::string _path; PluginMetadata _metadata; - HotReloadData _hotReloadData; - bool _hotReloadEnabled{}; public: std::string GetPath() const { return _path; }; @@ -53,16 +45,11 @@ namespace OpenRCT2::Scripting Plugin(duk_context * context, const std::string &path); Plugin(const Plugin&) = delete; Plugin(Plugin&&) = delete; - ~Plugin(); void Load(); void Start(); void Update(); - void EnableHotReload(); - bool ShouldHotReload(); - void DisableHotReload(); - private: static PluginMetadata GetMetadata(const DukValue& dukMetadata); }; From 5ba96a34ac768f2bc3073691df057b68f4ccd430 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 31 Mar 2018 10:27:45 +0100 Subject: [PATCH 024/159] Fix FileWatcher for Windows --- src/openrct2/core/FileWatcher.cpp | 4 +++- src/openrct2/core/FileWatcher.h | 1 + src/openrct2/scripting/ScriptEngine.cpp | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index a9b7d853a7..d48b47ef0b 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -77,6 +77,7 @@ FileWatcher::WatchDescriptor::~WatchDescriptor() FileWatcher::FileWatcher(const std::string &directoryPath) { #ifdef _WIN32 + _path = directoryPath; _directoryHandle = CreateFileA(directoryPath.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (_directoryHandle == INVALID_HANDLE_VALUE) { @@ -127,7 +128,8 @@ void FileWatcher::WatchDirectory() std::wstring fileNameW(notifyInfo->FileName, notifyInfo->FileNameLength / sizeof(wchar_t)); auto fileName = String::ToUtf8(fileNameW); - onFileChanged(fileName); + auto path = fs::path(_path) / fs::path(fileName); + onFileChanged(path.u8string()); } while (notifyInfo->NextEntryOffset != 0); } diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h index 0c1dc23750..da3fb0b9c0 100644 --- a/src/openrct2/core/FileWatcher.h +++ b/src/openrct2/core/FileWatcher.h @@ -17,6 +17,7 @@ class FileWatcher private: std::thread _watchThread; #ifdef _WIN32 + std::string _path; HANDLE _directoryHandle{}; #else struct FileDescriptor diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index a0f4e7cbdc..50f0dfe720 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -114,7 +114,7 @@ void ScriptEngine::AutoReloadPlugins() auto findResult = std::find_if(_plugins.begin(), _plugins.end(), [&path](const std::shared_ptr& plugin) { - return path == plugin->GetPath(); + return Path::Equals(path, plugin->GetPath()); }); if (findResult != _plugins.end()) { From 24eafb0a864b23eba5978c71e9b96b2a967622ef Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 23 May 2018 17:56:42 +0100 Subject: [PATCH 025/159] Do not crash if plugins directory is missing --- src/openrct2/scripting/ScriptEngine.cpp | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 50f0dfe720..7d4d4999cc 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -94,14 +94,21 @@ void ScriptEngine::LoadPlugins() } } - // Enable hot reloading - _pluginFileWatcher = std::make_unique(base); - _pluginFileWatcher->OnFileChanged = - [this](const std::string &path) - { - std::lock_guard guard(_changedPluginFilesMutex); - _changedPluginFiles.push_back(path); - }; + try + { + // Enable hot reloading + _pluginFileWatcher = std::make_unique(base); + _pluginFileWatcher->OnFileChanged = + [this](const std::string &path) + { + std::lock_guard guard(_changedPluginFilesMutex); + _changedPluginFiles.push_back(path); + }; + } + catch (const std::exception& e) + { + std::printf("Unable to enable hot reloading of plugins: %s\n", e.what()); + } } void ScriptEngine::AutoReloadPlugins() From 5befd39063af3a7b0ab5f57608a5530ceeb87c07 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Thu, 24 May 2018 14:49:11 +0200 Subject: [PATCH 026/159] Construct ScWindow properly --- src/openrct2-ui/scripting/ScWindow.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index a38b01eaba..0251cf36a0 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -15,8 +15,8 @@ namespace OpenRCT2::Scripting public: ScWindow(rct_window * w) + : ScWindow(w->classification, w->number) { - ScWindow(w->classification, w->number); } ScWindow(rct_windowclass c, rct_windownumber n) From 34b5aab6c06c4c0af7d48b3aecb75b8135605d88 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Thu, 24 May 2018 23:01:16 +0200 Subject: [PATCH 027/159] Add new tile element classes for each type This introduces some template code to get around the problem of properties not being available for child-elements. I've tried to make clear what it's for by adding a comment. So far only the Track element has an extra property (rideIndex), but it's fairly easy to add new ones. --- src/openrct2/scripting/ScTile.hpp | 176 ++++++++++++++++++++++++++++-- 1 file changed, 167 insertions(+), 9 deletions(-) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index c53062b412..ede552bae4 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -9,7 +9,7 @@ namespace OpenRCT2::Scripting { class ScTileElement { - private: + protected: rct_tile_element * _element; public: @@ -18,16 +18,33 @@ namespace OpenRCT2::Scripting { } - std::string type_get() + std::string type_get() const { - if (_element->GetType() == TILE_ELEMENT_TYPE_PATH) + switch (_element->GetType()) { - return "footpath"; + case TILE_ELEMENT_TYPE_SURFACE: return "surface"; + case TILE_ELEMENT_TYPE_PATH: return "footpath"; + case TILE_ELEMENT_TYPE_TRACK: return "track"; + case TILE_ELEMENT_TYPE_SMALL_SCENERY: return "small-scenery"; + case TILE_ELEMENT_TYPE_ENTRANCE: return "entrance"; + case TILE_ELEMENT_TYPE_WALL: return "wall"; + case TILE_ELEMENT_TYPE_LARGE_SCENERY: return "large-scenery"; + case TILE_ELEMENT_TYPE_BANNER: return "banner"; + case TILE_ELEMENT_TYPE_CORRUPT: return "openrct2-corrupt"; + default: return "unknown"; } - return "unknown"; } - bool broken_get() { return _element->flags & TILE_ELEMENT_FLAG_BROKEN; } + template + T* getAs() + { + return static_cast(this); + } + + bool broken_get() const + { + return _element->flags & TILE_ELEMENT_FLAG_BROKEN; + } void broken_set(bool value) { if (value) @@ -40,13 +57,154 @@ namespace OpenRCT2::Scripting } } - static void Register(duk_context * ctx) + auto baseHeight_get() const { - dukglue_register_property(ctx, &ScTileElement::type_get, nullptr, "type"); - dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + return _element->base_height; + } + void baseHeight_set(uint8 newBaseHeight) + { + _element->base_height = newBaseHeight; + } + + auto clearanceHeight_get() const + { + return _element->clearance_height; + } + void clearanceHeight_set(uint8 newClearanceHeight) + { + _element->clearance_height = newClearanceHeight; + } + + static void Register(duk_context* ctx); + template + static void RegisterSharedProperties(duk_context* ctx); + }; + + class ScSurfaceElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); } }; + class ScFootpathElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + } + }; + + class ScTrackElement final : public ScTileElement + { + auto track_ride_index_get() const + { + return _element->properties.track.ride_index; + } + + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + dukglue_register_property(ctx, &ScTrackElement::track_ride_index_get, nullptr, "rideIndex"); + } + }; + + class ScSmallSceneryElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + } + }; + + class ScEntranceElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + } + }; + + class ScWallElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + } + }; + + class ScLargeSceneryElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + } + }; + + class ScBannerElement final : public ScTileElement + { + public: + static void Register(duk_context* ctx) + { + RegisterSharedProperties(ctx); + } + }; + + void ScTileElement::Register(duk_context* ctx) + { + dukglue_register_method(ctx, &ScTileElement::getAs, "asSurface"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asTrack"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asSmallScenery"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asEntrance"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asWall"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asLargeScenery"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asBanner"); + + // Shared properties + RegisterSharedProperties(ctx); + + // Register type specific properties + ScSurfaceElement ::Register(ctx); + ScTrackElement ::Register(ctx); + ScSmallSceneryElement ::Register(ctx); + ScEntranceElement ::Register(ctx); + ScWallElement ::Register(ctx); + ScLargeSceneryElement ::Register(ctx); + ScBannerElement ::Register(ctx); + } + + template + void ScTileElement::RegisterSharedProperties(duk_context* ctx) + { + // When you register a member function of a parent class, it belongs to the parent and cannot be accessed by its + // children. To get around this issue, we need to force the function pointer types to be of the class we want them to be + // available for. This needs to be done for every child. + dukglue_register_property(ctx, static_cast(&ScTileElement::type_get), nullptr, "type"); + dukglue_register_property( + ctx, + static_cast(&ScTileElement::broken_get), + static_cast(&ScTileElement::broken_set), + "broken"); + dukglue_register_property( + ctx, + static_cast(&ScTileElement::baseHeight_get), + static_cast(&ScTileElement::baseHeight_set), + "baseHeight"); + dukglue_register_property( + ctx, + static_cast(&ScTileElement::clearanceHeight_get), + static_cast(&ScTileElement::clearanceHeight_set), + "clearanceHeight"); + } + class ScTile { private: From d6b40647947a04e20e2bca9577b2c8af1d95e055 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Fri, 25 May 2018 14:42:05 +0200 Subject: [PATCH 028/159] Use variant argument type for console.log --- src/openrct2/scripting/ScConsole.hpp | 43 ++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index b3c908b697..cfdf6e4603 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -2,6 +2,9 @@ #include #include "../interface/InteractiveConsole.h" +#include "../core/Math.hpp" + +#include namespace OpenRCT2::Scripting { @@ -9,9 +12,10 @@ namespace OpenRCT2::Scripting { private: InteractiveConsole& _console; + public: - ScConsole(InteractiveConsole& console) : - _console(console) + ScConsole(InteractiveConsole& console) + : _console(console) { } @@ -20,15 +24,42 @@ namespace OpenRCT2::Scripting _console.Clear(); } - void log(const std::string &s) + void log(DukValue val) { - _console.WriteLine(s); + std::string str; + switch (val.type()) + { + case DukValue::Type::UNDEFINED: str = "undefined"; break; + case DukValue::Type::NULLREF: str = "null"; break; + case DukValue::Type::BOOLEAN: str = val.as_bool() ? "true" : "false"; break; + case DukValue::Type::NUMBER: + { + const auto d = val.as_double(); + const duk_int_t i = val.as_int(); + if (Math::AlmostEqual(d, i)) + { + str = std::to_string(i); + } + else + { + str = std::to_string(d); + } + break; + } + case DukValue::Type::STRING: str = val.as_string(); break; + case DukValue::Type::OBJECT: str = "{}"; break; + case DukValue::Type::BUFFER: str = "buffer"; break; + case DukValue::Type::POINTER: str = "pointer"; break; + case DukValue::Type::LIGHTFUNC: break; + } + + _console.WriteLine(str); } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_method(ctx, &ScConsole::clear, "clear"); dukglue_register_method(ctx, &ScConsole::log, "log"); } }; -} +} // namespace OpenRCT2::Scripting From c0646142803ec46e8ab1078a6d345d791512707f Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Sun, 17 Jun 2018 15:48:42 +0200 Subject: [PATCH 029/159] Use new copyright/license notice --- src/openrct2-ui/scripting/ScUi.hpp | 9 +++++++++ src/openrct2-ui/scripting/ScWindow.hpp | 9 +++++++++ src/openrct2-ui/scripting/UiExtensions.cpp | 9 +++++++++ src/openrct2-ui/scripting/UiExtensions.h | 9 +++++++++ src/openrct2/core/FileWatcher.cpp | 9 +++++++++ src/openrct2/core/FileWatcher.h | 9 +++++++++ src/openrct2/scripting/Plugin.cpp | 15 ++++----------- src/openrct2/scripting/Plugin.h | 15 ++++----------- src/openrct2/scripting/ScConsole.hpp | 9 +++++++++ src/openrct2/scripting/ScContext.hpp | 9 +++++++++ src/openrct2/scripting/ScDisposable.hpp | 9 +++++++++ src/openrct2/scripting/ScMap.hpp | 9 +++++++++ src/openrct2/scripting/ScPark.hpp | 9 +++++++++ src/openrct2/scripting/ScThing.hpp | 9 +++++++++ src/openrct2/scripting/ScTile.hpp | 9 +++++++++ 15 files changed, 125 insertions(+), 22 deletions(-) diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 28e9852c2a..ae2a4cc950 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 0251cf36a0..690245f36d 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index e7ea265d9a..667d0eb9fe 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + #include #include "UiExtensions.h" #include "ScUi.hpp" diff --git a/src/openrct2-ui/scripting/UiExtensions.h b/src/openrct2-ui/scripting/UiExtensions.h index 08b05edd41..fc361da666 100644 --- a/src/openrct2-ui/scripting/UiExtensions.h +++ b/src/openrct2-ui/scripting/UiExtensions.h @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 namespace OpenRCT2::Scripting diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index d48b47ef0b..9b989cedd0 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + #include #include #include diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h index da3fb0b9c0..4d977be4be 100644 --- a/src/openrct2/core/FileWatcher.h +++ b/src/openrct2/core/FileWatcher.h @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 561405e33c..4367e02514 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -1,18 +1,11 @@ -#pragma region Copyright (c) 2014-2018 OpenRCT2 Developers /***************************************************************************** - * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. + * Copyright (c) 2014-2018 OpenRCT2 developers * - * OpenRCT2 is the work of many authors, a full list can be found in contributors.md - * For more information, visit https://github.com/OpenRCT2/OpenRCT2 + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 * - * OpenRCT2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * A full copy of the GNU General Public License can be found in licence.txt + * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#pragma endregion #include "Plugin.h" #include diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 0c16f0c22b..99171e4540 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -1,18 +1,11 @@ -#pragma region Copyright (c) 2014-2018 OpenRCT2 Developers /***************************************************************************** - * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. + * Copyright (c) 2014-2018 OpenRCT2 developers * - * OpenRCT2 is the work of many authors, a full list can be found in contributors.md - * For more information, visit https://github.com/OpenRCT2/OpenRCT2 + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 * - * OpenRCT2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * A full copy of the GNU General Public License can be found in licence.txt + * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#pragma endregion #pragma once diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index cfdf6e4603..ceee2643da 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index f858cd7232..1cd1fdd638 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index eb3b58782a..a285d05018 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 86a355535d..d10adb6cf0 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 656904179a..7aecbb483e 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 980ce1d2b2..c3f0ae5d2a 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index ede552bae4..0e1de94238 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -1,3 +1,12 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 #include From c37d7d859e1959e10aa432c49654fe95a6367129 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Tue, 31 Jul 2018 16:25:50 +0200 Subject: [PATCH 030/159] Use C++ types --- src/openrct2-ui/interface/InGameConsole.h | 2 ++ src/openrct2-ui/scripting/CustomWindow.cpp | 42 +++++++++++----------- src/openrct2-ui/scripting/ScUi.hpp | 12 +++---- src/openrct2-ui/scripting/ScWindow.hpp | 12 +++---- src/openrct2/interface/Window.h | 2 +- src/openrct2/scripting/HookEngine.cpp | 4 +-- src/openrct2/scripting/HookEngine.h | 8 ++--- src/openrct2/scripting/ScMap.hpp | 8 ++--- src/openrct2/scripting/ScPark.hpp | 12 +++---- src/openrct2/scripting/ScThing.hpp | 14 ++++---- src/openrct2/scripting/ScTile.hpp | 12 +++---- src/openrct2/scripting/ScriptEngine.h | 2 +- 12 files changed, 66 insertions(+), 64 deletions(-) diff --git a/src/openrct2-ui/interface/InGameConsole.h b/src/openrct2-ui/interface/InGameConsole.h index 601b4b9743..42af4c3ea6 100644 --- a/src/openrct2-ui/interface/InGameConsole.h +++ b/src/openrct2-ui/interface/InGameConsole.h @@ -9,8 +9,10 @@ #pragma once +#include #include #include +#include namespace OpenRCT2::Ui { diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 1bfd2de279..72b0172f56 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -46,7 +46,7 @@ namespace OpenRCT2::Ui::Windows static void window_custom_mouseup(rct_window * w, rct_widgetindex widgetIndex); static void window_custom_mousedown(rct_window * w, rct_widgetindex widgetIndex, rct_widget * widget); static void window_custom_resize(rct_window * w); - static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, sint32 dropdownIndex); + static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, int32_t dropdownIndex); static void window_custom_invalidate(rct_window * w); static void window_custom_paint(rct_window * w, rct_drawpixelinfo * dpi); @@ -86,13 +86,13 @@ namespace OpenRCT2::Ui::Windows { // Properties std::string Type; - sint32 X{}; - sint32 Y{}; - sint32 Width{}; - sint32 Height{}; + int32_t X{}; + int32_t Y{}; + int32_t Width{}; + int32_t Height{}; std::string Text; std::vector Items; - sint32 SelectedIndex{}; + int32_t SelectedIndex{}; // Event handlers DukValue OnClick; @@ -128,16 +128,16 @@ namespace OpenRCT2::Ui::Windows struct CustomWindowDesc { std::string Classification; - std::optional X; - std::optional Y; - sint32 Width; - sint32 Height; - std::optional MinWidth; - std::optional MinHeight; - std::optional MaxWidth; - std::optional MaxHeight; + std::optional X; + std::optional Y; + int32_t Width; + int32_t Height; + std::optional MinWidth; + std::optional MinHeight; + std::optional MaxWidth; + std::optional MaxHeight; std::string Title; - std::optional Id; + std::optional Id; std::vector Widgets; CustomWindowDesc() = default; @@ -172,7 +172,7 @@ namespace OpenRCT2::Ui::Windows return std::move(result); } - static std::optional GetOptionalInt(DukValue input) + static std::optional GetOptionalInt(DukValue input) { return input.type() == DukValue::Type::NUMBER ? std::make_optional(input.as_int()) : @@ -232,7 +232,7 @@ namespace OpenRCT2::Ui::Windows { auto desc = CustomWindowDesc::FromDukValue(dukDesc); - uint16 windowFlags = 0; + uint16_t windowFlags = 0; if (desc.IsResizable()) { windowFlags |= WF_RESIZABLE; @@ -270,8 +270,8 @@ namespace OpenRCT2::Ui::Windows { window->min_width = desc.MinWidth.value_or(0); window->min_height = desc.MinHeight.value_or(0); - window->max_width = desc.MaxWidth.value_or(std::numeric_limits::max()); - window->max_height = desc.MaxHeight.value_or(std::numeric_limits::max()); + window->max_width = desc.MaxWidth.value_or(std::numeric_limits::max()); + window->max_height = desc.MaxHeight.value_or(std::numeric_limits::max()); } RefreshWidgets(window); window_init_scroll_widgets(window); @@ -338,7 +338,7 @@ namespace OpenRCT2::Ui::Windows for (size_t i = 0; i < numItems; i++) { gDropdownItemsFormat[i] = STR_STRING; - set_format_arg_on((uint8*)&gDropdownItemsArgs[i], 0, const char *, items[i].c_str()); + set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char *, items[i].c_str()); } window_dropdown_show_text_custom_width( w->x + widget->left, @@ -353,7 +353,7 @@ namespace OpenRCT2::Ui::Windows } } - static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, sint32 dropdownIndex) + static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, int32_t dropdownIndex) { if (dropdownIndex == -1) return; diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index ae2a4cc950..9b46766ed7 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -39,11 +39,11 @@ namespace OpenRCT2::Scripting { } - sint32 width_get() { return context_get_width(); } - sint32 height_get() { return context_get_height(); } - sint32 windows_get() + int32_t width_get() { return context_get_width(); } + int32_t height_get() { return context_get_height(); } + int32_t windows_get() { - return static_cast(g_window_list.size()); + return static_cast(g_window_list.size()); } std::shared_ptr openWindow(DukValue desc) @@ -83,9 +83,9 @@ namespace OpenRCT2::Scripting window_close_all(); } - std::shared_ptr getWindow(sint32 index) + std::shared_ptr getWindow(int32_t index) { - for (sint32 i = 0; i < g_window_list.size(); i++) + for (int32_t i = 0; i < g_window_list.size(); i++) { if (i == index) { diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 690245f36d..ee834e516a 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -34,20 +34,20 @@ namespace OpenRCT2::Scripting { } - sint32 x_get() { return GetWindow()->x; } - void x_set(sint32 value) + int32_t x_get() { return GetWindow()->x; } + void x_set(int32_t value) { auto w = GetWindow(); window_set_position(w, value, w->y); } - sint32 y_get() { return GetWindow()->y; } - void y_set(sint32 value) + int32_t y_get() { return GetWindow()->y; } + void y_set(int32_t value) { auto w = GetWindow(); window_set_position(w, w->x, value); } - sint32 width_get() { return GetWindow()->width; } - sint32 height_get() { return GetWindow()->height; } + int32_t width_get() { return GetWindow()->width; } + int32_t height_get() { return GetWindow()->height; } bool isSticky_get() { auto flags = GetWindow()->flags; diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index 5f6e6c36b6..ee60345b1e 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -64,7 +64,7 @@ struct widget_identifier extern widget_identifier gCurrentTextBox; -using WidgetFlags = uint32; +using WidgetFlags = uint32_t; namespace WIDGET_FLAGS { const WidgetFlags TEXT_IS_STRING = 1 << 0; diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 8dee351c77..b6a1823e4f 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -35,7 +35,7 @@ HookEngine::HookEngine(ScriptExecutionInfo& execInfo) : } } -uint32 HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function) +uint32_t HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function) { auto& hookList = GetHookList(type); auto cookie = _nextCookie++; @@ -44,7 +44,7 @@ uint32 HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr owner, cons return cookie; } -void HookEngine::Unsubscribe(HOOK_TYPE type, uint32 cookie) +void HookEngine::Unsubscribe(HOOK_TYPE type, uint32_t cookie) { auto& hookList = GetHookList(type); auto& hooks = hookList.Hooks; diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 8fc3099f9f..24cdd36d89 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -32,12 +32,12 @@ namespace OpenRCT2::Scripting struct Hook { - uint32 Cookie; + uint32_t Cookie; std::shared_ptr Owner; DukValue Function; Hook(); - Hook(uint32 cookie, std::shared_ptr owner, const DukValue &function) + Hook(uint32_t cookie, std::shared_ptr owner, const DukValue &function) : Cookie(cookie), Owner(owner), Function(function) @@ -70,8 +70,8 @@ namespace OpenRCT2::Scripting public: HookEngine(ScriptExecutionInfo& execInfo); HookEngine(const HookEngine&) = delete; - uint32 Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function); - void Unsubscribe(HOOK_TYPE type, uint32 cookie); + uint32_t Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function); + void Unsubscribe(HOOK_TYPE type, uint32_t cookie); void UnsubscribeAll(std::shared_ptr owner); void Call(HOOK_TYPE type); diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index d10adb6cf0..989eb61105 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -40,23 +40,23 @@ namespace OpenRCT2::Scripting return DukValue::take_from_stack(ctx); } - sint32 rides_get() + int32_t rides_get() { return MAX_RIDES; } - sint32 things_get() + int32_t things_get() { return MAX_SPRITES; } - std::shared_ptr getTile(sint32 x, sint32 y) + std::shared_ptr getTile(int32_t x, int32_t y) { auto firstElement = map_get_first_element_at(x, y); return std::make_shared(firstElement); } - std::shared_ptr getThing(sint32 id) + std::shared_ptr getThing(int32_t id) { if (id >= 0 && id < MAX_SPRITES) { diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 7aecbb483e..67ddf6ec82 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -31,8 +31,8 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - sint32 rating_get() { return gParkRating; } - void rating_set(sint32 value) + int32_t rating_get() { return gParkRating; } + void rating_set(int32_t value) { gParkRating = std::min(std::max(0, value), 999); auto intent = Intent(INTENT_ACTION_UPDATE_PARK_RATING); @@ -59,7 +59,7 @@ namespace OpenRCT2::Scripting { try { - uint8 type = NEWS_ITEM_BLANK; + uint8_t type = NEWS_ITEM_BLANK; std::string text; if (message.type() == DukValue::Type::STRING) { @@ -70,7 +70,7 @@ namespace OpenRCT2::Scripting type = GetParkMessageType(message["type"].as_string()); text = message["text"].as_string(); } - news_item_add_to_queue_raw(type, text.c_str(), static_cast(-1)); + news_item_add_to_queue_raw(type, text.c_str(), static_cast(-1)); } catch (const std::exception&) { @@ -87,7 +87,7 @@ namespace OpenRCT2::Scripting } private: - uint8 GetParkMessageType(const std::string& key) + uint8_t GetParkMessageType(const std::string& key) { static auto keys = { "attraction", @@ -99,7 +99,7 @@ namespace OpenRCT2::Scripting "guests", "award", "chart" }; - uint8 i = 0; + uint8_t i = 0; for (const auto& k : keys) { if (k == key) diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index c3f0ae5d2a..0de40ee18f 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -35,14 +35,14 @@ namespace OpenRCT2::Scripting return "unknown"; } - sint32 x_get() { return _sprite->unknown.x; } - sint32 y_get() { return _sprite->unknown.y; } - sint32 z_get() { return _sprite->unknown.z; } + int32_t x_get() { return _sprite->unknown.x; } + int32_t y_get() { return _sprite->unknown.y; } + int32_t z_get() { return _sprite->unknown.z; } - uint8 tshirtColour_get() { return _sprite->peep.tshirt_colour; } - void tshirtColour_set(uint8 value) { _sprite->peep.tshirt_colour = value; } - uint8 trousersColour_get() { return _sprite->peep.trousers_colour; } - void trousersColour_set(uint8 value) { _sprite->peep.trousers_colour = value; } + uint8_t tshirtColour_get() { return _sprite->peep.tshirt_colour; } + void tshirtColour_set(uint8_t value) { _sprite->peep.tshirt_colour = value; } + uint8_t trousersColour_get() { return _sprite->peep.trousers_colour; } + void trousersColour_set(uint8_t value) { _sprite->peep.trousers_colour = value; } static void Register(duk_context * ctx) { diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 0e1de94238..39ba7d5a3c 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -70,7 +70,7 @@ namespace OpenRCT2::Scripting { return _element->base_height; } - void baseHeight_set(uint8 newBaseHeight) + void baseHeight_set(uint8_t newBaseHeight) { _element->base_height = newBaseHeight; } @@ -79,7 +79,7 @@ namespace OpenRCT2::Scripting { return _element->clearance_height; } - void clearanceHeight_set(uint8 newClearanceHeight) + void clearanceHeight_set(uint8_t newClearanceHeight) { _element->clearance_height = newClearanceHeight; } @@ -204,13 +204,13 @@ namespace OpenRCT2::Scripting "broken"); dukglue_register_property( ctx, - static_cast(&ScTileElement::baseHeight_get), - static_cast(&ScTileElement::baseHeight_set), + static_cast(&ScTileElement::baseHeight_get), + static_cast(&ScTileElement::baseHeight_set), "baseHeight"); dukglue_register_property( ctx, - static_cast(&ScTileElement::clearanceHeight_get), - static_cast(&ScTileElement::clearanceHeight_set), + static_cast(&ScTileElement::clearanceHeight_get), + static_cast(&ScTileElement::clearanceHeight_set), "clearanceHeight"); } diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 5b808ba356..04318f87e9 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -88,7 +88,7 @@ namespace OpenRCT2::Scripting bool _initialised{}; std::queue, std::string>> _evalQueue; std::vector> _plugins; - uint32 _lastHotReloadCheckTick{}; + uint32_t _lastHotReloadCheckTick{}; HookEngine _hookEngine; ScriptExecutionInfo _execInfo; From e8bdb95f13a9b874529ba34875082b61d5ec6823 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Tue, 31 Jul 2018 17:59:48 +0200 Subject: [PATCH 031/159] format new files Since many of the changes were made before the clang-format changes went live, the new source files used a different format still. This PR applies the new style to all the new source files. --- src/openrct2-ui/interface/Widget.cpp | 4 +- src/openrct2-ui/scripting/CustomWindow.cpp | 199 +++++++++------------ src/openrct2-ui/scripting/ScUi.hpp | 26 ++- src/openrct2-ui/scripting/ScWindow.hpp | 35 ++-- src/openrct2-ui/scripting/UiExtensions.cpp | 4 +- src/openrct2-ui/scripting/UiExtensions.h | 2 +- src/openrct2/core/FileWatcher.cpp | 43 ++--- src/openrct2/core/FileWatcher.h | 6 +- src/openrct2/interface/StdInOutConsole.cpp | 3 +- src/openrct2/interface/Window.h | 2 +- src/openrct2/interface/Window_internal.h | 2 +- src/openrct2/scripting/HookEngine.cpp | 16 +- src/openrct2/scripting/HookEngine.h | 25 +-- src/openrct2/scripting/Plugin.cpp | 33 ++-- src/openrct2/scripting/Plugin.h | 17 +- src/openrct2/scripting/ScConsole.hpp | 34 ++-- src/openrct2/scripting/ScContext.hpp | 19 +- src/openrct2/scripting/ScDisposable.hpp | 8 +- src/openrct2/scripting/ScMap.hpp | 13 +- src/openrct2/scripting/ScPark.hpp | 43 +++-- src/openrct2/scripting/ScThing.hpp | 46 +++-- src/openrct2/scripting/ScTile.hpp | 83 +++++---- src/openrct2/scripting/ScriptEngine.cpp | 53 +++--- src/openrct2/scripting/ScriptEngine.h | 36 ++-- 24 files changed, 409 insertions(+), 343 deletions(-) diff --git a/src/openrct2-ui/interface/Widget.cpp b/src/openrct2-ui/interface/Widget.cpp index b5cc9cfd16..7f4072b40f 100644 --- a/src/openrct2-ui/interface/Widget.cpp +++ b/src/openrct2-ui/interface/Widget.cpp @@ -362,7 +362,7 @@ static void widget_text_centred(rct_drawpixelinfo* dpi, rct_window* w, rct_widge t = w->windowPos.y + widget->top; auto stringId = widget->text; - void * formatArgs = gCommonFormatArgs; + void* formatArgs = gCommonFormatArgs; if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) { stringId = STR_STRING; @@ -407,7 +407,7 @@ static void widget_text(rct_drawpixelinfo* dpi, rct_window* w, rct_widgetindex w t = w->windowPos.y + widget->top; auto stringId = widget->text; - void * formatArgs = gCommonFormatArgs; + void* formatArgs = gCommonFormatArgs; if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) { stringId = STR_STRING; diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 72b0172f56..72d0ad25f3 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -7,19 +7,20 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ +#include "../interface/Dropdown.h" +#include "ScUi.hpp" +#include "ScWindow.hpp" + #include -#include -#include -#include +#include +#include #include #include #include #include -#include -#include -#include "../interface/Dropdown.h" -#include "ScUi.hpp" -#include "ScWindow.hpp" +#include +#include +#include using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -36,51 +37,48 @@ namespace OpenRCT2::Ui::Windows }; static rct_widget CustomDefaultWidgets[] = { - { WWT_FRAME, 0, 0, 0, 0, 0, 0xFFFFFFFF, STR_NONE }, // panel / background - { WWT_CAPTION, 0, 1, 0, 1, 14, STR_STRING, STR_WINDOW_TITLE_TIP }, // title bar - { WWT_CLOSEBOX, 0, 0, 0, 2, 13, STR_CLOSE_X, STR_CLOSE_WINDOW_TIP }, // close x button - { WWT_RESIZE, 1, 0, 0, 14, 0, 0xFFFFFFFF, STR_NONE }, // content panel + { WWT_FRAME, 0, 0, 0, 0, 0, 0xFFFFFFFF, STR_NONE }, // panel / background + { WWT_CAPTION, 0, 1, 0, 1, 14, STR_STRING, STR_WINDOW_TITLE_TIP }, // title bar + { WWT_CLOSEBOX, 0, 0, 0, 2, 13, STR_CLOSE_X, STR_CLOSE_WINDOW_TIP }, // close x button + { WWT_RESIZE, 1, 0, 0, 14, 0, 0xFFFFFFFF, STR_NONE }, // content panel }; - static void window_custom_close(rct_window * w); - static void window_custom_mouseup(rct_window * w, rct_widgetindex widgetIndex); - static void window_custom_mousedown(rct_window * w, rct_widgetindex widgetIndex, rct_widget * widget); - static void window_custom_resize(rct_window * w); - static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, int32_t dropdownIndex); - static void window_custom_invalidate(rct_window * w); - static void window_custom_paint(rct_window * w, rct_drawpixelinfo * dpi); + static void window_custom_close(rct_window* w); + static void window_custom_mouseup(rct_window* w, rct_widgetindex widgetIndex); + static void window_custom_mousedown(rct_window* w, rct_widgetindex widgetIndex, rct_widget* widget); + static void window_custom_resize(rct_window* w); + static void window_custom_dropdown(rct_window* w, rct_widgetindex widgetIndex, int32_t dropdownIndex); + static void window_custom_invalidate(rct_window* w); + static void window_custom_paint(rct_window* w, rct_drawpixelinfo* dpi); - static rct_window_event_list window_custom_events = - { - window_custom_close, - window_custom_mouseup, - window_custom_resize, - window_custom_mousedown, - window_custom_dropdown, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - window_custom_invalidate, - window_custom_paint, - nullptr - }; + static rct_window_event_list window_custom_events = { window_custom_close, + window_custom_mouseup, + window_custom_resize, + window_custom_mousedown, + window_custom_dropdown, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + window_custom_invalidate, + window_custom_paint, + nullptr }; struct CustomWidgetDesc { @@ -165,8 +163,9 @@ namespace OpenRCT2::Ui::Windows if (desc["widgets"].is_array()) { auto dukWidgets = desc["widgets"].as_array(); - std::transform(dukWidgets.begin(), dukWidgets.end(), std::back_inserter(result.Widgets), - [](const DukValue& w) { return CustomWidgetDesc::FromDukValue(w); }); + std::transform(dukWidgets.begin(), dukWidgets.end(), std::back_inserter(result.Widgets), [](const DukValue& w) { + return CustomWidgetDesc::FromDukValue(w); + }); } return std::move(result); @@ -174,9 +173,7 @@ namespace OpenRCT2::Ui::Windows static std::optional GetOptionalInt(DukValue input) { - return input.type() == DukValue::Type::NUMBER ? - std::make_optional(input.as_int()) : - std::nullopt; + return input.type() == DukValue::Type::NUMBER ? std::make_optional(input.as_int()) : std::nullopt; } }; @@ -193,20 +190,17 @@ namespace OpenRCT2::Ui::Windows std::vector WidgetIndexMap; CustomWindowInfo( - rct_windowclass cls, - rct_windownumber number, - std::shared_ptr owner, - const CustomWindowDesc& desc) - : _class(cls), - _number(number), - Owner(owner), - Desc(desc) + rct_windowclass cls, rct_windownumber number, std::shared_ptr owner, const CustomWindowDesc& desc) + : _class(cls) + , _number(number) + , Owner(owner) + , Desc(desc) { } CustomWindowInfo(const CustomWindowInfo&) = delete; - const CustomWidgetDesc * GetCustomWidgetDesc(size_t widgetIndex) const + const CustomWidgetDesc* GetCustomWidgetDesc(size_t widgetIndex) const { if (widgetIndex < WidgetIndexMap.size()) { @@ -222,13 +216,14 @@ namespace OpenRCT2::Ui::Windows static rct_windownumber _nextWindowNumber; - static CustomWindowInfo& GetInfo(rct_window * w); + static CustomWindowInfo& GetInfo(rct_window* w); static rct_windownumber GetNewWindowNumber(); - static void RefreshWidgets(rct_window * w); + static void RefreshWidgets(rct_window* w); static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler); - static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args); + static void InvokeEventHandler( + std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args); - rct_window * window_custom_open(std::shared_ptr owner, DukValue dukDesc) + rct_window* window_custom_open(std::shared_ptr owner, DukValue dukDesc) { auto desc = CustomWindowDesc::FromDukValue(dukDesc); @@ -238,26 +233,15 @@ namespace OpenRCT2::Ui::Windows windowFlags |= WF_RESIZABLE; } - rct_window * window; + rct_window* window; if (desc.X && desc.Y) { window = window_create( - desc.X.value(), - desc.Y.value(), - desc.Width, - desc.Height, - &window_custom_events, - WC_CUSTOM, - windowFlags); + desc.X.value(), desc.Y.value(), desc.Width, desc.Height, &window_custom_events, WC_CUSTOM, windowFlags); } else { - window = window_create_auto_pos( - desc.Width, - desc.Height, - &window_custom_events, - WC_CUSTOM, - windowFlags); + window = window_create_auto_pos(desc.Width, desc.Height, &window_custom_events, WC_CUSTOM, windowFlags); } window->number = GetNewWindowNumber(); @@ -278,19 +262,20 @@ namespace OpenRCT2::Ui::Windows return window; } - static void window_custom_close(rct_window * w) + static void window_custom_close(rct_window* w) { - delete static_cast(w->custom_info); + delete static_cast(w->custom_info); w->custom_info = nullptr; } - static void window_custom_mouseup(rct_window * w, rct_widgetindex widgetIndex) + static void window_custom_mouseup(rct_window* w, rct_widgetindex widgetIndex) { - switch (widgetIndex) { - case WIDX_CLOSE: - window_close(w); - break; - default: + switch (widgetIndex) + { + case WIDX_CLOSE: + window_close(w); + break; + default: { const auto& info = GetInfo(w); const auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); @@ -306,7 +291,7 @@ namespace OpenRCT2::Ui::Windows } } - static void window_custom_resize(rct_window * w) + static void window_custom_resize(rct_window* w) { const auto& desc = GetInfo(w).Desc; if (desc.IsResizable()) @@ -324,7 +309,7 @@ namespace OpenRCT2::Ui::Windows } } - static void window_custom_mousedown(rct_window * w, rct_widgetindex widgetIndex, rct_widget * widget) + static void window_custom_mousedown(rct_window* w, rct_widgetindex widgetIndex, rct_widget* widget) { const auto& info = GetInfo(w); const auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); @@ -338,22 +323,16 @@ namespace OpenRCT2::Ui::Windows for (size_t i = 0; i < numItems; i++) { gDropdownItemsFormat[i] = STR_STRING; - set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char *, items[i].c_str()); + set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, items[i].c_str()); } window_dropdown_show_text_custom_width( - w->x + widget->left, - w->y + widget->top, - widget->bottom - widget->top + 1, - w->colours[widget->colour], - 0, - DROPDOWN_FLAG_STAY_OPEN, - numItems, - widget->right - widget->left - 3); + w->x + widget->left, w->y + widget->top, widget->bottom - widget->top + 1, w->colours[widget->colour], 0, + DROPDOWN_FLAG_STAY_OPEN, numItems, widget->right - widget->left - 3); } } } - static void window_custom_dropdown(rct_window * w, rct_widgetindex widgetIndex, int32_t dropdownIndex) + static void window_custom_dropdown(rct_window* w, rct_widgetindex widgetIndex, int32_t dropdownIndex) { if (dropdownIndex == -1) return; @@ -379,7 +358,7 @@ namespace OpenRCT2::Ui::Windows } } - static void window_custom_invalidate(rct_window * w) + static void window_custom_invalidate(rct_window* w) { w->widgets[WIDX_BACKGROUND].right = w->width - 1; w->widgets[WIDX_BACKGROUND].bottom = w->height - 1; @@ -390,17 +369,17 @@ namespace OpenRCT2::Ui::Windows w->widgets[WIDX_CONTENT_PANEL].bottom = w->height - 1; const auto& desc = GetInfo(w).Desc; - set_format_arg(0, void *, desc.Title.c_str()); + set_format_arg(0, void*, desc.Title.c_str()); } - static void window_custom_paint(rct_window * w, rct_drawpixelinfo * dpi) + static void window_custom_paint(rct_window* w, rct_drawpixelinfo* dpi) { window_draw_widgets(w, dpi); } - static CustomWindowInfo& GetInfo(rct_window * w) + static CustomWindowInfo& GetInfo(rct_window* w) { - return *(static_cast(w->custom_info)); + return *(static_cast(w->custom_info)); } static rct_windownumber GetNewWindowNumber() @@ -413,7 +392,7 @@ namespace OpenRCT2::Ui::Windows return result; } - static void CreateWidget(std::vector& widgetList, const CustomWidgetDesc &desc) + static void CreateWidget(std::vector& widgetList, const CustomWidgetDesc& desc) { rct_widget widget{}; widget.colour = 1; @@ -456,7 +435,7 @@ namespace OpenRCT2::Ui::Windows } } - static void RefreshWidgets(rct_window * w) + static void RefreshWidgets(rct_window* w) { auto& info = GetInfo(w); auto& widgets = info.Widgets; @@ -521,4 +500,4 @@ namespace OpenRCT2::Ui::Windows } } } -} +} // namespace OpenRCT2::Ui::Windows diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 9b46766ed7..1d58081e4c 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -9,13 +9,14 @@ #pragma once +#include "../Context.h" +#include "../common.h" +#include "ScWindow.hpp" + #include #include -#include #include -#include "../common.h" -#include "../Context.h" -#include "ScWindow.hpp" +#include namespace OpenRCT2::Scripting { @@ -24,7 +25,7 @@ namespace OpenRCT2::Scripting namespace OpenRCT2::Ui::Windows { - rct_window * window_custom_open(std::shared_ptr owner, DukValue dukDesc); + rct_window* window_custom_open(std::shared_ptr owner, DukValue dukDesc); } namespace OpenRCT2::Scripting @@ -33,14 +34,21 @@ namespace OpenRCT2::Scripting { private: ScriptEngine& _scriptEngine; + public: ScUi(ScriptEngine& scriptEngine) : _scriptEngine(scriptEngine) { } - int32_t width_get() { return context_get_width(); } - int32_t height_get() { return context_get_height(); } + int32_t width_get() + { + return context_get_width(); + } + int32_t height_get() + { + return context_get_height(); + } int32_t windows_get() { return static_cast(g_window_list.size()); @@ -97,7 +105,7 @@ namespace OpenRCT2::Scripting return nullptr; } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScUi::height_get, nullptr, "height"); dukglue_register_property(ctx, &ScUi::width_get, nullptr, "width"); @@ -114,4 +122,4 @@ namespace OpenRCT2::Scripting return WC_NULL; } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index ee834e516a..1925e7bf2e 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -9,11 +9,12 @@ #pragma once -#include #include "../common.h" #include "../interface/Window.h" #include "../interface/Window_internal.h" +#include + namespace OpenRCT2::Scripting { class ScWindow @@ -23,38 +24,50 @@ namespace OpenRCT2::Scripting rct_windownumber _number; public: - ScWindow(rct_window * w) + ScWindow(rct_window* w) : ScWindow(w->classification, w->number) { } ScWindow(rct_windowclass c, rct_windownumber n) - : _class(c), - _number(n) + : _class(c) + , _number(n) { } - int32_t x_get() { return GetWindow()->x; } + int32_t x_get() + { + return GetWindow()->x; + } void x_set(int32_t value) { auto w = GetWindow(); window_set_position(w, value, w->y); } - int32_t y_get() { return GetWindow()->y; } + int32_t y_get() + { + return GetWindow()->y; + } void y_set(int32_t value) { auto w = GetWindow(); window_set_position(w, w->x, value); } - int32_t width_get() { return GetWindow()->width; } - int32_t height_get() { return GetWindow()->height; } + int32_t width_get() + { + return GetWindow()->width; + } + int32_t height_get() + { + return GetWindow()->height; + } bool isSticky_get() { auto flags = GetWindow()->flags; return (flags & (WF_STICK_TO_BACK | WF_STICK_TO_FRONT)) != 0; } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); dukglue_register_property(ctx, &ScWindow::y_get, &ScWindow::y_set, "y"); @@ -64,9 +77,9 @@ namespace OpenRCT2::Scripting } private: - rct_window * GetWindow() const + rct_window* GetWindow() const { return window_find_by_number(_class, _number); } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index 667d0eb9fe..773d466cd8 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -7,11 +7,13 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include #include "UiExtensions.h" + #include "ScUi.hpp" #include "ScWindow.hpp" +#include + using namespace OpenRCT2::Scripting; void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) diff --git a/src/openrct2-ui/scripting/UiExtensions.h b/src/openrct2-ui/scripting/UiExtensions.h index fc361da666..4f9fbfcd45 100644 --- a/src/openrct2-ui/scripting/UiExtensions.h +++ b/src/openrct2-ui/scripting/UiExtensions.h @@ -18,4 +18,4 @@ namespace OpenRCT2::Scripting public: static void Extend(ScriptEngine& scriptEngine); }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index 9b989cedd0..6725870cf8 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -8,17 +8,17 @@ *****************************************************************************/ #include -#include #include +#include #ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include +# define WIN32_LEAN_AND_MEAN +# include #else -#include -#include -#include -#include +# include +# include +# include +# include #endif #include "../core/String.hpp" @@ -61,9 +61,9 @@ void FileWatcher::FileDescriptor::Close() } FileWatcher::WatchDescriptor::WatchDescriptor(int fd, const std::string& path) - : Fd(fd), - Wd(inotify_add_watch(fd, path.c_str(), IN_CLOSE_WRITE)), - Path(path) + : Fd(fd) + , Wd(inotify_add_watch(fd, path.c_str(), IN_CLOSE_WRITE)) + , Path(path) { if (Wd >= 0) { @@ -83,11 +83,13 @@ FileWatcher::WatchDescriptor::~WatchDescriptor() } #endif -FileWatcher::FileWatcher(const std::string &directoryPath) +FileWatcher::FileWatcher(const std::string& directoryPath) { #ifdef _WIN32 _path = directoryPath; - _directoryHandle = CreateFileA(directoryPath.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + _directoryHandle = CreateFileA( + directoryPath.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, + nullptr); if (_directoryHandle == INVALID_HANDLE_VALUE) { throw std::runtime_error("Unable to open directory '" + directoryPath + "'"); @@ -123,12 +125,14 @@ void FileWatcher::WatchDirectory() #ifdef _WIN32 std::array eventData; DWORD bytesReturned; - while (ReadDirectoryChangesW(_directoryHandle, eventData.data(), (DWORD)eventData.size(), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE, &bytesReturned, nullptr, nullptr)) + while (ReadDirectoryChangesW( + _directoryHandle, eventData.data(), (DWORD)eventData.size(), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE, &bytesReturned, + nullptr, nullptr)) { auto onFileChanged = OnFileChanged; if (onFileChanged) { - FILE_NOTIFY_INFORMATION * notifyInfo; + FILE_NOTIFY_INFORMATION* notifyInfo; size_t offset = 0; do { @@ -139,8 +143,7 @@ void FileWatcher::WatchDirectory() auto fileName = String::ToUtf8(fileNameW); auto path = fs::path(_path) / fs::path(fileName); onFileChanged(path.u8string()); - } - while (notifyInfo->NextEntryOffset != 0); + } while (notifyInfo->NextEntryOffset != 0); } } #else @@ -165,11 +168,9 @@ void FileWatcher::WatchDirectory() // Find watch descriptor int wd = e->wd; - auto findResult = std::find_if(_watchDescs.begin(), _watchDescs.end(), - [wd](const WatchDescriptor& watchDesc) - { - return wd == watchDesc.Wd; - }); + auto findResult = std::find_if( + _watchDescs.begin(), _watchDescs.end(), + [wd](const WatchDescriptor& watchDesc) { return wd == watchDesc.Wd; }); if (findResult != _watchDescs.end()) { auto directory = findResult->Path; diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h index 4d977be4be..1db80379db 100644 --- a/src/openrct2/core/FileWatcher.h +++ b/src/openrct2/core/FileWatcher.h @@ -15,7 +15,7 @@ #include #ifdef _WIN32 -typedef void * HANDLE; +typedef void* HANDLE; #endif /** @@ -53,9 +53,9 @@ private: #endif public: - std::function OnFileChanged; + std::function OnFileChanged; - FileWatcher(const std::string &directoryPath); + FileWatcher(const std::string& directoryPath); ~FileWatcher(); private: diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index c4338d98bb..a52d9dc346 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -7,13 +7,14 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include #include "../Context.h" #include "../OpenRCT2.h" #include "../platform/Platform2.h" #include "../scripting/ScriptEngine.h" #include "InteractiveConsole.h" +#include + using namespace OpenRCT2; void StdInOutConsole::Start() diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index ee60345b1e..fa3ddbedf6 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -69,7 +69,7 @@ namespace WIDGET_FLAGS { const WidgetFlags TEXT_IS_STRING = 1 << 0; const WidgetFlags IS_ENABLED = 1 << 1; -} +} // namespace WIDGET_FLAGS /** * Widget structure diff --git a/src/openrct2/interface/Window_internal.h b/src/openrct2/interface/Window_internal.h index 1ba55eab3c..7e64440a55 100644 --- a/src/openrct2/interface/Window_internal.h +++ b/src/openrct2/interface/Window_internal.h @@ -55,7 +55,7 @@ struct rct_window scenery_variables scenery; track_list_variables track_list; error_variables error; - void * custom_info; + void* custom_info; }; int16_t page; union diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index b6a1823e4f..3ef3f239e6 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -7,26 +7,26 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include #include "HookEngine.h" + #include "ScriptEngine.h" +#include + using namespace OpenRCT2::Scripting; -HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string &name) +HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string& name) { static const std::unordered_map LookupTable({ { "interval.tick", HOOK_TYPE::INTERVAL_TICK }, { "interval.day", HOOK_TYPE::INTERVAL_DAY }, }); auto result = LookupTable.find(name); - return (result != LookupTable.end()) ? - result->second : - HOOK_TYPE::UNDEFINED; + return (result != LookupTable.end()) ? result->second : HOOK_TYPE::UNDEFINED; } -HookEngine::HookEngine(ScriptExecutionInfo& execInfo) : - _execInfo(execInfo) +HookEngine::HookEngine(ScriptExecutionInfo& execInfo) + : _execInfo(execInfo) { _hookMap.resize(NUM_HOOK_TYPES); for (size_t i = 0; i < NUM_HOOK_TYPES; i++) @@ -35,7 +35,7 @@ HookEngine::HookEngine(ScriptExecutionInfo& execInfo) : } } -uint32_t HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function) +uint32_t HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue& function) { auto& hookList = GetHookList(type); auto cookie = _nextCookie++; diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 24cdd36d89..ed426a42c6 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -10,10 +10,11 @@ #pragma once #include "../common.h" + +#include #include #include #include -#include namespace OpenRCT2::Scripting { @@ -28,7 +29,7 @@ namespace OpenRCT2::Scripting UNDEFINED = -1, }; constexpr size_t NUM_HOOK_TYPES = static_cast(HOOK_TYPE::COUNT); - HOOK_TYPE GetHookType(const std::string &name); + HOOK_TYPE GetHookType(const std::string& name); struct Hook { @@ -37,10 +38,10 @@ namespace OpenRCT2::Scripting DukValue Function; Hook(); - Hook(uint32_t cookie, std::shared_ptr owner, const DukValue &function) - : Cookie(cookie), - Owner(owner), - Function(function) + Hook(uint32_t cookie, std::shared_ptr owner, const DukValue& function) + : Cookie(cookie) + , Owner(owner) + , Function(function) { } }; @@ -50,11 +51,13 @@ namespace OpenRCT2::Scripting HOOK_TYPE Type; std::vector Hooks; - HookList() {} + HookList() + { + } HookList(const HookList&) = delete; HookList(HookList&& src) - : Type(std::move(src.Type)), - Hooks(std::move(src.Hooks)) + : Type(std::move(src.Type)) + , Hooks(std::move(src.Hooks)) { } }; @@ -70,7 +73,7 @@ namespace OpenRCT2::Scripting public: HookEngine(ScriptExecutionInfo& execInfo); HookEngine(const HookEngine&) = delete; - uint32_t Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue &function); + uint32_t Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue& function); void Unsubscribe(HOOK_TYPE type, uint32_t cookie); void UnsubscribeAll(std::shared_ptr owner); void Call(HOOK_TYPE type); @@ -78,4 +81,4 @@ namespace OpenRCT2::Scripting private: HookList& GetHookList(HOOK_TYPE type); }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 4367e02514..234c8a3e7f 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -8,26 +8,27 @@ *****************************************************************************/ #include "Plugin.h" + +#include #include #include -#include #include #include #ifdef _WIN32 - + #else - #include - #include - #include - #include +# include +# include +# include +# include #endif using namespace OpenRCT2::Scripting; -Plugin::Plugin(duk_context * context, const std::string &path) - : _context(context), - _path(path) +Plugin::Plugin(duk_context* context, const std::string& path) + : _context(context) + , _path(path) { } @@ -39,12 +40,10 @@ void Plugin::Load() std::ifstream fs(_path); if (fs.is_open()) { - fs.seekg(0, std::ios::end); + fs.seekg(0, std::ios::end); code.reserve(fs.tellg()); fs.seekg(0, std::ios::beg); - code.assign( - std::istreambuf_iterator(fs), - std::istreambuf_iterator()); + code.assign(std::istreambuf_iterator(fs), std::istreambuf_iterator()); } } // Wrap the script in a function and pass the global objects as variables @@ -98,11 +97,9 @@ PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) if (dukAuthors.is_array()) { auto elements = dukAuthors.as_array(); - std::transform( - elements.begin(), - elements.end(), - std::back_inserter(metadata.Authors), - [](const DukValue& v) { return v.as_string(); }); + std::transform(elements.begin(), elements.end(), std::back_inserter(metadata.Authors), [](const DukValue& v) { + return v.as_string(); + }); } else { diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 99171e4540..c95ca31315 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -9,10 +9,10 @@ #pragma once +#include #include #include #include -#include namespace OpenRCT2::Scripting { @@ -27,15 +27,20 @@ namespace OpenRCT2::Scripting class Plugin { private: - duk_context * _context; + duk_context* _context; std::string _path; PluginMetadata _metadata; public: - std::string GetPath() const { return _path; }; + std::string GetPath() const + { + return _path; + }; - Plugin() { } - Plugin(duk_context * context, const std::string &path); + Plugin() + { + } + Plugin(duk_context* context, const std::string& path); Plugin(const Plugin&) = delete; Plugin(Plugin&&) = delete; @@ -46,4 +51,4 @@ namespace OpenRCT2::Scripting private: static PluginMetadata GetMetadata(const DukValue& dukMetadata); }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index ceee2643da..c6fb8038e0 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -9,9 +9,8 @@ #pragma once -#include -#include "../interface/InteractiveConsole.h" #include "../core/Math.hpp" +#include "../interface/InteractiveConsole.h" #include @@ -38,9 +37,15 @@ namespace OpenRCT2::Scripting std::string str; switch (val.type()) { - case DukValue::Type::UNDEFINED: str = "undefined"; break; - case DukValue::Type::NULLREF: str = "null"; break; - case DukValue::Type::BOOLEAN: str = val.as_bool() ? "true" : "false"; break; + case DukValue::Type::UNDEFINED: + str = "undefined"; + break; + case DukValue::Type::NULLREF: + str = "null"; + break; + case DukValue::Type::BOOLEAN: + str = val.as_bool() ? "true" : "false"; + break; case DukValue::Type::NUMBER: { const auto d = val.as_double(); @@ -55,11 +60,20 @@ namespace OpenRCT2::Scripting } break; } - case DukValue::Type::STRING: str = val.as_string(); break; - case DukValue::Type::OBJECT: str = "{}"; break; - case DukValue::Type::BUFFER: str = "buffer"; break; - case DukValue::Type::POINTER: str = "pointer"; break; - case DukValue::Type::LIGHTFUNC: break; + case DukValue::Type::STRING: + str = val.as_string(); + break; + case DukValue::Type::OBJECT: + str = "{}"; + break; + case DukValue::Type::BUFFER: + str = "buffer"; + break; + case DukValue::Type::POINTER: + str = "pointer"; + break; + case DukValue::Type::LIGHTFUNC: + break; } _console.WriteLine(str); diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 1cd1fdd638..85b8de1956 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -9,11 +9,12 @@ #pragma once -#include #include "HookEngine.h" #include "ScDisposable.hpp" #include "ScriptEngine.h" + #include +#include #include namespace OpenRCT2::Scripting @@ -26,8 +27,8 @@ namespace OpenRCT2::Scripting public: ScContext(ScriptExecutionInfo& execInfo, HookEngine& hookEngine) - : _execInfo(execInfo), - _hookEngine(hookEngine) + : _execInfo(execInfo) + , _hookEngine(hookEngine) { } @@ -35,7 +36,7 @@ namespace OpenRCT2::Scripting { } - std::shared_ptr subscribe(const std::string &hook, const DukValue &callback) + std::shared_ptr subscribe(const std::string& hook, const DukValue& callback) { auto hookType = GetHookType(hook); if (hookType == HOOK_TYPE::UNDEFINED) @@ -55,17 +56,13 @@ namespace OpenRCT2::Scripting } auto cookie = _hookEngine.Subscribe(hookType, owner, callback); - return std::make_shared( - [this, hookType, cookie]() - { - _hookEngine.Unsubscribe(hookType, cookie); - }); + return std::make_shared([this, hookType, cookie]() { _hookEngine.Unsubscribe(hookType, cookie); }); } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_method(ctx, &ScContext::registerIntent, "registerIntent"); dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index a285d05018..7e2840710b 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -20,8 +20,8 @@ namespace OpenRCT2::Scripting std::function _onDispose; public: - ScDisposable(std::function onDispose) : - _onDispose(onDispose) + ScDisposable(std::function onDispose) + : _onDispose(onDispose) { } @@ -33,9 +33,9 @@ namespace OpenRCT2::Scripting } } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_method(ctx, &ScDisposable::dispose, "dispose"); } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 989eb61105..84866ac2f6 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -9,22 +9,23 @@ #pragma once -#include #include "../common.h" #include "../ride/Ride.h" #include "../world/Map.h" -#include "ScTile.hpp" #include "ScThing.hpp" +#include "ScTile.hpp" + +#include namespace OpenRCT2::Scripting { class ScMap { private: - duk_context * _context; + duk_context* _context; public: - ScMap(duk_context * ctx) + ScMap(duk_context* ctx) : _context(ctx) { } @@ -69,7 +70,7 @@ namespace OpenRCT2::Scripting return nullptr; } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScMap::size_get, nullptr, "size"); dukglue_register_property(ctx, &ScMap::rides_get, nullptr, "rides"); @@ -78,4 +79,4 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScMap::getThing, "getThing"); } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 67ddf6ec82..bc966afb7f 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -9,21 +9,25 @@ #pragma once -#include -#include -#include "../common.h" #include "../Context.h" +#include "../common.h" #include "../management/Finance.h" #include "../management/NewsItem.h" #include "../windows/Intent.h" #include "../world/Park.h" +#include +#include + namespace OpenRCT2::Scripting { class ScPark { public: - money32 cash_get() { return gCash; } + money32 cash_get() + { + return gCash; + } void cash_set(money32 value) { gCash = value; @@ -31,7 +35,10 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - int32_t rating_get() { return gParkRating; } + int32_t rating_get() + { + return gParkRating; + } void rating_set(int32_t value) { gParkRating = std::min(std::max(0, value), 999); @@ -39,7 +46,10 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - money32 bankLoan_get() { return gBankLoan; } + money32 bankLoan_get() + { + return gBankLoan; + } void bankLoan_set(money32 value) { gBankLoan = value; @@ -47,7 +57,10 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - money32 maxBankLoan_get() { return gMaxBankLoan; } + money32 maxBankLoan_get() + { + return gMaxBankLoan; + } void maxBankLoan_set(money32 value) { gMaxBankLoan = value; @@ -77,7 +90,7 @@ namespace OpenRCT2::Scripting } } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScPark::cash_get, &ScPark::cash_set, "cash"); dukglue_register_property(ctx, &ScPark::rating_get, &ScPark::rating_set, "rating"); @@ -89,16 +102,8 @@ namespace OpenRCT2::Scripting private: uint8_t GetParkMessageType(const std::string& key) { - static auto keys = { - "attraction", - "peep_on_attraction", - "peep", - "money", - "blank", - "research", - "guests", - "award", - "chart" }; + static auto keys = { "attraction", "peep_on_attraction", "peep", "money", "blank", "research", "guests", "award", + "chart" }; uint8_t i = 0; for (const auto& k : keys) { @@ -111,4 +116,4 @@ namespace OpenRCT2::Scripting return NEWS_ITEM_BLANK; } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 0de40ee18f..f6d14cff8a 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -9,19 +9,20 @@ #pragma once -#include #include "../common.h" #include "../world/Sprite.h" +#include + namespace OpenRCT2::Scripting { class ScThing { private: - rct_sprite * _sprite; + rct_sprite* _sprite; public: - ScThing(rct_sprite * sprite) + ScThing(rct_sprite* sprite) : _sprite(sprite) { } @@ -35,16 +36,37 @@ namespace OpenRCT2::Scripting return "unknown"; } - int32_t x_get() { return _sprite->unknown.x; } - int32_t y_get() { return _sprite->unknown.y; } - int32_t z_get() { return _sprite->unknown.z; } + int32_t x_get() + { + return _sprite->unknown.x; + } + int32_t y_get() + { + return _sprite->unknown.y; + } + int32_t z_get() + { + return _sprite->unknown.z; + } - uint8_t tshirtColour_get() { return _sprite->peep.tshirt_colour; } - void tshirtColour_set(uint8_t value) { _sprite->peep.tshirt_colour = value; } - uint8_t trousersColour_get() { return _sprite->peep.trousers_colour; } - void trousersColour_set(uint8_t value) { _sprite->peep.trousers_colour = value; } + uint8_t tshirtColour_get() + { + return _sprite->peep.tshirt_colour; + } + void tshirtColour_set(uint8_t value) + { + _sprite->peep.tshirt_colour = value; + } + uint8_t trousersColour_get() + { + return _sprite->peep.trousers_colour; + } + void trousersColour_set(uint8_t value) + { + _sprite->peep.trousers_colour = value; + } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); dukglue_register_property(ctx, &ScThing::x_get, nullptr, "x"); @@ -54,4 +76,4 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScThing::trousersColour_get, &ScThing::trousersColour_set, "trousersColour"); } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 39ba7d5a3c..78661aef0d 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -9,20 +9,21 @@ #pragma once -#include #include "../common.h" #include "../world/Sprite.h" + #include +#include namespace OpenRCT2::Scripting { class ScTileElement { protected: - rct_tile_element * _element; + rct_tile_element* _element; public: - ScTileElement(rct_tile_element * element) + ScTileElement(rct_tile_element* element) : _element(element) { } @@ -31,21 +32,30 @@ namespace OpenRCT2::Scripting { switch (_element->GetType()) { - case TILE_ELEMENT_TYPE_SURFACE: return "surface"; - case TILE_ELEMENT_TYPE_PATH: return "footpath"; - case TILE_ELEMENT_TYPE_TRACK: return "track"; - case TILE_ELEMENT_TYPE_SMALL_SCENERY: return "small-scenery"; - case TILE_ELEMENT_TYPE_ENTRANCE: return "entrance"; - case TILE_ELEMENT_TYPE_WALL: return "wall"; - case TILE_ELEMENT_TYPE_LARGE_SCENERY: return "large-scenery"; - case TILE_ELEMENT_TYPE_BANNER: return "banner"; - case TILE_ELEMENT_TYPE_CORRUPT: return "openrct2-corrupt"; - default: return "unknown"; + case TILE_ELEMENT_TYPE_SURFACE: + return "surface"; + case TILE_ELEMENT_TYPE_PATH: + return "footpath"; + case TILE_ELEMENT_TYPE_TRACK: + return "track"; + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + return "small-scenery"; + case TILE_ELEMENT_TYPE_ENTRANCE: + return "entrance"; + case TILE_ELEMENT_TYPE_WALL: + return "wall"; + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + return "large-scenery"; + case TILE_ELEMENT_TYPE_BANNER: + return "banner"; + case TILE_ELEMENT_TYPE_CORRUPT: + return "openrct2-corrupt"; + default: + return "unknown"; } } - template - T* getAs() + template T* getAs() { return static_cast(this); } @@ -85,8 +95,7 @@ namespace OpenRCT2::Scripting } static void Register(duk_context* ctx); - template - static void RegisterSharedProperties(duk_context* ctx); + template static void RegisterSharedProperties(duk_context* ctx); }; class ScSurfaceElement final : public ScTileElement @@ -190,38 +199,31 @@ namespace OpenRCT2::Scripting ScBannerElement ::Register(ctx); } - template - void ScTileElement::RegisterSharedProperties(duk_context* ctx) + template void ScTileElement::RegisterSharedProperties(duk_context* ctx) { // When you register a member function of a parent class, it belongs to the parent and cannot be accessed by its // children. To get around this issue, we need to force the function pointer types to be of the class we want them to be // available for. This needs to be done for every child. dukglue_register_property(ctx, static_cast(&ScTileElement::type_get), nullptr, "type"); dukglue_register_property( - ctx, - static_cast(&ScTileElement::broken_get), - static_cast(&ScTileElement::broken_set), - "broken"); + ctx, static_cast(&ScTileElement::broken_get), + static_cast(&ScTileElement::broken_set), "broken"); dukglue_register_property( - ctx, - static_cast(&ScTileElement::baseHeight_get), - static_cast(&ScTileElement::baseHeight_set), - "baseHeight"); + ctx, static_cast(&ScTileElement::baseHeight_get), + static_cast(&ScTileElement::baseHeight_set), "baseHeight"); dukglue_register_property( - ctx, - static_cast(&ScTileElement::clearanceHeight_get), - static_cast(&ScTileElement::clearanceHeight_set), - "clearanceHeight"); + ctx, static_cast(&ScTileElement::clearanceHeight_get), + static_cast(&ScTileElement::clearanceHeight_set), "clearanceHeight"); } class ScTile { private: - rct_tile_element * _first; + rct_tile_element* _first; size_t _count = 0; public: - ScTile(rct_tile_element * first) + ScTile(rct_tile_element* first) : _first(first) { _count = 0; @@ -231,16 +233,19 @@ namespace OpenRCT2::Scripting do { _count++; - } - while (!(element++)->IsLastForTile()); + } while (!(element++)->IsLastForTile()); } } - size_t numElements_get() { return _count; } + size_t numElements_get() + { + return _count; + } std::shared_ptr getElement(size_t index) { - if (index >= _count) return nullptr; + if (index >= _count) + return nullptr; return std::make_shared(&_first[index]); } @@ -256,11 +261,11 @@ namespace OpenRCT2::Scripting // return elements; // } - static void Register(duk_context * ctx) + static void Register(duk_context* ctx) { // dukglue_register_property(ctx, &ScTile::elements_get, nullptr, "elements"); dukglue_register_property(ctx, &ScTile::numElements_get, nullptr, "numElements"); dukglue_register_method(ctx, &ScTile::getElement, "getElement"); } }; -} +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 7d4d4999cc..b413227f8a 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -8,28 +8,29 @@ *****************************************************************************/ #include "ScriptEngine.h" + +#include "../PlatformEnvironment.h" #include "../core/FileScanner.h" #include "../core/Path.hpp" #include "../interface/InteractiveConsole.h" #include "../platform/Platform2.h" -#include "../PlatformEnvironment.h" -#include -#include -#include -#include - #include "ScConsole.hpp" #include "ScContext.hpp" #include "ScDisposable.hpp" #include "ScMap.hpp" #include "ScPark.hpp" -#include "ScTile.hpp" #include "ScThing.hpp" +#include "ScTile.hpp" + +#include +#include +#include +#include using namespace OpenRCT2; using namespace OpenRCT2::Scripting; -static std::string Stringify(duk_context * ctx, duk_idx_t idx); +static std::string Stringify(duk_context* ctx, duk_idx_t idx); DukContext::DukContext() { @@ -45,10 +46,10 @@ DukContext::~DukContext() duk_destroy_heap(_context); } -ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) : - _console(console), - _env(env), - _hookEngine(_execInfo) +ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) + : _console(console) + , _env(env) + , _hookEngine(_execInfo) { } @@ -88,7 +89,7 @@ void ScriptEngine::LoadPlugins() plugin->Load(); _plugins.push_back(std::move(plugin)); } - catch (const std::exception &e) + catch (const std::exception& e) { _console.WriteLineError(e.what()); } @@ -98,12 +99,10 @@ void ScriptEngine::LoadPlugins() { // Enable hot reloading _pluginFileWatcher = std::make_unique(base); - _pluginFileWatcher->OnFileChanged = - [this](const std::string &path) - { - std::lock_guard guard(_changedPluginFilesMutex); - _changedPluginFiles.push_back(path); - }; + _pluginFileWatcher->OnFileChanged = [this](const std::string& path) { + std::lock_guard guard(_changedPluginFilesMutex); + _changedPluginFiles.push_back(path); + }; } catch (const std::exception& e) { @@ -118,11 +117,9 @@ void ScriptEngine::AutoReloadPlugins() std::lock_guard guard(_changedPluginFilesMutex); for (auto& path : _changedPluginFiles) { - auto findResult = std::find_if(_plugins.begin(), _plugins.end(), - [&path](const std::shared_ptr& plugin) - { - return Path::Equals(path, plugin->GetPath()); - }); + auto findResult = std::find_if(_plugins.begin(), _plugins.end(), [&path](const std::shared_ptr& plugin) { + return Path::Equals(path, plugin->GetPath()); + }); if (findResult != _plugins.end()) { auto& plugin = *findResult; @@ -134,7 +131,7 @@ void ScriptEngine::AutoReloadPlugins() plugin->Load(); plugin->Start(); } - catch (const std::exception &e) + catch (const std::exception& e) { _console.WriteLineError(e.what()); } @@ -153,7 +150,7 @@ void ScriptEngine::StartPlugins() { plugin->Start(); } - catch (const std::exception &e) + catch (const std::exception& e) { _console.WriteLineError(e.what()); } @@ -196,7 +193,7 @@ void ScriptEngine::Update() } } -std::future ScriptEngine::Eval(const std::string &s) +std::future ScriptEngine::Eval(const std::string& s) { std::promise barrier; auto future = barrier.get_future(); @@ -204,7 +201,7 @@ std::future ScriptEngine::Eval(const std::string &s) return future; } -static std::string Stringify(duk_context * ctx, duk_idx_t idx) +static std::string Stringify(duk_context* ctx, duk_idx_t idx) { auto type = duk_get_type(ctx, idx); if (type == DUK_TYPE_OBJECT && !duk_is_function(ctx, idx)) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 04318f87e9..551ba200bc 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -13,6 +13,7 @@ #include "../core/FileWatcher.h" #include "HookEngine.h" #include "Plugin.h" + #include #include #include @@ -47,8 +48,8 @@ namespace OpenRCT2::Scripting public: PluginScope(ScriptExecutionInfo& execInfo, std::shared_ptr plugin) - : _execInfo(execInfo), - _plugin(plugin) + : _execInfo(execInfo) + , _plugin(plugin) { _execInfo._plugin = plugin; } @@ -59,13 +60,16 @@ namespace OpenRCT2::Scripting } }; - std::shared_ptr GetCurrentPlugin() { return _plugin; } + std::shared_ptr GetCurrentPlugin() + { + return _plugin; + } }; class DukContext { private: - duk_context * _context{}; + duk_context* _context{}; public: DukContext(); @@ -76,7 +80,10 @@ namespace OpenRCT2::Scripting } ~DukContext(); - operator duk_context*() { return _context; } + operator duk_context*() + { + return _context; + } }; class ScriptEngine @@ -100,12 +107,21 @@ namespace OpenRCT2::Scripting ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); ScriptEngine(ScriptEngine&) = delete; - duk_context * GetContext() { return _context; } - HookEngine& GetHookEngine() { return _hookEngine; } - ScriptExecutionInfo& GetExecInfo() { return _execInfo; } + duk_context* GetContext() + { + return _context; + } + HookEngine& GetHookEngine() + { + return _hookEngine; + } + ScriptExecutionInfo& GetExecInfo() + { + return _execInfo; + } void Update(); - std::future Eval(const std::string &s); + std::future Eval(const std::string& s); private: void Initialise(); @@ -113,4 +129,4 @@ namespace OpenRCT2::Scripting void StartPlugins(); void AutoReloadPlugins(); }; -} +} // namespace OpenRCT2::Scripting From bec9c4da65a8493acdd49c76b1e2c6944031070e Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Sat, 11 Aug 2018 16:54:13 +0200 Subject: [PATCH 032/159] Expose surface element properties --- src/openrct2/scripting/ScThing.hpp | 34 +++++++++++++-- src/openrct2/scripting/ScTile.hpp | 68 ++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 4 deletions(-) diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index f6d14cff8a..05fee9bf89 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -36,18 +36,35 @@ namespace OpenRCT2::Scripting return "unknown"; } + // x getter and setter int32_t x_get() { return _sprite->unknown.x; } + void x_set(int32_t value) + { + _sprite->unknown.x = value; + } + + // y getter and setter int32_t y_get() { return _sprite->unknown.y; } - int32_t z_get() + void y_set(int32_t value) + { + _sprite->unknown.y = value; + } + + // z getter and setter + int16_t z_get() { return _sprite->unknown.z; } + void z_set(int16_t value) + { + _sprite->unknown.z = value; + } uint8_t tshirtColour_get() { @@ -66,12 +83,21 @@ namespace OpenRCT2::Scripting _sprite->peep.trousers_colour = value; } + template static void dukglue_property_helper(duk_context* ctx, T& var, const char* name) + { + auto getter = []() -> const T { return var; }; + auto setter = [&var](T& value) -> void { var = value; }; + dukglue_register_property(ctx, getter, setter, name); + } + static void Register(duk_context* ctx) { + dukglue_register_constructor(ctx, "Thing"); dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); - dukglue_register_property(ctx, &ScThing::x_get, nullptr, "x"); - dukglue_register_property(ctx, &ScThing::y_get, nullptr, "y"); - dukglue_register_property(ctx, &ScThing::z_get, nullptr, "z"); + dukglue_register_property(ctx, &ScThing::x_get, &ScThing::x_set, "x"); + //dukglue_property_helper(ctx, _sprite->peep.x, "x"); + dukglue_register_property(ctx, &ScThing::y_get, &ScThing::y_set, "y"); + dukglue_register_property(ctx, &ScThing::z_get, &ScThing::z_set, "z"); dukglue_register_property(ctx, &ScThing::tshirtColour_get, &ScThing::tshirtColour_set, "tshirtColour"); dukglue_register_property(ctx, &ScThing::trousersColour_get, &ScThing::trousersColour_set, "trousersColour"); } diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 78661aef0d..06404d4e29 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -11,6 +11,7 @@ #include "../common.h" #include "../world/Sprite.h" +#include "../world/Surface.h" #include #include @@ -100,10 +101,77 @@ namespace OpenRCT2::Scripting class ScSurfaceElement final : public ScTileElement { + uint8_t slope_get() + { + return _element->properties.surface.slope & TILE_ELEMENT_SURFACE_SLOPE_MASK; + } + void slope_set(uint8_t value) + { + // TODO: Give warning when value > TILE_ELEMENT_SURFACE_SLOPE_MASK + _element->properties.surface.slope &= ~TILE_ELEMENT_SURFACE_SLOPE_MASK; + _element->properties.surface.slope |= value & TILE_ELEMENT_SURFACE_SLOPE_MASK; + } + + uint8_t terrain_get() + { + return surface_get_terrain(_element); + } + void terrain_set(uint8_t value) + { + surface_set_terrain(_element, value); + } + + uint8_t waterHeight_get() + { + return surface_get_water_height(_element); + } + void waterHeight_set(uint8_t value) + { + // TODO: Give warning when value > TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK + _element->properties.surface.terrain &= ~TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK; + _element->properties.surface.terrain |= value & TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK; + } + + uint8_t grassLength_get() + { + return _element->properties.surface.grass_length; + } + void grassLength_set(uint8_t value) + { + // TODO: Give warning when value > GRASS_LENGTH_CLUMPS_2 + _element->properties.surface.grass_length = value; + } + + uint8_t ownership_get() + { + return _element->properties.surface.ownership & 0xF0; + } + void ownership_set(uint8_t flags) + { + _element->properties.surface.ownership &= ~0xF0; + _element->properties.surface.ownership |= flags << 4; + } + + uint8_t parkFences_get() + { + return _element->properties.surface.ownership & 0xF0; + } + void parkFences_set(uint8_t flags) + { + _element->properties.surface.ownership &= ~0x0F; + _element->properties.surface.ownership |= flags & 0x0F; + } + public: static void Register(duk_context* ctx) { RegisterSharedProperties(ctx); + dukglue_register_property(ctx, &slope_get, &slope_set, "slope"); + dukglue_register_property(ctx, &terrain_get, &terrain_set, "terrain"); + dukglue_register_property(ctx, &waterHeight_get, &waterHeight_set, "waterHeight"); + dukglue_register_property(ctx, &grassLength_get, &grassLength_set, "grassLength"); + dukglue_register_property(ctx, &ownership_get, &ownership_set, "ownership"); + dukglue_register_property(ctx, &waterHeight_get, &parkFences_set, "parkFences"); } }; From 6e45c23833e7d388f9d99e22f23f9f75a774dfee Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Sat, 11 Aug 2018 16:55:02 +0200 Subject: [PATCH 033/159] Update TrueScript definition file to match the properties --- distribution/openrct2.d.ts | 47 +++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 349bcffa70..9ed132bba7 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -64,16 +64,57 @@ export interface TileElement { type: TileElementType; zBase: number; zClearance: number; - - // footpath-item: broken: boolean; + + /** + * Gets the element as a specific type to access its properties + */ + asSurface(): SurfaceElement; + asTrack(): TrackElement; + asSmallScenery(): SmallSceneryElement; + asEntrance(): EntranceElement; + asWall(): WallElement; + asLargeScenery(): LargeSceneryElement; + asBanner(): BannerElement; + asCorruptElement(): CorruptElement; +} + +export interface SurfaceElement extends TileElement { + slope: number; + terrain: number; + waterHeight: number; + grassLength: number; + ownership: number; + parkFences: number; +} + +export interface TrackElement extends TileElement { +} + +export interface SmallSceneryElement extends TileElement { +} + +export interface EntranceElement extends TileElement { +} + +export interface WallElement extends TileElement { +} + +export interface LargeSceneryElement extends TileElement { +} + +export interface BannerElement extends TileElement { +} + +export interface CorruptElement extends TileElement { } export interface Tile { x: number; y: number; - type: TileType; elements: TileElement[]; + + getElement(index: number): TileElement; } export interface Ride { From 9b2ed0d641c60bae758eab82a3179a355e008ac0 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Sun, 12 Aug 2018 23:08:39 +0200 Subject: [PATCH 034/159] Expose properties for path scenery --- distribution/openrct2.d.ts | 31 ++++- src/openrct2/scripting/ScTile.hpp | 182 ++++++++++++++++++++++++++++++ 2 files changed, 210 insertions(+), 3 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 9ed132bba7..da2171d8e0 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -58,18 +58,19 @@ export interface IDisposable { } export type TileElementType = - "surface" | "footpath-item"; + "surface" | "footpath"; export interface TileElement { type: TileElementType; - zBase: number; - zClearance: number; + baseHeight: number; + clearanceHeight: number; broken: boolean; /** * Gets the element as a specific type to access its properties */ asSurface(): SurfaceElement; + asFootpath(): FootpathElement; asTrack(): TrackElement; asSmallScenery(): SmallSceneryElement; asEntrance(): EntranceElement; @@ -88,6 +89,30 @@ export interface SurfaceElement extends TileElement { parkFences: number; } +export interface FootpathAddition { + type: number; + isBin: boolean; + isBench: boolean; + isLamp: boolean; + isBreakable: boolean; + isJumpingFountainWater: boolean; + isJumpingFountainSnow: boolean; + allowedOnQueue: boolean; + allowedOnSlope: boolean; + isQueueScreen: boolean; + + /** + * Remove the path addition + */ + remove(): void; +} + +export interface FootpathElement extends TileElement { + type: number; + isSloped: boolean; + addition: FootpathAddition; +} + export interface TrackElement extends TileElement { } diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 06404d4e29..af38b9afbe 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -10,6 +10,8 @@ #pragma once #include "../common.h" +#include "../world/Footpath.h" +#include "../world/Scenery.h" #include "../world/Sprite.h" #include "../world/Surface.h" @@ -177,10 +179,188 @@ namespace OpenRCT2::Scripting class ScFootpathElement final : public ScTileElement { + class ScFootpathAddition + { + protected: + rct_tile_element* _element; + bool VerifyPathAdditionExists() + { + if (!footpath_element_has_path_scenery(_element)) + { + // TODO: Show warning in console that the path addition has been removed + return false; + } + return true; + } + + public: + ScFootpathAddition(ScFootpathElement* path) + : _element(path->_element) + { + } + + void Remove() + { + footpath_element_set_path_scenery(_element, 0); + } + + uint8_t type_get() + { + if (!VerifyPathAdditionExists()) + return 0; + return footpath_element_get_path_scenery(_element); + } + void type_set(uint8_t value) + { + footpath_element_set_path_scenery(_element, value); + } + + bool isBin_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_BIN; + } + bool isBench_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_BENCH; + } + bool isLamp_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_LAMP; + } + bool isBreakable_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_BREAKABLE; + } + bool isJumpingFountainWater_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_JUMPING_FOUNTAIN_WATER; + } + bool isJumpingFountainSnow_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_JUMPING_FOUNTAIN_SNOW; + } + bool allowedOnQueue_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_DONT_ALLOW_ON_QUEUE; + } + bool allowedOnSlope_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_DONT_ALLOW_ON_SLOPE; + } + bool isQueueScreen_get() + { + if (!VerifyPathAdditionExists()) + return false; + + auto index = footpath_element_get_path_scenery_index(_element); + auto sceneryEntry = get_footpath_item_entry(index); + return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_QUEUE_SCREEN; + } + + static void Register(duk_context* ctx) + { + dukglue_register_method(ctx, &ScFootpathAddition::Remove, "remove"); + + dukglue_register_property(ctx, &type_get, &type_set, "type"); + dukglue_register_property(ctx, &isBin_get, nullptr, "isBin"); + dukglue_register_property(ctx, &isBench_get, nullptr, "isBench"); + dukglue_register_property(ctx, &isLamp_get, nullptr, "isLamp"); + dukglue_register_property(ctx, &isBreakable_get, nullptr, "isBreakable"); + dukglue_register_property(ctx, &isJumpingFountainWater_get, nullptr, "isJumpingFountainWater"); + dukglue_register_property(ctx, &isJumpingFountainSnow_get, nullptr, "isJumpingFountainSnow"); + dukglue_register_property(ctx, &allowedOnQueue_get, nullptr, "allowedOnQueue"); + dukglue_register_property(ctx, &allowedOnSlope_get, nullptr, "allowedOnSlope"); + dukglue_register_property(ctx, &isQueueScreen_get, nullptr, "isQueueScreen"); + } + }; + + uint8_t type_get() + { + return footpath_element_get_type(_element); + } + void type_set(uint8_t index) + { + auto entry = get_footpath_entry(index); + if (entry == nullptr) + { + // TODO: Give warning (most likely only happens when index > MAX_PATH_OBJECTS) + return; + } + footpath_element_set_type(_element, index); + } + + bool sloped_get() + { + return footpath_element_is_sloped(_element); + } + void slope_set(bool value) + { + footpath_element_set_sloped(_element, value); + } + + std::shared_ptr addition_get() + { + + if (!footpath_element_has_path_scenery(_element)) + return nullptr; + + return std::make_shared(this); + } + public: static void Register(duk_context* ctx) { + // Registe rshared properties (baseheight, clearance height, etc.) RegisterSharedProperties(ctx); + + // Register path addition properties (.addition.isBench, .addition.isLamp, etc.) + ScFootpathAddition::Register(ctx); + + // Specific properties + dukglue_register_property(ctx, &type_get, &type_set, "type"); + dukglue_register_property(ctx, &sloped_get, &slope_set, "isSloped"); + dukglue_register_property(ctx, &sloped_get, &slope_set, "isQueue"); + dukglue_register_property(ctx, &addition_get, nullptr, "addition"); } }; @@ -247,6 +427,7 @@ namespace OpenRCT2::Scripting void ScTileElement::Register(duk_context* ctx) { dukglue_register_method(ctx, &ScTileElement::getAs, "asSurface"); + dukglue_register_method(ctx, &ScTileElement::getAs, "asFootpath"); dukglue_register_method(ctx, &ScTileElement::getAs, "asTrack"); dukglue_register_method(ctx, &ScTileElement::getAs, "asSmallScenery"); dukglue_register_method(ctx, &ScTileElement::getAs, "asEntrance"); @@ -259,6 +440,7 @@ namespace OpenRCT2::Scripting // Register type specific properties ScSurfaceElement ::Register(ctx); + ScFootpathElement::Register(ctx); ScTrackElement ::Register(ctx); ScSmallSceneryElement ::Register(ctx); ScEntranceElement ::Register(ctx); From d7123834df8888e19b4a78b4b2f74a04c51f0ae5 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Tue, 14 Aug 2018 01:59:30 +0200 Subject: [PATCH 035/159] Expose more footpath and footpath-adition properties --- distribution/openrct2.d.ts | 11 ++- src/openrct2/scripting/ScTile.hpp | 132 +++++++++++++++++++++++++++--- 2 files changed, 129 insertions(+), 14 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index da2171d8e0..08b5a254b5 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -89,6 +89,13 @@ export interface SurfaceElement extends TileElement { parkFences: number; } +export interface FootpathAdditionStatus { + north: number; + east: number; + south: number; + west: number; +} + export interface FootpathAddition { type: number; isBin: boolean; @@ -100,6 +107,8 @@ export interface FootpathAddition { allowedOnQueue: boolean; allowedOnSlope: boolean; isQueueScreen: boolean; + status: FootpathAdditionStatus; + rideIndex: number; /** * Remove the path addition @@ -108,7 +117,7 @@ export interface FootpathAddition { } export interface FootpathElement extends TileElement { - type: number; + footpathType: number; isSloped: boolean; addition: FootpathAddition; } diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index af38b9afbe..89ccaafd33 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -31,7 +31,7 @@ namespace OpenRCT2::Scripting { } - std::string type_get() const + std::string footpathType_get() const { switch (_element->GetType()) { @@ -181,6 +181,66 @@ namespace OpenRCT2::Scripting { class ScFootpathAddition { + class ScFootpathAdditionStatus + { + protected: + rct_tile_element* _element; + + public: + ScFootpathAdditionStatus(rct_tile_element* element) + : _element(element) + { + } + + uint8_t north_get() + { + return _element->properties.path.addition_status & 3; + } + void north_set(uint8_t value) + { + _element->properties.path.addition_status &= ~3; + _element->properties.path.addition_status |= value & 3; + } + + uint8_t east_get() + { + return _element->properties.path.addition_status & 3; + } + void east_set(uint8_t value) + { + _element->properties.path.addition_status &= ~(3 << 2); + _element->properties.path.addition_status |= (value & 3) << 2; + } + + uint8_t south_get() + { + return _element->properties.path.addition_status & 3; + } + void south_set(uint8_t value) + { + _element->properties.path.addition_status &= ~(3 << 4); + _element->properties.path.addition_status |= (value & 3) << 4; + } + + uint8_t west_get() + { + return _element->properties.path.addition_status & 3; + } + void west_set(uint8_t value) + { + _element->properties.path.addition_status &= ~(3 << 6); + _element->properties.path.addition_status |= (value & 3) << 6; + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &north_get, &north_set, "north"); + dukglue_register_property(ctx, &east_get, &east_set, "east"); + dukglue_register_property(ctx, &south_get, &south_set, "south"); + dukglue_register_property(ctx, &west_get, &west_set, "west"); + } + }; + protected: rct_tile_element* _element; bool VerifyPathAdditionExists() @@ -194,8 +254,8 @@ namespace OpenRCT2::Scripting } public: - ScFootpathAddition(ScFootpathElement* path) - : _element(path->_element) + ScFootpathAddition(rct_tile_element* element) + : _element(element) { } @@ -297,10 +357,20 @@ namespace OpenRCT2::Scripting return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_QUEUE_SCREEN; } + std::shared_ptr status_get() + { + return std::make_shared(_element); + } + static void Register(duk_context* ctx) { + // Addition status properties (.status.north, .status.east, etc.) + ScFootpathAdditionStatus::Register(ctx); + + // Functions dukglue_register_method(ctx, &ScFootpathAddition::Remove, "remove"); + // Properties dukglue_register_property(ctx, &type_get, &type_set, "type"); dukglue_register_property(ctx, &isBin_get, nullptr, "isBin"); dukglue_register_property(ctx, &isBench_get, nullptr, "isBench"); @@ -311,10 +381,11 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &allowedOnQueue_get, nullptr, "allowedOnQueue"); dukglue_register_property(ctx, &allowedOnSlope_get, nullptr, "allowedOnSlope"); dukglue_register_property(ctx, &isQueueScreen_get, nullptr, "isQueueScreen"); + dukglue_register_property(ctx, &status_get, nullptr, "status"); } }; - uint8_t type_get() + uint8_t footpathType_get() { return footpath_element_get_type(_element); } @@ -329,38 +400,72 @@ namespace OpenRCT2::Scripting footpath_element_set_type(_element, index); } - bool sloped_get() + bool isSloped_get() { return footpath_element_is_sloped(_element); } - void slope_set(bool value) + void isSlope_set(bool value) { footpath_element_set_sloped(_element, value); } + bool isQueue_get() + { + return footpath_element_is_queue(_element); + } + std::shared_ptr addition_get() { - if (!footpath_element_has_path_scenery(_element)) return nullptr; - return std::make_shared(this); + return std::make_shared(_element); + } + + uint8_t edges_get() + { + return footpath_element_get_edges(_element); + } + void edges_set(uint8_t value) + { + footpath_element_set_edges(_element, value); + } + + uint8_t corners_get() + { + return footpath_element_get_corners(_element); + } + void corners_set(uint8_t value) + { + footpath_element_set_corners(_element, value); + } + + uint8_t rideIndex_get() + { + if (!footpath_element_is_queue(_element)) + { + // TODO: Show warning that "path is not a queue" + } + return _element->properties.path.ride_index; } public: static void Register(duk_context* ctx) { - // Registe rshared properties (baseheight, clearance height, etc.) + // Register shared properties (baseheight, clearance height, etc.) RegisterSharedProperties(ctx); // Register path addition properties (.addition.isBench, .addition.isLamp, etc.) ScFootpathAddition::Register(ctx); // Specific properties - dukglue_register_property(ctx, &type_get, &type_set, "type"); - dukglue_register_property(ctx, &sloped_get, &slope_set, "isSloped"); - dukglue_register_property(ctx, &sloped_get, &slope_set, "isQueue"); + dukglue_register_property(ctx, &footpathType_get, &type_set, "footpathType"); + dukglue_register_property(ctx, &isSloped_get, &isSlope_set, "isSloped"); + dukglue_register_property(ctx, &isQueue_get, nullptr, "isQueue"); dukglue_register_property(ctx, &addition_get, nullptr, "addition"); + dukglue_register_property(ctx, &edges_get, &edges_set, "edges"); + dukglue_register_property(ctx, &corners_get, &corners_set, "corners"); + dukglue_register_property(ctx, &rideIndex_get, nullptr, "rideIndex"); } }; @@ -454,7 +559,8 @@ namespace OpenRCT2::Scripting // When you register a member function of a parent class, it belongs to the parent and cannot be accessed by its // children. To get around this issue, we need to force the function pointer types to be of the class we want them to be // available for. This needs to be done for every child. - dukglue_register_property(ctx, static_cast(&ScTileElement::type_get), nullptr, "type"); + dukglue_register_property( + ctx, static_cast(&ScTileElement::footpathType_get), nullptr, "type"); dukglue_register_property( ctx, static_cast(&ScTileElement::broken_get), static_cast(&ScTileElement::broken_set), "broken"); From e8468e71bb2d99cecec32c5cfc03566494d820b9 Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Tue, 14 Aug 2018 02:02:43 +0200 Subject: [PATCH 036/159] Update typescript definition --- distribution/openrct2.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 08b5a254b5..9ba8576d96 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -108,7 +108,6 @@ export interface FootpathAddition { allowedOnSlope: boolean; isQueueScreen: boolean; status: FootpathAdditionStatus; - rideIndex: number; /** * Remove the path addition @@ -119,7 +118,11 @@ export interface FootpathAddition { export interface FootpathElement extends TileElement { footpathType: number; isSloped: boolean; + isQueue: boolean; addition: FootpathAddition; + edges: number; + corners: number; + rideIndex: number; } export interface TrackElement extends TileElement { From 5bd58118b54de88569268921a22ae5e31047debb Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 23 Jul 2019 23:21:42 +0100 Subject: [PATCH 037/159] Get the plugin branch building again --- src/openrct2-ui/scripting/ScUi.hpp | 12 +- src/openrct2-ui/scripting/ScWindow.hpp | 9 +- src/openrct2/interface/StdInOutConsole.cpp | 3 +- src/openrct2/scripting/Duktape.hpp | 4 + src/openrct2/scripting/HookEngine.h | 2 +- src/openrct2/scripting/Plugin.cpp | 4 +- src/openrct2/scripting/Plugin.h | 3 +- src/openrct2/scripting/ScConsole.hpp | 19 ++- src/openrct2/scripting/ScContext.hpp | 2 +- src/openrct2/scripting/ScDisposable.hpp | 3 +- src/openrct2/scripting/ScMap.hpp | 5 +- src/openrct2/scripting/ScPark.hpp | 2 +- src/openrct2/scripting/ScThing.hpp | 17 ++- src/openrct2/scripting/ScTile.hpp | 141 ++++++++++----------- src/openrct2/scripting/ScriptEngine.cpp | 3 +- 15 files changed, 118 insertions(+), 111 deletions(-) create mode 100644 src/openrct2/scripting/Duktape.hpp diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 1d58081e4c..5484286a6f 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -9,12 +9,12 @@ #pragma once -#include "../Context.h" -#include "../common.h" #include "ScWindow.hpp" -#include #include +#include +#include +#include #include #include @@ -93,12 +93,12 @@ namespace OpenRCT2::Scripting std::shared_ptr getWindow(int32_t index) { - for (int32_t i = 0; i < g_window_list.size(); i++) + int32_t i = 0; + for (auto w : g_window_list) { if (i == index) { - auto w = g_window_list[i].get(); - return std::make_shared(w); + return std::make_shared(w.get()); } i++; } diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 1925e7bf2e..413b260894 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -9,11 +9,10 @@ #pragma once -#include "../common.h" -#include "../interface/Window.h" -#include "../interface/Window_internal.h" - -#include +#include +#include +#include +#include namespace OpenRCT2::Scripting { diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index a52d9dc346..9491b00cd7 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -11,10 +11,9 @@ #include "../OpenRCT2.h" #include "../platform/Platform2.h" #include "../scripting/ScriptEngine.h" +#include "../thirdparty/linenoise.hpp" #include "InteractiveConsole.h" -#include - using namespace OpenRCT2; void StdInOutConsole::Start() diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp new file mode 100644 index 0000000000..22b096e3f6 --- /dev/null +++ b/src/openrct2/scripting/Duktape.hpp @@ -0,0 +1,4 @@ +#pragma once + +#include "../thirdparty/dukglue/dukglue.h" +#include diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index ed426a42c6..4753d3ce64 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -10,8 +10,8 @@ #pragma once #include "../common.h" +#include "Duktape.hpp" -#include #include #include #include diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 234c8a3e7f..f96b75272b 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -9,9 +9,9 @@ #include "Plugin.h" +#include "Duktape.hpp" + #include -#include -#include #include #include diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index c95ca31315..4ae6b8a8d3 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -9,7 +9,8 @@ #pragma once -#include +#include "Duktape.hpp" + #include #include #include diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index c6fb8038e0..a53a9b8b82 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -9,10 +9,8 @@ #pragma once -#include "../core/Math.hpp" #include "../interface/InteractiveConsole.h" - -#include +#include "Duktape.hpp" namespace OpenRCT2::Scripting { @@ -50,7 +48,7 @@ namespace OpenRCT2::Scripting { const auto d = val.as_double(); const duk_int_t i = val.as_int(); - if (Math::AlmostEqual(d, i)) + if (AlmostEqual(d, i)) { str = std::to_string(i); } @@ -84,5 +82,18 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScConsole::clear, "clear"); dukglue_register_method(ctx, &ScConsole::log, "log"); } + + private: + // Taken from http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon + template + static typename std::enable_if::is_integer, bool>::type AlmostEqual(T x, T y, int32_t ulp = 20) + { + // the machine epsilon has to be scaled to the magnitude of the values used + // and multiplied by the desired precision in ULPs (units in the last place) + return std::abs(x - y) <= std::numeric_limits::epsilon() * std::abs(x + y) * ulp + // unless the result is subnormal + || std::abs(x - y) + < (std::numeric_limits::min)(); // TODO: Remove parentheses around min once the macro is removed + } }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 85b8de1956..b53770a9fe 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -9,12 +9,12 @@ #pragma once +#include "Duktape.hpp" #include "HookEngine.h" #include "ScDisposable.hpp" #include "ScriptEngine.h" #include -#include #include namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index 7e2840710b..13219b0ed4 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -9,7 +9,8 @@ #pragma once -#include +#include "Duktape.hpp" + #include namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 84866ac2f6..410b894610 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -12,11 +12,10 @@ #include "../common.h" #include "../ride/Ride.h" #include "../world/Map.h" +#include "Duktape.hpp" #include "ScThing.hpp" #include "ScTile.hpp" -#include - namespace OpenRCT2::Scripting { class ScMap @@ -62,7 +61,7 @@ namespace OpenRCT2::Scripting if (id >= 0 && id < MAX_SPRITES) { auto sprite = get_sprite(id); - if (sprite != nullptr && sprite->unknown.sprite_identifier != SPRITE_IDENTIFIER_NULL) + if (sprite != nullptr && sprite->generic.sprite_identifier != SPRITE_IDENTIFIER_NULL) { return std::make_shared(sprite); } diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index bc966afb7f..57d133f57e 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -15,9 +15,9 @@ #include "../management/NewsItem.h" #include "../windows/Intent.h" #include "../world/Park.h" +#include "Duktape.hpp" #include -#include namespace OpenRCT2::Scripting { diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 05fee9bf89..5d303454f3 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -11,8 +11,7 @@ #include "../common.h" #include "../world/Sprite.h" - -#include +#include "Duktape.hpp" namespace OpenRCT2::Scripting { @@ -29,7 +28,7 @@ namespace OpenRCT2::Scripting std::string type_get() { - if (_sprite->unknown.sprite_identifier == SPRITE_IDENTIFIER_PEEP) + if (_sprite->generic.sprite_identifier == SPRITE_IDENTIFIER_PEEP) { return "peep"; } @@ -39,31 +38,31 @@ namespace OpenRCT2::Scripting // x getter and setter int32_t x_get() { - return _sprite->unknown.x; + return _sprite->generic.x; } void x_set(int32_t value) { - _sprite->unknown.x = value; + _sprite->generic.x = value; } // y getter and setter int32_t y_get() { - return _sprite->unknown.y; + return _sprite->generic.y; } void y_set(int32_t value) { - _sprite->unknown.y = value; + _sprite->generic.y = value; } // z getter and setter int16_t z_get() { - return _sprite->unknown.z; + return _sprite->generic.z; } void z_set(int16_t value) { - _sprite->unknown.z = value; + _sprite->generic.z = value; } uint8_t tshirtColour_get() diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 89ccaafd33..69c605106b 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -14,19 +14,19 @@ #include "../world/Scenery.h" #include "../world/Sprite.h" #include "../world/Surface.h" +#include "Duktape.hpp" #include -#include namespace OpenRCT2::Scripting { class ScTileElement { protected: - rct_tile_element* _element; + TileElement* _element; public: - ScTileElement(rct_tile_element* element) + ScTileElement(TileElement* element) : _element(element) { } @@ -105,63 +105,59 @@ namespace OpenRCT2::Scripting { uint8_t slope_get() { - return _element->properties.surface.slope & TILE_ELEMENT_SURFACE_SLOPE_MASK; + return _element->AsSurface()->GetSlope(); } void slope_set(uint8_t value) { // TODO: Give warning when value > TILE_ELEMENT_SURFACE_SLOPE_MASK - _element->properties.surface.slope &= ~TILE_ELEMENT_SURFACE_SLOPE_MASK; - _element->properties.surface.slope |= value & TILE_ELEMENT_SURFACE_SLOPE_MASK; + _element->AsSurface()->SetSlope(value); } uint8_t terrain_get() { - return surface_get_terrain(_element); + return _element->AsSurface()->GetSurfaceStyle(); } void terrain_set(uint8_t value) { - surface_set_terrain(_element, value); + _element->AsSurface()->SetSurfaceStyle(value); } uint8_t waterHeight_get() { - return surface_get_water_height(_element); + return _element->AsSurface()->GetWaterHeight(); } void waterHeight_set(uint8_t value) { // TODO: Give warning when value > TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK - _element->properties.surface.terrain &= ~TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK; - _element->properties.surface.terrain |= value & TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK; + _element->AsSurface()->SetWaterHeight(value); } uint8_t grassLength_get() { - return _element->properties.surface.grass_length; + return _element->AsSurface()->GetGrassLength(); } void grassLength_set(uint8_t value) { // TODO: Give warning when value > GRASS_LENGTH_CLUMPS_2 - _element->properties.surface.grass_length = value; + return _element->AsSurface()->SetGrassLength(value); } uint8_t ownership_get() { - return _element->properties.surface.ownership & 0xF0; + return _element->AsSurface()->GetOwnership(); } void ownership_set(uint8_t flags) { - _element->properties.surface.ownership &= ~0xF0; - _element->properties.surface.ownership |= flags << 4; + _element->AsSurface()->SetOwnership(flags); } uint8_t parkFences_get() { - return _element->properties.surface.ownership & 0xF0; + return _element->AsSurface()->GetParkFences(); } void parkFences_set(uint8_t flags) { - _element->properties.surface.ownership &= ~0x0F; - _element->properties.surface.ownership |= flags & 0x0F; + return _element->AsSurface()->SetParkFences(flags); } public: @@ -184,52 +180,60 @@ namespace OpenRCT2::Scripting class ScFootpathAdditionStatus { protected: - rct_tile_element* _element; + TileElement* _element; public: - ScFootpathAdditionStatus(rct_tile_element* element) + ScFootpathAdditionStatus(TileElement* element) : _element(element) { } uint8_t north_get() { - return _element->properties.path.addition_status & 3; + return _element->AsPath()->GetAdditionStatus() & 3; } void north_set(uint8_t value) { - _element->properties.path.addition_status &= ~3; - _element->properties.path.addition_status |= value & 3; + auto addition = _element->AsPath()->GetAdditionStatus(); + addition &= ~3; + addition |= value & 3; + _element->AsPath()->SetAdditionStatus(addition); } uint8_t east_get() { - return _element->properties.path.addition_status & 3; + return _element->AsPath()->GetAdditionStatus() & 3; } void east_set(uint8_t value) { - _element->properties.path.addition_status &= ~(3 << 2); - _element->properties.path.addition_status |= (value & 3) << 2; + auto addition = _element->AsPath()->GetAdditionStatus(); + addition &= ~(3 << 2); + addition |= (value & 3) << 2; + _element->AsPath()->SetAdditionStatus(addition); } uint8_t south_get() { - return _element->properties.path.addition_status & 3; + return _element->AsPath()->GetAdditionStatus() & 3; } void south_set(uint8_t value) { - _element->properties.path.addition_status &= ~(3 << 4); - _element->properties.path.addition_status |= (value & 3) << 4; + auto addition = _element->AsPath()->GetAdditionStatus(); + addition &= ~(3 << 4); + addition |= (value & 3) << 4; + _element->AsPath()->SetAdditionStatus(addition); } uint8_t west_get() { - return _element->properties.path.addition_status & 3; + return _element->AsPath()->GetAdditionStatus() & 3; } void west_set(uint8_t value) { - _element->properties.path.addition_status &= ~(3 << 6); - _element->properties.path.addition_status |= (value & 3) << 6; + auto addition = _element->AsPath()->GetAdditionStatus(); + addition &= ~(3 << 6); + addition |= (value & 3) << 6; + _element->AsPath()->SetAdditionStatus(addition); } static void Register(duk_context* ctx) @@ -242,10 +246,10 @@ namespace OpenRCT2::Scripting }; protected: - rct_tile_element* _element; + TileElement* _element; bool VerifyPathAdditionExists() { - if (!footpath_element_has_path_scenery(_element)) + if (!_element->AsPath()->HasAddition()) { // TODO: Show warning in console that the path addition has been removed return false; @@ -254,25 +258,25 @@ namespace OpenRCT2::Scripting } public: - ScFootpathAddition(rct_tile_element* element) + ScFootpathAddition(TileElement* element) : _element(element) { } void Remove() { - footpath_element_set_path_scenery(_element, 0); + _element->AsPath()->SetAddition(0); } uint8_t type_get() { if (!VerifyPathAdditionExists()) return 0; - return footpath_element_get_path_scenery(_element); + return _element->AsPath()->GetAddition(); } void type_set(uint8_t value) { - footpath_element_set_path_scenery(_element, value); + _element->AsPath()->SetAddition(value); } bool isBin_get() @@ -280,8 +284,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_BIN; } bool isBench_get() @@ -289,8 +292,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_BENCH; } bool isLamp_get() @@ -298,8 +300,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_LAMP; } bool isBreakable_get() @@ -307,8 +308,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_BREAKABLE; } bool isJumpingFountainWater_get() @@ -316,8 +316,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_JUMPING_FOUNTAIN_WATER; } bool isJumpingFountainSnow_get() @@ -325,8 +324,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_JUMPING_FOUNTAIN_SNOW; } bool allowedOnQueue_get() @@ -334,8 +332,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_DONT_ALLOW_ON_QUEUE; } bool allowedOnSlope_get() @@ -343,8 +340,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_DONT_ALLOW_ON_SLOPE; } bool isQueueScreen_get() @@ -352,8 +348,7 @@ namespace OpenRCT2::Scripting if (!VerifyPathAdditionExists()) return false; - auto index = footpath_element_get_path_scenery_index(_element); - auto sceneryEntry = get_footpath_item_entry(index); + auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_QUEUE_SCREEN; } @@ -387,36 +382,36 @@ namespace OpenRCT2::Scripting uint8_t footpathType_get() { - return footpath_element_get_type(_element); + return _element->AsPath()->GetPathEntryIndex(); } void type_set(uint8_t index) { - auto entry = get_footpath_entry(index); + auto entry = get_path_surface_entry(index); if (entry == nullptr) { // TODO: Give warning (most likely only happens when index > MAX_PATH_OBJECTS) return; } - footpath_element_set_type(_element, index); + _element->AsPath()->SetPathEntryIndex(index); } bool isSloped_get() { - return footpath_element_is_sloped(_element); + return _element->AsPath()->IsSloped(); } void isSlope_set(bool value) { - footpath_element_set_sloped(_element, value); + _element->AsPath()->SetSloped(value); } bool isQueue_get() { - return footpath_element_is_queue(_element); + return _element->AsPath()->IsQueue(); } std::shared_ptr addition_get() { - if (!footpath_element_has_path_scenery(_element)) + if (!_element->AsPath()->HasAddition()) return nullptr; return std::make_shared(_element); @@ -424,29 +419,29 @@ namespace OpenRCT2::Scripting uint8_t edges_get() { - return footpath_element_get_edges(_element); + return _element->AsPath()->GetEdges(); } void edges_set(uint8_t value) { - footpath_element_set_edges(_element, value); + _element->AsPath()->SetEdges(value); } uint8_t corners_get() { - return footpath_element_get_corners(_element); + return _element->AsPath()->GetCorners(); } void corners_set(uint8_t value) { - footpath_element_set_corners(_element, value); + _element->AsPath()->SetCorners(value); } uint8_t rideIndex_get() { - if (!footpath_element_is_queue(_element)) + if (!_element->AsPath()->IsQueue()) { // TODO: Show warning that "path is not a queue" } - return _element->properties.path.ride_index; + return _element->AsPath()->GetRideIndex(); } public: @@ -473,7 +468,7 @@ namespace OpenRCT2::Scripting { auto track_ride_index_get() const { - return _element->properties.track.ride_index; + return _element->AsTrack()->GetRideIndex(); } public: @@ -575,11 +570,11 @@ namespace OpenRCT2::Scripting class ScTile { private: - rct_tile_element* _first; + TileElement* _first; size_t _count = 0; public: - ScTile(rct_tile_element* first) + ScTile(TileElement* first) : _first(first) { _count = 0; diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index b413227f8a..7d8012e3e8 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -14,6 +14,7 @@ #include "../core/Path.hpp" #include "../interface/InteractiveConsole.h" #include "../platform/Platform2.h" +#include "Duktape.hpp" #include "ScConsole.hpp" #include "ScContext.hpp" #include "ScDisposable.hpp" @@ -22,8 +23,6 @@ #include "ScThing.hpp" #include "ScTile.hpp" -#include -#include #include #include From 5d78a1f2bf8d42d6f28b190520019c76a6276649 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 24 Jul 2019 21:08:03 +0100 Subject: [PATCH 038/159] Add initial network API --- distribution/openrct2.d.ts | 13 ++++ src/openrct2/scripting/Plugin.cpp | 16 ++--- src/openrct2/scripting/ScNetwork.hpp | 81 +++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 6 +- 4 files changed, 105 insertions(+), 11 deletions(-) create mode 100644 src/openrct2/scripting/ScNetwork.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 9ba8576d96..7e97a2eb31 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -264,10 +264,23 @@ export interface Ui { closeAllWindows(): void; } +export interface Player { + name: string; +} + +export interface Network { + players: number; + + getPlayer(index: number): Player; + sendMessage(message: string); + sendMessage(players: number[], message: string); +} + declare global { var console: Console; var context: Context; var map: Map; + var network: Network; var park: Park; var ui: Ui; } diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index f96b75272b..cdac2f3877 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -9,21 +9,13 @@ #include "Plugin.h" +#include "..\OpenRCT2.h" #include "Duktape.hpp" #include #include #include -#ifdef _WIN32 - -#else -# include -# include -# include -# include -#endif - using namespace OpenRCT2::Scripting; Plugin::Plugin(duk_context* context, const std::string& path) @@ -34,7 +26,11 @@ Plugin::Plugin(duk_context* context, const std::string& path) void Plugin::Load() { - std::string projectedVariables = "console,context,map,park,ui"; + std::string projectedVariables = "console,context,map,network,park"; + if (!gOpenRCT2Headless) + { + projectedVariables += ",ui"; + } std::string code; { std::ifstream fs(_path); diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp new file mode 100644 index 0000000000..4de87192af --- /dev/null +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -0,0 +1,81 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 + +#include "../network/network.h" +#include "Duktape.hpp" + +namespace OpenRCT2::Scripting +{ + class ScPlayer + { + private: + int32_t _id; + + public: + ScPlayer(int32_t id) + : _id(id) + { + } + + int32_t id_get() + { + return _id; + } + + std::string name_get() + { + auto index = network_get_player_index(_id); + if (index == -1) + return {}; + return network_get_player_name(index); + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &ScPlayer::id_get, nullptr, "id"); + dukglue_register_property(ctx, &ScPlayer::name_get, nullptr, "name"); + } + }; + + class ScNetwork + { + private: + duk_context* _context; + + public: + ScNetwork(duk_context* ctx) + : _context(ctx) + { + } + + int32_t players_get() + { + return network_get_num_players(); + } + + std::shared_ptr getPlayer(int32_t index) + { + auto numPlayers = network_get_num_players(); + if (index < numPlayers) + { + auto playerId = network_get_player_id(index); + return std::make_shared(playerId); + } + return nullptr; + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &ScNetwork::players_get, nullptr, "players"); + dukglue_register_method(ctx, &ScNetwork::getPlayer, "getPlayer"); + } + }; +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 7d8012e3e8..842b6301d0 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -19,6 +19,7 @@ #include "ScContext.hpp" #include "ScDisposable.hpp" #include "ScMap.hpp" +#include "ScNetwork.hpp" #include "ScPark.hpp" #include "ScThing.hpp" #include "ScTile.hpp" @@ -59,7 +60,9 @@ void ScriptEngine::Initialise() ScContext::Register(ctx); ScDisposable::Register(ctx); ScMap::Register(ctx); + ScNetwork::Register(ctx); ScPark::Register(ctx); + ScPlayer::Register(ctx); ScTile::Register(ctx); ScTileElement::Register(ctx); ScThing::Register(ctx); @@ -67,6 +70,7 @@ void ScriptEngine::Initialise() dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); dukglue_register_global(ctx, std::make_shared(ctx), "map"); + dukglue_register_global(ctx, std::make_shared(ctx), "network"); dukglue_register_global(ctx, std::make_shared(), "park"); LoadPlugins(); @@ -174,7 +178,7 @@ void ScriptEngine::Update() std::string result = std::string(duk_safe_to_string(_context, -1)); _console.WriteLineError(result); } - else + else if (duk_get_type(_context, -1) != DUK_TYPE_UNDEFINED) { std::string result = Stringify(_context, -1); _console.WriteLine(result); From 082eaf7c9c01bcc1a0ec661ae2d6fd8e1c0708b0 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 25 Jul 2019 20:45:38 +0100 Subject: [PATCH 039/159] Add more network API --- distribution/openrct2.d.ts | 74 ++++++++-- src/openrct2/scripting/ScNetwork.hpp | 189 ++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 1 + 3 files changed, 252 insertions(+), 12 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 7e97a2eb31..7e88986af0 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -147,8 +147,8 @@ export interface CorruptElement extends TileElement { } export interface Tile { - x: number; - y: number; + readonly x: number; + readonly y: number; elements: TileElement[]; getElement(index: number): TileElement; @@ -162,7 +162,7 @@ export interface Ride { totalCustomers: number; } -export type TileElementType = +export type ThingType = "car" | "duck" | "peep"; export interface Thing { @@ -177,9 +177,9 @@ export interface Thing { } export interface Map { - size: { x: number; y: number; }; - rides: number; - things: number; + readonly size: { x: number; y: number; }; + readonly rides: number; + readonly things: number; getRide(id: number): Ride; getTile(x: number, y: number): Tile; @@ -253,9 +253,9 @@ export interface WindowDesc { } export interface Ui { - width: number; - height: number; - windows: number; + readonly width: number; + readonly height: number; + readonly windows: number; getWindow(id: number): Window; getWindow(classification: string, id?: number): Window; @@ -265,15 +265,65 @@ export interface Ui { } export interface Player { + readonly id: number; + readonly name: string; + group: number; + readonly ping: number; + readonly commandsRan: number; + readonly moneySpent: number; +} + +export type PermissionType = + "chat" | + "terraform" | + "set_water_level" | + "toggle_pause" | + "create_ride" | + "remove_ride" | + "build_ride" | + "ride_properties" | + "scenery" | + "path" | + "clear_landscape" | + "guest" | + "staff" | + "park_properties" | + "park_funding" | + "kick_player" | + "modify_groups" | + "set_player_group" | + "cheat" | + "toggle_scenery_cluster" | + "passwordless_login" | + "modify_tile" | + "edit_scenario_options"; + +export interface PlayerGroup { + readonly id: number; name: string; + permissions: PermissionType[]; +} + +export interface ServerInfo { + readonly name: string; + readonly description: string; + readonly greeting: string; + readonly providerName: string; + readonly providerEmail: string; + readonly providerWebsite: string; } export interface Network { - players: number; + readonly groups: number; + readonly players: number; + defaultGroup: number; + getServerInfo(): ServerInfo; + getGroup(index: number): PlayerGroup; + setGroups(groups: PlayerGroup[]): void; getPlayer(index: number): Player; - sendMessage(message: string); - sendMessage(players: number[], message: string); + sendMessage(message: string): void; + sendMessage(players: number[], message: string): void; } declare global { diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index 4de87192af..ea74774ebd 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -9,11 +9,132 @@ #pragma once +#include "../actions/NetworkModifyGroupAction.hpp" +#include "../actions/PlayerSetGroupAction.hpp" +#include "../network/NetworkAction.h" #include "../network/network.h" #include "Duktape.hpp" namespace OpenRCT2::Scripting { + class ScPlayerGroup + { + private: + int32_t _id; + + public: + ScPlayerGroup(int32_t id) + : _id(id) + { + } + + int32_t id_get() + { + return _id; + } + + std::string name_get() + { + auto index = network_get_group_index(_id); + if (index == -1) + return {}; + return network_get_group_name(index); + } + void name_set(std::string value) + { + auto action = NetworkModifyGroupAction(ModifyGroupType::SetName, _id, value); + GameActions::Execute(&action); + } + + std::vector permissions_get() + { + auto index = network_get_group_index(_id); + if (index == -1) + return {}; + + // Create array of permissions + std::vector result; + auto permissionIndex = 0; + for (const auto& action : NetworkActions::Actions) + { + if (network_can_perform_action(index, permissionIndex)) + { + auto p = TransformPermissionKeyToJS(action.PermissionName); + result.push_back(p); + } + permissionIndex++; + } + return result; + } + void permissions_set(std::vector value) + { + auto groupIndex = network_get_group_index(_id); + if (groupIndex == -1) + return; + + // First clear all permissions + auto networkAction = NetworkModifyGroupAction( + ModifyGroupType::SetPermissions, _id, "", 0, PermissionState::ClearAll); + GameActions::Execute(&networkAction); + + std::vector enabledPermissions; + enabledPermissions.resize(NetworkActions::Actions.size()); + for (const auto& p : value) + { + auto permissionName = TransformPermissionKeyToInternal(p); + + auto permissionIndex = 0; + for (const auto& action : NetworkActions::Actions) + { + if (action.PermissionName == permissionName) + { + enabledPermissions[permissionIndex] = true; + } + permissionIndex++; + } + } + + for (size_t i = 0; i < enabledPermissions.size(); i++) + { + auto toggle = (enabledPermissions[i] != (network_can_perform_action(groupIndex, (uint32_t)i) != 0)); + if (toggle) + { + auto networkAction2 = NetworkModifyGroupAction( + ModifyGroupType::SetPermissions, _id, "", (uint32_t)i, PermissionState::Toggle); + GameActions::Execute(&networkAction2); + } + } + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &ScPlayerGroup::id_get, nullptr, "id"); + dukglue_register_property(ctx, &ScPlayerGroup::name_get, &ScPlayerGroup::name_set, "name"); + dukglue_register_property(ctx, &ScPlayerGroup::permissions_get, &ScPlayerGroup::permissions_set, "permissions"); + } + + private: + std::string TransformPermissionKeyToJS(const std::string& s) + { + auto result = s.substr(11); + for (auto& c : result) + { + c = std::tolower(c); + } + return result; + } + + std::string TransformPermissionKeyToInternal(const std::string& s) + { + auto result = "PERMISSION_" + s; + for (auto& c : result) + { + c = std::toupper(c); + } + return result; + } + }; + class ScPlayer { private: @@ -38,10 +159,51 @@ namespace OpenRCT2::Scripting return network_get_player_name(index); } + int32_t group_get() + { + auto index = network_get_player_index(_id); + if (index == -1) + return {}; + return network_get_player_group(index); + } + void group_set(int32_t value) + { + auto playerSetGroupAction = PlayerSetGroupAction(_id, value); + GameActions::Execute(&playerSetGroupAction); + } + + int32_t ping_get() + { + auto index = network_get_player_index(_id); + if (index == -1) + return {}; + return network_get_player_ping(index); + } + + int32_t commandsRan_get() + { + auto index = network_get_player_index(_id); + if (index == -1) + return {}; + return network_get_player_commands_ran(index); + } + + int32_t moneySpent_get() + { + auto index = network_get_player_index(_id); + if (index == -1) + return {}; + return network_get_player_money_spent(index); + } + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScPlayer::id_get, nullptr, "id"); dukglue_register_property(ctx, &ScPlayer::name_get, nullptr, "name"); + dukglue_register_property(ctx, &ScPlayer::group_get, &ScPlayer::group_set, "group"); + dukglue_register_property(ctx, &ScPlayer::ping_get, nullptr, "ping"); + dukglue_register_property(ctx, &ScPlayer::commandsRan_get, nullptr, "commandsRan"); + dukglue_register_property(ctx, &ScPlayer::moneySpent_get, nullptr, "moneySpent"); } }; @@ -60,6 +222,19 @@ namespace OpenRCT2::Scripting { return network_get_num_players(); } + int32_t groups_get() + { + return network_get_num_groups(); + } + int32_t defaultGroup_get() + { + return network_get_default_group(); + } + void defaultGroup_set(int32_t value) + { + auto action = NetworkModifyGroupAction(ModifyGroupType::SetDefault, value); + GameActions::Execute(&action); + } std::shared_ptr getPlayer(int32_t index) { @@ -72,10 +247,24 @@ namespace OpenRCT2::Scripting return nullptr; } + std::shared_ptr getGroup(int32_t index) + { + auto numGroups = network_get_num_groups(); + if (index < numGroups) + { + auto groupId = network_get_group_id(index); + return std::make_shared(groupId); + } + return nullptr; + } + static void Register(duk_context* ctx) { + dukglue_register_property(ctx, &ScNetwork::groups_get, nullptr, "groups"); dukglue_register_property(ctx, &ScNetwork::players_get, nullptr, "players"); + dukglue_register_property(ctx, &ScNetwork::defaultGroup_get, &ScNetwork::defaultGroup_set, "defaultGroup"); dukglue_register_method(ctx, &ScNetwork::getPlayer, "getPlayer"); + dukglue_register_method(ctx, &ScNetwork::getGroup, "getGroup"); } }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 842b6301d0..eaa1b41cf2 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -63,6 +63,7 @@ void ScriptEngine::Initialise() ScNetwork::Register(ctx); ScPark::Register(ctx); ScPlayer::Register(ctx); + ScPlayerGroup::Register(ctx); ScTile::Register(ctx); ScTileElement::Register(ctx); ScThing::Register(ctx); From 098348d3c34bbd8245a9ed164d0dd43a5c3a6f29 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 25 Jul 2019 22:59:26 +0100 Subject: [PATCH 040/159] Add hooking for chat message --- distribution/openrct2.d.ts | 6 ++++- src/openrct2/network/Network.cpp | 7 ++++++ src/openrct2/scripting/HookEngine.cpp | 36 +++++++++++++++++++++++++++ src/openrct2/scripting/HookEngine.h | 4 +++ 4 files changed, 52 insertions(+), 1 deletion(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 7e88986af0..1edbf4d395 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -28,6 +28,10 @@ export interface Configuration { has(key: string): boolean; } +export type HookType = + "interval.tick" | "interval.day" | + "network.chat"; + export interface Context { /** * The user's current configuration. @@ -42,7 +46,7 @@ export interface Context { /** * Subscribes to the given hook. */ - subscribe(hook: string, callback: Function): IDisposable; + subscribe(hook: HookType, callback: Function): IDisposable; } export interface IntentDesc diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 8ab46138ab..e0fc690a72 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -19,6 +19,7 @@ #include "../actions/PeepPickupAction.hpp" #include "../core/Guard.hpp" #include "../platform/platform.h" +#include "../scripting/ScriptEngine.h" #include "../ui/UiContext.h" #include "../ui/WindowManager.h" #include "../util/SawyerCoding.h" @@ -2832,6 +2833,12 @@ void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& p const char* text = packet.ReadString(); if (text) { + auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, { + { "player", (int32_t)connection.Player->Id }, + { "message", std::string(text) } + }); + const char* formatted = FormatChat(connection.Player, text); chat_history_add(formatted); Server_Send_CHAT(formatted); diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 3ef3f239e6..ae93d31f78 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -20,6 +20,7 @@ HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string& name) static const std::unordered_map LookupTable({ { "interval.tick", HOOK_TYPE::INTERVAL_TICK }, { "interval.day", HOOK_TYPE::INTERVAL_DAY }, + { "network.chat", HOOK_TYPE::NETWORK_CHAT }, }); auto result = LookupTable.find(name); return (result != LookupTable.end()) ? result->second : HOOK_TYPE::UNDEFINED; @@ -91,6 +92,41 @@ void HookEngine::Call(HOOK_TYPE type) } } +void HookEngine::Call(HOOK_TYPE type, const std::initializer_list>& args) +{ + auto& hookList = GetHookList(type); + for (auto& hook : hookList.Hooks) + { + ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner); + + const auto& function = hook.Function; + auto ctx = function.context(); + function.push(); + + auto objIdx = duk_push_object(ctx); + for (const auto& arg : args) + { + if (arg.second.type() == typeid(int32_t)) + { + auto val = std::any_cast(arg.second); + duk_push_int(ctx, val); + } + else if (arg.second.type() == typeid(std::string)) + { + const auto& val = std::any_cast(arg.second); + duk_push_string(ctx, val.c_str()); + } + else + { + throw std::runtime_error("Not implemented"); + } + duk_put_prop_string(ctx, objIdx, arg.first.data()); + } + duk_pcall(ctx, 1); + duk_pop(ctx); + } +} + HookList& HookEngine::GetHookList(HOOK_TYPE type) { auto index = static_cast(type); diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 4753d3ce64..9d476a10b0 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -12,8 +12,10 @@ #include "../common.h" #include "Duktape.hpp" +#include #include #include +#include #include namespace OpenRCT2::Scripting @@ -25,6 +27,7 @@ namespace OpenRCT2::Scripting { INTERVAL_TICK, INTERVAL_DAY, + NETWORK_CHAT, COUNT, UNDEFINED = -1, }; @@ -77,6 +80,7 @@ namespace OpenRCT2::Scripting void Unsubscribe(HOOK_TYPE type, uint32_t cookie); void UnsubscribeAll(std::shared_ptr owner); void Call(HOOK_TYPE type); + void Call(HOOK_TYPE type, const std::initializer_list>& args); private: HookList& GetHookList(HOOK_TYPE type); From 4109b2c55a1b3f122b74516e15add1dad3837782 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 1 Feb 2020 16:43:00 +0000 Subject: [PATCH 041/159] Fix build errors --- src/openrct2-ui/scripting/CustomWindow.cpp | 6 +++--- src/openrct2-ui/scripting/ScWindow.hpp | 4 ++-- src/openrct2/core/FileWatcher.cpp | 4 +--- src/openrct2/scripting/ScMap.hpp | 2 +- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 72d0ad25f3..2788c3f2a8 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -237,7 +237,7 @@ namespace OpenRCT2::Ui::Windows if (desc.X && desc.Y) { window = window_create( - desc.X.value(), desc.Y.value(), desc.Width, desc.Height, &window_custom_events, WC_CUSTOM, windowFlags); + { desc.X.value(), desc.Y.value() }, desc.Width, desc.Height, &window_custom_events, WC_CUSTOM, windowFlags); } else { @@ -298,12 +298,12 @@ namespace OpenRCT2::Ui::Windows { if (w->width < w->min_width) { - window_invalidate(w); + w->Invalidate(); w->width = w->min_width; } if (w->height < w->min_height) { - window_invalidate(w); + w->Invalidate(); w->height = w->min_height; } } diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 413b260894..44ac133ed7 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -41,7 +41,7 @@ namespace OpenRCT2::Scripting void x_set(int32_t value) { auto w = GetWindow(); - window_set_position(w, value, w->y); + window_set_position(w, { value, w->y }); } int32_t y_get() { @@ -50,7 +50,7 @@ namespace OpenRCT2::Scripting void y_set(int32_t value) { auto w = GetWindow(); - window_set_position(w, w->x, value); + window_set_position(w, { w->x, value }); } int32_t width_get() { diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index 6725870cf8..f48db28b27 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -8,7 +8,6 @@ *****************************************************************************/ #include -#include #include #ifdef _WIN32 @@ -22,10 +21,9 @@ #endif #include "../core/String.hpp" +#include "FileSystem.hpp" #include "FileWatcher.h" -namespace fs = std::experimental::filesystem; - #ifndef _WIN32 FileWatcher::FileDescriptor::~FileDescriptor() { diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 410b894610..5ffea1e1e4 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -52,7 +52,7 @@ namespace OpenRCT2::Scripting std::shared_ptr getTile(int32_t x, int32_t y) { - auto firstElement = map_get_first_element_at(x, y); + auto firstElement = map_get_first_element_at({ x, y }); return std::make_shared(firstElement); } From f29e4f326395ed2d76c5fd293898669416d5c2d1 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 6 Feb 2020 13:23:04 +0000 Subject: [PATCH 042/159] Add storage APIs --- distribution/openrct2.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 1edbf4d395..09ebc941e8 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -38,6 +38,16 @@ export interface Context { */ configuration: Configuration; + /** + * Shared generic storage for all plugins. + */ + sharedStorage: Configuration; + + /** + * Local generic storage for a each plugin. + */ + localStorage: Configuration; + /** * Registers a new intent (command) that can be mapped to a shortcut. */ From f9d7237e92d719ec81485a479398573918565f33 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 6 Feb 2020 13:26:40 +0000 Subject: [PATCH 043/159] Split peep stuff out of Thing --- distribution/openrct2.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 09ebc941e8..4f962147a5 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -180,12 +180,15 @@ export type ThingType = "car" | "duck" | "peep"; export interface Thing { - type: ThingType; + readonly type: ThingType; x: number; y: number; z: number; - // Peep + asPeep(): Thing | null; +} + +export interface Peep extends Thing { tshirt: number; trousers: number; } From 2e62078c30bafe24483243d5024a1231ece50bb4 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 6 Feb 2020 21:55:53 +0000 Subject: [PATCH 044/159] Exclude node_modules directory --- src/openrct2/scripting/ScriptEngine.cpp | 27 ++++++++++++++++--------- src/openrct2/scripting/ScriptEngine.h | 1 + 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index eaa1b41cf2..253338beef 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -86,16 +86,19 @@ void ScriptEngine::LoadPlugins() while (scanner->Next()) { auto path = std::string(scanner->GetPath()); - try + if (ShouldLoadScript(path)) { - auto plugin = std::make_shared(_context, path); - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); - plugin->Load(); - _plugins.push_back(std::move(plugin)); - } - catch (const std::exception& e) - { - _console.WriteLineError(e.what()); + try + { + auto plugin = std::make_shared(_context, path); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + plugin->Load(); + _plugins.push_back(std::move(plugin)); + } + catch (const std::exception& e) + { + _console.WriteLineError(e.what()); + } } } @@ -114,6 +117,12 @@ void ScriptEngine::LoadPlugins() } } +bool ScriptEngine::ShouldLoadScript(const std::string& path) +{ + // A lot of JavaScript is often found in a node_modules directory tree and is most likely unwanted, so ignore it + return path.find("/node_modules/") == std::string::npos && path.find("\\node_modules\\") == std::string::npos; +} + void ScriptEngine::AutoReloadPlugins() { if (_changedPluginFiles.size() > 0) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 551ba200bc..90898ea19a 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -127,6 +127,7 @@ namespace OpenRCT2::Scripting void Initialise(); void LoadPlugins(); void StartPlugins(); + bool ShouldLoadScript(const std::string& path); void AutoReloadPlugins(); }; } // namespace OpenRCT2::Scripting From e6915e8799cde9f3cd2724b9055b85bfaca19929 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 6 Feb 2020 23:15:20 +0000 Subject: [PATCH 045/159] Do not load plugins on title screen --- distribution/openrct2.d.ts | 11 +++ src/openrct2/Game.cpp | 11 +++ src/openrct2/scripting/HookEngine.cpp | 9 ++ src/openrct2/scripting/HookEngine.h | 1 + src/openrct2/scripting/Plugin.cpp | 38 +++++++- src/openrct2/scripting/Plugin.h | 38 +++++++- src/openrct2/scripting/ScriptEngine.cpp | 110 ++++++++++++++++++++---- src/openrct2/scripting/ScriptEngine.h | 11 ++- 8 files changed, 205 insertions(+), 24 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 4f962147a5..698fde90ec 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -15,6 +15,17 @@ // /// // +export type PluginType = "server" | "client" | "server_client"; + +export interface PluginMetadata { + name: string; + version: string; + authors: string | string[]; + type: PluginType; + minApiVersion: number; + main: () => void; +} + export interface Console { clear(): void; log(message?: any, ...optionalParams: any[]): void; diff --git a/src/openrct2/Game.cpp b/src/openrct2/Game.cpp index c323435ec7..d19a9937db 100644 --- a/src/openrct2/Game.cpp +++ b/src/openrct2/Game.cpp @@ -46,6 +46,7 @@ #include "ride/TrackDesign.h" #include "ride/Vehicle.h" #include "scenario/Scenario.h" +#include "scripting/ScriptEngine.h" #include "title/TitleScreen.h" #include "ui/UiContext.h" #include "ui/WindowManager.h" @@ -587,6 +588,13 @@ void game_load_init() audio_stop_title_music(); gGameSpeed = 1; + + GetContext()->GetScriptEngine().LoadPlugins(); +} + +void game_finish() +{ + GetContext()->GetScriptEngine().UnloadPlugins(); } /** @@ -801,6 +809,7 @@ static void game_load_or_quit_no_save_prompt_callback(int32_t result, const utf8 { if (result == MODAL_RESULT_OK) { + game_finish(); window_close_by_class(WC_EDITOR_OBJECT_SELECTION); context_load_park_from_file(path); } @@ -843,10 +852,12 @@ void game_load_or_quit_no_save_prompt() } gGameSpeed = 1; gFirstTimeSaving = true; + game_finish(); title_load(); break; } default: + game_finish(); openrct2_finish(); break; } diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index ae93d31f78..d87c7d4669 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -78,6 +78,15 @@ void HookEngine::UnsubscribeAll(std::shared_ptr owner) } } +void HookEngine::UnsubscribeAll() +{ + for (auto& hookList : _hookMap) + { + auto& hooks = hookList.Hooks; + hooks.clear(); + } +} + void HookEngine::Call(HOOK_TYPE type) { auto& hookList = GetHookList(type); diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 9d476a10b0..7c417e64c5 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -79,6 +79,7 @@ namespace OpenRCT2::Scripting uint32_t Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue& function); void Unsubscribe(HOOK_TYPE type, uint32_t cookie); void UnsubscribeAll(std::shared_ptr owner); + void UnsubscribeAll(); void Call(HOOK_TYPE type); void Call(HOOK_TYPE type, const std::initializer_list>& args); diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index cdac2f3877..7c74139646 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -74,19 +74,40 @@ void Plugin::Start() throw std::runtime_error("[" + _metadata.Name + "] " + val); } duk_pop(_context); + + _hasStarted = true; +} + +void Plugin::Stop() +{ + _hasStarted = false; } void Plugin::Update() { } +static std::string TryGetString(const DukValue& value, const std::string& message) +{ + if (value.type() != DukValue::Type::STRING) + throw std::runtime_error(message); + return value.as_string(); +} + PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) { PluginMetadata metadata; if (dukMetadata.type() == DukValue::Type::OBJECT) { - metadata.Name = dukMetadata["name"].as_string(); - metadata.Version = dukMetadata["version"].as_string(); + metadata.Name = TryGetString(dukMetadata["name"], "Plugin name not specified."); + metadata.Version = TryGetString(dukMetadata["version"], "Plugin version not specified."); + metadata.Type = ParsePluginType(TryGetString(dukMetadata["type"], "Plugin type not specified.")); + + auto dukMinApiVersion = dukMetadata["minApiVersion"]; + if (dukMinApiVersion.type() == DukValue::Type::NUMBER) + { + metadata.MinApiVersion = dukMinApiVersion.as_int(); + } auto dukAuthors = dukMetadata["authors"]; dukAuthors.push(); @@ -97,7 +118,7 @@ PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) return v.as_string(); }); } - else + else if (dukAuthors.type() == DukValue::Type::STRING) { metadata.Authors = { dukAuthors.as_string() }; } @@ -105,3 +126,14 @@ PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) } return metadata; } + +PluginType Plugin::ParsePluginType(const std::string_view& type) +{ + if (type == "server") + return PluginType::Server; + if (type == "client") + return PluginType::Server; + if (type == "server_client") + return PluginType::Server; + throw std::invalid_argument("Unknown plugin type."); +} diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 4ae6b8a8d3..b005cba4b3 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -13,24 +13,48 @@ #include #include +#include #include namespace OpenRCT2::Scripting { + enum class PluginType + { + /** + * Scripts that can run on any client with no impact on the game state. + */ + Client, + + /** + * Scripts that can run on servers with no impact on the game state and will not + * be uploaded to clients. + */ + Server, + + /** + * Scripts that can run on servers and will be uploaded to clients with ability to + * modify game state in certain contexts. + */ + ServerClient, + }; + struct PluginMetadata { std::string Name; std::string Version; std::vector Authors; + PluginType Type; + int32_t MinApiVersion{}; DukValue Main; }; class Plugin { private: - duk_context* _context; + duk_context* _context{}; std::string _path; PluginMetadata _metadata; + bool _hasStarted{}; public: std::string GetPath() const @@ -38,6 +62,16 @@ namespace OpenRCT2::Scripting return _path; }; + const PluginMetadata& GetMetadata() const + { + return _metadata; + } + + bool HasStarted() const + { + return _hasStarted; + } + Plugin() { } @@ -47,9 +81,11 @@ namespace OpenRCT2::Scripting void Load(); void Start(); + void Stop(); void Update(); private: static PluginMetadata GetMetadata(const DukValue& dukMetadata); + static PluginType ParsePluginType(const std::string_view& type); }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 253338beef..8632d94028 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -32,6 +32,8 @@ using namespace OpenRCT2::Scripting; static std::string Stringify(duk_context* ctx, duk_idx_t idx); +static constexpr int32_t OPENRCT2_PLUGIN_API_VERSION = 1; + DukContext::DukContext() { _context = duk_create_heap_default(); @@ -74,8 +76,9 @@ void ScriptEngine::Initialise() dukglue_register_global(ctx, std::make_shared(ctx), "network"); dukglue_register_global(ctx, std::make_shared(), "park"); - LoadPlugins(); - StartPlugins(); + _initialised = true; + _pluginsLoaded = false; + _pluginsStarted = false; } void ScriptEngine::LoadPlugins() @@ -93,7 +96,17 @@ void ScriptEngine::LoadPlugins() auto plugin = std::make_shared(_context, path); ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); - _plugins.push_back(std::move(plugin)); + + auto metadata = plugin->GetMetadata(); + if (metadata.MinApiVersion <= OPENRCT2_PLUGIN_API_VERSION) + { + LogPluginInfo(plugin, "Loaded"); + _plugins.push_back(std::move(plugin)); + } + else + { + LogPluginInfo(plugin, "Requires newer API version: v" + std::to_string(metadata.MinApiVersion)); + } } catch (const std::exception& e) { @@ -115,6 +128,8 @@ void ScriptEngine::LoadPlugins() { std::printf("Unable to enable hot reloading of plugins: %s\n", e.what()); } + + _pluginsLoaded = true; } bool ScriptEngine::ShouldLoadScript(const std::string& path) @@ -142,6 +157,7 @@ void ScriptEngine::AutoReloadPlugins() ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); + LogPluginInfo(plugin, "Reloaded"); plugin->Start(); } catch (const std::exception& e) @@ -154,20 +170,57 @@ void ScriptEngine::AutoReloadPlugins() } } +void ScriptEngine::UnloadPlugins() +{ + StopPlugins(); + for (auto& plugin : _plugins) + { + LogPluginInfo(plugin, "Unloaded"); + } + _plugins.clear(); + _pluginsLoaded = false; + _pluginsStarted = false; +} + void ScriptEngine::StartPlugins() { for (auto& plugin : _plugins) { - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); - try + if (!plugin->HasStarted()) { - plugin->Start(); - } - catch (const std::exception& e) - { - _console.WriteLineError(e.what()); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + try + { + plugin->Start(); + } + catch (const std::exception& e) + { + _console.WriteLineError(e.what()); + } } } + _pluginsStarted = true; +} + +void ScriptEngine::StopPlugins() +{ + _hookEngine.UnsubscribeAll(); + for (auto& plugin : _plugins) + { + if (plugin->HasStarted()) + { + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + try + { + plugin->Stop(); + } + catch (const std::exception& e) + { + _console.WriteLineError(e.what()); + } + } + } + _pluginsStarted = false; } void ScriptEngine::Update() @@ -175,8 +228,30 @@ void ScriptEngine::Update() if (!_initialised) { Initialise(); - _initialised = true; } + + if (_pluginsLoaded) + { + if (!_pluginsStarted) + { + StartPlugins(); + } + else + { + auto tick = Platform::GetTicks(); + if (tick - _lastHotReloadCheckTick > 1000) + { + AutoReloadPlugins(); + _lastHotReloadCheckTick = tick; + } + } + } + + ProcessREPL(); +} + +void ScriptEngine::ProcessREPL() +{ while (_evalQueue.size() > 0) { auto item = std::move(_evalQueue.front()); @@ -197,13 +272,6 @@ void ScriptEngine::Update() // Signal the promise so caller can continue promise.set_value(); } - - auto tick = Platform::GetTicks(); - if (tick - _lastHotReloadCheckTick > 1000) - { - AutoReloadPlugins(); - _lastHotReloadCheckTick = tick; - } } std::future ScriptEngine::Eval(const std::string& s) @@ -214,6 +282,12 @@ std::future ScriptEngine::Eval(const std::string& s) return future; } +void ScriptEngine::LogPluginInfo(const std::shared_ptr& plugin, const std::string_view& message) +{ + const auto& pluginName = plugin->GetMetadata().Name; + _console.WriteLine("[" + pluginName + "] " + std::string(message)); +} + static std::string Stringify(duk_context* ctx, duk_idx_t idx) { auto type = duk_get_type(ctx, idx); diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 90898ea19a..398e63bf78 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -74,7 +74,7 @@ namespace OpenRCT2::Scripting public: DukContext(); DukContext(DukContext&) = delete; - DukContext(DukContext&& src) + DukContext(DukContext&& src) noexcept : _context(std::move(src._context)) { } @@ -93,6 +93,8 @@ namespace OpenRCT2::Scripting IPlatformEnvironment& _env; DukContext _context; bool _initialised{}; + bool _pluginsLoaded{}; + bool _pluginsStarted{}; std::queue, std::string>> _evalQueue; std::vector> _plugins; uint32_t _lastHotReloadCheckTick{}; @@ -120,14 +122,19 @@ namespace OpenRCT2::Scripting return _execInfo; } + void LoadPlugins(); + void UnloadPlugins(); void Update(); std::future Eval(const std::string& s); + void LogPluginInfo(const std::shared_ptr& plugin, const std::string_view& message); + private: void Initialise(); - void LoadPlugins(); void StartPlugins(); + void StopPlugins(); bool ShouldLoadScript(const std::string& path); void AutoReloadPlugins(); + void ProcessREPL(); }; } // namespace OpenRCT2::Scripting From 0a81cabd6d327aa86047c6cccaf8bae9027f5263 Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 10 Feb 2020 13:12:20 +0000 Subject: [PATCH 046/159] Add more APIs to the plugin schema --- distribution/openrct2.d.ts | 86 +++++++++++++++++++++++++++++++------- 1 file changed, 70 insertions(+), 16 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 698fde90ec..06d2706c9e 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -41,7 +41,7 @@ export interface Configuration { export type HookType = "interval.tick" | "interval.day" | - "network.chat"; + "network.chat" | "network.action" | "network.join" | "network.leave"; export interface Context { /** @@ -62,7 +62,7 @@ export interface Context { /** * Registers a new intent (command) that can be mapped to a shortcut. */ - registerIntent(desc: IntentDesc); + registerIntent(desc: IntentDesc): void; /** * Subscribes to the given hook. @@ -83,7 +83,7 @@ export interface IDisposable { } export type TileElementType = - "surface" | "footpath"; + "surface" | "footpath" | "track" | "small_scenery" | "entrance" | "large_scenery" | "banner"; export interface TileElement { type: TileElementType; @@ -232,21 +232,17 @@ export interface Park { postMessage(message: ParkMessage): void; } -export interface Window { - id: number; - classification: string; - x: number; - y: number; - width: number; - height: number; - title: string; - isSticky: boolean; - - close(): void; -} +/** + * User Interface APIs + * These will only be available to servers and clients that are not running headless mode. + * Plugin writers should check if ui is available using `typeof ui !== 'undefined'`. + */ +/** + * Represents the type of a widget, e.g. button or label. + */ export type WidgetType = - "button" | "dropdown"; + "button" | "dropdown" | "label" | "tabview" | "viewport"; export interface Widget { type: WidgetType; @@ -267,6 +263,49 @@ export interface DropdownWidget extends Widget { onChanged: (index: number) => void; } +export interface LabelWidget extends Widget { + text: string; +} + +export interface Coord3 { + x: number; + y: number; + z: number; +} + +export interface ViewportWidget extends Widget { + target: null | number | Coord3; + zoom: number; +} + +export interface Tab { + image: number; + tooltip: string; + widgets: Widget[]; +} + +export interface Window { + id: number; + classification: string; + x: number; + y: number; + width: number; + height: number; + isSticky: boolean; + colours: number[]; + title: string; + widgets: Widget[]; + + close(): void; +} + +export interface TabbedWindow extends Window { + tabs: Tab[]; + activeTabIndex: number; + + onTabChanged: (index: number) => void; +} + export interface WindowDesc { classification: string; x?: number; @@ -278,6 +317,7 @@ export interface WindowDesc { minWidth?: number; minHeight?: number; widgets?: Widget[]; + tabs?: Tab[]; } export interface Ui { @@ -292,6 +332,14 @@ export interface Ui { closeAllWindows(): void; } +/** + * Network APIs + * Use `network.status` to determine whether the current game is a client, server or in single player mode. + */ + + /** + * Represents a player within a network game. + */ export interface Player { readonly id: number; readonly name: string; @@ -341,7 +389,10 @@ export interface ServerInfo { readonly providerWebsite: string; } +export type NetworkStatus = "none" | "server" | "client"; + export interface Network { + readonly status: NetworkStatus; readonly groups: number; readonly players: number; defaultGroup: number; @@ -354,6 +405,9 @@ export interface Network { sendMessage(players: number[], message: string): void; } +/** + * Global context for accessing all other APIs. + */ declare global { var console: Console; var context: Context; From 3f58a0d9f821f115f59221cfbb52a49464f27243 Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 10 Feb 2020 17:31:58 +0000 Subject: [PATCH 047/159] Implement network mode --- distribution/openrct2.d.ts | 4 ++-- src/openrct2/scripting/ScNetwork.hpp | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 06d2706c9e..66fa8ecf12 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -389,10 +389,10 @@ export interface ServerInfo { readonly providerWebsite: string; } -export type NetworkStatus = "none" | "server" | "client"; +export type NetworkMode = "none" | "server" | "client"; export interface Network { - readonly status: NetworkStatus; + readonly mode: NetworkMode; readonly groups: number; readonly players: number; defaultGroup: number; diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index ea74774ebd..1dd41c465e 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -218,6 +218,19 @@ namespace OpenRCT2::Scripting { } + std::string mode_get() + { + switch (network_get_mode()) + { + default: + case NETWORK_MODE_NONE: + return "none"; + case NETWORK_MODE_SERVER: + return "server"; + case NETWORK_MODE_CLIENT: + return "client"; + } + } int32_t players_get() { return network_get_num_players(); @@ -260,6 +273,7 @@ namespace OpenRCT2::Scripting static void Register(duk_context* ctx) { + dukglue_register_property(ctx, &ScNetwork::mode_get, nullptr, "mode"); dukglue_register_property(ctx, &ScNetwork::groups_get, nullptr, "groups"); dukglue_register_property(ctx, &ScNetwork::players_get, nullptr, "players"); dukglue_register_property(ctx, &ScNetwork::defaultGroup_get, &ScNetwork::defaultGroup_set, "defaultGroup"); From 3ac22476c6cc33e0c9daa17f79d0598c8e71ef8d Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 10 Feb 2020 18:04:34 +0000 Subject: [PATCH 048/159] Implement basic send message --- distribution/openrct2.d.ts | 3 ++- src/openrct2/scripting/ScNetwork.hpp | 28 +++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 66fa8ecf12..57de82f7e0 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -401,8 +401,9 @@ export interface Network { getGroup(index: number): PlayerGroup; setGroups(groups: PlayerGroup[]): void; getPlayer(index: number): Player; + kickPlayer(index: number): Player; sendMessage(message: string): void; - sendMessage(players: number[], message: string): void; + sendMessage(message: string, players: number[]): void; } /** diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index 1dd41c465e..0d52b9efa4 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -10,6 +10,7 @@ #pragma once #include "../actions/NetworkModifyGroupAction.hpp" +#include "../actions/PlayerKickAction.hpp" #include "../actions/PlayerSetGroupAction.hpp" #include "../network/NetworkAction.h" #include "../network/network.h" @@ -271,14 +272,39 @@ namespace OpenRCT2::Scripting return nullptr; } + void kickPlayer(int32_t index) + { + auto numPlayers = network_get_num_players(); + if (index < numPlayers) + { + auto playerId = network_get_player_id(index); + auto kickPlayerAction = PlayerKickAction(playerId); + GameActions::Execute(&kickPlayerAction); + } + } + + void sendMessage(std::string message, DukValue players) + { + if (players.is_array()) + { + duk_error(players.context(), DUK_ERR_ERROR, "Not yet supported"); + } + else + { + network_send_chat(message.c_str()); + } + } + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScNetwork::mode_get, nullptr, "mode"); dukglue_register_property(ctx, &ScNetwork::groups_get, nullptr, "groups"); dukglue_register_property(ctx, &ScNetwork::players_get, nullptr, "players"); dukglue_register_property(ctx, &ScNetwork::defaultGroup_get, &ScNetwork::defaultGroup_set, "defaultGroup"); - dukglue_register_method(ctx, &ScNetwork::getPlayer, "getPlayer"); dukglue_register_method(ctx, &ScNetwork::getGroup, "getGroup"); + dukglue_register_method(ctx, &ScNetwork::getPlayer, "getPlayer"); + dukglue_register_method(ctx, &ScNetwork::kickPlayer, "kickPlayer"); + dukglue_register_method(ctx, &ScNetwork::sendMessage, "sendMessage"); } }; } // namespace OpenRCT2::Scripting From 0e8c62732468a2b66c0dc62cdbffb85f57a5742b Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 10 Feb 2020 18:44:42 +0000 Subject: [PATCH 049/159] Add config option for hot reload and refactor --- src/openrct2/config/Config.cpp | 20 +++++ src/openrct2/config/Config.h | 6 ++ src/openrct2/scripting/ScriptEngine.cpp | 97 +++++++++++++++---------- src/openrct2/scripting/ScriptEngine.h | 5 +- 4 files changed, 89 insertions(+), 39 deletions(-) diff --git a/src/openrct2/config/Config.cpp b/src/openrct2/config/Config.cpp index 098d8fb292..e0a5e2df45 100644 --- a/src/openrct2/config/Config.cpp +++ b/src/openrct2/config/Config.cpp @@ -549,6 +549,22 @@ namespace Config writer->WriteInt32("hinting_threshold", model->hinting_threshold); } + static void ReadPlugin(IIniReader* reader) + { + if (reader->ReadSection("plugin")) + { + auto model = &gConfigPlugin; + model->enable_hot_reloading = reader->GetBoolean("enable_hot_reloading", false); + } + } + + static void WritePlugin(IIniWriter* writer) + { + auto model = &gConfigPlugin; + writer->WriteSection("plugin"); + writer->WriteBoolean("enable_hot_reloading", model->enable_hot_reloading); + } + static bool SetDefaults() { try @@ -561,6 +577,7 @@ namespace Config ReadNotifications(reader.get()); ReadTwitch(reader.get()); ReadFont(reader.get()); + ReadPlugin(reader.get()); return true; } catch (const std::exception&) @@ -582,6 +599,7 @@ namespace Config ReadNotifications(reader.get()); ReadTwitch(reader.get()); ReadFont(reader.get()); + ReadPlugin(reader.get()); return true; } catch (const std::exception&) @@ -606,6 +624,7 @@ namespace Config WriteNotifications(writer.get()); WriteTwitch(writer.get()); WriteFont(writer.get()); + WritePlugin(writer.get()); return true; } catch (const std::exception& ex) @@ -721,6 +740,7 @@ TwitchConfiguration gConfigTwitch; NetworkConfiguration gConfigNetwork; NotificationConfiguration gConfigNotifications; FontConfiguration gConfigFonts; +PluginConfiguration gConfigPlugin; void config_set_defaults() { diff --git a/src/openrct2/config/Config.h b/src/openrct2/config/Config.h index a001e44623..feb1c3a1ae 100644 --- a/src/openrct2/config/Config.h +++ b/src/openrct2/config/Config.h @@ -203,6 +203,11 @@ struct FontConfiguration int32_t hinting_threshold; }; +struct PluginConfiguration +{ + bool enable_hot_reloading; +}; + enum SORT { SORT_NAME_ASCENDING, @@ -238,6 +243,7 @@ extern TwitchConfiguration gConfigTwitch; extern NetworkConfiguration gConfigNetwork; extern NotificationConfiguration gConfigNotifications; extern FontConfiguration gConfigFonts; +extern PluginConfiguration gConfigPlugin; bool config_open(const utf8* path); bool config_save(const utf8* path); diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 8632d94028..9a318c9098 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -10,6 +10,7 @@ #include "ScriptEngine.h" #include "../PlatformEnvironment.h" +#include "../config/Config.h" #include "../core/FileScanner.h" #include "../core/Path.hpp" #include "../interface/InteractiveConsole.h" @@ -83,53 +84,56 @@ void ScriptEngine::Initialise() void ScriptEngine::LoadPlugins() { - auto base = _env.GetDirectoryPath(DIRBASE::USER, DIRID::PLUGIN); - auto pattern = Path::Combine(base, "*.js"); - auto scanner = std::unique_ptr(Path::ScanDirectory(pattern, true)); - while (scanner->Next()) + if (!_initialised) { - auto path = std::string(scanner->GetPath()); - if (ShouldLoadScript(path)) - { - try - { - auto plugin = std::make_shared(_context, path); - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); - plugin->Load(); - - auto metadata = plugin->GetMetadata(); - if (metadata.MinApiVersion <= OPENRCT2_PLUGIN_API_VERSION) - { - LogPluginInfo(plugin, "Loaded"); - _plugins.push_back(std::move(plugin)); - } - else - { - LogPluginInfo(plugin, "Requires newer API version: v" + std::to_string(metadata.MinApiVersion)); - } - } - catch (const std::exception& e) - { - _console.WriteLineError(e.what()); - } - } + Initialise(); } + auto base = _env.GetDirectoryPath(DIRBASE::USER, DIRID::PLUGIN); + if (Path::DirectoryExists(base)) + { + auto pattern = Path::Combine(base, "*.js"); + auto scanner = std::unique_ptr(Path::ScanDirectory(pattern, true)); + while (scanner->Next()) + { + auto path = std::string(scanner->GetPath()); + if (ShouldLoadScript(path)) + { + LoadPlugin(path); + } + } + + if (gConfigPlugin.enable_hot_reloading) + { + SetupHotReloading(); + } + } + _pluginsLoaded = true; +} + +void ScriptEngine::LoadPlugin(const std::string& path) +{ try { - // Enable hot reloading - _pluginFileWatcher = std::make_unique(base); - _pluginFileWatcher->OnFileChanged = [this](const std::string& path) { - std::lock_guard guard(_changedPluginFilesMutex); - _changedPluginFiles.push_back(path); - }; + auto plugin = std::make_shared(_context, path); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + plugin->Load(); + + auto metadata = plugin->GetMetadata(); + if (metadata.MinApiVersion <= OPENRCT2_PLUGIN_API_VERSION) + { + LogPluginInfo(plugin, "Loaded"); + _plugins.push_back(std::move(plugin)); + } + else + { + LogPluginInfo(plugin, "Requires newer API version: v" + std::to_string(metadata.MinApiVersion)); + } } catch (const std::exception& e) { - std::printf("Unable to enable hot reloading of plugins: %s\n", e.what()); + _console.WriteLineError(e.what()); } - - _pluginsLoaded = true; } bool ScriptEngine::ShouldLoadScript(const std::string& path) @@ -138,6 +142,23 @@ bool ScriptEngine::ShouldLoadScript(const std::string& path) return path.find("/node_modules/") == std::string::npos && path.find("\\node_modules\\") == std::string::npos; } +void ScriptEngine::SetupHotReloading() +{ + try + { + auto base = _env.GetDirectoryPath(DIRBASE::USER, DIRID::PLUGIN); + _pluginFileWatcher = std::make_unique(base); + _pluginFileWatcher->OnFileChanged = [this](const std::string& path) { + std::lock_guard guard(_changedPluginFilesMutex); + _changedPluginFiles.emplace(path); + }; + } + catch (const std::exception& e) + { + std::printf("Unable to enable hot reloading of plugins: %s\n", e.what()); + } +} + void ScriptEngine::AutoReloadPlugins() { if (_changedPluginFiles.size() > 0) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 398e63bf78..70556f436a 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -19,6 +19,7 @@ #include #include #include +#include #include struct duk_hthread; @@ -102,7 +103,7 @@ namespace OpenRCT2::Scripting ScriptExecutionInfo _execInfo; std::unique_ptr _pluginFileWatcher; - std::vector _changedPluginFiles; + std::unordered_set _changedPluginFiles; std::mutex _changedPluginFilesMutex; public: @@ -133,7 +134,9 @@ namespace OpenRCT2::Scripting void Initialise(); void StartPlugins(); void StopPlugins(); + void LoadPlugin(const std::string& path); bool ShouldLoadScript(const std::string& path); + void SetupHotReloading(); void AutoReloadPlugins(); void ProcessREPL(); }; From c8fbc2e529b0fe34421a4144f74fab3037c02bbf Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 10 Feb 2020 23:33:00 +0000 Subject: [PATCH 050/159] Improve chat subscription --- distribution/openrct2.d.ts | 8 ++++- src/openrct2/network/Network.cpp | 50 +++++++++++++++++++++------ src/openrct2/scripting/HookEngine.cpp | 29 ++++++++++++++++ src/openrct2/scripting/HookEngine.h | 5 ++- 4 files changed, 80 insertions(+), 12 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 57de82f7e0..9f0d27e701 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -43,6 +43,11 @@ export type HookType = "interval.tick" | "interval.day" | "network.chat" | "network.action" | "network.join" | "network.leave"; +export interface NetworkChatEventArgs { + player: number; + message: string; +} + export interface Context { /** * The user's current configuration. @@ -68,6 +73,7 @@ export interface Context { * Subscribes to the given hook. */ subscribe(hook: HookType, callback: Function): IDisposable; + subscribe(hook: "network.chat", callback: (e: NetworkChatEventArgs) => void): IDisposable; } export interface IntentDesc @@ -401,7 +407,7 @@ export interface Network { getGroup(index: number): PlayerGroup; setGroups(groups: PlayerGroup[]): void; getPlayer(index: number): Player; - kickPlayer(index: number): Player; + kickPlayer(index: number): void; sendMessage(message: string): void; sendMessage(message: string, players: number[]): void; } diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index e0fc690a72..1a5724e5cd 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -2822,6 +2822,10 @@ void Network::Client_Handle_CHAT([[maybe_unused]] NetworkConnection& connection, void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& packet) { + auto szText = packet.ReadString(); + if (szText == nullptr || szText[0] == '\0') + return; + if (connection.Player) { NetworkGroup* group = GetGroupByID(connection.Player->Group); @@ -2830,19 +2834,44 @@ void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& p return; } } - const char* text = packet.ReadString(); - if (text) + + std::string text = szText; + if (connection.Player != nullptr) { auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); - hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, { - { "player", (int32_t)connection.Player->Id }, - { "message", std::string(text) } - }); + if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT)) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); - const char* formatted = FormatChat(connection.Player, text); - chat_history_add(formatted); - Server_Send_CHAT(formatted); + // Create event args object + auto objIdx = duk_push_object(ctx); + duk_push_number(ctx, (int32_t)connection.Player->Id); + duk_put_prop_string(ctx, objIdx, "player"); + duk_push_string(ctx, text.c_str()); + duk_put_prop_string(ctx, objIdx, "message"); + auto e = DukValue::take_from_stack(ctx); + + // Call the subscriptions + hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, e); + + // Update text from object if subscriptions changed it + if (e["message"].type() != DukValue::Type::STRING) + { + // Subscription set text to non-string, do not relay message + return; + } + text = e["message"].as_string(); + if (text.empty()) + { + // Subscription set text to empty string, do not relay message + return; + } + } } + + const char* formatted = FormatChat(connection.Player, text.c_str()); + chat_history_add(formatted); + Server_Send_CHAT(formatted); } void Network::Client_Handle_GAME_ACTION([[maybe_unused]] NetworkConnection& connection, NetworkPacket& packet) @@ -3582,7 +3611,8 @@ GameActionResult::Ptr network_kick_player(NetworkPlayerId_t playerId, bool isExe NetworkPlayer* player = gNetwork.GetPlayerByID(playerId); if (player == nullptr) { - // Player might be already removed by the PLAYERLIST command, need to refactor non-game commands executing too early. + // Player might be already removed by the PLAYERLIST command, need to refactor non-game commands executing too + // early. return std::make_unique(GA_ERROR::UNKNOWN, STR_NONE); } diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index d87c7d4669..695586b9cb 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -87,6 +87,12 @@ void HookEngine::UnsubscribeAll() } } +bool HookEngine::HasSubscriptions(HOOK_TYPE type) const +{ + auto& hookList = GetHookList(type); + return !hookList.Hooks.empty(); +} + void HookEngine::Call(HOOK_TYPE type) { auto& hookList = GetHookList(type); @@ -101,6 +107,23 @@ void HookEngine::Call(HOOK_TYPE type) } } +void HookEngine::Call(HOOK_TYPE type, DukValue args) +{ + auto& hookList = GetHookList(type); + for (auto& hook : hookList.Hooks) + { + ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner); + + const auto& function = hook.Function; + auto ctx = function.context(); + function.push(); + + args.push(); + duk_pcall(ctx, 1); + duk_pop(ctx); + } +} + void HookEngine::Call(HOOK_TYPE type, const std::initializer_list>& args) { auto& hookList = GetHookList(type); @@ -141,3 +164,9 @@ HookList& HookEngine::GetHookList(HOOK_TYPE type) auto index = static_cast(type); return _hookMap[index]; } + +const HookList& HookEngine::GetHookList(HOOK_TYPE type) const +{ + auto index = static_cast(type); + return _hookMap[index]; +} diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 7c417e64c5..e2dde251b8 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -51,7 +51,7 @@ namespace OpenRCT2::Scripting struct HookList { - HOOK_TYPE Type; + HOOK_TYPE Type{}; std::vector Hooks; HookList() @@ -80,10 +80,13 @@ namespace OpenRCT2::Scripting void Unsubscribe(HOOK_TYPE type, uint32_t cookie); void UnsubscribeAll(std::shared_ptr owner); void UnsubscribeAll(); + bool HasSubscriptions(HOOK_TYPE type) const; void Call(HOOK_TYPE type); + void Call(HOOK_TYPE type, DukValue args); void Call(HOOK_TYPE type, const std::initializer_list>& args); private: HookList& GetHookList(HOOK_TYPE type); + const HookList& GetHookList(HOOK_TYPE type) const; }; } // namespace OpenRCT2::Scripting From a915cb0998d60a91b9e45460a0ee87f3e9abacfe Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 11 Feb 2020 13:31:33 +0000 Subject: [PATCH 051/159] Add more APIs relevant to game actions --- distribution/openrct2.d.ts | 163 ++++++++++++++++++++++++++++++------- 1 file changed, 134 insertions(+), 29 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 9f0d27e701..a1e36d3067 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -39,12 +39,62 @@ export interface Configuration { has(key: string): boolean; } +export interface Coord2 { + x: number; + y: number; +} + +export interface Coord3 { + x: number; + y: number; + z: number; +} + export type HookType = "interval.tick" | "interval.day" | "network.chat" | "network.action" | "network.join" | "network.leave"; -export interface NetworkChatEventArgs { - player: number; +export type ExpenditureType = + "ride_construction" | + "ride_runningcosts" | + "land_purchase" | + "landscaping" | + "park_entrance_tickets" | + "park_ride_tickets" | + "shop_sales" | + "shop_stock" | + "food_drink_sales" | + "food_drink_stock" | + "wages" | + "marketing" | + "research" | + "interest"; + +export interface GameActionResult { + error: string; + errorTitle: string; + errorMessage: string; + position: Coord3; + cost: number; + expenditureType: ExpenditureType; +} + +export interface GameActionDesc { + id: string; + query: (args: object) => GameActionResult; + execute: (args: object) => GameActionResult; +} + +export interface NetworkEventArgs { + readonly player: number; +} + +export interface NetworkActionEventArgs extends NetworkEventArgs { + readonly type: string; + result: GameActionResult; +} + +export interface NetworkChatEventArgs extends NetworkEventArgs { message: string; } @@ -69,11 +119,22 @@ export interface Context { */ registerIntent(desc: IntentDesc): void; + /** + * Registers a new game action that allows clients to interact with the game. + */ + registerGameAction(desc: GameActionDesc): void; + /** * Subscribes to the given hook. */ subscribe(hook: HookType, callback: Function): IDisposable; + + subscribe(hook: "interval.tick", callback: () => void): IDisposable; + subscribe(hook: "interval.day", callback: () => void): IDisposable; + subscribe(hook: "network.action", callback: (e: NetworkActionEventArgs) => void): IDisposable; subscribe(hook: "network.chat", callback: (e: NetworkChatEventArgs) => void): IDisposable; + subscribe(hook: "network.join", callback: (e: NetworkEventArgs) => void): IDisposable; + subscribe(hook: "network.leave", callback: (e: NetworkEventArgs) => void): IDisposable; } export interface IntentDesc @@ -91,27 +152,29 @@ export interface IDisposable { export type TileElementType = "surface" | "footpath" | "track" | "small_scenery" | "entrance" | "large_scenery" | "banner"; -export interface TileElement { +export interface BaseTileElement { type: TileElementType; baseHeight: number; clearanceHeight: number; broken: boolean; +} +export interface TileElement extends BaseTileElement { /** * Gets the element as a specific type to access its properties */ - asSurface(): SurfaceElement; - asFootpath(): FootpathElement; - asTrack(): TrackElement; - asSmallScenery(): SmallSceneryElement; - asEntrance(): EntranceElement; - asWall(): WallElement; - asLargeScenery(): LargeSceneryElement; - asBanner(): BannerElement; - asCorruptElement(): CorruptElement; + asSurface(): SurfaceElement | null; + asFootpath(): FootpathElement | null; + asTrack(): TrackElement | null; + asSmallScenery(): SmallSceneryElement | null; + asEntrance(): EntranceElement | null; + asWall(): WallElement | null; + asLargeScenery(): LargeSceneryElement | null; + asBanner(): BannerElement | null; + asCorruptElement(): CorruptElement | null; } -export interface SurfaceElement extends TileElement { +export interface SurfaceElement extends BaseTileElement { slope: number; terrain: number; waterHeight: number; @@ -120,14 +183,14 @@ export interface SurfaceElement extends TileElement { parkFences: number; } -export interface FootpathAdditionStatus { +export interface FootpathAdditionStatus extends BaseTileElement { north: number; east: number; south: number; west: number; } -export interface FootpathAddition { +export interface FootpathAddition extends BaseTileElement { type: number; isBin: boolean; isBench: boolean; @@ -146,7 +209,7 @@ export interface FootpathAddition { remove(): void; } -export interface FootpathElement extends TileElement { +export interface FootpathElement extends BaseTileElement { footpathType: number; isSloped: boolean; isQueue: boolean; @@ -156,25 +219,25 @@ export interface FootpathElement extends TileElement { rideIndex: number; } -export interface TrackElement extends TileElement { +export interface TrackElement extends BaseTileElement { } -export interface SmallSceneryElement extends TileElement { +export interface SmallSceneryElement extends BaseTileElement { } -export interface EntranceElement extends TileElement { +export interface EntranceElement extends BaseTileElement { } -export interface WallElement extends TileElement { +export interface WallElement extends BaseTileElement { } -export interface LargeSceneryElement extends TileElement { +export interface LargeSceneryElement extends BaseTileElement { } -export interface BannerElement extends TileElement { +export interface BannerElement extends BaseTileElement { } -export interface CorruptElement extends TileElement { +export interface CorruptElement extends BaseTileElement { } export interface Tile { @@ -273,12 +336,6 @@ export interface LabelWidget extends Widget { text: string; } -export interface Coord3 { - x: number; - y: number; - z: number; -} - export interface ViewportWidget extends Widget { target: null | number | Coord3; zoom: number; @@ -326,6 +383,50 @@ export interface WindowDesc { tabs?: Tab[]; } +export type ToolCallbackType = "move" | "press" | "release"; + +export interface ToolCallback { + type: ToolCallbackType; + tiles: Coord2[]; +} + +export type CursorType = + "arrow" | + "blank" | + "up_arrow" | + "up_down_arrow" | + "hand_point" | + "zzz" | + "diagonal_arrows" | + "picker" | + "tree_down" | + "fountain_down" | + "statue_down" | + "bench_down" | + "cross_hair" | + "bin_down" | + "lamppost_down" | + "fence_down" | + "flower_down" | + "path_down" | + "dig_down" | + "water_down" | + "house_down" | + "volcano_down" | + "walk_down" | + "paint_down" | + "entrance_down" | + "hand_open" | + "hand_closed"; + +export interface ToolDesc { + id: string; + cursor: CursorType; + width: number; + height: number; + callback: (e: ToolCallback) => void; +} + export interface Ui { readonly width: number; readonly height: number; @@ -336,6 +437,8 @@ export interface Ui { openWindow(desc: WindowDesc): Window; closeWindows(classification: string, id?: number): void; closeAllWindows(): void; + + activateTool(options: ToolDesc): IDisposable; } /** @@ -410,6 +513,8 @@ export interface Network { kickPlayer(index: number): void; sendMessage(message: string): void; sendMessage(message: string, players: number[]): void; + sendQueryAction(action: string, args: object, callback: (result: GameActionResult) => void): void; + sendExecuteAction(action: string, args: object, callback: (result: GameActionResult) => void): void; } /** From 4b95a3a9d061ef6eaea7076f52bb6ffd79e850d0 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 11 Feb 2020 21:26:05 +0000 Subject: [PATCH 052/159] Implement custom menu items --- distribution/openrct2.d.ts | 1 + src/openrct2-ui/scripting/CustomMenu.cpp | 36 +++++++++ src/openrct2-ui/scripting/CustomMenu.h | 52 ++++++++++++ src/openrct2-ui/scripting/ScUi.hpp | 9 +++ src/openrct2-ui/scripting/UiExtensions.cpp | 3 + src/openrct2-ui/windows/TopToolbar.cpp | 93 ++++++++++++++++------ src/openrct2/scripting/ScriptEngine.cpp | 38 +++++---- src/openrct2/scripting/ScriptEngine.h | 7 ++ 8 files changed, 199 insertions(+), 40 deletions(-) create mode 100644 src/openrct2-ui/scripting/CustomMenu.cpp create mode 100644 src/openrct2-ui/scripting/CustomMenu.h diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index a1e36d3067..ffa0bc929e 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -439,6 +439,7 @@ export interface Ui { closeAllWindows(): void; activateTool(options: ToolDesc): IDisposable; + registerMenuItem(text: string, callback: () => void): void; } /** diff --git a/src/openrct2-ui/scripting/CustomMenu.cpp b/src/openrct2-ui/scripting/CustomMenu.cpp new file mode 100644 index 0000000000..63e79e3b67 --- /dev/null +++ b/src/openrct2-ui/scripting/CustomMenu.cpp @@ -0,0 +1,36 @@ +/***************************************************************************** + * 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. + *****************************************************************************/ + +#include "CustomMenu.h" + +namespace OpenRCT2::Scripting +{ + std::vector CustomMenuItems; + + static void RemoveMenuItems(std::shared_ptr owner) + { + auto& menuItems = CustomMenuItems; + for (auto it = menuItems.begin(); it != menuItems.end();) + { + if (it->Owner == owner) + { + it = menuItems.erase(it); + } + else + { + it++; + } + } + } + + void InitialiseCustomMenuItems(ScriptEngine& scriptEngine) + { + scriptEngine.SubscribeToPluginStoppedEvent([](std::shared_ptr plugin) -> void { RemoveMenuItems(plugin); }); + } +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2-ui/scripting/CustomMenu.h b/src/openrct2-ui/scripting/CustomMenu.h new file mode 100644 index 0000000000..4a26fb1a56 --- /dev/null +++ b/src/openrct2-ui/scripting/CustomMenu.h @@ -0,0 +1,52 @@ +/***************************************************************************** + * 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 + +#include +#include +#include +#include +#include +#include + +namespace OpenRCT2::Scripting +{ + class CustomToolbarMenuItem + { + public: + std::shared_ptr Owner; + std::string Text; + DukValue Callback; + + CustomToolbarMenuItem(std::shared_ptr owner, std::string text, DukValue callback) + : Owner(owner) + , Text(text) + , Callback(callback) + { + } + + void Invoke() const + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto& execInfo = scriptEngine.GetExecInfo(); + auto ctx = scriptEngine.GetContext(); + + ScriptExecutionInfo::PluginScope scope(execInfo, Owner); + Callback.push(); + duk_pcall(ctx, 0); + duk_pop(ctx); + } + }; + + extern std::vector CustomMenuItems; + + void InitialiseCustomMenuItems(ScriptEngine& scriptEngine); + +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 5484286a6f..cd47708af6 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -9,6 +9,7 @@ #pragma once +#include "CustomMenu.h" #include "ScWindow.hpp" #include @@ -105,6 +106,13 @@ namespace OpenRCT2::Scripting return nullptr; } + void registerMenuItem(std::string text, DukValue callback) + { + auto& execInfo = _scriptEngine.GetExecInfo(); + auto owner = execInfo.GetCurrentPlugin(); + CustomMenuItems.emplace_back(owner, text, callback); + } + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScUi::height_get, nullptr, "height"); @@ -114,6 +122,7 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScUi::closeWindows, "closeWindows"); dukglue_register_method(ctx, &ScUi::closeAllWindows, "closeAllWindows"); dukglue_register_method(ctx, &ScUi::getWindow, "getWindow"); + dukglue_register_method(ctx, &ScUi::registerMenuItem, "registerMenuItem"); } private: diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index 773d466cd8..84b23901f2 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -9,6 +9,7 @@ #include "UiExtensions.h" +#include "CustomMenu.h" #include "ScUi.hpp" #include "ScWindow.hpp" @@ -24,4 +25,6 @@ void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) ScUi::Register(ctx); ScWindow::Register(ctx); + + InitialiseCustomMenuItems(scriptEngine); } diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index 0de292c018..29be4af650 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -9,6 +9,7 @@ #include "../UiContext.h" #include "../interface/InGameConsole.h" +#include "../scripting/CustomMenu.h" #include #include @@ -305,6 +306,8 @@ static rct_window_event_list window_top_toolbar_events = { static void top_toolbar_init_view_menu(rct_window* window, rct_widget* widget); static void top_toolbar_view_menu_dropdown(int16_t dropdownIndex); +static void top_toolbar_init_map_menu(rct_window* window, rct_widget* widget); +static void top_toolbar_map_menu_dropdown(int16_t dropdownIndex); static void top_toolbar_init_fastforward_menu(rct_window* window, rct_widget* widget); static void top_toolbar_fastforward_menu_dropdown(int16_t dropdownIndex); static void top_toolbar_init_rotate_menu(rct_window* window, rct_widget* widget); @@ -521,20 +524,7 @@ static void window_top_toolbar_mousedown(rct_window* w, rct_widgetindex widgetIn top_toolbar_init_view_menu(w, widget); break; case WIDX_MAP: - gDropdownItemsFormat[0] = STR_SHORTCUT_SHOW_MAP; - gDropdownItemsFormat[1] = STR_EXTRA_VIEWPORT; - numItems = 2; - - if ((gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) && gS6Info.editor_step == EDITOR_STEP_LANDSCAPE_EDITOR) - { - gDropdownItemsFormat[2] = STR_MAPGEN_WINDOW_TITLE; - numItems++; - } - - window_dropdown_show_text( - w->windowPos.x + widget->left, w->windowPos.y + widget->top, widget->bottom - widget->top + 1, - w->colours[1] | 0x80, 0, numItems); - gDropdownDefaultIndex = DDIDX_SHOW_MAP; + top_toolbar_init_map_menu(w, widget); break; case WIDX_FASTFORWARD: top_toolbar_init_fastforward_menu(w, widget); @@ -651,18 +641,7 @@ static void window_top_toolbar_dropdown(rct_window* w, rct_widgetindex widgetInd top_toolbar_view_menu_dropdown(dropdownIndex); break; case WIDX_MAP: - switch (dropdownIndex) - { - case 0: - context_open_window(WC_MAP); - break; - case 1: - context_open_window(WC_VIEWPORT); - break; - case 2: - context_open_window(WC_MAPGEN); - break; - } + top_toolbar_map_menu_dropdown(dropdownIndex); break; case WIDX_FASTFORWARD: top_toolbar_fastforward_menu_dropdown(dropdownIndex); @@ -3293,6 +3272,68 @@ static void window_top_toolbar_tool_abort(rct_window* w, rct_widgetindex widgetI } } +static void top_toolbar_init_map_menu(rct_window* w, rct_widget* widget) +{ + auto i = 0; + gDropdownItemsFormat[i++] = STR_SHORTCUT_SHOW_MAP; + gDropdownItemsFormat[i++] = STR_EXTRA_VIEWPORT; + if ((gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) && gS6Info.editor_step == EDITOR_STEP_LANDSCAPE_EDITOR) + { + gDropdownItemsFormat[i++] = STR_MAPGEN_WINDOW_TITLE; + } + + const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; + if (!customMenuItems.empty()) + { + gDropdownItemsFormat[i++] = STR_EMPTY; + for (const auto& item : customMenuItems) + { + gDropdownItemsFormat[i] = STR_STRING; + set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, item.Text.c_str()); + i++; + } + } + + window_dropdown_show_text( + w->windowPos.x + widget->left, w->windowPos.y + widget->top, widget->bottom - widget->top + 1, w->colours[1] | 0x80, 0, + i); + gDropdownDefaultIndex = DDIDX_SHOW_MAP; +} + +static void top_toolbar_map_menu_dropdown(int16_t dropdownIndex) +{ + int32_t customStartIndex = 3; + if ((gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) && gS6Info.editor_step == EDITOR_STEP_LANDSCAPE_EDITOR) + { + customStartIndex++; + } + + if (dropdownIndex < customStartIndex) + { + switch (dropdownIndex) + { + case 0: + context_open_window(WC_MAP); + break; + case 1: + context_open_window(WC_VIEWPORT); + break; + case 2: + context_open_window(WC_MAPGEN); + break; + } + } + else + { + const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; + auto customIndex = dropdownIndex - customStartIndex; + if (customMenuItems.size() > customIndex) + { + customMenuItems[customIndex].Invoke(); + } + } +} + static void top_toolbar_init_fastforward_menu(rct_window* w, rct_widget* widget) { int32_t num_items = 4; diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 9a318c9098..aa3c4fdebf 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -136,6 +136,28 @@ void ScriptEngine::LoadPlugin(const std::string& path) } } +void ScriptEngine::StopPlugin(std::shared_ptr plugin) +{ + if (plugin->HasStarted()) + { + _hookEngine.UnsubscribeAll(plugin); + for (auto callback : _pluginStoppedSubscriptions) + { + callback(plugin); + } + + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + try + { + plugin->Stop(); + } + catch (const std::exception& e) + { + _console.WriteLineError(e.what()); + } + } +} + bool ScriptEngine::ShouldLoadScript(const std::string& path) { // A lot of JavaScript is often found in a node_modules directory tree and is most likely unwanted, so ignore it @@ -174,7 +196,7 @@ void ScriptEngine::AutoReloadPlugins() auto& plugin = *findResult; try { - _hookEngine.UnsubscribeAll(plugin); + StopPlugin(plugin); ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); @@ -225,21 +247,9 @@ void ScriptEngine::StartPlugins() void ScriptEngine::StopPlugins() { - _hookEngine.UnsubscribeAll(); for (auto& plugin : _plugins) { - if (plugin->HasStarted()) - { - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); - try - { - plugin->Stop(); - } - catch (const std::exception& e) - { - _console.WriteLineError(e.what()); - } - } + StopPlugin(plugin); } _pluginsStarted = false; } diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 70556f436a..c83ba577af 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -105,6 +105,7 @@ namespace OpenRCT2::Scripting std::unique_ptr _pluginFileWatcher; std::unordered_set _changedPluginFiles; std::mutex _changedPluginFilesMutex; + std::vector)>> _pluginStoppedSubscriptions; public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); @@ -130,11 +131,17 @@ namespace OpenRCT2::Scripting void LogPluginInfo(const std::shared_ptr& plugin, const std::string_view& message); + void SubscribeToPluginStoppedEvent(std::function)> callback) + { + _pluginStoppedSubscriptions.push_back(callback); + } + private: void Initialise(); void StartPlugins(); void StopPlugins(); void LoadPlugin(const std::string& path); + void StopPlugin(std::shared_ptr plugin); bool ShouldLoadScript(const std::string& path); void SetupHotReloading(); void AutoReloadPlugins(); From ab5bfffde0e406b4b1bce0121bab5c3a40488933 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 11 Feb 2020 23:25:19 +0000 Subject: [PATCH 053/159] Fix tile element scripting --- distribution/openrct2.d.ts | 30 +- src/openrct2/scripting/ScMap.hpp | 5 +- src/openrct2/scripting/ScTile.hpp | 517 +++--------------------------- 3 files changed, 56 insertions(+), 496 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index ffa0bc929e..ccc7ba579c 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -159,20 +159,22 @@ export interface BaseTileElement { broken: boolean; } -export interface TileElement extends BaseTileElement { - /** - * Gets the element as a specific type to access its properties - */ - asSurface(): SurfaceElement | null; - asFootpath(): FootpathElement | null; - asTrack(): TrackElement | null; - asSmallScenery(): SmallSceneryElement | null; - asEntrance(): EntranceElement | null; - asWall(): WallElement | null; - asLargeScenery(): LargeSceneryElement | null; - asBanner(): BannerElement | null; - asCorruptElement(): CorruptElement | null; -} +// export interface TileElement extends BaseTileElement { +// /** +// * Gets the element as a specific type to access its properties +// */ +// asSurface(): SurfaceElement | null; +// asFootpath(): FootpathElement | null; +// asTrack(): TrackElement | null; +// asSmallScenery(): SmallSceneryElement | null; +// asEntrance(): EntranceElement | null; +// asWall(): WallElement | null; +// asLargeScenery(): LargeSceneryElement | null; +// asBanner(): BannerElement | null; +// asCorruptElement(): CorruptElement | null; +// } + +export type TileElement = SurfaceElement | FootpathElement | TrackElement; export interface SurfaceElement extends BaseTileElement { slope: number; diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 5ffea1e1e4..61f12c2c94 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -52,8 +52,9 @@ namespace OpenRCT2::Scripting std::shared_ptr getTile(int32_t x, int32_t y) { - auto firstElement = map_get_first_element_at({ x, y }); - return std::make_shared(firstElement); + auto coords = TileCoordsXY(x, y).ToCoordsXY(); + auto firstElement = map_get_first_element_at(coords); + return std::make_shared(coords, firstElement); } std::shared_ptr getThing(int32_t id) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 69c605106b..c2603250b9 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -20,18 +20,23 @@ namespace OpenRCT2::Scripting { + class ScSurfaceElement; + class ScTileElement { protected: + CoordsXY _coords; TileElement* _element; public: - ScTileElement(TileElement* element) - : _element(element) + ScTileElement(CoordsXY coords, TileElement* element) + : _coords(coords) + , _element(element) { } - std::string footpathType_get() const + private: + std::string type_get() const { switch (_element->GetType()) { @@ -58,11 +63,6 @@ namespace OpenRCT2::Scripting } } - template T* getAs() - { - return static_cast(this); - } - bool broken_get() const { return _element->flags & TILE_ELEMENT_FLAG_BROKEN; @@ -97,485 +97,55 @@ namespace OpenRCT2::Scripting _element->clearance_height = newClearanceHeight; } - static void Register(duk_context* ctx); - template static void RegisterSharedProperties(duk_context* ctx); - }; - - class ScSurfaceElement final : public ScTileElement - { - uint8_t slope_get() - { - return _element->AsSurface()->GetSlope(); - } - void slope_set(uint8_t value) - { - // TODO: Give warning when value > TILE_ELEMENT_SURFACE_SLOPE_MASK - _element->AsSurface()->SetSlope(value); - } - - uint8_t terrain_get() - { - return _element->AsSurface()->GetSurfaceStyle(); - } - void terrain_set(uint8_t value) - { - _element->AsSurface()->SetSurfaceStyle(value); - } - - uint8_t waterHeight_get() - { - return _element->AsSurface()->GetWaterHeight(); - } - void waterHeight_set(uint8_t value) - { - // TODO: Give warning when value > TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK - _element->AsSurface()->SetWaterHeight(value); - } - uint8_t grassLength_get() { - return _element->AsSurface()->GetGrassLength(); + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetGrassLength(); + return 0; } void grassLength_set(uint8_t value) { - // TODO: Give warning when value > GRASS_LENGTH_CLUMPS_2 - return _element->AsSurface()->SetGrassLength(value); + auto el = _element->AsSurface(); + if (el != nullptr) + { + // TODO: Give warning when value > GRASS_LENGTH_CLUMPS_2 + el->SetGrassLengthAndInvalidate(value, _coords); + } } - uint8_t ownership_get() + bool hasOwnership_get() { - return _element->AsSurface()->GetOwnership(); - } - void ownership_set(uint8_t flags) - { - _element->AsSurface()->SetOwnership(flags); - } - - uint8_t parkFences_get() - { - return _element->AsSurface()->GetParkFences(); - } - void parkFences_set(uint8_t flags) - { - return _element->AsSurface()->SetParkFences(flags); + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetOwnership() & OWNERSHIP_OWNED; + return false; } public: static void Register(duk_context* ctx) { - RegisterSharedProperties(ctx); - dukglue_register_property(ctx, &slope_get, &slope_set, "slope"); - dukglue_register_property(ctx, &terrain_get, &terrain_set, "terrain"); - dukglue_register_property(ctx, &waterHeight_get, &waterHeight_set, "waterHeight"); - dukglue_register_property(ctx, &grassLength_get, &grassLength_set, "grassLength"); - dukglue_register_property(ctx, &ownership_get, &ownership_set, "ownership"); - dukglue_register_property(ctx, &waterHeight_get, &parkFences_set, "parkFences"); + dukglue_register_property(ctx, &ScTileElement::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + dukglue_register_property(ctx, &ScTileElement::baseHeight_get, &ScTileElement::baseHeight_set, "baseHeight"); + dukglue_register_property( + ctx, &ScTileElement::clearanceHeight_get, &ScTileElement::clearanceHeight_set, "clearanceHeight"); + dukglue_register_property(ctx, &ScTileElement::grassLength_get, &ScTileElement::grassLength_set, "grassLength"); + dukglue_register_property(ctx, &ScTileElement::hasOwnership_get, nullptr, "hasOwnership"); } }; - class ScFootpathElement final : public ScTileElement - { - class ScFootpathAddition - { - class ScFootpathAdditionStatus - { - protected: - TileElement* _element; - - public: - ScFootpathAdditionStatus(TileElement* element) - : _element(element) - { - } - - uint8_t north_get() - { - return _element->AsPath()->GetAdditionStatus() & 3; - } - void north_set(uint8_t value) - { - auto addition = _element->AsPath()->GetAdditionStatus(); - addition &= ~3; - addition |= value & 3; - _element->AsPath()->SetAdditionStatus(addition); - } - - uint8_t east_get() - { - return _element->AsPath()->GetAdditionStatus() & 3; - } - void east_set(uint8_t value) - { - auto addition = _element->AsPath()->GetAdditionStatus(); - addition &= ~(3 << 2); - addition |= (value & 3) << 2; - _element->AsPath()->SetAdditionStatus(addition); - } - - uint8_t south_get() - { - return _element->AsPath()->GetAdditionStatus() & 3; - } - void south_set(uint8_t value) - { - auto addition = _element->AsPath()->GetAdditionStatus(); - addition &= ~(3 << 4); - addition |= (value & 3) << 4; - _element->AsPath()->SetAdditionStatus(addition); - } - - uint8_t west_get() - { - return _element->AsPath()->GetAdditionStatus() & 3; - } - void west_set(uint8_t value) - { - auto addition = _element->AsPath()->GetAdditionStatus(); - addition &= ~(3 << 6); - addition |= (value & 3) << 6; - _element->AsPath()->SetAdditionStatus(addition); - } - - static void Register(duk_context* ctx) - { - dukglue_register_property(ctx, &north_get, &north_set, "north"); - dukglue_register_property(ctx, &east_get, &east_set, "east"); - dukglue_register_property(ctx, &south_get, &south_set, "south"); - dukglue_register_property(ctx, &west_get, &west_set, "west"); - } - }; - - protected: - TileElement* _element; - bool VerifyPathAdditionExists() - { - if (!_element->AsPath()->HasAddition()) - { - // TODO: Show warning in console that the path addition has been removed - return false; - } - return true; - } - - public: - ScFootpathAddition(TileElement* element) - : _element(element) - { - } - - void Remove() - { - _element->AsPath()->SetAddition(0); - } - - uint8_t type_get() - { - if (!VerifyPathAdditionExists()) - return 0; - return _element->AsPath()->GetAddition(); - } - void type_set(uint8_t value) - { - _element->AsPath()->SetAddition(value); - } - - bool isBin_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_BIN; - } - bool isBench_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_BENCH; - } - bool isLamp_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_LAMP; - } - bool isBreakable_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_BREAKABLE; - } - bool isJumpingFountainWater_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_JUMPING_FOUNTAIN_WATER; - } - bool isJumpingFountainSnow_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_JUMPING_FOUNTAIN_SNOW; - } - bool allowedOnQueue_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_DONT_ALLOW_ON_QUEUE; - } - bool allowedOnSlope_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_DONT_ALLOW_ON_SLOPE; - } - bool isQueueScreen_get() - { - if (!VerifyPathAdditionExists()) - return false; - - auto sceneryEntry = _element->AsPath()->GetAdditionEntry(); - return sceneryEntry->path_bit.flags & PATH_BIT_FLAG_IS_QUEUE_SCREEN; - } - - std::shared_ptr status_get() - { - return std::make_shared(_element); - } - - static void Register(duk_context* ctx) - { - // Addition status properties (.status.north, .status.east, etc.) - ScFootpathAdditionStatus::Register(ctx); - - // Functions - dukglue_register_method(ctx, &ScFootpathAddition::Remove, "remove"); - - // Properties - dukglue_register_property(ctx, &type_get, &type_set, "type"); - dukglue_register_property(ctx, &isBin_get, nullptr, "isBin"); - dukglue_register_property(ctx, &isBench_get, nullptr, "isBench"); - dukglue_register_property(ctx, &isLamp_get, nullptr, "isLamp"); - dukglue_register_property(ctx, &isBreakable_get, nullptr, "isBreakable"); - dukglue_register_property(ctx, &isJumpingFountainWater_get, nullptr, "isJumpingFountainWater"); - dukglue_register_property(ctx, &isJumpingFountainSnow_get, nullptr, "isJumpingFountainSnow"); - dukglue_register_property(ctx, &allowedOnQueue_get, nullptr, "allowedOnQueue"); - dukglue_register_property(ctx, &allowedOnSlope_get, nullptr, "allowedOnSlope"); - dukglue_register_property(ctx, &isQueueScreen_get, nullptr, "isQueueScreen"); - dukglue_register_property(ctx, &status_get, nullptr, "status"); - } - }; - - uint8_t footpathType_get() - { - return _element->AsPath()->GetPathEntryIndex(); - } - void type_set(uint8_t index) - { - auto entry = get_path_surface_entry(index); - if (entry == nullptr) - { - // TODO: Give warning (most likely only happens when index > MAX_PATH_OBJECTS) - return; - } - _element->AsPath()->SetPathEntryIndex(index); - } - - bool isSloped_get() - { - return _element->AsPath()->IsSloped(); - } - void isSlope_set(bool value) - { - _element->AsPath()->SetSloped(value); - } - - bool isQueue_get() - { - return _element->AsPath()->IsQueue(); - } - - std::shared_ptr addition_get() - { - if (!_element->AsPath()->HasAddition()) - return nullptr; - - return std::make_shared(_element); - } - - uint8_t edges_get() - { - return _element->AsPath()->GetEdges(); - } - void edges_set(uint8_t value) - { - _element->AsPath()->SetEdges(value); - } - - uint8_t corners_get() - { - return _element->AsPath()->GetCorners(); - } - void corners_set(uint8_t value) - { - _element->AsPath()->SetCorners(value); - } - - uint8_t rideIndex_get() - { - if (!_element->AsPath()->IsQueue()) - { - // TODO: Show warning that "path is not a queue" - } - return _element->AsPath()->GetRideIndex(); - } - - public: - static void Register(duk_context* ctx) - { - // Register shared properties (baseheight, clearance height, etc.) - RegisterSharedProperties(ctx); - - // Register path addition properties (.addition.isBench, .addition.isLamp, etc.) - ScFootpathAddition::Register(ctx); - - // Specific properties - dukglue_register_property(ctx, &footpathType_get, &type_set, "footpathType"); - dukglue_register_property(ctx, &isSloped_get, &isSlope_set, "isSloped"); - dukglue_register_property(ctx, &isQueue_get, nullptr, "isQueue"); - dukglue_register_property(ctx, &addition_get, nullptr, "addition"); - dukglue_register_property(ctx, &edges_get, &edges_set, "edges"); - dukglue_register_property(ctx, &corners_get, &corners_set, "corners"); - dukglue_register_property(ctx, &rideIndex_get, nullptr, "rideIndex"); - } - }; - - class ScTrackElement final : public ScTileElement - { - auto track_ride_index_get() const - { - return _element->AsTrack()->GetRideIndex(); - } - - public: - static void Register(duk_context* ctx) - { - RegisterSharedProperties(ctx); - dukglue_register_property(ctx, &ScTrackElement::track_ride_index_get, nullptr, "rideIndex"); - } - }; - - class ScSmallSceneryElement final : public ScTileElement - { - public: - static void Register(duk_context* ctx) - { - RegisterSharedProperties(ctx); - } - }; - - class ScEntranceElement final : public ScTileElement - { - public: - static void Register(duk_context* ctx) - { - RegisterSharedProperties(ctx); - } - }; - - class ScWallElement final : public ScTileElement - { - public: - static void Register(duk_context* ctx) - { - RegisterSharedProperties(ctx); - } - }; - - class ScLargeSceneryElement final : public ScTileElement - { - public: - static void Register(duk_context* ctx) - { - RegisterSharedProperties(ctx); - } - }; - - class ScBannerElement final : public ScTileElement - { - public: - static void Register(duk_context* ctx) - { - RegisterSharedProperties(ctx); - } - }; - - void ScTileElement::Register(duk_context* ctx) - { - dukglue_register_method(ctx, &ScTileElement::getAs, "asSurface"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asFootpath"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asTrack"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asSmallScenery"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asEntrance"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asWall"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asLargeScenery"); - dukglue_register_method(ctx, &ScTileElement::getAs, "asBanner"); - - // Shared properties - RegisterSharedProperties(ctx); - - // Register type specific properties - ScSurfaceElement ::Register(ctx); - ScFootpathElement::Register(ctx); - ScTrackElement ::Register(ctx); - ScSmallSceneryElement ::Register(ctx); - ScEntranceElement ::Register(ctx); - ScWallElement ::Register(ctx); - ScLargeSceneryElement ::Register(ctx); - ScBannerElement ::Register(ctx); - } - - template void ScTileElement::RegisterSharedProperties(duk_context* ctx) - { - // When you register a member function of a parent class, it belongs to the parent and cannot be accessed by its - // children. To get around this issue, we need to force the function pointer types to be of the class we want them to be - // available for. This needs to be done for every child. - dukglue_register_property( - ctx, static_cast(&ScTileElement::footpathType_get), nullptr, "type"); - dukglue_register_property( - ctx, static_cast(&ScTileElement::broken_get), - static_cast(&ScTileElement::broken_set), "broken"); - dukglue_register_property( - ctx, static_cast(&ScTileElement::baseHeight_get), - static_cast(&ScTileElement::baseHeight_set), "baseHeight"); - dukglue_register_property( - ctx, static_cast(&ScTileElement::clearanceHeight_get), - static_cast(&ScTileElement::clearanceHeight_set), "clearanceHeight"); - } - class ScTile { private: + CoordsXY _coords; TileElement* _first; size_t _count = 0; public: - ScTile(TileElement* first) - : _first(first) + ScTile(CoordsXY coords, TileElement* first) + : _coords(coords) + , _first(first) { _count = 0; if (first != nullptr) @@ -588,7 +158,7 @@ namespace OpenRCT2::Scripting } } - size_t numElements_get() + size_t elements_get() { return _count; } @@ -597,25 +167,12 @@ namespace OpenRCT2::Scripting { if (index >= _count) return nullptr; - return std::make_shared(&_first[index]); + return std::make_shared(_coords, &_first[index]); } - // This is not a good idea as the array is generated each time elements is accessed and - // chances are scripts will do tile.elements[0], tile.elements[1]... - // std::vector> elements_get() - // { - // std::vector> elements; - // for (size_t i = 0; i < _count; i++) - // { - // elements.push_back(std::make_shared(&_first[i])); - // } - // return elements; - // } - static void Register(duk_context* ctx) { - // dukglue_register_property(ctx, &ScTile::elements_get, nullptr, "elements"); - dukglue_register_property(ctx, &ScTile::numElements_get, nullptr, "numElements"); + dukglue_register_property(ctx, &ScTile::elements_get, nullptr, "elements"); dukglue_register_method(ctx, &ScTile::getElement, "getElement"); } }; From 91043cec516f8e875cff4a049a427e7a2dc32311 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 12 Feb 2020 14:29:02 +0000 Subject: [PATCH 054/159] Add RideObject API --- distribution/openrct2.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index ccc7ba579c..956238c7d8 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -250,7 +250,16 @@ export interface Tile { getElement(index: number): TileElement; } +export interface RideObject { + readonly id: number; + readonly name: string; + readonly description: string; + readonly capacity: string; +} + export interface Ride { + readonly object: RideObject; + type: string; name: string; excitement: number; intensity: number; From 560be19cdf479cd8786d5c0b1807fef6283b7de8 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 12 Feb 2020 17:32:24 +0000 Subject: [PATCH 055/159] Implement Ride and RideObject API --- distribution/openrct2.d.ts | 8 +- src/openrct2/scripting/ScMap.hpp | 18 ++- src/openrct2/scripting/ScRide.hpp | 168 ++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 3 + 4 files changed, 194 insertions(+), 3 deletions(-) create mode 100644 src/openrct2/scripting/ScRide.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 956238c7d8..b92becd0f9 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -250,15 +250,19 @@ export interface Tile { getElement(index: number): TileElement; } -export interface RideObject { - readonly id: number; +export interface Object { + readonly identifier: string; readonly name: string; +} + +export interface RideObject extends Object { readonly description: string; readonly capacity: string; } export interface Ride { readonly object: RideObject; + readonly id: number; type: string; name: string; excitement: number; diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 61f12c2c94..2d8c9d097d 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -13,6 +13,7 @@ #include "../ride/Ride.h" #include "../world/Map.h" #include "Duktape.hpp" +#include "ScRide.hpp" #include "ScThing.hpp" #include "ScTile.hpp" @@ -42,7 +43,7 @@ namespace OpenRCT2::Scripting int32_t rides_get() { - return MAX_RIDES; + return static_cast(GetRideManager().size()); } int32_t things_get() @@ -50,6 +51,20 @@ namespace OpenRCT2::Scripting return MAX_SPRITES; } + std::shared_ptr getRide(int32_t id) + { + auto rideManager = GetRideManager(); + if (id >= 0 && id < rideManager.size()) + { + auto ride = rideManager[static_cast(id)]; + if (ride != nullptr) + { + return std::make_shared(ride); + } + } + return nullptr; + } + std::shared_ptr getTile(int32_t x, int32_t y) { auto coords = TileCoordsXY(x, y).ToCoordsXY(); @@ -75,6 +90,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScMap::size_get, nullptr, "size"); dukglue_register_property(ctx, &ScMap::rides_get, nullptr, "rides"); dukglue_register_property(ctx, &ScMap::things_get, nullptr, "things"); + dukglue_register_method(ctx, &ScMap::getRide, "getRide"); dukglue_register_method(ctx, &ScMap::getTile, "getTile"); dukglue_register_method(ctx, &ScMap::getThing, "getThing"); } diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp new file mode 100644 index 0000000000..7bb3ae0fb6 --- /dev/null +++ b/src/openrct2/scripting/ScRide.hpp @@ -0,0 +1,168 @@ +/***************************************************************************** + * 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 + +#include "../common.h" +#include "../object/RideObject.h" +#include "../ride/Ride.h" +#include "Duktape.hpp" + +namespace OpenRCT2::Scripting +{ + class ScRideObject + { + private: + rct_ride_entry* _entry; + + public: + ScRideObject(rct_ride_entry* entry) + { + _entry = entry; + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &id_get, nullptr, "identifier"); + dukglue_register_property(ctx, &name_get, nullptr, "name"); + dukglue_register_property(ctx, &description_get, nullptr, "description"); + dukglue_register_property(ctx, &capacity_get, nullptr, "capacity"); + } + + private: + std::string id_get() + { + auto obj = static_cast(_entry->obj); + if (obj != nullptr) + { + return obj->GetIdentifier(); + } + return {}; + } + + std::string name_get() + { + auto obj = static_cast(_entry->obj); + if (obj != nullptr) + { + return obj->GetName(); + } + return {}; + } + + std::string description_get() + { + auto obj = static_cast(_entry->obj); + if (obj != nullptr) + { + return obj->GetDescription(); + } + return {}; + } + + std::string capacity_get() + { + auto obj = static_cast(_entry->obj); + if (obj != nullptr) + { + return obj->GetCapacity(); + } + return {}; + } + }; + + class ScRide + { + private: + Ride* _ride; + + public: + ScRide(Ride* ride) + : _ride(ride) + { + } + + int32_t id_get() + { + return _ride->id; + } + + std::shared_ptr object_get() + { + auto rideEntry = _ride->GetRideEntry(); + if (rideEntry != nullptr) + { + return std::make_shared(rideEntry); + } + return nullptr; + } + + int32_t type_get() + { + return _ride->type; + } + + std::string name_get() + { + return _ride->GetName(); + } + void name_set(std::string value) + { + _ride->custom_name = value; + } + + int32_t excitement_get() + { + return _ride->excitement; + } + void excitement_set(int32_t value) + { + _ride->excitement = value; + } + + int32_t intensity_get() + { + return _ride->intensity; + } + void intensity_set(int32_t value) + { + _ride->intensity = value; + } + + int32_t nausea_get() + { + return _ride->nausea; + } + void nausea_set(int32_t value) + { + _ride->nausea = value; + } + + int32_t totalCustomers_get() + { + return _ride->total_customers; + } + void totalCustomers_set(int32_t value) + { + _ride->total_customers = value; + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &ScRide::id_get, nullptr, "id"); + dukglue_register_property(ctx, &ScRide::object_get, nullptr, "object"); + dukglue_register_property(ctx, &ScRide::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScRide::name_get, &ScRide::name_set, "name"); + dukglue_register_property(ctx, &ScRide::excitement_get, &ScRide::excitement_set, "excitement"); + dukglue_register_property(ctx, &ScRide::intensity_get, &ScRide::intensity_set, "intensity"); + dukglue_register_property(ctx, &ScRide::nausea_get, &ScRide::nausea_set, "nausea"); + dukglue_register_property(ctx, &ScRide::totalCustomers_get, &ScRide::totalCustomers_set, "totalCustomers"); + } + }; +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index aa3c4fdebf..08f59ef7a0 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -22,6 +22,7 @@ #include "ScMap.hpp" #include "ScNetwork.hpp" #include "ScPark.hpp" +#include "ScRide.hpp" #include "ScThing.hpp" #include "ScTile.hpp" @@ -67,6 +68,8 @@ void ScriptEngine::Initialise() ScPark::Register(ctx); ScPlayer::Register(ctx); ScPlayerGroup::Register(ctx); + ScRide::Register(ctx); + ScRideObject::Register(ctx); ScTile::Register(ctx); ScTileElement::Register(ctx); ScThing::Register(ctx); From d3af46ad9f204d67c6ca17819eb0c2cf5e0c529c Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 12 Feb 2020 21:56:18 +0000 Subject: [PATCH 056/159] Implement label widget --- src/openrct2-ui/scripting/CustomWindow.cpp | 33 ++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 2788c3f2a8..ebbbb7a2a9 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -96,6 +96,24 @@ namespace OpenRCT2::Ui::Windows DukValue OnClick; DukValue OnChange; + static std::string ProcessString(const std::string_view& s) + { + std::string result; + result.reserve(s.size()); + for (char c : s) + { + if (c == '\n') + { + result.push_back(FORMAT_NEWLINE); + } + else + { + result.push_back(c); + } + } + return result; + } + static CustomWidgetDesc FromDukValue(DukValue desc) { CustomWidgetDesc result; @@ -119,6 +137,10 @@ namespace OpenRCT2::Ui::Windows result.SelectedIndex = desc["selectedIndex"].as_int(); result.OnChange = desc["onChange"]; } + else if (result.Type == "label") + { + result.Text = ProcessString(desc["text"].as_string()); + } return result; } }; @@ -128,8 +150,8 @@ namespace OpenRCT2::Ui::Windows std::string Classification; std::optional X; std::optional Y; - int32_t Width; - int32_t Height; + int32_t Width{}; + int32_t Height{}; std::optional MinWidth; std::optional MinHeight; std::optional MaxWidth; @@ -433,6 +455,13 @@ namespace OpenRCT2::Ui::Windows widget.flags |= WIDGET_FLAGS::IS_ENABLED; widgetList.push_back(widget); } + else if (desc.Type == "label") + { + widget.type = WWT_LABEL; + widget.string = (utf8*)desc.Text.c_str(); + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + widgetList.push_back(widget); + } } static void RefreshWidgets(rct_window* w) From 0ec4475d62fe1a0f1ccb91972eb857cf69bba1dd Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 13 Feb 2020 09:36:53 +0000 Subject: [PATCH 057/159] Implement tile x, y coordinates --- src/openrct2/scripting/ScTile.hpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index c2603250b9..82593fe111 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -158,6 +158,16 @@ namespace OpenRCT2::Scripting } } + int32_t x_get() + { + return _coords.x / 32; + } + + int32_t y_get() + { + return _coords.y / 32; + } + size_t elements_get() { return _count; @@ -172,6 +182,8 @@ namespace OpenRCT2::Scripting static void Register(duk_context* ctx) { + dukglue_register_property(ctx, &ScTile::x_get, nullptr, "x"); + dukglue_register_property(ctx, &ScTile::y_get, nullptr, "y"); dukglue_register_property(ctx, &ScTile::elements_get, nullptr, "elements"); dukglue_register_method(ctx, &ScTile::getElement, "getElement"); } From 3596480016cbc84cc357a4ecd8a735f4c6339d29 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 14 Feb 2020 19:55:04 +0000 Subject: [PATCH 058/159] Add viewport APIs --- distribution/openrct2.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index b92becd0f9..37950a3523 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -442,10 +442,21 @@ export interface ToolDesc { callback: (e: ToolCallback) => void; } +export interface ViewportInfo { + rotation: number; + zoom: number; + visibilityFlags: number; + + getCentrePosition(): Coord2; + moveTo(position: Coord2 | Coord3): void; + scrollTo(position: Coord2 | Coord3): void; +} + export interface Ui { readonly width: number; readonly height: number; readonly windows: number; + readonly mainViewport: ViewportInfo; getWindow(id: number): Window; getWindow(classification: string, id?: number): Window; From d7d880dc2305e44868589b2e275e483e519ec481 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 14 Feb 2020 19:53:04 +0000 Subject: [PATCH 059/159] Restart plugins when starting new game from a game --- src/openrct2/scripting/ScriptEngine.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 08f59ef7a0..fa17633c84 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -91,6 +91,10 @@ void ScriptEngine::LoadPlugins() { Initialise(); } + if (_pluginsLoaded) + { + UnloadPlugins(); + } auto base = _env.GetDirectoryPath(DIRBASE::USER, DIRID::PLUGIN); if (Path::DirectoryExists(base)) @@ -112,6 +116,7 @@ void ScriptEngine::LoadPlugins() } } _pluginsLoaded = true; + _pluginsStarted = false; } void ScriptEngine::LoadPlugin(const std::string& path) @@ -237,6 +242,7 @@ void ScriptEngine::StartPlugins() ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); try { + LogPluginInfo(plugin, "Started"); plugin->Start(); } catch (const std::exception& e) @@ -253,6 +259,7 @@ void ScriptEngine::StopPlugins() for (auto& plugin : _plugins) { StopPlugin(plugin); + LogPluginInfo(plugin, "Stopped"); } _pluginsStarted = false; } From 7274e45c9321de015f7efbc3fe491b4d00593143 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 14 Feb 2020 21:22:22 +0000 Subject: [PATCH 060/159] Implement main viewport API --- distribution/openrct2.d.ts | 8 +- src/openrct2-ui/scripting/ScUi.hpp | 9 + src/openrct2-ui/scripting/ScViewport.hpp | 302 +++++++++++++++++++++ src/openrct2-ui/scripting/UiExtensions.cpp | 1 + 4 files changed, 318 insertions(+), 2 deletions(-) create mode 100644 src/openrct2-ui/scripting/ScViewport.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 37950a3523..2093d931bd 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -442,7 +442,11 @@ export interface ToolDesc { callback: (e: ToolCallback) => void; } -export interface ViewportInfo { +export interface Viewport { + left: number; + top: number; + right: number; + bottom: number; rotation: number; zoom: number; visibilityFlags: number; @@ -456,7 +460,7 @@ export interface Ui { readonly width: number; readonly height: number; readonly windows: number; - readonly mainViewport: ViewportInfo; + readonly mainViewport: Viewport; getWindow(id: number): Window; getWindow(classification: string, id?: number): Window; diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index cd47708af6..fdedf11ae2 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -10,6 +10,7 @@ #pragma once #include "CustomMenu.h" +#include "ScViewport.hpp" #include "ScWindow.hpp" #include @@ -42,6 +43,7 @@ namespace OpenRCT2::Scripting { } + private: int32_t width_get() { return context_get_width(); @@ -55,6 +57,11 @@ namespace OpenRCT2::Scripting return static_cast(g_window_list.size()); } + std::shared_ptr mainViewport_get() + { + return std::make_shared(WC_MAIN_WINDOW); + } + std::shared_ptr openWindow(DukValue desc) { using namespace OpenRCT2::Ui::Windows; @@ -113,11 +120,13 @@ namespace OpenRCT2::Scripting CustomMenuItems.emplace_back(owner, text, callback); } + public: static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScUi::height_get, nullptr, "height"); dukglue_register_property(ctx, &ScUi::width_get, nullptr, "width"); dukglue_register_property(ctx, &ScUi::windows_get, nullptr, "windows"); + dukglue_register_property(ctx, &ScUi::mainViewport_get, nullptr, "mainViewport"); dukglue_register_method(ctx, &ScUi::openWindow, "openWindow"); dukglue_register_method(ctx, &ScUi::closeWindows, "closeWindows"); dukglue_register_method(ctx, &ScUi::closeAllWindows, "closeAllWindows"); diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp new file mode 100644 index 0000000000..f7a94d08fc --- /dev/null +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -0,0 +1,302 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 + +#include "../interface/Window.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace OpenRCT2::Scripting +{ + class ScViewport + { + private: + rct_windowclass _class{}; + rct_windownumber _number{}; + + public: + ScViewport(rct_windowclass c, rct_windownumber n = 0) + : _class(c) + , _number(n) + { + } + + private: + int32_t left_get() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + return viewport->view_x; + } + return 0; + } + void left_set(int32_t value) + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + SetViewLeftTop(value, viewport->view_y); + } + } + + int32_t top_get() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + return viewport->view_y; + } + return 0; + } + void top_set(int32_t value) + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + SetViewLeftTop(viewport->view_x, value); + } + } + + int32_t right_get() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + return viewport->view_x + viewport->view_width; + } + return 0; + } + void right_set(int32_t value) + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + SetViewLeftTop(value - viewport->view_width, viewport->view_y); + } + } + + int32_t bottom_get() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + return viewport->view_y + viewport->view_height; + } + return 0; + } + void bottom_set(int32_t value) + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + SetViewLeftTop(viewport->view_x, value - viewport->view_height); + } + } + + int32_t rotation_get() + { + return get_current_rotation(); + } + void rotation_set(int32_t value) + { + if (value >= 0 && value < 4) + { + auto w = GetWindow(); + if (w != nullptr) + { + while (get_current_rotation() != value) + { + window_rotate_camera(w, 1); + } + } + } + } + + int32_t zoom_get() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + return viewport->zoom; + } + return 0; + } + void zoom_set(int32_t value) + { + auto w = GetWindow(); + if (w != nullptr) + { + window_zoom_set(w, value, false); + } + } + + uint32_t visibilityFlags_get() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + return viewport->flags; + } + return 0; + } + void visibilityFlags_set(uint32_t value) + { + auto w = GetWindow(); + if (w != nullptr) + { + auto viewport = w->viewport; + if (viewport != nullptr) + { + if (viewport->flags != value) + { + viewport->flags = value; + w->Invalidate(); + } + } + } + } + + DukValue getCentrePosition() + { + auto viewport = GetViewport(); + if (viewport != nullptr) + { + auto centreX = viewport->view_x + (viewport->view_width / 2); + auto centreY = viewport->view_y + (viewport->view_height / 2); + auto coords = viewport_coord_to_map_coord(centreX, centreY, 24); + + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto obj = duk_push_object(ctx); + duk_push_number(ctx, coords.x); + duk_put_prop_string(ctx, obj, "x"); + duk_push_number(ctx, coords.y); + duk_put_prop_string(ctx, obj, "y"); + return DukValue::take_from_stack(ctx); + } + return {}; + } + + void moveTo(DukValue position) + { + auto w = GetWindow(); + if (w != nullptr) + { + auto viewport = w->viewport; + if (viewport != nullptr) + { + auto coords = GetCoordsFromObject(position); + if (coords) + { + auto screenCoords = translate_3d_to_2d_with_z(get_current_rotation(), *coords); + auto left = screenCoords.x - (viewport->view_width / 2); + auto top = screenCoords.y - (viewport->view_height / 2); + SetViewLeftTop(left, top); + } + } + } + } + + void scrollTo(DukValue position) + { + auto w = GetWindow(); + if (w != nullptr) + { + auto coords = GetCoordsFromObject(position); + if (coords) + { + window_scroll_to_location(w, coords->x, coords->y, coords->z); + } + } + } + + public: + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &left_get, &left_set, "left"); + dukglue_register_property(ctx, &top_get, &top_set, "top"); + dukglue_register_property(ctx, &right_get, &right_set, "right"); + dukglue_register_property(ctx, &bottom_get, &bottom_set, "bottom"); + dukglue_register_property(ctx, &rotation_get, &rotation_set, "rotation"); + dukglue_register_property(ctx, &zoom_get, &zoom_set, "zoom"); + dukglue_register_property(ctx, &visibilityFlags_get, &visibilityFlags_set, "visibilityFlags"); + dukglue_register_method(ctx, &getCentrePosition, "getCentrePosition"); + dukglue_register_method(ctx, &moveTo, "moveTo"); + dukglue_register_method(ctx, &scrollTo, "scrollTo"); + } + + private: + rct_window* GetWindow() + { + if (_class == WC_MAIN_WINDOW) + return window_get_main(); + else + return window_find_by_number(_class, _number); + } + + rct_viewport* GetViewport() + { + auto w = GetWindow(); + if (w != nullptr) + { + return w->viewport; + } + return nullptr; + } + + void SetViewLeftTop(int32_t left, int32_t top) + { + auto w = GetWindow(); + if (w != nullptr) + { + auto viewport = w->viewport; + if (viewport != nullptr) + { + viewport->view_x = left; + viewport->view_y = top; + viewport->flags &= ~WF_SCROLLING_TO_LOCATION; + w->saved_view_x = viewport->view_x; + w->saved_view_y = viewport->view_y; + } + } + } + + std::optional GetCoordsFromObject(DukValue position) + { + if (position.type() == DukValue::Type::OBJECT) + { + auto dukX = position["x"]; + auto dukY = position["y"]; + auto dukZ = position["z"]; + if (dukX.type() == DukValue::Type::NUMBER && dukY.type() == DukValue::Type::NUMBER) + { + auto x = dukX.as_int(); + auto y = dukY.as_int(); + if (dukZ.type() == DukValue::Type::NUMBER) + { + return CoordsXYZ(x, y, dukZ.as_int()); + } + else + { + auto z = tile_element_height(CoordsXY(x, y)); + return CoordsXYZ(x, y, z); + } + } + } + return {}; + } + }; +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index 84b23901f2..c2c959bb6f 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -24,6 +24,7 @@ void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) dukglue_register_global(ctx, std::make_shared(scriptEngine), "ui"); ScUi::Register(ctx); + ScViewport::Register(ctx); ScWindow::Register(ctx); InitialiseCustomMenuItems(scriptEngine); From b1cf6fcf63db218457c1249ba264e8f39816fcdb Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 14 Feb 2020 23:36:24 +0000 Subject: [PATCH 061/159] Implement Widget API --- src/openrct2-ui/scripting/CustomWindow.cpp | 20 ++ src/openrct2-ui/scripting/CustomWindow.h | 17 ++ src/openrct2-ui/scripting/ScWidget.hpp | 235 +++++++++++++++++++++ src/openrct2-ui/scripting/ScWindow.hpp | 19 ++ src/openrct2-ui/scripting/UiExtensions.cpp | 2 + 5 files changed, 293 insertions(+) create mode 100644 src/openrct2-ui/scripting/CustomWindow.h create mode 100644 src/openrct2-ui/scripting/ScWidget.hpp diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index ebbbb7a2a9..a5d02962a0 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -234,6 +234,11 @@ namespace OpenRCT2::Ui::Windows } return nullptr; } + + CustomWidgetDesc* GetCustomWidgetDesc(size_t widgetIndex) + { + return const_cast(std::as_const(*this).GetCustomWidgetDesc(widgetIndex)); + } }; static rct_windownumber _nextWindowNumber; @@ -529,4 +534,19 @@ namespace OpenRCT2::Ui::Windows } } } + + void UpdateWidgetText(rct_window* w, rct_widgetindex widgetIndex, const std::string& value) + { + if (w->custom_info != nullptr) + { + auto &customInfo = GetInfo(w); + auto customWidgetInfo = customInfo.GetCustomWidgetDesc(widgetIndex); + if (customWidgetInfo != nullptr) + { + customWidgetInfo->Text = CustomWidgetDesc::ProcessString(value); + w->widgets[widgetIndex].string = customWidgetInfo->Text.data(); + } + } + } + } // namespace OpenRCT2::Ui::Windows diff --git a/src/openrct2-ui/scripting/CustomWindow.h b/src/openrct2-ui/scripting/CustomWindow.h new file mode 100644 index 0000000000..ba81fcd91c --- /dev/null +++ b/src/openrct2-ui/scripting/CustomWindow.h @@ -0,0 +1,17 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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. + *****************************************************************************/ + +#include "../interface/Window.h" + +#include + +namespace OpenRCT2::Ui::Windows +{ + void UpdateWidgetText(rct_window* w, rct_widgetindex widget, const std::string& value); +} diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp new file mode 100644 index 0000000000..d06141fbf4 --- /dev/null +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -0,0 +1,235 @@ +/***************************************************************************** + * Copyright (c) 2014-2018 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 + +#include "../interface/Widget.h" +#include "../interface/Window.h" +#include "CustomWindow.h" + +#include +#include +#include +#include +#include + +namespace OpenRCT2::Scripting +{ + class ScWidget + { + private: + rct_windowclass _class{}; + rct_windownumber _number{}; + rct_widgetindex _widgetIndex{}; + + public: + ScWidget(rct_windowclass c, rct_windownumber n, rct_widgetindex widgetIndex) + : _class(c) + , _number(n) + , _widgetIndex(widgetIndex) + { + } + + private: + std::string type_get() + { + auto widget = GetWidget(); + if (widget != nullptr) + { + switch (widget->type) + { + case WWT_FRAME: + return "frame"; + case WWT_RESIZE: + return "resize"; + case WWT_IMGBTN: + case WWT_COLOURBTN: + case WWT_TRNBTN: + case WWT_FLATBTN: + case WWT_BUTTON: + case WWT_CLOSEBOX: + return "button"; + case WWT_TAB: + return "tab"; + case WWT_LABEL_CENTRED: + case WWT_LABEL: + return "label"; + case WWT_TABLE_HEADER: + return "table_header"; + case WWT_SPINNER: + return "spinner"; + case WWT_DROPDOWN: + return "dropdown"; + case WWT_VIEWPORT: + return "viewport"; + case WWT_GROUPBOX: + return "groupbox"; + case WWT_CAPTION: + return "caption"; + case WWT_SCROLL: + return "scroll_view"; + case WWT_CHECKBOX: + return "checkbox"; + case WWT_TEXT_BOX: + return "textbox"; + } + } + return "unknown"; + } + + int32_t x_get() + { + auto widget = GetWidget(); + if (widget != nullptr) + { + return widget->left; + } + return 0; + } + void x_set(int32_t value) + { + auto widget = GetWidget(); + if (widget != nullptr) + { + Invalidate(); + widget->left = value; + Invalidate(); + } + } + + int32_t y_get() + { + auto widget = GetWidget(); + if (widget != nullptr) + { + return widget->top; + } + return 0; + } + void y_set(int32_t value) + { + auto widget = GetWidget(); + if (widget != nullptr) + { + Invalidate(); + widget->top = value; + Invalidate(); + } + } + + int32_t width_get() + { + auto widget = GetWidget(); + if (widget != nullptr) + { + return widget->right - widget->left; + } + return 0; + } + void width_set(int32_t value) + { + auto widget = GetWidget(); + if (widget != nullptr) + { + Invalidate(); + widget->right = widget->left + value; + Invalidate(); + } + } + + int32_t height_get() + { + auto widget = GetWidget(); + if (widget != nullptr) + { + return widget->bottom - widget->top; + } + return 0; + } + void height_set(int32_t value) + { + auto widget = GetWidget(); + if (widget != nullptr) + { + Invalidate(); + widget->bottom = widget->top + value; + Invalidate(); + } + } + + std::string text_get() + { + if (IsCustomWindow()) + { + auto widget = GetWidget(); + if (widget != nullptr && widget->string != nullptr) + { + return widget->string; + } + } + return ""; + } + void text_set(std::string value) + { + auto w = GetWindow(); + if (w != nullptr && IsCustomWindow()) + { + OpenRCT2::Ui::Windows::UpdateWidgetText(w, _widgetIndex, value); + } + } + + public: + static void Register(duk_context* ctx) + { + // Common + dukglue_register_property(ctx, &type_get, nullptr, "type"); + dukglue_register_property(ctx, &x_get, &x_set, "x"); + dukglue_register_property(ctx, &y_get, &y_set, "y"); + dukglue_register_property(ctx, &width_get, &width_set, "width"); + dukglue_register_property(ctx, &height_get, &height_set, "height"); + + // No so common + dukglue_register_property(ctx, &text_get, &text_set, "text"); + } + + private: + rct_window* GetWindow() + { + if (_class == WC_MAIN_WINDOW) + return window_get_main(); + else + return window_find_by_number(_class, _number); + } + + rct_widget* GetWidget() + { + auto w = GetWindow(); + if (w != nullptr) + { + return &w->widgets[_widgetIndex]; + } + return nullptr; + } + + bool IsCustomWindow() + { + auto w = GetWindow(); + if (w != nullptr) + { + return w->classification == WC_CUSTOM; + } + return false; + } + + void Invalidate() + { + widget_invalidate_by_number(_class, _number, _widgetIndex); + } + }; +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 44ac133ed7..8bd94a0958 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -9,6 +9,8 @@ #pragma once +#include "ScWidget.hpp" + #include #include #include @@ -66,6 +68,22 @@ namespace OpenRCT2::Scripting return (flags & (WF_STICK_TO_BACK | WF_STICK_TO_FRONT)) != 0; } + std::vector> widgets_get() + { + std::vector> result; + auto w = GetWindow(); + if (w != nullptr) + { + rct_widgetindex widgetIndex = 0; + for (auto widget = w->widgets; widget->type != WWT_LAST; widget++) + { + result.push_back(std::make_shared(_class, _number, widgetIndex)); + widgetIndex++; + } + } + return result; + } + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); @@ -73,6 +91,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScWindow::width_get, nullptr, "width"); dukglue_register_property(ctx, &ScWindow::height_get, nullptr, "height"); dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); + dukglue_register_property(ctx, &ScWindow::widgets_get, nullptr, "widgets"); } private: diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index c2c959bb6f..0eb68ea9d6 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -11,6 +11,7 @@ #include "CustomMenu.h" #include "ScUi.hpp" +#include "ScWidget.hpp" #include "ScWindow.hpp" #include @@ -25,6 +26,7 @@ void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) ScUi::Register(ctx); ScViewport::Register(ctx); + ScWidget::Register(ctx); ScWindow::Register(ctx); InitialiseCustomMenuItems(scriptEngine); From a9a67a7a7e2db334887e279b0a14d031d452ecff Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 15 Feb 2020 14:19:11 +0000 Subject: [PATCH 062/159] Implement group boxes --- distribution/openrct2.d.ts | 2 +- src/openrct2-ui/interface/Widget.cpp | 19 +++++++++++++++++-- src/openrct2-ui/scripting/CustomWindow.cpp | 9 ++++++++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 2093d931bd..bf3058ba13 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -326,7 +326,7 @@ export interface Park { * Represents the type of a widget, e.g. button or label. */ export type WidgetType = - "button" | "dropdown" | "label" | "tabview" | "viewport"; + "button" | "dropdown" | "groupbox" | "label" | "tabview" | "viewport"; export interface Widget { type: WidgetType; diff --git a/src/openrct2-ui/interface/Widget.cpp b/src/openrct2-ui/interface/Widget.cpp index 7f4072b40f..78f2d7311e 100644 --- a/src/openrct2-ui/interface/Widget.cpp +++ b/src/openrct2-ui/interface/Widget.cpp @@ -455,7 +455,22 @@ static void widget_groupbox_draw(rct_drawpixelinfo* dpi, rct_window* w, rct_widg int32_t textRight = l; // Text - if (widget->text != STR_NONE) + auto stringId = widget->text; + void* formatArgs = gCommonFormatArgs; + if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) + { + if (widget->string == nullptr || widget->string[0] == '\0') + { + stringId = STR_NONE; + formatArgs = nullptr; + } + else + { + stringId = STR_STRING; + formatArgs = &widget->string; + } + } + if (stringId != STR_NONE) { uint8_t colour = w->colours[widget->colour] & 0x7F; if (widget_is_disabled(w, widgetIndex)) @@ -463,7 +478,7 @@ static void widget_groupbox_draw(rct_drawpixelinfo* dpi, rct_window* w, rct_widg utf8 buffer[512] = { 0 }; uint8_t args[sizeof(uintptr_t)] = { 0 }; - format_string(buffer, sizeof(buffer), widget->text, gCommonFormatArgs); + format_string(buffer, sizeof(buffer), stringId, formatArgs); Formatter(args).Add(buffer); gfx_draw_string_left(dpi, STR_STRING, args, colour, l, t); textRight = l + gfx_get_string_width(buffer) + 1; diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index a5d02962a0..80834e61cb 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -137,7 +137,7 @@ namespace OpenRCT2::Ui::Windows result.SelectedIndex = desc["selectedIndex"].as_int(); result.OnChange = desc["onChange"]; } - else if (result.Type == "label") + else if (result.Type == "groupbox" || result.Type == "label") { result.Text = ProcessString(desc["text"].as_string()); } @@ -460,6 +460,13 @@ namespace OpenRCT2::Ui::Windows widget.flags |= WIDGET_FLAGS::IS_ENABLED; widgetList.push_back(widget); } + else if (desc.Type == "groupbox") + { + widget.type = WWT_GROUPBOX; + widget.string = (utf8*)desc.Text.c_str(); + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + widgetList.push_back(widget); + } else if (desc.Type == "label") { widget.type = WWT_LABEL; From da98ef63d37b97a12a22dacb5efcafda6c085600 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 15 Feb 2020 15:07:10 +0000 Subject: [PATCH 063/159] Implement checkboxes and disabling widgets --- distribution/openrct2.d.ts | 9 ++- src/openrct2-ui/interface/Widget.cpp | 39 +++++++------ src/openrct2-ui/scripting/CustomWindow.cpp | 66 ++++++++++++++++++++-- src/openrct2-ui/scripting/ScWidget.hpp | 42 ++++++++++++++ src/openrct2/interface/Window.h | 2 + 5 files changed, 136 insertions(+), 22 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index bf3058ba13..5d3dc92d81 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -326,7 +326,7 @@ export interface Park { * Represents the type of a widget, e.g. button or label. */ export type WidgetType = - "button" | "dropdown" | "groupbox" | "label" | "tabview" | "viewport"; + "button" | "checkbox" | "dropdown" | "groupbox" | "label" | "tabview" | "viewport"; export interface Widget { type: WidgetType; @@ -334,6 +334,7 @@ export interface Widget { y: number; width: number; height: number; + isDisabled: boolean; } export interface ButtonWidget extends Widget { @@ -341,6 +342,12 @@ export interface ButtonWidget extends Widget { onClick: () => void; } +export interface CheckboxWidget extends Widget { + text: string; + isChecked: number; + onChanged: (isChecked: boolean) => void; +} + export interface DropdownWidget extends Widget { items: string[]; selectedIndex: number; diff --git a/src/openrct2-ui/interface/Widget.cpp b/src/openrct2-ui/interface/Widget.cpp index 78f2d7311e..a4bc08c884 100644 --- a/src/openrct2-ui/interface/Widget.cpp +++ b/src/openrct2-ui/interface/Widget.cpp @@ -438,6 +438,26 @@ static void widget_text_inset(rct_drawpixelinfo* dpi, rct_window* w, rct_widgeti widget_text(dpi, w, widgetIndex); } +static std::pair widget_get_stringid_and_args(const rct_widget* widget) +{ + auto stringId = widget->text; + void* formatArgs = gCommonFormatArgs; + if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) + { + if (widget->string == nullptr || widget->string[0] == '\0') + { + stringId = STR_NONE; + formatArgs = nullptr; + } + else + { + stringId = STR_STRING; + formatArgs = (void*)&widget->string; + } + } + return std::make_pair(stringId, formatArgs); +} + /** * * rct2: 0x006EB535 @@ -455,21 +475,7 @@ static void widget_groupbox_draw(rct_drawpixelinfo* dpi, rct_window* w, rct_widg int32_t textRight = l; // Text - auto stringId = widget->text; - void* formatArgs = gCommonFormatArgs; - if (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) - { - if (widget->string == nullptr || widget->string[0] == '\0') - { - stringId = STR_NONE; - formatArgs = nullptr; - } - else - { - stringId = STR_STRING; - formatArgs = &widget->string; - } - } + auto [stringId, formatArgs] = widget_get_stringid_and_args(widget); if (stringId != STR_NONE) { uint8_t colour = w->colours[widget->colour] & 0x7F; @@ -639,7 +645,8 @@ static void widget_checkbox_draw(rct_drawpixelinfo* dpi, rct_window* w, rct_widg if (widget->text == STR_NONE) return; - gfx_draw_string_left_centred(dpi, widget->text, gCommonFormatArgs, colour, l + 14, yMid); + auto [stringId, formatArgs] = widget_get_stringid_and_args(widget); + gfx_draw_string_left_centred(dpi, stringId, formatArgs, colour, l + 14, yMid); } /** diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 80834e61cb..ceb7e3b292 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -91,11 +91,20 @@ namespace OpenRCT2::Ui::Windows std::string Text; std::vector Items; int32_t SelectedIndex{}; + bool IsChecked{}; + bool IsDisabled{}; // Event handlers DukValue OnClick; DukValue OnChange; + static std::string ProcessString(const DukValue& value) + { + if (value.type() == DukValue::Type::STRING) + return ProcessString(value.as_string()); + return {}; + } + static std::string ProcessString(const std::string_view& s) { std::string result; @@ -124,22 +133,32 @@ namespace OpenRCT2::Ui::Windows result.Height = desc["height"].as_int(); if (result.Type == "button") { - result.Text = desc["text"].as_string(); + result.Text = ProcessString(desc["text"]); result.OnClick = desc["onClick"]; } + else if (result.Type == "checkbox") + { + result.Text = ProcessString(desc["text"]); + auto dukIsChecked = desc["isChecked"]; + if (dukIsChecked.type() == DukValue::Type::BOOLEAN) + { + result.IsChecked = dukIsChecked.as_bool(); + } + result.OnChange = desc["onChange"]; + } else if (result.Type == "dropdown") { auto dukItems = desc["items"].as_array(); for (const auto& dukItem : dukItems) { - result.Items.push_back(dukItem.as_string()); + result.Items.push_back(ProcessString(dukItem)); } result.SelectedIndex = desc["selectedIndex"].as_int(); result.OnChange = desc["onChange"]; } else if (result.Type == "groupbox" || result.Type == "label") { - result.Text = ProcessString(desc["text"].as_string()); + result.Text = ProcessString(desc["text"]); } return result; } @@ -312,6 +331,20 @@ namespace OpenRCT2::Ui::Windows { InvokeEventHandler(info.Owner, widgetDesc->OnClick); } + else if (widgetDesc->Type == "checkbox") + { + auto& widget = w->widgets[widgetIndex]; + widget.flags ^= WIDGET_FLAGS::IS_PRESSED; + bool isChecked = widget.flags & WIDGET_FLAGS::IS_PRESSED; + + widget_set_checkbox_value(w, widgetIndex, isChecked); + + std::vector args; + auto ctx = widgetDesc->OnChange.context(); + duk_push_boolean(ctx, isChecked); + args.push_back(DukValue::take_from_stack(ctx)); + InvokeEventHandler(info.Owner, widgetDesc->OnChange, args); + } } break; } @@ -429,6 +462,8 @@ namespace OpenRCT2::Ui::Windows widget.bottom = desc.Y + desc.Height; widget.tooltip = STR_NONE; widget.flags = WIDGET_FLAGS::IS_ENABLED; + if (desc.IsDisabled) + widget.flags |= WIDGET_FLAGS::IS_DISABLED; if (desc.Type == "button") { @@ -437,6 +472,17 @@ namespace OpenRCT2::Ui::Windows widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); } + else if (desc.Type == "checkbox") + { + widget.type = WWT_CHECKBOX; + widget.string = (utf8*)desc.Text.c_str(); + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + if (desc.IsChecked) + { + widget.flags |= WIDGET_FLAGS::IS_PRESSED; + } + widgetList.push_back(widget); + } else if (desc.Type == "dropdown") { widget.type = WWT_DROPDOWN; @@ -510,9 +556,19 @@ namespace OpenRCT2::Ui::Windows w->enabled_widgets = 1ULL << WIDX_CLOSE; for (size_t i = 0; i < std::min(widgets.size(), 64); i++) { - if (widgets[i].flags & WIDGET_FLAGS::IS_ENABLED) + auto mask = 1ULL << i; + auto flags = widgets[i].flags; + if (flags & WIDGET_FLAGS::IS_ENABLED) { - w->enabled_widgets |= 1ULL << i; + w->enabled_widgets |= mask; + } + if (flags & WIDGET_FLAGS::IS_PRESSED) + { + w->pressed_widgets |= mask; + } + if (flags & WIDGET_FLAGS::IS_DISABLED) + { + w->disabled_widgets |= mask; } } } diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index d06141fbf4..afec19de5a 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -163,6 +163,46 @@ namespace OpenRCT2::Scripting } } + bool isDisabled_get() + { + auto w = GetWindow(); + if (w != nullptr) + { + return widget_is_disabled(w, _widgetIndex); + } + return false; + } + void isDisabled_set(bool value) + { + auto w = GetWindow(); + if (w != nullptr) + { + auto mask = 1ULL << _widgetIndex; + if (value) + w->disabled_widgets |= mask; + else + w->disabled_widgets &= ~mask; + } + } + + bool isChecked_get() + { + auto w = GetWindow(); + if (w != nullptr) + { + return widget_is_pressed(w, _widgetIndex); + } + return false; + } + void isChecked_set(bool value) + { + auto w = GetWindow(); + if (w != nullptr) + { + widget_set_checkbox_value(w, _widgetIndex, value ? 1 : 0); + } + } + std::string text_get() { if (IsCustomWindow()) @@ -193,9 +233,11 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &y_get, &y_set, "y"); dukglue_register_property(ctx, &width_get, &width_set, "width"); dukglue_register_property(ctx, &height_get, &height_set, "height"); + dukglue_register_property(ctx, &isDisabled_get, &isDisabled_set, "isDisabled"); // No so common dukglue_register_property(ctx, &text_get, &text_set, "text"); + dukglue_register_property(ctx, &isChecked_get, &isChecked_set, "isChecked"); } private: diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index fa3ddbedf6..8b3704afb0 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -69,6 +69,8 @@ namespace WIDGET_FLAGS { const WidgetFlags TEXT_IS_STRING = 1 << 0; const WidgetFlags IS_ENABLED = 1 << 1; + const WidgetFlags IS_PRESSED = 1 << 2; + const WidgetFlags IS_DISABLED = 1 << 3; } // namespace WIDGET_FLAGS /** From e0f66fe3cd5b50f0e3cd35980b046e674eb9c466 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 15 Feb 2020 17:09:41 +0000 Subject: [PATCH 064/159] Implement viewport widgets --- distribution/openrct2.d.ts | 3 +- src/openrct2-ui/scripting/CustomWindow.cpp | 59 +++++++++++++++++++++- src/openrct2-ui/scripting/ScWidget.hpp | 16 ++++++ src/openrct2/interface/Window.cpp | 2 + 4 files changed, 77 insertions(+), 3 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 5d3dc92d81..1193b2d0ac 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -359,8 +359,7 @@ export interface LabelWidget extends Widget { } export interface ViewportWidget extends Widget { - target: null | number | Coord3; - zoom: number; + viewport: Viewport } export interface Tab { diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index ceb7e3b292..41c44877e6 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,7 @@ namespace OpenRCT2::Ui::Windows static void window_custom_dropdown(rct_window* w, rct_widgetindex widgetIndex, int32_t dropdownIndex); static void window_custom_invalidate(rct_window* w); static void window_custom_paint(rct_window* w, rct_drawpixelinfo* dpi); + static void window_custom_update_viewport(rct_window* w); static rct_window_event_list window_custom_events = { window_custom_close, window_custom_mouseup, @@ -305,6 +307,7 @@ namespace OpenRCT2::Ui::Windows } RefreshWidgets(window); window_init_scroll_widgets(window); + window_custom_update_viewport(window); return window; } @@ -367,6 +370,7 @@ namespace OpenRCT2::Ui::Windows w->height = w->min_height; } } + window_custom_update_viewport(w); } static void window_custom_mousedown(rct_window* w, rct_widgetindex widgetIndex, rct_widget* widget) @@ -435,6 +439,52 @@ namespace OpenRCT2::Ui::Windows static void window_custom_paint(rct_window* w, rct_drawpixelinfo* dpi) { window_draw_widgets(w, dpi); + if (w->viewport != nullptr) + { + window_draw_viewport(dpi, w); + } + } + + static std::optional GetViewportWidgetIndex(rct_window* w) + { + rct_widgetindex widgetIndex = 0; + for (auto widget = w->widgets; widget->type != WWT_LAST; widget++) + { + if (widget->type == WWT_VIEWPORT) + { + return widgetIndex; + } + widgetIndex++; + } + return 0; + } + + static void window_custom_update_viewport(rct_window* w) + { + auto viewportWidgetIndex = GetViewportWidgetIndex(w); + if (viewportWidgetIndex) + { + auto viewportWidget = &w->widgets[*viewportWidgetIndex]; + auto& customInfo = GetInfo(w); + auto widgetInfo = customInfo.GetCustomWidgetDesc(*viewportWidgetIndex); + if (widgetInfo != nullptr) + { + if (w->viewport == nullptr) + { + auto left = w->x + viewportWidget->left + 1; + auto top = w->y + viewportWidget->top + 1; + auto width = (viewportWidget->right - viewportWidget->left) - 1; + auto height = (viewportWidget->bottom - viewportWidget->top) - 1; + auto mapX = 0; + auto mapY = 0; + auto mapZ = 0; + viewport_create( + w, left, top, width, height, 0, mapX, mapY, mapZ, VIEWPORT_FOCUS_TYPE_COORDINATE, SPRITE_INDEX_NULL); + w->flags |= WF_NO_SCROLLING; + w->Invalidate(); + } + } + } } static CustomWindowInfo& GetInfo(rct_window* w) @@ -460,6 +510,7 @@ namespace OpenRCT2::Ui::Windows widget.top = desc.Y; widget.right = desc.X + desc.Width; widget.bottom = desc.Y + desc.Height; + widget.content = std::numeric_limits::max(); widget.tooltip = STR_NONE; widget.flags = WIDGET_FLAGS::IS_ENABLED; if (desc.IsDisabled) @@ -520,6 +571,12 @@ namespace OpenRCT2::Ui::Windows widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); } + else if (desc.Type == "viewport") + { + widget.type = WWT_VIEWPORT; + widget.text = STR_NONE; + widgetList.push_back(widget); + } } static void RefreshWidgets(rct_window* w) @@ -602,7 +659,7 @@ namespace OpenRCT2::Ui::Windows { if (w->custom_info != nullptr) { - auto &customInfo = GetInfo(w); + auto& customInfo = GetInfo(w); auto customWidgetInfo = customInfo.GetCustomWidgetDesc(widgetIndex); if (customWidgetInfo != nullptr) { diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index afec19de5a..d86b84f602 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -12,6 +12,7 @@ #include "../interface/Widget.h" #include "../interface/Window.h" #include "CustomWindow.h" +#include "ScViewport.hpp" #include #include @@ -224,6 +225,20 @@ namespace OpenRCT2::Scripting } } + std::shared_ptr viewport_get() + { + auto w = GetWindow(); + if (w != nullptr && IsCustomWindow()) + { + auto widget = GetWidget(); + if (widget != nullptr && widget->type == WWT_VIEWPORT) + { + return std::make_shared(w->classification, w->number); + } + } + return {}; + } + public: static void Register(duk_context* ctx) { @@ -238,6 +253,7 @@ namespace OpenRCT2::Scripting // No so common dukglue_register_property(ctx, &text_get, &text_set, "text"); dukglue_register_property(ctx, &isChecked_get, &isChecked_set, "isChecked"); + dukglue_register_property(ctx, &viewport_get, nullptr, "viewport"); } private: diff --git a/src/openrct2/interface/Window.cpp b/src/openrct2/interface/Window.cpp index a1316f2859..4cb29bd83e 100644 --- a/src/openrct2/interface/Window.cpp +++ b/src/openrct2/interface/Window.cpp @@ -1009,6 +1009,8 @@ void window_viewport_centre_tile_around_cursor(rct_window* w, int16_t map_x, int void window_zoom_set(rct_window* w, ZoomLevel zoomLevel, bool atCursor) { rct_viewport* v = w->viewport; + if (v == nullptr) + return; zoomLevel = std::clamp(zoomLevel, ZoomLevel::min(), ZoomLevel::max()); if (v->zoom == zoomLevel) From b93e5b3456201cd7d451553b864b7d4bbe52550c Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 18 Feb 2020 22:31:43 +0000 Subject: [PATCH 065/159] Fix d.ts so it works correctly in TypeScript and GameDate --- distribution/openrct2.d.ts | 1110 ++++++++++++++++++------------------ 1 file changed, 570 insertions(+), 540 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 1193b2d0ac..992fa34ab4 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -17,549 +17,579 @@ export type PluginType = "server" | "client" | "server_client"; -export interface PluginMetadata { - name: string; - version: string; - authors: string | string[]; - type: PluginType; - minApiVersion: number; - main: () => void; -} - -export interface Console { - clear(): void; - log(message?: any, ...optionalParams: any[]): void; -} - -export interface Configuration { - getAll(pattern: string): { [name: string]: any }; - get(key: string): T | undefined; - get(key: string, defaultValue: T): T; - set(key: string, value: T): void; - has(key: string): boolean; -} - -export interface Coord2 { - x: number; - y: number; -} - -export interface Coord3 { - x: number; - y: number; - z: number; -} - -export type HookType = - "interval.tick" | "interval.day" | - "network.chat" | "network.action" | "network.join" | "network.leave"; - -export type ExpenditureType = - "ride_construction" | - "ride_runningcosts" | - "land_purchase" | - "landscaping" | - "park_entrance_tickets" | - "park_ride_tickets" | - "shop_sales" | - "shop_stock" | - "food_drink_sales" | - "food_drink_stock" | - "wages" | - "marketing" | - "research" | - "interest"; - -export interface GameActionResult { - error: string; - errorTitle: string; - errorMessage: string; - position: Coord3; - cost: number; - expenditureType: ExpenditureType; -} - -export interface GameActionDesc { - id: string; - query: (args: object) => GameActionResult; - execute: (args: object) => GameActionResult; -} - -export interface NetworkEventArgs { - readonly player: number; -} - -export interface NetworkActionEventArgs extends NetworkEventArgs { - readonly type: string; - result: GameActionResult; -} - -export interface NetworkChatEventArgs extends NetworkEventArgs { - message: string; -} - -export interface Context { - /** - * The user's current configuration. - */ - configuration: Configuration; - - /** - * Shared generic storage for all plugins. - */ - sharedStorage: Configuration; - - /** - * Local generic storage for a each plugin. - */ - localStorage: Configuration; - - /** - * Registers a new intent (command) that can be mapped to a shortcut. - */ - registerIntent(desc: IntentDesc): void; - - /** - * Registers a new game action that allows clients to interact with the game. - */ - registerGameAction(desc: GameActionDesc): void; - - /** - * Subscribes to the given hook. - */ - subscribe(hook: HookType, callback: Function): IDisposable; - - subscribe(hook: "interval.tick", callback: () => void): IDisposable; - subscribe(hook: "interval.day", callback: () => void): IDisposable; - subscribe(hook: "network.action", callback: (e: NetworkActionEventArgs) => void): IDisposable; - subscribe(hook: "network.chat", callback: (e: NetworkChatEventArgs) => void): IDisposable; - subscribe(hook: "network.join", callback: (e: NetworkEventArgs) => void): IDisposable; - subscribe(hook: "network.leave", callback: (e: NetworkEventArgs) => void): IDisposable; -} - -export interface IntentDesc -{ - key: string; - title?: string; - shortcut?: string; - action: Function; -} - -export interface IDisposable { - dispose(): void; -} - -export type TileElementType = - "surface" | "footpath" | "track" | "small_scenery" | "entrance" | "large_scenery" | "banner"; - -export interface BaseTileElement { - type: TileElementType; - baseHeight: number; - clearanceHeight: number; - broken: boolean; -} - -// export interface TileElement extends BaseTileElement { -// /** -// * Gets the element as a specific type to access its properties -// */ -// asSurface(): SurfaceElement | null; -// asFootpath(): FootpathElement | null; -// asTrack(): TrackElement | null; -// asSmallScenery(): SmallSceneryElement | null; -// asEntrance(): EntranceElement | null; -// asWall(): WallElement | null; -// asLargeScenery(): LargeSceneryElement | null; -// asBanner(): BannerElement | null; -// asCorruptElement(): CorruptElement | null; -// } - -export type TileElement = SurfaceElement | FootpathElement | TrackElement; - -export interface SurfaceElement extends BaseTileElement { - slope: number; - terrain: number; - waterHeight: number; - grassLength: number; - ownership: number; - parkFences: number; -} - -export interface FootpathAdditionStatus extends BaseTileElement { - north: number; - east: number; - south: number; - west: number; -} - -export interface FootpathAddition extends BaseTileElement { - type: number; - isBin: boolean; - isBench: boolean; - isLamp: boolean; - isBreakable: boolean; - isJumpingFountainWater: boolean; - isJumpingFountainSnow: boolean; - allowedOnQueue: boolean; - allowedOnSlope: boolean; - isQueueScreen: boolean; - status: FootpathAdditionStatus; - - /** - * Remove the path addition - */ - remove(): void; -} - -export interface FootpathElement extends BaseTileElement { - footpathType: number; - isSloped: boolean; - isQueue: boolean; - addition: FootpathAddition; - edges: number; - corners: number; - rideIndex: number; -} - -export interface TrackElement extends BaseTileElement { -} - -export interface SmallSceneryElement extends BaseTileElement { -} - -export interface EntranceElement extends BaseTileElement { -} - -export interface WallElement extends BaseTileElement { -} - -export interface LargeSceneryElement extends BaseTileElement { -} - -export interface BannerElement extends BaseTileElement { -} - -export interface CorruptElement extends BaseTileElement { -} - -export interface Tile { - readonly x: number; - readonly y: number; - elements: TileElement[]; - - getElement(index: number): TileElement; -} - -export interface Object { - readonly identifier: string; - readonly name: string; -} - -export interface RideObject extends Object { - readonly description: string; - readonly capacity: string; -} - -export interface Ride { - readonly object: RideObject; - readonly id: number; - type: string; - name: string; - excitement: number; - intensity: number; - nausea: number; - totalCustomers: number; -} - -export type ThingType = - "car" | "duck" | "peep"; - -export interface Thing { - readonly type: ThingType; - x: number; - y: number; - z: number; - - asPeep(): Thing | null; -} - -export interface Peep extends Thing { - tshirt: number; - trousers: number; -} - -export interface Map { - readonly size: { x: number; y: number; }; - readonly rides: number; - readonly things: number; - - getRide(id: number): Ride; - getTile(x: number, y: number): Tile; - getThing(id: number): Thing; -} - -export type ParkMessageType = - "attraction" | "peep_on_attraction" | "peep" | "money" | "blank" | "research" | "guests" | "award" | "chart"; - -export interface ParkMessage { - type: ParkMessageType; - text: string; -} - -export interface Park { - cash: number; - rating: number; - bankLoan: number; - maxBankLoan: number; - - postMessage(message: string): void; - postMessage(message: ParkMessage): void; -} - -/** - * User Interface APIs - * These will only be available to servers and clients that are not running headless mode. - * Plugin writers should check if ui is available using `typeof ui !== 'undefined'`. - */ - -/** - * Represents the type of a widget, e.g. button or label. - */ -export type WidgetType = - "button" | "checkbox" | "dropdown" | "groupbox" | "label" | "tabview" | "viewport"; - -export interface Widget { - type: WidgetType; - x: number; - y: number; - width: number; - height: number; - isDisabled: boolean; -} - -export interface ButtonWidget extends Widget { - text: string; - onClick: () => void; -} - -export interface CheckboxWidget extends Widget { - text: string; - isChecked: number; - onChanged: (isChecked: boolean) => void; -} - -export interface DropdownWidget extends Widget { - items: string[]; - selectedIndex: number; - onChanged: (index: number) => void; -} - -export interface LabelWidget extends Widget { - text: string; -} - -export interface ViewportWidget extends Widget { - viewport: Viewport -} - -export interface Tab { - image: number; - tooltip: string; - widgets: Widget[]; -} - -export interface Window { - id: number; - classification: string; - x: number; - y: number; - width: number; - height: number; - isSticky: boolean; - colours: number[]; - title: string; - widgets: Widget[]; - - close(): void; -} - -export interface TabbedWindow extends Window { - tabs: Tab[]; - activeTabIndex: number; - - onTabChanged: (index: number) => void; -} - -export interface WindowDesc { - classification: string; - x?: number; - y?: number; - width: number; - height: number; - title: string; - id?: number; - minWidth?: number; - minHeight?: number; - widgets?: Widget[]; - tabs?: Tab[]; -} - -export type ToolCallbackType = "move" | "press" | "release"; - -export interface ToolCallback { - type: ToolCallbackType; - tiles: Coord2[]; -} - -export type CursorType = - "arrow" | - "blank" | - "up_arrow" | - "up_down_arrow" | - "hand_point" | - "zzz" | - "diagonal_arrows" | - "picker" | - "tree_down" | - "fountain_down" | - "statue_down" | - "bench_down" | - "cross_hair" | - "bin_down" | - "lamppost_down" | - "fence_down" | - "flower_down" | - "path_down" | - "dig_down" | - "water_down" | - "house_down" | - "volcano_down" | - "walk_down" | - "paint_down" | - "entrance_down" | - "hand_open" | - "hand_closed"; - -export interface ToolDesc { - id: string; - cursor: CursorType; - width: number; - height: number; - callback: (e: ToolCallback) => void; -} - -export interface Viewport { - left: number; - top: number; - right: number; - bottom: number; - rotation: number; - zoom: number; - visibilityFlags: number; - - getCentrePosition(): Coord2; - moveTo(position: Coord2 | Coord3): void; - scrollTo(position: Coord2 | Coord3): void; -} - -export interface Ui { - readonly width: number; - readonly height: number; - readonly windows: number; - readonly mainViewport: Viewport; - - getWindow(id: number): Window; - getWindow(classification: string, id?: number): Window; - openWindow(desc: WindowDesc): Window; - closeWindows(classification: string, id?: number): void; - closeAllWindows(): void; - - activateTool(options: ToolDesc): IDisposable; - registerMenuItem(text: string, callback: () => void): void; -} - -/** - * Network APIs - * Use `network.status` to determine whether the current game is a client, server or in single player mode. - */ - - /** - * Represents a player within a network game. - */ -export interface Player { - readonly id: number; - readonly name: string; - group: number; - readonly ping: number; - readonly commandsRan: number; - readonly moneySpent: number; -} - -export type PermissionType = - "chat" | - "terraform" | - "set_water_level" | - "toggle_pause" | - "create_ride" | - "remove_ride" | - "build_ride" | - "ride_properties" | - "scenery" | - "path" | - "clear_landscape" | - "guest" | - "staff" | - "park_properties" | - "park_funding" | - "kick_player" | - "modify_groups" | - "set_player_group" | - "cheat" | - "toggle_scenery_cluster" | - "passwordless_login" | - "modify_tile" | - "edit_scenario_options"; - -export interface PlayerGroup { - readonly id: number; - name: string; - permissions: PermissionType[]; -} - -export interface ServerInfo { - readonly name: string; - readonly description: string; - readonly greeting: string; - readonly providerName: string; - readonly providerEmail: string; - readonly providerWebsite: string; -} - -export type NetworkMode = "none" | "server" | "client"; - -export interface Network { - readonly mode: NetworkMode; - readonly groups: number; - readonly players: number; - defaultGroup: number; - - getServerInfo(): ServerInfo; - getGroup(index: number): PlayerGroup; - setGroups(groups: PlayerGroup[]): void; - getPlayer(index: number): Player; - kickPlayer(index: number): void; - sendMessage(message: string): void; - sendMessage(message: string, players: number[]): void; - sendQueryAction(action: string, args: object, callback: (result: GameActionResult) => void): void; - sendExecuteAction(action: string, args: object, callback: (result: GameActionResult) => void): void; -} - -/** - * Global context for accessing all other APIs. - */ declare global { + interface PluginMetadata { + name: string; + version: string; + authors: string | string[]; + type: PluginType; + minApiVersion: number; + main: () => void; + } + + interface Console { + clear(): void; + log(message?: any, ...optionalParams: any[]): void; + } + + interface Configuration { + getAll(pattern: string): { [name: string]: any }; + get(key: string): T | undefined; + get(key: string, defaultValue: T): T; + set(key: string, value: T): void; + has(key: string): boolean; + } + + interface Coord2 { + x: number; + y: number; + } + + interface Coord3 { + x: number; + y: number; + z: number; + } + + type HookType = + "interval.tick" | "interval.day" | + "network.chat" | "network.action" | "network.join" | "network.leave"; + + type ExpenditureType = + "ride_construction" | + "ride_runningcosts" | + "land_purchase" | + "landscaping" | + "park_entrance_tickets" | + "park_ride_tickets" | + "shop_sales" | + "shop_stock" | + "food_drink_sales" | + "food_drink_stock" | + "wages" | + "marketing" | + "research" | + "interest"; + + interface GameActionResult { + error: string; + errorTitle: string; + errorMessage: string; + position: Coord3; + cost: number; + expenditureType: ExpenditureType; + } + + interface GameActionDesc { + id: string; + query: (args: object) => GameActionResult; + execute: (args: object) => GameActionResult; + } + + interface NetworkEventArgs { + readonly player: number; + } + + interface NetworkActionEventArgs extends NetworkEventArgs { + readonly type: string; + result: GameActionResult; + } + + interface NetworkChatEventArgs extends NetworkEventArgs { + message: string; + } + + interface Context { + /** + * The user's current configuration. + */ + configuration: Configuration; + + /** + * Shared generic storage for all plugins. + */ + sharedStorage: Configuration; + + /** + * Local generic storage for a each plugin. + */ + localStorage: Configuration; + + /** + * Registers a new intent (command) that can be mapped to a shortcut. + */ + registerIntent(desc: IntentDesc): void; + + /** + * Registers a new game action that allows clients to interact with the game. + */ + registerGameAction(desc: GameActionDesc): void; + + /** + * Subscribes to the given hook. + */ + subscribe(hook: HookType, callback: Function): IDisposable; + + subscribe(hook: "interval.tick", callback: () => void): IDisposable; + subscribe(hook: "interval.day", callback: () => void): IDisposable; + subscribe(hook: "network.action", callback: (e: NetworkActionEventArgs) => void): IDisposable; + subscribe(hook: "network.chat", callback: (e: NetworkChatEventArgs) => void): IDisposable; + subscribe(hook: "network.join", callback: (e: NetworkEventArgs) => void): IDisposable; + subscribe(hook: "network.leave", callback: (e: NetworkEventArgs) => void): IDisposable; + } + + interface IntentDesc + { + key: string; + title?: string; + shortcut?: string; + action: Function; + } + + interface IDisposable { + dispose(): void; + } + + type TileElementType = + "surface" | "footpath" | "track" | "small_scenery" | "entrance" | "large_scenery" | "banner"; + + interface BaseTileElement { + type: TileElementType; + baseHeight: number; + clearanceHeight: number; + broken: boolean; + } + + // interface TileElement extends BaseTileElement { + // /** + // * Gets the element as a specific type to access its properties + // */ + // asSurface(): SurfaceElement | null; + // asFootpath(): FootpathElement | null; + // asTrack(): TrackElement | null; + // asSmallScenery(): SmallSceneryElement | null; + // asEntrance(): EntranceElement | null; + // asWall(): WallElement | null; + // asLargeScenery(): LargeSceneryElement | null; + // asBanner(): BannerElement | null; + // asCorruptElement(): CorruptElement | null; + // } + + type TileElement = SurfaceElement | FootpathElement | TrackElement; + + interface SurfaceElement extends BaseTileElement { + slope: number; + terrain: number; + waterHeight: number; + grassLength: number; + ownership: number; + parkFences: number; + } + + interface FootpathAdditionStatus extends BaseTileElement { + north: number; + east: number; + south: number; + west: number; + } + + interface FootpathAddition extends BaseTileElement { + isBin: boolean; + isBench: boolean; + isLamp: boolean; + isBreakable: boolean; + isJumpingFountainWater: boolean; + isJumpingFountainSnow: boolean; + allowedOnQueue: boolean; + allowedOnSlope: boolean; + isQueueScreen: boolean; + status: FootpathAdditionStatus; + + /** + * Remove the path addition + */ + remove(): void; + } + + interface FootpathElement extends BaseTileElement { + footpathType: number; + isSloped: boolean; + isQueue: boolean; + addition: FootpathAddition; + edges: number; + corners: number; + rideIndex: number; + } + + interface TrackElement extends BaseTileElement { + } + + interface SmallSceneryElement extends BaseTileElement { + } + + interface EntranceElement extends BaseTileElement { + } + + interface WallElement extends BaseTileElement { + } + + interface LargeSceneryElement extends BaseTileElement { + } + + interface BannerElement extends BaseTileElement { + } + + interface CorruptElement extends BaseTileElement { + } + + interface Tile { + readonly x: number; + readonly y: number; + elements: TileElement[]; + + getElement(index: number): TileElement; + } + + interface Object { + readonly identifier: string; + readonly name: string; + } + + interface RideObject extends Object { + readonly description: string; + readonly capacity: string; + } + + interface Ride { + readonly object: RideObject; + readonly id: number; + type: number; + name: string; + excitement: number; + intensity: number; + nausea: number; + totalCustomers: number; + } + + type ThingType = + "car" | "duck" | "peep"; + + interface Thing { + readonly type: ThingType; + x: number; + y: number; + z: number; + + asPeep(): Thing | null; + } + + interface Peep extends Thing { + tshirt: number; + trousers: number; + } + + interface Map { + readonly size: { x: number; y: number; }; + readonly rides: number; + readonly things: number; + + getRide(id: number): Ride; + getTile(x: number, y: number): Tile; + getThing(id: number): Thing; + } + + type ParkMessageType = + "attraction" | "peep_on_attraction" | "peep" | "money" | "blank" | "research" | "guests" | "award" | "chart"; + + interface ParkMessage { + type: ParkMessageType; + text: string; + } + + interface Park { + cash: number; + rating: number; + bankLoan: number; + maxBankLoan: number; + + postMessage(message: string): void; + postMessage(message: ParkMessage): void; + } + + /** + * User Interface APIs + * These will only be available to servers and clients that are not running headless mode. + * Plugin writers should check if ui is available using `typeof ui !== 'undefined'`. + */ + + /** + * Represents the type of a widget, e.g. button or label. + */ + type WidgetType = + "button" | "checkbox" | "dropdown" | "groupbox" | "label" | "tabview" | "viewport"; + + interface Widget { + type: WidgetType; + x: number; + y: number; + width: number; + height: number; + isDisabled: boolean; + } + + interface ButtonWidget extends Widget { + text: string; + onClick: () => void; + } + + interface CheckboxWidget extends Widget { + text: string; + isChecked: number; + onChanged: (isChecked: boolean) => void; + } + + interface DropdownWidget extends Widget { + items: string[]; + selectedIndex: number; + onChanged: (index: number) => void; + } + + interface LabelWidget extends Widget { + text: string; + } + + interface ViewportWidget extends Widget { + viewport: Viewport + } + + interface Tab { + image: number; + tooltip: string; + widgets: Widget[]; + } + + interface Window { + id: number; + classification: string; + x: number; + y: number; + width: number; + height: number; + isSticky: boolean; + colours: number[]; + title: string; + widgets: Widget[]; + + close(): void; + } + + interface TabbedWindow extends Window { + tabs: Tab[]; + activeTabIndex: number; + + onTabChanged: (index: number) => void; + } + + interface WindowDesc { + classification: string; + x?: number; + y?: number; + width: number; + height: number; + title: string; + id?: number; + minWidth?: number; + minHeight?: number; + widgets?: Widget[]; + tabs?: Tab[]; + } + + type ToolCallbackType = "move" | "press" | "release"; + + interface ToolCallback { + type: ToolCallbackType; + tiles: Coord2[]; + } + + type CursorType = + "arrow" | + "blank" | + "up_arrow" | + "up_down_arrow" | + "hand_point" | + "zzz" | + "diagonal_arrows" | + "picker" | + "tree_down" | + "fountain_down" | + "statue_down" | + "bench_down" | + "cross_hair" | + "bin_down" | + "lamppost_down" | + "fence_down" | + "flower_down" | + "path_down" | + "dig_down" | + "water_down" | + "house_down" | + "volcano_down" | + "walk_down" | + "paint_down" | + "entrance_down" | + "hand_open" | + "hand_closed"; + + interface ToolDesc { + id: string; + cursor: CursorType; + width: number; + height: number; + callback: (e: ToolCallback) => void; + } + + interface Viewport { + left: number; + top: number; + right: number; + bottom: number; + rotation: number; + zoom: number; + visibilityFlags: number; + + getCentrePosition(): Coord2; + moveTo(position: Coord2 | Coord3): void; + scrollTo(position: Coord2 | Coord3): void; + } + + interface Ui { + readonly width: number; + readonly height: number; + readonly windows: number; + readonly mainViewport: Viewport; + + getWindow(id: number): Window; + getWindow(classification: string, id?: number): Window; + openWindow(desc: WindowDesc): Window; + closeWindows(classification: string, id?: number): void; + closeAllWindows(): void; + + activateTool(options: ToolDesc): IDisposable; + registerMenuItem(text: string, callback: () => void): void; + } + + /** + * Network APIs + * Use `network.status` to determine whether the current game is a client, server or in single player mode. + */ + + /** + * Represents a player within a network game. + */ + interface Player { + readonly id: number; + readonly name: string; + group: number; + readonly ping: number; + readonly commandsRan: number; + readonly moneySpent: number; + } + + type PermissionType = + "chat" | + "terraform" | + "set_water_level" | + "toggle_pause" | + "create_ride" | + "remove_ride" | + "build_ride" | + "ride_properties" | + "scenery" | + "path" | + "clear_landscape" | + "guest" | + "staff" | + "park_properties" | + "park_funding" | + "kick_player" | + "modify_groups" | + "set_player_group" | + "cheat" | + "toggle_scenery_cluster" | + "passwordless_login" | + "modify_tile" | + "edit_scenario_options"; + + interface PlayerGroup { + readonly id: number; + name: string; + permissions: PermissionType[]; + } + + interface ServerInfo { + readonly name: string; + readonly description: string; + readonly greeting: string; + readonly providerName: string; + readonly providerEmail: string; + readonly providerWebsite: string; + } + + type NetworkMode = "none" | "server" | "client"; + + interface Network { + readonly mode: NetworkMode; + readonly groups: number; + readonly players: number; + defaultGroup: number; + + getServerInfo(): ServerInfo; + getGroup(index: number): PlayerGroup; + setGroups(groups: PlayerGroup[]): void; + getPlayer(index: number): Player; + kickPlayer(index: number): void; + sendMessage(message: string): void; + sendMessage(message: string, players: number[]): void; + sendQueryAction(action: string, args: object, callback: (result: GameActionResult) => void): void; + sendExecuteAction(action: string, args: object, callback: (result: GameActionResult) => void): void; + } + + interface GameDate { + /** + * The total number of ticks that have elapsed since the beginning of the game / scenario. This + * should never reset. + */ + readonly ticksElapsed: number; + /** + * The total number of months that have elapsed. This will equate to 16 on 1st March, Year 2. + * Note: this represents the current date and may be reset by cheats or scripts. + */ + monthsElapsed: number; + /** + * The total number of years that have elapsed. This always equates to (monthsElapsed / 8). + */ + readonly yearsElapsed: number; + + /** + * How far through the month we are between 0 and 65536. This is incremented by 4 each tick, so + * every month takes ~6.8 minutes to complete making a year take just under an hour. + */ + monthProgress: number; + + /** The day of the month from 1 to 31. */ + readonly day: number; + /** The current month of the year from 0 to 7, where 0 is March and 7 is October. */ + readonly month: number; + /** The current year starting from 1. */ + readonly year: number; + } + + /** + * Global context for accessing all other APIs. + */ var console: Console; var context: Context; + var date: GameDate; var map: Map; var network: Network; var park: Park; From d8b0b24c437d535dc833a6a912f9b7cde073a3f2 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 18 Feb 2020 22:31:54 +0000 Subject: [PATCH 066/159] Implement date API --- src/openrct2/GameState.cpp | 9 ++- src/openrct2/scripting/Plugin.cpp | 2 +- src/openrct2/scripting/ScDate.hpp | 95 +++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.cpp | 3 + 4 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 src/openrct2/scripting/ScDate.hpp diff --git a/src/openrct2/GameState.cpp b/src/openrct2/GameState.cpp index bdeeaff041..2523a03dac 100644 --- a/src/openrct2/GameState.cpp +++ b/src/openrct2/GameState.cpp @@ -272,8 +272,15 @@ void GameState::UpdateLogic() auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); hookEngine.Call(HOOK_TYPE::INTERVAL_TICK); + auto day = _date.GetDay(); + date_update(); - _date = Date(gDateMonthTicks, gDateMonthTicks); + _date = Date(gDateMonthsElapsed, gDateMonthTicks); + + if (day != _date.GetDay()) + { + hookEngine.Call(HOOK_TYPE::INTERVAL_DAY); + } scenario_update(); climate_update(); diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 7c74139646..5a0e2e0e09 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -26,7 +26,7 @@ Plugin::Plugin(duk_context* context, const std::string& path) void Plugin::Load() { - std::string projectedVariables = "console,context,map,network,park"; + std::string projectedVariables = "console,context,date,map,network,park"; if (!gOpenRCT2Headless) { projectedVariables += ",ui"; diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp new file mode 100644 index 0000000000..455466753d --- /dev/null +++ b/src/openrct2/scripting/ScDate.hpp @@ -0,0 +1,95 @@ +/***************************************************************************** + * 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 + +#include "../Context.h" +#include "../Date.h" +#include "../Game.h" +#include "../GameState.h" +#include "../common.h" +#include "../localisation/Date.h" +#include "Duktape.hpp" + +namespace OpenRCT2::Scripting +{ + class ScDate + { + public: + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &monthsElapsed_get, &monthsElapsed_set, "monthsElapsed"); + dukglue_register_property(ctx, &monthProgress_get, &monthProgress_set, "monthProgress"); + dukglue_register_property(ctx, &yearsElapsed_get, nullptr, "yearsElapsed"); + dukglue_register_property(ctx, &ticksElapsed_get, nullptr, "ticksElapsed"); + dukglue_register_property(ctx, &day_get, nullptr, "day"); + dukglue_register_property(ctx, &month_get, nullptr, "month"); + dukglue_register_property(ctx, &year_get, nullptr, "year"); + } + + private: + uint32_t monthsElapsed_get() + { + const auto& date = GetDate(); + return date.GetMonthsElapsed(); + } + + void monthsElapsed_set(uint32_t value) + { + gDateMonthsElapsed = value; + } + + uint32_t monthProgress_get() + { + const auto& date = GetDate(); + return date.GetMonthTicks(); + } + + void monthProgress_set(int32_t value) + { + gDateMonthTicks = value; + } + + uint32_t yearsElapsed_get() + { + const auto& date = GetDate(); + return date.GetMonthsElapsed() / 8; + } + + uint32_t ticksElapsed_get() + { + return gCurrentTicks; + } + + int32_t day_get() + { + const auto& date = GetDate(); + return date.GetDay() + 1; + } + + int32_t month_get() + { + const auto& date = GetDate(); + return date.GetMonth(); + } + + int32_t year_get() + { + const auto& date = GetDate(); + return date.GetYear() + 1; + } + + private: + const Date& GetDate() + { + auto gameState = GetContext()->GetGameState(); + return gameState->GetDate(); + } + }; +} // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index fa17633c84..19a23ec4ef 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -18,6 +18,7 @@ #include "Duktape.hpp" #include "ScConsole.hpp" #include "ScContext.hpp" +#include "ScDate.hpp" #include "ScDisposable.hpp" #include "ScMap.hpp" #include "ScNetwork.hpp" @@ -62,6 +63,7 @@ void ScriptEngine::Initialise() auto ctx = (duk_context*)_context; ScConsole::Register(ctx); ScContext::Register(ctx); + ScDate::Register(ctx); ScDisposable::Register(ctx); ScMap::Register(ctx); ScNetwork::Register(ctx); @@ -76,6 +78,7 @@ void ScriptEngine::Initialise() dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); + dukglue_register_global(ctx, std::make_shared(), "date"); dukglue_register_global(ctx, std::make_shared(ctx), "map"); dukglue_register_global(ctx, std::make_shared(ctx), "network"); dukglue_register_global(ctx, std::make_shared(), "park"); From 057155e5ab606fc5574d8ba7cd841d2240238812 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 19 Feb 2020 01:00:02 +0000 Subject: [PATCH 067/159] Use a function to register plugin rather than return value --- distribution/openrct2.d.ts | 10 ++++++++-- src/openrct2/scripting/Plugin.cpp | 14 +++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 992fa34ab4..b2df570ff5 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 @@ -23,7 +23,7 @@ declare global { version: string; authors: string | string[]; type: PluginType; - minApiVersion: number; + minApiVersion?: number; main: () => void; } @@ -594,4 +594,10 @@ declare global { var network: Network; var park: Park; var ui: Ui; + + /** + * Registers the plugin. This only only be called once. + * @param metadata Information about the plugin and the entry point. + */ + function registerPlugin(metadata: PluginMetadata): void; } diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 5a0e2e0e09..1baac9553c 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -44,7 +44,19 @@ void Plugin::Load() } // Wrap the script in a function and pass the global objects as variables // so that if the script modifies them, they are not modified for other scripts. - code = "(function(" + projectedVariables + "){" + code + "})(" + projectedVariables + ");"; + + // clang-format off + code = + " (function(" + projectedVariables + ") {" + " var __metadata__ = null;" + " var registerPlugin = function(m) { __metadata__ = m };" + " (function(__metadata__) {" + + code + + " })();" + " return __metadata__;" + " })(" + projectedVariables + ");"; + // clang-format on + auto flags = DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NOFILENAME; auto result = duk_eval_raw(_context, code.c_str(), code.size(), flags); if (result != DUK_ERR_NONE) From d670c656aebe0feecd47a8d816fb04f26a5bace8 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 20 Feb 2020 17:58:15 +0000 Subject: [PATCH 068/159] Add more window APIs --- distribution/openrct2.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index b2df570ff5..39ccbe0330 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -334,7 +334,8 @@ declare global { y: number; width: number; height: number; - isDisabled: boolean; + name?: string; + isDisabled?: boolean; } interface ButtonWidget extends Widget { @@ -381,6 +382,8 @@ declare global { widgets: Widget[]; close(): void; + bringToFront(): void; + findWidget(name: string): T; } interface TabbedWindow extends Window { @@ -402,6 +405,8 @@ declare global { minHeight?: number; widgets?: Widget[]; tabs?: Tab[]; + + onClose?: () => void; } type ToolCallbackType = "move" | "press" | "release"; From 77262af46d345b97f6a337d594b3263d0d611f22 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 22 Feb 2020 12:32:09 +0000 Subject: [PATCH 069/159] Use new dependencies that contain duktape --- openrct2.proj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/openrct2.proj b/openrct2.proj index 658a4d27c9..eb7f8ee031 100644 --- a/openrct2.proj +++ b/openrct2.proj @@ -37,10 +37,10 @@ $(RootDir).dependencies - https://github.com/OpenRCT2/Dependencies/releases/download/v20/openrct2-libs-v20-x86-windows-static.zip - 2963fb45c23f5996638babd1e0bcd9661248ca02 - https://github.com/OpenRCT2/Dependencies/releases/download/v20/openrct2-libs-v20-x64-windows-static.zip - b7019e51bd78254cf19301d5668483a370a59eb0 + https://github.com/OpenRCT2/Dependencies/releases/download/v21/openrct2-libs-v21-x86-windows-static.zip + d5bc5b951c15880da0a413ccea27cff9b1b5ae5d + https://github.com/OpenRCT2/Dependencies/releases/download/v21/openrct2-libs-v21-x64-windows-static.zip + 91643da944a3682325f349ebe8dd6f1610e918a6 2fe3bd994b3189899d93f1d5a881e725e046fdc2 https://github.com/google/googletest/archive/$(GtestVersion).zip 058b9df80244c03f1633cb06e9f70471a29ebb8e From 0c1ed7b509b029d380b1dbb592e8957f63b048bd Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 22 Feb 2020 13:29:18 +0000 Subject: [PATCH 070/159] Implement APIs for bringToFront, findWidget etc. --- src/openrct2-ui/scripting/CustomWindow.cpp | 43 +++++++++++++++++++++- src/openrct2-ui/scripting/CustomWindow.h | 9 +++-- src/openrct2-ui/scripting/ScUi.hpp | 27 ++++++++++---- src/openrct2-ui/scripting/ScWindow.hpp | 39 ++++++++++++++++++++ 4 files changed, 107 insertions(+), 11 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 41c44877e6..0da71f13c5 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -90,6 +90,7 @@ namespace OpenRCT2::Ui::Windows int32_t Y{}; int32_t Width{}; int32_t Height{}; + std::string Name; std::string Text; std::vector Items; int32_t SelectedIndex{}; @@ -133,6 +134,10 @@ namespace OpenRCT2::Ui::Windows result.Y = desc["y"].as_int(); result.Width = desc["width"].as_int(); result.Height = desc["height"].as_int(); + if (desc["name"].type() == DukValue::Type::STRING) + { + result.Name = desc["name"].as_string(); + } if (result.Type == "button") { result.Text = ProcessString(desc["text"]); @@ -655,7 +660,7 @@ namespace OpenRCT2::Ui::Windows } } - void UpdateWidgetText(rct_window* w, rct_widgetindex widgetIndex, const std::string& value) + void UpdateWidgetText(rct_window* w, rct_widgetindex widgetIndex, const std::string_view& value) { if (w->custom_info != nullptr) { @@ -669,4 +674,40 @@ namespace OpenRCT2::Ui::Windows } } + rct_window* FindCustomWindowByClassification(const std::string_view& classification) + { + for (auto w : g_window_list) + { + if (w->classification == WC_CUSTOM) + { + auto& customInfo = GetInfo(w.get()); + if (customInfo.Desc.Classification == classification) + { + return w.get(); + } + } + } + return nullptr; + } + + std::optional FindWidgetIndexByName(rct_window* w, const std::string_view& name) + { + if (w->custom_info != nullptr) + { + auto& customInfo = GetInfo(w); + for (rct_widgetindex i = 0; i < customInfo.Widgets.size(); i++) + { + auto customWidgetInfo = customInfo.GetCustomWidgetDesc(i); + if (customWidgetInfo != nullptr) + { + if (customWidgetInfo->Name == name) + { + return i; + } + } + } + } + return {}; + } + } // namespace OpenRCT2::Ui::Windows diff --git a/src/openrct2-ui/scripting/CustomWindow.h b/src/openrct2-ui/scripting/CustomWindow.h index ba81fcd91c..130340375c 100644 --- a/src/openrct2-ui/scripting/CustomWindow.h +++ b/src/openrct2-ui/scripting/CustomWindow.h @@ -9,9 +9,12 @@ #include "../interface/Window.h" -#include +#include +#include namespace OpenRCT2::Ui::Windows { - void UpdateWidgetText(rct_window* w, rct_widgetindex widget, const std::string& value); -} + void UpdateWidgetText(rct_window* w, rct_widgetindex widget, const std::string_view& string_view); + rct_window* FindCustomWindowByClassification(const std::string_view& classification); + std::optional FindWidgetIndexByName(rct_window* w, const std::string_view& name); +} // namespace OpenRCT2::Ui::Windows diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index fdedf11ae2..3eaefe15a6 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -99,18 +99,31 @@ namespace OpenRCT2::Scripting window_close_all(); } - std::shared_ptr getWindow(int32_t index) + std::shared_ptr getWindow(DukValue a, DukValue b) { - int32_t i = 0; - for (auto w : g_window_list) + if (a.type() == DukValue::Type::NUMBER) { - if (i == index) + auto index = a.as_int(); + auto i = 0; + for (auto w : g_window_list) { - return std::make_shared(w.get()); + if (i == index) + { + return std::make_shared(w.get()); + } + i++; } - i++; } - return nullptr; + else if (a.type() == DukValue::Type::STRING) + { + auto classification = a.as_string(); + auto w = FindCustomWindowByClassification(classification); + if (w != nullptr) + { + return std::make_shared(w); + } + } + return {}; } void registerMenuItem(std::string text, DukValue callback) diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 8bd94a0958..c20f81716f 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -18,6 +18,8 @@ namespace OpenRCT2::Scripting { + using namespace OpenRCT2::Ui::Windows; + class ScWindow { private: @@ -84,6 +86,39 @@ namespace OpenRCT2::Scripting return result; } + void close() + { + auto w = GetWindow(); + if (w != nullptr) + { + window_close(w); + } + } + + std::shared_ptr findWidget(std::string name) + { + auto w = GetWindow(); + if (w != nullptr) + { + auto widgetIndex = FindWidgetIndexByName(w, name); + if (widgetIndex) + { + return std::make_shared(_class, _number, *widgetIndex); + } + } + return {}; + } + + void bringToFront() + { + auto w = GetWindow(); + if (w != nullptr) + { + window_bring_to_front(w); + w->flags |= WF_WHITE_BORDER_MASK; + } + } + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); @@ -92,6 +127,10 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScWindow::height_get, nullptr, "height"); dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); dukglue_register_property(ctx, &ScWindow::widgets_get, nullptr, "widgets"); + + dukglue_register_method(ctx, &close, "close"); + dukglue_register_method(ctx, &findWidget, "findWidget"); + dukglue_register_method(ctx, &bringToFront, "bringToFront"); } private: From 412c838a0769d6dfbe8a189d6d8211682c0d74dc Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 22 Feb 2020 16:36:01 +0000 Subject: [PATCH 071/159] Fix warnings --- src/openrct2/scripting/ScMap.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 2d8c9d097d..1b90ea0a8a 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -54,7 +54,7 @@ namespace OpenRCT2::Scripting std::shared_ptr getRide(int32_t id) { auto rideManager = GetRideManager(); - if (id >= 0 && id < rideManager.size()) + if (id >= 0 && id < static_cast(rideManager.size())) { auto ride = rideManager[static_cast(id)]; if (ride != nullptr) From facd5573550cd84d8fa4e664e32ac9ae10d43195 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 22 Feb 2020 16:37:47 +0000 Subject: [PATCH 072/159] Fix formatting --- src/openrct2/scripting/Duktape.hpp | 1 + src/openrct2/scripting/ScThing.hpp | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 22b096e3f6..7bd111f1ac 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -1,4 +1,5 @@ #pragma once #include "../thirdparty/dukglue/dukglue.h" + #include diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 5d303454f3..3df142597b 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -94,7 +94,6 @@ namespace OpenRCT2::Scripting dukglue_register_constructor(ctx, "Thing"); dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); dukglue_register_property(ctx, &ScThing::x_get, &ScThing::x_set, "x"); - //dukglue_property_helper(ctx, _sprite->peep.x, "x"); dukglue_register_property(ctx, &ScThing::y_get, &ScThing::y_set, "y"); dukglue_register_property(ctx, &ScThing::z_get, &ScThing::z_set, "z"); dukglue_register_property(ctx, &ScThing::tshirtColour_get, &ScThing::tshirtColour_set, "tshirtColour"); From 639faa20859be79c8a9f1fb778d8d291d9ded416 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 22 Feb 2020 18:04:27 +0000 Subject: [PATCH 073/159] Fix GCC issues --- openrct2.common.props | 2 +- src/openrct2-ui/scripting/CustomWindow.cpp | 4 ++-- src/openrct2-ui/scripting/ScViewport.hpp | 20 ++++++++++---------- src/openrct2-ui/scripting/ScWidget.hpp | 18 +++++++++--------- src/openrct2-ui/scripting/ScWindow.hpp | 6 +++--- src/openrct2-ui/windows/TopToolbar.cpp | 2 +- src/openrct2/CMakeLists.txt | 5 +++-- src/openrct2/Context.cpp | 2 +- src/openrct2/Game.h | 1 + src/openrct2/interface/Window.h | 2 +- src/openrct2/scripting/Duktape.hpp | 3 +-- src/openrct2/scripting/Plugin.cpp | 2 +- src/openrct2/scripting/ScDate.hpp | 14 +++++++------- src/openrct2/scripting/ScRide.hpp | 8 ++++---- src/openrct2/scripting/ScThing.hpp | 7 ------- 15 files changed, 45 insertions(+), 51 deletions(-) diff --git a/openrct2.common.props b/openrct2.common.props index f897da6b04..e62f3ea129 100644 --- a/openrct2.common.props +++ b/openrct2.common.props @@ -101,7 +101,7 @@ - $(SolutionDir)src;$(SolutionDir)lib\$(Platform)\include;$(SolutionDir)lib\$(Platform)\include\SDL2;$(IncludePath) + $(SolutionDir)src;$(SolutionDir)src\openrct2\thirdparty;$(SolutionDir)lib\$(Platform)\include;$(SolutionDir)lib\$(Platform)\include\SDL2;$(IncludePath) $(SolutionDir)lib\$(Platform)\debug\lib;$(LibraryPath) $(SolutionDir)lib\$(Platform)\lib;$(LibraryPath) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 0da71f13c5..7a55c621cd 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -216,7 +216,7 @@ namespace OpenRCT2::Ui::Windows }); } - return std::move(result); + return result; } static std::optional GetOptionalInt(DukValue input) @@ -695,7 +695,7 @@ namespace OpenRCT2::Ui::Windows if (w->custom_info != nullptr) { auto& customInfo = GetInfo(w); - for (rct_widgetindex i = 0; i < customInfo.Widgets.size(); i++) + for (size_t i = 0; i < customInfo.Widgets.size(); i++) { auto customWidgetInfo = customInfo.GetCustomWidgetDesc(i); if (customWidgetInfo != nullptr) diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index f7a94d08fc..17e5e99169 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -226,16 +226,16 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { - dukglue_register_property(ctx, &left_get, &left_set, "left"); - dukglue_register_property(ctx, &top_get, &top_set, "top"); - dukglue_register_property(ctx, &right_get, &right_set, "right"); - dukglue_register_property(ctx, &bottom_get, &bottom_set, "bottom"); - dukglue_register_property(ctx, &rotation_get, &rotation_set, "rotation"); - dukglue_register_property(ctx, &zoom_get, &zoom_set, "zoom"); - dukglue_register_property(ctx, &visibilityFlags_get, &visibilityFlags_set, "visibilityFlags"); - dukglue_register_method(ctx, &getCentrePosition, "getCentrePosition"); - dukglue_register_method(ctx, &moveTo, "moveTo"); - dukglue_register_method(ctx, &scrollTo, "scrollTo"); + dukglue_register_property(ctx, &ScViewport::left_get, &ScViewport::left_set, "left"); + dukglue_register_property(ctx, &ScViewport::top_get, &ScViewport::top_set, "top"); + dukglue_register_property(ctx, &ScViewport::right_get, &ScViewport::right_set, "right"); + dukglue_register_property(ctx, &ScViewport::bottom_get, &ScViewport::bottom_set, "bottom"); + dukglue_register_property(ctx, &ScViewport::rotation_get, &ScViewport::rotation_set, "rotation"); + dukglue_register_property(ctx, &ScViewport::zoom_get, &ScViewport::zoom_set, "zoom"); + dukglue_register_property(ctx, &ScViewport::visibilityFlags_get, &ScViewport::visibilityFlags_set, "visibilityFlags"); + dukglue_register_method(ctx, &ScViewport::getCentrePosition, "getCentrePosition"); + dukglue_register_method(ctx, &ScViewport::moveTo, "moveTo"); + dukglue_register_method(ctx, &ScViewport::scrollTo, "scrollTo"); } private: diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index d86b84f602..cca75554fb 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -243,17 +243,17 @@ namespace OpenRCT2::Scripting static void Register(duk_context* ctx) { // Common - dukglue_register_property(ctx, &type_get, nullptr, "type"); - dukglue_register_property(ctx, &x_get, &x_set, "x"); - dukglue_register_property(ctx, &y_get, &y_set, "y"); - dukglue_register_property(ctx, &width_get, &width_set, "width"); - dukglue_register_property(ctx, &height_get, &height_set, "height"); - dukglue_register_property(ctx, &isDisabled_get, &isDisabled_set, "isDisabled"); + dukglue_register_property(ctx, &ScWidget::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScWidget::x_get, &ScWidget::x_set, "x"); + dukglue_register_property(ctx, &ScWidget::y_get, &ScWidget::y_set, "y"); + dukglue_register_property(ctx, &ScWidget::width_get, &ScWidget::width_set, "width"); + dukglue_register_property(ctx, &ScWidget::height_get, &ScWidget::height_set, "height"); + dukglue_register_property(ctx, &ScWidget::isDisabled_get, &ScWidget::isDisabled_set, "isDisabled"); // No so common - dukglue_register_property(ctx, &text_get, &text_set, "text"); - dukglue_register_property(ctx, &isChecked_get, &isChecked_set, "isChecked"); - dukglue_register_property(ctx, &viewport_get, nullptr, "viewport"); + dukglue_register_property(ctx, &ScWidget::text_get, &ScWidget::text_set, "text"); + dukglue_register_property(ctx, &ScWidget::isChecked_get, &ScWidget::isChecked_set, "isChecked"); + dukglue_register_property(ctx, &ScWidget::viewport_get, nullptr, "viewport"); } private: diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index c20f81716f..3969e73d2a 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -128,9 +128,9 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); dukglue_register_property(ctx, &ScWindow::widgets_get, nullptr, "widgets"); - dukglue_register_method(ctx, &close, "close"); - dukglue_register_method(ctx, &findWidget, "findWidget"); - dukglue_register_method(ctx, &bringToFront, "bringToFront"); + dukglue_register_method(ctx, &ScWindow::close, "close"); + dukglue_register_method(ctx, &ScWindow::findWidget, "findWidget"); + dukglue_register_method(ctx, &ScWindow::bringToFront, "bringToFront"); } private: diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index 29be4af650..48c81d0643 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -3326,7 +3326,7 @@ static void top_toolbar_map_menu_dropdown(int16_t dropdownIndex) else { const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; - auto customIndex = dropdownIndex - customStartIndex; + auto customIndex = static_cast(dropdownIndex - customStartIndex); if (customMenuItems.size() > customIndex) { customMenuItems[customIndex].Invoke(); diff --git a/src/openrct2/CMakeLists.txt b/src/openrct2/CMakeLists.txt index 75471fafe7..cc9e4cc142 100644 --- a/src/openrct2/CMakeLists.txt +++ b/src/openrct2/CMakeLists.txt @@ -200,8 +200,9 @@ endif() target_include_directories(${PROJECT_NAME} PRIVATE ${LIBZIP_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PUBLIC ${JANSSON_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PRIVATE ${PNG_INCLUDE_DIRS} - ${DUKTAPE_INCLUDE_DIRS} - ${ZLIB_INCLUDE_DIRS}) + ${DUKTAPE_INCLUDE_DIRS} + ${ZLIB_INCLUDE_DIRS}) +include_directories(${PROJECT_NAME} SYSTEM ${CMAKE_CURRENT_LIST_DIR}/thirdparty) # To avoid unnecessary rebuilds set the current branch and # short sha1 only for the two files that use these diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 9e32f46d35..487dc9f3a5 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -138,8 +138,8 @@ namespace OpenRCT2 , _audioContext(audioContext) , _uiContext(uiContext) , _localisationService(std::make_unique(env)) - , _painter(std::make_unique(uiContext)) , _scriptEngine(_stdInOutConsole, *env) + , _painter(std::make_unique(uiContext)) { // Can't have more than one context currently. Guard::Assert(Instance == nullptr); diff --git a/src/openrct2/Game.h b/src/openrct2/Game.h index dd244943d6..29f06e0c55 100644 --- a/src/openrct2/Game.h +++ b/src/openrct2/Game.h @@ -156,6 +156,7 @@ void update_palette_effects(); void game_load_or_quit_no_save_prompt(); void load_from_sv6(const char* path); void game_load_init(); +void game_finish(); void pause_toggle(); bool game_is_paused(); bool game_is_not_paused(); diff --git a/src/openrct2/interface/Window.h b/src/openrct2/interface/Window.h index 8b3704afb0..86c5eca6a4 100644 --- a/src/openrct2/interface/Window.h +++ b/src/openrct2/interface/Window.h @@ -95,7 +95,7 @@ struct rct_widget rct_string_id tooltip; // 0x0E // New properties - WidgetFlags flags; + WidgetFlags flags{}; }; /** diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 7bd111f1ac..27573a8d50 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -1,5 +1,4 @@ #pragma once -#include "../thirdparty/dukglue/dukglue.h" - +#include #include diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 1baac9553c..9e97028e46 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -9,7 +9,7 @@ #include "Plugin.h" -#include "..\OpenRCT2.h" +#include "../OpenRCT2.h" #include "Duktape.hpp" #include diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 455466753d..03bb89c715 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -24,13 +24,13 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { - dukglue_register_property(ctx, &monthsElapsed_get, &monthsElapsed_set, "monthsElapsed"); - dukglue_register_property(ctx, &monthProgress_get, &monthProgress_set, "monthProgress"); - dukglue_register_property(ctx, &yearsElapsed_get, nullptr, "yearsElapsed"); - dukglue_register_property(ctx, &ticksElapsed_get, nullptr, "ticksElapsed"); - dukglue_register_property(ctx, &day_get, nullptr, "day"); - dukglue_register_property(ctx, &month_get, nullptr, "month"); - dukglue_register_property(ctx, &year_get, nullptr, "year"); + dukglue_register_property(ctx, &ScDate::monthsElapsed_get, &ScDate::monthsElapsed_set, "monthsElapsed"); + dukglue_register_property(ctx, &ScDate::monthProgress_get, &ScDate::monthProgress_set, "monthProgress"); + dukglue_register_property(ctx, &ScDate::yearsElapsed_get, nullptr, "yearsElapsed"); + dukglue_register_property(ctx, &ScDate::ticksElapsed_get, nullptr, "ticksElapsed"); + dukglue_register_property(ctx, &ScDate::day_get, nullptr, "day"); + dukglue_register_property(ctx, &ScDate::month_get, nullptr, "month"); + dukglue_register_property(ctx, &ScDate::year_get, nullptr, "year"); } private: diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index 7bb3ae0fb6..f316bf906c 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -29,10 +29,10 @@ namespace OpenRCT2::Scripting static void Register(duk_context* ctx) { - dukglue_register_property(ctx, &id_get, nullptr, "identifier"); - dukglue_register_property(ctx, &name_get, nullptr, "name"); - dukglue_register_property(ctx, &description_get, nullptr, "description"); - dukglue_register_property(ctx, &capacity_get, nullptr, "capacity"); + dukglue_register_property(ctx, &ScRideObject::id_get, nullptr, "identifier"); + dukglue_register_property(ctx, &ScRideObject::name_get, nullptr, "name"); + dukglue_register_property(ctx, &ScRideObject::description_get, nullptr, "description"); + dukglue_register_property(ctx, &ScRideObject::capacity_get, nullptr, "capacity"); } private: diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 3df142597b..41496e1199 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -82,13 +82,6 @@ namespace OpenRCT2::Scripting _sprite->peep.trousers_colour = value; } - template static void dukglue_property_helper(duk_context* ctx, T& var, const char* name) - { - auto getter = []() -> const T { return var; }; - auto setter = [&var](T& value) -> void { var = value; }; - dukglue_register_property(ctx, getter, setter, name); - } - static void Register(duk_context* ctx) { dukglue_register_constructor(ctx, "Thing"); From dc64d3541d46d10cb8388fad9aa990763d721921 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 22 Feb 2020 22:18:22 +0000 Subject: [PATCH 074/159] Transfer server-client scripts over network --- src/openrct2-ui/windows/TitleMenu.cpp | 1 + src/openrct2/Context.cpp | 4 ++ src/openrct2/Game.cpp | 4 ++ src/openrct2/Game.h | 1 + src/openrct2/network/Network.cpp | 53 +++++++++++++++++++++++++ src/openrct2/network/NetworkTypes.h | 1 + src/openrct2/scripting/Plugin.cpp | 41 +++++++++++++------ src/openrct2/scripting/Plugin.h | 14 +++++++ src/openrct2/scripting/ScriptEngine.cpp | 46 ++++++++++++++++++--- src/openrct2/scripting/ScriptEngine.h | 8 ++++ 10 files changed, 155 insertions(+), 18 deletions(-) diff --git a/src/openrct2-ui/windows/TitleMenu.cpp b/src/openrct2-ui/windows/TitleMenu.cpp index b7d3f3f5c6..4db6d11eea 100644 --- a/src/openrct2-ui/windows/TitleMenu.cpp +++ b/src/openrct2-ui/windows/TitleMenu.cpp @@ -123,6 +123,7 @@ rct_window* window_title_menu_open() static void window_title_menu_scenarioselect_callback(const utf8* path) { context_load_park_from_file(path); + game_load_scripts(); } static void window_title_menu_mouseup(rct_window* w, rct_widgetindex widgetIndex) diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 487dc9f3a5..7dd8edf040 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -810,7 +810,11 @@ namespace OpenRCT2 } network_begin_server(gNetworkStartPort, gNetworkStartAddress); } + else #endif // DISABLE_NETWORK + { + game_load_scripts(); + } break; } case STARTUP_ACTION_EDIT: diff --git a/src/openrct2/Game.cpp b/src/openrct2/Game.cpp index d19a9937db..7526bb5d2c 100644 --- a/src/openrct2/Game.cpp +++ b/src/openrct2/Game.cpp @@ -588,7 +588,10 @@ void game_load_init() audio_stop_title_music(); gGameSpeed = 1; +} +void game_load_scripts() +{ GetContext()->GetScriptEngine().LoadPlugins(); } @@ -812,6 +815,7 @@ static void game_load_or_quit_no_save_prompt_callback(int32_t result, const utf8 game_finish(); window_close_by_class(WC_EDITOR_OBJECT_SELECTION); context_load_park_from_file(path); + game_load_scripts(); } } diff --git a/src/openrct2/Game.h b/src/openrct2/Game.h index 29f06e0c55..a1167563f2 100644 --- a/src/openrct2/Game.h +++ b/src/openrct2/Game.h @@ -156,6 +156,7 @@ void update_palette_effects(); void game_load_or_quit_no_save_prompt(); void load_from_sv6(const char* path); void game_load_init(); +void game_load_scripts(); void game_finish(); void pause_toggle(); bool game_is_paused(); diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 1a5724e5cd..182c6c2153 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -194,6 +194,7 @@ public: void Client_Send_GAMEINFO(); void Client_Send_OBJECTS(const std::vector& objects); void Server_Send_OBJECTS(NetworkConnection& connection, const std::vector& objects) const; + void Server_Send_SCRIPTS(NetworkConnection& connection) const; NetworkStats_t GetStats() const; json_t* GetServerInfoAsJson() const; @@ -309,6 +310,7 @@ private: void Client_Handle_TOKEN(NetworkConnection& connection, NetworkPacket& packet); void Server_Handle_TOKEN(NetworkConnection& connection, NetworkPacket& packet); void Client_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket& packet); + void Client_Handle_SCRIPTS(NetworkConnection& connection, NetworkPacket& packet); void Client_Handle_GAMESTATE(NetworkConnection& connection, NetworkPacket& packet); void Server_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket& packet); @@ -344,6 +346,7 @@ Network::Network() client_command_handlers[NETWORK_COMMAND_GAMEINFO] = &Network::Client_Handle_GAMEINFO; client_command_handlers[NETWORK_COMMAND_TOKEN] = &Network::Client_Handle_TOKEN; client_command_handlers[NETWORK_COMMAND_OBJECTS] = &Network::Client_Handle_OBJECTS; + client_command_handlers[NETWORK_COMMAND_SCRIPTS] = &Network::Client_Handle_SCRIPTS; client_command_handlers[NETWORK_COMMAND_GAMESTATE] = &Network::Client_Handle_GAMESTATE; server_command_handlers.resize(NETWORK_COMMAND_MAX, nullptr); server_command_handlers[NETWORK_COMMAND_AUTH] = &Network::Server_Handle_AUTH; @@ -624,6 +627,8 @@ bool Network::BeginServer(uint16_t port, const std::string& address) _serverState.gamestateSnapshotsEnabled = gConfigNetwork.desync_debugging; _advertiser = CreateServerAdvertiser(listening_port); + game_load_scripts(); + return true; } @@ -1465,6 +1470,37 @@ void Network::Server_Send_OBJECTS(NetworkConnection& connection, const std::vect connection.QueuePacket(std::move(packet)); } +void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const +{ + using namespace OpenRCT2::Scripting; + + auto& scriptEngine = GetContext()->GetScriptEngine(); + const auto& plugins = scriptEngine.GetPlugins(); + std::vector> pluginsToSend; + for (const auto& plugin : plugins) + { + const auto& metadata = plugin->GetMetadata(); + if (metadata.Type == OpenRCT2::Scripting::PluginType::ServerClient) + { + pluginsToSend.push_back(plugin); + } + } + + log_verbose("Server sends %u scripts", pluginsToSend.size()); + std::unique_ptr packet(NetworkPacket::Allocate()); + *packet << (uint32_t)NETWORK_COMMAND_SCRIPTS << (uint32_t)pluginsToSend.size(); + for (const auto& plugin : pluginsToSend) + { + const auto& metadata = plugin->GetMetadata(); + log_verbose("Script %s", metadata.Name.c_str()); + + const auto& code = plugin->GetCode(); + *packet << (uint32_t)code.size(); + packet->Write((const uint8_t*)code.c_str(), code.size()); + } + connection.QueuePacket(std::move(packet)); +} + NetworkStats_t Network::GetStats() const { NetworkStats_t stats = {}; @@ -2339,6 +2375,7 @@ void Network::Server_Client_Joined(const char* name, const std::string& keyhash, auto& objManager = context->GetObjectManager(); auto objects = objManager.GetPackableObjects(); Server_Send_OBJECTS(connection, objects); + Server_Send_SCRIPTS(connection); // Log player joining event std::string playerNameHash = player->Name + " (" + keyhash + ")"; @@ -2398,6 +2435,21 @@ void Network::Client_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket Client_Send_OBJECTS(requested_objects); } +void Network::Client_Handle_SCRIPTS(NetworkConnection& connection, NetworkPacket& packet) +{ + auto& scriptEngine = GetContext()->GetScriptEngine(); + + uint32_t numScripts{}; + packet >> numScripts; + for (uint32_t i = 0; i < numScripts; i++) + { + uint32_t codeLength{}; + packet >> codeLength; + auto code = std::string_view((const char*)packet.Read(codeLength), codeLength); + scriptEngine.AddNetworkPlugin(code); + } +} + void Network::Client_Handle_GAMESTATE(NetworkConnection& connection, NetworkPacket& packet) { uint32_t tick; @@ -2683,6 +2735,7 @@ void Network::Client_Handle_MAP([[maybe_unused]] NetworkConnection& connection, if (LoadMap(&ms)) { game_load_init(); + game_load_scripts(); _serverState.tick = gCurrentTicks; // window_network_status_open("Loaded new map from network"); _serverState.state = NETWORK_SERVER_STATE_OK; diff --git a/src/openrct2/network/NetworkTypes.h b/src/openrct2/network/NetworkTypes.h index 3837c72da9..a2bf68150a 100644 --- a/src/openrct2/network/NetworkTypes.h +++ b/src/openrct2/network/NetworkTypes.h @@ -68,6 +68,7 @@ enum NETWORK_COMMAND NETWORK_COMMAND_PLAYERINFO, NETWORK_COMMAND_REQUEST_GAMESTATE, NETWORK_COMMAND_GAMESTATE, + NETWORK_COMMAND_SCRIPTS, NETWORK_COMMAND_MAX, NETWORK_COMMAND_INVALID = -1 }; diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 9e97028e46..cc9ea3ce62 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -24,28 +24,29 @@ Plugin::Plugin(duk_context* context, const std::string& path) { } +void Plugin::SetCode(const std::string_view& code) +{ + _code = code; +} + void Plugin::Load() { + if (!_path.empty()) + { + LoadCodeFromFile(); + } + std::string projectedVariables = "console,context,date,map,network,park"; if (!gOpenRCT2Headless) { projectedVariables += ",ui"; } - std::string code; - { - std::ifstream fs(_path); - if (fs.is_open()) - { - fs.seekg(0, std::ios::end); - code.reserve(fs.tellg()); - fs.seekg(0, std::ios::beg); - code.assign(std::istreambuf_iterator(fs), std::istreambuf_iterator()); - } - } + // Wrap the script in a function and pass the global objects as variables // so that if the script modifies them, they are not modified for other scripts. // clang-format off + auto code = _code; code = " (function(" + projectedVariables + ") {" " var __metadata__ = null;" @@ -99,6 +100,20 @@ void Plugin::Update() { } +void Plugin::LoadCodeFromFile() +{ + std::string code; + std::ifstream fs(_path); + if (fs.is_open()) + { + fs.seekg(0, std::ios::end); + code.reserve(fs.tellg()); + fs.seekg(0, std::ios::beg); + code.assign(std::istreambuf_iterator(fs), std::istreambuf_iterator()); + } + _code = std::move(code); +} + static std::string TryGetString(const DukValue& value, const std::string& message) { if (value.type() != DukValue::Type::STRING) @@ -144,8 +159,8 @@ PluginType Plugin::ParsePluginType(const std::string_view& type) if (type == "server") return PluginType::Server; if (type == "client") - return PluginType::Server; + return PluginType::Client; if (type == "server_client") - return PluginType::Server; + return PluginType::ServerClient; throw std::invalid_argument("Unknown plugin type."); } diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index b005cba4b3..956840d55a 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -54,6 +54,7 @@ namespace OpenRCT2::Scripting duk_context* _context{}; std::string _path; PluginMetadata _metadata; + std::string _code; bool _hasStarted{}; public: @@ -62,11 +63,21 @@ namespace OpenRCT2::Scripting return _path; }; + bool HasPath() const + { + return _path.empty(); + } + const PluginMetadata& GetMetadata() const { return _metadata; } + const std::string& GetCode() const + { + return _code; + } + bool HasStarted() const { return _hasStarted; @@ -79,12 +90,15 @@ namespace OpenRCT2::Scripting Plugin(const Plugin&) = delete; Plugin(Plugin&&) = delete; + void SetCode(const std::string_view& code); void Load(); void Start(); void Stop(); void Update(); private: + void LoadCodeFromFile(); + static PluginMetadata GetMetadata(const DukValue& dukMetadata); static PluginType ParsePluginType(const std::string_view& type); }; diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 19a23ec4ef..163b8e5b74 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -113,7 +113,7 @@ void ScriptEngine::LoadPlugins() } } - if (gConfigPlugin.enable_hot_reloading) + if (gConfigPlugin.enable_hot_reloading && network_get_mode() == NETWORK_MODE_NONE) { SetupHotReloading(); } @@ -123,10 +123,15 @@ void ScriptEngine::LoadPlugins() } void ScriptEngine::LoadPlugin(const std::string& path) +{ + auto plugin = std::make_shared(_context, path); + LoadPlugin(plugin); +} + +void ScriptEngine::LoadPlugin(std::shared_ptr& plugin) { try { - auto plugin = std::make_shared(_context, path); ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); plugin->Load(); @@ -240,7 +245,7 @@ void ScriptEngine::StartPlugins() { for (auto& plugin : _plugins) { - if (!plugin->HasStarted()) + if (!plugin->HasStarted() && ShouldStartPlugin(plugin)) { ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); try @@ -257,12 +262,36 @@ void ScriptEngine::StartPlugins() _pluginsStarted = true; } +bool ScriptEngine::ShouldStartPlugin(const std::shared_ptr& plugin) +{ + auto networkMode = network_get_mode(); + if (networkMode == NETWORK_MODE_CLIENT) + { + // Only client plugins and plugins downloaded from server should be started + const auto& metadata = plugin->GetMetadata(); + if (metadata.Type == PluginType::Server) + { + LogPluginInfo(plugin, "Server plugin not started"); + return false; + } + else if (metadata.Type == PluginType::ServerClient && plugin->HasPath()) + { + LogPluginInfo(plugin, "Server / client plugin not started"); + return false; + } + } + return true; +} + void ScriptEngine::StopPlugins() { for (auto& plugin : _plugins) { - StopPlugin(plugin); - LogPluginInfo(plugin, "Stopped"); + if (plugin->HasStarted()) + { + StopPlugin(plugin); + LogPluginInfo(plugin, "Stopped"); + } } _pluginsStarted = false; } @@ -332,6 +361,13 @@ void ScriptEngine::LogPluginInfo(const std::shared_ptr& plugin, const st _console.WriteLine("[" + pluginName + "] " + std::string(message)); } +void ScriptEngine::AddNetworkPlugin(const std::string_view& code) +{ + auto plugin = std::make_shared(_context, std::string()); + plugin->SetCode(code); + LoadPlugin(plugin); +} + static std::string Stringify(duk_context* ctx, duk_idx_t idx) { auto type = duk_get_type(ctx, idx); diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index c83ba577af..4156c13825 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -123,6 +123,10 @@ namespace OpenRCT2::Scripting { return _execInfo; } + std::vector>& GetPlugins() + { + return _plugins; + } void LoadPlugins(); void UnloadPlugins(); @@ -136,13 +140,17 @@ namespace OpenRCT2::Scripting _pluginStoppedSubscriptions.push_back(callback); } + void AddNetworkPlugin(const std::string_view& code); + private: void Initialise(); void StartPlugins(); void StopPlugins(); void LoadPlugin(const std::string& path); + void LoadPlugin(std::shared_ptr& plugin); void StopPlugin(std::shared_ptr plugin); bool ShouldLoadScript(const std::string& path); + bool ShouldStartPlugin(const std::shared_ptr &plugin); void SetupHotReloading(); void AutoReloadPlugins(); void ProcessREPL(); From a5c8ff920ffbb663d126405ddd9b2462564f85a6 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 23 Feb 2020 02:00:22 +0000 Subject: [PATCH 075/159] Add game mutable protection --- src/openrct2-ui/scripting/CustomMenu.h | 2 +- src/openrct2-ui/scripting/CustomWindow.cpp | 2 +- src/openrct2-ui/scripting/ScViewport.hpp | 3 ++- src/openrct2/GameState.cpp | 4 ++-- src/openrct2/network/Network.cpp | 2 +- src/openrct2/scripting/HookEngine.cpp | 12 +++++----- src/openrct2/scripting/HookEngine.h | 6 ++--- src/openrct2/scripting/ScDate.hpp | 2 ++ src/openrct2/scripting/ScPark.hpp | 6 +++++ src/openrct2/scripting/ScRide.hpp | 5 +++++ src/openrct2/scripting/ScThing.hpp | 11 ++++++--- src/openrct2/scripting/ScTile.hpp | 4 ++++ src/openrct2/scripting/ScriptEngine.cpp | 26 ++++++++++++++++++---- src/openrct2/scripting/ScriptEngine.h | 16 +++++++++++-- 14 files changed, 77 insertions(+), 24 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomMenu.h b/src/openrct2-ui/scripting/CustomMenu.h index 4a26fb1a56..74f1a009bd 100644 --- a/src/openrct2-ui/scripting/CustomMenu.h +++ b/src/openrct2-ui/scripting/CustomMenu.h @@ -38,7 +38,7 @@ namespace OpenRCT2::Scripting auto& execInfo = scriptEngine.GetExecInfo(); auto ctx = scriptEngine.GetContext(); - ScriptExecutionInfo::PluginScope scope(execInfo, Owner); + ScriptExecutionInfo::PluginScope scope(execInfo, Owner, false); Callback.push(); duk_pcall(ctx, 0); duk_pop(ctx); diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 7a55c621cd..d93b512d13 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -648,7 +648,7 @@ namespace OpenRCT2::Ui::Windows auto& scriptEngine = GetContext()->GetScriptEngine(); auto& execInfo = scriptEngine.GetExecInfo(); { - ScriptExecutionInfo::PluginScope scope(execInfo, owner); + ScriptExecutionInfo::PluginScope scope(execInfo, owner, false); dukHandler.push(); for (const auto& arg : args) { diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index 17e5e99169..c56cfccec5 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -232,7 +232,8 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScViewport::bottom_get, &ScViewport::bottom_set, "bottom"); dukglue_register_property(ctx, &ScViewport::rotation_get, &ScViewport::rotation_set, "rotation"); dukglue_register_property(ctx, &ScViewport::zoom_get, &ScViewport::zoom_set, "zoom"); - dukglue_register_property(ctx, &ScViewport::visibilityFlags_get, &ScViewport::visibilityFlags_set, "visibilityFlags"); + dukglue_register_property( + ctx, &ScViewport::visibilityFlags_get, &ScViewport::visibilityFlags_set, "visibilityFlags"); dukglue_register_method(ctx, &ScViewport::getCentrePosition, "getCentrePosition"); dukglue_register_method(ctx, &ScViewport::moveTo, "moveTo"); dukglue_register_method(ctx, &ScViewport::scrollTo, "scrollTo"); diff --git a/src/openrct2/GameState.cpp b/src/openrct2/GameState.cpp index 2523a03dac..568fdb2183 100644 --- a/src/openrct2/GameState.cpp +++ b/src/openrct2/GameState.cpp @@ -270,7 +270,7 @@ void GameState::UpdateLogic() } auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); - hookEngine.Call(HOOK_TYPE::INTERVAL_TICK); + hookEngine.Call(HOOK_TYPE::INTERVAL_TICK, true); auto day = _date.GetDay(); @@ -279,7 +279,7 @@ void GameState::UpdateLogic() if (day != _date.GetDay()) { - hookEngine.Call(HOOK_TYPE::INTERVAL_DAY); + hookEngine.Call(HOOK_TYPE::INTERVAL_DAY, true); } scenario_update(); diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 182c6c2153..10f36d33a6 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -2905,7 +2905,7 @@ void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& p auto e = DukValue::take_from_stack(ctx); // Call the subscriptions - hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, e); + hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, e, false); // Update text from object if subscriptions changed it if (e["message"].type() != DukValue::Type::STRING) diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 695586b9cb..be79ffe3b3 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -93,12 +93,12 @@ bool HookEngine::HasSubscriptions(HOOK_TYPE type) const return !hookList.Hooks.empty(); } -void HookEngine::Call(HOOK_TYPE type) +void HookEngine::Call(HOOK_TYPE type, bool isGameStateMutable) { auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner); + ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner, false); const auto& function = hook.Function; function.push(); @@ -107,12 +107,12 @@ void HookEngine::Call(HOOK_TYPE type) } } -void HookEngine::Call(HOOK_TYPE type, DukValue args) +void HookEngine::Call(HOOK_TYPE type, DukValue args, bool isGameStateMutable) { auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner); + ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner, false); const auto& function = hook.Function; auto ctx = function.context(); @@ -124,12 +124,12 @@ void HookEngine::Call(HOOK_TYPE type, DukValue args) } } -void HookEngine::Call(HOOK_TYPE type, const std::initializer_list>& args) +void HookEngine::Call(HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable) { auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner); + ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner, false); const auto& function = hook.Function; auto ctx = function.context(); diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index e2dde251b8..9efa3d4a74 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -81,9 +81,9 @@ namespace OpenRCT2::Scripting void UnsubscribeAll(std::shared_ptr owner); void UnsubscribeAll(); bool HasSubscriptions(HOOK_TYPE type) const; - void Call(HOOK_TYPE type); - void Call(HOOK_TYPE type, DukValue args); - void Call(HOOK_TYPE type, const std::initializer_list>& args); + void Call(HOOK_TYPE type, bool isGameStateMutable); + void Call(HOOK_TYPE type, DukValue args, bool isGameStateMutable); + void Call(HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable); private: HookList& GetHookList(HOOK_TYPE type); diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 03bb89c715..96838e5c90 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -42,6 +42,7 @@ namespace OpenRCT2::Scripting void monthsElapsed_set(uint32_t value) { + ThrowIfGameStateNotMutable(); gDateMonthsElapsed = value; } @@ -53,6 +54,7 @@ namespace OpenRCT2::Scripting void monthProgress_set(int32_t value) { + ThrowIfGameStateNotMutable(); gDateMonthTicks = value; } diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 57d133f57e..6d073df32c 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -16,6 +16,7 @@ #include "../windows/Intent.h" #include "../world/Park.h" #include "Duktape.hpp" +#include "ScriptEngine.h" #include @@ -30,6 +31,7 @@ namespace OpenRCT2::Scripting } void cash_set(money32 value) { + ThrowIfGameStateNotMutable(); gCash = value; auto intent = Intent(INTENT_ACTION_UPDATE_CASH); context_broadcast_intent(&intent); @@ -41,6 +43,7 @@ namespace OpenRCT2::Scripting } void rating_set(int32_t value) { + ThrowIfGameStateNotMutable(); gParkRating = std::min(std::max(0, value), 999); auto intent = Intent(INTENT_ACTION_UPDATE_PARK_RATING); context_broadcast_intent(&intent); @@ -52,6 +55,7 @@ namespace OpenRCT2::Scripting } void bankLoan_set(money32 value) { + ThrowIfGameStateNotMutable(); gBankLoan = value; auto intent = Intent(INTENT_ACTION_UPDATE_CASH); context_broadcast_intent(&intent); @@ -63,6 +67,7 @@ namespace OpenRCT2::Scripting } void maxBankLoan_set(money32 value) { + ThrowIfGameStateNotMutable(); gMaxBankLoan = value; auto intent = Intent(INTENT_ACTION_UPDATE_CASH); context_broadcast_intent(&intent); @@ -70,6 +75,7 @@ namespace OpenRCT2::Scripting void postMessage(DukValue message) { + ThrowIfGameStateNotMutable(); try { uint8_t type = NEWS_ITEM_BLANK; diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index f316bf906c..1e75fb7d3b 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -114,6 +114,7 @@ namespace OpenRCT2::Scripting } void name_set(std::string value) { + ThrowIfGameStateNotMutable(); _ride->custom_name = value; } @@ -123,6 +124,7 @@ namespace OpenRCT2::Scripting } void excitement_set(int32_t value) { + ThrowIfGameStateNotMutable(); _ride->excitement = value; } @@ -132,6 +134,7 @@ namespace OpenRCT2::Scripting } void intensity_set(int32_t value) { + ThrowIfGameStateNotMutable(); _ride->intensity = value; } @@ -141,6 +144,7 @@ namespace OpenRCT2::Scripting } void nausea_set(int32_t value) { + ThrowIfGameStateNotMutable(); _ride->nausea = value; } @@ -150,6 +154,7 @@ namespace OpenRCT2::Scripting } void totalCustomers_set(int32_t value) { + ThrowIfGameStateNotMutable(); _ride->total_customers = value; } diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 41496e1199..e67aa60b24 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -42,7 +42,8 @@ namespace OpenRCT2::Scripting } void x_set(int32_t value) { - _sprite->generic.x = value; + ThrowIfGameStateNotMutable(); + sprite_move(value, _sprite->generic.y, _sprite->generic.z, &_sprite->generic); } // y getter and setter @@ -52,7 +53,8 @@ namespace OpenRCT2::Scripting } void y_set(int32_t value) { - _sprite->generic.y = value; + ThrowIfGameStateNotMutable(); + sprite_move(_sprite->generic.x, value, _sprite->generic.z, &_sprite->generic); } // z getter and setter @@ -62,7 +64,8 @@ namespace OpenRCT2::Scripting } void z_set(int16_t value) { - _sprite->generic.z = value; + ThrowIfGameStateNotMutable(); + sprite_move(_sprite->generic.x, _sprite->generic.y, value, &_sprite->generic); } uint8_t tshirtColour_get() @@ -71,6 +74,7 @@ namespace OpenRCT2::Scripting } void tshirtColour_set(uint8_t value) { + ThrowIfGameStateNotMutable(); _sprite->peep.tshirt_colour = value; } uint8_t trousersColour_get() @@ -79,6 +83,7 @@ namespace OpenRCT2::Scripting } void trousersColour_set(uint8_t value) { + ThrowIfGameStateNotMutable(); _sprite->peep.trousers_colour = value; } diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 82593fe111..d65e9ed3ac 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -69,6 +69,7 @@ namespace OpenRCT2::Scripting } void broken_set(bool value) { + ThrowIfGameStateNotMutable(); if (value) { _element->flags |= TILE_ELEMENT_FLAG_BROKEN; @@ -85,6 +86,7 @@ namespace OpenRCT2::Scripting } void baseHeight_set(uint8_t newBaseHeight) { + ThrowIfGameStateNotMutable(); _element->base_height = newBaseHeight; } @@ -94,6 +96,7 @@ namespace OpenRCT2::Scripting } void clearanceHeight_set(uint8_t newClearanceHeight) { + ThrowIfGameStateNotMutable(); _element->clearance_height = newClearanceHeight; } @@ -106,6 +109,7 @@ namespace OpenRCT2::Scripting } void grassLength_set(uint8_t value) { + ThrowIfGameStateNotMutable(); auto el = _element->AsSurface(); if (el != nullptr) { diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 163b8e5b74..e067791114 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -132,7 +132,7 @@ void ScriptEngine::LoadPlugin(std::shared_ptr& plugin) { try { - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin, false); plugin->Load(); auto metadata = plugin->GetMetadata(); @@ -162,7 +162,7 @@ void ScriptEngine::StopPlugin(std::shared_ptr plugin) callback(plugin); } - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin, false); try { plugin->Stop(); @@ -214,7 +214,7 @@ void ScriptEngine::AutoReloadPlugins() { StopPlugin(plugin); - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin, false); plugin->Load(); LogPluginInfo(plugin, "Reloaded"); plugin->Start(); @@ -247,7 +247,7 @@ void ScriptEngine::StartPlugins() { if (!plugin->HasStarted() && ShouldStartPlugin(plugin)) { - ScriptExecutionInfo::PluginScope scope(_execInfo, plugin); + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin, false); try { LogPluginInfo(plugin, "Started"); @@ -380,3 +380,21 @@ static std::string Stringify(duk_context* ctx, duk_idx_t idx) return duk_safe_to_string(ctx, idx); } } + +bool OpenRCT2::Scripting::IsGameStateMutable() +{ + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto& execInfo = scriptEngine.GetExecInfo(); + return execInfo.IsGameStateMutable(); +} + +void OpenRCT2::Scripting::ThrowIfGameStateNotMutable() +{ + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto& execInfo = scriptEngine.GetExecInfo(); + if (!execInfo.IsGameStateMutable()) + { + auto ctx = scriptEngine.GetContext(); + duk_error(ctx, DUK_ERR_ERROR, "Game state is not mutable in this context."); + } +} diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 4156c13825..da6517f699 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -39,6 +39,7 @@ namespace OpenRCT2::Scripting { private: std::shared_ptr _plugin; + bool _isGameStateMutable{}; public: class PluginScope @@ -48,16 +49,18 @@ namespace OpenRCT2::Scripting std::shared_ptr _plugin; public: - PluginScope(ScriptExecutionInfo& execInfo, std::shared_ptr plugin) + PluginScope(ScriptExecutionInfo& execInfo, std::shared_ptr plugin, bool isGameStateMutable) : _execInfo(execInfo) , _plugin(plugin) { _execInfo._plugin = plugin; + _execInfo._isGameStateMutable = isGameStateMutable; } PluginScope(const PluginScope&) = delete; ~PluginScope() { _execInfo._plugin = nullptr; + _execInfo._isGameStateMutable = false; } }; @@ -65,6 +68,11 @@ namespace OpenRCT2::Scripting { return _plugin; } + + bool IsGameStateMutable() + { + return _isGameStateMutable; + } }; class DukContext @@ -150,9 +158,13 @@ namespace OpenRCT2::Scripting void LoadPlugin(std::shared_ptr& plugin); void StopPlugin(std::shared_ptr plugin); bool ShouldLoadScript(const std::string& path); - bool ShouldStartPlugin(const std::shared_ptr &plugin); + bool ShouldStartPlugin(const std::shared_ptr& plugin); void SetupHotReloading(); void AutoReloadPlugins(); void ProcessREPL(); }; + + bool IsGameStateMutable(); + void ThrowIfGameStateNotMutable(); + } // namespace OpenRCT2::Scripting From 34078124cddd2497938556c66b37ce837d3df186 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 23 Feb 2020 12:22:15 +0000 Subject: [PATCH 076/159] Fix formatting --- src/openrct2/scripting/HookEngine.cpp | 3 ++- src/openrct2/scripting/HookEngine.h | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index be79ffe3b3..1e6801d189 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -124,7 +124,8 @@ void HookEngine::Call(HOOK_TYPE type, DukValue args, bool isGameStateMutable) } } -void HookEngine::Call(HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable) +void HookEngine::Call( + HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable) { auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 9efa3d4a74..042bcbe52a 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -83,7 +83,8 @@ namespace OpenRCT2::Scripting bool HasSubscriptions(HOOK_TYPE type) const; void Call(HOOK_TYPE type, bool isGameStateMutable); void Call(HOOK_TYPE type, DukValue args, bool isGameStateMutable); - void Call(HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable); + void Call( + HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable); private: HookList& GetHookList(HOOK_TYPE type); From bac91cd563e270b080a1a65acc92627d13164ec2 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 23 Feb 2020 12:55:48 +0000 Subject: [PATCH 077/159] Allow scripting to be compile-disabled --- openrct2.common.props | 1 + src/openrct2-ui/UiContext.cpp | 2 + src/openrct2-ui/scripting/CustomMenu.cpp | 6 ++- src/openrct2-ui/scripting/CustomMenu.h | 16 +++++--- src/openrct2-ui/scripting/CustomWindow.cpp | 32 ++++++++------- src/openrct2-ui/scripting/UiExtensions.cpp | 16 +++++--- src/openrct2-ui/windows/TopToolbar.cpp | 4 ++ src/openrct2/Context.cpp | 9 +++++ src/openrct2/Context.h | 2 + src/openrct2/Game.cpp | 4 ++ src/openrct2/GameState.cpp | 4 ++ src/openrct2/interface/InteractiveConsole.h | 5 +++ src/openrct2/interface/StdInOutConsole.cpp | 27 +++++++++++++ src/openrct2/network/Network.cpp | 23 +++++++++-- src/openrct2/scripting/HookEngine.cpp | 12 ++++-- src/openrct2/scripting/ScriptEngine.cpp | 44 +++++++++++---------- src/openrct2/scripting/ScriptEngine.h | 26 ++++++------ 17 files changed, 167 insertions(+), 66 deletions(-) diff --git a/openrct2.common.props b/openrct2.common.props index e62f3ea129..f8228d5e25 100644 --- a/openrct2.common.props +++ b/openrct2.common.props @@ -54,6 +54,7 @@ C4555: expression has no effect; expected expression with side-effect --> __AVX2__;__SSE4_1__;OPENGL_NO_LINK;_CRT_SECURE_NO_WARNINGS;_USE_MATH_DEFINES;SDL_MAIN_HANDLED;_WINSOCK_DEPRECATED_NO_WARNINGS;NOMINMAX;%(PreprocessorDefinitions) + __ENABLE_SCRIPTING__;%(PreprocessorDefinitions) MultiThreaded MultiThreadedDLL true diff --git a/src/openrct2-ui/UiContext.cpp b/src/openrct2-ui/UiContext.cpp index 1f75eac344..78d8b9ee75 100644 --- a/src/openrct2-ui/UiContext.cpp +++ b/src/openrct2-ui/UiContext.cpp @@ -120,8 +120,10 @@ public: void Initialise() override { +#ifdef __ENABLE_SCRIPTING__ auto& scriptEngine = GetContext()->GetScriptEngine(); UiScriptExtensions::Extend(scriptEngine); +#endif } void Update() override diff --git a/src/openrct2-ui/scripting/CustomMenu.cpp b/src/openrct2-ui/scripting/CustomMenu.cpp index 63e79e3b67..542a0366b6 100644 --- a/src/openrct2-ui/scripting/CustomMenu.cpp +++ b/src/openrct2-ui/scripting/CustomMenu.cpp @@ -7,7 +7,9 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "CustomMenu.h" +#ifdef __ENABLE_SCRIPTING__ + +# include "CustomMenu.h" namespace OpenRCT2::Scripting { @@ -34,3 +36,5 @@ namespace OpenRCT2::Scripting scriptEngine.SubscribeToPluginStoppedEvent([](std::shared_ptr plugin) -> void { RemoveMenuItems(plugin); }); } } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2-ui/scripting/CustomMenu.h b/src/openrct2-ui/scripting/CustomMenu.h index 74f1a009bd..05300ac894 100644 --- a/src/openrct2-ui/scripting/CustomMenu.h +++ b/src/openrct2-ui/scripting/CustomMenu.h @@ -9,12 +9,14 @@ #pragma once -#include -#include -#include -#include -#include -#include +#ifdef __ENABLE_SCRIPTING__ + +# include +# include +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -50,3 +52,5 @@ namespace OpenRCT2::Scripting void InitialiseCustomMenuItems(ScriptEngine& scriptEngine); } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index d93b512d13..28c5af6a66 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -7,21 +7,23 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "../interface/Dropdown.h" -#include "ScUi.hpp" -#include "ScWindow.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include "../interface/Dropdown.h" +# include "ScUi.hpp" +# include "ScWindow.hpp" + +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -711,3 +713,5 @@ namespace OpenRCT2::Ui::Windows } } // namespace OpenRCT2::Ui::Windows + +#endif diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index 0eb68ea9d6..b70f9552fc 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -7,14 +7,16 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "UiExtensions.h" +#ifdef __ENABLE_SCRIPTING__ -#include "CustomMenu.h" -#include "ScUi.hpp" -#include "ScWidget.hpp" -#include "ScWindow.hpp" +# include "UiExtensions.h" -#include +# include "CustomMenu.h" +# include "ScUi.hpp" +# include "ScWidget.hpp" +# include "ScWindow.hpp" + +# include using namespace OpenRCT2::Scripting; @@ -31,3 +33,5 @@ void UiScriptExtensions::Extend(ScriptEngine& scriptEngine) InitialiseCustomMenuItems(scriptEngine); } + +#endif diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index 48c81d0643..0ddd5ade53 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -3282,6 +3282,7 @@ static void top_toolbar_init_map_menu(rct_window* w, rct_widget* widget) gDropdownItemsFormat[i++] = STR_MAPGEN_WINDOW_TITLE; } +#ifdef __ENABLE_SCRIPTING__ const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; if (!customMenuItems.empty()) { @@ -3293,6 +3294,7 @@ static void top_toolbar_init_map_menu(rct_window* w, rct_widget* widget) i++; } } +#endif window_dropdown_show_text( w->windowPos.x + widget->left, w->windowPos.y + widget->top, widget->bottom - widget->top + 1, w->colours[1] | 0x80, 0, @@ -3325,12 +3327,14 @@ static void top_toolbar_map_menu_dropdown(int16_t dropdownIndex) } else { +#ifdef __ENABLE_SCRIPTING__ const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; auto customIndex = static_cast(dropdownIndex - customStartIndex); if (customMenuItems.size() > customIndex) { customMenuItems[customIndex].Invoke(); } +#endif } } diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 7dd8edf040..0a04bea93b 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -103,7 +103,9 @@ namespace OpenRCT2 std::unique_ptr _discordService; #endif StdInOutConsole _stdInOutConsole; +#ifdef __ENABLE_SCRIPTING__ ScriptEngine _scriptEngine; +#endif // Game states std::unique_ptr _titleScreen; @@ -138,7 +140,9 @@ namespace OpenRCT2 , _audioContext(audioContext) , _uiContext(uiContext) , _localisationService(std::make_unique(env)) +#ifdef __ENABLE_SCRIPTING__ , _scriptEngine(_stdInOutConsole, *env) +#endif , _painter(std::make_unique(uiContext)) { // Can't have more than one context currently. @@ -181,10 +185,12 @@ namespace OpenRCT2 return _uiContext; } +#ifdef __ENABLE_SCRIPTING__ Scripting::ScriptEngine& GetScriptEngine() override { return _scriptEngine; } +#endif GameState* GetGameState() override { @@ -1026,7 +1032,10 @@ namespace OpenRCT2 Twitch::Update(); chat_update(); +#ifdef __ENABLE_SCRIPTING__ _scriptEngine.Update(); +#endif + _stdInOutConsole.ProcessEvalQueue(); _uiContext->Update(); } diff --git a/src/openrct2/Context.h b/src/openrct2/Context.h index c8ee6181ed..0ec9465f13 100644 --- a/src/openrct2/Context.h +++ b/src/openrct2/Context.h @@ -114,7 +114,9 @@ namespace OpenRCT2 virtual Localisation::LocalisationService& GetLocalisationService() abstract; virtual IObjectManager& GetObjectManager() abstract; virtual IObjectRepository& GetObjectRepository() abstract; +#ifdef __ENABLE_SCRIPTING__ virtual Scripting::ScriptEngine& GetScriptEngine() abstract; +#endif virtual ITrackDesignRepository* GetTrackDesignRepository() abstract; virtual IScenarioRepository* GetScenarioRepository() abstract; virtual IReplayManager* GetReplayManager() abstract; diff --git a/src/openrct2/Game.cpp b/src/openrct2/Game.cpp index 7526bb5d2c..cdbf7ff8bc 100644 --- a/src/openrct2/Game.cpp +++ b/src/openrct2/Game.cpp @@ -592,12 +592,16 @@ void game_load_init() void game_load_scripts() { +#ifdef __ENABLE_SCRIPTING__ GetContext()->GetScriptEngine().LoadPlugins(); +#endif } void game_finish() { +#ifdef __ENABLE_SCRIPTING__ GetContext()->GetScriptEngine().UnloadPlugins(); +#endif } /** diff --git a/src/openrct2/GameState.cpp b/src/openrct2/GameState.cpp index 568fdb2183..4e9de175a2 100644 --- a/src/openrct2/GameState.cpp +++ b/src/openrct2/GameState.cpp @@ -269,18 +269,22 @@ void GameState::UpdateLogic() } } +#ifdef __ENABLE_SCRIPTING__ auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); hookEngine.Call(HOOK_TYPE::INTERVAL_TICK, true); auto day = _date.GetDay(); +#endif date_update(); _date = Date(gDateMonthsElapsed, gDateMonthTicks); +#ifdef __ENABLE_SCRIPTING__ if (day != _date.GetDay()) { hookEngine.Call(HOOK_TYPE::INTERVAL_DAY, true); } +#endif scenario_update(); climate_update(); diff --git a/src/openrct2/interface/InteractiveConsole.h b/src/openrct2/interface/InteractiveConsole.h index ce35d74e1d..136c135eb8 100644 --- a/src/openrct2/interface/InteractiveConsole.h +++ b/src/openrct2/interface/InteractiveConsole.h @@ -13,6 +13,7 @@ #include "../localisation/FormatCodes.h" #include +#include #include struct rct_drawpixelinfo; @@ -50,9 +51,13 @@ public: class StdInOutConsole final : public InteractiveConsole { +private: + std::queue, std::string>> _evalQueue; + public: void Start(); std::future Eval(const std::string& s); + void ProcessEvalQueue(); void Clear() override; void Close() override; diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index 9491b00cd7..9fc0ac896a 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -55,8 +55,35 @@ void StdInOutConsole::Start() std::future StdInOutConsole::Eval(const std::string& s) { +#ifdef __ENABLE_SCRIPTING__ auto& scriptEngine = GetContext()->GetScriptEngine(); return scriptEngine.Eval(s); +#else + // Push on-demand evaluations onto a queue so that it can be processed deterministically + // on the main thead at the right time. + std::promise barrier; + auto future = barrier.get_future(); + _evalQueue.emplace(std::move(barrier), s); + return future; +#endif +} + +void StdInOutConsole::ProcessEvalQueue() +{ +#ifndef __ENABLE_SCRIPTING__ + while (_evalQueue.size() > 0) + { + auto item = std::move(_evalQueue.front()); + _evalQueue.pop(); + auto promise = std::move(std::get<0>(item)); + auto command = std::move(std::get<1>(item)); + + Execute(command); + + // Signal the promise so caller can continue + promise.set_value(); + } +#endif } void StdInOutConsole::Clear() diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 10f36d33a6..8ced55ee05 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -1472,6 +1472,9 @@ void Network::Server_Send_OBJECTS(NetworkConnection& connection, const std::vect void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const { + std::unique_ptr packet(NetworkPacket::Allocate()); + *packet << (uint32_t)NETWORK_COMMAND_SCRIPTS; +# ifdef __ENABLE_SCRIPTING__ using namespace OpenRCT2::Scripting; auto& scriptEngine = GetContext()->GetScriptEngine(); @@ -1487,8 +1490,7 @@ void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const } log_verbose("Server sends %u scripts", pluginsToSend.size()); - std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_SCRIPTS << (uint32_t)pluginsToSend.size(); + *packet << (uint32_t)pluginsToSend.size(); for (const auto& plugin : pluginsToSend) { const auto& metadata = plugin->GetMetadata(); @@ -1498,6 +1500,9 @@ void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const *packet << (uint32_t)code.size(); packet->Write((const uint8_t*)code.c_str(), code.size()); } +# else + *packet << (uint32_t)0; +# endif connection.QueuePacket(std::move(packet)); } @@ -2437,10 +2442,11 @@ void Network::Client_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket void Network::Client_Handle_SCRIPTS(NetworkConnection& connection, NetworkPacket& packet) { - auto& scriptEngine = GetContext()->GetScriptEngine(); - uint32_t numScripts{}; packet >> numScripts; + +# ifdef __ENABLE_SCRIPTING__ + auto& scriptEngine = GetContext()->GetScriptEngine(); for (uint32_t i = 0; i < numScripts; i++) { uint32_t codeLength{}; @@ -2448,6 +2454,13 @@ void Network::Client_Handle_SCRIPTS(NetworkConnection& connection, NetworkPacket auto code = std::string_view((const char*)packet.Read(codeLength), codeLength); scriptEngine.AddNetworkPlugin(code); } +# else + if (numScripts > 0) + { + connection.SetLastDisconnectReason("The server requires plugin support."); + Close(); + } +# endif } void Network::Client_Handle_GAMESTATE(NetworkConnection& connection, NetworkPacket& packet) @@ -2891,6 +2904,7 @@ void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& p std::string text = szText; if (connection.Player != nullptr) { +# ifdef __ENABLE_SCRIPTING__ auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT)) { @@ -2920,6 +2934,7 @@ void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& p return; } } +# endif } const char* formatted = FormatChat(connection.Player, text.c_str()); diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 1e6801d189..ee554fd75a 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 @@ -7,11 +7,13 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "HookEngine.h" +#ifdef __ENABLE_SCRIPTING__ -#include "ScriptEngine.h" +# include "HookEngine.h" -#include +# include "ScriptEngine.h" + +# include using namespace OpenRCT2::Scripting; @@ -171,3 +173,5 @@ const HookList& HookEngine::GetHookList(HOOK_TYPE type) const auto index = static_cast(type); return _hookMap[index]; } + +#endif diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index e067791114..796cb96e02 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -7,28 +7,30 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "ScriptEngine.h" +#ifdef __ENABLE_SCRIPTING__ -#include "../PlatformEnvironment.h" -#include "../config/Config.h" -#include "../core/FileScanner.h" -#include "../core/Path.hpp" -#include "../interface/InteractiveConsole.h" -#include "../platform/Platform2.h" -#include "Duktape.hpp" -#include "ScConsole.hpp" -#include "ScContext.hpp" -#include "ScDate.hpp" -#include "ScDisposable.hpp" -#include "ScMap.hpp" -#include "ScNetwork.hpp" -#include "ScPark.hpp" -#include "ScRide.hpp" -#include "ScThing.hpp" -#include "ScTile.hpp" +# include "ScriptEngine.h" -#include -#include +# include "../PlatformEnvironment.h" +# include "../config/Config.h" +# include "../core/FileScanner.h" +# include "../core/Path.hpp" +# include "../interface/InteractiveConsole.h" +# include "../platform/Platform2.h" +# include "Duktape.hpp" +# include "ScConsole.hpp" +# include "ScContext.hpp" +# include "ScDate.hpp" +# include "ScDisposable.hpp" +# include "ScMap.hpp" +# include "ScNetwork.hpp" +# include "ScPark.hpp" +# include "ScRide.hpp" +# include "ScThing.hpp" +# include "ScTile.hpp" + +# include +# include using namespace OpenRCT2; using namespace OpenRCT2::Scripting; @@ -398,3 +400,5 @@ void OpenRCT2::Scripting::ThrowIfGameStateNotMutable() duk_error(ctx, DUK_ERR_ERROR, "Game state is not mutable in this context."); } } + +#endif diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index da6517f699..6ebce0af41 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -9,18 +9,20 @@ #pragma once -#include "../common.h" -#include "../core/FileWatcher.h" -#include "HookEngine.h" -#include "Plugin.h" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include -#include -#include -#include +# include "../common.h" +# include "../core/FileWatcher.h" +# include "HookEngine.h" +# include "Plugin.h" + +# include +# include +# include +# include +# include +# include +# include struct duk_hthread; typedef struct duk_hthread duk_context; @@ -168,3 +170,5 @@ namespace OpenRCT2::Scripting void ThrowIfGameStateNotMutable(); } // namespace OpenRCT2::Scripting + +#endif From e6341f0a421f02f8688b747a17ec1009fbed23ca Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 23 Feb 2020 15:33:01 +0000 Subject: [PATCH 078/159] Get scripting compiling on clang --- .vscode/c_cpp_properties.json | 1 + CMakeLists.txt | 4 + openrct2.common.props | 2 +- scripts/check-code-formatting | 2 +- .../app/src/main/CMakeLists.txt | 2 + src/openrct2-ui/CMakeLists.txt | 2 +- src/openrct2-ui/scripting/CustomWindow.cpp | 13 +-- src/openrct2-ui/scripting/CustomWindow.h | 12 ++- src/openrct2-ui/scripting/ScUi.hpp | 22 +++--- src/openrct2-ui/scripting/ScViewport.hpp | 20 +++-- src/openrct2-ui/scripting/ScWidget.hpp | 22 +++--- src/openrct2-ui/scripting/ScWindow.hpp | 14 ++-- src/openrct2-ui/scripting/UiExtensions.h | 4 + src/openrct2/CMakeLists.txt | 2 +- src/openrct2/core/FileSystem.hpp | 2 +- src/openrct2/interface/StdInOutConsole.cpp | 3 +- src/openrct2/scripting/Duktape.hpp | 17 +++- src/openrct2/scripting/HookEngine.h | 19 +++-- src/openrct2/scripting/Plugin.cpp | 16 ++-- src/openrct2/scripting/Plugin.h | 14 ++-- src/openrct2/scripting/ScConsole.hpp | 8 +- src/openrct2/scripting/ScContext.hpp | 16 ++-- src/openrct2/scripting/ScDate.hpp | 19 +++-- src/openrct2/scripting/ScDisposable.hpp | 8 +- src/openrct2/scripting/ScMap.hpp | 18 +++-- src/openrct2/scripting/ScNetwork.hpp | 79 +++++++++++++++++-- src/openrct2/scripting/ScPark.hpp | 22 +++--- src/openrct2/scripting/ScRide.hpp | 13 ++- src/openrct2/scripting/ScThing.hpp | 11 ++- src/openrct2/scripting/ScTile.hpp | 19 +++-- .../thirdparty/dukglue/detail_class_proto.h | 0 .../thirdparty/dukglue/detail_constructor.h | 0 .../thirdparty/dukglue/detail_function.h | 0 .../thirdparty/dukglue/detail_method.h | 0 .../dukglue/detail_primitive_types.h | 0 .../thirdparty/dukglue/detail_refs.h | 0 .../thirdparty/dukglue/detail_stack.h | 0 .../thirdparty/dukglue/detail_traits.h | 0 .../thirdparty/dukglue/detail_typeinfo.h | 0 .../thirdparty/dukglue/detail_types.h | 0 .../thirdparty/dukglue/dukexception.h | 0 .../thirdparty/dukglue/dukglue.h | 0 .../thirdparty/dukglue/dukvalue.h | 0 .../thirdparty/dukglue/public_util.h | 0 .../thirdparty/dukglue/register_class.h | 0 .../thirdparty/dukglue/register_function.h | 0 .../thirdparty/dukglue/register_property.h | 0 src/{openrct2 => }/thirdparty/filesystem.hpp | 0 src/{openrct2 => }/thirdparty/linenoise.hpp | 0 49 files changed, 282 insertions(+), 124 deletions(-) rename src/{openrct2 => }/thirdparty/dukglue/detail_class_proto.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_constructor.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_function.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_method.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_primitive_types.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_refs.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_stack.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_traits.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_typeinfo.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/detail_types.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/dukexception.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/dukglue.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/dukvalue.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/public_util.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/register_class.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/register_function.h (100%) rename src/{openrct2 => }/thirdparty/dukglue/register_property.h (100%) rename src/{openrct2 => }/thirdparty/filesystem.hpp (100%) rename src/{openrct2 => }/thirdparty/linenoise.hpp (100%) diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index 148ce9879b..ede5d8c31e 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -56,6 +56,7 @@ "includePath": [ "${workspaceRoot}", "${workspaceRoot}/src", + "${workspaceRoot}/src/thirdparty", "${workspaceRoot}/lib/Win32/include", "${workspaceRoot}/lib/x64/include", "${workspaceRoot}/lib/googletest/googletest/include" diff --git a/CMakeLists.txt b/CMakeLists.txt index 33107734dd..99c2549ed2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,7 @@ option(DISABLE_HTTP_TWITCH "Disable HTTP and Twitch support.") option(DISABLE_NETWORK "Disable multiplayer functionality. Mainly for testing.") option(DISABLE_TTF "Disable support for TTF provided by freetype2.") option(ENABLE_LIGHTFX "Enable lighting effects." ON) +option(ENABLE_SCRIPTING "Enable script / plugin support." ON) option(DISABLE_GUI "Don't build GUI. (Headless only.)") @@ -121,6 +122,9 @@ endif () if (ENABLE_LIGHTFX) add_definitions(-D__ENABLE_LIGHTFX__) endif () +if (ENABLE_SCRIPTING) + add_definitions(-D__ENABLE_SCRIPTING__) +endif () if (NOT DISABLE_DISCORD_RPC) if(EXISTS "${ROOT_DIR}/discord-rpc") diff --git a/openrct2.common.props b/openrct2.common.props index f8228d5e25..49b68916f3 100644 --- a/openrct2.common.props +++ b/openrct2.common.props @@ -102,7 +102,7 @@ - $(SolutionDir)src;$(SolutionDir)src\openrct2\thirdparty;$(SolutionDir)lib\$(Platform)\include;$(SolutionDir)lib\$(Platform)\include\SDL2;$(IncludePath) + $(SolutionDir)src;$(SolutionDir)src\thirdparty;$(SolutionDir)lib\$(Platform)\include;$(SolutionDir)lib\$(Platform)\include\SDL2;$(IncludePath) $(SolutionDir)lib\$(Platform)\debug\lib;$(LibraryPath) $(SolutionDir)lib\$(Platform)\lib;$(LibraryPath) diff --git a/scripts/check-code-formatting b/scripts/check-code-formatting index 491d21742b..51f8498328 100755 --- a/scripts/check-code-formatting +++ b/scripts/check-code-formatting @@ -5,4 +5,4 @@ set -e basedir="$(readlink -f `dirname $0`/..)" cd $basedir -scripts/run-clang-format.py -r src test --exclude src/openrct2/thirdparty +scripts/run-clang-format.py -r src test --exclude src/thirdparty diff --git a/src/openrct2-android/app/src/main/CMakeLists.txt b/src/openrct2-android/app/src/main/CMakeLists.txt index ba367e5adf..8b865d9deb 100644 --- a/src/openrct2-android/app/src/main/CMakeLists.txt +++ b/src/openrct2-android/app/src/main/CMakeLists.txt @@ -183,5 +183,7 @@ target_link_libraries(openrct2-ui openrct2 android stdc++ GLESv1_CM GLESv2 SDL2m add_executable(openrct2-cli ${OPENRCT2_CLI_SOURCES}) target_link_libraries(openrct2-cli openrct2 android stdc++ GLESv1_CM GLESv2) +target_include_directories(openrct2 SYSTEM PRIVATE "${ORCT2_ROOT}/src/thirdparty") target_include_directories(openrct2-ui PRIVATE "${ORCT2_ROOT}/src") +target_include_directories(openrct2-ui SYSTEM PRIVATE "${ORCT2_ROOT}/src/thirdparty") target_include_directories(openrct2-cli PRIVATE "${ORCT2_ROOT}/src") diff --git a/src/openrct2-ui/CMakeLists.txt b/src/openrct2-ui/CMakeLists.txt index 0ff4920417..d4978b2ffa 100644 --- a/src/openrct2-ui/CMakeLists.txt +++ b/src/openrct2-ui/CMakeLists.txt @@ -65,7 +65,7 @@ endif () target_include_directories(${PROJECT} PRIVATE "${CMAKE_CURRENT_LIST_DIR}/.." ${SPEEX_INCLUDE_DIRS}) target_include_directories(${PROJECT} SYSTEM PRIVATE ${SDL2_INCLUDE_DIRS} - "${CMAKE_CURRENT_LIST_DIR}/../openrct2/thirdparty") + "${CMAKE_CURRENT_LIST_DIR}/../thirdparty") # Compiler flags if (WIN32) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 28c5af6a66..27525ed3e2 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -229,21 +229,14 @@ namespace OpenRCT2::Ui::Windows class CustomWindowInfo { - private: - rct_windowclass _class; - rct_windownumber _number; - public: std::shared_ptr Owner; CustomWindowDesc Desc; std::vector Widgets; std::vector WidgetIndexMap; - CustomWindowInfo( - rct_windowclass cls, rct_windownumber number, std::shared_ptr owner, const CustomWindowDesc& desc) - : _class(cls) - , _number(number) - , Owner(owner) + CustomWindowInfo(std::shared_ptr owner, const CustomWindowDesc& desc) + : Owner(owner) , Desc(desc) { } @@ -300,7 +293,7 @@ namespace OpenRCT2::Ui::Windows } window->number = GetNewWindowNumber(); - window->custom_info = new CustomWindowInfo(window->classification, window->number, owner, desc); + window->custom_info = new CustomWindowInfo(owner, desc); window->enabled_widgets = (1 << WIDX_CLOSE); window->colours[0] = COLOUR_GREY; window->colours[1] = COLOUR_GREY; diff --git a/src/openrct2-ui/scripting/CustomWindow.h b/src/openrct2-ui/scripting/CustomWindow.h index 130340375c..f63ecfcfec 100644 --- a/src/openrct2-ui/scripting/CustomWindow.h +++ b/src/openrct2-ui/scripting/CustomWindow.h @@ -7,10 +7,14 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "../interface/Window.h" +#pragma once -#include -#include +#ifdef __ENABLE_SCRIPTING__ + +# include "../interface/Window.h" + +# include +# include namespace OpenRCT2::Ui::Windows { @@ -18,3 +22,5 @@ namespace OpenRCT2::Ui::Windows rct_window* FindCustomWindowByClassification(const std::string_view& classification); std::optional FindWidgetIndexByName(rct_window* w, const std::string_view& name); } // namespace OpenRCT2::Ui::Windows + +#endif diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 3eaefe15a6..68c397c128 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -9,16 +9,18 @@ #pragma once -#include "CustomMenu.h" -#include "ScViewport.hpp" -#include "ScWindow.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include -#include -#include +# include "CustomMenu.h" +# include "ScViewport.hpp" +# include "ScWindow.hpp" + +# include +# include +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -154,3 +156,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index c56cfccec5..012205e12a 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -9,15 +9,17 @@ #pragma once -#include "../interface/Window.h" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include -#include -#include -#include +# include "../interface/Window.h" + +# include +# include +# include +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -301,3 +303,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index cca75554fb..3a43538db2 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -9,16 +9,18 @@ #pragma once -#include "../interface/Widget.h" -#include "../interface/Window.h" -#include "CustomWindow.h" -#include "ScViewport.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include -#include +# include "../interface/Widget.h" +# include "../interface/Window.h" +# include "CustomWindow.h" +# include "ScViewport.hpp" + +# include +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -291,3 +293,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 3969e73d2a..0c41b3a8a3 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -9,12 +9,14 @@ #pragma once -#include "ScWidget.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include +# include "ScWidget.hpp" + +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -140,3 +142,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2-ui/scripting/UiExtensions.h b/src/openrct2-ui/scripting/UiExtensions.h index 4f9fbfcd45..3e9af4ed22 100644 --- a/src/openrct2-ui/scripting/UiExtensions.h +++ b/src/openrct2-ui/scripting/UiExtensions.h @@ -9,6 +9,8 @@ #pragma once +#ifdef __ENABLE_SCRIPTING__ + namespace OpenRCT2::Scripting { class ScriptEngine; @@ -19,3 +21,5 @@ namespace OpenRCT2::Scripting static void Extend(ScriptEngine& scriptEngine); }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/CMakeLists.txt b/src/openrct2/CMakeLists.txt index cc9e4cc142..7bedc0006c 100644 --- a/src/openrct2/CMakeLists.txt +++ b/src/openrct2/CMakeLists.txt @@ -202,7 +202,7 @@ target_include_directories(${PROJECT_NAME} PUBLIC ${JANSSON_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PRIVATE ${PNG_INCLUDE_DIRS} ${DUKTAPE_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIRS}) -include_directories(${PROJECT_NAME} SYSTEM ${CMAKE_CURRENT_LIST_DIR}/thirdparty) +include_directories(${PROJECT_NAME} SYSTEM ${CMAKE_CURRENT_LIST_DIR}/../thirdparty) # To avoid unnecessary rebuilds set the current branch and # short sha1 only for the two files that use these diff --git a/src/openrct2/core/FileSystem.hpp b/src/openrct2/core/FileSystem.hpp index fa09497388..e33f6fc4cf 100644 --- a/src/openrct2/core/FileSystem.hpp +++ b/src/openrct2/core/FileSystem.hpp @@ -35,7 +35,7 @@ # include namespace fs = std::filesystem; #else -# include "../thirdparty/filesystem.hpp" +# include namespace fs = ghc::filesystem; #endif diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index 9fc0ac896a..92ed0970c1 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -11,9 +11,10 @@ #include "../OpenRCT2.h" #include "../platform/Platform2.h" #include "../scripting/ScriptEngine.h" -#include "../thirdparty/linenoise.hpp" #include "InteractiveConsole.h" +#include + using namespace OpenRCT2; void StdInOutConsole::Start() diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 27573a8d50..2c150d9d5a 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -1,4 +1,17 @@ +/***************************************************************************** + * Copyright (c) 2014-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 -#include -#include +#ifdef __ENABLE_SCRIPTING__ + +# include +# include + +#endif diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 042bcbe52a..cfaeaf9474 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -9,14 +9,16 @@ #pragma once -#include "../common.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include -#include +# include "../common.h" +# include "Duktape.hpp" + +# include +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -70,7 +72,6 @@ namespace OpenRCT2::Scripting private: ScriptExecutionInfo& _execInfo; std::vector _hookMap; - size_t _numHooks{}; uint32_t _nextCookie = 1; public: @@ -91,3 +92,5 @@ namespace OpenRCT2::Scripting const HookList& GetHookList(HOOK_TYPE type) const; }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index cc9ea3ce62..cb3fecd37f 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -7,14 +7,16 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "Plugin.h" +#ifdef __ENABLE_SCRIPTING__ -#include "../OpenRCT2.h" -#include "Duktape.hpp" +# include "Plugin.h" -#include -#include -#include +# include "../OpenRCT2.h" +# include "Duktape.hpp" + +# include +# include +# include using namespace OpenRCT2::Scripting; @@ -164,3 +166,5 @@ PluginType Plugin::ParsePluginType(const std::string_view& type) return PluginType::ServerClient; throw std::invalid_argument("Unknown plugin type."); } + +#endif diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 956840d55a..f584c26560 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -9,12 +9,14 @@ #pragma once -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include -#include -#include -#include +# include "Duktape.hpp" + +# include +# include +# include +# include namespace OpenRCT2::Scripting { @@ -103,3 +105,5 @@ namespace OpenRCT2::Scripting static PluginType ParsePluginType(const std::string_view& type); }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index a53a9b8b82..c3ccacbf65 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -9,8 +9,10 @@ #pragma once -#include "../interface/InteractiveConsole.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ + +# include "../interface/InteractiveConsole.h" +# include "Duktape.hpp" namespace OpenRCT2::Scripting { @@ -97,3 +99,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index b53770a9fe..e5528ac443 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -9,13 +9,15 @@ #pragma once -#include "Duktape.hpp" -#include "HookEngine.h" -#include "ScDisposable.hpp" -#include "ScriptEngine.h" +#ifdef __ENABLE_SCRIPTING__ -#include -#include +# include "Duktape.hpp" +# include "HookEngine.h" +# include "ScDisposable.hpp" +# include "ScriptEngine.h" + +# include +# include namespace OpenRCT2::Scripting { @@ -66,3 +68,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 96838e5c90..76c664364b 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -9,13 +9,16 @@ #pragma once -#include "../Context.h" -#include "../Date.h" -#include "../Game.h" -#include "../GameState.h" -#include "../common.h" -#include "../localisation/Date.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ + +# include "../Context.h" +# include "../Date.h" +# include "../Game.h" +# include "../GameState.h" +# include "../common.h" +# include "../localisation/Date.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" namespace OpenRCT2::Scripting { @@ -95,3 +98,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index 13219b0ed4..5b591e35c3 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -9,9 +9,11 @@ #pragma once -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include +# include "Duktape.hpp" + +# include namespace OpenRCT2::Scripting { @@ -40,3 +42,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 1b90ea0a8a..94f4749a3b 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -9,13 +9,15 @@ #pragma once -#include "../common.h" -#include "../ride/Ride.h" -#include "../world/Map.h" -#include "Duktape.hpp" -#include "ScRide.hpp" -#include "ScThing.hpp" -#include "ScTile.hpp" +#ifdef __ENABLE_SCRIPTING__ + +# include "../common.h" +# include "../ride/Ride.h" +# include "../world/Map.h" +# include "Duktape.hpp" +# include "ScRide.hpp" +# include "ScThing.hpp" +# include "ScTile.hpp" namespace OpenRCT2::Scripting { @@ -96,3 +98,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index 0d52b9efa4..b09fae62db 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -9,12 +9,14 @@ #pragma once -#include "../actions/NetworkModifyGroupAction.hpp" -#include "../actions/PlayerKickAction.hpp" -#include "../actions/PlayerSetGroupAction.hpp" -#include "../network/NetworkAction.h" -#include "../network/network.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ + +# include "../actions/NetworkModifyGroupAction.hpp" +# include "../actions/PlayerKickAction.hpp" +# include "../actions/PlayerSetGroupAction.hpp" +# include "../network/NetworkAction.h" +# include "../network/network.h" +# include "Duktape.hpp" namespace OpenRCT2::Scripting { @@ -36,19 +38,26 @@ namespace OpenRCT2::Scripting std::string name_get() { +# ifndef DISABLE_NETWORK auto index = network_get_group_index(_id); if (index == -1) return {}; return network_get_group_name(index); +# else + return {}; +# endif } void name_set(std::string value) { +# ifndef DISABLE_NETWORK auto action = NetworkModifyGroupAction(ModifyGroupType::SetName, _id, value); GameActions::Execute(&action); +# endif } std::vector permissions_get() { +# ifndef DISABLE_NETWORK auto index = network_get_group_index(_id); if (index == -1) return {}; @@ -66,9 +75,13 @@ namespace OpenRCT2::Scripting permissionIndex++; } return result; +# else + return {}; +# endif } void permissions_set(std::vector value) { +# ifndef DISABLE_NETWORK auto groupIndex = network_get_group_index(_id); if (groupIndex == -1) return; @@ -105,6 +118,7 @@ namespace OpenRCT2::Scripting GameActions::Execute(&networkAction2); } } +# endif } static void Register(duk_context* ctx) @@ -154,47 +168,69 @@ namespace OpenRCT2::Scripting std::string name_get() { +# ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); if (index == -1) return {}; return network_get_player_name(index); +# else + return {}; +# endif } int32_t group_get() { +# ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); if (index == -1) return {}; return network_get_player_group(index); +# else + return 0; +# endif } void group_set(int32_t value) { +# ifndef DISABLE_NETWORK auto playerSetGroupAction = PlayerSetGroupAction(_id, value); GameActions::Execute(&playerSetGroupAction); +# endif } int32_t ping_get() { +# ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); if (index == -1) return {}; return network_get_player_ping(index); +# else + return 0; +# endif } int32_t commandsRan_get() { +# ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); if (index == -1) return {}; return network_get_player_commands_ran(index); +# else + return 0; +# endif } int32_t moneySpent_get() { +# ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); if (index == -1) return {}; return network_get_player_money_spent(index); +# else + return 0; +# endif } static void Register(duk_context* ctx) @@ -211,6 +247,9 @@ namespace OpenRCT2::Scripting class ScNetwork { private: +# ifdef __clang__ + [[maybe_unused]] +# endif duk_context* _context; public: @@ -221,6 +260,7 @@ namespace OpenRCT2::Scripting std::string mode_get() { +# ifndef DISABLE_NETWORK switch (network_get_mode()) { default: @@ -231,49 +271,71 @@ namespace OpenRCT2::Scripting case NETWORK_MODE_CLIENT: return "client"; } +# else + return "none"; +# endif } int32_t players_get() { +# ifndef DISABLE_NETWORK return network_get_num_players(); +# else + return 0; +# endif } int32_t groups_get() { +# ifndef DISABLE_NETWORK return network_get_num_groups(); +# else + return 0; +# endif } int32_t defaultGroup_get() { +# ifndef DISABLE_NETWORK return network_get_default_group(); +# else + return 0; +# endif } void defaultGroup_set(int32_t value) { +# ifndef DISABLE_NETWORK auto action = NetworkModifyGroupAction(ModifyGroupType::SetDefault, value); GameActions::Execute(&action); +# endif } std::shared_ptr getPlayer(int32_t index) { +# ifndef DISABLE_NETWORK auto numPlayers = network_get_num_players(); if (index < numPlayers) { auto playerId = network_get_player_id(index); return std::make_shared(playerId); } +# endif return nullptr; } std::shared_ptr getGroup(int32_t index) { +# ifndef DISABLE_NETWORK auto numGroups = network_get_num_groups(); if (index < numGroups) { auto groupId = network_get_group_id(index); return std::make_shared(groupId); } +# endif return nullptr; } void kickPlayer(int32_t index) { +# ifndef DISABLE_NETWORK auto numPlayers = network_get_num_players(); if (index < numPlayers) { @@ -281,10 +343,12 @@ namespace OpenRCT2::Scripting auto kickPlayerAction = PlayerKickAction(playerId); GameActions::Execute(&kickPlayerAction); } +# endif } void sendMessage(std::string message, DukValue players) { +# ifndef DISABLE_NETWORK if (players.is_array()) { duk_error(players.context(), DUK_ERR_ERROR, "Not yet supported"); @@ -293,6 +357,7 @@ namespace OpenRCT2::Scripting { network_send_chat(message.c_str()); } +# endif } static void Register(duk_context* ctx) @@ -308,3 +373,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 6d073df32c..7b908b8cd4 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -9,16 +9,18 @@ #pragma once -#include "../Context.h" -#include "../common.h" -#include "../management/Finance.h" -#include "../management/NewsItem.h" -#include "../windows/Intent.h" -#include "../world/Park.h" -#include "Duktape.hpp" -#include "ScriptEngine.h" +#ifdef __ENABLE_SCRIPTING__ -#include +# include "../Context.h" +# include "../common.h" +# include "../management/Finance.h" +# include "../management/NewsItem.h" +# include "../windows/Intent.h" +# include "../world/Park.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" + +# include namespace OpenRCT2::Scripting { @@ -123,3 +125,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index 1e75fb7d3b..71fc3c8ad1 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -9,10 +9,13 @@ #pragma once -#include "../common.h" -#include "../object/RideObject.h" -#include "../ride/Ride.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ + +# include "../common.h" +# include "../object/RideObject.h" +# include "../ride/Ride.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" namespace OpenRCT2::Scripting { @@ -171,3 +174,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index e67aa60b24..d741a0e811 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -9,9 +9,12 @@ #pragma once -#include "../common.h" -#include "../world/Sprite.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ + +# include "../common.h" +# include "../world/Sprite.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" namespace OpenRCT2::Scripting { @@ -99,3 +102,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index d65e9ed3ac..e8d4fd6315 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -9,14 +9,17 @@ #pragma once -#include "../common.h" -#include "../world/Footpath.h" -#include "../world/Scenery.h" -#include "../world/Sprite.h" -#include "../world/Surface.h" -#include "Duktape.hpp" +#ifdef __ENABLE_SCRIPTING__ -#include +# include "../common.h" +# include "../world/Footpath.h" +# include "../world/Scenery.h" +# include "../world/Sprite.h" +# include "../world/Surface.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" + +# include namespace OpenRCT2::Scripting { @@ -193,3 +196,5 @@ namespace OpenRCT2::Scripting } }; } // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/thirdparty/dukglue/detail_class_proto.h b/src/thirdparty/dukglue/detail_class_proto.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_class_proto.h rename to src/thirdparty/dukglue/detail_class_proto.h diff --git a/src/openrct2/thirdparty/dukglue/detail_constructor.h b/src/thirdparty/dukglue/detail_constructor.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_constructor.h rename to src/thirdparty/dukglue/detail_constructor.h diff --git a/src/openrct2/thirdparty/dukglue/detail_function.h b/src/thirdparty/dukglue/detail_function.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_function.h rename to src/thirdparty/dukglue/detail_function.h diff --git a/src/openrct2/thirdparty/dukglue/detail_method.h b/src/thirdparty/dukglue/detail_method.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_method.h rename to src/thirdparty/dukglue/detail_method.h diff --git a/src/openrct2/thirdparty/dukglue/detail_primitive_types.h b/src/thirdparty/dukglue/detail_primitive_types.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_primitive_types.h rename to src/thirdparty/dukglue/detail_primitive_types.h diff --git a/src/openrct2/thirdparty/dukglue/detail_refs.h b/src/thirdparty/dukglue/detail_refs.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_refs.h rename to src/thirdparty/dukglue/detail_refs.h diff --git a/src/openrct2/thirdparty/dukglue/detail_stack.h b/src/thirdparty/dukglue/detail_stack.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_stack.h rename to src/thirdparty/dukglue/detail_stack.h diff --git a/src/openrct2/thirdparty/dukglue/detail_traits.h b/src/thirdparty/dukglue/detail_traits.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_traits.h rename to src/thirdparty/dukglue/detail_traits.h diff --git a/src/openrct2/thirdparty/dukglue/detail_typeinfo.h b/src/thirdparty/dukglue/detail_typeinfo.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_typeinfo.h rename to src/thirdparty/dukglue/detail_typeinfo.h diff --git a/src/openrct2/thirdparty/dukglue/detail_types.h b/src/thirdparty/dukglue/detail_types.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/detail_types.h rename to src/thirdparty/dukglue/detail_types.h diff --git a/src/openrct2/thirdparty/dukglue/dukexception.h b/src/thirdparty/dukglue/dukexception.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/dukexception.h rename to src/thirdparty/dukglue/dukexception.h diff --git a/src/openrct2/thirdparty/dukglue/dukglue.h b/src/thirdparty/dukglue/dukglue.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/dukglue.h rename to src/thirdparty/dukglue/dukglue.h diff --git a/src/openrct2/thirdparty/dukglue/dukvalue.h b/src/thirdparty/dukglue/dukvalue.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/dukvalue.h rename to src/thirdparty/dukglue/dukvalue.h diff --git a/src/openrct2/thirdparty/dukglue/public_util.h b/src/thirdparty/dukglue/public_util.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/public_util.h rename to src/thirdparty/dukglue/public_util.h diff --git a/src/openrct2/thirdparty/dukglue/register_class.h b/src/thirdparty/dukglue/register_class.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/register_class.h rename to src/thirdparty/dukglue/register_class.h diff --git a/src/openrct2/thirdparty/dukglue/register_function.h b/src/thirdparty/dukglue/register_function.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/register_function.h rename to src/thirdparty/dukglue/register_function.h diff --git a/src/openrct2/thirdparty/dukglue/register_property.h b/src/thirdparty/dukglue/register_property.h similarity index 100% rename from src/openrct2/thirdparty/dukglue/register_property.h rename to src/thirdparty/dukglue/register_property.h diff --git a/src/openrct2/thirdparty/filesystem.hpp b/src/thirdparty/filesystem.hpp similarity index 100% rename from src/openrct2/thirdparty/filesystem.hpp rename to src/thirdparty/filesystem.hpp diff --git a/src/openrct2/thirdparty/linenoise.hpp b/src/thirdparty/linenoise.hpp similarity index 100% rename from src/openrct2/thirdparty/linenoise.hpp rename to src/thirdparty/linenoise.hpp From 03e861945a4a21c1313491a189fdc71bf27e6dde Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 23 Feb 2020 23:13:32 +0000 Subject: [PATCH 079/159] Add scripting readme --- distribution/scripting.md | 155 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 distribution/scripting.md diff --git a/distribution/scripting.md b/distribution/scripting.md new file mode 100644 index 0000000000..d3b7b87554 --- /dev/null +++ b/distribution/scripting.md @@ -0,0 +1,155 @@ +# Scripts for OpenRCT2 + +OpenRCT2 allows custom scripts (also known as plugins) to be written and executed in the game providing additional behaviour on top of the vanilla experience. This can range from extra windows providing information about the park to entire new multiplayer game modes. + +Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This usually `C:\Users\YourName\Documents\OpenRCT2` or `/home/YourName/.config/openrct2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively, so if you want to prevent a plugin from being used, you must move it outside this directory or rename it so the filename does not end with `.js`. + +There are two types of scripts: +* Local +* Remote + +Local scripts can not alter the game state. This allows each player to enable any local script for their own game without affecting or other players needing to also enable the same script. These scripts tend to provide extra tools for productivity or new windows containing information. + +Remote scripts can alter the game state in certain contexts and must be executed for every player in a multiplayer game. Players can not enable or disable remote scripts for multiplayer servers they join. Instead the server will upload any remote scripts that have been enabled on the server to each player. Servers can therefore enable scripts without players needing to manually download or enable the same script on their end. + +## Writing Scripts + +Scripts are written in EcmaScript 5 compatible JavaScript. OpenRCT2 currently uses the duktape library to execute scripts. This does not mean you need to write your plugin in JavaScript, there are many transpilers that allow you to write in the language of your choice and then compile it to JavaScript which can then be executed by OpenRCT2. We however recommend using either JavaScript or TypeScript as that will allow you to utilise the type definition file we supply (openrct2.d.ts). If you would like to use EcmaScript 6 or above features such as the `let` keyword or classes, then you will need to use a transpiler such as `babel` or TypeScript. + +The best reference for writing plugins is: +* The API: `openrct2.d.ts` distributed with OpenRCT2. +* Our collection of sample scripts: https://github.com/OpenRCT2/plugin-samples +* A TypeScript plugin comprised on multiple sources: https://github.com/IntelOrca/OpenRCT2-ParkManager + +Start by copying this template script into a new file in your `plugin` directory. + +```js +function main() { + console.log("Your plugin has started!"); +} + +registerPlugin({ + name: 'Your Plugin', + version: '1.0', + authors: ['Your Name'], + type: 'remote', + main: main +}); +``` + +This will log a message to stdout when you open any park. If you are on Windows, make sure to run `openrct2.com` instead of `openrct2.exe` so you can interact with the stdin / stdout console. The console will is also a JavaScript interpreter (REPL), this means you can write and test expressions similar to the console found in web browsers when you press F12. When you make changes to your script, you must exit your current game and open it again for the script to reload... unless you use the hot reload feature. + +The hot reload feature can be enabled by editing your config.ini file and setting `enable_hot_reloading` to `true` under `[plugin]`. With this enabled, anytime you save your javascript file, the game will auto-reload the script in real-time. This is allows rapid development of plugins, you may even want to write temporary code for this to preview changes faster such as closing and opening a specific custom window on startup. A demonstration of this can be found here: https://www.youtube.com/watch?v=jmjWzEhmDjk + +## Frequently Asked Questions + +> Why was JavaScript chosen instead LUA or Python. + +JavaScript is a very mature and flexible language with a large if not largest resource base available. There are arguably more transpilers, tools, and libraries for JavaScript than any other language. That and also it using a familiar C-like syntax and 0-based arrays make it more suitable than LUA and Python. Of course if you would still like to use LUA or another language, I am sure you can find a transpiler that will compile it to JavaScript for you. + +Another benefit of JavaScript being used is that you get rich editor features such as completion and API documentation using a typescript definition file which works for both JavaScript and TypeScript. [Visual Studo Code](https://code.visualstudio.com) is recommended as that supports the workflow very well. See this video for a demonstration of the editor functionality: https://www.youtube.com/watch?v=jmjWzEhmDjk + +> How safe are scripts? + +Scripts are executed in a sandbox container with no direct access to your computer. Scripts can only use the APIs we provide which only consist of interactions to OpenRCT2 and a limited API for storing data. It is technically possible for a script to freeze the game, fill your disc up with data, but these aren't particular severe issues and are noticed very quickly. + +We use duktape to execute scripts, it is a very mature library for executing scripts, but no library can promise 100% security. If any security vulnerabilities are found, they will likely be fixed quickly and we will update duktape accordingly for OpenRCT2. + +We would not provide the scripts feature if we were not confident they were safe, and they are much safe than the alternative which would be native code loaded from DLLs. + +> Is it possible for someone to run a bitcoin miner in my game? + +Yes, but the performance would be so dire that it would be a waste of their time. This probably the least of your worries. + +> What are the limits? + +Scripts can conist of any behaviour and have a large memory pool available to them. The speed will vary depending on the computer executing them. The scripts are interpreted, so do not expect anywhere near the performance of native code. In most scenarios this should be good enough, but your random map generator or genetic algorithm for building roller coasters might struggle. Like any other language, there will be tricks to optimising JavaScript and the use of OpenRCT2's APIs. + +The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plugin system is to add APIs on demand, so if you find an API is missing, please raise an issue for it on GitHub. + +> What does the error 'Game state is not mutable in this context' mean? + +This means you are attempting to modify the game state (e.g. change the park, map or guests etc.) in a context where you should not be doing so. This might be because your script is defined as `local` meaning it must work independently of other players not having the script, or a remote script attempting to modify the game in the main function or a user interface event. + +Any changes to the game state must be synchronised across all players so that the same changes happen on the same tick for every player. This prevents the game going out of sync. To do this you must only change game state in a compatible hook such as `interval.day` or in the execute method of a game action. Game actions allow players to make specific changes to the game providing they have the correct permissions and the server allows it. + +Whilst we try to prevent desynchronision from happening, it still requires careful coding from the script writer. Any attempt to use local specific or non-deterministic data to change the game state will cause a desync. This can be as easy as using `ui.windows`, a variable that will different for every player. + +> What are hooks? + +Hooks allow a script to subscribe to certain events that occur in the game. For example if the script wants to award cash to the park every day, it can subscribe to the `interval.day` event as follows: + +```js +context.subscribe('interval.day', function() { + park.cash += 10000; +}); +``` + +Other hooks including receiving a chat message in multiplayer or a ride breaking down. + +> What are game actions? + +Game actions allow you to define new actions players can invoke in games which have their own permission. The flow of a game action is: + +1. Player executes action (open park) via UI. +2. Game action (open park), query method is called. +3. If query succeeds, send action to server, else show error message. +4. Server receives action and query method is called on server. +5. If query or permission fails, send error message back to player, else: +6. Send action to all player to execute action at tick ###. +7. All players execute action at tick ###. + +This sequence of actions ensure that every player execute the action exactly the same way on the exact same game tick. It also allows the server to validate that the action is allowed and does not fail due to permission or another player winning with a conflicting action. This is why there is a noticable delay when constructing in multiplayer games as the client has to wait for the server to acknowledge the action and reply with the tick number to execute it on, since we do not yet have any rollback support. + +> Can I run code specifically for servers or clients? + +Yep, there is an API to get the current network mode. + +```js +if (network.mode == "server") { + console.log("This is a server..."); +} else if (network.mode == "client") { + console.log("This is a client..."); +} else { + console.log("This is single player..."); +} +``` + +> Can I run code only if the user interface is available? + +Yes, it is good practice, particularly if writing scripts for servers to check if the game is running in headless mode before attempting to use any UI APIs. The `ui` namespace is not available in headless mode, so make sure you check it otherwise an error will be thrown. + +```js +if (typeof ui !== 'undefined') { + console.log("OpenRCT2 is not running in headless, UI is available!"); + ui.registerMenuItem('My window', function() { + // ... + }); +} +``` + +> Can I use third party JavaScript libraries? + +Absolutely, just embed the library in your JavaScript file. There are a number of tools to help you do this. + +> Can I share code across multiple scripts? + +There are two ways this can be done. If you are just sharing helper routines or libraries, the best thing is to embed it in each plugin. There are a number of tools for JavaScript to help you do this. If you would like two plugins to communicate to each other, perhaps to share data then you can do this by declaring a variable or function in global scope which makes it available to all plugins or use the shared storage APIs. + +> What do I do if there is no API for ...? + +No problem, if there is something you need, post a new issue on our issue tracker asking for the API you require: https://github.com/OpenRCT2/OpenRCT2/issues + +Adding new APIs is most of time straight forward, so they can be added to new development builds quickly. Or if you capable, make the change yourself to the OpenRCT2 source stream and create a pull request. + +> Where shall I keep the code for my script? + +We recommend GitHub (where OpenRCT2 is hosted), or another source control host such as BitBucket or GitLab. All of them offer private repositories if you want to keep your code private or public repositories which allow others to contribute to your script. + +> What licence should I use for my script? + +This is up to you. The OpenRCT2 licence does not enforce any licence requirement for content that is loaded into it. MIT is recommended as is the most permissive. You also have to consider what licence any third party libraries you use require. + +> Is there a good place to distribute my script to other players? + +We not currently host any content database for this. We recommend for now uploading releases of your script on GitHub alongside your source code (if public). Some people like to make a GitHub repository that just consists of a list of content (scripts in this case) which anyone can add to via pull requests. From 08cdb831afffa1fc584a8d12b88550f52936ce9c Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 24 Feb 2020 13:45:57 +0000 Subject: [PATCH 080/159] Improve readme --- distribution/scripting.md | 69 ++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/distribution/scripting.md b/distribution/scripting.md index d3b7b87554..1656f3d4dc 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -1,31 +1,30 @@ # Scripts for OpenRCT2 -OpenRCT2 allows custom scripts (also known as plugins) to be written and executed in the game providing additional behaviour on top of the vanilla experience. This can range from extra windows providing information about the park to entire new multiplayer game modes. +OpenRCT2 allows custom scripts (also known as plug-ins) to be written and executed in the game providing additional behaviour on top of the vanilla experience. This can range from extra windows providing information about the park to entire new multiplayer game modes. -Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This usually `C:\Users\YourName\Documents\OpenRCT2` or `/home/YourName/.config/openrct2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively, so if you want to prevent a plugin from being used, you must move it outside this directory or rename it so the filename does not end with `.js`. +Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This is usually `C:\Users\YourName\Documents\OpenRCT2`, or `/home/YourName/.config/openrct2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively. So if you want to prevent a plug-in from being used, you must move it outside this directory, or rename it so the filename does not end with `.js`. There are two types of scripts: * Local * Remote -Local scripts can not alter the game state. This allows each player to enable any local script for their own game without affecting or other players needing to also enable the same script. These scripts tend to provide extra tools for productivity or new windows containing information. +Local scripts can **not** alter the game state. This allows each player to enable any local script for their own game without other players needing to also enable the same script. These scripts tend to provide extra tools for productivity, or new windows containing information. -Remote scripts can alter the game state in certain contexts and must be executed for every player in a multiplayer game. Players can not enable or disable remote scripts for multiplayer servers they join. Instead the server will upload any remote scripts that have been enabled on the server to each player. Servers can therefore enable scripts without players needing to manually download or enable the same script on their end. +Remote scripts on the other hand can alter the game state in certain contexts thus must be enabled for every player in a multiplayer game. Players can not enable or disable remote scripts for multiplayer servers they join. Instead the server will upload any remote scripts that have been enabled on the server to each player. This allows servers to enable scripts without players needing to manually download or enable the same script on their end. ## Writing Scripts -Scripts are written in EcmaScript 5 compatible JavaScript. OpenRCT2 currently uses the duktape library to execute scripts. This does not mean you need to write your plugin in JavaScript, there are many transpilers that allow you to write in the language of your choice and then compile it to JavaScript which can then be executed by OpenRCT2. We however recommend using either JavaScript or TypeScript as that will allow you to utilise the type definition file we supply (openrct2.d.ts). If you would like to use EcmaScript 6 or above features such as the `let` keyword or classes, then you will need to use a transpiler such as `babel` or TypeScript. +Scripts are written in ECMAScript 5 compatible JavaScript. OpenRCT2 currently uses the [duktape](https://duktape.org) library to execute scripts. This however does not mean you need to write your plug-in in JavaScript, there are many transpilers that allow you to write in a language of your choice and then compile it to JavaScript allowing it to be executed by OpenRCT2. JavaScript or [TypeScript](https://www.typescriptlang.org) is recommended however, as that will allow you to utilise the type definition file we supply (`openrct2.d.ts`). If you would like to use ECMAScript 6 or later which contain features such as the `let` keyword or classes, then you will need to use a transpiler such as [Babel](https://babeljs.io) or [TypeScript](https://www.typescriptlang.org). -The best reference for writing plugins is: +Offical references for writing plug-ins are: * The API: `openrct2.d.ts` distributed with OpenRCT2. * Our collection of sample scripts: https://github.com/OpenRCT2/plugin-samples -* A TypeScript plugin comprised on multiple sources: https://github.com/IntelOrca/OpenRCT2-ParkManager - -Start by copying this template script into a new file in your `plugin` directory. +* A TypeScript plug-in comprised on multiple sources: https://github.com/IntelOrca/OpenRCT2-ParkManager +Start by copying this template script into a new file in your `plugin` directory: ```js function main() { - console.log("Your plugin has started!"); + console.log("Your plug-in has started!"); } registerPlugin({ @@ -37,47 +36,45 @@ registerPlugin({ }); ``` -This will log a message to stdout when you open any park. If you are on Windows, make sure to run `openrct2.com` instead of `openrct2.exe` so you can interact with the stdin / stdout console. The console will is also a JavaScript interpreter (REPL), this means you can write and test expressions similar to the console found in web browsers when you press F12. When you make changes to your script, you must exit your current game and open it again for the script to reload... unless you use the hot reload feature. +This will log a message to stdout when you open any park. If you are on Windows, make sure to run `openrct2.com` instead of `openrct2.exe` so you can interact with the stdin / stdout console. The console is a JavaScript interpreter (REPL), this means you can write and test expressions similar to the console found in web browsers when you press F12. When you make changes to your script, you must exit your current game and open it again for the script to reload... unless you use the hot reload feature. -The hot reload feature can be enabled by editing your config.ini file and setting `enable_hot_reloading` to `true` under `[plugin]`. With this enabled, anytime you save your javascript file, the game will auto-reload the script in real-time. This is allows rapid development of plugins, you may even want to write temporary code for this to preview changes faster such as closing and opening a specific custom window on startup. A demonstration of this can be found here: https://www.youtube.com/watch?v=jmjWzEhmDjk +The hot reload feature can be enabled by editing your `config.ini` file and setting `enable_hot_reloading` to `true` under `[plugin]`. When this is enabled, the game will auto-reload the script in real-time whenever you save your JavaScript file. This is allows rapid development of plug-ins. You may even want to write temporary code to preview your changes quickly, such as closing and opening a specific custom window on startup. A demonstration of this can be found here: https://www.youtube.com/watch?v=jmjWzEhmDjk ## Frequently Asked Questions > Why was JavaScript chosen instead LUA or Python. -JavaScript is a very mature and flexible language with a large if not largest resource base available. There are arguably more transpilers, tools, and libraries for JavaScript than any other language. That and also it using a familiar C-like syntax and 0-based arrays make it more suitable than LUA and Python. Of course if you would still like to use LUA or another language, I am sure you can find a transpiler that will compile it to JavaScript for you. +JavaScript is a very mature and flexible language with a large, if not largest, resource base available. There are arguably more transpilers, tools, and libraries for JavaScript than any other language. That and also it using a familiar C-like syntax and 0-indexed arrays make it more suitable than LUA and Python. Of course if you would still like to use LUA or another language, there will likely be a JavaScript transpiler for it. -Another benefit of JavaScript being used is that you get rich editor features such as completion and API documentation using a typescript definition file which works for both JavaScript and TypeScript. [Visual Studo Code](https://code.visualstudio.com) is recommended as that supports the workflow very well. See this video for a demonstration of the editor functionality: https://www.youtube.com/watch?v=jmjWzEhmDjk +Another benefit of using JavaScript is that you get rich editor features such as completion and API documentation by using a TypeScript definition file which works for both TypeScript and JavaScript. [Visual Studio Code](https://code.visualstudio.com) is recommended, as that supports the workflow very well. See this video for a demonstration of the editor functionality: https://www.youtube.com/watch?v=jmjWzEhmDjk > How safe are scripts? -Scripts are executed in a sandbox container with no direct access to your computer. Scripts can only use the APIs we provide which only consist of interactions to OpenRCT2 and a limited API for storing data. It is technically possible for a script to freeze the game, fill your disc up with data, but these aren't particular severe issues and are noticed very quickly. +Scripts are executed in a sandbox container with no direct access to your computer. Scripts can only use the APIs we provide which only consist of interactions to OpenRCT2 and a limited API for storing data. It is technically possible for a script to freeze the game, or fill your disc up with data, but these aren't particularly severe issues and are noticed quite quickly. -We use duktape to execute scripts, it is a very mature library for executing scripts, but no library can promise 100% security. If any security vulnerabilities are found, they will likely be fixed quickly and we will update duktape accordingly for OpenRCT2. - -We would not provide the scripts feature if we were not confident they were safe, and they are much safe than the alternative which would be native code loaded from DLLs. +The [duktape](https://duktape.org) library is used to execute scripts, it is a very mature library for executing scripts, but no library can promise 100% security. If any security vulnerabilities are found, they will likely be fixed promptly and OpenRCT2 can then be updated to use the new version of duktape. > Is it possible for someone to run a bitcoin miner in my game? -Yes, but the performance would be so dire that it would be a waste of their time. This probably the least of your worries. +Yes, but the performance would be so dire that it would be a waste of their time. This is probably the least of your worries. > What are the limits? -Scripts can conist of any behaviour and have a large memory pool available to them. The speed will vary depending on the computer executing them. The scripts are interpreted, so do not expect anywhere near the performance of native code. In most scenarios this should be good enough, but your random map generator or genetic algorithm for building roller coasters might struggle. Like any other language, there will be tricks to optimising JavaScript and the use of OpenRCT2's APIs. +Scripts can conist of any behaviour and have a large memory pool available to them. The speed will vary depending on the hardware and system executing them. The scripts are interpreted, so do not expect anywhere close to the performance of native code. In most scenarios this should be satisfactory, but a random map generator, or genetic algorithm for building roller coasters might struggle. Like any language, there will be tricks to optimising JavaScript and the use of the OpenRCT2 APIs. -The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plugin system is to add APIs on demand, so if you find an API is missing, please raise an issue for it on GitHub. +The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plug-in system is to add APIs on-demand. So if you find an API is missing, please raise an issue for it on GitHub. > What does the error 'Game state is not mutable in this context' mean? -This means you are attempting to modify the game state (e.g. change the park, map or guests etc.) in a context where you should not be doing so. This might be because your script is defined as `local` meaning it must work independently of other players not having the script, or a remote script attempting to modify the game in the main function or a user interface event. +This means you are attempting to modify the game state (e.g. change the park, map or guests etc.) in a context where you should not be doing so. This might be because your script is defined as `local` meaning it must work independently of other players not having the script enabled, or a remote script attempting to modify the game in the main function or a user interface event. Any changes to the game state must be synchronised across all players so that the same changes happen on the same tick for every player. This prevents the game going out of sync. To do this you must only change game state in a compatible hook such as `interval.day` or in the execute method of a game action. Game actions allow players to make specific changes to the game providing they have the correct permissions and the server allows it. -Whilst we try to prevent desynchronision from happening, it still requires careful coding from the script writer. Any attempt to use local specific or non-deterministic data to change the game state will cause a desync. This can be as easy as using `ui.windows`, a variable that will different for every player. +Whilst OpenRCT2 try's to prevent desynchronision from happening, it still requires careful coding to ensure the behaviour is deterministic across all clients. Any attempt to use local specific or non-deterministic data to change the game state will cause a desync. This can be as easy as using `ui.windows`, a variable that can be different for every player. > What are hooks? -Hooks allow a script to subscribe to certain events that occur in the game. For example if the script wants to award cash to the park every day, it can subscribe to the `interval.day` event as follows: +Hooks allow a script to subscribe to certain events that occur in the game. For example if the script was to award cash to the park every day, it would subscribe to the `interval.day` event as follows: ```js context.subscribe('interval.day', function() { @@ -85,11 +82,11 @@ context.subscribe('interval.day', function() { }); ``` -Other hooks including receiving a chat message in multiplayer or a ride breaking down. +Other hooks include receiving a chat message in multiplayer, or a ride breaking-down. > What are game actions? -Game actions allow you to define new actions players can invoke in games which have their own permission. The flow of a game action is: +Game actions allow you to define new actions (with a new permission slot) that players can invoke in games. Here is an example flow of a game action such as opening the park: 1. Player executes action (open park) via UI. 2. Game action (open park), query method is called. @@ -99,7 +96,7 @@ Game actions allow you to define new actions players can invoke in games which h 6. Send action to all player to execute action at tick ###. 7. All players execute action at tick ###. -This sequence of actions ensure that every player execute the action exactly the same way on the exact same game tick. It also allows the server to validate that the action is allowed and does not fail due to permission or another player winning with a conflicting action. This is why there is a noticable delay when constructing in multiplayer games as the client has to wait for the server to acknowledge the action and reply with the tick number to execute it on, since we do not yet have any rollback support. +This sequence of actions ensure that every player execute the action exactly the same way on the exact same game tick. It also allows the server to validate that the action is allowed and does not fail due to permission or another player executing conflicting action just before it. This is why there is a noticable delay when constructing in multiplayer games, as the client has to wait for the server to acknowledge the action and reply with the tick number to execute it on, since we do not yet have any rollback support. > Can I run code specifically for servers or clients? @@ -117,7 +114,7 @@ if (network.mode == "server") { > Can I run code only if the user interface is available? -Yes, it is good practice, particularly if writing scripts for servers to check if the game is running in headless mode before attempting to use any UI APIs. The `ui` namespace is not available in headless mode, so make sure you check it otherwise an error will be thrown. +Yes, it is good practice, particularly if writing scripts for servers to check if the game is running in headless mode before attempting to use any UI APIs. The `ui` namespace is not available in headless mode, so make sure you check it, otherwise an error will be thrown. ```js if (typeof ui !== 'undefined') { @@ -128,28 +125,32 @@ if (typeof ui !== 'undefined') { } ``` +> Can servers add additional user interface elements to players? + +Yes, remote scripts are uploaded to every client and run as-is. Even if the server is running in headless mode, the script can still contain UI calls for the benefit of the players that are not running in headless mode. Be sure to check if the UI is available first before executing UI calls. + > Can I use third party JavaScript libraries? Absolutely, just embed the library in your JavaScript file. There are a number of tools to help you do this. > Can I share code across multiple scripts? -There are two ways this can be done. If you are just sharing helper routines or libraries, the best thing is to embed it in each plugin. There are a number of tools for JavaScript to help you do this. If you would like two plugins to communicate to each other, perhaps to share data then you can do this by declaring a variable or function in global scope which makes it available to all plugins or use the shared storage APIs. +There are two ways this can be done. If you are just sharing helper routines or libraries, the best thing is to embed it in each plug-in. There are a number of tools for JavaScript to help you do this. If you would like two plug-ins to communicate with each other, perhaps to share data, then you can do this by declaring a variable or function in global scope which is available to all plug-ins, or use the shared storage APIs. > What do I do if there is no API for ...? -No problem, if there is something you need, post a new issue on our issue tracker asking for the API you require: https://github.com/OpenRCT2/OpenRCT2/issues +No problem, if there is something you need, post a new issue on the issue tracker for OpenRCT2 asking for the API you require: https://github.com/OpenRCT2/OpenRCT2/issues -Adding new APIs is most of time straight forward, so they can be added to new development builds quickly. Or if you capable, make the change yourself to the OpenRCT2 source stream and create a pull request. +Adding new APIs is most of time straight forward, so they can be added to new development builds quickly. Or if you are capable, make the change yourself to the OpenRCT2 source stream and create a pull request. > Where shall I keep the code for my script? -We recommend GitHub (where OpenRCT2 is hosted), or another source control host such as BitBucket or GitLab. All of them offer private repositories if you want to keep your code private or public repositories which allow others to contribute to your script. +We recommend [GitHub](https://github.com) (where OpenRCT2 is hosted), or another source control host such as [BitBucket](https://bitbucket.org) or [GitLab](https://gitlab.com). All of them offer private repositories if you want to keep your code private, or public repositories which allow others to easily contribute to your script. > What licence should I use for my script? -This is up to you. The OpenRCT2 licence does not enforce any licence requirement for content that is loaded into it. MIT is recommended as is the most permissive. You also have to consider what licence any third party libraries you use require. +This is up to you. The OpenRCT2 licence does not enforce any licence requirement for content that is loaded into it. MIT is recommended as is the most permissive. You also have to consider what licence any third party libraries you are using allow. > Is there a good place to distribute my script to other players? -We not currently host any content database for this. We recommend for now uploading releases of your script on GitHub alongside your source code (if public). Some people like to make a GitHub repository that just consists of a list of content (scripts in this case) which anyone can add to via pull requests. +There is currently no official database for this. For now the recommendation is to upload releases for your script on GitHub alongside your source code (if public). Some people like to make a GitHub repository that just consists of a list of content (scripts in this case) which anyone can add to via pull requests. From 2890faee0af6dce3748ecd76aaa7d025769bbc00 Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 24 Feb 2020 17:40:36 +0000 Subject: [PATCH 081/159] Change plugin type to just local and remote --- src/openrct2/network/Network.cpp | 2 +- src/openrct2/scripting/Plugin.cpp | 10 ++++------ src/openrct2/scripting/Plugin.h | 11 +++-------- src/openrct2/scripting/ScriptEngine.cpp | 9 ++------- 4 files changed, 10 insertions(+), 22 deletions(-) diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 8ced55ee05..e603eda448 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -1483,7 +1483,7 @@ void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const for (const auto& plugin : plugins) { const auto& metadata = plugin->GetMetadata(); - if (metadata.Type == OpenRCT2::Scripting::PluginType::ServerClient) + if (metadata.Type == OpenRCT2::Scripting::PluginType::Remote) { pluginsToSend.push_back(plugin); } diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index cb3fecd37f..9d4fcb5133 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -158,12 +158,10 @@ PluginMetadata Plugin::GetMetadata(const DukValue& dukMetadata) PluginType Plugin::ParsePluginType(const std::string_view& type) { - if (type == "server") - return PluginType::Server; - if (type == "client") - return PluginType::Client; - if (type == "server_client") - return PluginType::ServerClient; + if (type == "local") + return PluginType::Local; + if (type == "remote") + return PluginType::Remote; throw std::invalid_argument("Unknown plugin type."); } diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index f584c26560..f7f409207e 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -23,21 +23,16 @@ namespace OpenRCT2::Scripting enum class PluginType { /** - * Scripts that can run on any client with no impact on the game state. - */ - Client, - - /** - * Scripts that can run on servers with no impact on the game state and will not + * Scripts that can run on servers or clients with no impact on the game state and will not * be uploaded to clients. */ - Server, + Local, /** * Scripts that can run on servers and will be uploaded to clients with ability to * modify game state in certain contexts. */ - ServerClient, + Remote, }; struct PluginMetadata diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 796cb96e02..e40ed99f93 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -271,14 +271,9 @@ bool ScriptEngine::ShouldStartPlugin(const std::shared_ptr& plugin) { // Only client plugins and plugins downloaded from server should be started const auto& metadata = plugin->GetMetadata(); - if (metadata.Type == PluginType::Server) + if (metadata.Type == PluginType::Remote && plugin->HasPath()) { - LogPluginInfo(plugin, "Server plugin not started"); - return false; - } - else if (metadata.Type == PluginType::ServerClient && plugin->HasPath()) - { - LogPluginInfo(plugin, "Server / client plugin not started"); + LogPluginInfo(plugin, "Remote plugin not started"); return false; } } From 177c1a16a7b5dc319e1e8f7b2aa0333a85b685a5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 24 Feb 2020 17:43:03 +0000 Subject: [PATCH 082/159] Always allow game state to be mutated in single player --- src/openrct2/scripting/ScriptEngine.cpp | 28 ++++++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index e40ed99f93..ae6273bd78 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -380,19 +380,31 @@ static std::string Stringify(duk_context* ctx, duk_idx_t idx) bool OpenRCT2::Scripting::IsGameStateMutable() { - auto& scriptEngine = GetContext()->GetScriptEngine(); - auto& execInfo = scriptEngine.GetExecInfo(); - return execInfo.IsGameStateMutable(); + // Allow single player to alter game state anywhere + if (network_get_mode() == NETWORK_MODE_NONE) + { + return true; + } + else + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto& execInfo = scriptEngine.GetExecInfo(); + return execInfo.IsGameStateMutable(); + } } void OpenRCT2::Scripting::ThrowIfGameStateNotMutable() { - auto& scriptEngine = GetContext()->GetScriptEngine(); - auto& execInfo = scriptEngine.GetExecInfo(); - if (!execInfo.IsGameStateMutable()) + // Allow single player to alter game state anywhere + if (network_get_mode() != NETWORK_MODE_NONE) { - auto ctx = scriptEngine.GetContext(); - duk_error(ctx, DUK_ERR_ERROR, "Game state is not mutable in this context."); + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto& execInfo = scriptEngine.GetExecInfo(); + if (!execInfo.IsGameStateMutable()) + { + auto ctx = scriptEngine.GetContext(); + duk_error(ctx, DUK_ERR_ERROR, "Game state is not mutable in this context."); + } } } From ae0c2638e3cdd31fe4f3fb1ac4eb63c5c257890a Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 24 Feb 2020 17:50:39 +0000 Subject: [PATCH 083/159] Distribute openrct2.d.ts and scripting.md --- CMakeLists.txt | 4 +++- distribution/windows/install.nsi | 8 ++++++++ scripts/build-portable | 4 +++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 99c2549ed2..1f0a901263 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -291,7 +291,9 @@ endif () # Don't recurse, grab all *.txt and *.md files file(GLOB DOC_FILES "${ROOT_DIR}/distribution/*.txt") list(APPEND DOC_FILES "${ROOT_DIR}/contributors.md" - "${ROOT_DIR}/licence.txt") + "${ROOT_DIR}/licence.txt" + "${ROOT_DIR}/distribution/scripting.md" + "${ROOT_DIR}/distribution/openrct2.d.ts") # CMake does not allow specifying a dependency chain which includes built-in # targets, like `install`, so we have to trick it and execute dependency ourselves. diff --git a/distribution/windows/install.nsi b/distribution/windows/install.nsi index 51ecaa085d..f3a16029d7 100644 --- a/distribution/windows/install.nsi +++ b/distribution/windows/install.nsi @@ -170,6 +170,12 @@ Section "!OpenRCT2" Section1 File ..\..\contributors.md Push "$INSTDIR\contributors.md" Call unix2dos + File ..\scripting.md + Push "$INSTDIR\scripting.md" + Call unix2dos + File ..\openrct2.d.ts + Push "$INSTDIR\openrct2.d.ts" + Call unix2dos ; Copy executable File /oname=${OPENRCT2_EXE} ${BINARY_DIR}\${OPENRCT2_EXE} @@ -240,6 +246,8 @@ Section "Uninstall" Delete "$INSTDIR\licence.txt" Delete "$INSTDIR\readme.txt" Delete "$INSTDIR\contributors.md" + Delete "$INSTDIR\scripting.md" + Delete "$INSTDIR\openrct2.d.ts" Delete "$INSTDIR\${OPENRCT2_EXE}" Delete "$INSTDIR\${OPENRCT2_COM}" Delete "$INSTDIR\INSTALL.LOG" diff --git a/scripts/build-portable b/scripts/build-portable index 7d50b86650..8e2912b15b 100755 --- a/scripts/build-portable +++ b/scripts/build-portable @@ -23,7 +23,9 @@ if [[ "$OSTYPE" == "cygwin" || "$OSTYPE" == "msys" ]]; then ../contributors.md \ ../licence.txt \ ../distribution/changelog.txt \ - ../distribution/readme.txt + ../distribution/readme.txt \ + ../distribution/scripting.md \ + ../distribution/openrct2.d.ts destination=$(cygpath -w $(readlink -f $destination)) printf '\033[0;32m%s\033[0m\n' "${destination} created successfully" From dfd45651dcdbdc00a72d3e574940318024f0a1c3 Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 24 Feb 2020 19:25:18 +0000 Subject: [PATCH 084/159] Improve stringify of expressions --- src/openrct2/scripting/ScConsole.hpp | 58 +-------- src/openrct2/scripting/ScriptEngine.cpp | 129 +++++++++++++++++++-- src/openrct2/scripting/ScriptEngine.h | 1 + src/thirdparty/dukglue/register_property.h | 1 + 4 files changed, 122 insertions(+), 67 deletions(-) diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index c3ccacbf65..4f341ca868 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -13,6 +13,7 @@ # include "../interface/InteractiveConsole.h" # include "Duktape.hpp" +# include "ScriptEngine.h" namespace OpenRCT2::Scripting { @@ -34,49 +35,7 @@ namespace OpenRCT2::Scripting void log(DukValue val) { - std::string str; - switch (val.type()) - { - case DukValue::Type::UNDEFINED: - str = "undefined"; - break; - case DukValue::Type::NULLREF: - str = "null"; - break; - case DukValue::Type::BOOLEAN: - str = val.as_bool() ? "true" : "false"; - break; - case DukValue::Type::NUMBER: - { - const auto d = val.as_double(); - const duk_int_t i = val.as_int(); - if (AlmostEqual(d, i)) - { - str = std::to_string(i); - } - else - { - str = std::to_string(d); - } - break; - } - case DukValue::Type::STRING: - str = val.as_string(); - break; - case DukValue::Type::OBJECT: - str = "{}"; - break; - case DukValue::Type::BUFFER: - str = "buffer"; - break; - case DukValue::Type::POINTER: - str = "pointer"; - break; - case DukValue::Type::LIGHTFUNC: - break; - } - - _console.WriteLine(str); + _console.WriteLine(Stringify(val)); } static void Register(duk_context* ctx) @@ -84,19 +43,6 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScConsole::clear, "clear"); dukglue_register_method(ctx, &ScConsole::log, "log"); } - - private: - // Taken from http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon - template - static typename std::enable_if::is_integer, bool>::type AlmostEqual(T x, T y, int32_t ulp = 20) - { - // the machine epsilon has to be scaled to the magnitude of the values used - // and multiplied by the desired precision in ULPs (units in the last place) - return std::abs(x - y) <= std::numeric_limits::epsilon() * std::abs(x + y) * ulp - // unless the result is subnormal - || std::abs(x - y) - < (std::numeric_limits::min)(); // TODO: Remove parentheses around min once the macro is removed - } }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index ae6273bd78..5f6cce1860 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -35,8 +35,6 @@ using namespace OpenRCT2; using namespace OpenRCT2::Scripting; -static std::string Stringify(duk_context* ctx, duk_idx_t idx); - static constexpr int32_t OPENRCT2_PLUGIN_API_VERSION = 1; DukContext::DukContext() @@ -335,7 +333,7 @@ void ScriptEngine::ProcessREPL() } else if (duk_get_type(_context, -1) != DUK_TYPE_UNDEFINED) { - std::string result = Stringify(_context, -1); + auto result = Stringify(DukValue::copy_from_stack(_context, -1)); _console.WriteLine(result); } duk_pop(_context); @@ -365,17 +363,126 @@ void ScriptEngine::AddNetworkPlugin(const std::string_view& code) LoadPlugin(plugin); } -static std::string Stringify(duk_context* ctx, duk_idx_t idx) +// Taken from http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon +template +static typename std::enable_if::is_integer, bool>::type AlmostEqual(T x, T y, int32_t ulp = 20) { - auto type = duk_get_type(ctx, idx); - if (type == DUK_TYPE_OBJECT && !duk_is_function(ctx, idx)) + // the machine epsilon has to be scaled to the magnitude of the values used + // and multiplied by the desired precision in ULPs (units in the last place) + return std::abs(x - y) <= std::numeric_limits::epsilon() * std::abs(x + y) * ulp + // unless the result is subnormal + || std::abs(x - y) < (std::numeric_limits::min)(); // TODO: Remove parentheses around min once the macro is removed +} + +std::string OpenRCT2::Scripting::Stringify(const DukValue& val, int32_t depth) +{ + if (depth >= 3) + return "..."; + + std::string str; + switch (val.type()) { - return duk_json_encode(ctx, idx); - } - else - { - return duk_safe_to_string(ctx, idx); + case DukValue::Type::UNDEFINED: + str = "undefined"; + break; + case DukValue::Type::NULLREF: + str = "null"; + break; + case DukValue::Type::BOOLEAN: + str = val.as_bool() ? "true" : "false"; + break; + case DukValue::Type::NUMBER: + { + const auto d = val.as_double(); + const duk_int_t i = val.as_int(); + if (AlmostEqual(d, i)) + { + str = std::to_string(i); + } + else + { + str = std::to_string(d); + } + break; + } + case DukValue::Type::STRING: + str = "\"" + val.as_string() + "\""; + break; + case DukValue::Type::OBJECT: + if (val.is_function()) + { + auto ctx = val.context(); + val.push(); + if (duk_is_c_function(ctx, -1)) + { + str = u8"Æ’ [native]"; + } + else if (duk_is_ecmascript_function(ctx, -1)) + { + str = u8"Æ’ [ecmascript]"; + } + else + { + str = u8"Æ’ [javascript]"; + } + duk_pop(ctx); + } + else if (val.is_array()) + { + str = "["; + auto ctx = val.context(); + val.push(); + auto arrayLen = duk_get_length(ctx, -1); + for (duk_uarridx_t i = 0; i < arrayLen; i++) + { + if (i != 0) + str += ", "; + if (duk_get_prop_index(ctx, -1, i)) + { + auto arrayVal = DukValue::take_from_stack(ctx); + str += Stringify(arrayVal, depth + 1); + } + if (i >= 4) + { + str += ", ..."; + break; + } + } + duk_pop(ctx); + str += "]"; + } + else + { + str = "{"; + auto ctx = val.context(); + val.push(); + duk_enum(ctx, -1, 0); + auto index = 0; + while (duk_next(ctx, -1, 1)) + { + if (index != 0) + str += ", "; + auto value = DukValue::take_from_stack(ctx, -1); + auto key = DukValue::take_from_stack(ctx, -1); + str += Stringify(key, depth + 1); + str += ": "; + str += Stringify(value, depth + 1); + index++; + } + duk_pop_2(ctx); + str += "}"; + } + break; + case DukValue::Type::BUFFER: + str = "buffer"; + break; + case DukValue::Type::POINTER: + str = "pointer"; + break; + case DukValue::Type::LIGHTFUNC: + break; } + return str; } bool OpenRCT2::Scripting::IsGameStateMutable() diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 6ebce0af41..3c2a2db8f0 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -168,6 +168,7 @@ namespace OpenRCT2::Scripting bool IsGameStateMutable(); void ThrowIfGameStateNotMutable(); + std::string Stringify(const DukValue& value, int32_t depth = 0); } // namespace OpenRCT2::Scripting diff --git a/src/thirdparty/dukglue/register_property.h b/src/thirdparty/dukglue/register_property.h index c4fd8b36b7..c71dc0a3ac 100644 --- a/src/thirdparty/dukglue/register_property.h +++ b/src/thirdparty/dukglue/register_property.h @@ -115,6 +115,7 @@ void dukglue_register_property(duk_context* ctx, duk_uint_t flags = DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER + | DUK_DEFPROP_SET_ENUMERABLE | DUK_DEFPROP_HAVE_CONFIGURABLE /* set not configurable (from JS) */ | DUK_DEFPROP_FORCE /* allow overriding built-ins and previously defined properties */; From c73bb63f0ea93e8742320b0ec9ebb605c94a472c Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 24 Feb 2020 19:25:31 +0000 Subject: [PATCH 085/159] Implement window classification and number --- distribution/openrct2.d.ts | 4 ++-- src/openrct2-ui/scripting/ScWindow.hpp | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 39ccbe0330..8e066e06b6 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -370,8 +370,8 @@ declare global { } interface Window { - id: number; - classification: string; + classification: number; + number: number; x: number; y: number; width: number; diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 0c41b3a8a3..490a38fe08 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -40,6 +40,16 @@ namespace OpenRCT2::Scripting { } + int32_t classification_get() + { + return static_cast(_class); + } + + int32_t number_get() + { + return static_cast(_number); + } + int32_t x_get() { return GetWindow()->x; @@ -123,6 +133,8 @@ namespace OpenRCT2::Scripting static void Register(duk_context* ctx) { + dukglue_register_property(ctx, &ScWindow::classification_get, nullptr, "classification"); + dukglue_register_property(ctx, &ScWindow::number_get, nullptr, "number"); dukglue_register_property(ctx, &ScWindow::x_get, &ScWindow::x_set, "x"); dukglue_register_property(ctx, &ScWindow::y_get, &ScWindow::y_set, "y"); dukglue_register_property(ctx, &ScWindow::width_get, nullptr, "width"); From e6ca727b4b7308855401edc1449cff069f6e1dcf Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 25 Feb 2020 00:43:49 +0000 Subject: [PATCH 086/159] Improve dumping of expressions --- src/openrct2/scripting/ScriptEngine.cpp | 423 +++++++++++++++++------- src/openrct2/scripting/ScriptEngine.h | 2 +- 2 files changed, 305 insertions(+), 120 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 5f6cce1860..06b4eca38a 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -37,6 +37,308 @@ using namespace OpenRCT2::Scripting; static constexpr int32_t OPENRCT2_PLUGIN_API_VERSION = 1; +struct ExpressionStringifier final +{ +private: + std::stringstream _ss; + duk_context* _context{}; + int32_t _indent{}; + + ExpressionStringifier(duk_context* ctx) + : _context(ctx) + { + } + + void PushIndent(int32_t c = 1) + { + _indent += c; + } + + void PopIndent(int32_t c = 1) + { + _indent -= c; + } + + void LineFeed() + { + _ss << "\n" << std::string(_indent, ' '); + } + + void Stringify(const DukValue& val, bool canStartWithNewLine) + { + switch (val.type()) + { + case DukValue::Type::UNDEFINED: + _ss << "undefined"; + break; + case DukValue::Type::NULLREF: + _ss << "null"; + break; + case DukValue::Type::BOOLEAN: + StringifyBoolean(val); + break; + case DukValue::Type::NUMBER: + StringifyNumber(val); + break; + case DukValue::Type::STRING: + _ss << "'" << val.as_string() << "'"; + break; + case DukValue::Type::OBJECT: + if (val.is_function()) + { + StringifyFunction(val); + } + else if (val.is_array()) + { + StringifyArray(val, canStartWithNewLine); + } + else + { + StringifyObject(val, canStartWithNewLine); + } + break; + case DukValue::Type::BUFFER: + _ss << "[Buffer]"; + break; + case DukValue::Type::POINTER: + _ss << "[Pointer]"; + break; + case DukValue::Type::LIGHTFUNC: + _ss << "[LightFunc]"; + break; + } + } + + void StringifyArray(const DukValue& val, bool canStartWithNewLine) + { + constexpr auto maxItemsToShow = 4; + + val.push(); + auto arrayLen = duk_get_length(_context, -1); + if (arrayLen == 0) + { + _ss << "[]"; + } + else if (arrayLen == 1) + { + _ss << "[ "; + for (duk_uarridx_t i = 0; i < arrayLen; i++) + { + if (duk_get_prop_index(_context, -1, i)) + { + if (i != 0) + { + _ss << ", "; + } + Stringify(DukValue::take_from_stack(_context), false); + } + } + _ss << " ]"; + } + else + { + if (canStartWithNewLine) + { + PushIndent(); + LineFeed(); + } + _ss << "[ "; + PushIndent(2); + for (duk_uarridx_t i = 0; i < arrayLen; i++) + { + if (i != 0) + { + _ss << ","; + LineFeed(); + } + if (i >= maxItemsToShow) + { + auto remainingItemsNotShown = arrayLen - maxItemsToShow; + if (remainingItemsNotShown == 1) + { + _ss << "... 1 more item"; + } + else + { + _ss << "... " << std::to_string(remainingItemsNotShown) << " more items"; + } + break; + } + else + { + if (duk_get_prop_index(_context, -1, i)) + { + Stringify(DukValue::take_from_stack(_context), false); + } + } + } + _ss << " ]"; + PopIndent(2); + if (canStartWithNewLine) + { + PopIndent(); + } + } + duk_pop(_context); + } + + void StringifyObject(const DukValue& val, bool canStartWithNewLine) + { + auto numEnumerables = GetNumEnumerablesOnObject(val); + if (numEnumerables == 0) + { + _ss << "{}"; + } + else if (numEnumerables == 1) + { + _ss << "{ "; + + val.push(); + duk_enum(_context, -1, 0); + auto index = 0; + while (duk_next(_context, -1, 1)) + { + if (index != 0) + { + _ss << ", "; + } + auto value = DukValue::take_from_stack(_context, -1); + auto key = DukValue::take_from_stack(_context, -1); + if (key.type() == DukValue::Type::STRING) + { + _ss << key.as_string() << ": "; + } + else + { + // For some reason the key was not a string + _ss << "?: "; + } + Stringify(value, true); + index++; + } + duk_pop_2(_context); + + _ss << " }"; + } + else + { + if (canStartWithNewLine) + { + PushIndent(); + LineFeed(); + } + + _ss << "{ "; + PushIndent(2); + + val.push(); + duk_enum(_context, -1, 0); + auto index = 0; + while (duk_next(_context, -1, 1)) + { + if (index != 0) + { + _ss << ","; + LineFeed(); + } + auto value = DukValue::take_from_stack(_context, -1); + auto key = DukValue::take_from_stack(_context, -1); + if (key.type() == DukValue::Type::STRING) + { + _ss << key.as_string() << ": "; + } + else + { + // For some reason the key was not a string + _ss << "?: "; + } + Stringify(value, true); + index++; + } + duk_pop_2(_context); + + PopIndent(2); + _ss << " }"; + + if (canStartWithNewLine) + { + PopIndent(); + } + } + } + + void StringifyFunction(const DukValue& val) + { + val.push(); + if (duk_is_c_function(_context, -1)) + { + _ss << "[Native Function]"; + } + else if (duk_is_ecmascript_function(_context, -1)) + { + _ss << "[ECMAScript Function]"; + } + else + { + _ss << "[Function]"; + } + duk_pop(_context); + } + + void StringifyBoolean(const DukValue& val) + { + _ss << val.as_bool() ? "true" : "false"; + } + + void StringifyNumber(const DukValue& val) + { + const auto d = val.as_double(); + const duk_int_t i = val.as_int(); + if (AlmostEqual(d, i)) + { + _ss << std::to_string(i); + } + else + { + _ss << std::to_string(d); + } + } + + size_t GetNumEnumerablesOnObject(const DukValue& val) + { + size_t count = 0; + val.push(); + duk_enum(_context, -1, 0); + while (duk_next(_context, -1, 0)) + { + count++; + duk_pop(_context); + } + duk_pop_2(_context); + return count; + } + + // Taken from http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon + template + static typename std::enable_if::is_integer, bool>::type AlmostEqual(T x, T y, int32_t ulp = 20) + { + // the machine epsilon has to be scaled to the magnitude of the values used + // and multiplied by the desired precision in ULPs (units in the last place) + return std::abs(x - y) <= std::numeric_limits::epsilon() * std::abs(x + y) * ulp + // unless the result is subnormal + || std::abs(x - y) + < (std::numeric_limits::min)(); // TODO: Remove parentheses around min once the macro is removed + } + +public: + static std::string StringifyExpression(const DukValue& val) + { + ExpressionStringifier instance(val.context()); + instance.Stringify(val, false); + return instance._ss.str(); + } +}; + DukContext::DukContext() { _context = duk_create_heap_default(); @@ -363,126 +665,9 @@ void ScriptEngine::AddNetworkPlugin(const std::string_view& code) LoadPlugin(plugin); } -// Taken from http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon -template -static typename std::enable_if::is_integer, bool>::type AlmostEqual(T x, T y, int32_t ulp = 20) +std::string OpenRCT2::Scripting::Stringify(const DukValue& val) { - // the machine epsilon has to be scaled to the magnitude of the values used - // and multiplied by the desired precision in ULPs (units in the last place) - return std::abs(x - y) <= std::numeric_limits::epsilon() * std::abs(x + y) * ulp - // unless the result is subnormal - || std::abs(x - y) < (std::numeric_limits::min)(); // TODO: Remove parentheses around min once the macro is removed -} - -std::string OpenRCT2::Scripting::Stringify(const DukValue& val, int32_t depth) -{ - if (depth >= 3) - return "..."; - - std::string str; - switch (val.type()) - { - case DukValue::Type::UNDEFINED: - str = "undefined"; - break; - case DukValue::Type::NULLREF: - str = "null"; - break; - case DukValue::Type::BOOLEAN: - str = val.as_bool() ? "true" : "false"; - break; - case DukValue::Type::NUMBER: - { - const auto d = val.as_double(); - const duk_int_t i = val.as_int(); - if (AlmostEqual(d, i)) - { - str = std::to_string(i); - } - else - { - str = std::to_string(d); - } - break; - } - case DukValue::Type::STRING: - str = "\"" + val.as_string() + "\""; - break; - case DukValue::Type::OBJECT: - if (val.is_function()) - { - auto ctx = val.context(); - val.push(); - if (duk_is_c_function(ctx, -1)) - { - str = u8"Æ’ [native]"; - } - else if (duk_is_ecmascript_function(ctx, -1)) - { - str = u8"Æ’ [ecmascript]"; - } - else - { - str = u8"Æ’ [javascript]"; - } - duk_pop(ctx); - } - else if (val.is_array()) - { - str = "["; - auto ctx = val.context(); - val.push(); - auto arrayLen = duk_get_length(ctx, -1); - for (duk_uarridx_t i = 0; i < arrayLen; i++) - { - if (i != 0) - str += ", "; - if (duk_get_prop_index(ctx, -1, i)) - { - auto arrayVal = DukValue::take_from_stack(ctx); - str += Stringify(arrayVal, depth + 1); - } - if (i >= 4) - { - str += ", ..."; - break; - } - } - duk_pop(ctx); - str += "]"; - } - else - { - str = "{"; - auto ctx = val.context(); - val.push(); - duk_enum(ctx, -1, 0); - auto index = 0; - while (duk_next(ctx, -1, 1)) - { - if (index != 0) - str += ", "; - auto value = DukValue::take_from_stack(ctx, -1); - auto key = DukValue::take_from_stack(ctx, -1); - str += Stringify(key, depth + 1); - str += ": "; - str += Stringify(value, depth + 1); - index++; - } - duk_pop_2(ctx); - str += "}"; - } - break; - case DukValue::Type::BUFFER: - str = "buffer"; - break; - case DukValue::Type::POINTER: - str = "pointer"; - break; - case DukValue::Type::LIGHTFUNC: - break; - } - return str; + return ExpressionStringifier::StringifyExpression(val); } bool OpenRCT2::Scripting::IsGameStateMutable() diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 3c2a2db8f0..705db8a2ef 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -168,7 +168,7 @@ namespace OpenRCT2::Scripting bool IsGameStateMutable(); void ThrowIfGameStateNotMutable(); - std::string Stringify(const DukValue& value, int32_t depth = 0); + std::string Stringify(const DukValue& value); } // namespace OpenRCT2::Scripting From 0cf0121f30dc67433635c07d212b1b5ef79a9833 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 25 Feb 2020 00:44:02 +0000 Subject: [PATCH 087/159] Fix API definitions --- distribution/openrct2.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 8e066e06b6..22030b4a60 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -15,7 +15,7 @@ // /// // -export type PluginType = "server" | "client" | "server_client"; +export type PluginType = "local" | "remote"; declare global { interface PluginMetadata { @@ -288,7 +288,7 @@ declare global { trousers: number; } - interface Map { + interface GameMap { readonly size: { x: number; y: number; }; readonly rides: number; readonly things: number; @@ -595,7 +595,7 @@ declare global { var console: Console; var context: Context; var date: GameDate; - var map: Map; + var map: GameMap; var network: Network; var park: Park; var ui: Ui; From e6011c891df0905ca189dbfb80321457eca84b63 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 25 Feb 2020 20:38:56 +0000 Subject: [PATCH 088/159] Add more questions to scripting readme --- distribution/scripting.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/distribution/scripting.md b/distribution/scripting.md index 1656f3d4dc..91e6bd2c76 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -64,6 +64,10 @@ Scripts can conist of any behaviour and have a large memory pool available to th The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plug-in system is to add APIs on-demand. So if you find an API is missing, please raise an issue for it on GitHub. +> How do I debug my script? + +Debugging has not yet been implemented but is planned. In the meantime, you can use `console.log` to print useful information for diagnosing problems. + > What does the error 'Game state is not mutable in this context' mean? This means you are attempting to modify the game state (e.g. change the park, map or guests etc.) in a context where you should not be doing so. This might be because your script is defined as `local` meaning it must work independently of other players not having the script enabled, or a remote script attempting to modify the game in the main function or a user interface event. @@ -125,6 +129,10 @@ if (typeof ui !== 'undefined') { } ``` +> Can I modify the widgets on built-in windows? + +Not yet. A lot of the internal code for these windows relies on the widgets existing, and being in a specific order, as well as hard resizing them to certain positions. Modifying them would likely crash the game until the window system is improved to handle such changes. + > Can servers add additional user interface elements to players? Yes, remote scripts are uploaded to every client and run as-is. Even if the server is running in headless mode, the script can still contain UI calls for the benefit of the players that are not running in headless mode. Be sure to check if the UI is available first before executing UI calls. From 00293d20e85b452a05df56ed93bf1a10a80c7252 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 25 Feb 2020 21:10:28 +0000 Subject: [PATCH 089/159] Fix compile --- src/openrct2/scripting/ScriptEngine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 06b4eca38a..0dc5514ff9 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -287,7 +287,7 @@ private: void StringifyBoolean(const DukValue& val) { - _ss << val.as_bool() ? "true" : "false"; + _ss << (val.as_bool() ? "true" : "false"); } void StringifyNumber(const DukValue& val) From 9dd9e600b541c4085331e802a02dbaf80f01f4a9 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 27 Feb 2020 18:22:32 +0000 Subject: [PATCH 090/159] Implement API for image buttons --- distribution/openrct2.d.ts | 1 + src/openrct2-ui/scripting/CustomWindow.cpp | 28 ++++++++++++++++++---- src/openrct2-ui/scripting/ScWidget.hpp | 24 ++++++++++++++++++- 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 22030b4a60..d4869fde9a 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -339,6 +339,7 @@ declare global { } interface ButtonWidget extends Widget { + image: number; text: string; onClick: () => void; } diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 27525ed3e2..4dd1756ec1 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -93,6 +93,7 @@ namespace OpenRCT2::Ui::Windows int32_t Width{}; int32_t Height{}; std::string Name; + ImageId Image; std::string Text; std::vector Items; int32_t SelectedIndex{}; @@ -136,13 +137,24 @@ namespace OpenRCT2::Ui::Windows result.Y = desc["y"].as_int(); result.Width = desc["width"].as_int(); result.Height = desc["height"].as_int(); + if (desc["isDisabled"].type() == DukValue::Type::BOOLEAN) + result.IsDisabled = desc["isDisabled"].as_bool(); if (desc["name"].type() == DukValue::Type::STRING) { result.Name = desc["name"].as_string(); } if (result.Type == "button") { - result.Text = ProcessString(desc["text"]); + auto dukImage = desc["image"]; + if (dukImage.type() == DukValue::Type::NUMBER) + { + auto img = dukImage.as_uint(); + result.Image = ImageId::FromUInt32(img); + } + else + { + result.Text = ProcessString(desc["text"]); + } result.OnClick = desc["onClick"]; } else if (result.Type == "checkbox") @@ -518,9 +530,17 @@ namespace OpenRCT2::Ui::Windows if (desc.Type == "button") { - widget.type = WWT_BUTTON; - widget.string = (utf8*)desc.Text.c_str(); - widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + if (desc.Image.HasValue()) + { + widget.type = WWT_FLATBTN; + widget.image = desc.Image.ToUInt32(); + } + else + { + widget.type = WWT_BUTTON; + widget.string = (utf8*)desc.Text.c_str(); + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + } widgetList.push_back(widget); } else if (desc.Type == "checkbox") diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index 3a43538db2..b6aff6d54d 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -206,12 +206,33 @@ namespace OpenRCT2::Scripting } } + uint32_t image_get() + { + if (IsCustomWindow()) + { + auto widget = GetWidget(); + if (widget != nullptr && widget->type == WWT_FLATBTN) + { + return widget->image; + } + } + return 0; + } + void image_set(uint32_t value) + { + auto widget = GetWidget(); + if (widget != nullptr && widget->type == WWT_FLATBTN) + { + widget->image = value; + } + } + std::string text_get() { if (IsCustomWindow()) { auto widget = GetWidget(); - if (widget != nullptr && widget->string != nullptr) + if (widget != nullptr && (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) && widget->string != nullptr) { return widget->string; } @@ -253,6 +274,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScWidget::isDisabled_get, &ScWidget::isDisabled_set, "isDisabled"); // No so common + dukglue_register_property(ctx, &ScWidget::image_get, &ScWidget::image_set, "image"); dukglue_register_property(ctx, &ScWidget::text_get, &ScWidget::text_set, "text"); dukglue_register_property(ctx, &ScWidget::isChecked_get, &ScWidget::isChecked_set, "isChecked"); dukglue_register_property(ctx, &ScWidget::viewport_get, nullptr, "viewport"); From 5c1fabec560a3e4560347cd825ab861c9df47742 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 27 Feb 2020 19:44:51 +0000 Subject: [PATCH 091/159] Implement API for spinners --- distribution/openrct2.d.ts | 9 ++++- src/openrct2-ui/scripting/CustomWindow.cpp | 46 ++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index d4869fde9a..a4ea761a93 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -326,7 +326,7 @@ declare global { * Represents the type of a widget, e.g. button or label. */ type WidgetType = - "button" | "checkbox" | "dropdown" | "groupbox" | "label" | "tabview" | "viewport"; + "button" | "checkbox" | "dropdown" | "groupbox" | "label" | "spinner" | "tabview" | "viewport"; interface Widget { type: WidgetType; @@ -358,6 +358,13 @@ declare global { interface LabelWidget extends Widget { text: string; + onChanged: (index: number) => void; + } + + interface SpinnerWidget extends Widget { + text: string; + onDecrement: () => void; + onIncrement: () => void; } interface ViewportWidget extends Widget { diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 4dd1756ec1..2d9aebd440 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -103,6 +103,8 @@ namespace OpenRCT2::Ui::Windows // Event handlers DukValue OnClick; DukValue OnChange; + DukValue OnIncrement; + DukValue OnDecrement; static std::string ProcessString(const DukValue& value) { @@ -181,6 +183,12 @@ namespace OpenRCT2::Ui::Windows { result.Text = ProcessString(desc["text"]); } + else if (result.Type == "spinner") + { + result.Text = ProcessString(desc["text"]); + result.OnIncrement = desc["onIncrement"]; + result.OnDecrement = desc["onDecrement"]; + } return result; } }; @@ -405,6 +413,17 @@ namespace OpenRCT2::Ui::Windows w->x + widget->left, w->y + widget->top, widget->bottom - widget->top + 1, w->colours[widget->colour], 0, DROPDOWN_FLAG_STAY_OPEN, numItems, widget->right - widget->left - 3); } + else if (widgetDesc->Type == "spinner") + { + if (widget->text == STR_NUMERIC_DOWN) + { + InvokeEventHandler(info.Owner, widgetDesc->OnDecrement); + } + else if (widget->text == STR_NUMERIC_UP) + { + InvokeEventHandler(info.Owner, widgetDesc->OnIncrement); + } + } } } @@ -591,6 +610,32 @@ namespace OpenRCT2::Ui::Windows widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); } + else if (desc.Type == "spinner") + { + widget.type = WWT_SPINNER; + widget.string = (utf8*)desc.Text.c_str(); + widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; + widgetList.push_back(widget); + + // Add the decrement button + widget = {}; + widget.type = WWT_BUTTON; + widget.colour = 1; + widget.left = desc.X + desc.Width - 25; + widget.right = widget.left + 12; + widget.top = desc.Y + 1; + widget.bottom = desc.Y + desc.Height - 1; + widget.text = STR_NUMERIC_DOWN; + widget.tooltip = STR_NONE; + widget.flags |= WIDGET_FLAGS::IS_ENABLED; + widgetList.push_back(widget); + + // Add the increment button + widget.left = desc.X + desc.Width - 12; + widget.right = widget.left + 11; + widget.text = STR_NUMERIC_UP; + widgetList.push_back(widget); + } else if (desc.Type == "viewport") { widget.type = WWT_VIEWPORT; @@ -685,6 +730,7 @@ namespace OpenRCT2::Ui::Windows { customWidgetInfo->Text = CustomWidgetDesc::ProcessString(value); w->widgets[widgetIndex].string = customWidgetInfo->Text.data(); + widget_invalidate(w, widgetIndex); } } } From 09c8c6d5083a86fde27990b50e769b00fc543fd8 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 27 Feb 2020 19:59:46 +0000 Subject: [PATCH 092/159] Implement window colours API --- distribution/openrct2.d.ts | 1 + src/openrct2-ui/scripting/CustomWindow.cpp | 22 +++++++++++++++++ src/openrct2-ui/scripting/ScWindow.hpp | 28 ++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index a4ea761a93..998f3bb311 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -412,6 +412,7 @@ declare global { minWidth?: number; minHeight?: number; widgets?: Widget[]; + colours?: number[]; tabs?: Tab[]; onClose?: () => void; diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 2d9aebd440..a79cf825db 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -207,6 +207,7 @@ namespace OpenRCT2::Ui::Windows std::string Title; std::optional Id; std::vector Widgets; + std::vector Colours; CustomWindowDesc() = default; @@ -238,6 +239,19 @@ namespace OpenRCT2::Ui::Windows }); } + if (desc["colours"].is_array()) + { + auto dukColours = desc["colours"].as_array(); + std::transform(dukColours.begin(), dukColours.end(), std::back_inserter(result.Colours), [](const DukValue& w) { + colour_t c = COLOUR_BLACK; + if (w.type() == DukValue::Type::NUMBER) + { + c = static_cast(std::clamp(w.as_int(), COLOUR_BLACK, COLOUR_COUNT - 1)); + } + return c; + }); + } + return result; } @@ -315,9 +329,17 @@ namespace OpenRCT2::Ui::Windows window->number = GetNewWindowNumber(); window->custom_info = new CustomWindowInfo(owner, desc); window->enabled_widgets = (1 << WIDX_CLOSE); + + // Set window colours window->colours[0] = COLOUR_GREY; window->colours[1] = COLOUR_GREY; window->colours[2] = COLOUR_GREY; + auto numColours = std::min(std::size(window->colours), std::size(desc.Colours)); + for (size_t i = 0; i < numColours; i++) + { + window->colours[i] = desc.Colours[i]; + } + if (desc.IsResizable()) { window->min_width = desc.MinWidth.value_or(0); diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 490a38fe08..7c81653972 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -98,6 +98,33 @@ namespace OpenRCT2::Scripting return result; } + std::vector colours_get() + { + std::vector result; + auto w = GetWindow(); + if (w != nullptr) + { + result.reserve(std::size(w->colours)); + for (auto c : w->colours) + { + result.push_back(c); + } + } + return result; + } + void colours_set(std::vector colours) + { + auto w = GetWindow(); + if (w != nullptr) + { + for (int32_t i = 0; i < std::size(w->colours); i++) + { + w->colours[i] = i < colours.size() ? std::clamp(colours[i], COLOUR_BLACK, COLOUR_COUNT - 1) + : COLOUR_BLACK; + } + } + } + void close() { auto w = GetWindow(); @@ -141,6 +168,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScWindow::height_get, nullptr, "height"); dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); dukglue_register_property(ctx, &ScWindow::widgets_get, nullptr, "widgets"); + dukglue_register_property(ctx, &ScWindow::colours_get, &ScWindow::colours_set, "colours"); dukglue_register_method(ctx, &ScWindow::close, "close"); dukglue_register_method(ctx, &ScWindow::findWidget, "findWidget"); From 4d221341daa338b1b67d100a0f7273901dff74f8 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 27 Feb 2020 22:13:49 +0000 Subject: [PATCH 093/159] Improve string handling and allow window update --- src/openrct2-ui/scripting/CustomWindow.cpp | 44 +++++++------ src/openrct2-ui/scripting/CustomWindow.h | 2 + src/openrct2-ui/scripting/ScWindow.hpp | 20 ++++++ src/openrct2/localisation/Language.cpp | 75 ++++++++++++++++++++++ src/openrct2/localisation/Language.h | 1 + 5 files changed, 121 insertions(+), 21 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index a79cf825db..6a6f3e929f 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -17,6 +17,7 @@ # include # include # include +# include # include # include # include @@ -109,28 +110,10 @@ namespace OpenRCT2::Ui::Windows static std::string ProcessString(const DukValue& value) { if (value.type() == DukValue::Type::STRING) - return ProcessString(value.as_string()); + return language_convert_string(value.as_string()); return {}; } - static std::string ProcessString(const std::string_view& s) - { - std::string result; - result.reserve(s.size()); - for (char c : s) - { - if (c == '\n') - { - result.push_back(FORMAT_NEWLINE); - } - else - { - result.push_back(c); - } - } - return result; - } - static CustomWidgetDesc FromDukValue(DukValue desc) { CustomWidgetDesc result; @@ -228,7 +211,7 @@ namespace OpenRCT2::Ui::Windows result.MaxWidth = GetOptionalInt(desc["maxWidth"]); result.MinHeight = GetOptionalInt(desc["minHeight"]); result.MaxHeight = GetOptionalInt(desc["maxHeight"]); - result.Title = desc["title"].as_string(); + result.Title = language_convert_string(desc["title"].as_string()); result.Id = GetOptionalInt(desc["id"]); if (desc["widgets"].is_array()) @@ -742,6 +725,25 @@ namespace OpenRCT2::Ui::Windows } } + std::string GetWindowTitle(rct_window* w) + { + if (w->custom_info != nullptr) + { + auto& customInfo = GetInfo(w); + return customInfo.Desc.Title; + } + return {}; + } + + void UpdateWindowTitle(rct_window* w, const std::string_view& value) + { + if (w->custom_info != nullptr) + { + auto& customInfo = GetInfo(w); + customInfo.Desc.Title = value; + } + } + void UpdateWidgetText(rct_window* w, rct_widgetindex widgetIndex, const std::string_view& value) { if (w->custom_info != nullptr) @@ -750,7 +752,7 @@ namespace OpenRCT2::Ui::Windows auto customWidgetInfo = customInfo.GetCustomWidgetDesc(widgetIndex); if (customWidgetInfo != nullptr) { - customWidgetInfo->Text = CustomWidgetDesc::ProcessString(value); + customWidgetInfo->Text = language_convert_string(value); w->widgets[widgetIndex].string = customWidgetInfo->Text.data(); widget_invalidate(w, widgetIndex); } diff --git a/src/openrct2-ui/scripting/CustomWindow.h b/src/openrct2-ui/scripting/CustomWindow.h index f63ecfcfec..5709d6ee9c 100644 --- a/src/openrct2-ui/scripting/CustomWindow.h +++ b/src/openrct2-ui/scripting/CustomWindow.h @@ -18,6 +18,8 @@ namespace OpenRCT2::Ui::Windows { + std::string GetWindowTitle(rct_window* w); + void UpdateWindowTitle(rct_window* w, const std::string_view& value); void UpdateWidgetText(rct_window* w, rct_widgetindex widget, const std::string_view& string_view); rct_window* FindCustomWindowByClassification(const std::string_view& classification); std::optional FindWidgetIndexByName(rct_window* w, const std::string_view& name); diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 7c81653972..33bffc2b7e 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -16,6 +16,7 @@ # include # include # include +# include # include namespace OpenRCT2::Scripting @@ -125,6 +126,24 @@ namespace OpenRCT2::Scripting } } + std::string title_get() + { + auto w = GetWindow(); + if (w != nullptr && w->classification == WC_CUSTOM) + { + return GetWindowTitle(w); + } + return {}; + } + void title_set(std::string value) + { + auto w = GetWindow(); + if (w != nullptr && w->classification == WC_CUSTOM) + { + UpdateWindowTitle(w, language_convert_string(value)); + } + } + void close() { auto w = GetWindow(); @@ -169,6 +188,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScWindow::isSticky_get, nullptr, "isSticky"); dukglue_register_property(ctx, &ScWindow::widgets_get, nullptr, "widgets"); dukglue_register_property(ctx, &ScWindow::colours_get, &ScWindow::colours_set, "colours"); + dukglue_register_property(ctx, &ScWindow::title_get, &ScWindow::title_set, "title"); dukglue_register_method(ctx, &ScWindow::close, "close"); dukglue_register_method(ctx, &ScWindow::findWidget, "findWidget"); diff --git a/src/openrct2/localisation/Language.cpp b/src/openrct2/localisation/Language.cpp index f7cc78bea6..adde094cf3 100644 --- a/src/openrct2/localisation/Language.cpp +++ b/src/openrct2/localisation/Language.cpp @@ -136,3 +136,78 @@ rct_string_id language_allocate_object_string(const std::string& target) auto& localisationService = OpenRCT2::GetContext()->GetLocalisationService(); return localisationService.AllocateObjectString(target); } + +std::string language_convert_string(const std::string_view& s) +{ + enum class PARSE_STATE + { + DEFAULT, + CR, + TOKEN, + }; + + std::string result; + std::string token; + PARSE_STATE state{}; + token.reserve(64); + result.reserve(s.size() * 2); + for (char c : s) + { + switch (state) + { + case PARSE_STATE::CR: + result.push_back(FORMAT_NEWLINE); + state = PARSE_STATE::DEFAULT; + [[fallthrough]]; + case PARSE_STATE::DEFAULT: + switch (c) + { + case '\r': + state = PARSE_STATE::CR; + break; + case '\n': + result.push_back(FORMAT_NEWLINE); + break; + case '{': + token.clear(); + state = PARSE_STATE::TOKEN; + break; + default: + if (c >= 32) + { + result.push_back(c); + } + break; + } + break; + case PARSE_STATE::TOKEN: + if (c == '}') + { + auto code = format_get_code(token.c_str()); + if (code == 0) + { + int32_t number{}; + if (sscanf(token.c_str(), "%d", &number) == 1) + { + auto b = static_cast(std::clamp(number, 0, 255)); + token.push_back(b); + } + } + else + { + char buffer[8]{}; + utf8_write_codepoint(buffer, code); + result.append(buffer); + } + state = PARSE_STATE::DEFAULT; + } + else + { + token.push_back(c); + } + break; + } + } + result.shrink_to_fit(); + return result; +} diff --git a/src/openrct2/localisation/Language.h b/src/openrct2/localisation/Language.h index ef10e08e2b..ada81173cc 100644 --- a/src/openrct2/localisation/Language.h +++ b/src/openrct2/localisation/Language.h @@ -107,6 +107,7 @@ bool language_get_localised_scenario_strings(const utf8* scenarioFilename, rct_s void language_free_object_string(rct_string_id stringId); rct_string_id language_get_object_override_string_id(const char* identifier, uint8_t index); rct_string_id language_allocate_object_string(const std::string& target); +std::string language_convert_string(const std::string_view& s); constexpr utf8* utf8_write_codepoint(utf8* dst, uint32_t codepoint) { From 7628289eb3eee1c83a66ce95e4d956f31b73dfff Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 27 Feb 2020 22:25:26 +0000 Subject: [PATCH 094/159] Implement reverse of string processing --- src/openrct2-ui/scripting/ScWidget.hpp | 2 +- src/openrct2-ui/scripting/ScWindow.hpp | 2 +- src/openrct2/localisation/Language.cpp | 35 ++++++++++++++++++++++++++ src/openrct2/localisation/Language.h | 1 + 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index b6aff6d54d..7d046a8a79 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -234,7 +234,7 @@ namespace OpenRCT2::Scripting auto widget = GetWidget(); if (widget != nullptr && (widget->flags & WIDGET_FLAGS::TEXT_IS_STRING) && widget->string != nullptr) { - return widget->string; + return language_convert_string_to_tokens(widget->string); } } return ""; diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 33bffc2b7e..ee42b5532b 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -131,7 +131,7 @@ namespace OpenRCT2::Scripting auto w = GetWindow(); if (w != nullptr && w->classification == WC_CUSTOM) { - return GetWindowTitle(w); + return language_convert_string_to_tokens(GetWindowTitle(w)); } return {}; } diff --git a/src/openrct2/localisation/Language.cpp b/src/openrct2/localisation/Language.cpp index adde094cf3..9fa7b04f09 100644 --- a/src/openrct2/localisation/Language.cpp +++ b/src/openrct2/localisation/Language.cpp @@ -137,6 +137,41 @@ rct_string_id language_allocate_object_string(const std::string& target) return localisationService.AllocateObjectString(target); } +std::string language_convert_string_to_tokens(const std::string_view& s) +{ + std::string result; + result.reserve(s.size() * 4); + std::string input = std::string(s); + auto readPtr = input.c_str(); + while (true) + { + char32_t code = utf8_get_next(readPtr, (const utf8**)&readPtr); + if (code == 0) + { + break; + } + else if (code == '\n') + { + result.push_back('\n'); + } + else if (utf8_is_format_code(code)) + { + auto token = format_get_token(code); + result.push_back('{'); + result.append(token); + result.push_back('}'); + } + else + { + char buffer[8]{}; + utf8_write_codepoint(buffer, code); + result.append(buffer); + } + } + result.shrink_to_fit(); + return result; +} + std::string language_convert_string(const std::string_view& s) { enum class PARSE_STATE diff --git a/src/openrct2/localisation/Language.h b/src/openrct2/localisation/Language.h index ada81173cc..9a0d40886d 100644 --- a/src/openrct2/localisation/Language.h +++ b/src/openrct2/localisation/Language.h @@ -107,6 +107,7 @@ bool language_get_localised_scenario_strings(const utf8* scenarioFilename, rct_s void language_free_object_string(rct_string_id stringId); rct_string_id language_get_object_override_string_id(const char* identifier, uint8_t index); rct_string_id language_allocate_object_string(const std::string& target); +std::string language_convert_string_to_tokens(const std::string_view& s); std::string language_convert_string(const std::string_view& s); constexpr utf8* utf8_write_codepoint(utf8* dst, uint32_t codepoint) From cf9478eb7610706235b44d5358b371cfa39f622d Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 28 Feb 2020 08:09:52 +0000 Subject: [PATCH 095/159] Fix build --- src/openrct2-ui/scripting/ScWindow.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index ee42b5532b..a6067aaccc 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -118,7 +118,7 @@ namespace OpenRCT2::Scripting auto w = GetWindow(); if (w != nullptr) { - for (int32_t i = 0; i < std::size(w->colours); i++) + for (size_t i = 0; i < std::size(w->colours); i++) { w->colours[i] = i < colours.size() ? std::clamp(colours[i], COLOUR_BLACK, COLOUR_COUNT - 1) : COLOUR_BLACK; From a4be43eaa9f953127447fc330ddd0f9f5e089289 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 28 Feb 2020 18:21:33 +0000 Subject: [PATCH 096/159] Fix clients starting remote scripts --- src/openrct2/scripting/Plugin.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index f7f409207e..3e593156d1 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -62,7 +62,7 @@ namespace OpenRCT2::Scripting bool HasPath() const { - return _path.empty(); + return !_path.empty(); } const PluginMetadata& GetMetadata() const From 32d72471b8ccd7e5701f24a5a0988e33ccc2efc4 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 28 Feb 2020 20:56:04 +0000 Subject: [PATCH 097/159] Add more tile APIs --- distribution/openrct2.d.ts | 24 +++- src/openrct2/scripting/ScMap.hpp | 3 +- src/openrct2/scripting/ScTile.hpp | 227 +++++++++++++++++++++++++++--- src/openrct2/world/Map.cpp | 33 +++-- 4 files changed, 251 insertions(+), 36 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 998f3bb311..585e5dbd28 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -242,12 +242,34 @@ declare global { interface CorruptElement extends BaseTileElement { } + /** + * Represents a tile containing tile elements on the map. This is a fixed handle + * for a given tile position. It can be re-used safely between game ticks. + */ interface Tile { + /** The x position in tiles. */ readonly x: number; + /** The y position in tiles. */ readonly y: number; - elements: TileElement[]; + /** Gets an array of all the tile elements on this tile. */ + readonly elements: TileElement[]; + /** Gets the number of tile elements on this tile. */ + readonly numElements: number; + /** + * Gets or sets the raw data for this tile. + * This can provide more control and efficiency for tile manipulation but requires + * knowledge of tile element structures and may change between versions of OpenRCT2. + */ + data: Uint8Array; + /** Gets the tile element at the given index on this tile. */ getElement(index: number): TileElement; + /** Gets the tile element at the given index on this tile. */ + getElement(index: number): T; + /** Inserts a new tile element at the given index on this tile. */ + insertElement(index: number): TileElement; + /** Removes the tile element at the given index from this tile. */ + removeElement(index: number): void; } interface Object { diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 94f4749a3b..191821d416 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -70,8 +70,7 @@ namespace OpenRCT2::Scripting std::shared_ptr getTile(int32_t x, int32_t y) { auto coords = TileCoordsXY(x, y).ToCoordsXY(); - auto firstElement = map_get_first_element_at(coords); - return std::make_shared(coords, firstElement); + return std::make_shared(coords); } std::shared_ptr getThing(int32_t id) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index e8d4fd6315..2f72c4f04c 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -66,6 +66,33 @@ namespace OpenRCT2::Scripting } } + void type_set(std::string value) + { + auto type = _element->type; + if (value == "surface") + type = TILE_ELEMENT_TYPE_SURFACE; + else if (value == "footpath") + type = TILE_ELEMENT_TYPE_PATH; + else if (value == "track") + type = TILE_ELEMENT_TYPE_TRACK; + else if (value == "small-scenery") + type = TILE_ELEMENT_TYPE_SMALL_SCENERY; + else if (value == "entrance") + type = TILE_ELEMENT_TYPE_ENTRANCE; + else if (value == "wall") + type = TILE_ELEMENT_TYPE_WALL; + else if (value == "large-scenery") + type = TILE_ELEMENT_TYPE_LARGE_SCENERY; + else if (value == "banner") + type = TILE_ELEMENT_TYPE_BANNER; + else if (value == "openrct2-corrupt") + type = TILE_ELEMENT_TYPE_CORRUPT; + else + return; + _element->type = type; + map_invalidate_tile_full(_coords); + } + bool broken_get() const { return _element->flags & TILE_ELEMENT_FLAG_BROKEN; @@ -132,11 +159,12 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { - dukglue_register_property(ctx, &ScTileElement::type_get, nullptr, "type"); - dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + dukglue_register_property(ctx, &ScTileElement::type_get, &ScTileElement::type_set, "type"); dukglue_register_property(ctx, &ScTileElement::baseHeight_get, &ScTileElement::baseHeight_set, "baseHeight"); dukglue_register_property( ctx, &ScTileElement::clearanceHeight_get, &ScTileElement::clearanceHeight_set, "clearanceHeight"); + + dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); dukglue_register_property(ctx, &ScTileElement::grassLength_get, &ScTileElement::grassLength_set, "grassLength"); dukglue_register_property(ctx, &ScTileElement::hasOwnership_get, nullptr, "hasOwnership"); } @@ -146,25 +174,14 @@ namespace OpenRCT2::Scripting { private: CoordsXY _coords; - TileElement* _first; - size_t _count = 0; public: - ScTile(CoordsXY coords, TileElement* first) + ScTile(CoordsXY coords) : _coords(coords) - , _first(first) { - _count = 0; - if (first != nullptr) - { - auto element = first; - do - { - _count++; - } while (!(element++)->IsLastForTile()); - } } + private: int32_t x_get() { return _coords.x / 32; @@ -175,24 +192,194 @@ namespace OpenRCT2::Scripting return _coords.y / 32; } - size_t elements_get() + size_t numElements_get() { - return _count; + auto first = GetFirstElement(); + return GetNumElements(first); + } + + std::vector> elements_get() + { + std::vector> result; + auto first = GetFirstElement(); + auto currentNumElements = GetNumElements(first); + if (currentNumElements != 0) + { + result.reserve(currentNumElements); + for (size_t i = 0; i < currentNumElements; i++) + { + result.push_back(std::make_shared(_coords, &first[i])); + } + } + return result; + } + + DukValue data_get() + { + auto ctx = GetDukContext(); + auto first = map_get_first_element_at(_coords); + auto dataLen = GetNumElements(first) * sizeof(TileElement); + auto data = duk_push_fixed_buffer(ctx, dataLen); + if (first != nullptr) + { + std::memcpy(data, first, dataLen); + } + duk_push_buffer_object(ctx, -1, 0, dataLen, DUK_BUFOBJ_UINT8ARRAY); + return DukValue::take_from_stack(ctx); + } + + void data_set(DukValue value) + { + auto ctx = value.context(); + value.push(); + if (duk_is_buffer_data(ctx, -1)) + { + duk_size_t dataLen{}; + auto data = duk_get_buffer_data(ctx, -1, &dataLen); + auto numElements = dataLen / sizeof(TileElement); + if (numElements == 0) + { + map_set_tile_element(TileCoordsXY(_coords), nullptr); + } + else + { + auto first = GetFirstElement(); + auto currentNumElements = GetNumElements(first); + if (numElements > currentNumElements) + { + // Allocate space for the extra tile elements (inefficient but works) + auto pos = TileCoordsXYZ(TileCoordsXY(_coords), 0); + auto numToInsert = numElements - currentNumElements; + for (size_t i = 0; i < numToInsert; i++) + { + tile_element_insert(pos, 0); + } + + // Copy data to element span + first = map_get_first_element_at(_coords); + currentNumElements = GetNumElements(first); + if (currentNumElements != 0) + { + std::memcpy(first, data, currentNumElements * sizeof(TileElement)); + // Safely force last tile flag for last element to avoid read overrun + first[numElements - 1].SetLastForTile(true); + } + } + else + { + std::memcpy(first, data, numElements * sizeof(TileElement)); + // Safely force last tile flag for last element to avoid read overrun + first[numElements - 1].SetLastForTile(true); + } + } + map_invalidate_tile_full(_coords); + } } std::shared_ptr getElement(size_t index) { - if (index >= _count) - return nullptr; - return std::make_shared(_coords, &_first[index]); + auto first = GetFirstElement(); + if (index < GetNumElements(first)) + { + return std::make_shared(_coords, &first[index]); + } + return {}; } + std::shared_ptr insertElement(size_t index) + { + auto first = GetFirstElement(); + auto origNumElements = GetNumElements(first); + if (index >= 0 && index <= origNumElements) + { + std::vector data(first, first + origNumElements); + + auto pos = TileCoordsXYZ(TileCoordsXY(_coords), 0); + auto newElement = tile_element_insert(pos, 0); + if (newElement == nullptr) + { + auto ctx = GetDukContext(); + duk_error(ctx, DUK_ERR_ERROR, "Unable to allocate element."); + } + else + { + // Inefficient, requires a dedicated method in tile element manager + first = GetFirstElement(); + // Copy elements before index + if (index > 0) + { + std::memcpy(first, &data[0], index * sizeof(TileElement)); + } + // Zero new element + std::memset(first + index, 0, sizeof(TileElement)); + // Copy elements after index + if (index < origNumElements) + { + std::memcpy(first + index + 1, &data[index], (origNumElements - index) * sizeof(TileElement)); + } + for (size_t i = 0; i < origNumElements; i++) + { + first[i].SetLastForTile(false); + } + first[origNumElements].SetLastForTile(true); + map_invalidate_tile_full(_coords); + return std::make_shared(_coords, &first[index]); + } + } + else + { + auto ctx = GetDukContext(); + duk_error(ctx, DUK_ERR_RANGE_ERROR, "Index must be between zero and the number of elements on the tile."); + } + } + + void removeElement(size_t index) + { + auto first = GetFirstElement(); + if (index < GetNumElements(first)) + { + tile_element_remove(&first[index]); + map_invalidate_tile_full(_coords); + } + } + + TileElement* GetFirstElement() + { + return map_get_first_element_at(_coords); + } + + static size_t GetNumElements(const TileElement* first) + { + size_t count = 0; + if (first != nullptr) + { + auto element = first; + do + { + count++; + } while (!(element++)->IsLastForTile()); + } + return count; + } + + duk_context* GetDukContext() + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto ctx = scriptEngine.GetContext(); + return ctx; + } + + public: static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScTile::x_get, nullptr, "x"); dukglue_register_property(ctx, &ScTile::y_get, nullptr, "y"); dukglue_register_property(ctx, &ScTile::elements_get, nullptr, "elements"); + dukglue_register_property(ctx, &ScTile::numElements_get, nullptr, "numElements"); + dukglue_register_property(ctx, &ScTile::data_get, &ScTile::data_set, "data"); dukglue_register_method(ctx, &ScTile::getElement, "getElement"); + dukglue_register_method(ctx, &ScTile::insertElement, "insertElement"); + dukglue_register_method(ctx, &ScTile::removeElement, "removeElement"); } }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/world/Map.cpp b/src/openrct2/world/Map.cpp index 07519cbc33..2937cec6ef 100644 --- a/src/openrct2/world/Map.cpp +++ b/src/openrct2/world/Map.cpp @@ -1170,21 +1170,28 @@ TileElement* tile_element_insert(const CoordsXYZ& loc, int32_t occupiedQuadrants // Set tile index pointer to point to new element block gTileElementTilePointers[tileLoc.y * MAXIMUM_MAP_SIZE_TECHNICAL + tileLoc.x] = newTileElement; - // Copy all elements that are below the insert height - while (loc.z >= originalTileElement->GetBaseZ()) + if (originalTileElement == nullptr) { - // Copy over map element - *newTileElement = *originalTileElement; - originalTileElement->base_height = 255; - originalTileElement++; - newTileElement++; - - if ((newTileElement - 1)->IsLastForTile()) + isLastForTile = true; + } + else + { + // Copy all elements that are below the insert height + while (loc.z >= originalTileElement->GetBaseZ()) { - // No more elements above the insert element - (newTileElement - 1)->SetLastForTile(false); - isLastForTile = true; - break; + // Copy over map element + *newTileElement = *originalTileElement; + originalTileElement->base_height = 255; + originalTileElement++; + newTileElement++; + + if ((newTileElement - 1)->IsLastForTile()) + { + // No more elements above the insert element + (newTileElement - 1)->SetLastForTile(false); + isLastForTile = true; + break; + } } } From 4d5e7f19ca015266db40be91a880138309e42662 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 29 Feb 2020 13:18:31 +0000 Subject: [PATCH 098/159] Implement surface style API and improve plugin calling --- distribution/openrct2.d.ts | 5 ++- src/openrct2-ui/scripting/CustomMenu.h | 8 +---- src/openrct2-ui/scripting/CustomWindow.cpp | 17 ++-------- src/openrct2/scripting/HookEngine.cpp | 37 +++++++-------------- src/openrct2/scripting/HookEngine.h | 14 ++++---- src/openrct2/scripting/ScTile.hpp | 38 +++++++++++++++++----- src/openrct2/scripting/ScriptEngine.cpp | 30 ++++++++++++++++- src/openrct2/scripting/ScriptEngine.h | 3 ++ 8 files changed, 86 insertions(+), 66 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 585e5dbd28..c24f568639 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -155,9 +155,8 @@ declare global { interface BaseTileElement { type: TileElementType; - baseHeight: number; - clearanceHeight: number; - broken: boolean; + baseZ: number; + clearanceZ: number; } // interface TileElement extends BaseTileElement { diff --git a/src/openrct2-ui/scripting/CustomMenu.h b/src/openrct2-ui/scripting/CustomMenu.h index 05300ac894..5b754a34bb 100644 --- a/src/openrct2-ui/scripting/CustomMenu.h +++ b/src/openrct2-ui/scripting/CustomMenu.h @@ -37,13 +37,7 @@ namespace OpenRCT2::Scripting void Invoke() const { auto& scriptEngine = GetContext()->GetScriptEngine(); - auto& execInfo = scriptEngine.GetExecInfo(); - auto ctx = scriptEngine.GetContext(); - - ScriptExecutionInfo::PluginScope scope(execInfo, Owner, false); - Callback.push(); - duk_pcall(ctx, 0); - duk_pop(ctx); + scriptEngine.ExecutePluginCall(Owner, Callback, {}, false); } }; diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 6a6f3e929f..d5299bc9f2 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -708,21 +708,8 @@ namespace OpenRCT2::Ui::Windows static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args) { - if (dukHandler.is_function()) - { - auto& scriptEngine = GetContext()->GetScriptEngine(); - auto& execInfo = scriptEngine.GetExecInfo(); - { - ScriptExecutionInfo::PluginScope scope(execInfo, owner, false); - dukHandler.push(); - for (const auto& arg : args) - { - arg.push(); - } - duk_pcall(dukHandler.context(), (duk_idx_t)args.size()); - duk_pop(dukHandler.context()); - } - } + auto& scriptEngine = GetContext()->GetScriptEngine(); + scriptEngine.ExecutePluginCall(owner, dukHandler, args, false); } std::string GetWindowTitle(rct_window* w) diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index ee554fd75a..fa3442f2ce 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -28,8 +28,9 @@ HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string& name) return (result != LookupTable.end()) ? result->second : HOOK_TYPE::UNDEFINED; } -HookEngine::HookEngine(ScriptExecutionInfo& execInfo) - : _execInfo(execInfo) +HookEngine::HookEngine(ScriptEngine& scriptEngine, ScriptExecutionInfo& execInfo) + : _scriptEngine(scriptEngine) + , _execInfo(execInfo) { _hookMap.resize(NUM_HOOK_TYPES); for (size_t i = 0; i < NUM_HOOK_TYPES; i++) @@ -100,29 +101,16 @@ void HookEngine::Call(HOOK_TYPE type, bool isGameStateMutable) auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner, false); - - const auto& function = hook.Function; - function.push(); - duk_pcall(function.context(), 0); - duk_pop(function.context()); + _scriptEngine.ExecutePluginCall(hook.Owner, hook.Function, {}, isGameStateMutable); } } -void HookEngine::Call(HOOK_TYPE type, DukValue args, bool isGameStateMutable) +void HookEngine::Call(HOOK_TYPE type, const DukValue& arg, bool isGameStateMutable) { auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner, false); - - const auto& function = hook.Function; - auto ctx = function.context(); - function.push(); - - args.push(); - duk_pcall(ctx, 1); - duk_pop(ctx); + _scriptEngine.ExecutePluginCall(hook.Owner, hook.Function, { arg }, isGameStateMutable); } } @@ -132,12 +120,9 @@ void HookEngine::Call( auto& hookList = GetHookList(type); for (auto& hook : hookList.Hooks) { - ScriptExecutionInfo::PluginScope scope(_execInfo, hook.Owner, false); - - const auto& function = hook.Function; - auto ctx = function.context(); - function.push(); + auto ctx = _scriptEngine.GetContext(); + // Convert key/value pairs into an object auto objIdx = duk_push_object(ctx); for (const auto& arg : args) { @@ -157,8 +142,10 @@ void HookEngine::Call( } duk_put_prop_string(ctx, objIdx, arg.first.data()); } - duk_pcall(ctx, 1); - duk_pop(ctx); + + std::vector dukArgs; + dukArgs.push_back(DukValue::take_from_stack(ctx)); + _scriptEngine.ExecutePluginCall(hook.Owner, hook.Function, dukArgs, isGameStateMutable); } } diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index cfaeaf9474..60ba158cfe 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -22,6 +22,7 @@ namespace OpenRCT2::Scripting { + class ScriptEngine; class ScriptExecutionInfo; class Plugin; @@ -42,7 +43,7 @@ namespace OpenRCT2::Scripting std::shared_ptr Owner; DukValue Function; - Hook(); + Hook() = default; Hook(uint32_t cookie, std::shared_ptr owner, const DukValue& function) : Cookie(cookie) , Owner(owner) @@ -56,11 +57,9 @@ namespace OpenRCT2::Scripting HOOK_TYPE Type{}; std::vector Hooks; - HookList() - { - } + HookList() = default; HookList(const HookList&) = delete; - HookList(HookList&& src) + HookList(HookList&& src) noexcept : Type(std::move(src.Type)) , Hooks(std::move(src.Hooks)) { @@ -70,12 +69,13 @@ namespace OpenRCT2::Scripting class HookEngine { private: + ScriptEngine& _scriptEngine; ScriptExecutionInfo& _execInfo; std::vector _hookMap; uint32_t _nextCookie = 1; public: - HookEngine(ScriptExecutionInfo& execInfo); + HookEngine(ScriptEngine& scriptEngine, ScriptExecutionInfo& execInfo); HookEngine(const HookEngine&) = delete; uint32_t Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue& function); void Unsubscribe(HOOK_TYPE type, uint32_t cookie); @@ -83,7 +83,7 @@ namespace OpenRCT2::Scripting void UnsubscribeAll(); bool HasSubscriptions(HOOK_TYPE type) const; void Call(HOOK_TYPE type, bool isGameStateMutable); - void Call(HOOK_TYPE type, DukValue args, bool isGameStateMutable); + void Call(HOOK_TYPE type, const DukValue& arg, bool isGameStateMutable); void Call( HOOK_TYPE type, const std::initializer_list>& args, bool isGameStateMutable); diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 2f72c4f04c..1b56d4dca7 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -20,6 +20,7 @@ # include "ScriptEngine.h" # include +# include namespace OpenRCT2::Scripting { @@ -110,26 +111,43 @@ namespace OpenRCT2::Scripting } } - auto baseHeight_get() const + auto baseZ_get() const { return _element->base_height; } - void baseHeight_set(uint8_t newBaseHeight) + void baseZ_set(uint8_t newBaseHeight) { ThrowIfGameStateNotMutable(); _element->base_height = newBaseHeight; } - auto clearanceHeight_get() const + auto clearanceZ_get() const { return _element->clearance_height; } - void clearanceHeight_set(uint8_t newClearanceHeight) + void clearanceZ_set(uint8_t newClearanceHeight) { ThrowIfGameStateNotMutable(); _element->clearance_height = newClearanceHeight; } + uint32_t surfaceStyle_get() + { + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetSurfaceStyle(); + return 0; + } + void surfaceStyle_set(uint32_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSurface(); + if (el != nullptr) + { + el->SetSurfaceStyle(value); + } + } + uint8_t grassLength_get() { auto el = _element->AsSurface(); @@ -160,13 +178,14 @@ namespace OpenRCT2::Scripting static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScTileElement::type_get, &ScTileElement::type_set, "type"); - dukglue_register_property(ctx, &ScTileElement::baseHeight_get, &ScTileElement::baseHeight_set, "baseHeight"); - dukglue_register_property( - ctx, &ScTileElement::clearanceHeight_get, &ScTileElement::clearanceHeight_set, "clearanceHeight"); + dukglue_register_property(ctx, &ScTileElement::baseZ_get, &ScTileElement::baseZ_set, "baseZ"); + dukglue_register_property(ctx, &ScTileElement::clearanceZ_get, &ScTileElement::clearanceZ_set, "clearanceZ"); - dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + dukglue_register_property(ctx, &ScTileElement::surfaceStyle_get, &ScTileElement::surfaceStyle_set, "surfaceStyle"); dukglue_register_property(ctx, &ScTileElement::grassLength_get, &ScTileElement::grassLength_set, "grassLength"); dukglue_register_property(ctx, &ScTileElement::hasOwnership_get, nullptr, "hasOwnership"); + + dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); } }; @@ -230,6 +249,7 @@ namespace OpenRCT2::Scripting void data_set(DukValue value) { + ThrowIfGameStateNotMutable(); auto ctx = value.context(); value.push(); if (duk_is_buffer_data(ctx, -1)) @@ -288,6 +308,7 @@ namespace OpenRCT2::Scripting std::shared_ptr insertElement(size_t index) { + ThrowIfGameStateNotMutable(); auto first = GetFirstElement(); auto origNumElements = GetNumElements(first); if (index >= 0 && index <= origNumElements) @@ -335,6 +356,7 @@ namespace OpenRCT2::Scripting void removeElement(size_t index) { + ThrowIfGameStateNotMutable(); auto first = GetFirstElement(); if (index < GetNumElements(first)) { diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 0dc5514ff9..6ce31a317a 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -356,7 +356,7 @@ DukContext::~DukContext() ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) : _console(console) , _env(env) - , _hookEngine(_execInfo) + , _hookEngine(*this, _execInfo) { } @@ -652,6 +652,34 @@ std::future ScriptEngine::Eval(const std::string& s) return future; } +bool ScriptEngine::ExecutePluginCall( + const std::shared_ptr& plugin, const DukValue& func, const std::vector& args, bool isGameStateMutable) +{ + if (func.is_function()) + { + ScriptExecutionInfo::PluginScope scope(_execInfo, plugin, isGameStateMutable); + func.push(); + for (const auto& arg : args) + { + arg.push(); + } + auto result = duk_pcall(_context, static_cast(args.size())); + if (result == DUK_EXEC_SUCCESS) + { + // TODO allow result to be returned as a DukValue + duk_pop(_context); + return true; + } + else + { + auto message = duk_safe_to_string(_context, -1); + LogPluginInfo(plugin, message); + duk_pop(_context); + } + } + return false; +} + void ScriptEngine::LogPluginInfo(const std::shared_ptr& plugin, const std::string_view& message) { const auto& pluginName = plugin->GetMetadata().Name; diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 705db8a2ef..cf7f62acfa 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -142,6 +142,9 @@ namespace OpenRCT2::Scripting void UnloadPlugins(); void Update(); std::future Eval(const std::string& s); + bool ExecutePluginCall( + const std::shared_ptr& plugin, const DukValue& func, const std::vector& args, + bool isGameStateMutable); void LogPluginInfo(const std::shared_ptr& plugin, const std::string_view& message); From 63b10166ac366d631ce0f0f72cfc94ab04cbae4b Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 29 Feb 2020 21:31:22 +0000 Subject: [PATCH 099/159] Add more surface element APIs --- src/openrct2/scripting/ScTile.hpp | 88 ++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 2 deletions(-) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 1b56d4dca7..96db468a8d 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -111,7 +111,7 @@ namespace OpenRCT2::Scripting } } - auto baseZ_get() const + uint8_t baseZ_get() const { return _element->base_height; } @@ -121,7 +121,7 @@ namespace OpenRCT2::Scripting _element->base_height = newBaseHeight; } - auto clearanceZ_get() const + uint8_t clearanceZ_get() const { return _element->clearance_height; } @@ -131,6 +131,23 @@ namespace OpenRCT2::Scripting _element->clearance_height = newClearanceHeight; } + int32_t waterHeight_get() const + { + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetWaterHeight(); + return 0; + } + void waterHeight_set(int32_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSurface(); + if (el != nullptr) + { + el->SetWaterHeight(value); + } + } + uint32_t surfaceStyle_get() { auto el = _element->AsSurface(); @@ -148,6 +165,23 @@ namespace OpenRCT2::Scripting } } + uint32_t edgeStyle_get() + { + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetEdgeStyle(); + return 0; + } + void edgeStyle_set(uint32_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSurface(); + if (el != nullptr) + { + el->SetEdgeStyle(value); + } + } + uint8_t grassLength_get() { auto el = _element->AsSurface(); @@ -174,6 +208,51 @@ namespace OpenRCT2::Scripting return false; } + bool hasConstructionRights_get() + { + auto el = _element->AsSurface(); + if (el != nullptr) + { + auto ownership = el->GetOwnership(); + return (ownership & OWNERSHIP_OWNED) || (ownership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED); + } + return false; + } + + uint8_t ownership_get() + { + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetOwnership(); + return 0; + } + void ownership_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSurface(); + if (el != nullptr) + { + el->SetOwnership(value); + } + } + + uint8_t parkFences_get() + { + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetParkFences(); + return 0; + } + void parkFences_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSurface(); + if (el != nullptr) + { + el->SetParkFences(value); + } + } + public: static void Register(duk_context* ctx) { @@ -181,9 +260,14 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScTileElement::baseZ_get, &ScTileElement::baseZ_set, "baseZ"); dukglue_register_property(ctx, &ScTileElement::clearanceZ_get, &ScTileElement::clearanceZ_set, "clearanceZ"); + dukglue_register_property(ctx, &ScTileElement::waterHeight_get, &ScTileElement::waterHeight_set, "waterHeight"); dukglue_register_property(ctx, &ScTileElement::surfaceStyle_get, &ScTileElement::surfaceStyle_set, "surfaceStyle"); + dukglue_register_property(ctx, &ScTileElement::edgeStyle_get, &ScTileElement::edgeStyle_set, "edgeStyle"); dukglue_register_property(ctx, &ScTileElement::grassLength_get, &ScTileElement::grassLength_set, "grassLength"); dukglue_register_property(ctx, &ScTileElement::hasOwnership_get, nullptr, "hasOwnership"); + dukglue_register_property(ctx, &ScTileElement::hasConstructionRights_get, nullptr, "hasConstructionRights"); + dukglue_register_property(ctx, &ScTileElement::ownership_get, &ScTileElement::ownership_set, "ownership"); + dukglue_register_property(ctx, &ScTileElement::parkFences_get, &ScTileElement::parkFences_set, "parkFences"); dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); } From 82639bae1befa8a453905ff117b7e021fc9c551e Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 29 Feb 2020 21:44:40 +0000 Subject: [PATCH 100/159] Implement more tile element APIs --- distribution/openrct2.d.ts | 30 ++++---- src/openrct2/scripting/ScTile.hpp | 109 ++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 18 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index c24f568639..ec918ddc4c 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -159,30 +159,17 @@ declare global { clearanceZ: number; } - // interface TileElement extends BaseTileElement { - // /** - // * Gets the element as a specific type to access its properties - // */ - // asSurface(): SurfaceElement | null; - // asFootpath(): FootpathElement | null; - // asTrack(): TrackElement | null; - // asSmallScenery(): SmallSceneryElement | null; - // asEntrance(): EntranceElement | null; - // asWall(): WallElement | null; - // asLargeScenery(): LargeSceneryElement | null; - // asBanner(): BannerElement | null; - // asCorruptElement(): CorruptElement | null; - // } - - type TileElement = SurfaceElement | FootpathElement | TrackElement; - interface SurfaceElement extends BaseTileElement { slope: number; - terrain: number; + surfaceStyle: number; + edgeStyle: number; waterHeight: number; grassLength: number; ownership: number; parkFences: number; + + readonly hasOwnership: boolean; + readonly hasConstructionRights: boolean; } interface FootpathAdditionStatus extends BaseTileElement { @@ -221,6 +208,11 @@ declare global { } interface TrackElement extends BaseTileElement { + trackType: number; + sequence: number; + ride: number; + station: number; + hasChainLift: boolean; } interface SmallSceneryElement extends BaseTileElement { @@ -241,6 +233,8 @@ declare global { interface CorruptElement extends BaseTileElement { } + type TileElement = SurfaceElement | FootpathElement | TrackElement; + /** * Represents a tile containing tile elements on the map. This is a fixed handle * for a given tile position. It can be re-used safely between game ticks. diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 96db468a8d..c367232556 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -131,6 +131,23 @@ namespace OpenRCT2::Scripting _element->clearance_height = newClearanceHeight; } + uint8_t slope_get() const + { + auto el = _element->AsSurface(); + if (el != nullptr) + return el->GetSlope(); + return 0; + } + void slope_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSurface(); + if (el != nullptr) + { + el->SetSlope(value); + } + } + int32_t waterHeight_get() const { auto el = _element->AsSurface(); @@ -253,6 +270,91 @@ namespace OpenRCT2::Scripting } } + uint8_t trackType_get() + { + auto el = _element->AsTrack(); + if (el != nullptr) + return el->GetTrackType(); + return 0; + } + void trackType_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsTrack(); + if (el != nullptr) + { + el->SetTrackType(value); + } + } + + uint8_t sequence_get() + { + auto el = _element->AsTrack(); + if (el != nullptr) + return el->GetSequenceIndex(); + return 0; + } + void sequence_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsTrack(); + if (el != nullptr) + { + el->SetSequenceIndex(value); + } + } + + uint8_t ride_get() + { + auto el = _element->AsTrack(); + if (el != nullptr) + return el->GetRideIndex(); + return 0; + } + void ride_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsTrack(); + if (el != nullptr) + { + el->SetRideIndex(value); + } + } + + uint8_t station_get() + { + auto el = _element->AsTrack(); + if (el != nullptr) + return el->GetStationIndex(); + return 0; + } + void station_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsTrack(); + if (el != nullptr) + { + el->SetStationIndex(value); + } + } + + bool hasChainLift_get() + { + auto el = _element->AsTrack(); + if (el != nullptr) + return el->HasChain(); + return 0; + } + void hasChainLift_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsTrack(); + if (el != nullptr) + { + el->SetHasChain(value); + } + } + public: static void Register(duk_context* ctx) { @@ -260,6 +362,7 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScTileElement::baseZ_get, &ScTileElement::baseZ_set, "baseZ"); dukglue_register_property(ctx, &ScTileElement::clearanceZ_get, &ScTileElement::clearanceZ_set, "clearanceZ"); + dukglue_register_property(ctx, &ScTileElement::slope_get, &ScTileElement::slope_set, "slope"); dukglue_register_property(ctx, &ScTileElement::waterHeight_get, &ScTileElement::waterHeight_set, "waterHeight"); dukglue_register_property(ctx, &ScTileElement::surfaceStyle_get, &ScTileElement::surfaceStyle_set, "surfaceStyle"); dukglue_register_property(ctx, &ScTileElement::edgeStyle_get, &ScTileElement::edgeStyle_set, "edgeStyle"); @@ -269,6 +372,12 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScTileElement::ownership_get, &ScTileElement::ownership_set, "ownership"); dukglue_register_property(ctx, &ScTileElement::parkFences_get, &ScTileElement::parkFences_set, "parkFences"); + dukglue_register_property(ctx, &ScTileElement::trackType_get, &ScTileElement::trackType_set, "trackType"); + dukglue_register_property(ctx, &ScTileElement::sequence_get, &ScTileElement::sequence_set, "sequence"); + dukglue_register_property(ctx, &ScTileElement::ride_get, &ScTileElement::ride_set, "ride"); + dukglue_register_property(ctx, &ScTileElement::station_get, &ScTileElement::station_set, "station"); + dukglue_register_property(ctx, &ScTileElement::hasChainLift_get, &ScTileElement::hasChainLift_set, "isChainLift"); + dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); } }; From 4e12c9541e830f03f23fc5c33bebff90d44f3e9c Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 29 Feb 2020 22:08:09 +0000 Subject: [PATCH 101/159] Implement more tile element APIs --- distribution/openrct2.d.ts | 11 ++ src/openrct2/scripting/ScTile.hpp | 287 +++++++++++++++++++++++++++--- 2 files changed, 277 insertions(+), 21 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index ec918ddc4c..b7b37839ed 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -216,15 +216,26 @@ declare global { } interface SmallSceneryElement extends BaseTileElement { + object: number; + primaryColour: number; + secondaryColour: number; } interface EntranceElement extends BaseTileElement { + object: number; + sequence: number; + ride: number; + station: number; } interface WallElement extends BaseTileElement { + object: number; } interface LargeSceneryElement extends BaseTileElement { + object: number; + primaryColour: number; + secondaryColour: number; } interface BannerElement extends BaseTileElement { diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index c367232556..07c9676de8 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -289,52 +289,106 @@ namespace OpenRCT2::Scripting uint8_t sequence_get() { - auto el = _element->AsTrack(); - if (el != nullptr) - return el->GetSequenceIndex(); + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_TRACK: + { + auto el = _element->AsTrack(); + return el->GetSequenceIndex(); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + return el->GetSequenceIndex(); + } + } return 0; } void sequence_set(uint8_t value) { ThrowIfGameStateNotMutable(); - auto el = _element->AsTrack(); - if (el != nullptr) + switch (_element->GetType()) { - el->SetSequenceIndex(value); + case TILE_ELEMENT_TYPE_TRACK: + { + auto el = _element->AsTrack(); + el->SetSequenceIndex(value); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + el->SetSequenceIndex(value); + } } } uint8_t ride_get() { - auto el = _element->AsTrack(); - if (el != nullptr) - return el->GetRideIndex(); + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_TRACK: + { + auto el = _element->AsTrack(); + return el->GetRideIndex(); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + return el->GetRideIndex(); + } + } return 0; } void ride_set(uint8_t value) { ThrowIfGameStateNotMutable(); - auto el = _element->AsTrack(); - if (el != nullptr) + switch (_element->GetType()) { - el->SetRideIndex(value); + case TILE_ELEMENT_TYPE_TRACK: + { + auto el = _element->AsTrack(); + el->SetRideIndex(value); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + el->SetRideIndex(value); + } } } uint8_t station_get() { - auto el = _element->AsTrack(); - if (el != nullptr) - return el->GetStationIndex(); + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_TRACK: + { + auto el = _element->AsTrack(); + return el->GetStationIndex(); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + return el->GetStationIndex(); + } + } return 0; } void station_set(uint8_t value) { ThrowIfGameStateNotMutable(); - auto el = _element->AsTrack(); - if (el != nullptr) + switch (_element->GetType()) { - el->SetStationIndex(value); + case TILE_ELEMENT_TYPE_TRACK: + { + auto el = _element->AsTrack(); + el->SetStationIndex(value); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + el->SetStationIndex(value); + } } } @@ -355,13 +409,198 @@ namespace OpenRCT2::Scripting } } + uint32_t object_get() + { + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_PATH: + { + auto el = _element->AsPath(); + return el->GetPathEntryIndex(); + } + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + { + auto el = _element->AsSmallScenery(); + return el->GetEntryIndex(); + } + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + { + auto el = _element->AsLargeScenery(); + return el->GetEntryIndex(); + } + case TILE_ELEMENT_TYPE_WALL: + { + auto el = _element->AsWall(); + return el->GetEntryIndex(); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + return el->GetEntranceType(); + } + } + return 0; + } + void object_set(uint32_t value) + { + ThrowIfGameStateNotMutable(); + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_PATH: + { + auto el = _element->AsPath(); + el->SetPathEntryIndex(value & 0xFF); + } + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + { + auto el = _element->AsSmallScenery(); + el->SetEntryIndex(value & 0xFF); + } + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + { + auto el = _element->AsLargeScenery(); + el->SetEntryIndex(value); + } + case TILE_ELEMENT_TYPE_WALL: + { + auto el = _element->AsWall(); + el->SetEntryIndex(value & 0xFFFF); + } + case TILE_ELEMENT_TYPE_ENTRANCE: + { + auto el = _element->AsEntrance(); + el->SetEntranceType(value & 0xFF); + } + } + } + + uint8_t age_get() + { + auto el = _element->AsSmallScenery(); + if (el != nullptr) + return el->GetAge(); + return 0; + } + void age_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsSmallScenery(); + if (el != nullptr) + { + el->SetAge(value); + } + } + + uint8_t primaryColour_get() + { + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + { + auto el = _element->AsSmallScenery(); + return el->GetPrimaryColour(); + } + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + { + auto el = _element->AsLargeScenery(); + return el->GetPrimaryColour(); + } + } + return 0; + } + void primaryColour_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + { + auto el = _element->AsSmallScenery(); + el->SetPrimaryColour(value); + } + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + { + auto el = _element->AsLargeScenery(); + el->SetPrimaryColour(value); + } + } + } + + uint8_t secondaryColour_get() + { + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + { + auto el = _element->AsSmallScenery(); + return el->GetSecondaryColour(); + } + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + { + auto el = _element->AsLargeScenery(); + return el->GetSecondaryColour(); + } + } + return 0; + } + void secondaryColour_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + switch (_element->GetType()) + { + case TILE_ELEMENT_TYPE_SMALL_SCENERY: + { + auto el = _element->AsSmallScenery(); + el->SetSecondaryColour(value); + } + case TILE_ELEMENT_TYPE_LARGE_SCENERY: + { + auto el = _element->AsLargeScenery(); + el->SetSecondaryColour(value); + } + } + } + + uint8_t footpathObject_get() + { + auto el = _element->AsEntrance(); + if (el != nullptr) + return el->GetPathType(); + return 0; + } + void footpathObject_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsEntrance(); + if (el != nullptr) + { + el->SetPathType(value); + } + } + public: static void Register(duk_context* ctx) { + // All dukglue_register_property(ctx, &ScTileElement::type_get, &ScTileElement::type_set, "type"); dukglue_register_property(ctx, &ScTileElement::baseZ_get, &ScTileElement::baseZ_set, "baseZ"); dukglue_register_property(ctx, &ScTileElement::clearanceZ_get, &ScTileElement::clearanceZ_set, "clearanceZ"); + // Some + dukglue_register_property(ctx, &ScTileElement::object_get, &ScTileElement::object_set, "object"); + + // Small Scenery | Large Scenery + dukglue_register_property( + ctx, &ScTileElement::primaryColour_get, &ScTileElement::primaryColour_set, "primaryColour"); + dukglue_register_property( + ctx, &ScTileElement::secondaryColour_get, &ScTileElement::secondaryColour_set, "secondaryColour"); + + // Ride | entrance + dukglue_register_property(ctx, &ScTileElement::sequence_get, &ScTileElement::sequence_set, "sequence"); + dukglue_register_property(ctx, &ScTileElement::ride_get, &ScTileElement::ride_set, "ride"); + dukglue_register_property(ctx, &ScTileElement::station_get, &ScTileElement::station_set, "station"); + + // Surface only dukglue_register_property(ctx, &ScTileElement::slope_get, &ScTileElement::slope_set, "slope"); dukglue_register_property(ctx, &ScTileElement::waterHeight_get, &ScTileElement::waterHeight_set, "waterHeight"); dukglue_register_property(ctx, &ScTileElement::surfaceStyle_get, &ScTileElement::surfaceStyle_set, "surfaceStyle"); @@ -372,13 +611,19 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScTileElement::ownership_get, &ScTileElement::ownership_set, "ownership"); dukglue_register_property(ctx, &ScTileElement::parkFences_get, &ScTileElement::parkFences_set, "parkFences"); + // Track only dukglue_register_property(ctx, &ScTileElement::trackType_get, &ScTileElement::trackType_set, "trackType"); - dukglue_register_property(ctx, &ScTileElement::sequence_get, &ScTileElement::sequence_set, "sequence"); - dukglue_register_property(ctx, &ScTileElement::ride_get, &ScTileElement::ride_set, "ride"); - dukglue_register_property(ctx, &ScTileElement::station_get, &ScTileElement::station_set, "station"); dukglue_register_property(ctx, &ScTileElement::hasChainLift_get, &ScTileElement::hasChainLift_set, "isChainLift"); + // Small Scenery only + dukglue_register_property(ctx, &ScTileElement::age_get, &ScTileElement::age_set, "age"); + + // Footpath only dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + + // Entrance only + dukglue_register_property( + ctx, &ScTileElement::footpathObject_get, &ScTileElement::footpathObject_set, "footpathObject"); } }; From 971c6e201d3c91205693269963c402ff46493f4b Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 1 Mar 2020 12:44:36 +0000 Subject: [PATCH 102/159] Improve some of the map APIs --- distribution/openrct2.d.ts | 85 ++++++++++++++++++++++++++--- src/openrct2/scripting/ScMap.hpp | 77 +++++++++++++++++++++++--- src/openrct2/scripting/ScPark.hpp | 3 +- src/openrct2/scripting/ScRide.hpp | 77 +++++++++++++++++++------- src/openrct2/scripting/ScThing.hpp | 86 ++++++++++++++++++++++++------ 5 files changed, 278 insertions(+), 50 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index b7b37839ed..3a8f60f3d3 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -151,7 +151,7 @@ declare global { } type TileElementType = - "surface" | "footpath" | "track" | "small_scenery" | "entrance" | "large_scenery" | "banner"; + "surface" | "footpath" | "track" | "small_scenery" | "wall" | "entrance" | "large_scenery" | "banner"; interface BaseTileElement { type: TileElementType; @@ -276,52 +276,125 @@ declare global { removeElement(index: number): void; } + /** + * Represents the definition of a loaded object (.DAT or .json) such a ride type or scenery item. + */ interface Object { + /** + * The unique name identifier of the object, e.g. "BURGB ". + * This may have trailing spaces if the name is shorter than 8 characters. + */ readonly identifier: string; + /** + * The name in the user's current language. + */ readonly name: string; } + /** + * Represents the object definition of a ride or stall. + */ interface RideObject extends Object { + /** + * The description of the ride / stall in the player's current language. + */ readonly description: string; + /** + * A text description describing the capacity of the ride in the player's current language. + */ readonly capacity: string; } + /** + * Represents a ride or stall within the park. + */ interface Ride { + /** + * The object metadata for this ride. + */ readonly object: RideObject; + /** + * The unique ID / index of the ride. + */ readonly id: number; + /** + * The type of the ride represented as the internal built-in ride type ID. + */ type: number; + /** + * The generated or custom name of the ride. + */ name: string; + /** + * The excitement metric of the ride represented as a 2 decimal point fixed integer. + * For example, `652` equates to `6.52`. + */ excitement: number; + /** + * The intensity metric of the ride represented as a 2 decimal point fixed integer. + * For example, `652` equates to `6.52`. + */ intensity: number; + /** + * The nausea metric of the ride represented as a 2 decimal point fixed integer. + * For example, `652` equates to `6.52`. + */ nausea: number; + /** + * The total number of customers the ride has served since it was built. + */ totalCustomers: number; } type ThingType = "car" | "duck" | "peep"; + /** + * Represents an object "thing" on the map that can typically moves and has a sub-tile coordinate. + */ interface Thing { + /** + * The type of thing, e.g. car, duck, litter, or peep. + */ readonly type: ThingType; + /** + * The x-coordinate of the thing in game units. + */ x: number; + /** + * The y-coordinate of the thing in game units. + */ y: number; + /** + * The z-coordinate of the thing in game units. + */ z: number; - - asPeep(): Thing | null; } + /** + * Represents a guest or staff member. + */ interface Peep extends Thing { + /** + * Colour of the peep's t-shirt. + */ tshirt: number; + /** + * Colour of the peep's trousers. + */ trousers: number; } interface GameMap { - readonly size: { x: number; y: number; }; - readonly rides: number; - readonly things: number; + readonly size: Coord2; + readonly numRides: number; + readonly numThings: number; + readonly rides: Ride[]; getRide(id: number): Ride; getTile(x: number, y: number): Tile; getThing(id: number): Thing; + getAllThings(type: ThingType); } type ParkMessageType = diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 191821d416..94badbfb98 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -43,16 +43,27 @@ namespace OpenRCT2::Scripting return DukValue::take_from_stack(ctx); } - int32_t rides_get() + int32_t numRides_get() { return static_cast(GetRideManager().size()); } - int32_t things_get() + int32_t numThings_get() { return MAX_SPRITES; } + std::vector> rides_get() + { + std::vector> result; + auto rideManager = GetRideManager(); + for (const auto& ride : rideManager) + { + result.push_back(std::make_shared(ride.id)); + } + return result; + } + std::shared_ptr getRide(int32_t id) { auto rideManager = GetRideManager(); @@ -61,10 +72,10 @@ namespace OpenRCT2::Scripting auto ride = rideManager[static_cast(id)]; if (ride != nullptr) { - return std::make_shared(ride); + return std::make_shared(ride->id); } } - return nullptr; + return {}; } std::shared_ptr getTile(int32_t x, int32_t y) @@ -77,23 +88,75 @@ namespace OpenRCT2::Scripting { if (id >= 0 && id < MAX_SPRITES) { - auto sprite = get_sprite(id); + auto spriteId = static_cast(id); + auto sprite = get_sprite(spriteId); if (sprite != nullptr && sprite->generic.sprite_identifier != SPRITE_IDENTIFIER_NULL) { - return std::make_shared(sprite); + return std::make_shared(spriteId); } } return nullptr; } + std::vector> getAllThings(const std::string& type) + { + SPRITE_LIST targetList{}; + uint8_t targetType{}; + if (type == "balloon") + { + targetList = SPRITE_LIST_MISC; + targetType = SPRITE_MISC_BALLOON; + } + if (type == "car") + { + targetList = SPRITE_LIST_VEHICLE; + } + else if (type == "litter") + { + targetList = SPRITE_LIST_LITTER; + } + else if (type == "duck") + { + targetList = SPRITE_LIST_MISC; + targetType = SPRITE_MISC_DUCK; + } + else if (type == "peep") + { + targetList = SPRITE_LIST_PEEP; + } + else + { + duk_error(_context, DUK_ERR_ERROR, "Invalid thing type."); + } + + std::vector> result; + auto spriteId = gSpriteListHead[targetList]; + while (spriteId != SPRITE_INDEX_NULL) + { + auto sprite = get_sprite(spriteId); + if (sprite != nullptr) + { + // Only the misc list checks the type property + if (targetList != SPRITE_LIST_MISC || sprite->generic.type == targetType) + { + result.push_back(std::make_shared(spriteId)); + } + spriteId = sprite->generic.next; + } + } + return result; + } + static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScMap::size_get, nullptr, "size"); + dukglue_register_property(ctx, &ScMap::numRides_get, nullptr, "numRides"); + dukglue_register_property(ctx, &ScMap::numThings_get, nullptr, "numThings"); dukglue_register_property(ctx, &ScMap::rides_get, nullptr, "rides"); - dukglue_register_property(ctx, &ScMap::things_get, nullptr, "things"); dukglue_register_method(ctx, &ScMap::getRide, "getRide"); dukglue_register_method(ctx, &ScMap::getTile, "getTile"); dukglue_register_method(ctx, &ScMap::getThing, "getThing"); + dukglue_register_method(ctx, &ScMap::getAllThings, "getAllThings"); } }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 7b908b8cd4..2226421b73 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -93,8 +93,9 @@ namespace OpenRCT2::Scripting } news_item_add_to_queue_raw(type, text.c_str(), static_cast(-1)); } - catch (const std::exception&) + catch (const DukException&) { + duk_error(message.context(), DUK_ERR_ERROR, "Invalid message argument."); } } diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index 71fc3c8ad1..c5d1d83b0b 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -22,12 +22,12 @@ namespace OpenRCT2::Scripting class ScRideObject { private: - rct_ride_entry* _entry; + rct_ride_entry* _entry{}; public: ScRideObject(rct_ride_entry* entry) + : _entry(entry) { - _entry = entry; } static void Register(duk_context* ctx) @@ -83,84 +83,121 @@ namespace OpenRCT2::Scripting class ScRide { private: - Ride* _ride; + ride_id_t _rideId = RIDE_ID_NULL; public: - ScRide(Ride* ride) - : _ride(ride) + ScRide(ride_id_t rideId) + : _rideId(rideId) { } + private: int32_t id_get() { - return _ride->id; + return _rideId; } std::shared_ptr object_get() { - auto rideEntry = _ride->GetRideEntry(); - if (rideEntry != nullptr) + auto ride = GetRide(); + if (ride != nullptr) { - return std::make_shared(rideEntry); + auto rideEntry = ride->GetRideEntry(); + if (rideEntry != nullptr) + { + return std::make_shared(rideEntry); + } } return nullptr; } int32_t type_get() { - return _ride->type; + auto ride = GetRide(); + return ride != nullptr ? ride->type : 0; } std::string name_get() { - return _ride->GetName(); + auto ride = GetRide(); + return ride != nullptr ? ride->GetName() : std::string(); } void name_set(std::string value) { ThrowIfGameStateNotMutable(); - _ride->custom_name = value; + auto ride = GetRide(); + if (ride != nullptr) + { + ride->custom_name = value; + } } int32_t excitement_get() { - return _ride->excitement; + auto ride = GetRide(); + return ride != nullptr ? ride->excitement : 0; } void excitement_set(int32_t value) { ThrowIfGameStateNotMutable(); - _ride->excitement = value; + auto ride = GetRide(); + if (ride != nullptr) + { + ride->excitement = value; + } } int32_t intensity_get() { - return _ride->intensity; + auto ride = GetRide(); + return ride != nullptr ? ride->intensity : 0; } void intensity_set(int32_t value) { ThrowIfGameStateNotMutable(); - _ride->intensity = value; + auto ride = GetRide(); + if (ride != nullptr) + { + ride->intensity = value; + } } int32_t nausea_get() { - return _ride->nausea; + auto ride = GetRide(); + return ride != nullptr ? ride->nausea : 0; } void nausea_set(int32_t value) { ThrowIfGameStateNotMutable(); - _ride->nausea = value; + auto ride = GetRide(); + if (ride != nullptr) + { + ride->nausea = value; + } } int32_t totalCustomers_get() { - return _ride->total_customers; + auto ride = GetRide(); + return ride != nullptr ? ride->total_customers : 0; } void totalCustomers_set(int32_t value) { ThrowIfGameStateNotMutable(); - _ride->total_customers = value; + auto ride = GetRide(); + if (ride != nullptr) + { + ride->total_customers = value; + } } + Ride* GetRide() + { + return get_ride(_rideId); + } + + public: static void Register(duk_context* ctx) { dukglue_register_property(ctx, &ScRide::id_get, nullptr, "id"); diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index d741a0e811..73990147b9 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -21,19 +21,38 @@ namespace OpenRCT2::Scripting class ScThing { private: - rct_sprite* _sprite; + uint16_t _id = SPRITE_INDEX_NULL; public: - ScThing(rct_sprite* sprite) - : _sprite(sprite) + ScThing(uint16_t id) + : _id(id) { } + private: std::string type_get() { - if (_sprite->generic.sprite_identifier == SPRITE_IDENTIFIER_PEEP) + auto thing = GetThing(); + if (thing != nullptr) { - return "peep"; + switch (thing->sprite_identifier) + { + case SPRITE_IDENTIFIER_VEHICLE: + return "car"; + case SPRITE_IDENTIFIER_PEEP: + return "peep"; + case SPRITE_IDENTIFIER_MISC: + switch (thing->type) + { + case SPRITE_MISC_BALLOON: + return "balloon"; + case SPRITE_MISC_DUCK: + return "duck"; + } + break; + case SPRITE_IDENTIFIER_LITTER: + return "litter"; + } } return "unknown"; } @@ -41,58 +60,93 @@ namespace OpenRCT2::Scripting // x getter and setter int32_t x_get() { - return _sprite->generic.x; + auto thing = GetThing(); + return thing != nullptr ? thing->x : 0; } void x_set(int32_t value) { ThrowIfGameStateNotMutable(); - sprite_move(value, _sprite->generic.y, _sprite->generic.z, &_sprite->generic); + auto thing = GetThing(); + if (thing != nullptr) + { + sprite_move(value, thing->y, thing->z, thing); + } } // y getter and setter int32_t y_get() { - return _sprite->generic.y; + auto thing = GetThing(); + return thing != nullptr ? thing->y : 0; } void y_set(int32_t value) { ThrowIfGameStateNotMutable(); - sprite_move(_sprite->generic.x, value, _sprite->generic.z, &_sprite->generic); + auto thing = GetThing(); + if (thing != nullptr) + { + sprite_move(thing->x, value, thing->z, thing); + } } // z getter and setter int16_t z_get() { - return _sprite->generic.z; + auto thing = GetThing(); + return thing != nullptr ? thing->z : 0; } void z_set(int16_t value) { ThrowIfGameStateNotMutable(); - sprite_move(_sprite->generic.x, _sprite->generic.y, value, &_sprite->generic); + auto thing = GetThing(); + if (thing != nullptr) + { + sprite_move(thing->x, thing->y, value, thing); + } } uint8_t tshirtColour_get() { - return _sprite->peep.tshirt_colour; + auto peep = GetPeep(); + return peep != nullptr ? peep->tshirt_colour : 0; } void tshirtColour_set(uint8_t value) { ThrowIfGameStateNotMutable(); - _sprite->peep.tshirt_colour = value; + auto peep = GetPeep(); + if (peep != nullptr) + { + peep->tshirt_colour = value; + } } uint8_t trousersColour_get() { - return _sprite->peep.trousers_colour; + auto peep = GetPeep(); + return peep != nullptr ? peep->trousers_colour : 0; } void trousersColour_set(uint8_t value) { ThrowIfGameStateNotMutable(); - _sprite->peep.trousers_colour = value; + auto peep = GetPeep(); + if (peep != nullptr) + { + peep->trousers_colour = value; + } } + SpriteBase* GetThing() + { + return &get_sprite(_id)->generic; + } + + Peep* GetPeep() + { + return get_sprite(_id)->AsPeep(); + } + + public: static void Register(duk_context* ctx) { - dukglue_register_constructor(ctx, "Thing"); dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); dukglue_register_property(ctx, &ScThing::x_get, &ScThing::x_set, "x"); dukglue_register_property(ctx, &ScThing::y_get, &ScThing::y_set, "y"); From f8394953aa9037d9bafba7aa957e11c901d8fcb5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 1 Mar 2020 13:22:17 +0000 Subject: [PATCH 103/159] Get thing inhertiance working --- src/openrct2/scripting/Duktape.hpp | 6 ++++ src/openrct2/scripting/ScMap.hpp | 38 ++++++++++++++++++++--- src/openrct2/scripting/ScThing.hpp | 41 +++++++++++++++++-------- src/openrct2/scripting/ScriptEngine.cpp | 1 + 4 files changed, 69 insertions(+), 17 deletions(-) diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 2c150d9d5a..280f5293fe 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -14,4 +14,10 @@ # include # include +template DukValue GetObjectAsDukValue(duk_context* ctx, const std::shared_ptr& value) +{ + dukglue::types::DukType>::template push(ctx, value); + return DukValue::take_from_stack(ctx); +} + #endif diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 94badbfb98..66a9a5ad84 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -98,7 +98,7 @@ namespace OpenRCT2::Scripting return nullptr; } - std::vector> getAllThings(const std::string& type) + std::vector getAllThings(const std::string& type) { SPRITE_LIST targetList{}; uint8_t targetType{}; @@ -109,7 +109,7 @@ namespace OpenRCT2::Scripting } if (type == "car") { - targetList = SPRITE_LIST_VEHICLE; + targetList = SPRITE_LIST_VEHICLE_HEAD; } else if (type == "litter") { @@ -129,17 +129,45 @@ namespace OpenRCT2::Scripting duk_error(_context, DUK_ERR_ERROR, "Invalid thing type."); } - std::vector> result; + std::vector result; auto spriteId = gSpriteListHead[targetList]; while (spriteId != SPRITE_INDEX_NULL) { auto sprite = get_sprite(spriteId); - if (sprite != nullptr) + if (sprite == nullptr) + { + break; + } + else { // Only the misc list checks the type property if (targetList != SPRITE_LIST_MISC || sprite->generic.type == targetType) { - result.push_back(std::make_shared(spriteId)); + if (targetList == SPRITE_LIST_PEEP) + { + result.push_back(GetObjectAsDukValue(_context, std::make_shared(spriteId))); + } + else if (targetList == SPRITE_LIST_VEHICLE_HEAD) + { + auto carId = spriteId; + while (carId != SPRITE_INDEX_NULL) + { + auto car = get_sprite(carId); + if (car == nullptr) + { + break; + } + else + { + result.push_back(GetObjectAsDukValue(_context, std::make_shared(carId))); + carId = car->vehicle.next_vehicle_on_train; + } + } + } + else + { + result.push_back(GetObjectAsDukValue(_context, std::make_shared(spriteId))); + } } spriteId = sprite->generic.next; } diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScThing.hpp index 73990147b9..5320af6825 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScThing.hpp @@ -20,7 +20,7 @@ namespace OpenRCT2::Scripting { class ScThing { - private: + protected: uint16_t _id = SPRITE_INDEX_NULL; public: @@ -105,6 +105,30 @@ namespace OpenRCT2::Scripting } } + SpriteBase* GetThing() + { + return &get_sprite(_id)->generic; + } + + public: + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScThing::x_get, &ScThing::x_set, "x"); + dukglue_register_property(ctx, &ScThing::y_get, &ScThing::y_set, "y"); + dukglue_register_property(ctx, &ScThing::z_get, &ScThing::z_set, "z"); + } + }; + + class ScPeep : public ScThing + { + public: + ScPeep(uint16_t id) + : ScThing(id) + { + } + + private: uint8_t tshirtColour_get() { auto peep = GetPeep(); @@ -134,11 +158,6 @@ namespace OpenRCT2::Scripting } } - SpriteBase* GetThing() - { - return &get_sprite(_id)->generic; - } - Peep* GetPeep() { return get_sprite(_id)->AsPeep(); @@ -147,14 +166,12 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { - dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); - dukglue_register_property(ctx, &ScThing::x_get, &ScThing::x_set, "x"); - dukglue_register_property(ctx, &ScThing::y_get, &ScThing::y_set, "y"); - dukglue_register_property(ctx, &ScThing::z_get, &ScThing::z_set, "z"); - dukglue_register_property(ctx, &ScThing::tshirtColour_get, &ScThing::tshirtColour_set, "tshirtColour"); - dukglue_register_property(ctx, &ScThing::trousersColour_get, &ScThing::trousersColour_set, "trousersColour"); + dukglue_set_base_class(ctx); + dukglue_register_property(ctx, &ScPeep::tshirtColour_get, &ScPeep::tshirtColour_set, "tshirtColour"); + dukglue_register_property(ctx, &ScPeep::trousersColour_get, &ScPeep::trousersColour_set, "trousersColour"); } }; + } // namespace OpenRCT2::Scripting #endif diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 6ce31a317a..f7d72ed029 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -377,6 +377,7 @@ void ScriptEngine::Initialise() ScTile::Register(ctx); ScTileElement::Register(ctx); ScThing::Register(ctx); + ScPeep::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); dukglue_register_global(ctx, std::make_shared(_execInfo, _hookEngine), "context"); From 07ed0f5c0ec2b498c6c527c532f63f2dc2ba2ebc Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 1 Mar 2020 15:52:18 +0000 Subject: [PATCH 104/159] Implement query and execute of game actions --- distribution/openrct2.d.ts | 24 +++++- src/openrct2/scripting/ScContext.hpp | 121 +++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 4 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 3a8f60f3d3..188c7d16a1 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -73,8 +73,8 @@ declare global { interface GameActionResult { error: string; - errorTitle: string; - errorMessage: string; + errorTitle?: string; + errorMessage?: string; position: Coord3; cost: number; expenditureType: ExpenditureType; @@ -125,6 +125,24 @@ declare global { */ registerGameAction(desc: GameActionDesc): void; + /** + * Query the result of running a game action. This allows you to check the outcome and validity of + * an action without actually executing it. + * @param action The name of the action. + * @param args The action parameters. + * @param callback The function to be called with the result of the action. + */ + queryAction(action: string, args: object, callback: (result: GameActionResult) => void): void; + + /** + * Executes a game action. In a network game, this will send a request to the server and wait + * for the server to reply. + * @param action The name of the action. + * @param args The action parameters. + * @param callback The function to be called with the result of the action. + */ + executeAction(action: string, args: object, callback: (result: GameActionResult) => void): void; + /** * Subscribes to the given hook. */ @@ -663,8 +681,6 @@ declare global { kickPlayer(index: number): void; sendMessage(message: string): void; sendMessage(message: string, players: number[]): void; - sendQueryAction(action: string, args: object, callback: (result: GameActionResult) => void): void; - sendExecuteAction(action: string, args: object, callback: (result: GameActionResult) => void): void; } interface GameDate { diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index e5528ac443..87ba11772c 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -11,6 +11,8 @@ #ifdef __ENABLE_SCRIPTING__ +# include "../actions/ParkSetNameAction.hpp" +# include "../actions/SmallSceneryPlaceAction.hpp" # include "Duktape.hpp" # include "HookEngine.h" # include "ScDisposable.hpp" @@ -34,6 +36,7 @@ namespace OpenRCT2::Scripting { } + private: void registerIntent(const DukValue& desc) { } @@ -61,10 +64,128 @@ namespace OpenRCT2::Scripting return std::make_shared([this, hookType, cookie]() { _hookEngine.Unsubscribe(hookType, cookie); }); } + void queryAction(const std::string& action, const DukValue& args, const DukValue& callback) + { + QueryOrExecuteAction(action, args, callback, false); + } + + void executeAction(const std::string& action, const DukValue& args, const DukValue& callback) + { + QueryOrExecuteAction(action, args, callback, true); + } + + void QueryOrExecuteAction(const std::string& actionid, const DukValue& args, const DukValue& callback, bool isExecute) + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto ctx = scriptEngine.GetContext(); + if (args.type() == DukValue::Type::OBJECT) + { + if (callback.is_function()) + { + try + { + auto action = CreateGameAction(actionid, args); + if (action != nullptr) + { + auto plugin = scriptEngine.GetExecInfo().GetCurrentPlugin(); + if (isExecute) + { + action->SetCallback( + [this, &plugin, &callback](const GameAction*, const GameActionResult* res) -> void { + HandleGameActionResult(plugin, *res, callback); + }); + GameActions::Execute(action.get()); + } + else + { + auto res = GameActions::Query(action.get()); + HandleGameActionResult(plugin, *res, callback); + } + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Unknown action."); + } + } + catch (DukException&) + { + duk_error(ctx, DUK_ERR_ERROR, "Invalid action parameters."); + } + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Callback was not a function."); + } + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Invalid action parameters."); + } + } + + std::unique_ptr CreateGameAction(const std::string& actionid, const DukValue& args) + { + if (actionid == "parksetname") + { + auto name = args["name"].as_string(); + return std::make_unique(name); + } + else if (actionid == "smallsceneryplace") + { + CoordsXYZD loc; + loc.x = args["x"].as_int(); + loc.y = args["y"].as_int(); + loc.z = args["z"].as_int(); + loc.direction = args["direction"].as_int(); + uint8_t quadrant = args["quadrant"].as_int(); + uint8_t sceneryType = args["object"].as_int(); + uint8_t primaryColour = args["primaryColour"].as_int(); + uint8_t secondaryColour = args["secondaryColour"].as_int(); + return std::make_unique(loc, quadrant, sceneryType, primaryColour, secondaryColour); + } + return {}; + } + + void HandleGameActionResult( + const std::shared_ptr& plugin, const GameActionResult& res, const DukValue& callback) + { + // Construct result object + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto ctx = scriptEngine.GetContext(); + auto objIdx = duk_push_object(ctx); + duk_push_int(ctx, static_cast(res.Error)); + duk_put_prop_string(ctx, objIdx, "error"); + + if (res.Error != GA_ERROR::OK) + { + auto title = format_string(res.ErrorTitle, nullptr); + duk_push_string(ctx, title.c_str()); + duk_put_prop_string(ctx, objIdx, "errorTitle"); + + auto message = format_string(res.ErrorMessage, res.ErrorMessageArgs.data()); + duk_push_string(ctx, message.c_str()); + duk_put_prop_string(ctx, objIdx, "errorMessage"); + } + + duk_push_int(ctx, static_cast(res.Cost)); + duk_put_prop_string(ctx, objIdx, "cost"); + + duk_push_int(ctx, static_cast(res.Expenditure)); + duk_put_prop_string(ctx, objIdx, "expenditureType"); + + auto args = DukValue::take_from_stack(ctx); + + // Call the plugin callback and pass the result object + scriptEngine.ExecutePluginCall(plugin, callback, { args }, false); + } + + public: static void Register(duk_context* ctx) { dukglue_register_method(ctx, &ScContext::registerIntent, "registerIntent"); dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); + dukglue_register_method(ctx, &ScContext::queryAction, "queryAction"); + dukglue_register_method(ctx, &ScContext::executeAction, "executeAction"); } }; } // namespace OpenRCT2::Scripting From 4e4379e6ef8f881893a7ed6cdece5bb30c8120e7 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 1 Mar 2020 21:56:49 +0000 Subject: [PATCH 105/159] Start work on custom game actions --- src/openrct2/Game.h | 1 + src/openrct2/actions/CustomAction.hpp | 56 +++++++++++++++++++ .../actions/GameActionRegistration.cpp | 4 ++ src/openrct2/network/Network.cpp | 13 +++-- src/openrct2/scripting/ScContext.hpp | 14 ++++- src/openrct2/scripting/ScriptEngine.cpp | 24 ++++++++ src/openrct2/scripting/ScriptEngine.h | 3 + 7 files changed, 108 insertions(+), 7 deletions(-) create mode 100644 src/openrct2/actions/CustomAction.hpp diff --git a/src/openrct2/Game.h b/src/openrct2/Game.h index a1167563f2..b29f5a77ff 100644 --- a/src/openrct2/Game.h +++ b/src/openrct2/Game.h @@ -98,6 +98,7 @@ enum GAME_COMMAND GAME_COMMAND_REMOVE_FOOTPATH_SCENERY, // GA GAME_COMMAND_GUEST_SET_FLAGS, // GA GAME_COMMAND_SET_DATE, // GA + GAME_COMMAND_CUSTOM, // GA GAME_COMMAND_COUNT, }; diff --git a/src/openrct2/actions/CustomAction.hpp b/src/openrct2/actions/CustomAction.hpp new file mode 100644 index 0000000000..e220598159 --- /dev/null +++ b/src/openrct2/actions/CustomAction.hpp @@ -0,0 +1,56 @@ +/***************************************************************************** + * Copyright (c) 2014-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 "../scripting/ScriptEngine.h" +# include "GameAction.h" + +DEFINE_GAME_ACTION(CustomAction, GAME_COMMAND_CUSTOM, GameActionResult) +{ +private: + std::string _id; + std::string _json; + +public: + CustomAction() = default; + CustomAction(const std::string& id, const std::string& json) + : _id(id) + , _json(json) + { + } + + uint16_t GetActionFlags() const override + { + return GameAction::GetActionFlags() | GA_FLAGS::ALLOW_WHILE_PAUSED; + } + + void Serialise(DataSerialiser & stream) override + { + GameAction::Serialise(stream); + stream << DS_TAG(_id) << DS_TAG(_json); + } + + GameActionResult::Ptr Query() const override + { + auto& scriptingEngine = OpenRCT2::GetContext()->GetScriptEngine(); + return scriptingEngine.QueryOrExecuteCustomGameAction(_id, _json, false); + } + + GameActionResult::Ptr Execute() const override + { + auto& scriptingEngine = OpenRCT2::GetContext()->GetScriptEngine(); + return scriptingEngine.QueryOrExecuteCustomGameAction(_id, _json, true); + } +}; + +#endif diff --git a/src/openrct2/actions/GameActionRegistration.cpp b/src/openrct2/actions/GameActionRegistration.cpp index c693d892c6..8f2638cd8d 100644 --- a/src/openrct2/actions/GameActionRegistration.cpp +++ b/src/openrct2/actions/GameActionRegistration.cpp @@ -15,6 +15,7 @@ #include "BannerSetStyleAction.hpp" #include "ClearAction.hpp" #include "ClimateSetAction.hpp" +#include "CustomAction.hpp" #include "FootpathPlaceAction.hpp" #include "FootpathPlaceFromTrackAction.hpp" #include "FootpathRemoveAction.hpp" @@ -171,5 +172,8 @@ namespace GameActions Register(); Register(); Register(); +#ifdef __ENABLE_SCRIPTING__ + Register(); +#endif } } // namespace GameActions diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index e603eda448..fec0573264 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -2997,12 +2997,15 @@ void Network::Server_Handle_GAME_ACTION(NetworkConnection& connection, NetworkPa return; } - // Check if player's group permission allows command to run - NetworkGroup* group = GetGroupByID(connection.Player->Group); - if (group == nullptr || group->CanPerformCommand(actionType) == false) + if (actionType != GAME_COMMAND_CUSTOM) { - Server_Send_SHOWERROR(connection, STR_CANT_DO_THIS, STR_PERMISSION_DENIED); - return; + // Check if player's group permission allows command to run + NetworkGroup* group = GetGroupByID(connection.Player->Group); + if (group == nullptr || group->CanPerformCommand(actionType) == false) + { + Server_Send_SHOWERROR(connection, STR_CANT_DO_THIS, STR_PERMISSION_DENIED); + return; + } } // Create and enqueue the action. diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 87ba11772c..8c7893ac1a 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -11,6 +11,7 @@ #ifdef __ENABLE_SCRIPTING__ +# include "../actions/CustomAction.hpp" # include "../actions/ParkSetNameAction.hpp" # include "../actions/SmallSceneryPlaceAction.hpp" # include "Duktape.hpp" @@ -91,7 +92,7 @@ namespace OpenRCT2::Scripting if (isExecute) { action->SetCallback( - [this, &plugin, &callback](const GameAction*, const GameActionResult* res) -> void { + [this, plugin, callback](const GameAction*, const GameActionResult* res) -> void { HandleGameActionResult(plugin, *res, callback); }); GameActions::Execute(action.get()); @@ -143,7 +144,16 @@ namespace OpenRCT2::Scripting uint8_t secondaryColour = args["secondaryColour"].as_int(); return std::make_unique(loc, quadrant, sceneryType, primaryColour, secondaryColour); } - return {}; + else + { + // Serialise args to json so that it can be sent + auto ctx = args.context(); + args.push(); + auto jsonz = duk_json_encode(ctx, -1); + auto json = std::string(jsonz); + duk_pop(ctx); + return std::make_unique(actionid, json); + } } void HandleGameActionResult( diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index f7d72ed029..47792c4c42 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -694,6 +694,30 @@ void ScriptEngine::AddNetworkPlugin(const std::string_view& code) LoadPlugin(plugin); } +std::unique_ptr ScriptEngine::QueryOrExecuteCustomGameAction( + const std::string_view& id, + const std::string_view& args, + bool isExecute) +{ + // Deserialise the JSON args + std::string argsz(args); + duk_push_string(_context, argsz.c_str()); + duk_json_decode(_context, -1); + auto dukArgs = DukValue::take_from_stack(_context); + + // Ready to call plugin handler + if (isExecute) + { + std::printf("EXECUTE: %s(%s)\n", std::string(id).c_str(), std::string(args).c_str()); + } + else + { + std::printf("QUERY: %s(%s)\n", std::string(id).c_str(), std::string(args).c_str()); + } + + return std::make_unique(); +} + 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 cf7f62acfa..a309f1faa1 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -27,6 +27,7 @@ struct duk_hthread; typedef struct duk_hthread duk_context; +class GameActionResult; class FileWatcher; class InteractiveConsole; @@ -155,6 +156,8 @@ namespace OpenRCT2::Scripting void AddNetworkPlugin(const std::string_view& code); + std::unique_ptr QueryOrExecuteCustomGameAction(const std::string_view& id, const std::string_view& args, bool isExecute); + private: void Initialise(); void StartPlugins(); From 2ad37db8174b0b25acd86e8d863de0edf79032a5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 2 Mar 2020 23:55:18 +0000 Subject: [PATCH 106/159] Implement registering game actions --- distribution/openrct2.d.ts | 18 ++--- src/openrct2-ui/windows/Error.cpp | 2 +- src/openrct2/scripting/ScContext.hpp | 79 ++++++++++++--------- src/openrct2/scripting/ScriptEngine.cpp | 92 ++++++++++++++++++++----- src/openrct2/scripting/ScriptEngine.h | 21 +++++- 5 files changed, 149 insertions(+), 63 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 188c7d16a1..d73baafa55 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -80,12 +80,6 @@ declare global { expenditureType: ExpenditureType; } - interface GameActionDesc { - id: string; - query: (args: object) => GameActionResult; - execute: (args: object) => GameActionResult; - } - interface NetworkEventArgs { readonly player: number; } @@ -122,8 +116,15 @@ declare global { /** * Registers a new game action that allows clients to interact with the game. + * @param action The unique name of the action. + * @param query Logic for validating and returning a price for an action. + * @param execute Logic for validating and executing the action. + * @throws An error if the action has already been registered by this or another plugin. */ - registerGameAction(desc: GameActionDesc): void; + registerGameAction( + action: string, + query: (args: object) => GameActionResult, + execute: (args: object) => GameActionResult): void; /** * Query the result of running a game action. This allows you to check the outcome and validity of @@ -156,8 +157,7 @@ declare global { subscribe(hook: "network.leave", callback: (e: NetworkEventArgs) => void): IDisposable; } - interface IntentDesc - { + interface IntentDesc { key: string; title?: string; shortcut?: string; diff --git a/src/openrct2-ui/windows/Error.cpp b/src/openrct2-ui/windows/Error.cpp index f7296cdb77..b7cad6960d 100644 --- a/src/openrct2-ui/windows/Error.cpp +++ b/src/openrct2-ui/windows/Error.cpp @@ -111,7 +111,7 @@ rct_window* window_error_open(rct_string_id title, rct_string_id message) gCurrentFontSpriteBase = FONT_SPRITE_BASE_MEDIUM; width = gfx_get_string_width_new_lined(_window_error_text); - width = std::min(196, width); + width = std::clamp(width, 64, 196); gCurrentFontSpriteBase = FONT_SPRITE_BASE_MEDIUM; gfx_wrap_string(_window_error_text, width + 1, &numLines, &fontHeight); diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 8c7893ac1a..f6e72fbf1e 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -79,46 +79,31 @@ namespace OpenRCT2::Scripting { auto& scriptEngine = GetContext()->GetScriptEngine(); auto ctx = scriptEngine.GetContext(); - if (args.type() == DukValue::Type::OBJECT) + try { - if (callback.is_function()) + auto action = CreateGameAction(actionid, args); + if (action != nullptr) { - try + auto plugin = scriptEngine.GetExecInfo().GetCurrentPlugin(); + if (isExecute) { - auto action = CreateGameAction(actionid, args); - if (action != nullptr) - { - auto plugin = scriptEngine.GetExecInfo().GetCurrentPlugin(); - if (isExecute) - { - action->SetCallback( - [this, plugin, callback](const GameAction*, const GameActionResult* res) -> void { - HandleGameActionResult(plugin, *res, callback); - }); - GameActions::Execute(action.get()); - } - else - { - auto res = GameActions::Query(action.get()); - HandleGameActionResult(plugin, *res, callback); - } - } - else - { - duk_error(ctx, DUK_ERR_ERROR, "Unknown action."); - } + action->SetCallback([this, plugin, callback](const GameAction*, const GameActionResult* res) -> void { + HandleGameActionResult(plugin, *res, callback); + }); + GameActions::Execute(action.get()); } - catch (DukException&) + else { - duk_error(ctx, DUK_ERR_ERROR, "Invalid action parameters."); + auto res = GameActions::Query(action.get()); + HandleGameActionResult(plugin, *res, callback); } } else { - duk_error(ctx, DUK_ERR_ERROR, "Callback was not a function."); + duk_error(ctx, DUK_ERR_ERROR, "Unknown action."); } } - else + catch (DukException&) { duk_error(ctx, DUK_ERR_ERROR, "Invalid action parameters."); } @@ -148,7 +133,14 @@ namespace OpenRCT2::Scripting { // Serialise args to json so that it can be sent auto ctx = args.context(); - args.push(); + if (args.type() == DukValue::Type::OBJECT) + { + args.push(); + } + else + { + duk_push_object(ctx); + } auto jsonz = duk_json_encode(ctx, -1); auto json = std::string(jsonz); duk_pop(ctx); @@ -185,8 +177,30 @@ namespace OpenRCT2::Scripting auto args = DukValue::take_from_stack(ctx); - // Call the plugin callback and pass the result object - scriptEngine.ExecutePluginCall(plugin, callback, { args }, false); + if (callback.is_function()) + { + // Call the plugin callback and pass the result object + scriptEngine.ExecutePluginCall(plugin, callback, { args }, false); + } + } + + void registerGameAction(const std::string& action, const DukValue& query, const DukValue& execute) + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + auto plugin = scriptEngine.GetExecInfo().GetCurrentPlugin(); + auto ctx = scriptEngine.GetContext(); + if (!query.is_function()) + { + duk_error(ctx, DUK_ERR_ERROR, "query was not a function."); + } + else if (!execute.is_function()) + { + duk_error(ctx, DUK_ERR_ERROR, "execute was not a function."); + } + else if (!scriptEngine.RegisterCustomAction(plugin, action, query, execute)) + { + duk_error(ctx, DUK_ERR_ERROR, "action has already been registered."); + } } public: @@ -196,6 +210,7 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); dukglue_register_method(ctx, &ScContext::queryAction, "queryAction"); dukglue_register_method(ctx, &ScContext::executeAction, "executeAction"); + dukglue_register_method(ctx, &ScContext::registerGameAction, "registerGameAction"); } }; } // namespace OpenRCT2::Scripting diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 47792c4c42..95b5efc74d 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -459,6 +459,7 @@ void ScriptEngine::StopPlugin(std::shared_ptr plugin) { if (plugin->HasStarted()) { + RemoveCustomGameActions(plugin); _hookEngine.UnsubscribeAll(plugin); for (auto callback : _pluginStoppedSubscriptions) { @@ -653,7 +654,7 @@ std::future ScriptEngine::Eval(const std::string& s) return future; } -bool ScriptEngine::ExecutePluginCall( +DukValue ScriptEngine::ExecutePluginCall( const std::shared_ptr& plugin, const DukValue& func, const std::vector& args, bool isGameStateMutable) { if (func.is_function()) @@ -667,9 +668,7 @@ bool ScriptEngine::ExecutePluginCall( auto result = duk_pcall(_context, static_cast(args.size())); if (result == DUK_EXEC_SUCCESS) { - // TODO allow result to be returned as a DukValue - duk_pop(_context); - return true; + return DukValue::take_from_stack(_context); } else { @@ -678,7 +677,7 @@ bool ScriptEngine::ExecutePluginCall( duk_pop(_context); } } - return false; + return DukValue(); } void ScriptEngine::LogPluginInfo(const std::shared_ptr& plugin, const std::string_view& message) @@ -695,27 +694,82 @@ void ScriptEngine::AddNetworkPlugin(const std::string_view& code) } std::unique_ptr ScriptEngine::QueryOrExecuteCustomGameAction( - const std::string_view& id, - const std::string_view& args, - bool isExecute) + const std::string_view& id, const std::string_view& args, bool isExecute) { - // Deserialise the JSON args - std::string argsz(args); - duk_push_string(_context, argsz.c_str()); - duk_json_decode(_context, -1); - auto dukArgs = DukValue::take_from_stack(_context); - - // Ready to call plugin handler - if (isExecute) + std::string actionz = std::string(id); + auto kvp = _customActions.find(actionz); + if (kvp != _customActions.end()) { - std::printf("EXECUTE: %s(%s)\n", std::string(id).c_str(), std::string(args).c_str()); + const auto& customAction = kvp->second; + + // Deserialise the JSON args + std::string argsz(args); + duk_push_string(_context, argsz.c_str()); + duk_json_decode(_context, -1); + auto dukArgs = DukValue::take_from_stack(_context); + + // Ready to call plugin handler + DukValue dukResult; + if (!isExecute) + { + dukResult = ExecutePluginCall(customAction.Plugin, customAction.Query, { dukArgs }, false); + } + else + { + dukResult = ExecutePluginCall(customAction.Plugin, customAction.Execute, { dukArgs }, true); + } + return DukToGameActionResult(dukResult); } else { - std::printf("QUERY: %s(%s)\n", std::string(id).c_str(), std::string(args).c_str()); + auto action = std::make_unique(); + action->Error = GA_ERROR::UNKNOWN; + action->ErrorTitle = OBJECT_ERROR_UNKNOWN; + return action; + } +} + +std::unique_ptr ScriptEngine::DukToGameActionResult(const DukValue& d) +{ + auto result = std::make_unique(); + result->Error = d["error"].type() == DukValue::Type::NUMBER ? static_cast(d["error"].as_int()) : GA_ERROR::OK; + auto errorTitle = d["errorTitle"].type() == DukValue::Type::STRING ? d["errorTitle"].as_string() : std::string(); + auto errorMessage = d["errorMessage"].type() == DukValue::Type::STRING ? d["errorMessage"].as_string() : std::string(); + result->Cost = d["cost"].type() == DukValue::Type::NUMBER ? d["cost"].as_int() : 0; + return result; +} + +bool ScriptEngine::RegisterCustomAction( + const std::shared_ptr& plugin, const std::string_view& action, const DukValue& query, const DukValue& execute) +{ + std::string actionz = std::string(action); + if (_customActions.find(actionz) != _customActions.end()) + { + return false; } - return std::make_unique(); + CustomAction customAction; + customAction.Plugin = plugin; + customAction.Name = std::move(actionz); + customAction.Query = query; + customAction.Execute = execute; + _customActions[customAction.Name] = std::move(customAction); + return true; +} + +void ScriptEngine::RemoveCustomGameActions(const std::shared_ptr& plugin) +{ + for (auto it = _customActions.begin(); it != _customActions.end();) + { + if (it->second.Plugin == plugin) + { + it = _customActions.erase(it); + } + else + { + it++; + } + } } std::string OpenRCT2::Scripting::Stringify(const DukValue& val) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index a309f1faa1..9a6981771c 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -21,6 +21,7 @@ # include # include # include +# include # include # include @@ -118,6 +119,16 @@ namespace OpenRCT2::Scripting std::mutex _changedPluginFilesMutex; std::vector)>> _pluginStoppedSubscriptions; + struct CustomAction + { + std::shared_ptr Plugin; + std::string Name; + DukValue Query; + DukValue Execute; + }; + + std::unordered_map _customActions; + public: ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env); ScriptEngine(ScriptEngine&) = delete; @@ -143,7 +154,7 @@ namespace OpenRCT2::Scripting void UnloadPlugins(); void Update(); std::future Eval(const std::string& s); - bool ExecutePluginCall( + DukValue ExecutePluginCall( const std::shared_ptr& plugin, const DukValue& func, const std::vector& args, bool isGameStateMutable); @@ -156,7 +167,11 @@ namespace OpenRCT2::Scripting void AddNetworkPlugin(const std::string_view& code); - std::unique_ptr QueryOrExecuteCustomGameAction(const std::string_view& id, const std::string_view& args, bool isExecute); + std::unique_ptr QueryOrExecuteCustomGameAction( + const std::string_view& id, const std::string_view& args, bool isExecute); + bool RegisterCustomAction( + const std::shared_ptr& plugin, const std::string_view& action, const DukValue& query, + const DukValue& execute); private: void Initialise(); @@ -170,6 +185,8 @@ namespace OpenRCT2::Scripting void SetupHotReloading(); void AutoReloadPlugins(); void ProcessREPL(); + void RemoveCustomGameActions(const std::shared_ptr& plugin); + std::unique_ptr DukToGameActionResult(const DukValue& d); }; bool IsGameStateMutable(); From 83fe0cf5c55600b23bf4d3b367dc38b51db8564c Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 3 Mar 2020 21:11:26 +0000 Subject: [PATCH 107/159] Implement strings for GameAction errors --- src/openrct2-ui/WindowManager.cpp | 5 +++ src/openrct2-ui/windows/Error.cpp | 40 +++++++++++-------- src/openrct2-ui/windows/RideConstruction.cpp | 5 ++- src/openrct2-ui/windows/TopToolbar.cpp | 14 +++++-- src/openrct2-ui/windows/TrackDesignPlace.cpp | 9 ++++- src/openrct2-ui/windows/Window.h | 2 + src/openrct2/actions/GameAction.cpp | 37 +++++++++++++++-- src/openrct2/actions/GameAction.h | 8 +++- src/openrct2/actions/GameActionCompat.cpp | 10 ++++- src/openrct2/actions/LandSmoothAction.hpp | 2 +- src/openrct2/actions/MazePlaceTrackAction.hpp | 4 +- src/openrct2/actions/MazeSetTrackAction.hpp | 3 +- src/openrct2/scripting/Duktape.hpp | 15 +++++++ src/openrct2/scripting/ScContext.hpp | 4 +- src/openrct2/scripting/ScriptEngine.cpp | 8 ++-- src/openrct2/ui/DummyWindowManager.cpp | 4 ++ src/openrct2/ui/WindowManager.h | 1 + src/openrct2/world/Map.cpp | 5 ++- 18 files changed, 135 insertions(+), 41 deletions(-) diff --git a/src/openrct2-ui/WindowManager.cpp b/src/openrct2-ui/WindowManager.cpp index 869626a465..2a79bf564d 100644 --- a/src/openrct2-ui/WindowManager.cpp +++ b/src/openrct2-ui/WindowManager.cpp @@ -207,6 +207,11 @@ public: return window_error_open(title, message); } + rct_window* ShowError(const std::string_view& title, const std::string_view& message) override + { + return window_error_open(title, message); + } + rct_window* OpenIntent(Intent* intent) override { switch (intent->GetWindowClass()) diff --git a/src/openrct2-ui/windows/Error.cpp b/src/openrct2-ui/windows/Error.cpp index b7cad6960d..5e6f2101fd 100644 --- a/src/openrct2-ui/windows/Error.cpp +++ b/src/openrct2-ui/windows/Error.cpp @@ -62,7 +62,7 @@ static rct_window_event_list window_error_events = { }; // clang-format on -static char _window_error_text[512]; +static std::string _window_error_text; static uint16_t _window_error_num_lines; /** @@ -74,30 +74,38 @@ static uint16_t _window_error_num_lines; */ rct_window* window_error_open(rct_string_id title, rct_string_id message) { - utf8* dst; + auto titlez = format_string(title, gCommonFormatArgs); + auto messagez = format_string(message, gCommonFormatArgs); + return window_error_open(titlez, messagez); +} + +rct_window* window_error_open(const std::string_view& title, const std::string_view& message) +{ int32_t numLines, fontHeight, width, height, maxY; rct_window* w; window_close_by_class(WC_ERROR); - dst = _window_error_text; + auto& buffer = _window_error_text; + buffer.clear(); // Format the title - dst = utf8_write_codepoint(dst, FORMAT_BLACK); - if (title != STR_NONE) { - format_string(dst, 512 - (dst - _window_error_text), title, gCommonFormatArgs); - dst = get_string_end(dst); + char temp[8]{}; + utf8_write_codepoint(temp, FORMAT_BLACK); + buffer.append(temp); } + buffer.append(title); // Format the message - if (message != STR_NONE) + if (!message.empty()) { - dst = utf8_write_codepoint(dst, FORMAT_NEWLINE); - format_string(dst, 512 - (dst - _window_error_text), message, gCommonFormatArgs); - dst = get_string_end(dst); + char temp[8]{}; + utf8_write_codepoint(temp, FORMAT_NEWLINE); + buffer.append(temp); + buffer.append(message); } - log_verbose("show error, %s", _window_error_text + 1); + log_verbose("show error, %s", buffer.c_str() + 1); // Don't do unnecessary work in headless. Also saves checking if cursor state is null. if (gOpenRCT2Headless) @@ -106,15 +114,15 @@ rct_window* window_error_open(rct_string_id title, rct_string_id message) } // Check if there is any text to display - if (dst == _window_error_text + 1) + if (buffer.size() <= 1) return nullptr; gCurrentFontSpriteBase = FONT_SPRITE_BASE_MEDIUM; - width = gfx_get_string_width_new_lined(_window_error_text); + width = gfx_get_string_width_new_lined(buffer.data()); width = std::clamp(width, 64, 196); gCurrentFontSpriteBase = FONT_SPRITE_BASE_MEDIUM; - gfx_wrap_string(_window_error_text, width + 1, &numLines, &fontHeight); + gfx_wrap_string(buffer.data(), width + 1, &numLines, &fontHeight); _window_error_num_lines = numLines; width = width + 3; @@ -186,5 +194,5 @@ static void window_error_paint(rct_window* w, rct_drawpixelinfo* dpi) l = w->windowPos.x + (w->width + 1) / 2 - 1; t = w->windowPos.y + 1; - draw_string_centred_raw(dpi, l, t, _window_error_num_lines, _window_error_text); + draw_string_centred_raw(dpi, l, t, _window_error_num_lines, _window_error_text.data()); } diff --git a/src/openrct2-ui/windows/RideConstruction.cpp b/src/openrct2-ui/windows/RideConstruction.cpp index 8fc121ec55..f875773cc6 100644 --- a/src/openrct2-ui/windows/RideConstruction.cpp +++ b/src/openrct2-ui/windows/RideConstruction.cpp @@ -1824,7 +1824,10 @@ static void window_ride_construction_construct(rct_window* w) // Used by some functions if (res->Error != GA_ERROR::OK) { - gGameCommandErrorText = res->ErrorMessage; + if (auto error = std::get_if(&res->ErrorMessage)) + gGameCommandErrorText = *error; + else + gGameCommandErrorText = STR_NONE; _trackPlaceCost = MONEY32_UNDEFINED; } else diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index 0ddd5ade53..dc04ebfb0b 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -1947,9 +1947,12 @@ static void window_top_toolbar_scenery_tool_down(int16_t x, int16_t y, rct_windo break; } - if (res->ErrorMessage == STR_NOT_ENOUGH_CASH_REQUIRES || res->ErrorMessage == STR_CAN_ONLY_BUILD_THIS_ON_WATER) + if (auto message = std::get_if(&res->ErrorMessage)) { - break; + if (*message == STR_NOT_ENOUGH_CASH_REQUIRES || *message == STR_CAN_ONLY_BUILD_THIS_ON_WATER) + { + break; + } } if (zAttemptRange != 1) @@ -1997,9 +2000,12 @@ static void window_top_toolbar_scenery_tool_down(int16_t x, int16_t y, rct_windo break; } - if (res->ErrorMessage == STR_NOT_ENOUGH_CASH_REQUIRES || res->ErrorMessage == STR_CAN_ONLY_BUILD_THIS_ON_WATER) + if (auto message = std::get_if(&res->ErrorMessage)) { - break; + if (*message == STR_NOT_ENOUGH_CASH_REQUIRES || *message == STR_CAN_ONLY_BUILD_THIS_ON_WATER) + { + break; + } } if (zAttemptRange != 1) diff --git a/src/openrct2-ui/windows/TrackDesignPlace.cpp b/src/openrct2-ui/windows/TrackDesignPlace.cpp index 8d8b2ce063..fc40213817 100644 --- a/src/openrct2-ui/windows/TrackDesignPlace.cpp +++ b/src/openrct2-ui/windows/TrackDesignPlace.cpp @@ -23,11 +23,15 @@ #include #include #include +#include +#include #include #include #include #include +using namespace OpenRCT2; + constexpr int16_t TRACK_MINI_PREVIEW_WIDTH = 168; constexpr int16_t TRACK_MINI_PREVIEW_HEIGHT = 78; constexpr uint16_t TRACK_MINI_PREVIEW_SIZE = TRACK_MINI_PREVIEW_WIDTH * TRACK_MINI_PREVIEW_HEIGHT; @@ -391,8 +395,9 @@ static void window_track_place_tooldown(rct_window* w, rct_widgetindex widgetInd // Unable to build track audio_play_sound_at_location(SoundId::Error, trackLoc); - std::copy(res->ErrorMessageArgs.begin(), res->ErrorMessageArgs.end(), gCommonFormatArgs); - context_show_error(res->ErrorTitle, res->ErrorMessage); + + auto windowManager = GetContext()->GetUiContext()->GetWindowManager(); + windowManager->ShowError(res->GetErrorTitle(), res->GetErrorMessage()); } /** diff --git a/src/openrct2-ui/windows/Window.h b/src/openrct2-ui/windows/Window.h index 75c7f67d77..b5894144dd 100644 --- a/src/openrct2-ui/windows/Window.h +++ b/src/openrct2-ui/windows/Window.h @@ -13,6 +13,7 @@ #include #include #include +#include using loadsave_callback = void (*)(int32_t result, const utf8* path); using scenarioselect_callback = void (*)(const utf8* path); @@ -105,6 +106,7 @@ void window_title_command_editor_open(struct TitleSequence* sequence, int32_t co rct_window* window_scenarioselect_open(scenarioselect_callback callback, bool titleEditor); rct_window* window_error_open(rct_string_id title, rct_string_id message); +rct_window* window_error_open(const std::string_view& title, const std::string_view& message); struct TrackDesign; rct_window* window_loadsave_open(int32_t type, const char* defaultName, loadsave_callback callback, TrackDesign* t6Exporter); rct_window* window_track_place_open(const struct track_design_file_ref* tdFileRef); diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index 7462e05140..03cb680b93 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -18,12 +18,16 @@ #include "../network/network.h" #include "../platform/platform.h" #include "../scenario/Scenario.h" +#include "../ui/UiContext.h" +#include "../ui/WindowManager.h" #include "../world/Park.h" #include "../world/Scenery.h" #include #include +using namespace OpenRCT2; + GameActionResult::GameActionResult(GA_ERROR error, rct_string_id message) { Error = error; @@ -45,6 +49,34 @@ GameActionResult::GameActionResult(GA_ERROR error, rct_string_id title, rct_stri std::copy_n(args, ErrorMessageArgs.size(), ErrorMessageArgs.begin()); } +std::string GameActionResult::GetErrorTitle() const +{ + std::string titlez; + if (auto title = std::get_if(&ErrorTitle)) + { + titlez = *title; + } + else + { + titlez = format_string(std::get(ErrorTitle), nullptr); + } + return titlez; +} + +std::string GameActionResult::GetErrorMessage() const +{ + std::string messagez; + if (auto message = std::get_if(&ErrorMessage)) + { + messagez = *message; + } + else + { + messagez = format_string(std::get(ErrorMessage), ErrorMessageArgs.data()); + } + return messagez; +} + namespace GameActions { struct QueuedGameAction @@ -486,9 +518,8 @@ namespace GameActions if (result->Error != GA_ERROR::OK && shouldShowError) { - // Show the error box - std::copy(result->ErrorMessageArgs.begin(), result->ErrorMessageArgs.end(), gCommonFormatArgs); - context_show_error(result->ErrorTitle, result->ErrorMessage); + auto windowManager = GetContext()->GetUiContext()->GetWindowManager(); + windowManager->ShowError(result->GetErrorTitle(), result->GetErrorMessage()); } return result; diff --git a/src/openrct2/actions/GameAction.h b/src/openrct2/actions/GameAction.h index ab3005901b..474dddc6a0 100644 --- a/src/openrct2/actions/GameAction.h +++ b/src/openrct2/actions/GameAction.h @@ -20,6 +20,7 @@ #include #include #include +#include /** * Common error codes for game actions. @@ -69,8 +70,8 @@ public: using Ptr = std::unique_ptr; GA_ERROR Error = GA_ERROR::OK; - rct_string_id ErrorTitle = STR_NONE; - rct_string_id ErrorMessage = STR_NONE; + std::variant ErrorTitle = STR_NONE; + std::variant ErrorMessage = STR_NONE; std::array ErrorMessageArgs; CoordsXYZ Position = { LOCATION_NULL, LOCATION_NULL, LOCATION_NULL }; money32 Cost = 0; @@ -82,6 +83,9 @@ public: GameActionResult(GA_ERROR error, rct_string_id title, rct_string_id message, uint8_t* args); GameActionResult(const GameActionResult&) = delete; virtual ~GameActionResult(){}; + + std::string GetErrorTitle() const; + std::string GetErrorMessage() const; }; struct GameAction diff --git a/src/openrct2/actions/GameActionCompat.cpp b/src/openrct2/actions/GameActionCompat.cpp index d389c7cae5..aebf267c9f 100644 --- a/src/openrct2/actions/GameActionCompat.cpp +++ b/src/openrct2/actions/GameActionCompat.cpp @@ -140,8 +140,14 @@ money32 maze_set_track( // NOTE: ride_construction_tooldown_construct requires them to be set. // Refactor result type once theres no C code referencing this function. - gGameCommandErrorText = res->ErrorMessage; - gGameCommandErrorTitle = res->ErrorTitle; + if (auto title = std::get_if(&res->ErrorTitle)) + gGameCommandErrorTitle = *title; + else + gGameCommandErrorTitle = STR_NONE; + if (auto message = std::get_if(&res->ErrorMessage)) + gGameCommandErrorText = *message; + else + gGameCommandErrorText = STR_NONE; if (res->Error != GA_ERROR::OK) { diff --git a/src/openrct2/actions/LandSmoothAction.hpp b/src/openrct2/actions/LandSmoothAction.hpp index 502bc7b3aa..3d50624403 100644 --- a/src/openrct2/actions/LandSmoothAction.hpp +++ b/src/openrct2/actions/LandSmoothAction.hpp @@ -642,7 +642,7 @@ private: } default: log_error("Invalid map selection %u", _selectionType); - return MakeResult(GA_ERROR::INVALID_PARAMETERS, res->ErrorTitle); + return MakeResult(GA_ERROR::INVALID_PARAMETERS, std::get(res->ErrorTitle)); } // switch selectionType // Raise / lower the land tool selection area diff --git a/src/openrct2/actions/MazePlaceTrackAction.hpp b/src/openrct2/actions/MazePlaceTrackAction.hpp index 079c1a2c21..18c723399a 100644 --- a/src/openrct2/actions/MazePlaceTrackAction.hpp +++ b/src/openrct2/actions/MazePlaceTrackAction.hpp @@ -93,7 +93,7 @@ public: { _loc.ToTileStart(), baseHeight, clearanceHeight }, &map_place_non_scenery_clear_func, { 0b1111, 0 }, GetFlags(), &clearCost, CREATE_CROSSING_MODE_NONE)) { - return MakeResult(GA_ERROR::NO_CLEARANCE, res->ErrorTitle, gGameCommandErrorText, gCommonFormatArgs); + return MakeResult(GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); } if (gMapGroundFlags & ELEMENT_IS_UNDERWATER) @@ -162,7 +162,7 @@ public: { _loc.ToTileStart(), baseHeight, clearanceHeight }, &map_place_non_scenery_clear_func, { 0b1111, 0 }, GetFlags() | GAME_COMMAND_FLAG_APPLY, &clearCost, CREATE_CROSSING_MODE_NONE)) { - return MakeResult(GA_ERROR::NO_CLEARANCE, res->ErrorTitle, gGameCommandErrorText, gCommonFormatArgs); + return MakeResult(GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); } money32 price = (((RideTrackCosts[ride->type].track_price * TrackPricing[TRACK_ELEM_MAZE]) >> 16)); diff --git a/src/openrct2/actions/MazeSetTrackAction.hpp b/src/openrct2/actions/MazeSetTrackAction.hpp index 4e980be78a..7dc8adeeb5 100644 --- a/src/openrct2/actions/MazeSetTrackAction.hpp +++ b/src/openrct2/actions/MazeSetTrackAction.hpp @@ -136,7 +136,8 @@ public: if (!map_can_construct_at({ _loc.ToTileStart(), baseHeight, clearanceHeight }, { 0b1111, 0 })) { - return MakeResult(GA_ERROR::NO_CLEARANCE, res->ErrorTitle, gGameCommandErrorText, gCommonFormatArgs); + return MakeResult( + GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); } if (gMapGroundFlags & ELEMENT_IS_UNDERWATER) diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 280f5293fe..d6e695d482 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -20,4 +20,19 @@ template DukValue GetObjectAsDukValue(duk_context* ctx, const std::s return DukValue::take_from_stack(ctx); } +template +const T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; + +template<> +inline const std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) +{ + return value.type() == DukValue::STRING ? value.as_string() : defaultValue; +} + +template<> +inline const int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) +{ + return value.type() == DukValue::NUMBER ? value.as_int() : defaultValue; +} + #endif diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index f6e72fbf1e..75f8abc26f 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -160,11 +160,11 @@ namespace OpenRCT2::Scripting if (res.Error != GA_ERROR::OK) { - auto title = format_string(res.ErrorTitle, nullptr); + auto title = res.GetErrorTitle(); duk_push_string(ctx, title.c_str()); duk_put_prop_string(ctx, objIdx, "errorTitle"); - auto message = format_string(res.ErrorMessage, res.ErrorMessageArgs.data()); + auto message = res.GetErrorMessage(); duk_push_string(ctx, message.c_str()); duk_put_prop_string(ctx, objIdx, "errorMessage"); } diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 95b5efc74d..981bae7005 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -732,10 +732,10 @@ std::unique_ptr ScriptEngine::QueryOrExecuteCustomGameAction( std::unique_ptr ScriptEngine::DukToGameActionResult(const DukValue& d) { auto result = std::make_unique(); - result->Error = d["error"].type() == DukValue::Type::NUMBER ? static_cast(d["error"].as_int()) : GA_ERROR::OK; - auto errorTitle = d["errorTitle"].type() == DukValue::Type::STRING ? d["errorTitle"].as_string() : std::string(); - auto errorMessage = d["errorMessage"].type() == DukValue::Type::STRING ? d["errorMessage"].as_string() : std::string(); - result->Cost = d["cost"].type() == DukValue::Type::NUMBER ? d["cost"].as_int() : 0; + result->Error = static_cast(AsOrDefault(d["error"])); + result->ErrorTitle = AsOrDefault(d["errorTitle"]); + result->ErrorMessage = AsOrDefault(d["errorMessage"]); + result->Cost = AsOrDefault(d["cost"]); return result; } diff --git a/src/openrct2/ui/DummyWindowManager.cpp b/src/openrct2/ui/DummyWindowManager.cpp index 8d1c6ab0a7..42c8d071ef 100644 --- a/src/openrct2/ui/DummyWindowManager.cpp +++ b/src/openrct2/ui/DummyWindowManager.cpp @@ -30,6 +30,10 @@ namespace OpenRCT2::Ui { return nullptr; } + rct_window* ShowError(const std::string_view& /*title*/, const std::string_view& /*message*/) override + { + return nullptr; + } rct_window* OpenIntent(Intent* /*intent*/) override { return nullptr; diff --git a/src/openrct2/ui/WindowManager.h b/src/openrct2/ui/WindowManager.h index 1392b68db9..fe49810854 100644 --- a/src/openrct2/ui/WindowManager.h +++ b/src/openrct2/ui/WindowManager.h @@ -30,6 +30,7 @@ namespace OpenRCT2::Ui virtual rct_window* OpenIntent(Intent * intent) abstract; virtual void BroadcastIntent(const Intent& intent) abstract; virtual rct_window* ShowError(rct_string_id title, rct_string_id message) abstract; + virtual rct_window* ShowError(const std::string_view& title, const std::string_view& message) abstract; virtual void ForceClose(rct_windowclass windowClass) abstract; virtual void UpdateMapTooltip() abstract; virtual void HandleInput() abstract; diff --git a/src/openrct2/world/Map.cpp b/src/openrct2/world/Map.cpp index 2937cec6ef..469de6cd97 100644 --- a/src/openrct2/world/Map.cpp +++ b/src/openrct2/world/Map.cpp @@ -1481,7 +1481,10 @@ bool map_can_construct_with_clear_at( uint8_t crossingMode) { GameActionResult::Ptr res = map_can_construct_with_clear_at(pos, clearFunc, quarterTile, flags, crossingMode); - gGameCommandErrorText = res->ErrorMessage; + if (auto message = std::get_if(&res->ErrorMessage)) + gGameCommandErrorText = *message; + else + gGameCommandErrorText = STR_NONE; std::copy(res->ErrorMessageArgs.begin(), res->ErrorMessageArgs.end(), gCommonFormatArgs); if (price != nullptr) { From 49b155d17834a20e75dc8e4047fd2834c7b83aa6 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 4 Mar 2020 00:01:17 +0000 Subject: [PATCH 108/159] Fix Linux build --- src/openrct2/scripting/Duktape.hpp | 6 +++--- src/openrct2/scripting/ScTile.hpp | 21 +++++++++++++++++++-- src/openrct2/scripting/ScriptEngine.cpp | 8 ++++---- src/openrct2/scripting/ScriptEngine.h | 2 +- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index d6e695d482..996d7ac0b7 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -21,16 +21,16 @@ template DukValue GetObjectAsDukValue(duk_context* ctx, const std::s } template -const T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; +T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; template<> -inline const std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) +inline std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) { return value.type() == DukValue::STRING ? value.as_string() : defaultValue; } template<> -inline const int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) +inline int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) { return value.type() == DukValue::NUMBER ? value.as_int() : defaultValue; } diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 07c9676de8..55746dacaf 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -313,11 +313,13 @@ namespace OpenRCT2::Scripting { auto el = _element->AsTrack(); el->SetSequenceIndex(value); + break; } case TILE_ELEMENT_TYPE_ENTRANCE: { auto el = _element->AsEntrance(); el->SetSequenceIndex(value); + break; } } } @@ -348,11 +350,13 @@ namespace OpenRCT2::Scripting { auto el = _element->AsTrack(); el->SetRideIndex(value); + break; } case TILE_ELEMENT_TYPE_ENTRANCE: { auto el = _element->AsEntrance(); el->SetRideIndex(value); + break; } } } @@ -383,11 +387,13 @@ namespace OpenRCT2::Scripting { auto el = _element->AsTrack(); el->SetStationIndex(value); + break; } case TILE_ELEMENT_TYPE_ENTRANCE: { auto el = _element->AsEntrance(); el->SetStationIndex(value); + break; } } } @@ -450,26 +456,31 @@ namespace OpenRCT2::Scripting { auto el = _element->AsPath(); el->SetPathEntryIndex(value & 0xFF); + break; } case TILE_ELEMENT_TYPE_SMALL_SCENERY: { auto el = _element->AsSmallScenery(); el->SetEntryIndex(value & 0xFF); + break; } case TILE_ELEMENT_TYPE_LARGE_SCENERY: { auto el = _element->AsLargeScenery(); el->SetEntryIndex(value); + break; } case TILE_ELEMENT_TYPE_WALL: { auto el = _element->AsWall(); el->SetEntryIndex(value & 0xFFFF); + break; } case TILE_ELEMENT_TYPE_ENTRANCE: { auto el = _element->AsEntrance(); el->SetEntranceType(value & 0xFF); + break; } } } @@ -517,11 +528,13 @@ namespace OpenRCT2::Scripting { auto el = _element->AsSmallScenery(); el->SetPrimaryColour(value); + break; } case TILE_ELEMENT_TYPE_LARGE_SCENERY: { auto el = _element->AsLargeScenery(); el->SetPrimaryColour(value); + break; } } } @@ -552,11 +565,13 @@ namespace OpenRCT2::Scripting { auto el = _element->AsSmallScenery(); el->SetSecondaryColour(value); + break; } case TILE_ELEMENT_TYPE_LARGE_SCENERY: { auto el = _element->AsLargeScenery(); el->SetSecondaryColour(value); + break; } } } @@ -747,9 +762,10 @@ namespace OpenRCT2::Scripting std::shared_ptr insertElement(size_t index) { ThrowIfGameStateNotMutable(); + std::shared_ptr result; auto first = GetFirstElement(); auto origNumElements = GetNumElements(first); - if (index >= 0 && index <= origNumElements) + if (index <= origNumElements) { std::vector data(first, first + origNumElements); @@ -782,7 +798,7 @@ namespace OpenRCT2::Scripting } first[origNumElements].SetLastForTile(true); map_invalidate_tile_full(_coords); - return std::make_shared(_coords, &first[index]); + result = std::make_shared(_coords, &first[index]); } } else @@ -790,6 +806,7 @@ namespace OpenRCT2::Scripting auto ctx = GetDukContext(); duk_error(ctx, DUK_ERR_RANGE_ERROR, "Index must be between zero and the number of elements on the tile."); } + return result; } void removeElement(size_t index) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 981bae7005..5665298914 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -712,11 +712,11 @@ std::unique_ptr ScriptEngine::QueryOrExecuteCustomGameAction( DukValue dukResult; if (!isExecute) { - dukResult = ExecutePluginCall(customAction.Plugin, customAction.Query, { dukArgs }, false); + dukResult = ExecutePluginCall(customAction.Owner, customAction.Query, { dukArgs }, false); } else { - dukResult = ExecutePluginCall(customAction.Plugin, customAction.Execute, { dukArgs }, true); + dukResult = ExecutePluginCall(customAction.Owner, customAction.Execute, { dukArgs }, true); } return DukToGameActionResult(dukResult); } @@ -749,7 +749,7 @@ bool ScriptEngine::RegisterCustomAction( } CustomAction customAction; - customAction.Plugin = plugin; + customAction.Owner = plugin; customAction.Name = std::move(actionz); customAction.Query = query; customAction.Execute = execute; @@ -761,7 +761,7 @@ void ScriptEngine::RemoveCustomGameActions(const std::shared_ptr& plugin { for (auto it = _customActions.begin(); it != _customActions.end();) { - if (it->second.Plugin == plugin) + if (it->second.Owner == plugin) { it = _customActions.erase(it); } diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 9a6981771c..871c40bea4 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -121,7 +121,7 @@ namespace OpenRCT2::Scripting struct CustomAction { - std::shared_ptr Plugin; + std::shared_ptr Owner; std::string Name; DukValue Query; DukValue Execute; From efcf9fd22aded16211c000c18f250129202b3561 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 4 Mar 2020 20:03:13 +0000 Subject: [PATCH 109/159] Implement hooking game actions --- distribution/openrct2.d.ts | 23 +++++---- src/openrct2/actions/GameAction.cpp | 18 +++++++ src/openrct2/scripting/HookEngine.cpp | 2 + src/openrct2/scripting/HookEngine.h | 2 + src/openrct2/scripting/ScriptEngine.cpp | 69 +++++++++++++++++++++++++ src/openrct2/scripting/ScriptEngine.h | 5 ++ 6 files changed, 109 insertions(+), 10 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index d73baafa55..4990861d66 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -72,23 +72,25 @@ declare global { "interest"; interface GameActionResult { - error: string; + error?: string; errorTitle?: string; errorMessage?: string; - position: Coord3; - cost: number; - expenditureType: ExpenditureType; + position?: Coord3; + cost?: number; + expenditureType?: ExpenditureType; + } + + interface ActionEventArgs { + readonly player: number; + readonly type: string; + readonly isClientOnly: boolean; + result: GameActionResult; } interface NetworkEventArgs { readonly player: number; } - interface NetworkActionEventArgs extends NetworkEventArgs { - readonly type: string; - result: GameActionResult; - } - interface NetworkChatEventArgs extends NetworkEventArgs { message: string; } @@ -149,9 +151,10 @@ declare global { */ subscribe(hook: HookType, callback: Function): IDisposable; + subscribe(hook: "action.query", callback: (e: ActionEventArgs) => void): IDisposable; + subscribe(hook: "action.execute", callback: (e: ActionEventArgs) => void): IDisposable; subscribe(hook: "interval.tick", callback: () => void): IDisposable; subscribe(hook: "interval.day", callback: () => void): IDisposable; - subscribe(hook: "network.action", callback: (e: NetworkActionEventArgs) => void): IDisposable; subscribe(hook: "network.chat", callback: (e: NetworkChatEventArgs) => void): IDisposable; subscribe(hook: "network.join", callback: (e: NetworkEventArgs) => void): IDisposable; subscribe(hook: "network.leave", callback: (e: NetworkEventArgs) => void): IDisposable; diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index 03cb680b93..00ce2751a4 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -18,6 +18,7 @@ #include "../network/network.h" #include "../platform/platform.h" #include "../scenario/Scenario.h" +#include "../scripting/ScriptEngine.h" #include "../ui/UiContext.h" #include "../ui/WindowManager.h" #include "../world/Park.h" @@ -399,6 +400,15 @@ namespace GameActions } GameActionResult::Ptr result = QueryInternal(action, topLevel); +#ifdef __ENABLE_SCRIPTING__ + if (result->Error == GA_ERROR::OK + && ((network_get_mode() == NETWORK_MODE_NONE) || (flags & GAME_COMMAND_FLAG_NETWORKED))) + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + scriptEngine.RunGameActionHooks(*action, result, false); + // Script hooks may now have changed the game action result... + } +#endif if (result->Error == GA_ERROR::OK) { if (topLevel) @@ -434,6 +444,14 @@ namespace GameActions // Execute the action, changing the game state result = action->Execute(); +#ifdef __ENABLE_SCRIPTING__ + if (result->Error == GA_ERROR::OK) + { + auto& scriptEngine = GetContext()->GetScriptEngine(); + scriptEngine.RunGameActionHooks(*action, result, true); + // Script hooks may now have changed the game action result... + } +#endif LogActionFinish(logContext, action, result); diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index fa3442f2ce..74295ec993 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -20,6 +20,8 @@ using namespace OpenRCT2::Scripting; HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string& name) { static const std::unordered_map LookupTable({ + { "action.query", HOOK_TYPE::ACTION_QUERY }, + { "action.execute", HOOK_TYPE::ACTION_EXECUTE }, { "interval.tick", HOOK_TYPE::INTERVAL_TICK }, { "interval.day", HOOK_TYPE::INTERVAL_DAY }, { "network.chat", HOOK_TYPE::NETWORK_CHAT }, diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 60ba158cfe..6547215866 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -28,6 +28,8 @@ namespace OpenRCT2::Scripting enum class HOOK_TYPE { + ACTION_QUERY, + ACTION_EXECUTE, INTERVAL_TICK, INTERVAL_DAY, NETWORK_CHAT, diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 5665298914..354c88c77b 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -12,6 +12,7 @@ # include "ScriptEngine.h" # include "../PlatformEnvironment.h" +# include "../actions/GameAction.h" # include "../config/Config.h" # include "../core/FileScanner.h" # include "../core/Path.hpp" @@ -739,6 +740,42 @@ std::unique_ptr ScriptEngine::DukToGameActionResult(const DukV return result; } +DukValue ScriptEngine::PositionToDuk(const CoordsXYZ& position) +{ + duk_context* ctx = _context; + auto obj = duk_push_object(ctx); + duk_push_int(ctx, position.x); + duk_put_prop_string(ctx, obj, "x"); + duk_push_int(ctx, position.y); + duk_put_prop_string(ctx, obj, "y"); + duk_push_int(ctx, position.z); + duk_put_prop_string(ctx, obj, "z"); + return DukValue::take_from_stack(ctx); +} + +DukValue ScriptEngine::GameActionResultToDuk(const GameAction& action, const std::unique_ptr& result) +{ + duk_context* ctx = _context; + auto obj = duk_push_object(ctx); + auto player = action.GetPlayer(); + if (player != -1) + { + duk_push_int(ctx, action.GetPlayer()); + duk_put_prop_string(ctx, obj, "player"); + } + if (result->Cost != MONEY32_UNDEFINED) + { + duk_push_int(ctx, result->Cost); + duk_put_prop_string(ctx, obj, "cost"); + } + if (!result->Position.isNull()) + { + PositionToDuk(result->Position).push(); + duk_put_prop_string(ctx, obj, "position"); + } + return DukValue::take_from_stack(ctx); +} + bool ScriptEngine::RegisterCustomAction( const std::shared_ptr& plugin, const std::string_view& action, const DukValue& query, const DukValue& execute) { @@ -772,6 +809,38 @@ void ScriptEngine::RemoveCustomGameActions(const std::shared_ptr& plugin } } +void ScriptEngine::RunGameActionHooks(const GameAction& action, std::unique_ptr& result, bool isExecute) +{ + auto hookType = isExecute ? HOOK_TYPE::ACTION_EXECUTE : HOOK_TYPE::ACTION_QUERY; + if (_hookEngine.HasSubscriptions(hookType)) + { + duk_context* ctx = _context; + auto obj = duk_push_object(ctx); + duk_push_uint(ctx, action.GetType()); + duk_put_prop_string(ctx, obj, "type"); + + auto flags = action.GetActionFlags(); + duk_push_boolean(ctx, (flags & GA_FLAGS::CLIENT_ONLY) != 0); + duk_put_prop_string(ctx, obj, "isClientOnly"); + + GameActionResultToDuk(action, result).push(); + duk_put_prop_string(ctx, obj, "result"); + auto dukEventArgs = DukValue::take_from_stack(ctx); + _hookEngine.Call(hookType, dukEventArgs, false); + + if (!isExecute) + { + auto error = AsOrDefault(dukEventArgs["error"]); + if (error != 0) + { + result->Error = static_cast(error); + result->ErrorTitle = AsOrDefault(dukEventArgs["errorTitle"]); + result->ErrorMessage = AsOrDefault(dukEventArgs["errorMessage"]); + } + } + } +} + 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 871c40bea4..7ad4f91232 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -13,6 +13,7 @@ # include "../common.h" # include "../core/FileWatcher.h" +# include "../world/Location.hpp" # include "HookEngine.h" # include "Plugin.h" @@ -28,6 +29,7 @@ struct duk_hthread; typedef struct duk_hthread duk_context; +struct GameAction; class GameActionResult; class FileWatcher; class InteractiveConsole; @@ -172,6 +174,7 @@ namespace OpenRCT2::Scripting bool RegisterCustomAction( const std::shared_ptr& plugin, const std::string_view& action, const DukValue& query, const DukValue& execute); + void RunGameActionHooks(const GameAction& action, std::unique_ptr& result, bool isExecute); private: void Initialise(); @@ -187,6 +190,8 @@ namespace OpenRCT2::Scripting void ProcessREPL(); void RemoveCustomGameActions(const std::shared_ptr& plugin); std::unique_ptr DukToGameActionResult(const DukValue& d); + DukValue GameActionResultToDuk(const GameAction& action, const std::unique_ptr& result); + DukValue PositionToDuk(const CoordsXYZ& position); }; bool IsGameStateMutable(); From a16cacff3a633bd5b8bae61891132a8235e20ced Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 5 Mar 2020 18:30:41 +0000 Subject: [PATCH 110/159] Add special properties for ride action --- src/openrct2/actions/RideCreateAction.hpp | 10 ++ src/openrct2/scripting/Duktape.hpp | 134 +++++++++++++++++++++- src/openrct2/scripting/ScriptEngine.cpp | 54 ++++++--- src/thirdparty/dukglue/dukvalue.h | 6 +- 4 files changed, 178 insertions(+), 26 deletions(-) diff --git a/src/openrct2/actions/RideCreateAction.hpp b/src/openrct2/actions/RideCreateAction.hpp index cb85997acf..5b13f591e6 100644 --- a/src/openrct2/actions/RideCreateAction.hpp +++ b/src/openrct2/actions/RideCreateAction.hpp @@ -60,6 +60,16 @@ public: { } + int32_t GetRideType() const + { + return _rideType; + } + + int32_t GetRideObject() const + { + return _subType; + } + uint16_t GetActionFlags() const override { return GameAction::GetActionFlags() | GA_FLAGS::ALLOW_WHILE_PAUSED; diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 996d7ac0b7..bead6995f2 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -11,8 +11,10 @@ #ifdef __ENABLE_SCRIPTING__ +# include # include # include +# include template DukValue GetObjectAsDukValue(duk_context* ctx, const std::shared_ptr& value) { @@ -20,19 +22,139 @@ template DukValue GetObjectAsDukValue(duk_context* ctx, const std::s return DukValue::take_from_stack(ctx); } -template -T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; +template T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; -template<> -inline std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) +template<> inline std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) { return value.type() == DukValue::STRING ? value.as_string() : defaultValue; } -template<> -inline int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) +template<> inline int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) { return value.type() == DukValue::NUMBER ? value.as_int() : defaultValue; } +/** + * Allows creation of an object on the duktape stack and setting properties on it before + * retrieving the DukValue instance of it. + */ +class DukObject +{ +private: + duk_context* _ctx{}; + duk_idx_t _idx = DUK_INVALID_INDEX; + +public: + DukObject(duk_context* ctx) + : _ctx(ctx) + { + } + + DukObject(const DukObject&) = delete; + + DukObject(DukObject&& m) noexcept + { + _ctx = m._ctx; + _idx = m._idx; + m._ctx = {}; + m._idx = {}; + } + + ~DukObject() + { + PopObjectIfExists(); + } + + void Set(const char* name, bool value) + { + EnsureObjectPushed(); + duk_push_boolean(_ctx, value); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, int32_t value) + { + EnsureObjectPushed(); + duk_push_int(_ctx, value); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, uint32_t value) + { + EnsureObjectPushed(); + duk_push_uint(_ctx, value); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, const std::string_view& value) + { + EnsureObjectPushed(); + duk_push_lstring(_ctx, value.data(), value.size()); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, const DukValue& value) + { + EnsureObjectPushed(); + value.push(); + duk_put_prop_string(_ctx, _idx, name); + } + + DukValue Take() + { + EnsureObjectPushed(); + auto result = DukValue::take_from_stack(_ctx, _idx); + _idx = DUK_INVALID_INDEX; + return result; + } + +private: + void PopObjectIfExists() + { + if (_idx != DUK_INVALID_INDEX) + { + duk_remove(_ctx, _idx); + _idx = DUK_INVALID_INDEX; + } + } + + void EnsureObjectPushed() + { + if (_idx == DUK_INVALID_INDEX) + { + _idx = duk_push_object(_ctx); + } + } +}; + +class DukStackFrame +{ +private: + duk_context* _ctx{}; + duk_idx_t _top; + +public: + DukStackFrame(duk_context* ctx) + : _ctx(ctx) + { + _top = duk_get_top(ctx); + } + + ~DukStackFrame() + { + auto top = duk_get_top(_ctx); + if (top != _top) + { + duk_set_top(_ctx, _top); + _ctx = {}; + std::fprintf(stderr, "duktape stack was not returned to original state!"); + // assert(false); + } + _ctx = {}; + } + + DukStackFrame(const DukStackFrame&) = delete; + DukStackFrame(DukStackFrame&&) = delete; +}; + #endif diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 354c88c77b..2a2c09046f 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -13,6 +13,7 @@ # include "../PlatformEnvironment.h" # include "../actions/GameAction.h" +# include "../actions/RideCreateAction.hpp" # include "../config/Config.h" # include "../core/FileScanner.h" # include "../core/Path.hpp" @@ -658,6 +659,7 @@ std::future ScriptEngine::Eval(const std::string& s) DukValue ScriptEngine::ExecutePluginCall( const std::shared_ptr& plugin, const DukValue& func, const std::vector& args, bool isGameStateMutable) { + DukStackFrame frame(_context); if (func.is_function()) { ScriptExecutionInfo::PluginScope scope(_execInfo, plugin, isGameStateMutable); @@ -742,6 +744,7 @@ std::unique_ptr ScriptEngine::DukToGameActionResult(const DukV DukValue ScriptEngine::PositionToDuk(const CoordsXYZ& position) { + DukStackFrame frame(_context); duk_context* ctx = _context; auto obj = duk_push_object(ctx); duk_push_int(ctx, position.x); @@ -755,25 +758,33 @@ DukValue ScriptEngine::PositionToDuk(const CoordsXYZ& position) DukValue ScriptEngine::GameActionResultToDuk(const GameAction& action, const std::unique_ptr& result) { - duk_context* ctx = _context; - auto obj = duk_push_object(ctx); + DukStackFrame frame(_context); + DukObject obj(_context); + auto player = action.GetPlayer(); if (player != -1) { - duk_push_int(ctx, action.GetPlayer()); - duk_put_prop_string(ctx, obj, "player"); + obj.Set("player", action.GetPlayer()); } if (result->Cost != MONEY32_UNDEFINED) { - duk_push_int(ctx, result->Cost); - duk_put_prop_string(ctx, obj, "cost"); + obj.Set("cost", result->Cost); } if (!result->Position.isNull()) { - PositionToDuk(result->Position).push(); - duk_put_prop_string(ctx, obj, "position"); + obj.Set("position", PositionToDuk(result->Position)); } - return DukValue::take_from_stack(ctx); + + if (action.GetType() == GAME_COMMAND_CREATE_RIDE) + { + auto& rideCreateResult = static_cast(*result.get()); + if (rideCreateResult.rideIndex != RIDE_ID_NULL) + { + obj.Set("ride", rideCreateResult.rideIndex); + } + } + + return obj.Take(); } bool ScriptEngine::RegisterCustomAction( @@ -809,23 +820,30 @@ 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); + auto hookType = isExecute ? HOOK_TYPE::ACTION_EXECUTE : HOOK_TYPE::ACTION_QUERY; if (_hookEngine.HasSubscriptions(hookType)) { - duk_context* ctx = _context; - auto obj = duk_push_object(ctx); - duk_push_uint(ctx, action.GetType()); - duk_put_prop_string(ctx, obj, "type"); + DukObject obj(_context); + obj.Set("type", action.GetType()); auto flags = action.GetActionFlags(); - duk_push_boolean(ctx, (flags & GA_FLAGS::CLIENT_ONLY) != 0); - duk_put_prop_string(ctx, obj, "isClientOnly"); + obj.Set("isClientOnly", (flags & GA_FLAGS::CLIENT_ONLY) != 0); + + if (action.GetType() == GAME_COMMAND_CREATE_RIDE) + { + auto& rideCreateAction = static_cast(action); + obj.Set("rideType", rideCreateAction.GetRideType()); + obj.Set("rideObject", rideCreateAction.GetRideObject()); + } + + obj.Set("result", GameActionResultToDuk(action, result)); + auto dukEventArgs = obj.Take(); - GameActionResultToDuk(action, result).push(); - duk_put_prop_string(ctx, obj, "result"); - auto dukEventArgs = DukValue::take_from_stack(ctx); _hookEngine.Call(hookType, dukEventArgs, false); if (!isExecute) diff --git a/src/thirdparty/dukglue/dukvalue.h b/src/thirdparty/dukglue/dukvalue.h index 4e505cce05..59092244c5 100644 --- a/src/thirdparty/dukglue/dukvalue.h +++ b/src/thirdparty/dukglue/dukvalue.h @@ -593,7 +593,9 @@ public: { push(); duk_get_prop_string(mContext, -1, key.c_str()); - return DukValue::take_from_stack(mContext); + auto result = DukValue::take_from_stack(mContext); + duk_pop(mContext); + return result; } bool is_array() const @@ -633,4 +635,4 @@ public: duk_pop(mContext); return result; } -}; \ No newline at end of file +}; From fa997006ba171a1fc515776918ef5b541001cfdb Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 5 Mar 2020 23:49:13 +0000 Subject: [PATCH 111/159] Allow console.log to take variable args --- src/openrct2/scripting/ScConsole.hpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index 4f341ca868..b804d349eb 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -33,15 +33,28 @@ namespace OpenRCT2::Scripting _console.Clear(); } - void log(DukValue val) + duk_ret_t log(duk_context* ctx) { - _console.WriteLine(Stringify(val)); + std::string line; + auto nargs = duk_get_top(ctx); + for (duk_idx_t i = 0; i < nargs; i++) + { + auto arg = DukValue::copy_from_stack(ctx, i); + auto argsz = Stringify(arg); + if (i != 0) + { + line.push_back(' '); + } + line += argsz; + } + _console.WriteLine(line); + return 0; } static void Register(duk_context* ctx) { dukglue_register_method(ctx, &ScConsole::clear, "clear"); - dukglue_register_method(ctx, &ScConsole::log, "log"); + dukglue_register_method_varargs(ctx, &ScConsole::log, "log"); } }; } // namespace OpenRCT2::Scripting From 61da82c71118c7146bb00b7eb332998f91623cb5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 6 Mar 2020 00:04:29 +0000 Subject: [PATCH 112/159] Add random number generator --- distribution/openrct2.d.ts | 21 +++++++++++++++++++++ src/openrct2/scripting/ScContext.hpp | 11 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 4990861d66..9c8c2014bc 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -87,6 +87,16 @@ declare global { result: GameActionResult; } + interface RideCreateGameActionResult extends GameActionResult { + readonly ride: number; + } + + interface RideCreateActionEventArgs extends ActionEventArgs { + readonly rideType: number; + readonly rideObject: number; + result: RideCreateGameActionResult; + } + interface NetworkEventArgs { readonly player: number; } @@ -111,6 +121,17 @@ declare global { */ localStorage: Configuration; + /** + * Gets a random integer within the specified range using the game's pseudo- + * random number generator. This is part of the game state and shared across + * all clients, you therefore must be in a context that can mutate the game + * state. Use this to generate random numbers instead of Math.Random during + * game logic routines such as hooks and game actions. + * @param min The minimum value inclusive. + * @param max The maximum value exclusive. + */ + getRandom(min: number, max: number): number; + /** * Registers a new intent (command) that can be mapped to a shortcut. */ diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 75f8abc26f..4e2c43cd3e 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -14,6 +14,7 @@ # include "../actions/CustomAction.hpp" # include "../actions/ParkSetNameAction.hpp" # include "../actions/SmallSceneryPlaceAction.hpp" +# include "../scenario/Scenario.h" # include "Duktape.hpp" # include "HookEngine.h" # include "ScDisposable.hpp" @@ -42,6 +43,15 @@ namespace OpenRCT2::Scripting { } + int32_t getRandom(int32_t min, int32_t max) + { + ThrowIfGameStateNotMutable(); + if (min >= max) + return min; + int32_t range = max - min; + return min + scenario_rand_max(range); + } + std::shared_ptr subscribe(const std::string& hook, const DukValue& callback) { auto hookType = GetHookType(hook); @@ -206,6 +216,7 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { + dukglue_register_method(ctx, &ScContext::getRandom, "getRandom"); dukglue_register_method(ctx, &ScContext::registerIntent, "registerIntent"); dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); dukglue_register_method(ctx, &ScContext::queryAction, "queryAction"); From 0c718869419687c8816de2bf8bef7f4f5e578792 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 6 Mar 2020 20:17:15 +0000 Subject: [PATCH 113/159] 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; From ea8890aaaa391edb877efe3489dc5e5270811483 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 7 Mar 2020 12:37:07 +0000 Subject: [PATCH 114/159] Improve shared storage read / write --- distribution/openrct2.d.ts | 5 - src/openrct2/PlatformEnvironment.cpp | 3 +- src/openrct2/PlatformEnvironment.h | 1 + src/openrct2/scripting/Duktape.hpp | 255 +++++++++++++----------- src/openrct2/scripting/ScriptEngine.cpp | 54 +++-- src/openrct2/scripting/ScriptEngine.h | 1 + 6 files changed, 179 insertions(+), 140 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 13b4cf10cc..a108a60dac 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -116,11 +116,6 @@ declare global { */ sharedStorage: Configuration; - /** - * Local generic storage for a each plugin. - */ - localStorage: Configuration; - /** * Gets a random integer within the specified range using the game's pseudo- * random number generator. This is part of the game state and shared across diff --git a/src/openrct2/PlatformEnvironment.cpp b/src/openrct2/PlatformEnvironment.cpp index 8c5f781301..4b25f4de76 100644 --- a/src/openrct2/PlatformEnvironment.cpp +++ b/src/openrct2/PlatformEnvironment.cpp @@ -240,6 +240,7 @@ const char * PlatformEnvironment::FileNames[] = "highscores.dat", // SCORES "scores.dat", // SCORES (LEGACY) "Saved Games" PATH_SEPARATOR "scores.dat", // SCORES (RCT2) - "changelog.txt" // CHANGELOG + "changelog.txt", // CHANGELOG + "plugin.store.json" // PLUGIN_STORE }; // clang-format on diff --git a/src/openrct2/PlatformEnvironment.h b/src/openrct2/PlatformEnvironment.h index a17974e455..a7024e2921 100644 --- a/src/openrct2/PlatformEnvironment.h +++ b/src/openrct2/PlatformEnvironment.h @@ -66,6 +66,7 @@ namespace OpenRCT2 SCORES_LEGACY, // Scenario scores, legacy (scores.dat). SCORES_RCT2, // Scenario scores, rct2 (\Saved Games\scores.dat). CHANGELOG, // Notable changes to the game between versions, distributed with the game. + PLUGIN_STORE, // Shared storage for plugins. }; /** diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index bead6995f2..06a3c7c516 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -14,147 +14,172 @@ # include # include # include +# include # include -template DukValue GetObjectAsDukValue(duk_context* ctx, const std::shared_ptr& value) +namespace OpenRCT2::Scripting { - dukglue::types::DukType>::template push(ctx, value); - return DukValue::take_from_stack(ctx); -} - -template T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; - -template<> inline std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) -{ - return value.type() == DukValue::STRING ? value.as_string() : defaultValue; -} - -template<> inline int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) -{ - return value.type() == DukValue::NUMBER ? value.as_int() : defaultValue; -} - -/** - * Allows creation of an object on the duktape stack and setting properties on it before - * retrieving the DukValue instance of it. - */ -class DukObject -{ -private: - duk_context* _ctx{}; - duk_idx_t _idx = DUK_INVALID_INDEX; - -public: - DukObject(duk_context* ctx) - : _ctx(ctx) + template DukValue GetObjectAsDukValue(duk_context* ctx, const std::shared_ptr& value) { + dukglue::types::DukType>::template push(ctx, value); + return DukValue::take_from_stack(ctx); } - DukObject(const DukObject&) = delete; + template T AsOrDefault(const DukValue& value, const T& defaultValue = {}) = delete; - DukObject(DukObject&& m) noexcept + template<> inline std::string AsOrDefault(const DukValue& value, const std::string& defaultValue) { - _ctx = m._ctx; - _idx = m._idx; - m._ctx = {}; - m._idx = {}; + return value.type() == DukValue::STRING ? value.as_string() : defaultValue; } - ~DukObject() + template<> inline int32_t AsOrDefault(const DukValue& value, const int32_t& defaultValue) { - PopObjectIfExists(); + return value.type() == DukValue::NUMBER ? value.as_int() : defaultValue; } - void Set(const char* name, bool value) + /** + * Allows creation of an object on the duktape stack and setting properties on it before + * retrieving the DukValue instance of it. + */ + class DukObject { - EnsureObjectPushed(); - duk_push_boolean(_ctx, value); - duk_put_prop_string(_ctx, _idx, name); - } + private: + duk_context* _ctx{}; + duk_idx_t _idx = DUK_INVALID_INDEX; - void Set(const char* name, int32_t value) - { - EnsureObjectPushed(); - duk_push_int(_ctx, value); - duk_put_prop_string(_ctx, _idx, name); - } - - void Set(const char* name, uint32_t value) - { - EnsureObjectPushed(); - duk_push_uint(_ctx, value); - duk_put_prop_string(_ctx, _idx, name); - } - - void Set(const char* name, const std::string_view& value) - { - EnsureObjectPushed(); - duk_push_lstring(_ctx, value.data(), value.size()); - duk_put_prop_string(_ctx, _idx, name); - } - - void Set(const char* name, const DukValue& value) - { - EnsureObjectPushed(); - value.push(); - duk_put_prop_string(_ctx, _idx, name); - } - - DukValue Take() - { - EnsureObjectPushed(); - auto result = DukValue::take_from_stack(_ctx, _idx); - _idx = DUK_INVALID_INDEX; - return result; - } - -private: - void PopObjectIfExists() - { - if (_idx != DUK_INVALID_INDEX) + public: + DukObject(duk_context* ctx) + : _ctx(ctx) { - duk_remove(_ctx, _idx); + } + + DukObject(const DukObject&) = delete; + + DukObject(DukObject&& m) noexcept + { + _ctx = m._ctx; + _idx = m._idx; + m._ctx = {}; + m._idx = {}; + } + + ~DukObject() + { + PopObjectIfExists(); + } + + void Set(const char* name, bool value) + { + EnsureObjectPushed(); + duk_push_boolean(_ctx, value); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, int32_t value) + { + EnsureObjectPushed(); + duk_push_int(_ctx, value); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, uint32_t value) + { + EnsureObjectPushed(); + duk_push_uint(_ctx, value); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, const std::string_view& value) + { + EnsureObjectPushed(); + duk_push_lstring(_ctx, value.data(), value.size()); + duk_put_prop_string(_ctx, _idx, name); + } + + void Set(const char* name, const DukValue& value) + { + EnsureObjectPushed(); + value.push(); + duk_put_prop_string(_ctx, _idx, name); + } + + DukValue Take() + { + EnsureObjectPushed(); + auto result = DukValue::take_from_stack(_ctx, _idx); _idx = DUK_INVALID_INDEX; + return result; } - } - void EnsureObjectPushed() - { - if (_idx == DUK_INVALID_INDEX) + private: + void PopObjectIfExists() { - _idx = duk_push_object(_ctx); + if (_idx != DUK_INVALID_INDEX) + { + duk_remove(_ctx, _idx); + _idx = DUK_INVALID_INDEX; + } } - } -}; -class DukStackFrame -{ -private: - duk_context* _ctx{}; - duk_idx_t _top; - -public: - DukStackFrame(duk_context* ctx) - : _ctx(ctx) - { - _top = duk_get_top(ctx); - } - - ~DukStackFrame() - { - auto top = duk_get_top(_ctx); - if (top != _top) + void EnsureObjectPushed() { - duk_set_top(_ctx, _top); + if (_idx == DUK_INVALID_INDEX) + { + _idx = duk_push_object(_ctx); + } + } + }; + + class DukStackFrame + { + private: + duk_context* _ctx{}; + duk_idx_t _top; + + public: + DukStackFrame(duk_context* ctx) + : _ctx(ctx) + { + _top = duk_get_top(ctx); + } + + ~DukStackFrame() + { + auto top = duk_get_top(_ctx); + if (top != _top) + { + duk_set_top(_ctx, _top); + _ctx = {}; + std::fprintf(stderr, "duktape stack was not returned to original state!"); + // assert(false); + } _ctx = {}; - std::fprintf(stderr, "duktape stack was not returned to original state!"); - // assert(false); } - _ctx = {}; + + DukStackFrame(const DukStackFrame&) = delete; + DukStackFrame(DukStackFrame&&) = delete; + }; + + inline duk_ret_t duk_json_decode_wrapper(duk_context* ctx, void*) + { + duk_json_decode(ctx, -1); + return 1; } - DukStackFrame(const DukStackFrame&) = delete; - DukStackFrame(DukStackFrame&&) = delete; -}; + inline std::optional DuktapeTryParseJson(duk_context* ctx, const std::string_view& json) + { + duk_push_lstring(ctx, json.data(), json.size()); + if (duk_safe_call(ctx, duk_json_decode_wrapper, nullptr, 1, 1) == DUK_EXEC_SUCCESS) + { + return DukValue::take_from_stack(ctx); + } + else + { + // Pop error off stack + duk_pop(ctx); + return std::nullopt; + } + } +} // namespace OpenRCT2::Scripting #endif diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index dbfa8fdd45..af4b9d5968 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -394,9 +394,7 @@ void ScriptEngine::Initialise() _pluginsLoaded = false; _pluginsStarted = false; - duk_push_object(ctx); - _sharedStorage = std::move(DukValue::take_from_stack(ctx)); - LoadSharedStorage(); + InitSharedStorage(); } void ScriptEngine::LoadPlugins() @@ -505,7 +503,7 @@ void ScriptEngine::SetupHotReloading() } catch (const std::exception& e) { - std::printf("Unable to enable hot reloading of plugins: %s\n", e.what()); + std::fprintf(stderr, "Unable to enable hot reloading of plugins: %s\n", e.what()); } } @@ -555,6 +553,8 @@ void ScriptEngine::UnloadPlugins() void ScriptEngine::StartPlugins() { + LoadSharedStorage(); + for (auto& plugin : _plugins) { if (!plugin->HasStarted() && ShouldStartPlugin(plugin)) @@ -713,19 +713,25 @@ std::unique_ptr ScriptEngine::QueryOrExecuteCustomGameAction( // Deserialise the JSON args std::string argsz(args); - duk_push_string(_context, argsz.c_str()); - duk_json_decode(_context, -1); - auto dukArgs = DukValue::take_from_stack(_context); + + auto dukArgs = DuktapeTryParseJson(_context, argsz); + if (!dukArgs) + { + auto action = std::make_unique(); + action->Error = GA_ERROR::INVALID_PARAMETERS; + action->ErrorTitle = "Invalid JSON"; + return action; + } // Ready to call plugin handler DukValue dukResult; if (!isExecute) { - dukResult = ExecutePluginCall(customAction.Owner, customAction.Query, { dukArgs }, false); + dukResult = ExecutePluginCall(customAction.Owner, customAction.Query, { *dukArgs }, false); } else { - dukResult = ExecutePluginCall(customAction.Owner, customAction.Execute, { dukArgs }, true); + dukResult = ExecutePluginCall(customAction.Owner, customAction.Execute, { *dukArgs }, true); } return DukToGameActionResult(dukResult); } @@ -733,7 +739,7 @@ std::unique_ptr ScriptEngine::QueryOrExecuteCustomGameAction( { auto action = std::make_unique(); action->Error = GA_ERROR::UNKNOWN; - action->ErrorTitle = OBJECT_ERROR_UNKNOWN; + action->ErrorTitle = "Unknown custom action"; return action; } } @@ -864,15 +870,25 @@ void ScriptEngine::RunGameActionHooks(const GameAction& action, std::unique_ptr< } } +void ScriptEngine::InitSharedStorage() +{ + duk_push_object(_context); + _sharedStorage = std::move(DukValue::take_from_stack(_context)); +} + void ScriptEngine::LoadSharedStorage() { - std::string path = "C:\\Users\\Ted\\Documents\\OpenRCT2\\plugin.json"; + InitSharedStorage(); + + auto path = _env.GetFilePath(PATHID::PLUGIN_STORE); 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)); + auto result = DuktapeTryParseJson(_context, std::string_view((const char*)data.data(), data.size())); + if (result) + { + _sharedStorage = std::move(*result); + } } catch (const std::exception&) { @@ -881,13 +897,13 @@ void ScriptEngine::LoadSharedStorage() 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"; + auto path = _env.GetFilePath(PATHID::PLUGIN_STORE); try { + _sharedStorage.push(); + auto json = std::string(duk_json_encode(_context, -1)); + duk_pop(_context); + File::WriteAllBytes(path, json.c_str(), json.size()); } catch (const std::exception&) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index c390b3220a..d54ad8d3d2 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -200,6 +200,7 @@ namespace OpenRCT2::Scripting DukValue GameActionResultToDuk(const GameAction& action, const std::unique_ptr& result); DukValue PositionToDuk(const CoordsXYZ& position); + void InitSharedStorage(); void LoadSharedStorage(); }; From 7a62d55c5fbed2148763d7c56adf2eb640557e16 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 7 Mar 2020 13:11:08 +0000 Subject: [PATCH 115/159] Clean up and remove unused APIs --- distribution/openrct2.d.ts | 551 +++++++++++++-------------- distribution/scripting.md | 13 + src/openrct2/scripting/ScContext.hpp | 4 +- 3 files changed, 286 insertions(+), 282 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index a108a60dac..e5f4938404 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -18,6 +18,63 @@ export type PluginType = "local" | "remote"; declare global { + /** + * Global context for accessing all other APIs. + */ + /** APIs for interacting with the stdout console. */ + var console: Console; + /** Core APIs for plugins. */ + var context: Context; + /** APIs for getting or setting the in-game date. */ + var date: GameDate; + /** APIs for manipulating the map. */ + var map: GameMap; + /** APIs for managing the server or interacting with the server or clients. */ + var network: Network; + /** APIs for the park and management of it. */ + var park: Park; + /** + * APIs for controlling the user interface. + * These will only be available to servers and clients that are not running headless mode. + * Plugin writers should check if ui is available using `typeof ui !== 'undefined'`. + */ + var ui: Ui; + + /** + * Registers the plugin. This only only be called once. + * @param metadata Information about the plugin and the entry point. + */ + function registerPlugin(metadata: PluginMetadata): void; + + /** + * Represents a JavaScript object that can or should be disposed when no longer needed. + */ + interface IDisposable { + dispose(): void; + } + + /** + * A coordinate within the game. + * Each in-game tile is a size of 32x32. + */ + interface Coord2 { + x: number; + y: number; + } + + /** + * A coordinate within the game. + * Each in-game tile is a size of 32x32. + * The z-coordinate raises 16 per land increment. A full-height wall is 32 in height. + */ + interface Coord3 extends Coord2 { + z: number; + } + + /** + * Represents information about the plugin such as type, name, author and version. + * It also includes the entry point. + */ interface PluginMetadata { name: string; version: string; @@ -27,84 +84,18 @@ declare global { main: () => void; } + /** + * Console APIs + * Currently interact with stdout. + */ interface Console { clear(): void; log(message?: any, ...optionalParams: any[]): void; } - interface Configuration { - getAll(namespace: string): { [name: string]: any }; - get(key: string): T | undefined; - get(key: string, defaultValue: T): T; - set(key: string, value: T): void; - has(key: string): boolean; - } - - interface Coord2 { - x: number; - y: number; - } - - interface Coord3 { - x: number; - y: number; - z: number; - } - - type HookType = - "interval.tick" | "interval.day" | - "network.chat" | "network.action" | "network.join" | "network.leave"; - - type ExpenditureType = - "ride_construction" | - "ride_runningcosts" | - "land_purchase" | - "landscaping" | - "park_entrance_tickets" | - "park_ride_tickets" | - "shop_sales" | - "shop_stock" | - "food_drink_sales" | - "food_drink_stock" | - "wages" | - "marketing" | - "research" | - "interest"; - - interface GameActionResult { - error?: string; - errorTitle?: string; - errorMessage?: string; - position?: Coord3; - cost?: number; - expenditureType?: ExpenditureType; - } - - interface ActionEventArgs { - readonly player: number; - readonly type: string; - readonly isClientOnly: boolean; - result: GameActionResult; - } - - interface RideCreateGameActionResult extends GameActionResult { - readonly ride: number; - } - - interface RideCreateActionEventArgs extends ActionEventArgs { - readonly rideType: number; - readonly rideObject: number; - result: RideCreateGameActionResult; - } - - interface NetworkEventArgs { - readonly player: number; - } - - interface NetworkChatEventArgs extends NetworkEventArgs { - message: string; - } - + /** + * Core APIs for storage and subscriptions. + */ interface Context { /** * The user's current configuration. @@ -112,7 +103,12 @@ declare global { configuration: Configuration; /** - * Shared generic storage for all plugins. + * Shared generic storage for all plugins. Data is persistant across instances + * of OpenRCT2 and is stored externally as a single JSON file in the OpenRCT2 + * user directory. Internally it is a JavaScript object. Objects and arrays + * are only copied by reference. The external file is only written when using + * the `set` method, do not rely on the file being saved by modifying your own + * objects. Functions and other internal structures will not be persisted. */ sharedStorage: Configuration; @@ -127,11 +123,6 @@ declare global { */ getRandom(min: number, max: number): number; - /** - * Registers a new intent (command) that can be mapped to a shortcut. - */ - registerIntent(desc: IntentDesc): void; - /** * Registers a new game action that allows clients to interact with the game. * @param action The unique name of the action. @@ -139,7 +130,7 @@ declare global { * @param execute Logic for validating and executing the action. * @throws An error if the action has already been registered by this or another plugin. */ - registerGameAction( + registerAction( action: string, query: (args: object) => GameActionResult, execute: (args: object) => GameActionResult): void; @@ -167,8 +158,8 @@ declare global { */ subscribe(hook: HookType, callback: Function): IDisposable; - subscribe(hook: "action.query", callback: (e: ActionEventArgs) => void): IDisposable; - subscribe(hook: "action.execute", callback: (e: ActionEventArgs) => void): IDisposable; + subscribe(hook: "action.query", callback: (e: GameActionEventArgs) => void): IDisposable; + subscribe(hook: "action.execute", callback: (e: GameActionEventArgs) => void): IDisposable; subscribe(hook: "interval.tick", callback: () => void): IDisposable; subscribe(hook: "interval.day", callback: () => void): IDisposable; subscribe(hook: "network.chat", callback: (e: NetworkChatEventArgs) => void): IDisposable; @@ -176,15 +167,114 @@ declare global { subscribe(hook: "network.leave", callback: (e: NetworkEventArgs) => void): IDisposable; } - interface IntentDesc { - key: string; - title?: string; - shortcut?: string; - action: Function; + interface Configuration { + getAll(namespace: string): { [name: string]: any }; + get(key: string): T | undefined; + get(key: string, defaultValue: T): T; + set(key: string, value: T): void; + has(key: string): boolean; } - interface IDisposable { - dispose(): void; + type HookType = + "interval.tick" | "interval.day" | + "network.chat" | "network.action" | "network.join" | "network.leave"; + + type ExpenditureType = + "ride_construction" | + "ride_runningcosts" | + "land_purchase" | + "landscaping" | + "park_entrance_tickets" | + "park_ride_tickets" | + "shop_sales" | + "shop_stock" | + "food_drink_sales" | + "food_drink_stock" | + "wages" | + "marketing" | + "research" | + "interest"; + + interface GameActionEventArgs { + readonly player: number; + readonly type: string; + readonly isClientOnly: boolean; + result: GameActionResult; + } + + interface GameActionResult { + error?: string; + errorTitle?: string; + errorMessage?: string; + position?: Coord3; + cost?: number; + expenditureType?: ExpenditureType; + } + + interface RideCreateGameActionResult extends GameActionResult { + readonly ride: number; + } + + interface RideCreateActionEventArgs extends GameActionEventArgs { + readonly rideType: number; + readonly rideObject: number; + result: RideCreateGameActionResult; + } + + interface NetworkEventArgs { + readonly player: number; + } + + interface NetworkChatEventArgs extends NetworkEventArgs { + message: string; + } + + /** + * APIs for the in-game date. + */ + interface GameDate { + /** + * The total number of ticks that have elapsed since the beginning of the game / scenario. This + * should never reset. + */ + readonly ticksElapsed: number; + /** + * The total number of months that have elapsed. This will equate to 16 on 1st March, Year 2. + * Note: this represents the current date and may be reset by cheats or scripts. + */ + monthsElapsed: number; + /** + * The total number of years that have elapsed. This always equates to (monthsElapsed / 8). + */ + readonly yearsElapsed: number; + + /** + * How far through the month we are between 0 and 65536. This is incremented by 4 each tick, so + * every month takes ~6.8 minutes to complete making a year take just under an hour. + */ + monthProgress: number; + + /** The day of the month from 1 to 31. */ + readonly day: number; + /** The current month of the year from 0 to 7, where 0 is March and 7 is October. */ + readonly month: number; + /** The current year starting from 1. */ + readonly year: number; + } + + /** + * APIs for the map. + */ + interface GameMap { + readonly size: Coord2; + readonly numRides: number; + readonly numThings: number; + readonly rides: Ride[]; + + getRide(id: number): Ride; + getTile(x: number, y: number): Tile; + getThing(id: number): Thing; + getAllThings(type: ThingType); } type TileElementType = @@ -422,19 +512,87 @@ declare global { trousers: number; } - interface GameMap { - readonly size: Coord2; - readonly numRides: number; - readonly numThings: number; - readonly rides: Ride[]; + /** + * Network APIs + * Use `network.status` to determine whether the current game is a client, server or in single player mode. + */ + interface Network { + readonly mode: NetworkMode; + readonly groups: number; + readonly players: number; + defaultGroup: number; - getRide(id: number): Ride; - getTile(x: number, y: number): Tile; - getThing(id: number): Thing; - getAllThings(type: ThingType); + getServerInfo(): ServerInfo; + getGroup(index: number): PlayerGroup; + setGroups(groups: PlayerGroup[]): void; + getPlayer(index: number): Player; + kickPlayer(index: number): void; + sendMessage(message: string): void; + sendMessage(message: string, players: number[]): void; } - type ParkMessageType = + type NetworkMode = "none" | "server" | "client"; + + /** + * Represents a player within a network game. + */ + interface Player { + readonly id: number; + readonly name: string; + group: number; + readonly ping: number; + readonly commandsRan: number; + readonly moneySpent: number; + } + + interface PlayerGroup { + readonly id: number; + name: string; + permissions: PermissionType[]; + } + + interface ServerInfo { + readonly name: string; + readonly description: string; + readonly greeting: string; + readonly providerName: string; + readonly providerEmail: string; + readonly providerWebsite: string; + } + + type PermissionType = + "chat" | + "terraform" | + "set_water_level" | + "toggle_pause" | + "create_ride" | + "remove_ride" | + "build_ride" | + "ride_properties" | + "scenery" | + "path" | + "clear_landscape" | + "guest" | + "staff" | + "park_properties" | + "park_funding" | + "kick_player" | + "modify_groups" | + "set_player_group" | + "cheat" | + "toggle_scenery_cluster" | + "passwordless_login" | + "modify_tile" | + "edit_scenario_options"; + + /** + * Park APIs + */ + + /** + * The type of park message, including icon and behaviour. + */ + type ParkMessageType = "attraction" | "peep_on_attraction" | "peep" | "money" | "blank" | "research" | "guests" | "award" | "chart"; interface ParkMessage { @@ -457,6 +615,20 @@ declare global { * These will only be available to servers and clients that are not running headless mode. * Plugin writers should check if ui is available using `typeof ui !== 'undefined'`. */ + interface Ui { + readonly width: number; + readonly height: number; + readonly windows: number; + readonly mainViewport: Viewport; + + getWindow(id: number): Window; + getWindow(classification: string, id?: number): Window; + openWindow(desc: WindowDesc): Window; + closeWindows(classification: string, id?: number): void; + closeAllWindows(): void; + + registerMenuItem(text: string, callback: () => void): void; + } /** * Represents the type of a widget, e.g. button or label. @@ -554,50 +726,6 @@ declare global { onClose?: () => void; } - type ToolCallbackType = "move" | "press" | "release"; - - interface ToolCallback { - type: ToolCallbackType; - tiles: Coord2[]; - } - - type CursorType = - "arrow" | - "blank" | - "up_arrow" | - "up_down_arrow" | - "hand_point" | - "zzz" | - "diagonal_arrows" | - "picker" | - "tree_down" | - "fountain_down" | - "statue_down" | - "bench_down" | - "cross_hair" | - "bin_down" | - "lamppost_down" | - "fence_down" | - "flower_down" | - "path_down" | - "dig_down" | - "water_down" | - "house_down" | - "volcano_down" | - "walk_down" | - "paint_down" | - "entrance_down" | - "hand_open" | - "hand_closed"; - - interface ToolDesc { - id: string; - cursor: CursorType; - width: number; - height: number; - callback: (e: ToolCallback) => void; - } - interface Viewport { left: number; top: number; @@ -611,141 +739,4 @@ declare global { moveTo(position: Coord2 | Coord3): void; scrollTo(position: Coord2 | Coord3): void; } - - interface Ui { - readonly width: number; - readonly height: number; - readonly windows: number; - readonly mainViewport: Viewport; - - getWindow(id: number): Window; - getWindow(classification: string, id?: number): Window; - openWindow(desc: WindowDesc): Window; - closeWindows(classification: string, id?: number): void; - closeAllWindows(): void; - - activateTool(options: ToolDesc): IDisposable; - registerMenuItem(text: string, callback: () => void): void; - } - - /** - * Network APIs - * Use `network.status` to determine whether the current game is a client, server or in single player mode. - */ - - /** - * Represents a player within a network game. - */ - interface Player { - readonly id: number; - readonly name: string; - group: number; - readonly ping: number; - readonly commandsRan: number; - readonly moneySpent: number; - } - - type PermissionType = - "chat" | - "terraform" | - "set_water_level" | - "toggle_pause" | - "create_ride" | - "remove_ride" | - "build_ride" | - "ride_properties" | - "scenery" | - "path" | - "clear_landscape" | - "guest" | - "staff" | - "park_properties" | - "park_funding" | - "kick_player" | - "modify_groups" | - "set_player_group" | - "cheat" | - "toggle_scenery_cluster" | - "passwordless_login" | - "modify_tile" | - "edit_scenario_options"; - - interface PlayerGroup { - readonly id: number; - name: string; - permissions: PermissionType[]; - } - - interface ServerInfo { - readonly name: string; - readonly description: string; - readonly greeting: string; - readonly providerName: string; - readonly providerEmail: string; - readonly providerWebsite: string; - } - - type NetworkMode = "none" | "server" | "client"; - - interface Network { - readonly mode: NetworkMode; - readonly groups: number; - readonly players: number; - defaultGroup: number; - - getServerInfo(): ServerInfo; - getGroup(index: number): PlayerGroup; - setGroups(groups: PlayerGroup[]): void; - getPlayer(index: number): Player; - kickPlayer(index: number): void; - sendMessage(message: string): void; - sendMessage(message: string, players: number[]): void; - } - - interface GameDate { - /** - * The total number of ticks that have elapsed since the beginning of the game / scenario. This - * should never reset. - */ - readonly ticksElapsed: number; - /** - * The total number of months that have elapsed. This will equate to 16 on 1st March, Year 2. - * Note: this represents the current date and may be reset by cheats or scripts. - */ - monthsElapsed: number; - /** - * The total number of years that have elapsed. This always equates to (monthsElapsed / 8). - */ - readonly yearsElapsed: number; - - /** - * How far through the month we are between 0 and 65536. This is incremented by 4 each tick, so - * every month takes ~6.8 minutes to complete making a year take just under an hour. - */ - monthProgress: number; - - /** The day of the month from 1 to 31. */ - readonly day: number; - /** The current month of the year from 0 to 7, where 0 is March and 7 is October. */ - readonly month: number; - /** The current year starting from 1. */ - readonly year: number; - } - - /** - * Global context for accessing all other APIs. - */ - var console: Console; - var context: Context; - var date: GameDate; - var map: GameMap; - var network: Network; - var park: Park; - var ui: Ui; - - /** - * Registers the plugin. This only only be called once. - * @param metadata Information about the plugin and the entry point. - */ - function registerPlugin(metadata: PluginMetadata): void; } diff --git a/distribution/scripting.md b/distribution/scripting.md index 91e6bd2c76..452093f060 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -137,6 +137,19 @@ Not yet. A lot of the internal code for these windows relies on the widgets exis Yes, remote scripts are uploaded to every client and run as-is. Even if the server is running in headless mode, the script can still contain UI calls for the benefit of the players that are not running in headless mode. Be sure to check if the UI is available first before executing UI calls. +> Can plugins persist data across multiple OpenRCT2 instances? + +Yes, use `context.sharedStorage` to read or write data to an external JSON file: `plugin.store.json` in the OpenRCT2 suer directory. It is recommended that you namespace all your plugin's data under a common name. + +```js +var h = context.sharedStorage.get('IntelOrca.MagicLift.Height'); +if (!h) { + context.sharedStorage.set('IntelOrca.MagicLift.Height', 2); +} +``` + +All plugins have access to the same shared storage. + > Can I use third party JavaScript libraries? Absolutely, just embed the library in your JavaScript file. There are a number of tools to help you do this. diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index c32e9df045..bae9ed2e53 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -206,7 +206,7 @@ namespace OpenRCT2::Scripting } } - void registerGameAction(const std::string& action, const DukValue& query, const DukValue& execute) + void registerAction(const std::string& action, const DukValue& query, const DukValue& execute) { auto& scriptEngine = GetContext()->GetScriptEngine(); auto plugin = scriptEngine.GetExecInfo().GetCurrentPlugin(); @@ -235,7 +235,7 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); dukglue_register_method(ctx, &ScContext::queryAction, "queryAction"); dukglue_register_method(ctx, &ScContext::executeAction, "executeAction"); - dukglue_register_method(ctx, &ScContext::registerGameAction, "registerGameAction"); + dukglue_register_method(ctx, &ScContext::registerAction, "registerAction"); } }; } // namespace OpenRCT2::Scripting From 76ebef10e3dc59539936ab4993f704ebbf0f44b7 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 7 Mar 2020 14:41:29 +0000 Subject: [PATCH 116/159] Add APIs for getting info about loaded objects --- distribution/openrct2.d.ts | 37 ++++++ src/openrct2/scripting/ScContext.hpp | 63 +++++++++- src/openrct2/scripting/ScObject.hpp | 151 ++++++++++++++++++++++++ src/openrct2/scripting/ScRide.hpp | 69 +---------- src/openrct2/scripting/ScriptEngine.cpp | 2 + 5 files changed, 255 insertions(+), 67 deletions(-) create mode 100644 src/openrct2/scripting/ScObject.hpp diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index e5f4938404..498e5fc30a 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -112,6 +112,17 @@ declare global { */ sharedStorage: Configuration; + /** + * Gets the loaded object at the given index. + * @param type The object type. + * @param index The index. + */ + getObject(type: ObjectType, index: number): Object; + getObject(type: "ride", index: number): RideObject; + + getAllObjects(type: ObjectType): Object[]; + getAllObjects(type: "ride"): RideObject[]; + /** * Gets a random integer within the specified range using the game's pseudo- * random number generator. This is part of the game state and shared across @@ -175,6 +186,22 @@ declare global { has(key: string): boolean; } + type ObjectType = + "ride" | + "small_scenery" | + "large_scenery" | + "wall" | + "banner" | + "footpath" | + "footpath_addition" | + "scenery_group" | + "park_entrance" | + "water" | + "terrain_surface" | + "terrain_edge" | + "station" | + "music"; + type HookType = "interval.tick" | "interval.day" | "network.chat" | "network.action" | "network.join" | "network.leave"; @@ -407,6 +434,16 @@ declare global { * Represents the definition of a loaded object (.DAT or .json) such a ride type or scenery item. */ interface Object { + /** + * The object type. + */ + readonly type: ObjectType; + + /** + * The index of the loaded object for the object type. + */ + readonly index: number; + /** * The unique name identifier of the object, e.g. "BURGB ". * This may have trailing spaces if the name is shorter than 8 characters. diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index bae9ed2e53..bed9c62764 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -14,11 +14,13 @@ # include "../actions/CustomAction.hpp" # include "../actions/ParkSetNameAction.hpp" # include "../actions/SmallSceneryPlaceAction.hpp" +# include "../object/ObjectManager.h" # include "../scenario/Scenario.h" # include "Duktape.hpp" # include "HookEngine.h" # include "ScConfiguration.hpp" # include "ScDisposable.hpp" +# include "ScObject.hpp" # include "ScriptEngine.h" # include @@ -51,8 +53,64 @@ namespace OpenRCT2::Scripting return std::make_shared(scriptEngine.GetSharedStorage()); } - void registerIntent(const DukValue& desc) + static DukValue CreateScObject(duk_context* ctx, uint8_t type, int32_t index) { + switch (type) + { + case OBJECT_TYPE_RIDE: + return GetObjectAsDukValue(ctx, std::make_shared(type, index)); + break; + default: + return GetObjectAsDukValue(ctx, std::make_shared(type, index)); + break; + } + } + + DukValue getObject(const std::string& typez, int32_t index) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto& objManager = GetContext()->GetObjectManager(); + + auto type = ScObject::StringToObjectType(typez); + if (type) + { + auto obj = objManager.GetLoadedObject(*type, index); + if (obj != nullptr) + { + return CreateScObject(ctx, *type, index); + } + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Invalid object type."); + } + return {}; + } + + std::vector getAllObjects(const std::string& typez) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto& objManager = GetContext()->GetObjectManager(); + + std::vector result; + auto type = ScObject::StringToObjectType(typez); + if (type) + { + auto count = object_entry_group_counts[*type]; + for (int32_t i = 0; i < count; i++) + { + auto obj = objManager.GetLoadedObject(*type, i); + if (obj != nullptr) + { + result.push_back(CreateScObject(ctx, *type, i)); + } + } + } + else + { + duk_error(ctx, DUK_ERR_ERROR, "Invalid object type."); + } + return result; } int32_t getRandom(int32_t min, int32_t max) @@ -230,8 +288,9 @@ namespace OpenRCT2::Scripting { dukglue_register_property(ctx, &ScContext::configuration_get, nullptr, "configuration"); dukglue_register_property(ctx, &ScContext::sharedStorage_get, nullptr, "sharedStorage"); + dukglue_register_method(ctx, &ScContext::getObject, "getObject"); + dukglue_register_method(ctx, &ScContext::getAllObjects, "getAllObjects"); dukglue_register_method(ctx, &ScContext::getRandom, "getRandom"); - dukglue_register_method(ctx, &ScContext::registerIntent, "registerIntent"); dukglue_register_method(ctx, &ScContext::subscribe, "subscribe"); dukglue_register_method(ctx, &ScContext::queryAction, "queryAction"); dukglue_register_method(ctx, &ScContext::executeAction, "executeAction"); diff --git a/src/openrct2/scripting/ScObject.hpp b/src/openrct2/scripting/ScObject.hpp new file mode 100644 index 0000000000..ee59e0f303 --- /dev/null +++ b/src/openrct2/scripting/ScObject.hpp @@ -0,0 +1,151 @@ +/***************************************************************************** + * 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 "../common.h" +# include "../object/ObjectManager.h" +# include "../object/RideObject.h" +# include "Duktape.hpp" +# include "ScriptEngine.h" + +# include + +namespace OpenRCT2::Scripting +{ + class ScObject + { + private: + uint8_t _type{}; + int32_t _index{}; + + public: + ScObject(uint8_t type, int32_t index) + : _type(type) + , _index(index) + { + } + + static void Register(duk_context* ctx) + { + dukglue_register_property(ctx, &ScObject::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScObject::index_get, nullptr, "index"); + dukglue_register_property(ctx, &ScObject::identifier_get, nullptr, "identifier"); + dukglue_register_property(ctx, &ScObject::name_get, nullptr, "name"); + } + + static std::optional StringToObjectType(const std::string_view& type) + { + for (uint8_t i = 0; i < OBJECT_TYPE_COUNT; i++) + { + auto s = ObjectTypeToString(i); + if (s == type) + { + return i; + } + } + return std::nullopt; + } + + static std::string_view ObjectTypeToString(uint8_t type) + { + static const char* Types[] = { "ride", "small_scenery", "large_scenery", "wall", "banner", + "footpath", "footpath_addition", "scenery_group", "park_entrance", "water", + "stex", "terrain_surface", "terrain_edge", "station", "music" }; + if (type >= std::size(Types)) + return "unknown"; + return Types[type]; + } + + private: + std::string type_get() + { + return std::string(ObjectTypeToString(_type)); + } + + int32_t index_get() + { + return _index; + } + + std::string identifier_get() + { + auto obj = GetObject(); + if (obj != nullptr) + { + return obj->GetIdentifier(); + } + return {}; + } + + std::string name_get() + { + auto obj = GetObject(); + if (obj != nullptr) + { + return obj->GetName(); + } + return {}; + } + + protected: + Object* GetObject() + { + auto& objManager = GetContext()->GetObjectManager(); + return objManager.GetLoadedObject(_type, _index); + } + }; + + class ScRideObject : public ScObject + { + public: + ScRideObject(uint8_t type, int32_t index) + : ScObject(type, index) + { + } + + static void Register(duk_context* ctx) + { + dukglue_set_base_class(ctx); + dukglue_register_property(ctx, &ScRideObject::description_get, nullptr, "description"); + dukglue_register_property(ctx, &ScRideObject::capacity_get, nullptr, "capacity"); + } + + private: + std::string description_get() + { + auto obj = GetObject(); + if (obj != nullptr) + { + return obj->GetDescription(); + } + return {}; + } + + std::string capacity_get() + { + auto obj = GetObject(); + if (obj != nullptr) + { + return obj->GetCapacity(); + } + return {}; + } + + protected: + RideObject* GetObject() + { + return static_cast(ScObject::GetObject()); + } + }; +} // namespace OpenRCT2::Scripting + +#endif diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index c5d1d83b0b..eb46929ef3 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -12,74 +12,13 @@ #ifdef __ENABLE_SCRIPTING__ # include "../common.h" -# include "../object/RideObject.h" # include "../ride/Ride.h" # include "Duktape.hpp" +# include "ScObject.hpp" # include "ScriptEngine.h" namespace OpenRCT2::Scripting { - class ScRideObject - { - private: - rct_ride_entry* _entry{}; - - public: - ScRideObject(rct_ride_entry* entry) - : _entry(entry) - { - } - - static void Register(duk_context* ctx) - { - dukglue_register_property(ctx, &ScRideObject::id_get, nullptr, "identifier"); - dukglue_register_property(ctx, &ScRideObject::name_get, nullptr, "name"); - dukglue_register_property(ctx, &ScRideObject::description_get, nullptr, "description"); - dukglue_register_property(ctx, &ScRideObject::capacity_get, nullptr, "capacity"); - } - - private: - std::string id_get() - { - auto obj = static_cast(_entry->obj); - if (obj != nullptr) - { - return obj->GetIdentifier(); - } - return {}; - } - - std::string name_get() - { - auto obj = static_cast(_entry->obj); - if (obj != nullptr) - { - return obj->GetName(); - } - return {}; - } - - std::string description_get() - { - auto obj = static_cast(_entry->obj); - if (obj != nullptr) - { - return obj->GetDescription(); - } - return {}; - } - - std::string capacity_get() - { - auto obj = static_cast(_entry->obj); - if (obj != nullptr) - { - return obj->GetCapacity(); - } - return {}; - } - }; - class ScRide { private: @@ -102,10 +41,10 @@ namespace OpenRCT2::Scripting auto ride = GetRide(); if (ride != nullptr) { - auto rideEntry = ride->GetRideEntry(); - if (rideEntry != nullptr) + auto rideObject = GetContext()->GetObjectManager().GetLoadedObject(OBJECT_TYPE_RIDE, ride->subtype); + if (rideObject != nullptr) { - return std::make_shared(rideEntry); + return std::make_shared(OBJECT_TYPE_RIDE, ride->subtype); } } return nullptr; diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index af4b9d5968..f1b324bde5 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -27,6 +27,7 @@ # include "ScDisposable.hpp" # include "ScMap.hpp" # include "ScNetwork.hpp" +# include "ScObject.hpp" # include "ScPark.hpp" # include "ScRide.hpp" # include "ScThing.hpp" @@ -373,6 +374,7 @@ void ScriptEngine::Initialise() ScDisposable::Register(ctx); ScMap::Register(ctx); ScNetwork::Register(ctx); + ScObject::Register(ctx); ScPark::Register(ctx); ScPlayer::Register(ctx); ScPlayerGroup::Register(ctx); From 098e6839e23d8f0fa110b028880011643d958c2b Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 7 Mar 2020 16:11:23 +0000 Subject: [PATCH 117/159] Fix build after rebase --- src/openrct2-ui/scripting/CustomWindow.cpp | 11 +++++---- src/openrct2-ui/scripting/ScViewport.hpp | 28 +++++++++++----------- src/openrct2-ui/scripting/ScWindow.hpp | 8 +++---- src/openrct2/scripting/ScTile.hpp | 16 ++++++------- 4 files changed, 31 insertions(+), 32 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index d5299bc9f2..5f7ddd1923 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -415,8 +415,8 @@ namespace OpenRCT2::Ui::Windows set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, items[i].c_str()); } window_dropdown_show_text_custom_width( - w->x + widget->left, w->y + widget->top, widget->bottom - widget->top + 1, w->colours[widget->colour], 0, - DROPDOWN_FLAG_STAY_OPEN, numItems, widget->right - widget->left - 3); + w->windowPos.x + widget->left, w->windowPos.y + widget->top, widget->bottom - widget->top + 1, + w->colours[widget->colour], 0, DROPDOWN_FLAG_STAY_OPEN, numItems, widget->right - widget->left - 3); } else if (widgetDesc->Type == "spinner") { @@ -507,15 +507,16 @@ namespace OpenRCT2::Ui::Windows { if (w->viewport == nullptr) { - auto left = w->x + viewportWidget->left + 1; - auto top = w->y + viewportWidget->top + 1; + auto left = w->windowPos.x + viewportWidget->left + 1; + auto top = w->windowPos.y + viewportWidget->top + 1; auto width = (viewportWidget->right - viewportWidget->left) - 1; auto height = (viewportWidget->bottom - viewportWidget->top) - 1; auto mapX = 0; auto mapY = 0; auto mapZ = 0; viewport_create( - w, left, top, width, height, 0, mapX, mapY, mapZ, VIEWPORT_FOCUS_TYPE_COORDINATE, SPRITE_INDEX_NULL); + w, { left, top }, width, height, 0, { mapX, mapY, mapZ }, VIEWPORT_FOCUS_TYPE_COORDINATE, + SPRITE_INDEX_NULL); w->flags |= WF_NO_SCROLLING; w->Invalidate(); } diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index 012205e12a..3730b9fc40 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -42,7 +42,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - return viewport->view_x; + return viewport->viewPos.x; } return 0; } @@ -51,7 +51,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - SetViewLeftTop(value, viewport->view_y); + SetViewLeftTop(value, viewport->viewPos.y); } } @@ -60,7 +60,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - return viewport->view_y; + return viewport->viewPos.y; } return 0; } @@ -69,7 +69,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - SetViewLeftTop(viewport->view_x, value); + SetViewLeftTop(viewport->viewPos.x, value); } } @@ -78,7 +78,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - return viewport->view_x + viewport->view_width; + return viewport->viewPos.x + viewport->view_width; } return 0; } @@ -87,7 +87,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - SetViewLeftTop(value - viewport->view_width, viewport->view_y); + SetViewLeftTop(value - viewport->view_width, viewport->viewPos.y); } } @@ -96,7 +96,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - return viewport->view_y + viewport->view_height; + return viewport->viewPos.y + viewport->view_height; } return 0; } @@ -105,7 +105,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - SetViewLeftTop(viewport->view_x, value - viewport->view_height); + SetViewLeftTop(viewport->viewPos.x, value - viewport->view_height); } } @@ -177,8 +177,8 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - auto centreX = viewport->view_x + (viewport->view_width / 2); - auto centreY = viewport->view_y + (viewport->view_height / 2); + auto centreX = viewport->viewPos.x + (viewport->view_width / 2); + auto centreY = viewport->viewPos.y + (viewport->view_height / 2); auto coords = viewport_coord_to_map_coord(centreX, centreY, 24); auto ctx = GetContext()->GetScriptEngine().GetContext(); @@ -268,11 +268,11 @@ namespace OpenRCT2::Scripting auto viewport = w->viewport; if (viewport != nullptr) { - viewport->view_x = left; - viewport->view_y = top; + viewport->viewPos.x = left; + viewport->viewPos.y = top; viewport->flags &= ~WF_SCROLLING_TO_LOCATION; - w->saved_view_x = viewport->view_x; - w->saved_view_y = viewport->view_y; + w->savedViewPos.x = viewport->viewPos.x; + w->savedViewPos.y = viewport->viewPos.y; } } } diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index a6067aaccc..9d7e2fbbfb 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -53,21 +53,21 @@ namespace OpenRCT2::Scripting int32_t x_get() { - return GetWindow()->x; + return GetWindow()->windowPos.x; } void x_set(int32_t value) { auto w = GetWindow(); - window_set_position(w, { value, w->y }); + window_set_position(w, { value, w->windowPos.y }); } int32_t y_get() { - return GetWindow()->y; + return GetWindow()->windowPos.y; } void y_set(int32_t value) { auto w = GetWindow(); - window_set_position(w, { w->x, value }); + window_set_position(w, { w->windowPos.x, value }); } int32_t width_get() { diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 55746dacaf..1c0e5aa6df 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -96,18 +96,16 @@ namespace OpenRCT2::Scripting bool broken_get() const { - return _element->flags & TILE_ELEMENT_FLAG_BROKEN; + auto el = _element->AsPath(); + return el != nullptr ? el->IsBroken() : false; } void broken_set(bool value) { ThrowIfGameStateNotMutable(); - if (value) + auto el = _element->AsPath(); + if (el != nullptr) { - _element->flags |= TILE_ELEMENT_FLAG_BROKEN; - } - else - { - _element->flags &= ~TILE_ELEMENT_FLAG_BROKEN; + el->SetIsBroken(value); } } @@ -422,7 +420,7 @@ namespace OpenRCT2::Scripting case TILE_ELEMENT_TYPE_PATH: { auto el = _element->AsPath(); - return el->GetPathEntryIndex(); + return el->GetSurfaceEntryIndex(); } case TILE_ELEMENT_TYPE_SMALL_SCENERY: { @@ -455,7 +453,7 @@ namespace OpenRCT2::Scripting case TILE_ELEMENT_TYPE_PATH: { auto el = _element->AsPath(); - el->SetPathEntryIndex(value & 0xFF); + el->SetSurfaceEntryIndex(value & 0xFF); break; } case TILE_ELEMENT_TYPE_SMALL_SCENERY: From 119b24a6ffd2306b133b99460a018c1cb3ef97ec Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 7 Mar 2020 16:39:08 +0000 Subject: [PATCH 118/159] Show selected index on custom dropdowns --- src/openrct2-ui/scripting/CustomWindow.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 5f7ddd1923..dbf8c724ab 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -407,11 +407,13 @@ namespace OpenRCT2::Ui::Windows if (widgetDesc->Type == "dropdown") { widget--; + auto selectedIndex = widgetDesc->SelectedIndex; const auto& items = widgetDesc->Items; const auto numItems = std::min(items.size(), DROPDOWN_ITEMS_MAX_SIZE); for (size_t i = 0; i < numItems; i++) { - gDropdownItemsFormat[i] = STR_STRING; + gDropdownItemsFormat[i] = selectedIndex == i ? STR_OPTIONS_DROPDOWN_ITEM_SELECTED + : STR_OPTIONS_DROPDOWN_ITEM; set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, items[i].c_str()); } window_dropdown_show_text_custom_width( @@ -437,8 +439,8 @@ namespace OpenRCT2::Ui::Windows if (dropdownIndex == -1) return; - const auto& info = GetInfo(w); - const auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); + auto& info = GetInfo(w); + auto widgetDesc = info.GetCustomWidgetDesc(widgetIndex); if (widgetDesc != nullptr) { if (widgetDesc->Type == "dropdown") @@ -453,6 +455,8 @@ namespace OpenRCT2::Ui::Windows auto& widget = w->widgets[widgetIndex - 1]; widget.string = (utf8*)widgetDesc->Items[dropdownIndex].c_str(); + + widgetDesc->SelectedIndex = dropdownIndex; } } } From b7b1920a794ce5e20f018ab8f2983164c90f6d59 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sat, 7 Mar 2020 22:40:45 +0000 Subject: [PATCH 119/159] Fix build --- src/openrct2-ui/scripting/CustomWindow.cpp | 4 ++-- src/openrct2/actions/MazePlaceTrackAction.hpp | 6 ++++-- src/openrct2/scripting/HookEngine.cpp | 3 +-- src/openrct2/scripting/HookEngine.h | 3 +-- src/openrct2/scripting/ScObject.hpp | 1 + src/openrct2/scripting/ScTile.hpp | 1 + src/openrct2/scripting/ScriptEngine.cpp | 2 +- 7 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index dbf8c724ab..6fd917491b 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -412,8 +412,8 @@ namespace OpenRCT2::Ui::Windows const auto numItems = std::min(items.size(), DROPDOWN_ITEMS_MAX_SIZE); for (size_t i = 0; i < numItems; i++) { - gDropdownItemsFormat[i] = selectedIndex == i ? STR_OPTIONS_DROPDOWN_ITEM_SELECTED - : STR_OPTIONS_DROPDOWN_ITEM; + gDropdownItemsFormat[i] = selectedIndex == (int32_t)i ? STR_OPTIONS_DROPDOWN_ITEM_SELECTED + : STR_OPTIONS_DROPDOWN_ITEM; set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, items[i].c_str()); } window_dropdown_show_text_custom_width( diff --git a/src/openrct2/actions/MazePlaceTrackAction.hpp b/src/openrct2/actions/MazePlaceTrackAction.hpp index 18c723399a..afcb95b551 100644 --- a/src/openrct2/actions/MazePlaceTrackAction.hpp +++ b/src/openrct2/actions/MazePlaceTrackAction.hpp @@ -93,7 +93,8 @@ public: { _loc.ToTileStart(), baseHeight, clearanceHeight }, &map_place_non_scenery_clear_func, { 0b1111, 0 }, GetFlags(), &clearCost, CREATE_CROSSING_MODE_NONE)) { - return MakeResult(GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); + return MakeResult( + GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); } if (gMapGroundFlags & ELEMENT_IS_UNDERWATER) @@ -162,7 +163,8 @@ public: { _loc.ToTileStart(), baseHeight, clearanceHeight }, &map_place_non_scenery_clear_func, { 0b1111, 0 }, GetFlags() | GAME_COMMAND_FLAG_APPLY, &clearCost, CREATE_CROSSING_MODE_NONE)) { - return MakeResult(GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); + return MakeResult( + GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); } money32 price = (((RideTrackCosts[ride->type].track_price * TrackPricing[TRACK_ELEM_MAZE]) >> 16)); diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 74295ec993..8263a88701 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -30,9 +30,8 @@ HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string& name) return (result != LookupTable.end()) ? result->second : HOOK_TYPE::UNDEFINED; } -HookEngine::HookEngine(ScriptEngine& scriptEngine, ScriptExecutionInfo& execInfo) +HookEngine::HookEngine(ScriptEngine& scriptEngine) : _scriptEngine(scriptEngine) - , _execInfo(execInfo) { _hookMap.resize(NUM_HOOK_TYPES); for (size_t i = 0; i < NUM_HOOK_TYPES; i++) diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 6547215866..8f31ab3907 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -72,12 +72,11 @@ namespace OpenRCT2::Scripting { private: ScriptEngine& _scriptEngine; - ScriptExecutionInfo& _execInfo; std::vector _hookMap; uint32_t _nextCookie = 1; public: - HookEngine(ScriptEngine& scriptEngine, ScriptExecutionInfo& execInfo); + HookEngine(ScriptEngine& scriptEngine); HookEngine(const HookEngine&) = delete; uint32_t Subscribe(HOOK_TYPE type, std::shared_ptr owner, const DukValue& function); void Unsubscribe(HOOK_TYPE type, uint32_t cookie); diff --git a/src/openrct2/scripting/ScObject.hpp b/src/openrct2/scripting/ScObject.hpp index ee59e0f303..bd049e767e 100644 --- a/src/openrct2/scripting/ScObject.hpp +++ b/src/openrct2/scripting/ScObject.hpp @@ -11,6 +11,7 @@ #ifdef __ENABLE_SCRIPTING__ +# include "../Context.h" # include "../common.h" # include "../object/ObjectManager.h" # include "../object/RideObject.h" diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 1c0e5aa6df..6adfbb30e3 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -11,6 +11,7 @@ #ifdef __ENABLE_SCRIPTING__ +# include "../Context.h" # include "../common.h" # include "../world/Footpath.h" # include "../world/Scenery.h" diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index f1b324bde5..5ca0c0b990 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -360,7 +360,7 @@ DukContext::~DukContext() ScriptEngine::ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env) : _console(console) , _env(env) - , _hookEngine(*this, _execInfo) + , _hookEngine(*this) { } From b9f3886ca8b2427c5dccf4f5a550145cbb886ebb Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 8 Mar 2020 11:30:57 +0000 Subject: [PATCH 120/159] Implement more footpath APIs --- distribution/openrct2.d.ts | 41 ++--- src/openrct2/scripting/ScTile.hpp | 285 ++++++++++++++++++++++++++++-- 2 files changed, 278 insertions(+), 48 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 498e5fc30a..febc79ba21 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -326,39 +326,20 @@ declare global { readonly hasConstructionRights: boolean; } - interface FootpathAdditionStatus extends BaseTileElement { - north: number; - east: number; - south: number; - west: number; - } - - interface FootpathAddition extends BaseTileElement { - isBin: boolean; - isBench: boolean; - isLamp: boolean; - isBreakable: boolean; - isJumpingFountainWater: boolean; - isJumpingFountainSnow: boolean; - allowedOnQueue: boolean; - allowedOnSlope: boolean; - isQueueScreen: boolean; - status: FootpathAdditionStatus; - - /** - * Remove the path addition - */ - remove(): void; - } - interface FootpathElement extends BaseTileElement { footpathType: number; - isSloped: boolean; + edgesAndCorners: number; + slopeDirection: number | null; + isBlockedByVehicle: boolean; + isWide: boolean; + isQueue: boolean; - addition: FootpathAddition; - edges: number; - corners: number; - rideIndex: number; + queueBannerDirection: number | null; + ride: number; + station: number; + + addition: number | null; + isAdditionBroken: boolean; } interface TrackElement extends BaseTileElement { diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 6adfbb30e3..f931158ea4 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -95,21 +95,6 @@ namespace OpenRCT2::Scripting map_invalidate_tile_full(_coords); } - bool broken_get() const - { - auto el = _element->AsPath(); - return el != nullptr ? el->IsBroken() : false; - } - void broken_set(bool value) - { - ThrowIfGameStateNotMutable(); - auto el = _element->AsPath(); - if (el != nullptr) - { - el->SetIsBroken(value); - } - } - uint8_t baseZ_get() const { return _element->base_height; @@ -327,6 +312,11 @@ namespace OpenRCT2::Scripting { switch (_element->GetType()) { + case TILE_ELEMENT_TYPE_PATH: + { + auto el = _element->AsPath(); + return el->GetRideIndex(); + } case TILE_ELEMENT_TYPE_TRACK: { auto el = _element->AsTrack(); @@ -345,6 +335,12 @@ namespace OpenRCT2::Scripting ThrowIfGameStateNotMutable(); switch (_element->GetType()) { + case TILE_ELEMENT_TYPE_PATH: + { + auto el = _element->AsPath(); + el->SetRideIndex(value); + break; + } case TILE_ELEMENT_TYPE_TRACK: { auto el = _element->AsTrack(); @@ -364,6 +360,11 @@ namespace OpenRCT2::Scripting { switch (_element->GetType()) { + case TILE_ELEMENT_TYPE_PATH: + { + auto el = _element->AsPath(); + return el->GetStationIndex(); + } case TILE_ELEMENT_TYPE_TRACK: { auto el = _element->AsTrack(); @@ -382,6 +383,12 @@ namespace OpenRCT2::Scripting ThrowIfGameStateNotMutable(); switch (_element->GetType()) { + case TILE_ELEMENT_TYPE_PATH: + { + auto el = _element->AsPath(); + el->SetStationIndex(value); + break; + } case TILE_ELEMENT_TYPE_TRACK: { auto el = _element->AsTrack(); @@ -575,6 +582,226 @@ namespace OpenRCT2::Scripting } } + bool railings_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->GetRailingEntryIndex() : false; + } + void railings_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetRailingEntryIndex(value); + } + } + + uint8_t edgesAndCorners_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->GetEdgesAndCorners() : 0; + } + void edgesAndCorners_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetEdgesAndCorners(value); + } + } + + DukValue slopeDirection_get() const + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto el = _element->AsPath(); + if (el != nullptr && el->IsSloped()) + { + auto slope = static_cast(el->GetSlopeDirection()); + duk_push_int(ctx, slope); + return DukValue::take_from_stack(ctx); + } + duk_push_null(ctx); + return DukValue::take_from_stack(ctx); + } + void slopeDirection_set(const DukValue& value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + if (value.type() == DukValue::Type::NUMBER) + { + el->SetSloped(true); + el->SetSlopeDirection(value.as_int()); + } + else + { + el->SetSloped(false); + el->SetSlopeDirection(0); + } + } + } + + bool isQueue_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->IsQueue() : false; + } + void isQueue_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetIsQueue(value); + } + } + + DukValue queueBannerDirection_get() const + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto el = _element->AsPath(); + if (el != nullptr && el->HasQueueBanner()) + { + duk_push_int(ctx, el->GetQueueBannerDirection()); + return DukValue::take_from_stack(ctx); + } + duk_push_null(ctx); + return DukValue::take_from_stack(ctx); + } + void queueBannerDirection_set(const DukValue& value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + if (value.type() == DukValue::Type::NUMBER) + { + el->SetHasQueueBanner(true); + el->SetQueueBannerDirection(value.as_int()); + } + else + { + el->SetHasQueueBanner(false); + el->SetQueueBannerDirection(0); + } + } + } + + bool isBlockedByVehicle_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->IsBlockedByVehicle() : false; + } + void isBlockedByVehicle_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetIsBlockedByVehicle(value); + } + } + + bool isWide_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->IsWide() : false; + } + void isWide_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetWide(value); + } + } + + DukValue addition_get() const + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto el = _element->AsPath(); + if (el != nullptr) + { + auto addition = el->GetAddition(); + if (addition != 0) + { + duk_push_int(ctx, addition - 1); + return DukValue::take_from_stack(ctx); + } + } + duk_push_null(ctx); + return DukValue::take_from_stack(ctx); + } + void addition_set(const DukValue& value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + if (value.type() == DukValue::Type::NUMBER) + { + auto addition = value.as_int(); + if (addition >= 0 && addition <= 254) + { + el->SetAddition(addition + 1); + } + } + else + { + el->SetAddition(0); + } + } + } + + uint8_t additionStatus_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->GetAdditionStatus() : 0; + } + void additionStatus_set(uint8_t value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetAdditionStatus(value); + } + } + + bool isAdditionBroken_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->IsBroken() : false; + } + void isAdditionBroken_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetIsBroken(value); + } + } + + bool isAdditionGhost_get() const + { + auto el = _element->AsPath(); + return el != nullptr ? el->AdditionIsGhost() : false; + } + void isAdditionGhost_set(bool value) + { + ThrowIfGameStateNotMutable(); + auto el = _element->AsPath(); + if (el != nullptr) + { + el->SetAdditionIsGhost(value); + } + } + uint8_t footpathObject_get() { auto el = _element->AsEntrance(); @@ -609,11 +836,13 @@ namespace OpenRCT2::Scripting dukglue_register_property( ctx, &ScTileElement::secondaryColour_get, &ScTileElement::secondaryColour_set, "secondaryColour"); - // Ride | entrance - dukglue_register_property(ctx, &ScTileElement::sequence_get, &ScTileElement::sequence_set, "sequence"); + // Path | track | entrance dukglue_register_property(ctx, &ScTileElement::ride_get, &ScTileElement::ride_set, "ride"); dukglue_register_property(ctx, &ScTileElement::station_get, &ScTileElement::station_set, "station"); + // Track | entrance + dukglue_register_property(ctx, &ScTileElement::sequence_get, &ScTileElement::sequence_set, "sequence"); + // Surface only dukglue_register_property(ctx, &ScTileElement::slope_get, &ScTileElement::slope_set, "slope"); dukglue_register_property(ctx, &ScTileElement::waterHeight_get, &ScTileElement::waterHeight_set, "waterHeight"); @@ -633,7 +862,27 @@ namespace OpenRCT2::Scripting dukglue_register_property(ctx, &ScTileElement::age_get, &ScTileElement::age_set, "age"); // Footpath only - dukglue_register_property(ctx, &ScTileElement::broken_get, &ScTileElement::broken_set, "broken"); + dukglue_register_property(ctx, &ScTileElement::railings_get, &ScTileElement::railings_set, "railings"); + dukglue_register_property( + ctx, &ScTileElement::edgesAndCorners_get, &ScTileElement::edgesAndCorners_set, "edgesAndCorners"); + dukglue_register_property( + ctx, &ScTileElement::slopeDirection_get, &ScTileElement::slopeDirection_set, "slopeDirection"); + dukglue_register_property(ctx, &ScTileElement::isQueue_get, &ScTileElement::isQueue_set, "isQueue"); + dukglue_register_property( + ctx, &ScTileElement::queueBannerDirection_get, &ScTileElement::queueBannerDirection_set, + "queueBannerDirection"); + + dukglue_register_property( + ctx, &ScTileElement::isBlockedByVehicle_get, &ScTileElement::isBlockedByVehicle_set, "isBlockedByVehicle"); + dukglue_register_property(ctx, &ScTileElement::isWide_get, &ScTileElement::isWide_set, "isWide"); + + dukglue_register_property(ctx, &ScTileElement::addition_get, &ScTileElement::addition_set, "addition"); + dukglue_register_property( + ctx, &ScTileElement::additionStatus_get, &ScTileElement::additionStatus_set, "additionStatus"); + dukglue_register_property( + ctx, &ScTileElement::isAdditionBroken_get, &ScTileElement::isAdditionBroken_set, "isAdditionBroken"); + dukglue_register_property( + ctx, &ScTileElement::isAdditionGhost_get, &ScTileElement::isAdditionGhost_set, "isAdditionGhost"); // Entrance only dukglue_register_property( From f12f439309485af9e257aa477e97c31e9917b40c Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 17 Apr 2020 18:41:23 +0100 Subject: [PATCH 121/159] Fix errors after rebase --- src/openrct2-ui/scripting/ScViewport.hpp | 2 +- src/openrct2/scripting/ScMap.hpp | 4 ++-- src/openrct2/scripting/ScTile.hpp | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index 3730b9fc40..52bd9e32b2 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -133,7 +133,7 @@ namespace OpenRCT2::Scripting auto viewport = GetViewport(); if (viewport != nullptr) { - return viewport->zoom; + return static_cast(viewport->zoom); } return 0; } diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 66a9a5ad84..a2be22c481 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -109,7 +109,7 @@ namespace OpenRCT2::Scripting } if (type == "car") { - targetList = SPRITE_LIST_VEHICLE_HEAD; + targetList = SPRITE_LIST_TRAIN_HEAD; } else if (type == "litter") { @@ -147,7 +147,7 @@ namespace OpenRCT2::Scripting { result.push_back(GetObjectAsDukValue(_context, std::make_shared(spriteId))); } - else if (targetList == SPRITE_LIST_VEHICLE_HEAD) + else if (targetList == SPRITE_LIST_TRAIN_HEAD) { auto carId = spriteId; while (carId != SPRITE_INDEX_NULL) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index f931158ea4..e4d17717a3 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -969,7 +969,7 @@ namespace OpenRCT2::Scripting if (numElements > currentNumElements) { // Allocate space for the extra tile elements (inefficient but works) - auto pos = TileCoordsXYZ(TileCoordsXY(_coords), 0); + auto pos = TileCoordsXYZ(TileCoordsXY(_coords), 0).ToCoordsXYZ(); auto numToInsert = numElements - currentNumElements; for (size_t i = 0; i < numToInsert; i++) { @@ -1017,7 +1017,7 @@ namespace OpenRCT2::Scripting { std::vector data(first, first + origNumElements); - auto pos = TileCoordsXYZ(TileCoordsXY(_coords), 0); + auto pos = TileCoordsXYZ(TileCoordsXY(_coords), 0).ToCoordsXYZ(); auto newElement = tile_element_insert(pos, 0); if (newElement == nullptr) { From a8bb0e59ec544bd7455a7404192d102bb72d1bd6 Mon Sep 17 00:00:00 2001 From: Michael Steenbeek Date: Fri, 17 Apr 2020 21:05:35 +0200 Subject: [PATCH 122/159] Update Xcode project --- OpenRCT2.xcodeproj/project.pbxproj | 91 ++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 5 deletions(-) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index ae175c6493..c7ea0d78b3 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -43,6 +43,9 @@ 2ADE2F3622441960002598AF /* RideTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = 2ADE2F352244195F002598AF /* RideTypes.h */; }; 2ADE2F382244198B002598AF /* SpriteBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 2ADE2F372244198A002598AF /* SpriteBase.h */; }; 304FE95023A2996600470197 /* SceneryScatter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 304FE94F23A2996600470197 /* SceneryScatter.cpp */; }; + 4C255958244A328B00CE7E45 /* CustomMenu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C25594F244A328A00CE7E45 /* CustomMenu.cpp */; }; + 4C255959244A328B00CE7E45 /* UiExtensions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C255954244A328A00CE7E45 /* UiExtensions.cpp */; }; + 4C25595A244A328B00CE7E45 /* CustomWindow.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C255957244A328B00CE7E45 /* CustomWindow.cpp */; }; 4C29DEB3218C6AE500E8707F /* RCT12.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C29DEB2218C6AE500E8707F /* RCT12.cpp */; }; 4C358E5221C445F700ADE6BC /* ReplayManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C358E5021C445F700ADE6BC /* ReplayManager.cpp */; }; 4C3B4236205914F7000C5BB7 /* InGameConsole.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C3B4234205914F7000C5BB7 /* InGameConsole.cpp */; }; @@ -648,8 +651,37 @@ 2ADE2F352244195F002598AF /* RideTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RideTypes.h; sourceTree = ""; }; 2ADE2F372244198A002598AF /* SpriteBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpriteBase.h; sourceTree = ""; }; 304FE94F23A2996600470197 /* SceneryScatter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SceneryScatter.cpp; sourceTree = ""; }; - 4C04D69F2056AA9600F82EBA /* linenoise.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = linenoise.hpp; sourceTree = ""; }; 4C1A53EC205FD19F000F8EF5 /* SceneryObject.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SceneryObject.cpp; sourceTree = ""; }; + 4C25594E244A328A00CE7E45 /* CustomWindow.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CustomWindow.h; path = scripting/CustomWindow.h; sourceTree = ""; }; + 4C25594F244A328A00CE7E45 /* CustomMenu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CustomMenu.cpp; path = scripting/CustomMenu.cpp; sourceTree = ""; }; + 4C255950244A328A00CE7E45 /* ScUi.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ScUi.hpp; path = scripting/ScUi.hpp; sourceTree = ""; }; + 4C255951244A328A00CE7E45 /* ScWidget.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ScWidget.hpp; path = scripting/ScWidget.hpp; sourceTree = ""; }; + 4C255952244A328A00CE7E45 /* ScWindow.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ScWindow.hpp; path = scripting/ScWindow.hpp; sourceTree = ""; }; + 4C255953244A328A00CE7E45 /* CustomMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CustomMenu.h; path = scripting/CustomMenu.h; sourceTree = ""; }; + 4C255954244A328A00CE7E45 /* UiExtensions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = UiExtensions.cpp; path = scripting/UiExtensions.cpp; sourceTree = ""; }; + 4C255955244A328A00CE7E45 /* ScViewport.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ScViewport.hpp; path = scripting/ScViewport.hpp; sourceTree = ""; }; + 4C255956244A328B00CE7E45 /* UiExtensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UiExtensions.h; path = scripting/UiExtensions.h; sourceTree = ""; }; + 4C255957244A328B00CE7E45 /* CustomWindow.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CustomWindow.cpp; path = scripting/CustomWindow.cpp; sourceTree = ""; }; + 4C25595C244A32E400CE7E45 /* filesystem.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = filesystem.hpp; path = src/thirdparty/filesystem.hpp; sourceTree = SOURCE_ROOT; }; + 4C25595D244A32E400CE7E45 /* linenoise.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = linenoise.hpp; path = src/thirdparty/linenoise.hpp; sourceTree = SOURCE_ROOT; }; + 4C25595F244A330700CE7E45 /* detail_stack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_stack.h; path = src/thirdparty/dukglue/detail_stack.h; sourceTree = SOURCE_ROOT; }; + 4C255960244A330700CE7E45 /* register_class.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = register_class.h; path = src/thirdparty/dukglue/register_class.h; sourceTree = SOURCE_ROOT; }; + 4C255961244A330700CE7E45 /* dukvalue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dukvalue.h; path = src/thirdparty/dukglue/dukvalue.h; sourceTree = SOURCE_ROOT; }; + 4C255962244A330700CE7E45 /* detail_primitive_types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_primitive_types.h; path = src/thirdparty/dukglue/detail_primitive_types.h; sourceTree = SOURCE_ROOT; }; + 4C255963244A330700CE7E45 /* dukglue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dukglue.h; path = src/thirdparty/dukglue/dukglue.h; sourceTree = SOURCE_ROOT; }; + 4C255964244A330700CE7E45 /* detail_class_proto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_class_proto.h; path = src/thirdparty/dukglue/detail_class_proto.h; sourceTree = SOURCE_ROOT; }; + 4C255965244A330700CE7E45 /* detail_traits.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_traits.h; path = src/thirdparty/dukglue/detail_traits.h; sourceTree = SOURCE_ROOT; }; + 4C255966244A330700CE7E45 /* register_function.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = register_function.h; path = src/thirdparty/dukglue/register_function.h; sourceTree = SOURCE_ROOT; }; + 4C255967244A330700CE7E45 /* detail_function.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_function.h; path = src/thirdparty/dukglue/detail_function.h; sourceTree = SOURCE_ROOT; }; + 4C255968244A330700CE7E45 /* detail_types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_types.h; path = src/thirdparty/dukglue/detail_types.h; sourceTree = SOURCE_ROOT; }; + 4C255969244A330800CE7E45 /* detail_constructor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_constructor.h; path = src/thirdparty/dukglue/detail_constructor.h; sourceTree = SOURCE_ROOT; }; + 4C25596A244A330800CE7E45 /* public_util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = public_util.h; path = src/thirdparty/dukglue/public_util.h; sourceTree = SOURCE_ROOT; }; + 4C25596B244A330800CE7E45 /* detail_refs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_refs.h; path = src/thirdparty/dukglue/detail_refs.h; sourceTree = SOURCE_ROOT; }; + 4C25596C244A330800CE7E45 /* register_property.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = register_property.h; path = src/thirdparty/dukglue/register_property.h; sourceTree = SOURCE_ROOT; }; + 4C25596D244A330800CE7E45 /* detail_method.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_method.h; path = src/thirdparty/dukglue/detail_method.h; sourceTree = SOURCE_ROOT; }; + 4C25596E244A330800CE7E45 /* dukexception.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dukexception.h; path = src/thirdparty/dukglue/dukexception.h; sourceTree = SOURCE_ROOT; }; + 4C25596F244A330800CE7E45 /* detail_typeinfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = detail_typeinfo.h; path = src/thirdparty/dukglue/detail_typeinfo.h; sourceTree = SOURCE_ROOT; }; + 4C255971244A342900CE7E45 /* CustomAction.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = CustomAction.hpp; sourceTree = ""; }; 4C29DEB2218C6AE500E8707F /* RCT12.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RCT12.cpp; sourceTree = ""; }; 4C358E5021C445F700ADE6BC /* ReplayManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ReplayManager.cpp; sourceTree = ""; }; 4C358E5121C445F700ADE6BC /* ReplayManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ReplayManager.h; sourceTree = ""; }; @@ -1825,12 +1857,56 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 4C04D69E2056AA5C00F82EBA /* thirdparty */ = { + 4C25594D244A326100CE7E45 /* scripting */ = { isa = PBXGroup; children = ( - 4C04D69F2056AA9600F82EBA /* linenoise.hpp */, + 4C25594F244A328A00CE7E45 /* CustomMenu.cpp */, + 4C255953244A328A00CE7E45 /* CustomMenu.h */, + 4C255957244A328B00CE7E45 /* CustomWindow.cpp */, + 4C25594E244A328A00CE7E45 /* CustomWindow.h */, + 4C255950244A328A00CE7E45 /* ScUi.hpp */, + 4C255955244A328A00CE7E45 /* ScViewport.hpp */, + 4C255951244A328A00CE7E45 /* ScWidget.hpp */, + 4C255952244A328A00CE7E45 /* ScWindow.hpp */, + 4C255954244A328A00CE7E45 /* UiExtensions.cpp */, + 4C255956244A328B00CE7E45 /* UiExtensions.h */, ); - path = thirdparty; + name = scripting; + sourceTree = ""; + }; + 4C25595B244A32A800CE7E45 /* thirdparty */ = { + isa = PBXGroup; + children = ( + 4C25595E244A32EA00CE7E45 /* dukglue */, + 4C25595C244A32E400CE7E45 /* filesystem.hpp */, + 4C25595D244A32E400CE7E45 /* linenoise.hpp */, + ); + name = thirdparty; + path = openrct2; + sourceTree = ""; + }; + 4C25595E244A32EA00CE7E45 /* dukglue */ = { + isa = PBXGroup; + children = ( + 4C255964244A330700CE7E45 /* detail_class_proto.h */, + 4C255969244A330800CE7E45 /* detail_constructor.h */, + 4C255967244A330700CE7E45 /* detail_function.h */, + 4C25596D244A330800CE7E45 /* detail_method.h */, + 4C255962244A330700CE7E45 /* detail_primitive_types.h */, + 4C25596B244A330800CE7E45 /* detail_refs.h */, + 4C25595F244A330700CE7E45 /* detail_stack.h */, + 4C255965244A330700CE7E45 /* detail_traits.h */, + 4C25596F244A330800CE7E45 /* detail_typeinfo.h */, + 4C255968244A330700CE7E45 /* detail_types.h */, + 4C25596E244A330800CE7E45 /* dukexception.h */, + 4C255963244A330700CE7E45 /* dukglue.h */, + 4C255961244A330700CE7E45 /* dukvalue.h */, + 4C25596A244A330800CE7E45 /* public_util.h */, + 4C255960244A330700CE7E45 /* register_class.h */, + 4C255966244A330700CE7E45 /* register_function.h */, + 4C25596C244A330800CE7E45 /* register_property.h */, + ); + name = dukglue; sourceTree = ""; }; 933CBDB820CB1B3F00134678 /* title */ = { @@ -2111,6 +2187,7 @@ 932A211722D73CF900C57EDB /* BannerSetStyleAction.hpp */, 932A211622D73CF900C57EDB /* ClearAction.hpp */, 932A20DE22D73CF000C57EDB /* ClimateSetAction.hpp */, + 4C255971244A342900CE7E45 /* CustomAction.hpp */, 932A20F722D73CF300C57EDB /* FootpathPlaceAction.hpp */, 932A20DB22D73CF000C57EDB /* FootpathPlaceFromTrackAction.hpp */, 932A20F322D73CF300C57EDB /* FootpathRemoveAction.hpp */, @@ -2225,6 +2302,7 @@ D41B72431C21015A0080A7B9 /* Sources */ = { isa = PBXGroup; children = ( + 4C25595B244A32A800CE7E45 /* thirdparty */, F76C85801EC4E82600FA49E2 /* openrct2-ui */, F76C857C1EC4E80E00FA49E2 /* openrct2-cli */, F76C83551EC4E7CC00FA49E2 /* libopenrct2 */, @@ -2527,7 +2605,6 @@ F76C846C1EC4E7CC00FA49E2 /* rct12 */, F76C84831EC4E7CC00FA49E2 /* ride */, F76C84F31EC4E7CD00FA49E2 /* scenario */, - 4C04D69E2056AA5C00F82EBA /* thirdparty */, F76C84FB1EC4E7CD00FA49E2 /* title */, F76C85041EC4E7CD00FA49E2 /* ui */, F76C85061EC4E7CD00FA49E2 /* util */, @@ -3295,6 +3372,7 @@ F76C858D1EC4E82600FA49E2 /* drawing */, F7CB86451EEDA1200030C877 /* input */, C68313CF1FDB4F4C006DB3D8 /* interface */, + 4C25594D244A326100CE7E45 /* scripting */, 933CBDB820CB1B3F00134678 /* title */, F7CB86401EEDA0E20030C877 /* windows */, F76C858A1EC4E82600FA49E2 /* CursorData.cpp */, @@ -3826,6 +3904,7 @@ 9346F9DB208A191900C77D91 /* GuestPathfinding.cpp in Sources */, C654DF361F69C0430040F43D /* Player.cpp in Sources */, 933F2CB720935653001B33FD /* LocalisationService.cpp in Sources */, + 4C255958244A328B00CE7E45 /* CustomMenu.cpp in Sources */, F76C88791EC5324E00FA49E2 /* AudioContext.cpp in Sources */, C666EE7A1F37ACB10061AA04 /* Themes.cpp in Sources */, C666EE7F1F37ACB10061AA04 /* Viewport.cpp in Sources */, @@ -3890,6 +3969,7 @@ C666ED761F33DBB20061AA04 /* ShortcutKeyChange.cpp in Sources */, 304FE95023A2996600470197 /* SceneryScatter.cpp in Sources */, C685E51C1F8907850090598F /* Map.cpp in Sources */, + 4C255959244A328B00CE7E45 /* UiExtensions.cpp in Sources */, F7CB864A1EEDA1330030C877 /* KeyboardShortcuts.cpp in Sources */, 01C6F0C922FD51FC0057E2F7 /* T6Importer.cpp in Sources */, 4CC5258223A19C2900D4366D /* TrackDesignAction.cpp in Sources */, @@ -3921,6 +4001,7 @@ C654DF301F69C0430040F43D /* Finances.cpp in Sources */, 9308DA01209908090079EE96 /* Surface.cpp in Sources */, 933CBDBF20CB1BCA00134678 /* Window.cpp in Sources */, + 4C25595A244A328B00CE7E45 /* CustomWindow.cpp in Sources */, C68878C320289B710084B384 /* DrawRectShader.cpp in Sources */, C666EE751F37ACB10061AA04 /* NewsOptions.cpp in Sources */, C654DF311F69C0430040F43D /* GuestList.cpp in Sources */, From 4a21c7df92cc73734461bf9c3ba9874e7314c11d Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Wed, 11 Mar 2020 11:26:14 +0100 Subject: [PATCH 123/159] Add duktape library to the Xcode project. --- OpenRCT2.xcodeproj/project.pbxproj | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index c7ea0d78b3..122c803511 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -129,6 +129,10 @@ 93F9DA3920B46FB800D1BE92 /* ObjectJsonHelpers.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4CE9AAAB1FDA7B14004093C6 /* ObjectJsonHelpers.cpp */; }; 93F9DA3A20B46FCA00D1BE92 /* SceneryObject.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C1A53EC205FD19F000F8EF5 /* SceneryObject.cpp */; }; 93F9DA3B20B4701100D1BE92 /* StdInOutConsole.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C3B423720591513000C5BB7 /* StdInOutConsole.cpp */; }; + 93FC08FF2418F3ED00CA3054 /* duktape.h in Headers */ = {isa = PBXBuildFile; fileRef = 93FC08FD2418F3ED00CA3054 /* duktape.h */; }; + 93FC09002418F3ED00CA3054 /* duk_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 93FC08FE2418F3ED00CA3054 /* duk_config.h */; }; + 93FC09022418F3F500CA3054 /* libduktape.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 93FC09012418F3F500CA3054 /* libduktape.dylib */; }; + 93FC09032418F41700CA3054 /* libduktape.dylib in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 93FC09012418F3F500CA3054 /* libduktape.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; C61ADB1F1FB6A0A70024F2EF /* TopToolbar.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C61ADB1E1FB6A0A60024F2EF /* TopToolbar.cpp */; }; C61ADB211FB7DC060024F2EF /* Scenery.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C61ADB201FB7DC060024F2EF /* Scenery.cpp */; }; C61ADB231FBBCB8B0024F2EF /* GameBottomToolbar.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C61ADB221FBBCB8A0024F2EF /* GameBottomToolbar.cpp */; }; @@ -587,6 +591,7 @@ 933F32EB24183CBB008376CE /* libicuuc.dylib in Embed Frameworks */, C6E96E371E040E040076A04F /* libzip.dylib in Embed Frameworks */, D45A39591CF300AF00659A24 /* libcrypto.dylib in Embed Frameworks */, + 93FC09032418F41700CA3054 /* libduktape.dylib in Embed Frameworks */, D45A395A1CF300AF00659A24 /* libfreetype.dylib in Embed Frameworks */, D45A395B1CF300AF00659A24 /* libjansson.dylib in Embed Frameworks */, D4A8B4B51DB4188D007A2F29 /* libpng16.dylib in Embed Frameworks */, @@ -1309,6 +1314,9 @@ 93F76EFC20BFF77A00D4512C /* Paint.Banner.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Paint.Banner.cpp; sourceTree = ""; }; 93F76EFD20BFF77A00D4512C /* Paint.TileElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Paint.TileElement.cpp; sourceTree = ""; }; 93F76EFE20BFF77A00D4512C /* Paint.Entrance.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Paint.Entrance.cpp; sourceTree = ""; }; + 93FC08FD2418F3ED00CA3054 /* duktape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = duktape.h; sourceTree = ""; }; + 93FC08FE2418F3ED00CA3054 /* duk_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = duk_config.h; sourceTree = ""; }; + 93FC09012418F3F500CA3054 /* libduktape.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; path = libduktape.dylib; sourceTree = ""; }; C61ADB1E1FB6A0A60024F2EF /* TopToolbar.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TopToolbar.cpp; sourceTree = ""; }; C61ADB201FB7DC060024F2EF /* Scenery.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Scenery.cpp; sourceTree = ""; }; C61ADB221FBBCB8A0024F2EF /* GameBottomToolbar.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GameBottomToolbar.cpp; sourceTree = ""; }; @@ -1824,6 +1832,7 @@ D41B73EF1C2101890080A7B9 /* libcurl.tbd in Frameworks */, D41B741D1C210A7A0080A7B9 /* libiconv.tbd in Frameworks */, D45A38BC1CF3006400659A24 /* libcrypto.dylib in Frameworks */, + 93FC09022418F3F500CA3054 /* libduktape.dylib in Frameworks */, 933F32EC24183CBB008376CE /* libicudata.dylib in Frameworks */, D45A38BE1CF3006400659A24 /* libjansson.dylib in Frameworks */, 933F32EA24183CBB008376CE /* libicuuc.dylib in Frameworks */, @@ -2549,6 +2558,8 @@ D45A39161CF3007A00659A24 /* SDL2 */, D45A39521CF3007A00659A24 /* speex */, 9350B44320B46E0800897BC5 /* unicode */, + 93FC08FE2418F3ED00CA3054 /* duk_config.h */, + 93FC08FD2418F3ED00CA3054 /* duktape.h */, D45A38C41CF3007A00659A24 /* jansson_config.h */, D45A38C51CF3007A00659A24 /* jansson.h */, C6E96E331E0408A80076A04F /* zip.h */, @@ -2561,6 +2572,7 @@ isa = PBXGroup; children = ( D45A38B31CF3006400659A24 /* libcrypto.dylib */, + 93FC09012418F3F500CA3054 /* libduktape.dylib */, D45A38B41CF3006400659A24 /* libfreetype.dylib */, 933F32E924183CBB008376CE /* libicudata.dylib */, 933F32E824183CBB008376CE /* libicuuc.dylib */, @@ -3587,9 +3599,11 @@ 93CBA4C320A7502E00867D56 /* Imaging.h in Headers */, 2ADE2F2B224418B2002598AF /* JobPool.hpp in Headers */, 2ADE2F3622441960002598AF /* RideTypes.h in Headers */, + 93FC08FF2418F3ED00CA3054 /* duktape.h in Headers */, 9308DA05209908090079EE96 /* Surface.h in Headers */, 93DE9753209C3C1000FB1CC8 /* GameState.h in Headers */, 2ADE2F2A224418B2002598AF /* Meta.hpp in Headers */, + 93FC09002418F3ED00CA3054 /* duk_config.h in Headers */, C6352B841F477022006CCEE3 /* DataSerialiser.h in Headers */, 939A35A020C12FDE00630B3F /* Paint.TileElement.h in Headers */, C67B28162002D67A00109C93 /* Window.h in Headers */, From 9ea056a83f0d619a49dd6096b021096b0b12bf5f Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Wed, 11 Mar 2020 11:40:15 +0100 Subject: [PATCH 124/159] Change Xcode dependencies bundle to download to v23. --- OpenRCT2.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index 122c803511..d705605be1 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -3782,7 +3782,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "version=\"22\"\nzipname=\"openrct2-libs-v22-x64-macos-dylibs.zip\"\nliburl=\"https://github.com/OpenRCT2/Dependencies/releases/download/v$version/$zipname\"\n\n[[ ! -d \"${SRCROOT}/libxc\" || ! -e \"${SRCROOT}/libversion\" || $(head -n 1 \"${SRCROOT}/libversion\") != $version ]]\noutdated=$?\n\nif [[ $outdated -eq 0 ]]; then\nif [[ -d \"${SRCROOT}/libxc\" ]]; then rm -r \"${SRCROOT}/libxc\"; fi\nmkdir \"${SRCROOT}/libxc\"\n\ncurl -L -o \"${SRCROOT}/libxc/$zipname\" \"$liburl\"\nunzip -uaq -d \"${SRCROOT}/libxc\" \"${SRCROOT}/libxc/$zipname\"\nrm \"${SRCROOT}/libxc/$zipname\"\n\necho $version > \"${SRCROOT}/libversion\"\nfi\n"; + shellScript = "version=\"23\"\nzipname=\"openrct2-libs-v23-x64-macos-dylibs.zip\"\nliburl=\"https://github.com/OpenRCT2/Dependencies/releases/download/v$version/$zipname\"\n\n[[ ! -d \"${SRCROOT}/libxc\" || ! -e \"${SRCROOT}/libversion\" || $(head -n 1 \"${SRCROOT}/libversion\") != $version ]]\noutdated=$?\n\nif [[ $outdated -eq 0 ]]; then\nif [[ -d \"${SRCROOT}/libxc\" ]]; then rm -r \"${SRCROOT}/libxc\"; fi\nmkdir \"${SRCROOT}/libxc\"\n\ncurl -L -o \"${SRCROOT}/libxc/$zipname\" \"$liburl\"\nunzip -uaq -d \"${SRCROOT}/libxc\" \"${SRCROOT}/libxc/$zipname\"\nrm \"${SRCROOT}/libxc/$zipname\"\n\necho $version > \"${SRCROOT}/libversion\"\nfi\n"; }; D42C09D21C254F4E00309751 /* Build g2.dat */ = { isa = PBXShellScriptBuildPhase; From 3c424be18058ed2f430f818cacd6e96ab8bbcac2 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 19 Apr 2020 23:14:56 +0100 Subject: [PATCH 125/159] Use correct thing type for getThing --- src/openrct2/scripting/ScMap.hpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index a2be22c481..fa293b713a 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -84,7 +84,7 @@ namespace OpenRCT2::Scripting return std::make_shared(coords); } - std::shared_ptr getThing(int32_t id) + DukValue getThing(int32_t id) { if (id >= 0 && id < MAX_SPRITES) { @@ -92,10 +92,11 @@ namespace OpenRCT2::Scripting auto sprite = get_sprite(spriteId); if (sprite != nullptr && sprite->generic.sprite_identifier != SPRITE_IDENTIFIER_NULL) { - return std::make_shared(spriteId); + return GetThingAsDukValue(sprite); } } - return nullptr; + duk_push_null(_context); + return DukValue::take_from_stack(_context); } std::vector getAllThings(const std::string& type) @@ -186,6 +187,19 @@ namespace OpenRCT2::Scripting dukglue_register_method(ctx, &ScMap::getThing, "getThing"); dukglue_register_method(ctx, &ScMap::getAllThings, "getAllThings"); } + + private: + DukValue GetThingAsDukValue(const rct_sprite* sprite) + { + auto spriteId = sprite->generic.sprite_index; + switch (sprite->generic.sprite_identifier) + { + case SPRITE_IDENTIFIER_PEEP: + return GetObjectAsDukValue(_context, std::make_shared(spriteId)); + default: + return GetObjectAsDukValue(_context, std::make_shared(spriteId)); + } + } }; } // namespace OpenRCT2::Scripting From 940cd6db73fc792183bed4488da22707f7f92561 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 19 Apr 2020 23:17:04 +0100 Subject: [PATCH 126/159] Fix type for isChecked in d.ts --- distribution/openrct2.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index febc79ba21..219ee8ead4 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -672,7 +672,7 @@ declare global { interface CheckboxWidget extends Widget { text: string; - isChecked: number; + isChecked: boolean; onChanged: (isChecked: boolean) => void; } From e1c08defc87f4efd5019e66f30fd5a5b54dbf3cf Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 20 Apr 2020 23:30:37 +0100 Subject: [PATCH 127/159] Remove use of std::variant --- src/openrct2-ui/windows/RideConstruction.cpp | 2 +- src/openrct2-ui/windows/TopToolbar.cpp | 4 +- src/openrct2/actions/GameAction.cpp | 8 +-- src/openrct2/actions/GameAction.h | 58 ++++++++++++++++++- src/openrct2/actions/GameActionCompat.cpp | 4 +- src/openrct2/actions/LandSmoothAction.hpp | 2 +- src/openrct2/actions/MazePlaceTrackAction.hpp | 6 +- src/openrct2/actions/MazeSetTrackAction.hpp | 2 +- src/openrct2/world/Map.cpp | 4 +- 9 files changed, 70 insertions(+), 20 deletions(-) diff --git a/src/openrct2-ui/windows/RideConstruction.cpp b/src/openrct2-ui/windows/RideConstruction.cpp index f875773cc6..8eba60739c 100644 --- a/src/openrct2-ui/windows/RideConstruction.cpp +++ b/src/openrct2-ui/windows/RideConstruction.cpp @@ -1824,7 +1824,7 @@ static void window_ride_construction_construct(rct_window* w) // Used by some functions if (res->Error != GA_ERROR::OK) { - if (auto error = std::get_if(&res->ErrorMessage)) + if (auto error = res->ErrorMessage.AsStringId()) gGameCommandErrorText = *error; else gGameCommandErrorText = STR_NONE; diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index dc04ebfb0b..e67a515a7c 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -1947,7 +1947,7 @@ static void window_top_toolbar_scenery_tool_down(int16_t x, int16_t y, rct_windo break; } - if (auto message = std::get_if(&res->ErrorMessage)) + if (auto message = res->ErrorMessage.AsStringId()) { if (*message == STR_NOT_ENOUGH_CASH_REQUIRES || *message == STR_CAN_ONLY_BUILD_THIS_ON_WATER) { @@ -2000,7 +2000,7 @@ static void window_top_toolbar_scenery_tool_down(int16_t x, int16_t y, rct_windo break; } - if (auto message = std::get_if(&res->ErrorMessage)) + if (auto message = res->ErrorMessage.AsStringId()) { if (*message == STR_NOT_ENOUGH_CASH_REQUIRES || *message == STR_CAN_ONLY_BUILD_THIS_ON_WATER) { diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index 00ce2751a4..b24c48de82 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -53,13 +53,13 @@ GameActionResult::GameActionResult(GA_ERROR error, rct_string_id title, rct_stri std::string GameActionResult::GetErrorTitle() const { std::string titlez; - if (auto title = std::get_if(&ErrorTitle)) + if (auto title = ErrorTitle.AsString()) { titlez = *title; } else { - titlez = format_string(std::get(ErrorTitle), nullptr); + titlez = format_string(ErrorTitle.GetStringId(), nullptr); } return titlez; } @@ -67,13 +67,13 @@ std::string GameActionResult::GetErrorTitle() const std::string GameActionResult::GetErrorMessage() const { std::string messagez; - if (auto message = std::get_if(&ErrorMessage)) + if (auto message = ErrorMessage.AsString()) { messagez = *message; } else { - messagez = format_string(std::get(ErrorMessage), ErrorMessageArgs.data()); + messagez = format_string(ErrorMessage.GetStringId(), ErrorMessageArgs.data()); } return messagez; } diff --git a/src/openrct2/actions/GameAction.h b/src/openrct2/actions/GameAction.h index 474dddc6a0..79ef489294 100644 --- a/src/openrct2/actions/GameAction.h +++ b/src/openrct2/actions/GameAction.h @@ -20,7 +20,6 @@ #include #include #include -#include /** * Common error codes for game actions. @@ -61,6 +60,59 @@ namespace GA_FLAGS # pragma GCC diagnostic ignored "-Wsuggest-final-types" #endif +class StringVariant +{ +private: + rct_string_id StringId = STR_NONE; + std::string String; + +public: + StringVariant() = default; + + StringVariant(rct_string_id stringId) + : StringId(stringId) + { + } + + StringVariant(const std::string& s) + : String(s) + { + } + + StringVariant(std::string&& s) + : String(s) + { + } + + StringVariant(const char* s) + : String(s) + { + } + + const std::string* AsString() const + { + if (!String.empty()) + { + return &String; + } + return {}; + } + + const rct_string_id* AsStringId() const + { + if (String.empty()) + { + return &StringId; + } + return {}; + } + + rct_string_id GetStringId() const + { + return String.empty() ? StringId : STR_NONE; + } +}; + /** * Represents the result of a game action query or execution. */ @@ -70,8 +122,8 @@ public: using Ptr = std::unique_ptr; GA_ERROR Error = GA_ERROR::OK; - std::variant ErrorTitle = STR_NONE; - std::variant ErrorMessage = STR_NONE; + StringVariant ErrorTitle; + StringVariant ErrorMessage; std::array ErrorMessageArgs; CoordsXYZ Position = { LOCATION_NULL, LOCATION_NULL, LOCATION_NULL }; money32 Cost = 0; diff --git a/src/openrct2/actions/GameActionCompat.cpp b/src/openrct2/actions/GameActionCompat.cpp index aebf267c9f..6dc34b7178 100644 --- a/src/openrct2/actions/GameActionCompat.cpp +++ b/src/openrct2/actions/GameActionCompat.cpp @@ -140,11 +140,11 @@ money32 maze_set_track( // NOTE: ride_construction_tooldown_construct requires them to be set. // Refactor result type once theres no C code referencing this function. - if (auto title = std::get_if(&res->ErrorTitle)) + if (auto title = res->ErrorTitle.AsStringId()) gGameCommandErrorTitle = *title; else gGameCommandErrorTitle = STR_NONE; - if (auto message = std::get_if(&res->ErrorMessage)) + if (auto message = res->ErrorMessage.AsStringId()) gGameCommandErrorText = *message; else gGameCommandErrorText = STR_NONE; diff --git a/src/openrct2/actions/LandSmoothAction.hpp b/src/openrct2/actions/LandSmoothAction.hpp index 3d50624403..ef68723978 100644 --- a/src/openrct2/actions/LandSmoothAction.hpp +++ b/src/openrct2/actions/LandSmoothAction.hpp @@ -642,7 +642,7 @@ private: } default: log_error("Invalid map selection %u", _selectionType); - return MakeResult(GA_ERROR::INVALID_PARAMETERS, std::get(res->ErrorTitle)); + return MakeResult(GA_ERROR::INVALID_PARAMETERS, res->ErrorTitle.GetStringId()); } // switch selectionType // Raise / lower the land tool selection area diff --git a/src/openrct2/actions/MazePlaceTrackAction.hpp b/src/openrct2/actions/MazePlaceTrackAction.hpp index afcb95b551..f8931d81d0 100644 --- a/src/openrct2/actions/MazePlaceTrackAction.hpp +++ b/src/openrct2/actions/MazePlaceTrackAction.hpp @@ -93,8 +93,7 @@ public: { _loc.ToTileStart(), baseHeight, clearanceHeight }, &map_place_non_scenery_clear_func, { 0b1111, 0 }, GetFlags(), &clearCost, CREATE_CROSSING_MODE_NONE)) { - return MakeResult( - GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); + return MakeResult(GA_ERROR::NO_CLEARANCE, res->ErrorTitle.GetStringId(), gGameCommandErrorText, gCommonFormatArgs); } if (gMapGroundFlags & ELEMENT_IS_UNDERWATER) @@ -163,8 +162,7 @@ public: { _loc.ToTileStart(), baseHeight, clearanceHeight }, &map_place_non_scenery_clear_func, { 0b1111, 0 }, GetFlags() | GAME_COMMAND_FLAG_APPLY, &clearCost, CREATE_CROSSING_MODE_NONE)) { - return MakeResult( - GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); + return MakeResult(GA_ERROR::NO_CLEARANCE, res->ErrorTitle.GetStringId(), gGameCommandErrorText, gCommonFormatArgs); } money32 price = (((RideTrackCosts[ride->type].track_price * TrackPricing[TRACK_ELEM_MAZE]) >> 16)); diff --git a/src/openrct2/actions/MazeSetTrackAction.hpp b/src/openrct2/actions/MazeSetTrackAction.hpp index 7dc8adeeb5..ed4e3698dd 100644 --- a/src/openrct2/actions/MazeSetTrackAction.hpp +++ b/src/openrct2/actions/MazeSetTrackAction.hpp @@ -137,7 +137,7 @@ public: if (!map_can_construct_at({ _loc.ToTileStart(), baseHeight, clearanceHeight }, { 0b1111, 0 })) { return MakeResult( - GA_ERROR::NO_CLEARANCE, std::get(res->ErrorTitle), gGameCommandErrorText, gCommonFormatArgs); + GA_ERROR::NO_CLEARANCE, res->ErrorTitle.GetStringId(), gGameCommandErrorText, gCommonFormatArgs); } if (gMapGroundFlags & ELEMENT_IS_UNDERWATER) diff --git a/src/openrct2/world/Map.cpp b/src/openrct2/world/Map.cpp index 469de6cd97..3c3d5d2c92 100644 --- a/src/openrct2/world/Map.cpp +++ b/src/openrct2/world/Map.cpp @@ -1324,7 +1324,7 @@ static GameActionResult::Ptr map_can_construct_with_clear_at( if (tileElement == nullptr) { res->Error = GA_ERROR::UNKNOWN; - res->ErrorMessage = 0; + res->ErrorMessage = STR_NONE; return res; } do @@ -1481,7 +1481,7 @@ bool map_can_construct_with_clear_at( uint8_t crossingMode) { GameActionResult::Ptr res = map_can_construct_with_clear_at(pos, clearFunc, quarterTile, flags, crossingMode); - if (auto message = std::get_if(&res->ErrorMessage)) + if (auto message = res->ErrorMessage.AsStringId()) gGameCommandErrorText = *message; else gGameCommandErrorText = STR_NONE; From 7f9ff121b11c2bd797bc36e73831da13360b149b Mon Sep 17 00:00:00 2001 From: Ted John Date: Mon, 20 Apr 2020 23:41:02 +0100 Subject: [PATCH 128/159] Fix rebase --- src/openrct2-ui/scripting/CustomWindow.cpp | 3 ++- src/openrct2-ui/windows/TopToolbar.cpp | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 6fd917491b..377f00ad88 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -414,7 +414,8 @@ namespace OpenRCT2::Ui::Windows { gDropdownItemsFormat[i] = selectedIndex == (int32_t)i ? STR_OPTIONS_DROPDOWN_ITEM_SELECTED : STR_OPTIONS_DROPDOWN_ITEM; - set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, items[i].c_str()); + auto sz = items[i].c_str(); + std::memcpy(&gDropdownItemsArgs[i], &sz, sizeof(const char*)); } window_dropdown_show_text_custom_width( w->windowPos.x + widget->left, w->windowPos.y + widget->top, widget->bottom - widget->top + 1, diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index e67a515a7c..72b61eb4dd 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -3296,7 +3296,8 @@ static void top_toolbar_init_map_menu(rct_window* w, rct_widget* widget) for (const auto& item : customMenuItems) { gDropdownItemsFormat[i] = STR_STRING; - set_format_arg_on((uint8_t*)&gDropdownItemsArgs[i], 0, const char*, item.Text.c_str()); + auto sz = item.Text.c_str(); + std::memcpy(&gDropdownItemsArgs[i], &sz, sizeof(const char*)); i++; } } From aefc49440a6a4395630dceec50cfec2bcf67ee4b Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Tue, 21 Apr 2020 17:05:37 +0200 Subject: [PATCH 129/159] Xcode: add new thirdparty location to header search paths. --- OpenRCT2.xcodeproj/project.pbxproj | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index d705605be1..f7e9e56ed0 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -4539,6 +4539,7 @@ "$(SRCROOT)/libxc/include/openssl", "$(SRCROOT)/libxc/include/freetype2", "$(SRCROOT)/src/", + "$(SRCROOT)/src/thirdparty/", ); INFOPLIST_FILE = "$(DERIVED_FILE_DIR)/Info.plist"; LD_RUNPATH_SEARCH_PATHS = ( @@ -4582,6 +4583,7 @@ "$(SRCROOT)/libxc/include/openssl", "$(SRCROOT)/libxc/include/freetype2", "$(SRCROOT)/src/", + "$(SRCROOT)/src/thirdparty/", ); INFOPLIST_FILE = "$(DERIVED_FILE_DIR)/Info.plist"; LD_RUNPATH_SEARCH_PATHS = ( @@ -4625,6 +4627,8 @@ "$(SRCROOT)/libxc/include/libpng16", "$(SRCROOT)/libxc/include/openssl", "$(SRCROOT)/libxc/include/freetype2", + "$(SRCROOT)/src/", + "$(SRCROOT)/src/thirdparty/", ); LIBRARY_SEARCH_PATHS = ( "$(inherited)", @@ -4665,6 +4669,8 @@ "$(SRCROOT)/libxc/include/libpng16", "$(SRCROOT)/libxc/include/openssl", "$(SRCROOT)/libxc/include/freetype2", + "$(SRCROOT)/src/", + "$(SRCROOT)/src/thirdparty/", ); LIBRARY_SEARCH_PATHS = ( "$(inherited)", @@ -4700,6 +4706,7 @@ "$(SRCROOT)/libxc/include/libpng16", "$(SRCROOT)/libxc/include/openssl", "$(SRCROOT)/src/", + "$(SRCROOT)/src/thirdparty/", ); LIBRARY_SEARCH_PATHS = ( "$(inherited)", @@ -4733,6 +4740,7 @@ "$(SRCROOT)/libxc/include/libpng16", "$(SRCROOT)/libxc/include/openssl", "$(SRCROOT)/src/", + "$(SRCROOT)/src/thirdparty/", ); LIBRARY_SEARCH_PATHS = ( "$(inherited)", From 62d15e44db9c22920de4e2095c613d5b47dea415 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 21 Apr 2020 18:20:59 +0100 Subject: [PATCH 130/159] Fix mingw build --- .github/workflows/ci.yml | 2 +- src/openrct2/CMakeLists.txt | 19 ++++++++++++++----- src/openrct2/core/FileWatcher.cpp | 6 ++++++ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fcdd4bdcf..8cf76b8a04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,7 +71,7 @@ jobs: run: | sudo su mkdir bin && cd bin - cmake .. -G Ninja -DCMAKE_TOOLCHAIN_FILE=../CMakeLists_mingw.txt -DCMAKE_BUILD_TYPE=MinSizeRel -DDISABLE_IPO=on -DFORCE32=on -DBUILD_SHARED_LIBS=ON + cmake .. -G Ninja -DCMAKE_TOOLCHAIN_FILE=../CMakeLists_mingw.txt -DCMAKE_BUILD_TYPE=MinSizeRel -DDISABLE_IPO=on -DFORCE32=on -DBUILD_SHARED_LIBS=ON -DENABLE_SCRIPTING=OFF ninja -k0 macos: name: macOS diff --git a/src/openrct2/CMakeLists.txt b/src/openrct2/CMakeLists.txt index 7bedc0006c..4421affdc8 100644 --- a/src/openrct2/CMakeLists.txt +++ b/src/openrct2/CMakeLists.txt @@ -100,9 +100,22 @@ if (NOT DISABLE_GOOGLE_BENCHMARK) endif () endif () +if (ENABLE_SCRIPTING) + if (MSVC) + find_package(duktape REQUIRED) + else () + PKG_CHECK_MODULES(DUKTAPE REQUIRED duktape) + target_include_directories(${PROJECT_NAME} PRIVATE ${DUKTAPE_INCLUDE_DIRS}) + if (STATIC) + target_link_libraries(${PROJECT_NAME} ${DUKTAPE_STATIC_LIBRARIES}) + else () + target_link_libraries(${PROJECT_NAME} ${DUKTAPE_LIBRARIES}) + endif () + endif () +endif () + # Third party libraries if (MSVC) - find_package(duktape REQUIRED) find_package(jansson CONFIG REQUIRED) set(JANSSON_LIBRARIES "jansson::jansson") find_package(png 1.6 REQUIRED) @@ -111,7 +124,6 @@ if (MSVC) find_path(LIBZIP_INCLUDE_DIRS zip.h) find_library(LIBZIP_LIBRARIES zip) else () - PKG_CHECK_MODULES(DUKTAPE REQUIRED duktape) PKG_CHECK_MODULES(JANSSON REQUIRED jansson>=2.5) PKG_CHECK_MODULES(LIBZIP REQUIRED libzip>=1.0) PKG_CHECK_MODULES(ZLIB REQUIRED zlib) @@ -130,13 +142,11 @@ endif () if (STATIC) target_link_libraries(${PROJECT_NAME} ${JANSSON_STATIC_LIBRARIES} - ${DUKTAPE_STATIC_LIBRARIES} ${PNG_STATIC_LIBRARIES} ${ZLIB_STATIC_LIBRARIES} ${LIBZIP_STATIC_LIBRARIES}) else () target_link_libraries(${PROJECT_NAME} ${JANSSON_LIBRARIES} - ${DUKTAPE_LIBRARIES} ${PNG_LIBRARIES} ${ZLIB_LIBRARIES} ${LIBZIP_LIBRARIES}) @@ -200,7 +210,6 @@ endif() target_include_directories(${PROJECT_NAME} PRIVATE ${LIBZIP_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PUBLIC ${JANSSON_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PRIVATE ${PNG_INCLUDE_DIRS} - ${DUKTAPE_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIRS}) include_directories(${PROJECT_NAME} SYSTEM ${CMAKE_CURRENT_LIST_DIR}/../thirdparty) diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index f48db28b27..06165a26c3 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -109,7 +109,13 @@ FileWatcher::FileWatcher(const std::string& directoryPath) FileWatcher::~FileWatcher() { #ifdef _WIN32 +# ifdef __MINGW32__ + // TODO CancelIo is documented as not working across a different thread but + // CancelIoEx is not available. + CancelIo(_directoryHandle); +# else CancelIoEx(_directoryHandle, nullptr); +# endif CloseHandle(_directoryHandle); #else _finished = true; From ea632a8eed28d6024737f5e2689f00a8f5327256 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 21 Apr 2020 19:32:08 +0100 Subject: [PATCH 131/159] Rename thing to entity --- distribution/openrct2.d.ts | 24 ++++---- .../scripting/{ScThing.hpp => ScEntity.hpp} | 58 +++++++++---------- src/openrct2/scripting/ScMap.hpp | 26 ++++----- src/openrct2/scripting/ScriptEngine.cpp | 4 +- 4 files changed, 56 insertions(+), 56 deletions(-) rename src/openrct2/scripting/{ScThing.hpp => ScEntity.hpp} (71%) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 219ee8ead4..954a28a481 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -295,13 +295,13 @@ declare global { interface GameMap { readonly size: Coord2; readonly numRides: number; - readonly numThings: number; + readonly numEntities: number; readonly rides: Ride[]; getRide(id: number): Ride; getTile(x: number, y: number): Tile; - getThing(id: number): Thing; - getAllThings(type: ThingType); + getEntity(id: number): Entity; + getAllEntities(type: EntityType); } type TileElementType = @@ -491,27 +491,27 @@ declare global { totalCustomers: number; } - type ThingType = + type EntityType = "car" | "duck" | "peep"; /** - * Represents an object "thing" on the map that can typically moves and has a sub-tile coordinate. + * Represents an object "entity" on the map that can typically moves and has a sub-tile coordinate. */ - interface Thing { + interface Entity { /** - * The type of thing, e.g. car, duck, litter, or peep. + * The type of entity, e.g. car, duck, litter, or peep. */ - readonly type: ThingType; + readonly type: EntityType; /** - * The x-coordinate of the thing in game units. + * The x-coordinate of the entity in game units. */ x: number; /** - * The y-coordinate of the thing in game units. + * The y-coordinate of the entity in game units. */ y: number; /** - * The z-coordinate of the thing in game units. + * The z-coordinate of the entity in game units. */ z: number; } @@ -519,7 +519,7 @@ declare global { /** * Represents a guest or staff member. */ - interface Peep extends Thing { + interface Peep extends Entity { /** * Colour of the peep's t-shirt. */ diff --git a/src/openrct2/scripting/ScThing.hpp b/src/openrct2/scripting/ScEntity.hpp similarity index 71% rename from src/openrct2/scripting/ScThing.hpp rename to src/openrct2/scripting/ScEntity.hpp index 5320af6825..eb8192e92a 100644 --- a/src/openrct2/scripting/ScThing.hpp +++ b/src/openrct2/scripting/ScEntity.hpp @@ -18,13 +18,13 @@ namespace OpenRCT2::Scripting { - class ScThing + class ScEntity { protected: uint16_t _id = SPRITE_INDEX_NULL; public: - ScThing(uint16_t id) + ScEntity(uint16_t id) : _id(id) { } @@ -32,17 +32,17 @@ namespace OpenRCT2::Scripting private: std::string type_get() { - auto thing = GetThing(); - if (thing != nullptr) + auto entity = GetEntity(); + if (entity != nullptr) { - switch (thing->sprite_identifier) + switch (entity->sprite_identifier) { case SPRITE_IDENTIFIER_VEHICLE: return "car"; case SPRITE_IDENTIFIER_PEEP: return "peep"; case SPRITE_IDENTIFIER_MISC: - switch (thing->type) + switch (entity->type) { case SPRITE_MISC_BALLOON: return "balloon"; @@ -60,52 +60,52 @@ namespace OpenRCT2::Scripting // x getter and setter int32_t x_get() { - auto thing = GetThing(); - return thing != nullptr ? thing->x : 0; + auto entity = GetEntity(); + return entity != nullptr ? entity->x : 0; } void x_set(int32_t value) { ThrowIfGameStateNotMutable(); - auto thing = GetThing(); - if (thing != nullptr) + auto entity = GetEntity(); + if (entity != nullptr) { - sprite_move(value, thing->y, thing->z, thing); + sprite_move(value, entity->y, entity->z, entity); } } // y getter and setter int32_t y_get() { - auto thing = GetThing(); - return thing != nullptr ? thing->y : 0; + auto entity = GetEntity(); + return entity != nullptr ? entity->y : 0; } void y_set(int32_t value) { ThrowIfGameStateNotMutable(); - auto thing = GetThing(); - if (thing != nullptr) + auto entity = GetEntity(); + if (entity != nullptr) { - sprite_move(thing->x, value, thing->z, thing); + sprite_move(entity->x, value, entity->z, entity); } } // z getter and setter int16_t z_get() { - auto thing = GetThing(); - return thing != nullptr ? thing->z : 0; + auto entity = GetEntity(); + return entity != nullptr ? entity->z : 0; } void z_set(int16_t value) { ThrowIfGameStateNotMutable(); - auto thing = GetThing(); - if (thing != nullptr) + auto entity = GetEntity(); + if (entity != nullptr) { - sprite_move(thing->x, thing->y, value, thing); + sprite_move(entity->x, entity->y, value, entity); } } - SpriteBase* GetThing() + SpriteBase* GetEntity() { return &get_sprite(_id)->generic; } @@ -113,18 +113,18 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { - dukglue_register_property(ctx, &ScThing::type_get, nullptr, "type"); - dukglue_register_property(ctx, &ScThing::x_get, &ScThing::x_set, "x"); - dukglue_register_property(ctx, &ScThing::y_get, &ScThing::y_set, "y"); - dukglue_register_property(ctx, &ScThing::z_get, &ScThing::z_set, "z"); + dukglue_register_property(ctx, &ScEntity::type_get, nullptr, "type"); + dukglue_register_property(ctx, &ScEntity::x_get, &ScEntity::x_set, "x"); + dukglue_register_property(ctx, &ScEntity::y_get, &ScEntity::y_set, "y"); + dukglue_register_property(ctx, &ScEntity::z_get, &ScEntity::z_set, "z"); } }; - class ScPeep : public ScThing + class ScPeep : public ScEntity { public: ScPeep(uint16_t id) - : ScThing(id) + : ScEntity(id) { } @@ -166,7 +166,7 @@ namespace OpenRCT2::Scripting public: static void Register(duk_context* ctx) { - dukglue_set_base_class(ctx); + dukglue_set_base_class(ctx); dukglue_register_property(ctx, &ScPeep::tshirtColour_get, &ScPeep::tshirtColour_set, "tshirtColour"); dukglue_register_property(ctx, &ScPeep::trousersColour_get, &ScPeep::trousersColour_set, "trousersColour"); } diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index fa293b713a..1013e5bc79 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -15,8 +15,8 @@ # include "../ride/Ride.h" # include "../world/Map.h" # include "Duktape.hpp" +# include "ScEntity.hpp" # include "ScRide.hpp" -# include "ScThing.hpp" # include "ScTile.hpp" namespace OpenRCT2::Scripting @@ -48,7 +48,7 @@ namespace OpenRCT2::Scripting return static_cast(GetRideManager().size()); } - int32_t numThings_get() + int32_t numEntities_get() { return MAX_SPRITES; } @@ -84,7 +84,7 @@ namespace OpenRCT2::Scripting return std::make_shared(coords); } - DukValue getThing(int32_t id) + DukValue getEntity(int32_t id) { if (id >= 0 && id < MAX_SPRITES) { @@ -92,14 +92,14 @@ namespace OpenRCT2::Scripting auto sprite = get_sprite(spriteId); if (sprite != nullptr && sprite->generic.sprite_identifier != SPRITE_IDENTIFIER_NULL) { - return GetThingAsDukValue(sprite); + return GetEntityAsDukValue(sprite); } } duk_push_null(_context); return DukValue::take_from_stack(_context); } - std::vector getAllThings(const std::string& type) + std::vector getAllEntities(const std::string& type) { SPRITE_LIST targetList{}; uint8_t targetType{}; @@ -127,7 +127,7 @@ namespace OpenRCT2::Scripting } else { - duk_error(_context, DUK_ERR_ERROR, "Invalid thing type."); + duk_error(_context, DUK_ERR_ERROR, "Invalid entity type."); } std::vector result; @@ -160,14 +160,14 @@ namespace OpenRCT2::Scripting } else { - result.push_back(GetObjectAsDukValue(_context, std::make_shared(carId))); + result.push_back(GetObjectAsDukValue(_context, std::make_shared(carId))); carId = car->vehicle.next_vehicle_on_train; } } } else { - result.push_back(GetObjectAsDukValue(_context, std::make_shared(spriteId))); + result.push_back(GetObjectAsDukValue(_context, std::make_shared(spriteId))); } } spriteId = sprite->generic.next; @@ -180,16 +180,16 @@ namespace OpenRCT2::Scripting { dukglue_register_property(ctx, &ScMap::size_get, nullptr, "size"); dukglue_register_property(ctx, &ScMap::numRides_get, nullptr, "numRides"); - dukglue_register_property(ctx, &ScMap::numThings_get, nullptr, "numThings"); + dukglue_register_property(ctx, &ScMap::numEntities_get, nullptr, "numEntities"); dukglue_register_property(ctx, &ScMap::rides_get, nullptr, "rides"); dukglue_register_method(ctx, &ScMap::getRide, "getRide"); dukglue_register_method(ctx, &ScMap::getTile, "getTile"); - dukglue_register_method(ctx, &ScMap::getThing, "getThing"); - dukglue_register_method(ctx, &ScMap::getAllThings, "getAllThings"); + dukglue_register_method(ctx, &ScMap::getEntity, "getEntity"); + dukglue_register_method(ctx, &ScMap::getAllEntities, "getAllEntities"); } private: - DukValue GetThingAsDukValue(const rct_sprite* sprite) + DukValue GetEntityAsDukValue(const rct_sprite* sprite) { auto spriteId = sprite->generic.sprite_index; switch (sprite->generic.sprite_identifier) @@ -197,7 +197,7 @@ namespace OpenRCT2::Scripting case SPRITE_IDENTIFIER_PEEP: return GetObjectAsDukValue(_context, std::make_shared(spriteId)); default: - return GetObjectAsDukValue(_context, std::make_shared(spriteId)); + return GetObjectAsDukValue(_context, std::make_shared(spriteId)); } } }; diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 5ca0c0b990..9a7d38dd80 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -25,12 +25,12 @@ # include "ScContext.hpp" # include "ScDate.hpp" # include "ScDisposable.hpp" +# include "ScEntity.hpp" # include "ScMap.hpp" # include "ScNetwork.hpp" # include "ScObject.hpp" # include "ScPark.hpp" # include "ScRide.hpp" -# include "ScThing.hpp" # include "ScTile.hpp" # include @@ -382,7 +382,7 @@ void ScriptEngine::Initialise() ScRideObject::Register(ctx); ScTile::Register(ctx); ScTileElement::Register(ctx); - ScThing::Register(ctx); + ScEntity::Register(ctx); ScPeep::Register(ctx); dukglue_register_global(ctx, std::make_shared(_console), "console"); From d9cbdf29ad7590fa1ac4c64e10a00989e1dc3901 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 21 Apr 2020 22:08:19 +0100 Subject: [PATCH 132/159] Ensure all paths return a value regardless of duk_error --- src/openrct2/scripting/ScConfiguration.hpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/openrct2/scripting/ScConfiguration.hpp b/src/openrct2/scripting/ScConfiguration.hpp index f621fcb600..01da35d14a 100644 --- a/src/openrct2/scripting/ScConfiguration.hpp +++ b/src/openrct2/scripting/ScConfiguration.hpp @@ -132,6 +132,7 @@ namespace OpenRCT2::Scripting DukValue getAll(const std::string& ns) { + DukValue result; auto ctx = GetContext()->GetScriptEngine().GetContext(); if (IsValidNamespace(ns)) { @@ -142,18 +143,19 @@ namespace OpenRCT2::Scripting { obj.Set("general.showFps", gConfigGeneral.show_fps); } - return obj.Take(); + result = obj.Take(); } else { auto obj = GetNamespaceObject(ns); - return obj ? *obj : DukObject(ctx).Take(); + result = obj ? *obj : DukObject(ctx).Take(); } } else { duk_error(ctx, DUK_ERR_ERROR, "Namespace was invalid."); } + return result; } DukValue get(const std::string& key, const DukValue& defaultValue) From efbb385bf74b9a9fb0271328d21e26988d71fed8 Mon Sep 17 00:00:00 2001 From: Ted John Date: Tue, 21 Apr 2020 22:26:06 +0100 Subject: [PATCH 133/159] Remove TabbedWindow API This doesn't exist yet. --- distribution/openrct2.d.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 954a28a481..92d33e6a25 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -697,12 +697,6 @@ declare global { viewport: Viewport } - interface Tab { - image: number; - tooltip: string; - widgets: Widget[]; - } - interface Window { classification: number; number: number; @@ -720,13 +714,6 @@ declare global { findWidget(name: string): T; } - interface TabbedWindow extends Window { - tabs: Tab[]; - activeTabIndex: number; - - onTabChanged: (index: number) => void; - } - interface WindowDesc { classification: string; x?: number; @@ -739,7 +726,6 @@ declare global { minHeight?: number; widgets?: Widget[]; colours?: number[]; - tabs?: Tab[]; onClose?: () => void; } From d480fb8daa2e31db7602a06a74b31dd9bd82bacb Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 22 Apr 2020 16:06:29 +0100 Subject: [PATCH 134/159] Apply suggestions from code review Co-Authored-By: Tulio Leao Co-Authored-By: Michael Steenbeek --- distribution/scripting.md | 38 +++++++++++----------- src/openrct2-ui/scripting/CustomMenu.cpp | 2 +- src/openrct2-ui/scripting/CustomMenu.h | 4 +-- src/openrct2-ui/scripting/CustomWindow.h | 2 +- src/openrct2-ui/scripting/ScUi.hpp | 2 +- src/openrct2-ui/scripting/ScViewport.hpp | 2 +- src/openrct2-ui/scripting/ScWidget.hpp | 2 +- src/openrct2-ui/scripting/ScWindow.hpp | 2 +- src/openrct2-ui/scripting/UiExtensions.cpp | 2 +- src/openrct2-ui/scripting/UiExtensions.h | 2 +- src/openrct2/actions/GameAction.cpp | 20 ++++++------ src/openrct2/core/FileWatcher.cpp | 2 +- src/openrct2/core/FileWatcher.h | 2 +- src/openrct2/scripting/HookEngine.h | 2 +- src/openrct2/scripting/Plugin.cpp | 2 +- src/openrct2/scripting/Plugin.h | 6 ++-- src/openrct2/scripting/ScConfiguration.hpp | 9 ++--- src/openrct2/scripting/ScConsole.hpp | 2 +- src/openrct2/scripting/ScContext.hpp | 2 +- src/openrct2/scripting/ScDate.hpp | 2 +- src/openrct2/scripting/ScDisposable.hpp | 2 +- src/openrct2/scripting/ScEntity.hpp | 2 +- src/openrct2/scripting/ScMap.hpp | 2 +- src/openrct2/scripting/ScNetwork.hpp | 2 +- 24 files changed, 55 insertions(+), 60 deletions(-) diff --git a/distribution/scripting.md b/distribution/scripting.md index 452093f060..1402113126 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -2,7 +2,7 @@ OpenRCT2 allows custom scripts (also known as plug-ins) to be written and executed in the game providing additional behaviour on top of the vanilla experience. This can range from extra windows providing information about the park to entire new multiplayer game modes. -Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This is usually `C:\Users\YourName\Documents\OpenRCT2`, or `/home/YourName/.config/openrct2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively. So if you want to prevent a plug-in from being used, you must move it outside this directory, or rename it so the filename does not end with `.js`. +Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This is usually `C:\Users\YourName\Documents\OpenRCT2` on Windows, or `/home/YourName/.config/openrct2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively. So if you want to prevent a plug-in from being used, you must move it outside this directory, or rename it so the filename does not end with `.js`. There are two types of scripts: * Local @@ -10,16 +10,16 @@ There are two types of scripts: Local scripts can **not** alter the game state. This allows each player to enable any local script for their own game without other players needing to also enable the same script. These scripts tend to provide extra tools for productivity, or new windows containing information. -Remote scripts on the other hand can alter the game state in certain contexts thus must be enabled for every player in a multiplayer game. Players can not enable or disable remote scripts for multiplayer servers they join. Instead the server will upload any remote scripts that have been enabled on the server to each player. This allows servers to enable scripts without players needing to manually download or enable the same script on their end. +Remote scripts on the other hand can alter the game state in certain contexts, thus must be enabled for every player in a multiplayer game. Players **cannot** enable or disable remote scripts for multiplayer servers they join. Instead the server will upload any remote scripts that have been enabled on the server to each player. This allows servers to enable scripts without players needing to manually download or enable the same script on their end. ## Writing Scripts Scripts are written in ECMAScript 5 compatible JavaScript. OpenRCT2 currently uses the [duktape](https://duktape.org) library to execute scripts. This however does not mean you need to write your plug-in in JavaScript, there are many transpilers that allow you to write in a language of your choice and then compile it to JavaScript allowing it to be executed by OpenRCT2. JavaScript or [TypeScript](https://www.typescriptlang.org) is recommended however, as that will allow you to utilise the type definition file we supply (`openrct2.d.ts`). If you would like to use ECMAScript 6 or later which contain features such as the `let` keyword or classes, then you will need to use a transpiler such as [Babel](https://babeljs.io) or [TypeScript](https://www.typescriptlang.org). -Offical references for writing plug-ins are: +Official references for writing plug-ins are: * The API: `openrct2.d.ts` distributed with OpenRCT2. -* Our collection of sample scripts: https://github.com/OpenRCT2/plugin-samples -* A TypeScript plug-in comprised on multiple sources: https://github.com/IntelOrca/OpenRCT2-ParkManager +* Our collection of sample scripts: [OpenRCT2/plugin-samples](https://github.com/OpenRCT2/plugin-samples) +* A TypeScript plug-in comprised of multiple sources: [IntelOrca/OpenRCT2-ParkManager](https://github.com/IntelOrca/OpenRCT2-ParkManager) Start by copying this template script into a new file in your `plugin` directory: ```js @@ -36,23 +36,23 @@ registerPlugin({ }); ``` -This will log a message to stdout when you open any park. If you are on Windows, make sure to run `openrct2.com` instead of `openrct2.exe` so you can interact with the stdin / stdout console. The console is a JavaScript interpreter (REPL), this means you can write and test expressions similar to the console found in web browsers when you press F12. When you make changes to your script, you must exit your current game and open it again for the script to reload... unless you use the hot reload feature. +This will log a message to the terminal screen (`stdout`) when you open any park. If you are on Windows, make sure to run `openrct2.com` instead of `openrct2.exe` so you can interact with the `stdin` / `stdout` console. The console is a JavaScript interpreter (REPL), this means you can write and test expressions similar to the console found in web browsers when you press `F12`. When you make changes to your script, you must exit your current game and open it again for the script to reload... unless you use the hot reload feature. -The hot reload feature can be enabled by editing your `config.ini` file and setting `enable_hot_reloading` to `true` under `[plugin]`. When this is enabled, the game will auto-reload the script in real-time whenever you save your JavaScript file. This is allows rapid development of plug-ins. You may even want to write temporary code to preview your changes quickly, such as closing and opening a specific custom window on startup. A demonstration of this can be found here: https://www.youtube.com/watch?v=jmjWzEhmDjk +The hot reload feature can be enabled by editing your `config.ini` file and setting `enable_hot_reloading` to `true` under `[plugin]`. When this is enabled, the game will auto-reload the script in real-time whenever you save your JavaScript file. This allows rapid development of plug-ins as you can write code and quickly preview your changes, such as closing and opening a specific custom window on startup. A demonstration of this can be found on YouTube: [OpenRCT2 plugin hot-reload demo](https://www.youtube.com/watch?v=jmjWzEhmDjk) ## Frequently Asked Questions -> Why was JavaScript chosen instead LUA or Python. +> Why was JavaScript chosen instead of LUA or Python. JavaScript is a very mature and flexible language with a large, if not largest, resource base available. There are arguably more transpilers, tools, and libraries for JavaScript than any other language. That and also it using a familiar C-like syntax and 0-indexed arrays make it more suitable than LUA and Python. Of course if you would still like to use LUA or another language, there will likely be a JavaScript transpiler for it. -Another benefit of using JavaScript is that you get rich editor features such as completion and API documentation by using a TypeScript definition file which works for both TypeScript and JavaScript. [Visual Studio Code](https://code.visualstudio.com) is recommended, as that supports the workflow very well. See this video for a demonstration of the editor functionality: https://www.youtube.com/watch?v=jmjWzEhmDjk +Another benefit of using JavaScript is that you get rich editor features such as completion and API documentation by using a TypeScript definition file which works for both TypeScript and JavaScript. [Visual Studio Code](https://code.visualstudio.com) is recommended, as that supports the workflow very well. See the [OpenRCT2 plugin hot-reload demo](https://www.youtube.com/watch?v=jmjWzEhmDjk) video for a demonstration of the editor functionality. > How safe are scripts? Scripts are executed in a sandbox container with no direct access to your computer. Scripts can only use the APIs we provide which only consist of interactions to OpenRCT2 and a limited API for storing data. It is technically possible for a script to freeze the game, or fill your disc up with data, but these aren't particularly severe issues and are noticed quite quickly. -The [duktape](https://duktape.org) library is used to execute scripts, it is a very mature library for executing scripts, but no library can promise 100% security. If any security vulnerabilities are found, they will likely be fixed promptly and OpenRCT2 can then be updated to use the new version of duktape. +The [duktape](https://duktape.org) library is used to execute scripts, it is a very mature library for executing scripts, but no library can promise 100% security. If any security vulnerabilities are found, they will likely be fixed promptly and OpenRCT2 can then be updated to use the new version of `duktape`. > Is it possible for someone to run a bitcoin miner in my game? @@ -62,19 +62,19 @@ Yes, but the performance would be so dire that it would be a waste of their time Scripts can conist of any behaviour and have a large memory pool available to them. The speed will vary depending on the hardware and system executing them. The scripts are interpreted, so do not expect anywhere close to the performance of native code. In most scenarios this should be satisfactory, but a random map generator, or genetic algorithm for building roller coasters might struggle. Like any language, there will be tricks to optimising JavaScript and the use of the OpenRCT2 APIs. -The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plug-in system is to add APIs on-demand. So if you find an API is missing, please raise an issue for it on GitHub. +The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plug-in system is to add APIs on-demand. So if you find an API is missing, please raise an issue for it on GitHub and also feel free to submit a pull request afterwards. > How do I debug my script? -Debugging has not yet been implemented but is planned. In the meantime, you can use `console.log` to print useful information for diagnosing problems. +Debugging has not yet been implemented, but is planned. In the meantime, you can use `console.log` to print useful information for diagnosing problems. > What does the error 'Game state is not mutable in this context' mean? -This means you are attempting to modify the game state (e.g. change the park, map or guests etc.) in a context where you should not be doing so. This might be because your script is defined as `local` meaning it must work independently of other players not having the script enabled, or a remote script attempting to modify the game in the main function or a user interface event. +This means you are attempting to modify the game state (e.g. change the park, map or guests etc.) in a context where you should not be doing so. This might be because your script is defined as `local`, meaning it must work independently of other players, not having the script enabled, or a remote script attempting to modify the game in the main function or a user interface event. Any changes to the game state must be synchronised across all players so that the same changes happen on the same tick for every player. This prevents the game going out of sync. To do this you must only change game state in a compatible hook such as `interval.day` or in the execute method of a game action. Game actions allow players to make specific changes to the game providing they have the correct permissions and the server allows it. -Whilst OpenRCT2 try's to prevent desynchronision from happening, it still requires careful coding to ensure the behaviour is deterministic across all clients. Any attempt to use local specific or non-deterministic data to change the game state will cause a desync. This can be as easy as using `ui.windows`, a variable that can be different for every player. +Whilst OpenRCT2 tries to prevent desynchronisation from happening, it still requires careful coding to ensure the behaviour is deterministic across all clients. Any attempt to use local specific or non-deterministic data to change the game state will cause a desync. This can be as easy as using `ui.windows`, a variable that can be different for every player. > What are hooks? @@ -100,7 +100,7 @@ Game actions allow you to define new actions (with a new permission slot) that p 6. Send action to all player to execute action at tick ###. 7. All players execute action at tick ###. -This sequence of actions ensure that every player execute the action exactly the same way on the exact same game tick. It also allows the server to validate that the action is allowed and does not fail due to permission or another player executing conflicting action just before it. This is why there is a noticable delay when constructing in multiplayer games, as the client has to wait for the server to acknowledge the action and reply with the tick number to execute it on, since we do not yet have any rollback support. +This sequence of actions ensures that every player execute the action exactly in the same way on the exact same game tick. It also allows the server to validate that the action is allowed and does not fail due to permission or another player executing a conflicting action just before it. This is why there is a noticeable delay when constructing in multiplayer games, as the client has to wait for the server to acknowledge the action and reply with the tick number to execute it on, since we do not yet have any rollback support. > Can I run code specifically for servers or clients? @@ -139,7 +139,7 @@ Yes, remote scripts are uploaded to every client and run as-is. Even if the serv > Can plugins persist data across multiple OpenRCT2 instances? -Yes, use `context.sharedStorage` to read or write data to an external JSON file: `plugin.store.json` in the OpenRCT2 suer directory. It is recommended that you namespace all your plugin's data under a common name. +Yes, use `context.sharedStorage` to read or write data to an external JSON file: `plugin.store.json` in the OpenRCT2 user directory. It is recommended that you namespace all your plugin's data under a common name. ```js var h = context.sharedStorage.get('IntelOrca.MagicLift.Height'); @@ -156,7 +156,7 @@ Absolutely, just embed the library in your JavaScript file. There are a number o > Can I share code across multiple scripts? -There are two ways this can be done. If you are just sharing helper routines or libraries, the best thing is to embed it in each plug-in. There are a number of tools for JavaScript to help you do this. If you would like two plug-ins to communicate with each other, perhaps to share data, then you can do this by declaring a variable or function in global scope which is available to all plug-ins, or use the shared storage APIs. +Yes, and there are two ways this can be done. If you are just sharing helper routines or libraries, the best thing is to embed it in each plug-in. There are a number of tools for JavaScript to help you do this. If you would like two plug-ins to communicate with each other, perhaps to share data, then you can do this by declaring a variable or function in global scope which is available to all plug-ins, or use the shared storage APIs. > What do I do if there is no API for ...? @@ -170,8 +170,8 @@ We recommend [GitHub](https://github.com) (where OpenRCT2 is hosted), or another > What licence should I use for my script? -This is up to you. The OpenRCT2 licence does not enforce any licence requirement for content that is loaded into it. MIT is recommended as is the most permissive. You also have to consider what licence any third party libraries you are using allow. +This is up to you. The OpenRCT2 licence does not enforce any licence requirement for content that is loaded into it. MIT is recommended as it is the most permissive. You also have to consider what licence any third party libraries you are using allow. > Is there a good place to distribute my script to other players? -There is currently no official database for this. For now the recommendation is to upload releases for your script on GitHub alongside your source code (if public). Some people like to make a GitHub repository that just consists of a list of content (scripts in this case) which anyone can add to via pull requests. +There is currently no official database for this. For now the recommendation is to upload releases of your script on GitHub alongside your source code (if public). Some people like to make a GitHub repository that just consists of a list of content (scripts in this case) which anyone can add to via pull requests. diff --git a/src/openrct2-ui/scripting/CustomMenu.cpp b/src/openrct2-ui/scripting/CustomMenu.cpp index 542a0366b6..eca0ad34db 100644 --- a/src/openrct2-ui/scripting/CustomMenu.cpp +++ b/src/openrct2-ui/scripting/CustomMenu.cpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2020 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/CustomMenu.h b/src/openrct2-ui/scripting/CustomMenu.h index 5b754a34bb..fa639752af 100644 --- a/src/openrct2-ui/scripting/CustomMenu.h +++ b/src/openrct2-ui/scripting/CustomMenu.h @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2020 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 @@ -27,7 +27,7 @@ namespace OpenRCT2::Scripting std::string Text; DukValue Callback; - CustomToolbarMenuItem(std::shared_ptr owner, std::string text, DukValue callback) + CustomToolbarMenuItem(std::shared_ptr owner, const std::string& text, DukValue callback) : Owner(owner) , Text(text) , Callback(callback) diff --git a/src/openrct2-ui/scripting/CustomWindow.h b/src/openrct2-ui/scripting/CustomWindow.h index 5709d6ee9c..25db69e806 100644 --- a/src/openrct2-ui/scripting/CustomWindow.h +++ b/src/openrct2-ui/scripting/CustomWindow.h @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 68c397c128..820ec0f3f5 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index 52bd9e32b2..e33d7c00a9 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index 7d046a8a79..fc362c15bf 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 9d7e2fbbfb..5561e5ad1e 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index b70f9552fc..93b95901b7 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2-ui/scripting/UiExtensions.h b/src/openrct2-ui/scripting/UiExtensions.h index 3e9af4ed22..7d29bcd41d 100644 --- a/src/openrct2-ui/scripting/UiExtensions.h +++ b/src/openrct2-ui/scripting/UiExtensions.h @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index b24c48de82..4c82e56f93 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -52,30 +52,30 @@ GameActionResult::GameActionResult(GA_ERROR error, rct_string_id title, rct_stri std::string GameActionResult::GetErrorTitle() const { - std::string titlez; - if (auto title = ErrorTitle.AsString()) + std::string title; + if (auto error = ErrorTitle.AsString()) { - titlez = *title; + title = *error; } else { - titlez = format_string(ErrorTitle.GetStringId(), nullptr); + title = format_string(ErrorTitle.GetStringId(), nullptr); } - return titlez; + return title; } std::string GameActionResult::GetErrorMessage() const { - std::string messagez; - if (auto message = ErrorMessage.AsString()) + std::string message; + if (auto error = ErrorMessage.AsString()) { - messagez = *message; + message = *error; } else { - messagez = format_string(ErrorMessage.GetStringId(), ErrorMessageArgs.data()); + message = format_string(ErrorMessage.GetStringId(), ErrorMessageArgs.data()); } - return messagez; + return message; } namespace GameActions diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index 06165a26c3..079c99b0f0 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h index 1db80379db..96a012efdf 100644 --- a/src/openrct2/core/FileWatcher.h +++ b/src/openrct2/core/FileWatcher.h @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 8f31ab3907..fb42a6b733 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 9d4fcb5133..293f9dbc23 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 3e593156d1..656a9f3bfa 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 @@ -80,9 +80,7 @@ namespace OpenRCT2::Scripting return _hasStarted; } - Plugin() - { - } + Plugin() = default; Plugin(duk_context* context, const std::string& path); Plugin(const Plugin&) = delete; Plugin(Plugin&&) = delete; diff --git a/src/openrct2/scripting/ScConfiguration.hpp b/src/openrct2/scripting/ScConfiguration.hpp index 01da35d14a..e3d8e6a1d4 100644 --- a/src/openrct2/scripting/ScConfiguration.hpp +++ b/src/openrct2/scripting/ScConfiguration.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2020 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 @@ -21,14 +21,11 @@ namespace OpenRCT2::Scripting class ScConfiguration { private: - bool _isUserConfig{}; + bool _isUserConfig{ true }; DukValue _backingObject; public: - ScConfiguration() - : _isUserConfig(true) - { - } + ScConfiguration() = default; ScConfiguration(const DukValue& backingObject) : _backingObject(backingObject) diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index b804d349eb..19edf7cb5d 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index bed9c62764..b4b818039d 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 76c664364b..25ad7c441e 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2020 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index 5b591e35c3..69e1170206 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/ScEntity.hpp b/src/openrct2/scripting/ScEntity.hpp index eb8192e92a..44b567c908 100644 --- a/src/openrct2/scripting/ScEntity.hpp +++ b/src/openrct2/scripting/ScEntity.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index 1013e5bc79..b109c67cb6 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index b09fae62db..1097c9b7ac 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2014-2018 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 From 2f525e0539b204c31c1c087f58b4cb9353dfce60 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 22 Apr 2020 22:53:32 +0100 Subject: [PATCH 135/159] Apply more code review comments --- .vscode/c_cpp_properties.json | 3 +- src/openrct2-ui/scripting/CustomWindow.cpp | 22 +++--- src/openrct2/Game.cpp | 8 +-- src/openrct2/Game.h | 2 +- src/openrct2/core/FileWatcher.cpp | 2 +- src/openrct2/network/Network.cpp | 80 ++++++++++++---------- src/openrct2/scripting/Duktape.hpp | 1 - src/openrct2/scripting/Plugin.cpp | 4 -- src/openrct2/scripting/Plugin.h | 1 - src/openrct2/scripting/ScTile.hpp | 8 +-- src/openrct2/scripting/ScriptEngine.cpp | 12 ++-- 11 files changed, 76 insertions(+), 67 deletions(-) diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index ede5d8c31e..e073544f69 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -64,7 +64,8 @@ "defines": [ "_DEBUG", "UNICODE", - "_UNICODE" + "_UNICODE", + "__ENABLE_SCRIPTING__" ], "intelliSenseMode": "msvc-x64", "browse": { diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 377f00ad88..390ac64986 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -31,7 +31,7 @@ using namespace OpenRCT2::Scripting; namespace OpenRCT2::Ui::Windows { - enum + enum CUSTOM_WINDOW_WIDX { WIDX_BACKGROUND, WIDX_TITLE, @@ -298,7 +298,7 @@ namespace OpenRCT2::Ui::Windows windowFlags |= WF_RESIZABLE; } - rct_window* window; + rct_window* window{}; if (desc.X && desc.Y) { window = window_create( @@ -412,8 +412,8 @@ namespace OpenRCT2::Ui::Windows const auto numItems = std::min(items.size(), DROPDOWN_ITEMS_MAX_SIZE); for (size_t i = 0; i < numItems; i++) { - gDropdownItemsFormat[i] = selectedIndex == (int32_t)i ? STR_OPTIONS_DROPDOWN_ITEM_SELECTED - : STR_OPTIONS_DROPDOWN_ITEM; + gDropdownItemsFormat[i] = selectedIndex == static_cast(i) ? STR_OPTIONS_DROPDOWN_ITEM_SELECTED + : STR_OPTIONS_DROPDOWN_ITEM; auto sz = items[i].c_str(); std::memcpy(&gDropdownItemsArgs[i], &sz, sizeof(const char*)); } @@ -455,7 +455,7 @@ namespace OpenRCT2::Ui::Windows InvokeEventHandler(info.Owner, widgetDesc->OnChange, args); auto& widget = w->widgets[widgetIndex - 1]; - widget.string = (utf8*)widgetDesc->Items[dropdownIndex].c_str(); + widget.string = const_cast(widgetDesc->Items[dropdownIndex].c_str()); widgetDesc->SelectedIndex = dropdownIndex; } @@ -568,7 +568,7 @@ namespace OpenRCT2::Ui::Windows else { widget.type = WWT_BUTTON; - widget.string = (utf8*)desc.Text.c_str(); + widget.string = const_cast(desc.Text.c_str()); widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; } widgetList.push_back(widget); @@ -576,7 +576,7 @@ namespace OpenRCT2::Ui::Windows else if (desc.Type == "checkbox") { widget.type = WWT_CHECKBOX; - widget.string = (utf8*)desc.Text.c_str(); + widget.string = const_cast(desc.Text.c_str()); widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; if (desc.IsChecked) { @@ -589,7 +589,7 @@ namespace OpenRCT2::Ui::Windows widget.type = WWT_DROPDOWN; if (desc.SelectedIndex >= 0 && (size_t)desc.SelectedIndex < desc.Items.size()) { - widget.string = (utf8*)desc.Items[desc.SelectedIndex].c_str(); + widget.string = const_cast(desc.Items[desc.SelectedIndex].c_str()); } widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); @@ -610,21 +610,21 @@ namespace OpenRCT2::Ui::Windows else if (desc.Type == "groupbox") { widget.type = WWT_GROUPBOX; - widget.string = (utf8*)desc.Text.c_str(); + widget.string = const_cast(desc.Text.c_str()); widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); } else if (desc.Type == "label") { widget.type = WWT_LABEL; - widget.string = (utf8*)desc.Text.c_str(); + widget.string = const_cast(desc.Text.c_str()); widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); } else if (desc.Type == "spinner") { widget.type = WWT_SPINNER; - widget.string = (utf8*)desc.Text.c_str(); + widget.string = const_cast(desc.Text.c_str()); widget.flags |= WIDGET_FLAGS::TEXT_IS_STRING; widgetList.push_back(widget); diff --git a/src/openrct2/Game.cpp b/src/openrct2/Game.cpp index cdbf7ff8bc..a3f0b1cfba 100644 --- a/src/openrct2/Game.cpp +++ b/src/openrct2/Game.cpp @@ -597,7 +597,7 @@ void game_load_scripts() #endif } -void game_finish() +void game_unload_scripts() { #ifdef __ENABLE_SCRIPTING__ GetContext()->GetScriptEngine().UnloadPlugins(); @@ -816,7 +816,7 @@ static void game_load_or_quit_no_save_prompt_callback(int32_t result, const utf8 { if (result == MODAL_RESULT_OK) { - game_finish(); + game_unload_scripts(); window_close_by_class(WC_EDITOR_OBJECT_SELECTION); context_load_park_from_file(path); game_load_scripts(); @@ -860,12 +860,12 @@ void game_load_or_quit_no_save_prompt() } gGameSpeed = 1; gFirstTimeSaving = true; - game_finish(); + game_unload_scripts(); title_load(); break; } default: - game_finish(); + game_unload_scripts(); openrct2_finish(); break; } diff --git a/src/openrct2/Game.h b/src/openrct2/Game.h index b29f5a77ff..d260adb236 100644 --- a/src/openrct2/Game.h +++ b/src/openrct2/Game.h @@ -158,7 +158,7 @@ void game_load_or_quit_no_save_prompt(); void load_from_sv6(const char* path); void game_load_init(); void game_load_scripts(); -void game_finish(); +void game_unload_scripts(); void pause_toggle(); bool game_is_paused(); bool game_is_not_paused(); diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index 079c99b0f0..b9921e4d71 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -165,7 +165,7 @@ void FileWatcher::WatchDirectory() int offset = 0; while (offset < length) { - auto e = (inotify_event*)(eventData.data() + offset); + auto e = reinterpret_cast(eventData.data() + offset); if ((e->mask & IN_CLOSE_WRITE) && !(e->mask & IN_ISDIR)) { log_verbose("FileWatcher: inotify event received for %s", e->name); diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index fec0573264..3ed563b753 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -1473,7 +1473,7 @@ void Network::Server_Send_OBJECTS(NetworkConnection& connection, const std::vect void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_SCRIPTS; + *packet << static_cast(NETWORK_COMMAND_SCRIPTS); # ifdef __ENABLE_SCRIPTING__ using namespace OpenRCT2::Scripting; @@ -1490,18 +1490,18 @@ void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const } log_verbose("Server sends %u scripts", pluginsToSend.size()); - *packet << (uint32_t)pluginsToSend.size(); + *packet << static_cast(pluginsToSend.size()); for (const auto& plugin : pluginsToSend) { const auto& metadata = plugin->GetMetadata(); log_verbose("Script %s", metadata.Name.c_str()); const auto& code = plugin->GetCode(); - *packet << (uint32_t)code.size(); - packet->Write((const uint8_t*)code.c_str(), code.size()); + *packet << static_cast(code.size()); + packet->Write(reinterpret_cast(code.c_str()), code.size()); } # else - *packet << (uint32_t)0; + *packet << static_cast(0); # endif connection.QueuePacket(std::move(packet)); } @@ -2451,7 +2451,7 @@ void Network::Client_Handle_SCRIPTS(NetworkConnection& connection, NetworkPacket { uint32_t codeLength{}; packet >> codeLength; - auto code = std::string_view((const char*)packet.Read(codeLength), codeLength); + auto code = std::string_view(reinterpret_cast(packet.Read(codeLength)), codeLength); scriptEngine.AddNetworkPlugin(code); } # else @@ -2886,6 +2886,42 @@ void Network::Client_Handle_CHAT([[maybe_unused]] NetworkConnection& connection, } } +static bool ProcessChatMessagePluginHooks(const NetworkPlayer& player, std::string& text) +{ +# ifdef __ENABLE_SCRIPTING__ + auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT)) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + + // Create event args object + auto objIdx = duk_push_object(ctx); + duk_push_number(ctx, static_cast(player.Id)); + duk_put_prop_string(ctx, objIdx, "player"); + duk_push_string(ctx, text.c_str()); + duk_put_prop_string(ctx, objIdx, "message"); + auto e = DukValue::take_from_stack(ctx); + + // Call the subscriptions + hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, e, false); + + // Update text from object if subscriptions changed it + if (e["message"].type() != DukValue::Type::STRING) + { + // Subscription set text to non-string, do not relay message + return false; + } + text = e["message"].as_string(); + if (text.empty()) + { + // Subscription set text to empty string, do not relay message + return false; + } + } +# endif + return true; +} + void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& packet) { auto szText = packet.ReadString(); @@ -2904,37 +2940,11 @@ void Network::Server_Handle_CHAT(NetworkConnection& connection, NetworkPacket& p std::string text = szText; if (connection.Player != nullptr) { -# ifdef __ENABLE_SCRIPTING__ - auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); - if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT)) + if (!ProcessChatMessagePluginHooks(*connection.Player, text)) { - auto ctx = GetContext()->GetScriptEngine().GetContext(); - - // Create event args object - auto objIdx = duk_push_object(ctx); - duk_push_number(ctx, (int32_t)connection.Player->Id); - duk_put_prop_string(ctx, objIdx, "player"); - duk_push_string(ctx, text.c_str()); - duk_put_prop_string(ctx, objIdx, "message"); - auto e = DukValue::take_from_stack(ctx); - - // Call the subscriptions - hookEngine.Call(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT, e, false); - - // Update text from object if subscriptions changed it - if (e["message"].type() != DukValue::Type::STRING) - { - // Subscription set text to non-string, do not relay message - return; - } - text = e["message"].as_string(); - if (text.empty()) - { - // Subscription set text to empty string, do not relay message - return; - } + // Message not to be relayed + return; } -# endif } const char* formatted = FormatChat(connection.Player, text.c_str()); diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 06a3c7c516..6d0874d818 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -151,7 +151,6 @@ namespace OpenRCT2::Scripting duk_set_top(_ctx, _top); _ctx = {}; std::fprintf(stderr, "duktape stack was not returned to original state!"); - // assert(false); } _ctx = {}; } diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index 293f9dbc23..f0d2e5832f 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -98,10 +98,6 @@ void Plugin::Stop() _hasStarted = false; } -void Plugin::Update() -{ -} - void Plugin::LoadCodeFromFile() { std::string code; diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 656a9f3bfa..d7e25c61ba 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -89,7 +89,6 @@ namespace OpenRCT2::Scripting void Load(); void Start(); void Stop(); - void Update(); private: void LoadCodeFromFile(); diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index e4d17717a3..0411c415a6 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -34,7 +34,7 @@ namespace OpenRCT2::Scripting TileElement* _element; public: - ScTileElement(CoordsXY coords, TileElement* element) + ScTileElement(const CoordsXY& coords, TileElement* element) : _coords(coords) , _element(element) { @@ -896,7 +896,7 @@ namespace OpenRCT2::Scripting CoordsXY _coords; public: - ScTile(CoordsXY coords) + ScTile(const CoordsXY& coords) : _coords(coords) { } @@ -904,12 +904,12 @@ namespace OpenRCT2::Scripting private: int32_t x_get() { - return _coords.x / 32; + return _coords.x / COORDS_XY_STEP; } int32_t y_get() { - return _coords.y / 32; + return _coords.y / COORDS_XY_STEP; } size_t numElements_get() diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 9a7d38dd80..84f997bdd4 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -885,15 +885,19 @@ void ScriptEngine::LoadSharedStorage() auto path = _env.GetFilePath(PATHID::PLUGIN_STORE); try { - auto data = File::ReadAllBytes(path); - auto result = DuktapeTryParseJson(_context, std::string_view((const char*)data.data(), data.size())); - if (result) + if (File::Exists(path)) { - _sharedStorage = std::move(*result); + auto data = File::ReadAllBytes(path); + auto result = DuktapeTryParseJson(_context, std::string_view((const char*)data.data(), data.size())); + if (result) + { + _sharedStorage = std::move(*result); + } } } catch (const std::exception&) { + fprintf(stderr, "Unable to read '%s'\n", path.c_str()); } } From 6cbea2fd37ba0497df08aba20eb97f3dcdd106a4 Mon Sep 17 00:00:00 2001 From: Ted John Date: Wed, 22 Apr 2020 23:20:54 +0100 Subject: [PATCH 136/159] Change baseZ / clearanceZ to baseHeight / clearanceHeight --- distribution/openrct2.d.ts | 4 ++-- src/openrct2/scripting/ScTile.hpp | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 92d33e6a25..7713bf7c3c 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -309,8 +309,8 @@ declare global { interface BaseTileElement { type: TileElementType; - baseZ: number; - clearanceZ: number; + baseHeight: number; + clearanceHeight: number; } interface SurfaceElement extends BaseTileElement { diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 0411c415a6..e00584a955 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -95,21 +95,21 @@ namespace OpenRCT2::Scripting map_invalidate_tile_full(_coords); } - uint8_t baseZ_get() const + uint8_t baseHeight_get() const { return _element->base_height; } - void baseZ_set(uint8_t newBaseHeight) + void baseHeight_set(uint8_t newBaseHeight) { ThrowIfGameStateNotMutable(); _element->base_height = newBaseHeight; } - uint8_t clearanceZ_get() const + uint8_t clearanceHeight_get() const { return _element->clearance_height; } - void clearanceZ_set(uint8_t newClearanceHeight) + void clearanceHeight_set(uint8_t newClearanceHeight) { ThrowIfGameStateNotMutable(); _element->clearance_height = newClearanceHeight; @@ -824,8 +824,9 @@ namespace OpenRCT2::Scripting { // All dukglue_register_property(ctx, &ScTileElement::type_get, &ScTileElement::type_set, "type"); - dukglue_register_property(ctx, &ScTileElement::baseZ_get, &ScTileElement::baseZ_set, "baseZ"); - dukglue_register_property(ctx, &ScTileElement::clearanceZ_get, &ScTileElement::clearanceZ_set, "clearanceZ"); + dukglue_register_property(ctx, &ScTileElement::baseHeight_get, &ScTileElement::baseHeight_set, "baseHeight"); + dukglue_register_property( + ctx, &ScTileElement::clearanceHeight_get, &ScTileElement::clearanceHeight_set, "clearanceHeight"); // Some dukglue_register_property(ctx, &ScTileElement::object_get, &ScTileElement::object_set, "object"); From c17f898931874207f18befe024cf3da272db1a3e Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Thu, 23 Apr 2020 10:38:47 +0200 Subject: [PATCH 137/159] Xcode: add __ENABLE_SCRIPTING__ preprocessor macro. --- OpenRCT2.xcodeproj/project.pbxproj | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index f7e9e56ed0..a16795c1ad 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -4527,6 +4527,7 @@ GCC_PREPROCESSOR_DEFINITIONS = ( "$(inherited)", __ENABLE_LIGHTFX__, + __ENABLE_SCRIPTING__, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4571,6 +4572,7 @@ GCC_PREPROCESSOR_DEFINITIONS = ( "$(inherited)", __ENABLE_LIGHTFX__, + __ENABLE_SCRIPTING__, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4616,6 +4618,7 @@ "DEBUG=1", "$(inherited)", __ENABLE_LIGHTFX__, + __ENABLE_SCRIPTING__, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4658,6 +4661,7 @@ OPENGL_NO_LINK, "OPENRCT2_BUILD_INFO_HEADER=\"\\\"$(DERIVED_FILE_DIR)/gitversion.h\\\"\"", __ENABLE_LIGHTFX__, + __ENABLE_SCRIPTING__, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4698,6 +4702,7 @@ "DEBUG=1", "$(inherited)", __ENABLE_LIGHTFX__, + __ENABLE_SCRIPTING__, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; HEADER_SEARCH_PATHS = ( @@ -4732,6 +4737,7 @@ OPENGL_NO_LINK, "OPENRCT2_BUILD_INFO_HEADER=\"\\\"$(DERIVED_FILE_DIR)/gitversion.h\\\"\"", __ENABLE_LIGHTFX__, + __ENABLE_SCRIPTING__, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; HEADER_SEARCH_PATHS = ( From 4c45e0ceb048a3e30bca7765c7b94e218d282107 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 23 Apr 2020 19:28:53 +0100 Subject: [PATCH 138/159] Remove use of .value() --- src/openrct2-ui/scripting/CustomWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 390ac64986..df8e6216fb 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -302,7 +302,7 @@ namespace OpenRCT2::Ui::Windows if (desc.X && desc.Y) { window = window_create( - { desc.X.value(), desc.Y.value() }, desc.Width, desc.Height, &window_custom_events, WC_CUSTOM, windowFlags); + { *desc.X, *desc.Y }, desc.Width, desc.Height, &window_custom_events, WC_CUSTOM, windowFlags); } else { From c1ab8b0b31be1eec0c217c7f14766403f8e14b27 Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 23 Apr 2020 19:31:56 +0100 Subject: [PATCH 139/159] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Breno Rodrigues Guimarães --- distribution/scripting.md | 2 +- src/openrct2-ui/scripting/CustomWindow.cpp | 9 +++++---- src/openrct2/scripting/HookEngine.cpp | 13 ++----------- src/openrct2/scripting/HookEngine.h | 6 +----- src/openrct2/scripting/ScContext.hpp | 2 -- src/openrct2/scripting/ScDisposable.hpp | 2 +- src/openrct2/scripting/ScNetwork.hpp | 8 ++------ 7 files changed, 12 insertions(+), 30 deletions(-) diff --git a/distribution/scripting.md b/distribution/scripting.md index 1402113126..e31701b518 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -60,7 +60,7 @@ Yes, but the performance would be so dire that it would be a waste of their time > What are the limits? -Scripts can conist of any behaviour and have a large memory pool available to them. The speed will vary depending on the hardware and system executing them. The scripts are interpreted, so do not expect anywhere close to the performance of native code. In most scenarios this should be satisfactory, but a random map generator, or genetic algorithm for building roller coasters might struggle. Like any language, there will be tricks to optimising JavaScript and the use of the OpenRCT2 APIs. +Scripts can consist of any behaviour and have a large memory pool available to them. The speed will vary depending on the hardware and system executing them. The scripts are interpreted, so do not expect anywhere close to the performance of native code. In most scenarios this should be satisfactory, but a random map generator, or genetic algorithm for building roller coasters might struggle. Like any language, there will be tricks to optimising JavaScript and the use of the OpenRCT2 APIs. The APIs for OpenRCT2 try to mimic the internal data structures as close as possible but we can only add so many at a time. The best way to grow the plug-in system is to add APIs on-demand. So if you find an API is missing, please raise an issue for it on GitHub and also feel free to submit a pull request afterwards. diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index df8e6216fb..d0053058af 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -284,9 +284,9 @@ namespace OpenRCT2::Ui::Windows static CustomWindowInfo& GetInfo(rct_window* w); static rct_windownumber GetNewWindowNumber(); static void RefreshWidgets(rct_window* w); - static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler); + static void InvokeEventHandler(const std::shared_ptr& owner, const DukValue& dukHandler); static void InvokeEventHandler( - std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args); + const std::shared_ptr& owner, const DukValue& dukHandler, const std::vector& args); rct_window* window_custom_open(std::shared_ptr owner, DukValue dukDesc) { @@ -706,13 +706,14 @@ namespace OpenRCT2::Ui::Windows } } - static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler) + static void InvokeEventHandler(const std::shared_ptr& owner, const DukValue& dukHandler) { std::vector args; InvokeEventHandler(owner, dukHandler, args); } - static void InvokeEventHandler(std::shared_ptr owner, const DukValue& dukHandler, const std::vector& args) + static void InvokeEventHandler( + const std::shared_ptr& owner, const DukValue& dukHandler, const std::vector& args) { auto& scriptEngine = GetContext()->GetScriptEngine(); scriptEngine.ExecutePluginCall(owner, dukHandler, args, false); diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 8263a88701..5211ca6154 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -68,17 +68,8 @@ void HookEngine::UnsubscribeAll(std::shared_ptr owner) for (auto& hookList : _hookMap) { auto& hooks = hookList.Hooks; - for (auto it = hooks.begin(); it != hooks.end();) - { - if (it->Owner == owner) - { - it = hooks.erase(it); - } - else - { - it++; - } - } + auto isOwner = [&](auto& obj) { return obj.Owner == owner; }; + hooks.erase(std::remove_if(hooks.begin(), hooks.end(), isOwner), hooks.end()); } } diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index fb42a6b733..8179c38fb7 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -61,11 +61,7 @@ namespace OpenRCT2::Scripting HookList() = default; HookList(const HookList&) = delete; - HookList(HookList&& src) noexcept - : Type(std::move(src.Type)) - , Hooks(std::move(src.Hooks)) - { - } + HookList(HookList&& src) = default; }; class HookEngine diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index b4b818039d..8c3dcf5be2 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -59,10 +59,8 @@ namespace OpenRCT2::Scripting { case OBJECT_TYPE_RIDE: return GetObjectAsDukValue(ctx, std::make_shared(type, index)); - break; default: return GetObjectAsDukValue(ctx, std::make_shared(type, index)); - break; } } diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index 69e1170206..4bd43a0e7b 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -23,7 +23,7 @@ namespace OpenRCT2::Scripting std::function _onDispose; public: - ScDisposable(std::function onDispose) + ScDisposable(const std::function& onDispose) : _onDispose(onDispose) { } diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index 1097c9b7ac..adb778e857 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -131,7 +131,7 @@ namespace OpenRCT2::Scripting private: std::string TransformPermissionKeyToJS(const std::string& s) { - auto result = s.substr(11); + auto result = s.substr(sizeof("PERMISSION_") - 1); for (auto& c : result) { c = std::tolower(c); @@ -263,17 +263,13 @@ namespace OpenRCT2::Scripting # ifndef DISABLE_NETWORK switch (network_get_mode()) { - default: - case NETWORK_MODE_NONE: - return "none"; case NETWORK_MODE_SERVER: return "server"; case NETWORK_MODE_CLIENT: return "client"; } -# else - return "none"; # endif + return "none"; } int32_t players_get() { From 3c28861122dad1db14a5abb09cc54402858816fc Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Thu, 23 Apr 2020 20:55:53 +0200 Subject: [PATCH 140/159] Xcode: add FileWatcher, scripting/ --- OpenRCT2.xcodeproj/project.pbxproj | 92 ++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index a16795c1ad..da8fdba36c 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -108,6 +108,27 @@ 93CBA4CC20A7504500867D56 /* ImageImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = 93CBA4C820A7504500867D56 /* ImageImporter.h */; }; 93DE9751209C3C1000FB1CC8 /* GameState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93DE974E209C3C0F00FB1CC8 /* GameState.cpp */; }; 93DE9753209C3C1000FB1CC8 /* GameState.h in Headers */ = {isa = PBXBuildFile; fileRef = 93DE974F209C3C0F00FB1CC8 /* GameState.h */; }; + 93DFD02E24521BA0001FCBAF /* FileWatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD02C24521B9F001FCBAF /* FileWatcher.h */; }; + 93DFD02F24521BA0001FCBAF /* FileWatcher.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93DFD02D24521BA0001FCBAF /* FileWatcher.cpp */; }; + 93DFD04424521C1A001FCBAF /* Plugin.h in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03124521C19001FCBAF /* Plugin.h */; }; + 93DFD04524521C1A001FCBAF /* ScObject.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03224521C19001FCBAF /* ScObject.hpp */; }; + 93DFD04624521C1A001FCBAF /* HookEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03324521C19001FCBAF /* HookEngine.h */; }; + 93DFD04724521C1A001FCBAF /* ScNetwork.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03424521C19001FCBAF /* ScNetwork.hpp */; }; + 93DFD04824521C1A001FCBAF /* HookEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93DFD03524521C19001FCBAF /* HookEngine.cpp */; }; + 93DFD04924521C1A001FCBAF /* ScTile.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03624521C19001FCBAF /* ScTile.hpp */; }; + 93DFD04A24521C1A001FCBAF /* ScConfiguration.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03724521C19001FCBAF /* ScConfiguration.hpp */; }; + 93DFD04B24521C1A001FCBAF /* ScriptEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93DFD03824521C19001FCBAF /* ScriptEngine.cpp */; }; + 93DFD04C24521C1A001FCBAF /* ScDisposable.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03924521C19001FCBAF /* ScDisposable.hpp */; }; + 93DFD04D24521C1A001FCBAF /* ScEntity.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03A24521C19001FCBAF /* ScEntity.hpp */; }; + 93DFD04E24521C1A001FCBAF /* Duktape.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03B24521C19001FCBAF /* Duktape.hpp */; }; + 93DFD04F24521C1A001FCBAF /* ScConsole.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03C24521C19001FCBAF /* ScConsole.hpp */; }; + 93DFD05024521C1A001FCBAF /* ScPark.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03D24521C19001FCBAF /* ScPark.hpp */; }; + 93DFD05124521C1A001FCBAF /* ScContext.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD03E24521C19001FCBAF /* ScContext.hpp */; }; + 93DFD05224521C1A001FCBAF /* Plugin.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93DFD03F24521C19001FCBAF /* Plugin.cpp */; }; + 93DFD05324521C1A001FCBAF /* ScRide.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD04024521C19001FCBAF /* ScRide.hpp */; }; + 93DFD05424521C1A001FCBAF /* ScDate.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD04124521C19001FCBAF /* ScDate.hpp */; }; + 93DFD05524521C1A001FCBAF /* ScMap.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD04224521C19001FCBAF /* ScMap.hpp */; }; + 93DFD05624521C1A001FCBAF /* ScriptEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 93DFD04324521C19001FCBAF /* ScriptEngine.h */; }; 93F6004C213DD7DD00EEB83E /* TerrainSurfaceObject.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93F60049213DD7DC00EEB83E /* TerrainSurfaceObject.cpp */; }; 93F6004D213DD7DD00EEB83E /* TerrainEdgeObject.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93F6004A213DD7DC00EEB83E /* TerrainEdgeObject.cpp */; }; 93F60050213DD7E400EEB83E /* StationObject.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93F6004F213DD7E300EEB83E /* StationObject.cpp */; }; @@ -1294,6 +1315,27 @@ 93CBA4C820A7504500867D56 /* ImageImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImageImporter.h; sourceTree = ""; }; 93DE974E209C3C0F00FB1CC8 /* GameState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GameState.cpp; sourceTree = ""; }; 93DE974F209C3C0F00FB1CC8 /* GameState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameState.h; sourceTree = ""; }; + 93DFD02C24521B9F001FCBAF /* FileWatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FileWatcher.h; sourceTree = ""; }; + 93DFD02D24521BA0001FCBAF /* FileWatcher.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FileWatcher.cpp; sourceTree = ""; }; + 93DFD03124521C19001FCBAF /* Plugin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Plugin.h; sourceTree = ""; }; + 93DFD03224521C19001FCBAF /* ScObject.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScObject.hpp; sourceTree = ""; }; + 93DFD03324521C19001FCBAF /* HookEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HookEngine.h; sourceTree = ""; }; + 93DFD03424521C19001FCBAF /* ScNetwork.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScNetwork.hpp; sourceTree = ""; }; + 93DFD03524521C19001FCBAF /* HookEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HookEngine.cpp; sourceTree = ""; }; + 93DFD03624521C19001FCBAF /* ScTile.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScTile.hpp; sourceTree = ""; }; + 93DFD03724521C19001FCBAF /* ScConfiguration.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScConfiguration.hpp; sourceTree = ""; }; + 93DFD03824521C19001FCBAF /* ScriptEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScriptEngine.cpp; sourceTree = ""; }; + 93DFD03924521C19001FCBAF /* ScDisposable.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScDisposable.hpp; sourceTree = ""; }; + 93DFD03A24521C19001FCBAF /* ScEntity.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScEntity.hpp; sourceTree = ""; }; + 93DFD03B24521C19001FCBAF /* Duktape.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = Duktape.hpp; sourceTree = ""; }; + 93DFD03C24521C19001FCBAF /* ScConsole.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScConsole.hpp; sourceTree = ""; }; + 93DFD03D24521C19001FCBAF /* ScPark.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScPark.hpp; sourceTree = ""; }; + 93DFD03E24521C19001FCBAF /* ScContext.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScContext.hpp; sourceTree = ""; }; + 93DFD03F24521C19001FCBAF /* Plugin.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Plugin.cpp; sourceTree = ""; }; + 93DFD04024521C19001FCBAF /* ScRide.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScRide.hpp; sourceTree = ""; }; + 93DFD04124521C19001FCBAF /* ScDate.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScDate.hpp; sourceTree = ""; }; + 93DFD04224521C19001FCBAF /* ScMap.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ScMap.hpp; sourceTree = ""; }; + 93DFD04324521C19001FCBAF /* ScriptEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScriptEngine.h; sourceTree = ""; }; 93F60048213DD7DC00EEB83E /* TerrainSurfaceObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TerrainSurfaceObject.h; sourceTree = ""; }; 93F60049213DD7DC00EEB83E /* TerrainSurfaceObject.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TerrainSurfaceObject.cpp; sourceTree = ""; }; 93F6004A213DD7DC00EEB83E /* TerrainEdgeObject.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TerrainEdgeObject.cpp; sourceTree = ""; }; @@ -2185,6 +2227,32 @@ path = config; sourceTree = ""; }; + 93DFD03024521C19001FCBAF /* scripting */ = { + isa = PBXGroup; + children = ( + 93DFD03B24521C19001FCBAF /* Duktape.hpp */, + 93DFD03524521C19001FCBAF /* HookEngine.cpp */, + 93DFD03324521C19001FCBAF /* HookEngine.h */, + 93DFD03F24521C19001FCBAF /* Plugin.cpp */, + 93DFD03124521C19001FCBAF /* Plugin.h */, + 93DFD03724521C19001FCBAF /* ScConfiguration.hpp */, + 93DFD03C24521C19001FCBAF /* ScConsole.hpp */, + 93DFD03E24521C19001FCBAF /* ScContext.hpp */, + 93DFD04124521C19001FCBAF /* ScDate.hpp */, + 93DFD03924521C19001FCBAF /* ScDisposable.hpp */, + 93DFD03A24521C19001FCBAF /* ScEntity.hpp */, + 93DFD04224521C19001FCBAF /* ScMap.hpp */, + 93DFD03424521C19001FCBAF /* ScNetwork.hpp */, + 93DFD03224521C19001FCBAF /* ScObject.hpp */, + 93DFD03D24521C19001FCBAF /* ScPark.hpp */, + 93DFD04024521C19001FCBAF /* ScRide.hpp */, + 93DFD03824521C19001FCBAF /* ScriptEngine.cpp */, + 93DFD04324521C19001FCBAF /* ScriptEngine.h */, + 93DFD03624521C19001FCBAF /* ScTile.hpp */, + ); + path = scripting; + sourceTree = ""; + }; C6352B871F477032006CCEE3 /* actions */ = { isa = PBXGroup; children = ( @@ -2617,6 +2685,7 @@ F76C846C1EC4E7CC00FA49E2 /* rct12 */, F76C84831EC4E7CC00FA49E2 /* ride */, F76C84F31EC4E7CD00FA49E2 /* scenario */, + 93DFD03024521C19001FCBAF /* scripting */, F76C84FB1EC4E7CD00FA49E2 /* title */, F76C85041EC4E7CD00FA49E2 /* ui */, F76C85061EC4E7CD00FA49E2 /* util */, @@ -2736,6 +2805,8 @@ F76C83811EC4E7CC00FA49E2 /* FileScanner.cpp */, F76C83821EC4E7CC00FA49E2 /* FileScanner.h */, F76C83831EC4E7CC00FA49E2 /* FileStream.hpp */, + 93DFD02D24521BA0001FCBAF /* FileWatcher.cpp */, + 93DFD02C24521B9F001FCBAF /* FileWatcher.h */, F76C83841EC4E7CC00FA49E2 /* Guard.cpp */, F76C83851EC4E7CC00FA49E2 /* Guard.hpp */, 4C8A6FF223EB5326001A8255 /* Http.cURL.cpp */, @@ -3576,36 +3647,53 @@ isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( + 93DFD05624521C1A001FCBAF /* ScriptEngine.h in Headers */, 2ADE2F3122441905002598AF /* DiscordService.h in Headers */, C67B28172002D67A00109C93 /* Viewport.h in Headers */, 939A359C20C12FC800630B3F /* Paint.Sprite.h in Headers */, + 93DFD05524521C1A001FCBAF /* ScMap.hpp in Headers */, 9308DA04209908090079EE96 /* TileElement.h in Headers */, C67B28152002D67A00109C93 /* Widget.h in Headers */, C6352B851F477022006CCEE3 /* DataSerialiserTraits.h in Headers */, + 93DFD05124521C1A001FCBAF /* ScContext.hpp in Headers */, 939A359F20C12FDE00630B3F /* Paint.Surface.h in Headers */, C67B28192002D7F200109C93 /* Window_internal.h in Headers */, + 93DFD05024521C1A001FCBAF /* ScPark.hpp in Headers */, + 93DFD02E24521BA0001FCBAF /* FileWatcher.h in Headers */, 2ADE2F28224418B2002598AF /* DataSerialiserTag.h in Headers */, + 93DFD04C24521C1A001FCBAF /* ScDisposable.hpp in Headers */, 2ADE2F2E224418E7002598AF /* ConversionTables.h in Headers */, 933F2CBB20935668001B33FD /* LocalisationService.h in Headers */, C6352B861F477022006CCEE3 /* Endianness.h in Headers */, 2ADE2F2C224418B2002598AF /* FileIndex.hpp in Headers */, + 93DFD04A24521C1A001FCBAF /* ScConfiguration.hpp in Headers */, 93CBA4CC20A7504500867D56 /* ImageImporter.h in Headers */, 2ADE2F29224418B2002598AF /* Numerics.hpp in Headers */, + 93DFD04924521C1A001FCBAF /* ScTile.hpp in Headers */, + 93DFD04524521C1A001FCBAF /* ScObject.hpp in Headers */, 2ADE2F382244198B002598AF /* SpriteBase.h in Headers */, C62D838B1FD36D6F008C04F1 /* EditorObjectSelectionSession.h in Headers */, 2ADE2F27224418B2002598AF /* Random.hpp in Headers */, 9344BEF920C1E6180047D165 /* Crypt.h in Headers */, 939A35A220C12FFD00630B3F /* InteractiveConsole.h in Headers */, 93CBA4C320A7502E00867D56 /* Imaging.h in Headers */, + 93DFD04D24521C1A001FCBAF /* ScEntity.hpp in Headers */, + 93DFD04E24521C1A001FCBAF /* Duktape.hpp in Headers */, 2ADE2F2B224418B2002598AF /* JobPool.hpp in Headers */, 2ADE2F3622441960002598AF /* RideTypes.h in Headers */, + 93DFD05324521C1A001FCBAF /* ScRide.hpp in Headers */, + 93DFD05424521C1A001FCBAF /* ScDate.hpp in Headers */, 93FC08FF2418F3ED00CA3054 /* duktape.h in Headers */, + 93DFD04F24521C1A001FCBAF /* ScConsole.hpp in Headers */, 9308DA05209908090079EE96 /* Surface.h in Headers */, 93DE9753209C3C1000FB1CC8 /* GameState.h in Headers */, 2ADE2F2A224418B2002598AF /* Meta.hpp in Headers */, + 93DFD04624521C1A001FCBAF /* HookEngine.h in Headers */, 93FC09002418F3ED00CA3054 /* duk_config.h in Headers */, C6352B841F477022006CCEE3 /* DataSerialiser.h in Headers */, 939A35A020C12FDE00630B3F /* Paint.TileElement.h in Headers */, + 93DFD04724521C1A001FCBAF /* ScNetwork.hpp in Headers */, + 93DFD04424521C1A001FCBAF /* Plugin.h in Headers */, C67B28162002D67A00109C93 /* Window.h in Headers */, 2ADE2F342244191E002598AF /* VirtualFloor.h in Headers */, ); @@ -4174,6 +4262,7 @@ F76C864D1EC4E88300FA49E2 /* NetworkGroup.cpp in Sources */, F76C864F1EC4E88300FA49E2 /* NetworkKey.cpp in Sources */, C688789620289B140084B384 /* Viewport.cpp in Sources */, + 93DFD05224521C1A001FCBAF /* Plugin.cpp in Sources */, C68878A520289B2A0084B384 /* Award.cpp in Sources */, F76C86511EC4E88300FA49E2 /* NetworkPacket.cpp in Sources */, F76C86531EC4E88300FA49E2 /* NetworkPlayer.cpp in Sources */, @@ -4190,6 +4279,7 @@ F76C86601EC4E88300FA49E2 /* BannerObject.cpp in Sources */, C688792A20289B9B0084B384 /* Lift.cpp in Sources */, F76C86621EC4E88300FA49E2 /* EntranceObject.cpp in Sources */, + 93DFD04824521C1A001FCBAF /* HookEngine.cpp in Sources */, C688792820289B9B0084B384 /* Twist.cpp in Sources */, C688792D20289B9B0084B384 /* SuspendedMonorail.cpp in Sources */, C688788620289ADE0084B384 /* TTF.cpp in Sources */, @@ -4201,6 +4291,7 @@ C688793420289B9B0084B384 /* WaterCoaster.cpp in Sources */, F76C86681EC4E88300FA49E2 /* ImageTable.cpp in Sources */, C68878E620289B9B0084B384 /* Platform.Linux.cpp in Sources */, + 93DFD04B24521C1A001FCBAF /* ScriptEngine.cpp in Sources */, C688785B20289A0A0084B384 /* Duck.cpp in Sources */, F76C866A1EC4E88300FA49E2 /* LargeSceneryObject.cpp in Sources */, C688788E20289AE70084B384 /* SSE41Drawing.cpp in Sources */, @@ -4287,6 +4378,7 @@ C688790A20289B9B0084B384 /* WoodenRollerCoaster.cpp in Sources */, C688787220289A780084B384 /* MusicList.cpp in Sources */, 93F76F0220BFF77B00D4512C /* Paint.Surface.cpp in Sources */, + 93DFD02F24521BA0001FCBAF /* FileWatcher.cpp in Sources */, F76C871C1EC4E88400FA49E2 /* TrackDesignRepository.cpp in Sources */, C68878FA20289B9B0084B384 /* LoopingRollerCoaster.cpp in Sources */, C68878A720289B2A0084B384 /* Marketing.cpp in Sources */, From 127dd1543ed328ee3278ae23e1d181606c4009bc Mon Sep 17 00:00:00 2001 From: Ted John Date: Thu, 23 Apr 2020 21:21:21 +0100 Subject: [PATCH 141/159] Disable FileWatcher for macOS --- src/openrct2/core/FileWatcher.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/openrct2/core/FileWatcher.cpp b/src/openrct2/core/FileWatcher.cpp index b9921e4d71..2d8d6f5839 100644 --- a/src/openrct2/core/FileWatcher.cpp +++ b/src/openrct2/core/FileWatcher.cpp @@ -8,12 +8,13 @@ *****************************************************************************/ #include +#include #include #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # include -#else +#elif defined(__linux__) # include # include # include @@ -24,7 +25,7 @@ #include "FileSystem.hpp" #include "FileWatcher.h" -#ifndef _WIN32 +#if defined(__linux__) FileWatcher::FileDescriptor::~FileDescriptor() { Close(); @@ -92,7 +93,7 @@ FileWatcher::FileWatcher(const std::string& directoryPath) { throw std::runtime_error("Unable to open directory '" + directoryPath + "'"); } -#else +#elif defined(__linux__) _fileDesc.Initialise(); _watchDescs.emplace_back(_fileDesc.Fd, directoryPath); for (auto& p : fs::recursive_directory_iterator(directoryPath)) @@ -102,6 +103,8 @@ FileWatcher::FileWatcher(const std::string& directoryPath) _watchDescs.emplace_back(_fileDesc.Fd, p.path().string()); } } +#else + throw std::runtime_error("FileWatcher not supported on this platform."); #endif _watchThread = std::thread(std::bind(&FileWatcher::WatchDirectory, this)); } @@ -117,16 +120,18 @@ FileWatcher::~FileWatcher() CancelIoEx(_directoryHandle, nullptr); # endif CloseHandle(_directoryHandle); -#else +#elif defined(__linux__) _finished = true; _fileDesc.Close(); +#else + return; #endif _watchThread.join(); } void FileWatcher::WatchDirectory() { -#ifdef _WIN32 +#if defined(_WIN32) std::array eventData; DWORD bytesReturned; while (ReadDirectoryChangesW( @@ -150,7 +155,7 @@ void FileWatcher::WatchDirectory() } while (notifyInfo->NextEntryOffset != 0); } } -#else +#elif defined(__linux__) log_verbose("FileWatcher: reading event data..."); std::array eventData; while (!_finished) From 161985259a2df990f11013c38a762c7868d513e5 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Thu, 23 Apr 2020 23:22:29 +0200 Subject: [PATCH 142/159] Xcode: change deployment target to 10.14. This is really unfortunate, but appears to be unavoidable. --- OpenRCT2.xcodeproj/project.pbxproj | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index da8fdba36c..d6cbe34616 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -4643,6 +4643,7 @@ "$(inherited)", "$(PROJECT_DIR)/libxc/lib", ); + MACOSX_DEPLOYMENT_TARGET = 10.14; PRODUCT_BUNDLE_IDENTIFIER = io.openrct2.OpenRCT2; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -4688,6 +4689,7 @@ "$(inherited)", "$(PROJECT_DIR)/libxc/lib", ); + MACOSX_DEPLOYMENT_TARGET = 10.14; PRODUCT_BUNDLE_IDENTIFIER = io.openrct2.OpenRCT2; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -4729,7 +4731,7 @@ "$(inherited)", "$(PROJECT_DIR)/libxc/lib", ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.14; PRIVATE_HEADERS_FOLDER_PATH = "$(CONTENTS_FOLDER_PATH)/PrivateHeaders"; PRODUCT_NAME = "$(TARGET_NAME)"; PUBLIC_HEADERS_FOLDER_PATH = "$(CONTENTS_FOLDER_PATH)/Headers"; @@ -4772,7 +4774,7 @@ "$(inherited)", "$(PROJECT_DIR)/libxc/lib", ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.14; PRIVATE_HEADERS_FOLDER_PATH = "$(CONTENTS_FOLDER_PATH)/PrivateHeaders"; PRODUCT_NAME = "$(TARGET_NAME)"; PUBLIC_HEADERS_FOLDER_PATH = "$(CONTENTS_FOLDER_PATH)/Headers"; @@ -4809,7 +4811,7 @@ "$(inherited)", "$(PROJECT_DIR)/libxc/lib", ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.14; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; @@ -4844,7 +4846,7 @@ "$(inherited)", "$(PROJECT_DIR)/libxc/lib", ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.14; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; From 3fe49ca2a35edf211ada6a7ba16eb85c09efdbd4 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 13:23:39 +0100 Subject: [PATCH 143/159] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Michał Janiszewski Co-Authored-By: Aaron van Geffen Co-Authored-By: Tulio Leao --- distribution/scripting.md | 4 ++-- src/openrct2-ui/interface/InGameConsole.h | 2 -- src/openrct2-ui/scripting/ScUi.hpp | 2 +- src/openrct2/scripting/Plugin.h | 4 ++-- src/openrct2/scripting/ScObject.hpp | 2 +- 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/distribution/scripting.md b/distribution/scripting.md index e31701b518..4be8ba207e 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -2,7 +2,7 @@ OpenRCT2 allows custom scripts (also known as plug-ins) to be written and executed in the game providing additional behaviour on top of the vanilla experience. This can range from extra windows providing information about the park to entire new multiplayer game modes. -Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This is usually `C:\Users\YourName\Documents\OpenRCT2` on Windows, or `/home/YourName/.config/openrct2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively. So if you want to prevent a plug-in from being used, you must move it outside this directory, or rename it so the filename does not end with `.js`. +Each script is a single physical javascript file within the `plugin` directory in your OpenRCT2 user directory. This is usually `C:\Users\YourName\Documents\OpenRCT2` on Windows, or `$XDG_CONFIG_HOME/OpenRCT2` or in its absence `$HOME/.config/OpenRCT2` on Linux. OpenRCT2 will load every single file with the extension `.js` in this directory recursively. So if you want to prevent a plug-in from being used, you must move it outside this directory, or rename it so the filename does not end with `.js`. There are two types of scripts: * Local @@ -44,7 +44,7 @@ The hot reload feature can be enabled by editing your `config.ini` file and sett > Why was JavaScript chosen instead of LUA or Python. -JavaScript is a very mature and flexible language with a large, if not largest, resource base available. There are arguably more transpilers, tools, and libraries for JavaScript than any other language. That and also it using a familiar C-like syntax and 0-indexed arrays make it more suitable than LUA and Python. Of course if you would still like to use LUA or another language, there will likely be a JavaScript transpiler for it. +JavaScript is a very mature and flexible language with a large, if not the largest, resource base available. There are arguably more transpilers, tools, and libraries for JavaScript than any other language. That and also it using a familiar C-like syntax and 0-indexed arrays make it more suitable than LUA and Python. Of course if you would still like to use LUA or another language, there will likely be a JavaScript transpiler for it. Another benefit of using JavaScript is that you get rich editor features such as completion and API documentation by using a TypeScript definition file which works for both TypeScript and JavaScript. [Visual Studio Code](https://code.visualstudio.com) is recommended, as that supports the workflow very well. See the [OpenRCT2 plugin hot-reload demo](https://www.youtube.com/watch?v=jmjWzEhmDjk) video for a demonstration of the editor functionality. diff --git a/src/openrct2-ui/interface/InGameConsole.h b/src/openrct2-ui/interface/InGameConsole.h index 42af4c3ea6..601b4b9743 100644 --- a/src/openrct2-ui/interface/InGameConsole.h +++ b/src/openrct2-ui/interface/InGameConsole.h @@ -9,10 +9,8 @@ #pragma once -#include #include #include -#include namespace OpenRCT2::Ui { diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 820ec0f3f5..9a812ff0c0 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -46,7 +46,7 @@ namespace OpenRCT2::Scripting } private: - int32_t width_get() + int32_t width_get() const { return context_get_width(); } diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index d7e25c61ba..3c70d911d1 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -40,7 +40,7 @@ namespace OpenRCT2::Scripting std::string Name; std::string Version; std::vector Authors; - PluginType Type; + PluginType Type{}; int32_t MinApiVersion{}; DukValue Main; }; @@ -50,7 +50,7 @@ namespace OpenRCT2::Scripting private: duk_context* _context{}; std::string _path; - PluginMetadata _metadata; + PluginMetadata _metadata{}; std::string _code; bool _hasStarted{}; diff --git a/src/openrct2/scripting/ScObject.hpp b/src/openrct2/scripting/ScObject.hpp index bd049e767e..b3124edfed 100644 --- a/src/openrct2/scripting/ScObject.hpp +++ b/src/openrct2/scripting/ScObject.hpp @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2020 OpenRCT2 developers + * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 From 4e1fa6a944335f240ea66a5998cc5786afd5cab5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 13:24:17 +0100 Subject: [PATCH 144/159] Update src/openrct2/scripting/ScriptEngine.h MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Breno Rodrigues Guimarães --- src/openrct2/scripting/ScriptEngine.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index d54ad8d3d2..8257dd769b 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -92,6 +92,7 @@ namespace OpenRCT2::Scripting DukContext(DukContext&& src) noexcept : _context(std::move(src._context)) { + src._context = {}; } ~DukContext(); From ad75cb07543b9524f00d98f484b4c03c9f4216ea Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 13:24:26 +0100 Subject: [PATCH 145/159] Update src/openrct2/scripting/ScriptEngine.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Breno Rodrigues Guimarães --- src/openrct2/scripting/ScriptEngine.cpp | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 84f997bdd4..5c93d7313a 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -821,17 +821,8 @@ bool ScriptEngine::RegisterCustomAction( void ScriptEngine::RemoveCustomGameActions(const std::shared_ptr& plugin) { - for (auto it = _customActions.begin(); it != _customActions.end();) - { - if (it->second.Owner == plugin) - { - it = _customActions.erase(it); - } - else - { - it++; - } - } + auto isOwner = [&] (auto& obj) { return obj.second.Owner == plugin; } + std::erase(std::remove_if(_customActions.begin(), _customActions.end(), isOwner), _customActions.end()); } void ScriptEngine::RunGameActionHooks(const GameAction& action, std::unique_ptr& result, bool isExecute) From 4162ad0eb67fa2468b457c0d6604051bb41a68c9 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 13:26:55 +0100 Subject: [PATCH 146/159] Remove unused getWindow parameter --- distribution/openrct2.d.ts | 2 +- src/openrct2-ui/scripting/ScUi.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/distribution/openrct2.d.ts b/distribution/openrct2.d.ts index 7713bf7c3c..1386a99e04 100644 --- a/distribution/openrct2.d.ts +++ b/distribution/openrct2.d.ts @@ -640,7 +640,7 @@ declare global { readonly mainViewport: Viewport; getWindow(id: number): Window; - getWindow(classification: string, id?: number): Window; + getWindow(classification: string): Window; openWindow(desc: WindowDesc): Window; closeWindows(classification: string, id?: number): void; closeAllWindows(): void; diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 9a812ff0c0..e00a898939 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -101,7 +101,7 @@ namespace OpenRCT2::Scripting window_close_all(); } - std::shared_ptr getWindow(DukValue a, DukValue b) + std::shared_ptr getWindow(DukValue a) { if (a.type() == DukValue::Type::NUMBER) { From 4ebd8da630ca8a3de8c888720a4b74bad52a429e Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 13:38:27 +0100 Subject: [PATCH 147/159] Revert change to RemoveCustomGameActions --- src/openrct2/scripting/ScriptEngine.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 5c93d7313a..84f997bdd4 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -821,8 +821,17 @@ bool ScriptEngine::RegisterCustomAction( void ScriptEngine::RemoveCustomGameActions(const std::shared_ptr& plugin) { - auto isOwner = [&] (auto& obj) { return obj.second.Owner == plugin; } - std::erase(std::remove_if(_customActions.begin(), _customActions.end(), isOwner), _customActions.end()); + for (auto it = _customActions.begin(); it != _customActions.end();) + { + if (it->second.Owner == plugin) + { + it = _customActions.erase(it); + } + else + { + it++; + } + } } void ScriptEngine::RunGameActionHooks(const GameAction& action, std::unique_ptr& result, bool isExecute) From c67962577af449d7325981ed3356ec6e1198e54a Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 15:58:01 +0100 Subject: [PATCH 148/159] Rename __ENABLE_SCRIPTING__ to ENABLE_SCRIPTING --- CMakeLists.txt | 2 +- OpenRCT2.xcodeproj/project.pbxproj | 12 ++++++------ openrct2.common.props | 2 +- src/openrct2-ui/UiContext.cpp | 2 +- src/openrct2-ui/scripting/CustomMenu.cpp | 2 +- src/openrct2-ui/scripting/CustomMenu.h | 2 +- src/openrct2-ui/scripting/CustomWindow.cpp | 2 +- src/openrct2-ui/scripting/CustomWindow.h | 2 +- src/openrct2-ui/scripting/ScUi.hpp | 2 +- src/openrct2-ui/scripting/ScViewport.hpp | 2 +- src/openrct2-ui/scripting/ScWidget.hpp | 2 +- src/openrct2-ui/scripting/ScWindow.hpp | 2 +- src/openrct2-ui/scripting/UiExtensions.cpp | 2 +- src/openrct2-ui/scripting/UiExtensions.h | 2 +- src/openrct2-ui/windows/TopToolbar.cpp | 4 ++-- src/openrct2/Context.cpp | 8 ++++---- src/openrct2/Context.h | 2 +- src/openrct2/Game.cpp | 4 ++-- src/openrct2/GameState.cpp | 4 ++-- src/openrct2/actions/CustomAction.hpp | 2 +- src/openrct2/actions/GameAction.cpp | 4 ++-- src/openrct2/actions/GameActionRegistration.cpp | 2 +- src/openrct2/interface/StdInOutConsole.cpp | 4 ++-- src/openrct2/network/Network.cpp | 6 +++--- src/openrct2/scripting/Duktape.hpp | 2 +- src/openrct2/scripting/HookEngine.cpp | 2 +- src/openrct2/scripting/HookEngine.h | 2 +- src/openrct2/scripting/Plugin.cpp | 2 +- src/openrct2/scripting/Plugin.h | 2 +- src/openrct2/scripting/ScConfiguration.hpp | 2 +- src/openrct2/scripting/ScConsole.hpp | 2 +- src/openrct2/scripting/ScContext.hpp | 2 +- src/openrct2/scripting/ScDate.hpp | 2 +- src/openrct2/scripting/ScDisposable.hpp | 2 +- src/openrct2/scripting/ScEntity.hpp | 2 +- src/openrct2/scripting/ScMap.hpp | 2 +- src/openrct2/scripting/ScNetwork.hpp | 2 +- src/openrct2/scripting/ScObject.hpp | 2 +- src/openrct2/scripting/ScPark.hpp | 2 +- src/openrct2/scripting/ScRide.hpp | 2 +- src/openrct2/scripting/ScTile.hpp | 2 +- src/openrct2/scripting/ScriptEngine.cpp | 2 +- src/openrct2/scripting/ScriptEngine.h | 2 +- 43 files changed, 58 insertions(+), 58 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f0a901263..c66dced475 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -123,7 +123,7 @@ if (ENABLE_LIGHTFX) add_definitions(-D__ENABLE_LIGHTFX__) endif () if (ENABLE_SCRIPTING) - add_definitions(-D__ENABLE_SCRIPTING__) + add_definitions(-DENABLE_SCRIPTING) endif () if (NOT DISABLE_DISCORD_RPC) diff --git a/OpenRCT2.xcodeproj/project.pbxproj b/OpenRCT2.xcodeproj/project.pbxproj index d6cbe34616..1e79ff4859 100644 --- a/OpenRCT2.xcodeproj/project.pbxproj +++ b/OpenRCT2.xcodeproj/project.pbxproj @@ -4619,7 +4619,7 @@ GCC_PREPROCESSOR_DEFINITIONS = ( "$(inherited)", __ENABLE_LIGHTFX__, - __ENABLE_SCRIPTING__, + ENABLE_SCRIPTING, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4665,7 +4665,7 @@ GCC_PREPROCESSOR_DEFINITIONS = ( "$(inherited)", __ENABLE_LIGHTFX__, - __ENABLE_SCRIPTING__, + ENABLE_SCRIPTING, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4712,7 +4712,7 @@ "DEBUG=1", "$(inherited)", __ENABLE_LIGHTFX__, - __ENABLE_SCRIPTING__, + ENABLE_SCRIPTING, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4755,7 +4755,7 @@ OPENGL_NO_LINK, "OPENRCT2_BUILD_INFO_HEADER=\"\\\"$(DERIVED_FILE_DIR)/gitversion.h\\\"\"", __ENABLE_LIGHTFX__, - __ENABLE_SCRIPTING__, + ENABLE_SCRIPTING, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_UNINITIALIZED_AUTOS = YES; @@ -4796,7 +4796,7 @@ "DEBUG=1", "$(inherited)", __ENABLE_LIGHTFX__, - __ENABLE_SCRIPTING__, + ENABLE_SCRIPTING, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; HEADER_SEARCH_PATHS = ( @@ -4831,7 +4831,7 @@ OPENGL_NO_LINK, "OPENRCT2_BUILD_INFO_HEADER=\"\\\"$(DERIVED_FILE_DIR)/gitversion.h\\\"\"", __ENABLE_LIGHTFX__, - __ENABLE_SCRIPTING__, + ENABLE_SCRIPTING, ); GCC_WARN_64_TO_32_BIT_CONVERSION = NO; HEADER_SEARCH_PATHS = ( diff --git a/openrct2.common.props b/openrct2.common.props index 49b68916f3..93aca8cd87 100644 --- a/openrct2.common.props +++ b/openrct2.common.props @@ -54,7 +54,7 @@ C4555: expression has no effect; expected expression with side-effect --> __AVX2__;__SSE4_1__;OPENGL_NO_LINK;_CRT_SECURE_NO_WARNINGS;_USE_MATH_DEFINES;SDL_MAIN_HANDLED;_WINSOCK_DEPRECATED_NO_WARNINGS;NOMINMAX;%(PreprocessorDefinitions) - __ENABLE_SCRIPTING__;%(PreprocessorDefinitions) + ENABLE_SCRIPTING;%(PreprocessorDefinitions) MultiThreaded MultiThreadedDLL true diff --git a/src/openrct2-ui/UiContext.cpp b/src/openrct2-ui/UiContext.cpp index 78d8b9ee75..f29217d915 100644 --- a/src/openrct2-ui/UiContext.cpp +++ b/src/openrct2-ui/UiContext.cpp @@ -120,7 +120,7 @@ public: void Initialise() override { -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING auto& scriptEngine = GetContext()->GetScriptEngine(); UiScriptExtensions::Extend(scriptEngine); #endif diff --git a/src/openrct2-ui/scripting/CustomMenu.cpp b/src/openrct2-ui/scripting/CustomMenu.cpp index eca0ad34db..a2d7ef47b4 100644 --- a/src/openrct2-ui/scripting/CustomMenu.cpp +++ b/src/openrct2-ui/scripting/CustomMenu.cpp @@ -7,7 +7,7 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "CustomMenu.h" diff --git a/src/openrct2-ui/scripting/CustomMenu.h b/src/openrct2-ui/scripting/CustomMenu.h index fa639752af..6d41982e21 100644 --- a/src/openrct2-ui/scripting/CustomMenu.h +++ b/src/openrct2-ui/scripting/CustomMenu.h @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include # include diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index d0053058af..74039ea776 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -7,7 +7,7 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../interface/Dropdown.h" # include "ScUi.hpp" diff --git a/src/openrct2-ui/scripting/CustomWindow.h b/src/openrct2-ui/scripting/CustomWindow.h index 25db69e806..5877673780 100644 --- a/src/openrct2-ui/scripting/CustomWindow.h +++ b/src/openrct2-ui/scripting/CustomWindow.h @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../interface/Window.h" diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index e00a898939..1377acaa9e 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "CustomMenu.h" # include "ScViewport.hpp" diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index e33d7c00a9..100c6ab670 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../interface/Window.h" diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index fc362c15bf..e28f2ff9c0 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../interface/Widget.h" # include "../interface/Window.h" diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index 5561e5ad1e..e885072e32 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "ScWidget.hpp" diff --git a/src/openrct2-ui/scripting/UiExtensions.cpp b/src/openrct2-ui/scripting/UiExtensions.cpp index 93b95901b7..de973d5ef7 100644 --- a/src/openrct2-ui/scripting/UiExtensions.cpp +++ b/src/openrct2-ui/scripting/UiExtensions.cpp @@ -7,7 +7,7 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "UiExtensions.h" diff --git a/src/openrct2-ui/scripting/UiExtensions.h b/src/openrct2-ui/scripting/UiExtensions.h index 7d29bcd41d..0f97ea7b06 100644 --- a/src/openrct2-ui/scripting/UiExtensions.h +++ b/src/openrct2-ui/scripting/UiExtensions.h @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING namespace OpenRCT2::Scripting { diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index 72b61eb4dd..e2e7a67589 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -3288,7 +3288,7 @@ static void top_toolbar_init_map_menu(rct_window* w, rct_widget* widget) gDropdownItemsFormat[i++] = STR_MAPGEN_WINDOW_TITLE; } -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; if (!customMenuItems.empty()) { @@ -3334,7 +3334,7 @@ static void top_toolbar_map_menu_dropdown(int16_t dropdownIndex) } else { -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING const auto& customMenuItems = OpenRCT2::Scripting::CustomMenuItems; auto customIndex = static_cast(dropdownIndex - customStartIndex); if (customMenuItems.size() > customIndex) diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 0a04bea93b..3b0d1a71b8 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -103,7 +103,7 @@ namespace OpenRCT2 std::unique_ptr _discordService; #endif StdInOutConsole _stdInOutConsole; -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING ScriptEngine _scriptEngine; #endif @@ -140,7 +140,7 @@ namespace OpenRCT2 , _audioContext(audioContext) , _uiContext(uiContext) , _localisationService(std::make_unique(env)) -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING , _scriptEngine(_stdInOutConsole, *env) #endif , _painter(std::make_unique(uiContext)) @@ -185,7 +185,7 @@ namespace OpenRCT2 return _uiContext; } -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING Scripting::ScriptEngine& GetScriptEngine() override { return _scriptEngine; @@ -1032,7 +1032,7 @@ namespace OpenRCT2 Twitch::Update(); chat_update(); -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING _scriptEngine.Update(); #endif _stdInOutConsole.ProcessEvalQueue(); diff --git a/src/openrct2/Context.h b/src/openrct2/Context.h index 0ec9465f13..19098f747f 100644 --- a/src/openrct2/Context.h +++ b/src/openrct2/Context.h @@ -114,7 +114,7 @@ namespace OpenRCT2 virtual Localisation::LocalisationService& GetLocalisationService() abstract; virtual IObjectManager& GetObjectManager() abstract; virtual IObjectRepository& GetObjectRepository() abstract; -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING virtual Scripting::ScriptEngine& GetScriptEngine() abstract; #endif virtual ITrackDesignRepository* GetTrackDesignRepository() abstract; diff --git a/src/openrct2/Game.cpp b/src/openrct2/Game.cpp index a3f0b1cfba..0047162ffc 100644 --- a/src/openrct2/Game.cpp +++ b/src/openrct2/Game.cpp @@ -592,14 +592,14 @@ void game_load_init() void game_load_scripts() { -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING GetContext()->GetScriptEngine().LoadPlugins(); #endif } void game_unload_scripts() { -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING GetContext()->GetScriptEngine().UnloadPlugins(); #endif } diff --git a/src/openrct2/GameState.cpp b/src/openrct2/GameState.cpp index 4e9de175a2..4e6543d460 100644 --- a/src/openrct2/GameState.cpp +++ b/src/openrct2/GameState.cpp @@ -269,7 +269,7 @@ void GameState::UpdateLogic() } } -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); hookEngine.Call(HOOK_TYPE::INTERVAL_TICK, true); @@ -279,7 +279,7 @@ void GameState::UpdateLogic() date_update(); _date = Date(gDateMonthsElapsed, gDateMonthTicks); -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING if (day != _date.GetDay()) { hookEngine.Call(HOOK_TYPE::INTERVAL_DAY, true); diff --git a/src/openrct2/actions/CustomAction.hpp b/src/openrct2/actions/CustomAction.hpp index e220598159..3419061a72 100644 --- a/src/openrct2/actions/CustomAction.hpp +++ b/src/openrct2/actions/CustomAction.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../Context.h" # include "../scripting/ScriptEngine.h" diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index 4c82e56f93..04226031a2 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -400,7 +400,7 @@ namespace GameActions } GameActionResult::Ptr result = QueryInternal(action, topLevel); -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING if (result->Error == GA_ERROR::OK && ((network_get_mode() == NETWORK_MODE_NONE) || (flags & GAME_COMMAND_FLAG_NETWORKED))) { @@ -444,7 +444,7 @@ namespace GameActions // Execute the action, changing the game state result = action->Execute(); -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING if (result->Error == GA_ERROR::OK) { auto& scriptEngine = GetContext()->GetScriptEngine(); diff --git a/src/openrct2/actions/GameActionRegistration.cpp b/src/openrct2/actions/GameActionRegistration.cpp index 8f2638cd8d..0d5ce2f7e5 100644 --- a/src/openrct2/actions/GameActionRegistration.cpp +++ b/src/openrct2/actions/GameActionRegistration.cpp @@ -172,7 +172,7 @@ namespace GameActions Register(); Register(); Register(); -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING Register(); #endif } diff --git a/src/openrct2/interface/StdInOutConsole.cpp b/src/openrct2/interface/StdInOutConsole.cpp index 92ed0970c1..ae60a1e033 100644 --- a/src/openrct2/interface/StdInOutConsole.cpp +++ b/src/openrct2/interface/StdInOutConsole.cpp @@ -56,7 +56,7 @@ void StdInOutConsole::Start() std::future StdInOutConsole::Eval(const std::string& s) { -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING auto& scriptEngine = GetContext()->GetScriptEngine(); return scriptEngine.Eval(s); #else @@ -71,7 +71,7 @@ std::future StdInOutConsole::Eval(const std::string& s) void StdInOutConsole::ProcessEvalQueue() { -#ifndef __ENABLE_SCRIPTING__ +#ifndef ENABLE_SCRIPTING while (_evalQueue.size() > 0) { auto item = std::move(_evalQueue.front()); diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 3ed563b753..f38fbf4597 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -1474,7 +1474,7 @@ void Network::Server_Send_SCRIPTS(NetworkConnection& connection) const { std::unique_ptr packet(NetworkPacket::Allocate()); *packet << static_cast(NETWORK_COMMAND_SCRIPTS); -# ifdef __ENABLE_SCRIPTING__ +# ifdef ENABLE_SCRIPTING using namespace OpenRCT2::Scripting; auto& scriptEngine = GetContext()->GetScriptEngine(); @@ -2445,7 +2445,7 @@ void Network::Client_Handle_SCRIPTS(NetworkConnection& connection, NetworkPacket uint32_t numScripts{}; packet >> numScripts; -# ifdef __ENABLE_SCRIPTING__ +# ifdef ENABLE_SCRIPTING auto& scriptEngine = GetContext()->GetScriptEngine(); for (uint32_t i = 0; i < numScripts; i++) { @@ -2888,7 +2888,7 @@ void Network::Client_Handle_CHAT([[maybe_unused]] NetworkConnection& connection, static bool ProcessChatMessagePluginHooks(const NetworkPlayer& player, std::string& text) { -# ifdef __ENABLE_SCRIPTING__ +# ifdef ENABLE_SCRIPTING auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HOOK_TYPE::NETWORK_CHAT)) { diff --git a/src/openrct2/scripting/Duktape.hpp b/src/openrct2/scripting/Duktape.hpp index 6d0874d818..6091b0a2ca 100644 --- a/src/openrct2/scripting/Duktape.hpp +++ b/src/openrct2/scripting/Duktape.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include # include diff --git a/src/openrct2/scripting/HookEngine.cpp b/src/openrct2/scripting/HookEngine.cpp index 5211ca6154..20010f4dc7 100644 --- a/src/openrct2/scripting/HookEngine.cpp +++ b/src/openrct2/scripting/HookEngine.cpp @@ -7,7 +7,7 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "HookEngine.h" diff --git a/src/openrct2/scripting/HookEngine.h b/src/openrct2/scripting/HookEngine.h index 8179c38fb7..8971ad9d60 100644 --- a/src/openrct2/scripting/HookEngine.h +++ b/src/openrct2/scripting/HookEngine.h @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../common.h" # include "Duktape.hpp" diff --git a/src/openrct2/scripting/Plugin.cpp b/src/openrct2/scripting/Plugin.cpp index f0d2e5832f..548539486c 100644 --- a/src/openrct2/scripting/Plugin.cpp +++ b/src/openrct2/scripting/Plugin.cpp @@ -7,7 +7,7 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "Plugin.h" diff --git a/src/openrct2/scripting/Plugin.h b/src/openrct2/scripting/Plugin.h index 3c70d911d1..fdf61aa3dc 100644 --- a/src/openrct2/scripting/Plugin.h +++ b/src/openrct2/scripting/Plugin.h @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "Duktape.hpp" diff --git a/src/openrct2/scripting/ScConfiguration.hpp b/src/openrct2/scripting/ScConfiguration.hpp index e3d8e6a1d4..15ca10d16d 100644 --- a/src/openrct2/scripting/ScConfiguration.hpp +++ b/src/openrct2/scripting/ScConfiguration.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../Context.h" # include "../config/Config.h" diff --git a/src/openrct2/scripting/ScConsole.hpp b/src/openrct2/scripting/ScConsole.hpp index 19edf7cb5d..0b8e90e6aa 100644 --- a/src/openrct2/scripting/ScConsole.hpp +++ b/src/openrct2/scripting/ScConsole.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../interface/InteractiveConsole.h" # include "Duktape.hpp" diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 8c3dcf5be2..2ca39eef1a 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../actions/CustomAction.hpp" # include "../actions/ParkSetNameAction.hpp" diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 25ad7c441e..9ce0b49220 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../Context.h" # include "../Date.h" diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index 4bd43a0e7b..3b57e83ceb 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "Duktape.hpp" diff --git a/src/openrct2/scripting/ScEntity.hpp b/src/openrct2/scripting/ScEntity.hpp index 44b567c908..b386ed4b99 100644 --- a/src/openrct2/scripting/ScEntity.hpp +++ b/src/openrct2/scripting/ScEntity.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../common.h" # include "../world/Sprite.h" diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index b109c67cb6..df1c2d00e4 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../common.h" # include "../ride/Ride.h" diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index adb778e857..25215c17f1 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../actions/NetworkModifyGroupAction.hpp" # include "../actions/PlayerKickAction.hpp" diff --git a/src/openrct2/scripting/ScObject.hpp b/src/openrct2/scripting/ScObject.hpp index b3124edfed..c5cd7db835 100644 --- a/src/openrct2/scripting/ScObject.hpp +++ b/src/openrct2/scripting/ScObject.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../Context.h" # include "../common.h" diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 2226421b73..9476df9596 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../Context.h" # include "../common.h" diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index eb46929ef3..35dde8054e 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../common.h" # include "../ride/Ride.h" diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index e00584a955..df9530b815 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../Context.h" # include "../common.h" diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index 84f997bdd4..889db5a430 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -7,7 +7,7 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "ScriptEngine.h" diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 8257dd769b..23e18756ad 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -9,7 +9,7 @@ #pragma once -#ifdef __ENABLE_SCRIPTING__ +#ifdef ENABLE_SCRIPTING # include "../common.h" # include "../core/FileWatcher.h" From b553850307d050a90493ca658aff5caf7beb18b9 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 16:05:11 +0100 Subject: [PATCH 149/159] Add minimum API version information to scripting readme --- distribution/scripting.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/distribution/scripting.md b/distribution/scripting.md index 4be8ba207e..d476871e55 100644 --- a/distribution/scripting.md +++ b/distribution/scripting.md @@ -164,6 +164,22 @@ No problem, if there is something you need, post a new issue on the issue tracke Adding new APIs is most of time straight forward, so they can be added to new development builds quickly. Or if you are capable, make the change yourself to the OpenRCT2 source stream and create a pull request. +> How do I prevent my script from running on older versions of OpenRCT2 that do not support all the APIs I require? + +When registering your plugin, you can specify a minimum required API version like below: +```js +registerPlugin({ + name: 'Your Plugin', + version: '1.2', // Your plugin version + authors: ['Your Name'], + type: 'remote', + minApiVersion: 7, // OpenRCT2 plugin API v7 or higher is required to run your plugin + main: main +}); +``` + +When new APIs are introduced, or the behaviour of current APIs change, a new version number will be issued which you can find in the OpenRCT2 source code or changelog. + > Where shall I keep the code for my script? We recommend [GitHub](https://github.com) (where OpenRCT2 is hosted), or another source control host such as [BitBucket](https://bitbucket.org) or [GitLab](https://gitlab.com). All of them offer private repositories if you want to keep your code private, or public repositories which allow others to easily contribute to your script. From a6eeb8c7c4055e1af9230186b4fa60a8db9a676b Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 16:07:58 +0100 Subject: [PATCH 150/159] Add const to ticksElapsed_get --- src/openrct2/scripting/ScDate.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 9ce0b49220..6aefa99a1b 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -67,7 +67,7 @@ namespace OpenRCT2::Scripting return date.GetMonthsElapsed() / 8; } - uint32_t ticksElapsed_get() + uint32_t ticksElapsed_get() const { return gCurrentTicks; } From 2c4cf49fb1588c49ec207973b86deb2e12346e72 Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Apr 2020 21:18:58 +0100 Subject: [PATCH 151/159] Add more const --- src/openrct2-ui/scripting/ScUi.hpp | 10 ++--- src/openrct2-ui/scripting/ScViewport.hpp | 22 +++++----- src/openrct2-ui/scripting/ScWidget.hpp | 26 ++++++------ src/openrct2-ui/scripting/ScWindow.hpp | 22 +++++----- src/openrct2/scripting/ScConfiguration.hpp | 20 ++++----- src/openrct2/scripting/ScContext.hpp | 4 +- src/openrct2/scripting/ScDate.hpp | 14 +++---- src/openrct2/scripting/ScDisposable.hpp | 2 +- src/openrct2/scripting/ScEntity.hpp | 16 ++++---- src/openrct2/scripting/ScMap.hpp | 18 ++++---- src/openrct2/scripting/ScNetwork.hpp | 32 +++++++-------- src/openrct2/scripting/ScObject.hpp | 16 ++++---- src/openrct2/scripting/ScPark.hpp | 10 ++--- src/openrct2/scripting/ScRide.hpp | 16 ++++---- src/openrct2/scripting/ScTile.hpp | 48 +++++++++++----------- 15 files changed, 138 insertions(+), 138 deletions(-) diff --git a/src/openrct2-ui/scripting/ScUi.hpp b/src/openrct2-ui/scripting/ScUi.hpp index 1377acaa9e..d1b2f5094c 100644 --- a/src/openrct2-ui/scripting/ScUi.hpp +++ b/src/openrct2-ui/scripting/ScUi.hpp @@ -50,16 +50,16 @@ namespace OpenRCT2::Scripting { return context_get_width(); } - int32_t height_get() + int32_t height_get() const { return context_get_height(); } - int32_t windows_get() + int32_t windows_get() const { return static_cast(g_window_list.size()); } - std::shared_ptr mainViewport_get() + std::shared_ptr mainViewport_get() const { return std::make_shared(WC_MAIN_WINDOW); } @@ -101,7 +101,7 @@ namespace OpenRCT2::Scripting window_close_all(); } - std::shared_ptr getWindow(DukValue a) + std::shared_ptr getWindow(DukValue a) const { if (a.type() == DukValue::Type::NUMBER) { @@ -150,7 +150,7 @@ namespace OpenRCT2::Scripting } private: - rct_windowclass GetClassification(const std::string& key) + rct_windowclass GetClassification(const std::string& key) const { return WC_NULL; } diff --git a/src/openrct2-ui/scripting/ScViewport.hpp b/src/openrct2-ui/scripting/ScViewport.hpp index 100c6ab670..4fee253028 100644 --- a/src/openrct2-ui/scripting/ScViewport.hpp +++ b/src/openrct2-ui/scripting/ScViewport.hpp @@ -37,7 +37,7 @@ namespace OpenRCT2::Scripting } private: - int32_t left_get() + int32_t left_get() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -55,7 +55,7 @@ namespace OpenRCT2::Scripting } } - int32_t top_get() + int32_t top_get() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -73,7 +73,7 @@ namespace OpenRCT2::Scripting } } - int32_t right_get() + int32_t right_get() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -91,7 +91,7 @@ namespace OpenRCT2::Scripting } } - int32_t bottom_get() + int32_t bottom_get() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -109,7 +109,7 @@ namespace OpenRCT2::Scripting } } - int32_t rotation_get() + int32_t rotation_get() const { return get_current_rotation(); } @@ -128,7 +128,7 @@ namespace OpenRCT2::Scripting } } - int32_t zoom_get() + int32_t zoom_get() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -146,7 +146,7 @@ namespace OpenRCT2::Scripting } } - uint32_t visibilityFlags_get() + uint32_t visibilityFlags_get() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -172,7 +172,7 @@ namespace OpenRCT2::Scripting } } - DukValue getCentrePosition() + DukValue getCentrePosition() const { auto viewport = GetViewport(); if (viewport != nullptr) @@ -242,7 +242,7 @@ namespace OpenRCT2::Scripting } private: - rct_window* GetWindow() + rct_window* GetWindow() const { if (_class == WC_MAIN_WINDOW) return window_get_main(); @@ -250,7 +250,7 @@ namespace OpenRCT2::Scripting return window_find_by_number(_class, _number); } - rct_viewport* GetViewport() + rct_viewport* GetViewport() const { auto w = GetWindow(); if (w != nullptr) @@ -277,7 +277,7 @@ namespace OpenRCT2::Scripting } } - std::optional GetCoordsFromObject(DukValue position) + std::optional GetCoordsFromObject(DukValue position) const { if (position.type() == DukValue::Type::OBJECT) { diff --git a/src/openrct2-ui/scripting/ScWidget.hpp b/src/openrct2-ui/scripting/ScWidget.hpp index e28f2ff9c0..2a6efecc57 100644 --- a/src/openrct2-ui/scripting/ScWidget.hpp +++ b/src/openrct2-ui/scripting/ScWidget.hpp @@ -40,7 +40,7 @@ namespace OpenRCT2::Scripting } private: - std::string type_get() + std::string type_get() const { auto widget = GetWidget(); if (widget != nullptr) @@ -86,7 +86,7 @@ namespace OpenRCT2::Scripting return "unknown"; } - int32_t x_get() + int32_t x_get() const { auto widget = GetWidget(); if (widget != nullptr) @@ -106,7 +106,7 @@ namespace OpenRCT2::Scripting } } - int32_t y_get() + int32_t y_get() const { auto widget = GetWidget(); if (widget != nullptr) @@ -126,7 +126,7 @@ namespace OpenRCT2::Scripting } } - int32_t width_get() + int32_t width_get() const { auto widget = GetWidget(); if (widget != nullptr) @@ -146,7 +146,7 @@ namespace OpenRCT2::Scripting } } - int32_t height_get() + int32_t height_get() const { auto widget = GetWidget(); if (widget != nullptr) @@ -166,7 +166,7 @@ namespace OpenRCT2::Scripting } } - bool isDisabled_get() + bool isDisabled_get() const { auto w = GetWindow(); if (w != nullptr) @@ -188,7 +188,7 @@ namespace OpenRCT2::Scripting } } - bool isChecked_get() + bool isChecked_get() const { auto w = GetWindow(); if (w != nullptr) @@ -206,7 +206,7 @@ namespace OpenRCT2::Scripting } } - uint32_t image_get() + uint32_t image_get() const { if (IsCustomWindow()) { @@ -227,7 +227,7 @@ namespace OpenRCT2::Scripting } } - std::string text_get() + std::string text_get() const { if (IsCustomWindow()) { @@ -248,7 +248,7 @@ namespace OpenRCT2::Scripting } } - std::shared_ptr viewport_get() + std::shared_ptr viewport_get() const { auto w = GetWindow(); if (w != nullptr && IsCustomWindow()) @@ -281,7 +281,7 @@ namespace OpenRCT2::Scripting } private: - rct_window* GetWindow() + rct_window* GetWindow() const { if (_class == WC_MAIN_WINDOW) return window_get_main(); @@ -289,7 +289,7 @@ namespace OpenRCT2::Scripting return window_find_by_number(_class, _number); } - rct_widget* GetWidget() + rct_widget* GetWidget() const { auto w = GetWindow(); if (w != nullptr) @@ -299,7 +299,7 @@ namespace OpenRCT2::Scripting return nullptr; } - bool IsCustomWindow() + bool IsCustomWindow() const { auto w = GetWindow(); if (w != nullptr) diff --git a/src/openrct2-ui/scripting/ScWindow.hpp b/src/openrct2-ui/scripting/ScWindow.hpp index e885072e32..1dfd629bb1 100644 --- a/src/openrct2-ui/scripting/ScWindow.hpp +++ b/src/openrct2-ui/scripting/ScWindow.hpp @@ -41,17 +41,17 @@ namespace OpenRCT2::Scripting { } - int32_t classification_get() + int32_t classification_get() const { return static_cast(_class); } - int32_t number_get() + int32_t number_get() const { return static_cast(_number); } - int32_t x_get() + int32_t x_get() const { return GetWindow()->windowPos.x; } @@ -60,7 +60,7 @@ namespace OpenRCT2::Scripting auto w = GetWindow(); window_set_position(w, { value, w->windowPos.y }); } - int32_t y_get() + int32_t y_get() const { return GetWindow()->windowPos.y; } @@ -69,21 +69,21 @@ namespace OpenRCT2::Scripting auto w = GetWindow(); window_set_position(w, { w->windowPos.x, value }); } - int32_t width_get() + int32_t width_get() const { return GetWindow()->width; } - int32_t height_get() + int32_t height_get() const { return GetWindow()->height; } - bool isSticky_get() + bool isSticky_get() const { auto flags = GetWindow()->flags; return (flags & (WF_STICK_TO_BACK | WF_STICK_TO_FRONT)) != 0; } - std::vector> widgets_get() + std::vector> widgets_get() const { std::vector> result; auto w = GetWindow(); @@ -99,7 +99,7 @@ namespace OpenRCT2::Scripting return result; } - std::vector colours_get() + std::vector colours_get() const { std::vector result; auto w = GetWindow(); @@ -126,7 +126,7 @@ namespace OpenRCT2::Scripting } } - std::string title_get() + std::string title_get() const { auto w = GetWindow(); if (w != nullptr && w->classification == WC_CUSTOM) @@ -153,7 +153,7 @@ namespace OpenRCT2::Scripting } } - std::shared_ptr findWidget(std::string name) + std::shared_ptr findWidget(std::string name) const { auto w = GetWindow(); if (w != nullptr) diff --git a/src/openrct2/scripting/ScConfiguration.hpp b/src/openrct2/scripting/ScConfiguration.hpp index 15ca10d16d..4dc295a65c 100644 --- a/src/openrct2/scripting/ScConfiguration.hpp +++ b/src/openrct2/scripting/ScConfiguration.hpp @@ -41,7 +41,7 @@ namespace OpenRCT2::Scripting } private: - std::pair GetNextNamespace(const std::string_view& input) + std::pair GetNextNamespace(const std::string_view& input) const { auto pos = input.find('.'); if (pos == std::string_view::npos) @@ -54,14 +54,14 @@ namespace OpenRCT2::Scripting } } - std::pair GetNamespaceAndKey(const std::string_view& input) + std::pair GetNamespaceAndKey(const std::string_view& input) const { 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) + std::optional GetNamespaceObject(const std::string_view& ns) const { auto store = _backingObject; auto k = ns; @@ -76,7 +76,7 @@ namespace OpenRCT2::Scripting return store.type() == DukValue::OBJECT ? std::make_optional(store) : std::nullopt; } - DukValue GetOrCreateNamespaceObject(duk_context* ctx, const std::string_view& ns) + DukValue GetOrCreateNamespaceObject(duk_context* ctx, const std::string_view& ns) const { auto store = _backingObject; if (!ns.empty()) @@ -106,7 +106,7 @@ namespace OpenRCT2::Scripting return store; } - bool IsValidNamespace(const std::string_view& ns) + bool IsValidNamespace(const std::string_view& ns) const { if (ns.empty() || ns[0] == '.' || ns[ns.size() - 1] == '.') { @@ -122,12 +122,12 @@ namespace OpenRCT2::Scripting return true; } - bool IsValidKey(const std::string_view& key) + bool IsValidKey(const std::string_view& key) const { return !key.empty() && key.find('.') == std::string_view::npos; } - DukValue getAll(const std::string& ns) + DukValue getAll(const std::string& ns) const { DukValue result; auto ctx = GetContext()->GetScriptEngine().GetContext(); @@ -155,7 +155,7 @@ namespace OpenRCT2::Scripting return result; } - DukValue get(const std::string& key, const DukValue& defaultValue) + DukValue get(const std::string& key, const DukValue& defaultValue) const { auto ctx = GetContext()->GetScriptEngine().GetContext(); if (_isUserConfig) @@ -193,7 +193,7 @@ namespace OpenRCT2::Scripting return defaultValue; } - void set(const std::string& key, const DukValue& value) + void set(const std::string& key, const DukValue& value) const { auto& scriptEngine = GetContext()->GetScriptEngine(); auto ctx = scriptEngine.GetContext(); @@ -246,7 +246,7 @@ namespace OpenRCT2::Scripting } } - bool has(const std::string& key) + bool has(const std::string& key) const { auto val = get(key, DukValue()); return val.type() != DukValue::Type::UNDEFINED; diff --git a/src/openrct2/scripting/ScContext.hpp b/src/openrct2/scripting/ScContext.hpp index 2ca39eef1a..0b9994621b 100644 --- a/src/openrct2/scripting/ScContext.hpp +++ b/src/openrct2/scripting/ScContext.hpp @@ -64,7 +64,7 @@ namespace OpenRCT2::Scripting } } - DukValue getObject(const std::string& typez, int32_t index) + DukValue getObject(const std::string& typez, int32_t index) const { auto ctx = GetContext()->GetScriptEngine().GetContext(); auto& objManager = GetContext()->GetObjectManager(); @@ -85,7 +85,7 @@ namespace OpenRCT2::Scripting return {}; } - std::vector getAllObjects(const std::string& typez) + std::vector getAllObjects(const std::string& typez) const { auto ctx = GetContext()->GetScriptEngine().GetContext(); auto& objManager = GetContext()->GetObjectManager(); diff --git a/src/openrct2/scripting/ScDate.hpp b/src/openrct2/scripting/ScDate.hpp index 6aefa99a1b..f746e7d6b9 100644 --- a/src/openrct2/scripting/ScDate.hpp +++ b/src/openrct2/scripting/ScDate.hpp @@ -37,7 +37,7 @@ namespace OpenRCT2::Scripting } private: - uint32_t monthsElapsed_get() + uint32_t monthsElapsed_get() const { const auto& date = GetDate(); return date.GetMonthsElapsed(); @@ -49,7 +49,7 @@ namespace OpenRCT2::Scripting gDateMonthsElapsed = value; } - uint32_t monthProgress_get() + uint32_t monthProgress_get() const { const auto& date = GetDate(); return date.GetMonthTicks(); @@ -61,7 +61,7 @@ namespace OpenRCT2::Scripting gDateMonthTicks = value; } - uint32_t yearsElapsed_get() + uint32_t yearsElapsed_get() const { const auto& date = GetDate(); return date.GetMonthsElapsed() / 8; @@ -72,26 +72,26 @@ namespace OpenRCT2::Scripting return gCurrentTicks; } - int32_t day_get() + int32_t day_get() const { const auto& date = GetDate(); return date.GetDay() + 1; } - int32_t month_get() + int32_t month_get() const { const auto& date = GetDate(); return date.GetMonth(); } - int32_t year_get() + int32_t year_get() const { const auto& date = GetDate(); return date.GetYear() + 1; } private: - const Date& GetDate() + const Date& GetDate() const { auto gameState = GetContext()->GetGameState(); return gameState->GetDate(); diff --git a/src/openrct2/scripting/ScDisposable.hpp b/src/openrct2/scripting/ScDisposable.hpp index 3b57e83ceb..c3c11450c9 100644 --- a/src/openrct2/scripting/ScDisposable.hpp +++ b/src/openrct2/scripting/ScDisposable.hpp @@ -28,7 +28,7 @@ namespace OpenRCT2::Scripting { } - void dispose() + void dispose() const { if (_onDispose) { diff --git a/src/openrct2/scripting/ScEntity.hpp b/src/openrct2/scripting/ScEntity.hpp index b386ed4b99..c304198435 100644 --- a/src/openrct2/scripting/ScEntity.hpp +++ b/src/openrct2/scripting/ScEntity.hpp @@ -30,7 +30,7 @@ namespace OpenRCT2::Scripting } private: - std::string type_get() + std::string type_get() const { auto entity = GetEntity(); if (entity != nullptr) @@ -58,7 +58,7 @@ namespace OpenRCT2::Scripting } // x getter and setter - int32_t x_get() + int32_t x_get() const { auto entity = GetEntity(); return entity != nullptr ? entity->x : 0; @@ -74,7 +74,7 @@ namespace OpenRCT2::Scripting } // y getter and setter - int32_t y_get() + int32_t y_get() const { auto entity = GetEntity(); return entity != nullptr ? entity->y : 0; @@ -90,7 +90,7 @@ namespace OpenRCT2::Scripting } // z getter and setter - int16_t z_get() + int16_t z_get() const { auto entity = GetEntity(); return entity != nullptr ? entity->z : 0; @@ -105,7 +105,7 @@ namespace OpenRCT2::Scripting } } - SpriteBase* GetEntity() + SpriteBase* GetEntity() const { return &get_sprite(_id)->generic; } @@ -129,7 +129,7 @@ namespace OpenRCT2::Scripting } private: - uint8_t tshirtColour_get() + uint8_t tshirtColour_get() const { auto peep = GetPeep(); return peep != nullptr ? peep->tshirt_colour : 0; @@ -143,7 +143,7 @@ namespace OpenRCT2::Scripting peep->tshirt_colour = value; } } - uint8_t trousersColour_get() + uint8_t trousersColour_get() const { auto peep = GetPeep(); return peep != nullptr ? peep->trousers_colour : 0; @@ -158,7 +158,7 @@ namespace OpenRCT2::Scripting } } - Peep* GetPeep() + Peep* GetPeep() const { return get_sprite(_id)->AsPeep(); } diff --git a/src/openrct2/scripting/ScMap.hpp b/src/openrct2/scripting/ScMap.hpp index df1c2d00e4..bd549b8f8d 100644 --- a/src/openrct2/scripting/ScMap.hpp +++ b/src/openrct2/scripting/ScMap.hpp @@ -32,7 +32,7 @@ namespace OpenRCT2::Scripting { } - DukValue size_get() + DukValue size_get() const { auto ctx = _context; auto objIdx = duk_push_object(ctx); @@ -43,17 +43,17 @@ namespace OpenRCT2::Scripting return DukValue::take_from_stack(ctx); } - int32_t numRides_get() + int32_t numRides_get() const { return static_cast(GetRideManager().size()); } - int32_t numEntities_get() + int32_t numEntities_get() const { return MAX_SPRITES; } - std::vector> rides_get() + std::vector> rides_get() const { std::vector> result; auto rideManager = GetRideManager(); @@ -64,7 +64,7 @@ namespace OpenRCT2::Scripting return result; } - std::shared_ptr getRide(int32_t id) + std::shared_ptr getRide(int32_t id) const { auto rideManager = GetRideManager(); if (id >= 0 && id < static_cast(rideManager.size())) @@ -78,13 +78,13 @@ namespace OpenRCT2::Scripting return {}; } - std::shared_ptr getTile(int32_t x, int32_t y) + std::shared_ptr getTile(int32_t x, int32_t y) const { auto coords = TileCoordsXY(x, y).ToCoordsXY(); return std::make_shared(coords); } - DukValue getEntity(int32_t id) + DukValue getEntity(int32_t id) const { if (id >= 0 && id < MAX_SPRITES) { @@ -99,7 +99,7 @@ namespace OpenRCT2::Scripting return DukValue::take_from_stack(_context); } - std::vector getAllEntities(const std::string& type) + std::vector getAllEntities(const std::string& type) const { SPRITE_LIST targetList{}; uint8_t targetType{}; @@ -189,7 +189,7 @@ namespace OpenRCT2::Scripting } private: - DukValue GetEntityAsDukValue(const rct_sprite* sprite) + DukValue GetEntityAsDukValue(const rct_sprite* sprite) const { auto spriteId = sprite->generic.sprite_index; switch (sprite->generic.sprite_identifier) diff --git a/src/openrct2/scripting/ScNetwork.hpp b/src/openrct2/scripting/ScNetwork.hpp index 25215c17f1..94e5ab47a0 100644 --- a/src/openrct2/scripting/ScNetwork.hpp +++ b/src/openrct2/scripting/ScNetwork.hpp @@ -36,7 +36,7 @@ namespace OpenRCT2::Scripting return _id; } - std::string name_get() + std::string name_get() const { # ifndef DISABLE_NETWORK auto index = network_get_group_index(_id); @@ -55,7 +55,7 @@ namespace OpenRCT2::Scripting # endif } - std::vector permissions_get() + std::vector permissions_get() const { # ifndef DISABLE_NETWORK auto index = network_get_group_index(_id); @@ -129,7 +129,7 @@ namespace OpenRCT2::Scripting } private: - std::string TransformPermissionKeyToJS(const std::string& s) + static std::string TransformPermissionKeyToJS(const std::string& s) { auto result = s.substr(sizeof("PERMISSION_") - 1); for (auto& c : result) @@ -139,7 +139,7 @@ namespace OpenRCT2::Scripting return result; } - std::string TransformPermissionKeyToInternal(const std::string& s) + static std::string TransformPermissionKeyToInternal(const std::string& s) { auto result = "PERMISSION_" + s; for (auto& c : result) @@ -161,12 +161,12 @@ namespace OpenRCT2::Scripting { } - int32_t id_get() + int32_t id_get() const { return _id; } - std::string name_get() + std::string name_get() const { # ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); @@ -178,7 +178,7 @@ namespace OpenRCT2::Scripting # endif } - int32_t group_get() + int32_t group_get() const { # ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); @@ -197,7 +197,7 @@ namespace OpenRCT2::Scripting # endif } - int32_t ping_get() + int32_t ping_get() const { # ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); @@ -209,7 +209,7 @@ namespace OpenRCT2::Scripting # endif } - int32_t commandsRan_get() + int32_t commandsRan_get() const { # ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); @@ -221,7 +221,7 @@ namespace OpenRCT2::Scripting # endif } - int32_t moneySpent_get() + int32_t moneySpent_get() const { # ifndef DISABLE_NETWORK auto index = network_get_player_index(_id); @@ -258,7 +258,7 @@ namespace OpenRCT2::Scripting { } - std::string mode_get() + std::string mode_get() const { # ifndef DISABLE_NETWORK switch (network_get_mode()) @@ -271,7 +271,7 @@ namespace OpenRCT2::Scripting # endif return "none"; } - int32_t players_get() + int32_t players_get() const { # ifndef DISABLE_NETWORK return network_get_num_players(); @@ -279,7 +279,7 @@ namespace OpenRCT2::Scripting return 0; # endif } - int32_t groups_get() + int32_t groups_get() const { # ifndef DISABLE_NETWORK return network_get_num_groups(); @@ -287,7 +287,7 @@ namespace OpenRCT2::Scripting return 0; # endif } - int32_t defaultGroup_get() + int32_t defaultGroup_get() const { # ifndef DISABLE_NETWORK return network_get_default_group(); @@ -303,7 +303,7 @@ namespace OpenRCT2::Scripting # endif } - std::shared_ptr getPlayer(int32_t index) + std::shared_ptr getPlayer(int32_t index) const { # ifndef DISABLE_NETWORK auto numPlayers = network_get_num_players(); @@ -316,7 +316,7 @@ namespace OpenRCT2::Scripting return nullptr; } - std::shared_ptr getGroup(int32_t index) + std::shared_ptr getGroup(int32_t index) const { # ifndef DISABLE_NETWORK auto numGroups = network_get_num_groups(); diff --git a/src/openrct2/scripting/ScObject.hpp b/src/openrct2/scripting/ScObject.hpp index c5cd7db835..38cc49b2c5 100644 --- a/src/openrct2/scripting/ScObject.hpp +++ b/src/openrct2/scripting/ScObject.hpp @@ -67,17 +67,17 @@ namespace OpenRCT2::Scripting } private: - std::string type_get() + std::string type_get() const { return std::string(ObjectTypeToString(_type)); } - int32_t index_get() + int32_t index_get() const { return _index; } - std::string identifier_get() + std::string identifier_get() const { auto obj = GetObject(); if (obj != nullptr) @@ -87,7 +87,7 @@ namespace OpenRCT2::Scripting return {}; } - std::string name_get() + std::string name_get() const { auto obj = GetObject(); if (obj != nullptr) @@ -98,7 +98,7 @@ namespace OpenRCT2::Scripting } protected: - Object* GetObject() + Object* GetObject() const { auto& objManager = GetContext()->GetObjectManager(); return objManager.GetLoadedObject(_type, _index); @@ -121,7 +121,7 @@ namespace OpenRCT2::Scripting } private: - std::string description_get() + std::string description_get() const { auto obj = GetObject(); if (obj != nullptr) @@ -131,7 +131,7 @@ namespace OpenRCT2::Scripting return {}; } - std::string capacity_get() + std::string capacity_get() const { auto obj = GetObject(); if (obj != nullptr) @@ -142,7 +142,7 @@ namespace OpenRCT2::Scripting } protected: - RideObject* GetObject() + RideObject* GetObject() const { return static_cast(ScObject::GetObject()); } diff --git a/src/openrct2/scripting/ScPark.hpp b/src/openrct2/scripting/ScPark.hpp index 9476df9596..74bd8f2e7e 100644 --- a/src/openrct2/scripting/ScPark.hpp +++ b/src/openrct2/scripting/ScPark.hpp @@ -27,7 +27,7 @@ namespace OpenRCT2::Scripting class ScPark { public: - money32 cash_get() + money32 cash_get() const { return gCash; } @@ -39,7 +39,7 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - int32_t rating_get() + int32_t rating_get() const { return gParkRating; } @@ -51,7 +51,7 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - money32 bankLoan_get() + money32 bankLoan_get() const { return gBankLoan; } @@ -63,7 +63,7 @@ namespace OpenRCT2::Scripting context_broadcast_intent(&intent); } - money32 maxBankLoan_get() + money32 maxBankLoan_get() const { return gMaxBankLoan; } @@ -109,7 +109,7 @@ namespace OpenRCT2::Scripting } private: - uint8_t GetParkMessageType(const std::string& key) + static uint8_t GetParkMessageType(const std::string& key) { static auto keys = { "attraction", "peep_on_attraction", "peep", "money", "blank", "research", "guests", "award", "chart" }; diff --git a/src/openrct2/scripting/ScRide.hpp b/src/openrct2/scripting/ScRide.hpp index 35dde8054e..b9c030a147 100644 --- a/src/openrct2/scripting/ScRide.hpp +++ b/src/openrct2/scripting/ScRide.hpp @@ -31,7 +31,7 @@ namespace OpenRCT2::Scripting } private: - int32_t id_get() + int32_t id_get() const { return _rideId; } @@ -50,13 +50,13 @@ namespace OpenRCT2::Scripting return nullptr; } - int32_t type_get() + int32_t type_get() const { auto ride = GetRide(); return ride != nullptr ? ride->type : 0; } - std::string name_get() + std::string name_get() const { auto ride = GetRide(); return ride != nullptr ? ride->GetName() : std::string(); @@ -71,7 +71,7 @@ namespace OpenRCT2::Scripting } } - int32_t excitement_get() + int32_t excitement_get() const { auto ride = GetRide(); return ride != nullptr ? ride->excitement : 0; @@ -86,7 +86,7 @@ namespace OpenRCT2::Scripting } } - int32_t intensity_get() + int32_t intensity_get() const { auto ride = GetRide(); return ride != nullptr ? ride->intensity : 0; @@ -101,7 +101,7 @@ namespace OpenRCT2::Scripting } } - int32_t nausea_get() + int32_t nausea_get() const { auto ride = GetRide(); return ride != nullptr ? ride->nausea : 0; @@ -116,7 +116,7 @@ namespace OpenRCT2::Scripting } } - int32_t totalCustomers_get() + int32_t totalCustomers_get() const { auto ride = GetRide(); return ride != nullptr ? ride->total_customers : 0; @@ -131,7 +131,7 @@ namespace OpenRCT2::Scripting } } - Ride* GetRide() + Ride* GetRide() const { return get_ride(_rideId); } diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index df9530b815..512338a9bf 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -149,7 +149,7 @@ namespace OpenRCT2::Scripting } } - uint32_t surfaceStyle_get() + uint32_t surfaceStyle_get() const { auto el = _element->AsSurface(); if (el != nullptr) @@ -166,7 +166,7 @@ namespace OpenRCT2::Scripting } } - uint32_t edgeStyle_get() + uint32_t edgeStyle_get() const { auto el = _element->AsSurface(); if (el != nullptr) @@ -183,7 +183,7 @@ namespace OpenRCT2::Scripting } } - uint8_t grassLength_get() + uint8_t grassLength_get() const { auto el = _element->AsSurface(); if (el != nullptr) @@ -201,7 +201,7 @@ namespace OpenRCT2::Scripting } } - bool hasOwnership_get() + bool hasOwnership_get() const { auto el = _element->AsSurface(); if (el != nullptr) @@ -220,7 +220,7 @@ namespace OpenRCT2::Scripting return false; } - uint8_t ownership_get() + uint8_t ownership_get() const { auto el = _element->AsSurface(); if (el != nullptr) @@ -237,7 +237,7 @@ namespace OpenRCT2::Scripting } } - uint8_t parkFences_get() + uint8_t parkFences_get() const { auto el = _element->AsSurface(); if (el != nullptr) @@ -254,7 +254,7 @@ namespace OpenRCT2::Scripting } } - uint8_t trackType_get() + uint8_t trackType_get() const { auto el = _element->AsTrack(); if (el != nullptr) @@ -271,7 +271,7 @@ namespace OpenRCT2::Scripting } } - uint8_t sequence_get() + uint8_t sequence_get() const { switch (_element->GetType()) { @@ -308,7 +308,7 @@ namespace OpenRCT2::Scripting } } - uint8_t ride_get() + uint8_t ride_get() const { switch (_element->GetType()) { @@ -356,7 +356,7 @@ namespace OpenRCT2::Scripting } } - uint8_t station_get() + uint8_t station_get() const { switch (_element->GetType()) { @@ -404,7 +404,7 @@ namespace OpenRCT2::Scripting } } - bool hasChainLift_get() + bool hasChainLift_get() const { auto el = _element->AsTrack(); if (el != nullptr) @@ -421,7 +421,7 @@ namespace OpenRCT2::Scripting } } - uint32_t object_get() + uint32_t object_get() const { switch (_element->GetType()) { @@ -491,7 +491,7 @@ namespace OpenRCT2::Scripting } } - uint8_t age_get() + uint8_t age_get() const { auto el = _element->AsSmallScenery(); if (el != nullptr) @@ -508,7 +508,7 @@ namespace OpenRCT2::Scripting } } - uint8_t primaryColour_get() + uint8_t primaryColour_get() const { switch (_element->GetType()) { @@ -545,7 +545,7 @@ namespace OpenRCT2::Scripting } } - uint8_t secondaryColour_get() + uint8_t secondaryColour_get() const { switch (_element->GetType()) { @@ -802,7 +802,7 @@ namespace OpenRCT2::Scripting } } - uint8_t footpathObject_get() + uint8_t footpathObject_get() const { auto el = _element->AsEntrance(); if (el != nullptr) @@ -903,23 +903,23 @@ namespace OpenRCT2::Scripting } private: - int32_t x_get() + int32_t x_get() const { return _coords.x / COORDS_XY_STEP; } - int32_t y_get() + int32_t y_get() const { return _coords.y / COORDS_XY_STEP; } - size_t numElements_get() + size_t numElements_get() const { auto first = GetFirstElement(); return GetNumElements(first); } - std::vector> elements_get() + std::vector> elements_get() const { std::vector> result; auto first = GetFirstElement(); @@ -935,7 +935,7 @@ namespace OpenRCT2::Scripting return result; } - DukValue data_get() + DukValue data_get() const { auto ctx = GetDukContext(); auto first = map_get_first_element_at(_coords); @@ -998,7 +998,7 @@ namespace OpenRCT2::Scripting } } - std::shared_ptr getElement(size_t index) + std::shared_ptr getElement(size_t index) const { auto first = GetFirstElement(); if (index < GetNumElements(first)) @@ -1069,7 +1069,7 @@ namespace OpenRCT2::Scripting } } - TileElement* GetFirstElement() + TileElement* GetFirstElement() const { return map_get_first_element_at(_coords); } @@ -1088,7 +1088,7 @@ namespace OpenRCT2::Scripting return count; } - duk_context* GetDukContext() + duk_context* GetDukContext() const { auto& scriptEngine = GetContext()->GetScriptEngine(); auto ctx = scriptEngine.GetContext(); From a0877d1518bb6b12a225f08c8362044f8087e5ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Janiszewski?= Date: Sat, 25 Apr 2020 22:07:38 +0200 Subject: [PATCH 152/159] Improve dukglue's includes --- src/thirdparty/dukglue/detail_function.h | 2 ++ src/thirdparty/dukglue/detail_stack.h | 1 + src/thirdparty/dukglue/detail_typeinfo.h | 5 +++-- src/thirdparty/dukglue/detail_types.h | 4 +--- src/thirdparty/dukglue/dukexception.h | 3 ++- src/thirdparty/dukglue/public_util.h | 7 ++++--- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/thirdparty/dukglue/detail_function.h b/src/thirdparty/dukglue/detail_function.h index 3d715884d3..84ecbcb4cc 100644 --- a/src/thirdparty/dukglue/detail_function.h +++ b/src/thirdparty/dukglue/detail_function.h @@ -1,6 +1,8 @@ #pragma once #include "detail_stack.h" +#include "detail_types.h" +#include "detail_primitive_types.h" namespace dukglue { diff --git a/src/thirdparty/dukglue/detail_stack.h b/src/thirdparty/dukglue/detail_stack.h index f5382ab898..b8164f9404 100644 --- a/src/thirdparty/dukglue/detail_stack.h +++ b/src/thirdparty/dukglue/detail_stack.h @@ -2,6 +2,7 @@ #include +#include "detail_primitive_types.h" #include "detail_traits.h" #include "detail_types.h" diff --git a/src/thirdparty/dukglue/detail_typeinfo.h b/src/thirdparty/dukglue/detail_typeinfo.h index 5626c64c5a..e906857d02 100644 --- a/src/thirdparty/dukglue/detail_typeinfo.h +++ b/src/thirdparty/dukglue/detail_typeinfo.h @@ -1,5 +1,6 @@ #pragma once +#include #include namespace dukglue @@ -7,7 +8,7 @@ namespace dukglue namespace detail { // same as duk_get_type_name, which is private for some reason *shakes fist* - static const char* get_type_name(duk_int_t type_idx) { + static inline const char* get_type_name(duk_int_t type_idx) { static const char* names[] = { "none", "undefined", @@ -21,7 +22,7 @@ namespace dukglue "lightfunc" }; - if (type_idx >= 0 && type_idx < sizeof(names) / sizeof(names[0])) + if (type_idx >= 0 && type_idx < static_cast(sizeof(names) / sizeof(names[0]))) return names[type_idx]; else return "unknown"; diff --git a/src/thirdparty/dukglue/detail_types.h b/src/thirdparty/dukglue/detail_types.h index de86afe414..56f16eb579 100644 --- a/src/thirdparty/dukglue/detail_types.h +++ b/src/thirdparty/dukglue/detail_types.h @@ -145,7 +145,7 @@ namespace dukglue { typedef typename Bare::type BareType; //typedef DukType ThisDukType; typedef typename DukType::IsValueType IsValueType; - + static_assert(!IsValueType::value || !std::is_pointer::value, "Cannot return pointer to value type."); static_assert(!IsValueType::value || (!std::is_reference::value || std::is_const::type>::value), @@ -156,5 +156,3 @@ namespace dukglue { }; } } - -#include "detail_primitive_types.h" diff --git a/src/thirdparty/dukglue/dukexception.h b/src/thirdparty/dukglue/dukexception.h index 7d42768ebe..9643c27974 100644 --- a/src/thirdparty/dukglue/dukexception.h +++ b/src/thirdparty/dukglue/dukexception.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -37,4 +38,4 @@ public: duk_pop(ctx); } } -}; \ No newline at end of file +}; diff --git a/src/thirdparty/dukglue/public_util.h b/src/thirdparty/dukglue/public_util.h index d6ff344d8f..5dc7947cab 100644 --- a/src/thirdparty/dukglue/public_util.h +++ b/src/thirdparty/dukglue/public_util.h @@ -2,6 +2,7 @@ #include "dukexception.h" #include "detail_traits.h" // for index_tuple/make_indexes +#include "detail_types.h" // This file has some useful utility functions for users. // Hopefully this saves you from wading through the implementation. @@ -125,7 +126,7 @@ typename std::enable_if::value, RetT>::type dukglue_pcall_met dukglue::detail::SafeMethodCallData data { &obj, method_name, std::tuple(args...), nullptr }; - + duk_idx_t rc = duk_safe_call(ctx, &dukglue::detail::call_method_safe, (void*) &data, 0, 1); if (rc != 0) throw DukErrorException(ctx, rc); @@ -234,11 +235,11 @@ typename std::enable_if::value, RetT>::type dukglue_pcall(du dukglue::detail::SafeCallData data{ &obj, std::tuple(args...), &result }; - + duk_int_t rc = duk_safe_call(ctx, &dukglue::detail::call_safe, (void*) &data, 0, 1); if (rc != 0) throw DukErrorException(ctx, rc); - + duk_pop(ctx); // remove result from stack return std::move(result); } From 2d43ac59366d4a17d8e7fd190a6c6f72bdbf1d06 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 13:39:06 +0100 Subject: [PATCH 153/159] Try using int32_t instead of size_t --- src/openrct2/scripting/ScTile.hpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index 512338a9bf..d3fc1e70b3 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -913,10 +913,10 @@ namespace OpenRCT2::Scripting return _coords.y / COORDS_XY_STEP; } - size_t numElements_get() const + uint32_t numElements_get() const { auto first = GetFirstElement(); - return GetNumElements(first); + return static_cast(GetNumElements(first)); } std::vector> elements_get() const @@ -998,17 +998,17 @@ namespace OpenRCT2::Scripting } } - std::shared_ptr getElement(size_t index) const + std::shared_ptr getElement(uint32_t index) const { auto first = GetFirstElement(); - if (index < GetNumElements(first)) + if (static_cast(index) < GetNumElements(first)) { return std::make_shared(_coords, &first[index]); } return {}; } - std::shared_ptr insertElement(size_t index) + std::shared_ptr insertElement(uint32_t index) { ThrowIfGameStateNotMutable(); std::shared_ptr result; @@ -1058,7 +1058,7 @@ namespace OpenRCT2::Scripting return result; } - void removeElement(size_t index) + void removeElement(uint32_t index) { ThrowIfGameStateNotMutable(); auto first = GetFirstElement(); From 51ed760409a74df85ff998e95978b6374e442d28 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 13:55:12 +0100 Subject: [PATCH 154/159] Fix FileWatcher header file --- src/openrct2/core/FileWatcher.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openrct2/core/FileWatcher.h b/src/openrct2/core/FileWatcher.h index 96a012efdf..54028812f0 100644 --- a/src/openrct2/core/FileWatcher.h +++ b/src/openrct2/core/FileWatcher.h @@ -25,10 +25,10 @@ class FileWatcher { private: std::thread _watchThread; -#ifdef _WIN32 +#if defined(_WIN32) std::string _path; HANDLE _directoryHandle{}; -#else +#elif defined(__linux__) struct FileDescriptor { int Fd = -1; From 7041b0793ec4e8d307fe4a6375d60e5263274150 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 14:42:13 +0100 Subject: [PATCH 155/159] Fix tile type literals --- src/openrct2/scripting/ScTile.hpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/openrct2/scripting/ScTile.hpp b/src/openrct2/scripting/ScTile.hpp index d3fc1e70b3..620c6f8fee 100644 --- a/src/openrct2/scripting/ScTile.hpp +++ b/src/openrct2/scripting/ScTile.hpp @@ -52,17 +52,17 @@ namespace OpenRCT2::Scripting case TILE_ELEMENT_TYPE_TRACK: return "track"; case TILE_ELEMENT_TYPE_SMALL_SCENERY: - return "small-scenery"; + return "small_scenery"; case TILE_ELEMENT_TYPE_ENTRANCE: return "entrance"; case TILE_ELEMENT_TYPE_WALL: return "wall"; case TILE_ELEMENT_TYPE_LARGE_SCENERY: - return "large-scenery"; + return "large_scenery"; case TILE_ELEMENT_TYPE_BANNER: return "banner"; case TILE_ELEMENT_TYPE_CORRUPT: - return "openrct2-corrupt"; + return "openrct2_corrupt"; default: return "unknown"; } @@ -77,17 +77,17 @@ namespace OpenRCT2::Scripting type = TILE_ELEMENT_TYPE_PATH; else if (value == "track") type = TILE_ELEMENT_TYPE_TRACK; - else if (value == "small-scenery") + else if (value == "small_scenery") type = TILE_ELEMENT_TYPE_SMALL_SCENERY; else if (value == "entrance") type = TILE_ELEMENT_TYPE_ENTRANCE; else if (value == "wall") type = TILE_ELEMENT_TYPE_WALL; - else if (value == "large-scenery") + else if (value == "large_scenery") type = TILE_ELEMENT_TYPE_LARGE_SCENERY; else if (value == "banner") type = TILE_ELEMENT_TYPE_BANNER; - else if (value == "openrct2-corrupt") + else if (value == "openrct2_corrupt") type = TILE_ELEMENT_TYPE_CORRUPT; else return; From 90f3a9b84610663c7135b80b86286e4b1c2be0e4 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 14:49:21 +0100 Subject: [PATCH 156/159] Add dukglue and duktape copyright information --- debian/control | 2 +- distribution/changelog.txt | 1 + distribution/readme.txt | 2 ++ readme.md | 1 + 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/debian/control b/debian/control index 49c2537656..7539bb83e7 100644 --- a/debian/control +++ b/debian/control @@ -4,7 +4,7 @@ Section: misc Priority: optional Standards-Version: 3.9.2 Multi-Arch: same -Build-Depends: debhelper (>= 9), cmake (>= 3.8), libsdl2-dev, g++ (>= 4:7), pkg-config, libjansson4 (>= 2.5), libjansson-dev (>= 2.3), libspeex-dev, libspeexdsp-dev, libcurl4-openssl-dev, libcrypto++-dev, libfontconfig1-dev, libfreetype6-dev, libpng-dev, libssl-dev, libzip-dev (>= 1.0.0), libicu-dev (>= 59.0) +Build-Depends: debhelper (>= 9), cmake (>= 3.8), duktape-dev, libsdl2-dev, g++ (>= 4:7), pkg-config, libjansson4 (>= 2.5), libjansson-dev (>= 2.3), libspeex-dev, libspeexdsp-dev, libcurl4-openssl-dev, libcrypto++-dev, libfontconfig1-dev, libfreetype6-dev, libpng-dev, libssl-dev, libzip-dev (>= 1.0.0), libicu-dev (>= 59.0) Package: openrct2 Architecture: any diff --git a/distribution/changelog.txt b/distribution/changelog.txt index c3ad803b9e..21d5455419 100644 --- a/distribution/changelog.txt +++ b/distribution/changelog.txt @@ -4,6 +4,7 @@ - Feature: [#10572] Cheat to allow building at invalid heights. - Feature: [#11231] Change shortcut window list order to be more intuitive, and split it into logical sections. - Feature: [#11306] Path additions are now kept when replacing the path. +- Feature: [#11320] Support for custom JavaScript plugins. - Change: [#11209] Warn when user is running OpenRCT2 through Wine. - Change: [#11358] Switch copy and paste button positions in tile inspector. - Change: [#11449] Remove complete circuit requirement from Air Powered Vertical Coaster (for RCT1 parity). diff --git a/distribution/readme.txt b/distribution/readme.txt index 63d49b44a8..fa535c783a 100644 --- a/distribution/readme.txt +++ b/distribution/readme.txt @@ -141,6 +141,8 @@ OpenRCT2 is licensed under the GNU General Public Licence version 3.0. For the complete licence text, see the file 'licence.txt'. This licence applies to all files in this distribution, except as noted below. +dukglue | MIT licence. +duktape | MIT licence. Jansson | MIT licence. libcURL | MIT (or Modified BSD-style) licence. libicu | Unicode licence. diff --git a/readme.md b/readme.md index f6f999a91b..86ac2f7ef8 100644 --- a/readme.md +++ b/readme.md @@ -110,6 +110,7 @@ The program can also be built as a command line program using CMake. This type o - icu (>= 59.0) - zlib - gl (commonly provided by Mesa or GPU vendors; only for UI client, can be disabled) +- duktape (unless scripting is disabled) - cmake --- From c0aa5bdcc8ab6b67daa8e1fa7ca1d7f4fc2eeb17 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 14:52:57 +0100 Subject: [PATCH 157/159] Create plugin directory automatically --- src/openrct2/Context.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openrct2/Context.cpp b/src/openrct2/Context.cpp index 3b0d1a71b8..850863bbd2 100644 --- a/src/openrct2/Context.cpp +++ b/src/openrct2/Context.cpp @@ -1053,6 +1053,7 @@ namespace OpenRCT2 DIRID::TRACK, DIRID::LANDSCAPE, DIRID::HEIGHTMAP, + DIRID::PLUGIN, DIRID::THEME, DIRID::SEQUENCE, DIRID::REPLAY, From ca98ffc6978a3b7c00ad3b3bf5668137dab21143 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 16:01:03 +0100 Subject: [PATCH 158/159] Implement onClose event for custom windows --- src/openrct2-ui/scripting/CustomWindow.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/openrct2-ui/scripting/CustomWindow.cpp b/src/openrct2-ui/scripting/CustomWindow.cpp index 74039ea776..82e43334a3 100644 --- a/src/openrct2-ui/scripting/CustomWindow.cpp +++ b/src/openrct2-ui/scripting/CustomWindow.cpp @@ -192,6 +192,9 @@ namespace OpenRCT2::Ui::Windows std::vector Widgets; std::vector Colours; + // Event handlers + DukValue OnClose; + CustomWindowDesc() = default; bool IsResizable() const @@ -235,6 +238,8 @@ namespace OpenRCT2::Ui::Windows }); } + result.OnClose = desc["onClose"]; + return result; } @@ -338,8 +343,13 @@ namespace OpenRCT2::Ui::Windows static void window_custom_close(rct_window* w) { - delete static_cast(w->custom_info); - w->custom_info = nullptr; + auto info = static_cast(w->custom_info); + if (info != nullptr) + { + InvokeEventHandler(info->Owner, info->Desc.OnClose); + delete info; + w->custom_info = nullptr; + } } static void window_custom_mouseup(rct_window* w, rct_widgetindex widgetIndex) From 3c02861c63904a08f1c5ce1f5482476cdcd4fda5 Mon Sep 17 00:00:00 2001 From: Ted John Date: Sun, 26 Apr 2020 16:01:40 +0100 Subject: [PATCH 159/159] Increment network version --- src/openrct2/network/Network.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index f38fbf4597..d1c011f7f2 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -32,7 +32,7 @@ // This string specifies which version of network stream current build uses. // It is used for making sure only compatible builds get connected, even within // single OpenRCT2 version. -#define NETWORK_STREAM_VERSION "8" +#define NETWORK_STREAM_VERSION "9" #define NETWORK_STREAM_ID OPENRCT2_VERSION "-" NETWORK_STREAM_VERSION static Peep* _pickup_peep = nullptr;