diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2d124d4f..791f086e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,6 +21,9 @@ jobs: - lua - python - quickjs + target_type: + - client + - server steps: - uses: actions/checkout@v4 @@ -38,13 +41,13 @@ jobs: xmake repo -u - run: | - xmake f -a x64 -m release -p windows -v -y --backend=${{ matrix.backend }} + xmake f -a x64 -m release -p windows -v -y --target_type=${{ matrix.target_type }} --backend=${{ matrix.backend }} - run: | xmake -y - uses: actions/upload-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: | bin/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b6dcdba4..a4d46b85 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,9 @@ jobs: - lua - python - quickjs + target_type: + - client + - server steps: - uses: actions/checkout@v4 @@ -30,14 +33,14 @@ jobs: xmake repo -u - run: | - xmake f -a x64 -m release -p windows -v -y --backend=${{ matrix.backend }} --publish=true + xmake f -a x64 -m release -p windows -v -y --target_type=${{ matrix.target_type }} --backend=${{ matrix.backend }} --publish=true - run: | xmake -y - uses: actions/upload-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: | bin/ @@ -50,6 +53,9 @@ jobs: - lua - python - quickjs + target_type: + - client + - server runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -62,7 +68,7 @@ jobs: - uses: actions/download-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: artifact - run: | @@ -102,12 +108,15 @@ jobs: - lua - python - quickjs + target_type: + - client + - server steps: - uses: actions/checkout@v4 - uses: actions/download-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: release/ - run: | @@ -116,10 +125,10 @@ jobs: - name: Archive release run: | cd release - zip -r ../legacy-script-engine-${{ matrix.backend }}-windows-x64.zip * + zip -r ../${{ github.event.repository.name }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip * cd .. - uses: softprops/action-gh-release@v1 with: files: | - legacy-script-engine-${{ matrix.backend }}-windows-x64.zip + ${{ github.event.repository.name }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip diff --git a/.github/workflows/sync_translation.yml b/.github/workflows/sync_translation.yml new file mode 100644 index 00000000..7c37842a --- /dev/null +++ b/.github/workflows/sync_translation.yml @@ -0,0 +1,30 @@ +on: + schedule: + - cron: 0 * * * * + workflow_dispatch: + +permissions: + contents: write + +jobs: + update: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - run: | + pip install crowdin-api-client + + - run: | + python scripts/sync_translations.py ${{secrets.CROWDIN_API}} + + - name: Configure git + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Sync translations + run: | + git add . && \ + git commit -m "Sync translations from Crowdin" && \ + git push || echo "No changes to commit" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e71f4ac..fdcdb302 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.17.0] - 2026-01-25 + +### Added + +- Added client support + +### Changed + +- Supported LeviLamina 1.9.0 +- Replace int with CommandPermissionLevel for debugCommandLevel + +## [0.17.0-rc.2] - 2026-01-19 + +### Changed + +- Supported LeviLamina 1.8.0-rc.2 +- Added client support +- Replace int with CommandPermissionLevel for debugCommandLevel +- ## [0.16.8] - 2026-01-14 ### Added @@ -1113,7 +1132,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#332]: https://github.com/LiteLDev/LegacyScriptEngine/issues/332 [#339]: https://github.com/LiteLDev/LegacyScriptEngine/issues/339 -[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.8...HEAD +[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0...HEAD +[0.17.0]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0-rc.2...v0.17.0 +[0.17.0-rc.2]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...v0.17.0-rc.2 [0.16.8]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...v0.16.8 [0.16.7]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.6...v0.16.7 [0.16.6]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.5...v0.16.6 diff --git a/manifest.json b/manifest.json index 3925c982..1aa92d2e 100644 --- a/manifest.json +++ b/manifest.json @@ -3,6 +3,7 @@ "entry": "${modFile}", "version": "${modVersion}", "type": "native", + "platform": "${modPlatform}", "description": "A plugin engine for running LLSE plugins on LeviLamina", "author": "LiteLDev", "dependencies": [ diff --git a/scripts/download_crowdin_files.py b/scripts/sync_translations.py similarity index 100% rename from scripts/download_crowdin_files.py rename to scripts/sync_translations.py diff --git a/src-client/lse/PluginManager.cpp b/src-client/lse/PluginManager.cpp new file mode 100644 index 00000000..2dd9b818 --- /dev/null +++ b/src-client/lse/PluginManager.cpp @@ -0,0 +1,304 @@ +#include "lse/PluginManager.h" + +#include "legacy/engine/EngineManager.h" +#include "legacy/engine/EngineOwnData.h" +#include "ll/api/io/FileUtils.h" // IWYU pragma: keep +#include "ll/api/mod/Mod.h" +#include "ll/api/mod/ModManager.h" +#include "ll/api/service/GamingStatus.h" +#include "ll/api/utils/ErrorUtils.h" +#include "ll/api/utils/StringUtils.h" +#include "lse/Entry.h" +#include "lse/ScriptPlugin.h" + +#include +#include +#include +#include + +#ifdef LSE_BACKEND_LUA + +constexpr auto BaseLibFileName = "BaseLib.lua"; +constexpr auto PluginManagerName = "lse-lua"; + +#endif + +#ifdef LSE_BACKEND_QUICKJS + +constexpr auto BaseLibFileName = "BaseLib.js"; +constexpr auto PluginManagerName = "lse-quickjs"; + +#endif + +#ifdef LSE_BACKEND_PYTHON + +#include "legacy/main/PythonHelper.h" +constexpr auto BaseLibFileName = "BaseLib.py"; +constexpr auto PluginManagerName = "lse-python"; + +#endif + +#ifdef LSE_BACKEND_NODEJS + +#include "legacy/main/NodeJsHelper.h" +constexpr auto PluginManagerName = "lse-nodejs"; + +#endif + +// Do not use legacy headers directly, otherwise there will be tons of errors. +void BindAPIs(std::shared_ptr engine); +void LLSERemoveTimeTaskData(std::shared_ptr engine); +bool LLSERemoveAllEventListeners(std::shared_ptr engine); +bool LLSERemoveCmdRegister(std::shared_ptr engine); +bool LLSERemoveCmdCallback(std::shared_ptr engine); +bool LLSERemoveAllExportedFuncs(std::shared_ptr engine); +bool LLSECallEventsOnHotLoad(std::shared_ptr engine); +bool LLSECallEventsOnUnload(std::shared_ptr engine); + +namespace lse { + +PluginManager::PluginManager() : ll::mod::ModManager(PluginManagerName) {} +PluginManager::~PluginManager() = default; + +ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { + if (hasMod(manifest.name)) { + return ll::makeStringError("Plugin has already loaded"); + } + + auto plugin = std::make_shared(manifest); + + return plugin->onLoad().transform([&, this] { addMod(manifest.name, plugin); }); +} + +ll::Expected<> PluginManager::enable(std::string_view name) { + auto plugin = std::static_pointer_cast(getMod(name)); + if (!plugin) { + return ll::makeStringError("Plugin {0} not found"_tr(name)); + } + auto manifest = plugin->getManifest(); +#ifdef LSE_BACKEND_PYTHON + auto& logger = lse::LegacyScriptEngine::getLogger(); + std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path + std::string entryPath = + PythonHelper::findEntryScript(ll::string_utils::u8str2str(dirPath.u8string())); // Plugin entry + // if (entryPath.empty()) return false; + // std::string pluginName = PythonHelper::getPluginPackageName(dirPath.string()); // Plugin name + + // Run "pip install" if needed + auto realPackageInstallDir = (std::filesystem::path(dirPath) / "site-packages").make_preferred(); + if (!std::filesystem::exists(realPackageInstallDir)) { + std::string dependTmpFilePath = + PythonHelper::getPluginPackDependencyFilePath(ll::string_utils::u8str2str(dirPath.u8string())); + if (!dependTmpFilePath.empty()) { + int exitCode = 0; + logger.info( + "Executing \"pip install\" for plugin {name}..."_tr( + fmt::arg("name", ll::string_utils::u8str2str(dirPath.filename().u8string())) + ) + ); + + if ((exitCode = PythonHelper::executePipCommand( + "pip install -r \"" + dependTmpFilePath + "\" -t \"" + + ll::string_utils::u8str2str(realPackageInstallDir.u8string()) + "\" --disable-pip-version-check " + )) + == 0) { + logger.info("Pip finished successfully."_tr()); + } else logger.error("Error occurred. Exit code: {code}"_tr(fmt::arg("code", exitCode))); + + // remove temp dependency file after installation + std::error_code ec; + std::filesystem::remove(std::filesystem::path(dependTmpFilePath), ec); + } + } +#endif +#ifdef LSE_BACKEND_NODEJS + auto& logger = lse::LegacyScriptEngine::getLogger(); + std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path + // std::string entryPath = NodeJsHelper::findEntryScript(dirPath.string()); // Plugin entry + // if (entryPath.empty()) return false; + // std::string pluginName = NodeJsHelper::getPluginPackageName(dirPath.string()); // Plugin name + + // Run "npm install" if needed + if (NodeJsHelper::doesPluginPackHasDependency(ll::string_utils::u8str2str(dirPath.u8string())) + && !std::filesystem::exists(std::filesystem::path(dirPath) / "node_modules")) { + int exitCode = 0; + logger.info( + "Executing \"npm install\" for plugin {name}..."_tr( + fmt::arg("name", ll::string_utils::u8str2str(dirPath.filename().u8string())) + ) + ); + if ((exitCode = NodeJsHelper::executeNpmCommand( + {"install", "--omit=dev", "--no-fund"}, + ll::string_utils::u8str2str(dirPath.u8string()) + )) + != 0) { + logger.error("Error occurred. Exit code: {code}"_tr(fmt::arg("code", exitCode))); + } + } +#endif + auto scriptEngine = EngineManager::newEngine(manifest.name); + + try { + EngineScope engineScope(scriptEngine.get()); + + // Init plugin logger + getEngineOwnData()->logger = ll::io::LoggerRegistry::getInstance().getOrCreate(manifest.name); + +#ifdef LSE_BACKEND_PYTHON + scriptEngine->eval("import sys as _llse_py_sys_module"); + std::error_code ec; + + // add plugin-own site-packages to sys.path + std::string pluginSitePackageFormatted = ll::string_utils::u8str2str( + std::filesystem::canonical(realPackageInstallDir.make_preferred(), ec).u8string() + ); + if (!ec) { + scriptEngine->eval("_llse_py_sys_module.path.insert(0, r'" + pluginSitePackageFormatted + "')"); + } + // add plugin source dir to sys.path + std::string sourceDirFormatted = + ll::string_utils::u8str2str(std::filesystem::canonical(dirPath.make_preferred()).u8string()); + scriptEngine->eval("_llse_py_sys_module.path.insert(0, r'" + sourceDirFormatted + "')"); + + // set __file__ and __name__ + std::string entryPathFormatted = ll::string_utils::u8str2str( + std::filesystem::canonical(std::filesystem::path(entryPath).make_preferred()).u8string() + ); + scriptEngine->set("__file__", entryPathFormatted); + // engine->set("__name__", String::newString("__main__")); +#endif + + BindAPIs(scriptEngine); + +#ifndef LSE_BACKEND_NODEJS // NodeJs backend load depends code in another place + auto& self = LegacyScriptEngine::getInstance().getSelf(); + // Load BaseLib. + auto baseLibPath = self.getModDir() / "baselib" / BaseLibFileName; + auto baseLibContent = ll::file_utils::readFile(baseLibPath); + if (!baseLibContent) { + return ll::makeStringError("Failed to read BaseLib at {0}"_tr(baseLibPath.string())); + } + scriptEngine->eval(baseLibContent.value()); +#endif + // Load the plugin entry. + auto entryPath = plugin->getModDir() / manifest.entry; + getEngineOwnData()->plugin = plugin; +#ifdef LSE_BACKEND_PYTHON + if (!PythonHelper::loadPluginCode( + scriptEngine, + ll::string_utils::u8str2str(entryPath.u8string()), + ll::string_utils::u8str2str(dirPath.u8string()) + )) { + return ll::makeStringError("Failed to load plugin code"_tr()); + } +#endif +#ifdef LSE_BACKEND_NODEJS + if (!NodeJsHelper::loadPluginCode( + scriptEngine, + ll::string_utils::u8str2str(entryPath.u8string()), + ll::string_utils::u8str2str(dirPath.u8string()), + NodeJsHelper::isESModulesSystem(ll::string_utils::u8str2str(dirPath.u8string())) + )) { + return ll::makeStringError("Failed to load plugin code"_tr()); + } +#endif +#if (defined LSE_BACKEND_QUICKJS) || (defined LSE_BACKEND_LUA) + // Try loadFile + try { + scriptEngine->loadFile(entryPath.u8string()); + } catch (const Exception&) { + // loadFile failed, try eval + auto pluginEntryContent = ll::file_utils::readFile(entryPath); + if (!pluginEntryContent) { + return ll::makeStringError("Failed to read plugin entry at {0}"_tr(entryPath.string())); + } + scriptEngine->eval(pluginEntryContent.value(), entryPath.u8string()); + } +#endif + if (ll::getGamingStatus() == ll::GamingStatus::Running) { // Is hot load + LLSECallEventsOnHotLoad(scriptEngine); + } + ExitEngineScope exit; + + if (auto res = plugin->onEnable(); !res) { + return res; + } + + return {}; + } catch (const Exception& e) { + if (scriptEngine) { + auto error = [&] { + EngineScope engineScope(scriptEngine.get()); + return ll::makeStringError( + "Failed to enable plugin {0}: {1}\n{2}"_tr(manifest.name, e.message(), e.stacktrace()) + ); + }(); + +#ifndef LSE_BACKEND_NODEJS + LLSERemoveTimeTaskData(scriptEngine); +#endif + LLSERemoveAllEventListeners(scriptEngine); + LLSERemoveCmdRegister(scriptEngine); + LLSERemoveCmdCallback(scriptEngine); + LLSERemoveAllExportedFuncs(scriptEngine); + + EngineOwnData::clearEngineObjects(scriptEngine); + EngineManager::unregisterEngine(scriptEngine); +#ifdef LSE_BACKEND_NODEJS + NodeJsHelper::stopEngine(scriptEngine); +#endif + return error; + } else { + return ll::makeStringError("Failed to enable plugin {0}: {1}"_tr(manifest.name, "ScriptEngine is nullptr")); + } + } +} + +ll::Expected<> PluginManager::disable(std::string_view name) { + try { + auto scriptEngine = EngineManager::getEngine(std::string(name)); + + if (!scriptEngine) { + return ll::makeStringError("Plugin {0} not found"_tr(name)); + } + + { + EngineScope scope(scriptEngine.get()); + LLSECallEventsOnUnload(scriptEngine); +#ifndef LSE_BACKEND_NODEJS + LLSERemoveTimeTaskData(scriptEngine); +#endif + LLSERemoveAllEventListeners(scriptEngine); + LLSERemoveCmdRegister(scriptEngine); + LLSERemoveCmdCallback(scriptEngine); + LLSERemoveAllExportedFuncs(scriptEngine); + EngineOwnData::clearEngineObjects(scriptEngine); + } + EngineManager::unregisterEngine(scriptEngine); +#ifdef LSE_BACKEND_NODEJS + NodeJsHelper::stopEngine(scriptEngine); +#endif + + if (auto plugin = std::static_pointer_cast(getMod(name))) { + plugin->registeredCommands.clear(); + if (auto res = plugin->onDisable(); !res) { + return res; + } + } + return {}; + } catch (const Exception&) { + return ll::makeStringError("Failed to disable plugin {0}: {1}"_tr(name, "Unknown script exception")); + } catch (const std::exception& e) { + return ll::makeStringError("Failed to disable plugin {0}: {1}"_tr(name, e.what())); + } +} + +ll::Expected<> PluginManager::unload(std::string_view name) { + if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { + return res; + } + eraseMod(name); + return {}; +} + +} // namespace lse diff --git a/src-client/lse/PluginManager.h b/src-client/lse/PluginManager.h new file mode 100644 index 00000000..9ea8d567 --- /dev/null +++ b/src-client/lse/PluginManager.h @@ -0,0 +1,22 @@ +#pragma once +#include "ll/api/Expected.h" +#include "ll/api/mod/Manifest.h" +#include "ll/api/mod/ModManager.h" + +#include + +namespace lse { + +class PluginManager final : public ll::mod::ModManager { +public: + PluginManager(); + ~PluginManager() override; + +private: + ll::Expected<> load(ll::mod::Manifest manifest) override; + ll::Expected<> unload(std::string_view name) override; + ll::Expected<> enable(std::string_view name) override; + ll::Expected<> disable(std::string_view name) override; +}; + +} // namespace lse diff --git a/src/lse/PluginManager.cpp b/src-server/lse/PluginManager.cpp similarity index 95% rename from src/lse/PluginManager.cpp rename to src-server/lse/PluginManager.cpp index 27c9cbd1..ddd7e971 100644 --- a/src/lse/PluginManager.cpp +++ b/src-server/lse/PluginManager.cpp @@ -1,22 +1,18 @@ -#include "PluginManager.h" +#include "lse/PluginManager.h" -#include "Entry.h" -#include "Plugin.h" #include "legacy/engine/EngineManager.h" #include "legacy/engine/EngineOwnData.h" -#include "ll/api/chrono/GameChrono.h" -#include "ll/api/coro/CoroTask.h" #include "ll/api/io/FileUtils.h" // IWYU pragma: keep #include "ll/api/mod/Mod.h" #include "ll/api/mod/ModManager.h" #include "ll/api/service/GamingStatus.h" -#include "ll/api/thread/ServerThreadExecutor.h" #include "ll/api/utils/StringUtils.h" +#include "lse/Entry.h" +#include "lse/ScriptPlugin.h" #include #include #include -#include #include #ifdef LSE_BACKEND_LUA @@ -65,7 +61,7 @@ PluginManager::~PluginManager() = default; ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { #ifdef LSE_BACKEND_PYTHON - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path std::string entryPath = PythonHelper::findEntryScript(ll::string_utils::u8str2str(dirPath.u8string())); // Plugin entry @@ -100,7 +96,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { } #endif #ifdef LSE_BACKEND_NODEJS - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path // std::string entryPath = NodeJsHelper::findEntryScript(dirPath.string()); // Plugin entry // if (entryPath.empty()) return false; @@ -129,7 +125,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { } auto scriptEngine = EngineManager::newEngine(manifest.name); - auto plugin = std::make_shared(manifest); + auto plugin = std::make_shared(manifest); try { EngineScope engineScope(scriptEngine.get()); @@ -212,7 +208,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { LLSECallEventsOnHotLoad(scriptEngine); } ExitEngineScope exit; - plugin->onLoad([](ll::mod::Mod&) { return true; }); + plugin->onDisable([this](ll::mod::Mod& self) { if (ll::getGamingStatus() == ll::GamingStatus::Stopping) { unload(self.getName()); @@ -271,16 +267,14 @@ ll::Expected<> PluginManager::unload(std::string_view name) { EngineOwnData::clearEngineObjects(scriptEngine); } EngineManager::unregisterEngine(scriptEngine); - - if (auto plugin = std::static_pointer_cast(getMod(name))) { - plugin->onUnload(); - } - - eraseMod(name); - #ifdef LSE_BACKEND_NODEJS NodeJsHelper::stopEngine(scriptEngine); #endif + + if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { + return res; + } + eraseMod(name); return {}; } catch (const Exception&) { return ll::makeStringError("Failed to unload plugin {0}: {1}"_tr(name, "Unknown script exception")); diff --git a/src/lse/PluginManager.h b/src-server/lse/PluginManager.h similarity index 93% rename from src/lse/PluginManager.h rename to src-server/lse/PluginManager.h index 7651b477..67a0949b 100644 --- a/src/lse/PluginManager.h +++ b/src-server/lse/PluginManager.h @@ -1,6 +1,5 @@ #pragma once #include "ll/api/Expected.h" -#include "ll/api/base/Macro.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/ModManager.h" diff --git a/src/lang/de.json b/src/lang/de.json index 60dac295..ad286afb 100644 --- a/src/lang/de.json +++ b/src/lang/de.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Konnte {} in registrierten Befehlen nicht finden." }, - "Event {} not found!": "Event {} nicht gefunden!" + "Event {} not found!": "Event {} nicht gefunden!", + "Failed to enable plugin {0}: {1}\\n{2}": "Konnte Plugin {0}nicht aktivieren: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Konnte Plugin {0}nicht aktivieren: {1}", + "Failed to disable plugin {0}: {1}": "Konnte Plugin {0}nicht deaktivieren: {1}" } diff --git a/src/lang/en.json b/src/lang/en.json index ec2992d2..86042a21 100644 --- a/src/lang/en.json +++ b/src/lang/en.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/fr.json b/src/lang/fr.json index 9369f4ce..60f1e6b8 100644 --- a/src/lang/fr.json +++ b/src/lang/fr.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Impossible de trouver {} dans les commandes enregistrées." }, - "Event {} not found!": "Événement {} introuvable !" + "Event {} not found!": "Événement {} introuvable !", + "Failed to enable plugin {0}: {1}\\n{2}": "Impossible d'activer le plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Impossible d'activer le plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Impossible de désactiver le plugin {0}: {1}" } diff --git a/src/lang/id.json b/src/lang/id.json index 749d7d98..f6c110a6 100644 --- a/src/lang/id.json +++ b/src/lang/id.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/it.json b/src/lang/it.json index 16cc424e..193c9ead 100644 --- a/src/lang/it.json +++ b/src/lang/it.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Impossibile trovare {} nei comandi registrati." }, - "Event {} not found!": "Evento {} non trovato!" + "Event {} not found!": "Evento {} non trovato!", + "Failed to enable plugin {0}: {1}\\n{2}": "Attivazione del plugin {0}non riuscita: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Attivazione del plugin {0}non riuscita: {1}", + "Failed to disable plugin {0}: {1}": "Impossibile disabilitare il plugin {0}: {1}" } diff --git a/src/lang/ja.json b/src/lang/ja.json index 029796aa..b5dd7096 100644 --- a/src/lang/ja.json +++ b/src/lang/ja.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "登録されたコマンドで {} が見つかりませんでした。" }, - "Event {} not found!": "イベント {} が見つかりません!" + "Event {} not found!": "イベント {} が見つかりません!", + "Failed to enable plugin {0}: {1}\\n{2}": "プラグイン {0}の有効化に失敗しました: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "プラグイン {0}の有効化に失敗しました: {1}", + "Failed to disable plugin {0}: {1}": "プラグイン {0}の無効化に失敗しました: {1}" } diff --git a/src/lang/ko.json b/src/lang/ko.json index a4f541ba..8d7e58d3 100644 --- a/src/lang/ko.json +++ b/src/lang/ko.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/pt_BR.json b/src/lang/pt_BR.json index 0a5216d7..ff9aff26 100644 --- a/src/lang/pt_BR.json +++ b/src/lang/pt_BR.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Não foi possível encontrar {} nos comandos registrados." }, - "Event {} not found!": "Evento {} não encontrado!" + "Event {} not found!": "Evento {} não encontrado!", + "Failed to enable plugin {0}: {1}\\n{2}": "Falha ao ativar o plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Falha ao ativar o plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Falha ao desativar o plugin {0}: {1}" } diff --git a/src/lang/ru.json b/src/lang/ru.json index cf5fae16..02f7943f 100644 --- a/src/lang/ru.json +++ b/src/lang/ru.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Не удалось найти {} в зарегистрированных командах." }, - "Event {} not found!": "Событие {} не найдено!" + "Event {} not found!": "Событие {} не найдено!", + "Failed to enable plugin {0}: {1}\\n{2}": "Не удалось включить плагин {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Не удалось включить плагин {0}: {1}", + "Failed to disable plugin {0}: {1}": "Не удалось отключить плагин {0}: {1}" } diff --git a/src/lang/th.json b/src/lang/th.json index a007ebf7..4b3df5b4 100644 --- a/src/lang/th.json +++ b/src/lang/th.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/tr.json b/src/lang/tr.json index 7d056e34..728894be 100644 --- a/src/lang/tr.json +++ b/src/lang/tr.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/vi.json b/src/lang/vi.json index dc922fc8..b0a2f62f 100644 --- a/src/lang/vi.json +++ b/src/lang/vi.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/zh_CN.json b/src/lang/zh_CN.json index 28c599be..fdb834a3 100644 --- a/src/lang/zh_CN.json +++ b/src/lang/zh_CN.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "在已注册的命令中找不到 {} 。" }, - "Event {} not found!": "找不到事件 {} !" + "Event {} not found!": "找不到事件 {} !", + "Failed to enable plugin {0}: {1}\\n{2}": "启用插件 {0} 失败: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "启用插件 {0} 失败: {1}", + "Failed to disable plugin {0}: {1}": "禁用插件 {0} 失败: {1}" } diff --git a/src/lang/zh_TW.json b/src/lang/zh_TW.json index c18b5464..7e6715a0 100644 --- a/src/lang/zh_TW.json +++ b/src/lang/zh_TW.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/legacy/api/APIHelp.cpp b/src/legacy/api/APIHelp.cpp index 67ed8517..f0f9391b 100644 --- a/src/legacy/api/APIHelp.cpp +++ b/src/legacy/api/APIHelp.cpp @@ -332,7 +332,7 @@ Local JsonToValue(std::string jsonStr) { auto j = ordered_json::parse(jsonStr, nullptr, true, true); return JsonToValue(j); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "{}{}", "JSON parse error"_tr(), ll::string_utils::tou8str(e.what()) diff --git a/src/legacy/api/APIHelp.h b/src/legacy/api/APIHelp.h index 38c30668..ec4fa1b0 100644 --- a/src/legacy/api/APIHelp.h +++ b/src/legacy/api/APIHelp.h @@ -25,19 +25,19 @@ std::string ValueKindToString(const ValueKind& kind); // 输出脚本调用堆栈,API名称,以及插件名 inline void CREATE_EXCEPTION_WITH_SCRIPT_INFO(std::string const& func = {}, std::string const& msg = {}) { auto e = script::Exception(msg); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "script::Exception: {0}\n{1}", e.message(), e.stacktrace() ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In API: " + func); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); + lse::LegacyScriptEngine::getLogger().error("In API: " + func); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); } inline void LOG_ERROR_WITH_SCRIPT_INFO(std::string const& func = {}, std::string const& msg = {}) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(msg); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In API: " + func); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); + lse::LegacyScriptEngine::getLogger().error(msg); + lse::LegacyScriptEngine::getLogger().error("In API: " + func); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); } // 参数类型错误输出 @@ -72,13 +72,13 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常 #define CATCH(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return Local(); \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return Local(); \ } @@ -107,13 +107,13 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常_Constructor #define CATCH_C(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return nullptr; \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return nullptr; \ } @@ -121,13 +121,13 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常_Setter #define CATCH_S(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return; \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return; \ } @@ -135,33 +135,33 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常_Constructor #define CATCH_WITHOUT_RETURN(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ } // 截获回调函数异常 #define CATCH_IN_CALLBACK(callback) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ + lse::LegacyScriptEngine::getLogger().error( \ std::string("In callback for ") + callback \ ); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ std::string("In callback for ") + callback \ ); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ } @@ -252,7 +252,7 @@ struct EnumDefineBuilder { } return arr; } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -265,7 +265,7 @@ struct EnumDefineBuilder { } return obj; } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -280,7 +280,7 @@ struct EnumDefineBuilder { return String::newString(magic_enum::enum_name(static_cast(args[0].asNumber().toInt32()))); return Local(); } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -289,7 +289,7 @@ struct EnumDefineBuilder { try { return String::newString(typeid(Type).name() + 5); } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -302,7 +302,7 @@ struct EnumDefineBuilder { try { return Number::newNumber(static_cast(val)); } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error in get {}.{}", enumName, name diff --git a/src/legacy/api/BlockAPI.cpp b/src/legacy/api/BlockAPI.cpp index f9b21434..8d54edc9 100644 --- a/src/legacy/api/BlockAPI.cpp +++ b/src/legacy/api/BlockAPI.cpp @@ -5,7 +5,6 @@ #include "api/BaseAPI.h" #include "api/BlockEntityAPI.h" #include "api/ContainerAPI.h" -#include "api/EntityAPI.h" #include "api/McAPI.h" #include "api/NbtAPI.h" #include "ll/api/service/Bedrock.h" @@ -299,7 +298,7 @@ Local BlockClass::destroyBlock(const Arguments& args) { ll::service::getLevel()->getDimension(blockPos.dim).lock()->getBlockSourceFromMainChunkSource(); return Boolean::newBoolean( ll::service::getLevel() - ->destroyBlock(bl, blockPos.getBlockPos(), args[0].asBoolean().value(), BlockChangeContext()) + ->destroyBlock(bl, blockPos.getBlockPos(), args[0].asBoolean().value(), BlockChangeContext(false)) ); } CATCH("Fail in destroyBlock!"); @@ -327,7 +326,7 @@ Local BlockClass::setNbt(const Arguments& args) { ->getDimension(blockPos.dim) .lock() ->getBlockSourceFromMainChunkSource() - .setBlock(blockPos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext()); + .setBlock(blockPos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext(false)); } preloadData(blockPos.getBlockPos(), blockPos.getDimensionId()); return Boolean::newBoolean(true); @@ -464,7 +463,11 @@ Local McClass::getBlock(const Arguments& args) { return {}; } auto& block = lc->getBlock( - ChunkBlockPos{(uchar)(pos.x & 0xf), ChunkLocalHeight{(short)pos.y - minHeight}, (uchar)(pos.z & 0xf)} + ChunkBlockPos{ + (uchar)(pos.x & 0xf), + ChunkLocalHeight{static_cast(pos.y - minHeight)}, + (uchar)(pos.z & 0xf) + } ); return BlockClass::newBlock(block, pos.getBlockPos(), pos.dim); } @@ -535,7 +538,7 @@ Local McClass::setBlock(const Arguments& args) { } BlockSource& bs = ll::service::getLevel()->getDimension(pos.dim).lock()->getBlockSourceFromMainChunkSource(); - return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext())); + return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext(false))); } else if (IsInstanceOf(block)) { // Nbt auto nbt = NbtCompoundClass::extract(block); @@ -545,7 +548,7 @@ Local McClass::setBlock(const Arguments& args) { } BlockSource& bs = ll::service::getLevel()->getDimension(pos.dim).lock()->getBlockSourceFromMainChunkSource(); - return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext())); + return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext(false))); } else { // other block object Block const* bl = BlockClass::extract(block); @@ -555,7 +558,7 @@ Local McClass::setBlock(const Arguments& args) { } BlockSource& bs = ll::service::getLevel()->getDimension(pos.dim).lock()->getBlockSourceFromMainChunkSource(); - return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext())); + return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext(false))); } } CATCH("Fail in SetBlock!") diff --git a/src/legacy/api/CommandAPI.cpp b/src/legacy/api/CommandAPI.cpp index 901dde86..07b234ed 100644 --- a/src/legacy/api/CommandAPI.cpp +++ b/src/legacy/api/CommandAPI.cpp @@ -20,6 +20,7 @@ #include "ll/api/thread/ServerThreadExecutor.h" #include "magic_enum.hpp" #include "mc/_HeaderOutputPredefine.h" +#include "mc/common/SharedPtr.h" #include "mc/deps/core/utility/MCRESULT.h" #include "mc/deps/json/FastWriter.h" #include "mc/deps/json/Value.h" @@ -94,11 +95,10 @@ Local convertResult(ParamStorageType const& result, CommandOrigin const& -1 ); } else if (result.hold(ParamKind::Kind::Item)) { - return ItemClass::newItem( - std::make_unique(ll::service::getLevel()->getItemRegistry().getNameFromLegacyID( - std::get(result.value()).mId - )) - ); + if (auto itemPtr = + ll::service::getLevel()->getItemRegistry().getItem(std::get(result.value()).mId).lock()) { + return ItemClass::newItem(std::make_unique(*itemPtr)); + } } else if (result.hold(ParamKind::Kind::Actor)) { auto arr = Array::newArray(); for (auto i : std::get>(result.value()).results(origin)) { @@ -162,7 +162,7 @@ std::enable_if_t, T> parseEnum(Local const& value) { if (!tmp.has_value()) throw std::runtime_error("Unable to parse Enum value"); return tmp.value(); } else if (value.isNumber()) { - return (T)value.asNumber().toInt32(); + return static_cast(value.asNumber().toInt32()); } throw std::runtime_error("Unable to parse Enum value"); } @@ -198,7 +198,7 @@ Local McClass::runcmdEx(const Arguments& args) { auto command = ll::service::getMinecraft()->mCommands->compileCommand( args[0].asString().toString(), origin, - (CurrentCmdVersion)CommandVersion::CurrentVersion(), + static_cast(CommandVersion::CurrentVersion()), [&](std::string const& err) { outputStr.append(err).append("\n"); } ); Local resObj = Object::newObject(); @@ -238,13 +238,13 @@ Local McClass::newCommand(const Arguments& args) { auto desc = args[1].asString().toString(); CommandPermissionLevel permission = CommandPermissionLevel::Admin; - CommandFlag flag = {(CommandFlagValue)0x80}; + CommandFlag flag = {static_cast(0x80)}; std::string alias; if (args.size() > 2) { - permission = (CommandPermissionLevel)parseEnum(args[2]); + permission = static_cast(parseEnum(args[2])); if (args.size() > 3) { CHECK_ARG_TYPE(args[3], ValueKind::kNumber); - flag = {(CommandFlagValue)args[3].asNumber().toInt32()}; + flag = {static_cast(args[3].asNumber().toInt32())}; if (args.size() > 4) { CHECK_ARG_TYPE(args[4], ValueKind::kString); alias = args[4].asString().toString(); @@ -256,16 +256,14 @@ Local McClass::newCommand(const Arguments& args) { CommandPermissionLevel const& permission, CommandFlag const& flag, std::string const& alias) { - auto registry = ll::service::getCommandRegistry(); - if (registry) { - auto instance = registry->findCommand(name); - if (instance) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + if (auto registry = ll::service::getCommandRegistry()) { + if (registry->findCommand(name)) { + lse::LegacyScriptEngine::getLogger().warn( "Runtime command {} already exists, changes will not beapplied except for setOverload!"_tr(name) ); } } - auto& command = CommandRegistrar::getInstance().getOrCreateCommand(name, desc, permission, flag); + auto& command = CommandRegistrar::getInstance(false).getOrCreateCommand(name, desc, permission, flag); if (!alias.empty()) { command.alias(alias); } @@ -308,7 +306,7 @@ Local CommandClass::setAlias(const Arguments& args) { std::string alias = args[0].asString().toString(); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([commandName(commandName), alias]() -> ll::coro::CoroTask<> { - ll::command::CommandRegistrar::getInstance().getOrCreateCommand(commandName).alias(alias); + CommandRegistrar::getInstance(false).getOrCreateCommand(commandName).alias(alias); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); return Boolean::newBoolean(true); @@ -335,12 +333,12 @@ Local CommandClass::setEnum(const Arguments& args) { } if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([enumName, enumValues]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().tryRegisterRuntimeEnum(enumName, std::move(enumValues)); + CommandRegistrar::getInstance(false).tryRegisterRuntimeEnum(enumName, std::move(enumValues)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); return String::newString(enumName); } else { - if (CommandRegistrar::getInstance().tryRegisterRuntimeEnum(enumName, std::move(enumValues))) { + if (CommandRegistrar::getInstance(false).tryRegisterRuntimeEnum(enumName, std::move(enumValues))) { return String::newString(enumName); } } @@ -351,8 +349,8 @@ Local CommandClass::setEnum(const Arguments& args) { void onExecute(CommandOrigin const& origin, CommandOutput& output, RuntimeCommand const& runtime) { std::string commandName = runtime.getCommandName(); - if (localShareData->commandCallbacks.find(commandName) == localShareData->commandCallbacks.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + if (!localShareData->commandCallbacks.contains(commandName)) { + lse::LegacyScriptEngine::getLogger().warn( "Command {} failed to execute, is the plugin unloaded?"_tr(commandName) ); return; @@ -365,10 +363,8 @@ void onExecute(CommandOrigin const& origin, CommandOutput& output, RuntimeComman auto* outp = new CommandOutputClass(std::make_shared(output), ori->get()); auto& registeredCommands = getEngineOwnData()->plugin->registeredCommands; - if (registeredCommands.find(commandName) == registeredCommands.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( - "Could not find {} in registered commands."_tr(commandName) - ); + if (!registeredCommands.contains(commandName)) { + lse::LegacyScriptEngine::getLogger().warn("Could not find {} in registered commands."_tr(commandName)); return; } for (auto& info : registeredCommands[commandName]) { @@ -411,7 +407,7 @@ Local CommandClass::newParameter(const Arguments& args) { CHECK_ARG_TYPE(args[0], ValueKind::kString); try { auto name = args[0].asString().toString(); - ParamKind::Kind type = (ParamKind::Kind)parseEnum(args[1]); + ParamKind::Kind type = static_cast(parseEnum(args[1])); std::string enumName = ""; bool optional = false; std::string identifier = ""; @@ -421,7 +417,7 @@ Local CommandClass::newParameter(const Arguments& args) { if (args.size() > index && args[index].isString()) enumName = args[index++].asString().toString(); if (args.size() > index && args[index].isString()) identifier = args[index++].asString().toString(); if (args.size() > index && args[index].isNumber()) - option = (CommandParameterOption)args[index++].asNumber().toInt32(); + option = static_cast(args[index++].asNumber().toInt32()); if (index != args.size()) throw std::runtime_error("Error Argument in newParameter"); getEngineOwnData()->plugin->registeredCommands[commandName].push_back( @@ -440,7 +436,7 @@ Local CommandClass::mandatory(const Arguments& args) { CHECK_ARG_TYPE(args[0], ValueKind::kString); try { auto name = args[0].asString().toString(); - ParamKind::Kind type = (ParamKind::Kind)parseEnum(args[1]); + ParamKind::Kind type = static_cast(parseEnum(args[1])); std::string enumName = ""; std::string identifier = ""; size_t index = 2; @@ -448,7 +444,7 @@ Local CommandClass::mandatory(const Arguments& args) { if (args.size() > index && args[index].isString()) enumName = args[index++].asString().toString(); if (args.size() > index && args[index].isString()) identifier = args[index++].asString().toString(); if (args.size() > index && args[index].isNumber()) - option = (CommandParameterOption)args[index++].asNumber().toInt32(); + option = static_cast(args[index++].asNumber().toInt32()); if (index != args.size()) throw std::runtime_error("Error Argument in newParameter"); getEngineOwnData()->plugin->registeredCommands[commandName].push_back( @@ -467,7 +463,7 @@ Local CommandClass::optional(const Arguments& args) { CHECK_ARG_TYPE(args[0], ValueKind::kString); try { auto name = args[0].asString().toString(); - ParamKind::Kind type = (ParamKind::Kind)parseEnum(args[1]); + ParamKind::Kind type = static_cast(parseEnum(args[1])); std::string enumName = ""; std::string identifier = ""; size_t index = 2; @@ -475,7 +471,7 @@ Local CommandClass::optional(const Arguments& args) { if (args.size() > index && args[index].isString()) enumName = args[index++].asString().toString(); if (args.size() > index && args[index].isString()) identifier = args[index++].asString().toString(); if (args.size() > index && args[index].isNumber()) - option = (CommandParameterOption)args[index++].asNumber().toInt32(); + option = static_cast(args[index++].asNumber().toInt32()); if (index != args.size()) throw std::runtime_error("Error Argument in newParameter"); getEngineOwnData()->plugin->registeredCommands[commandName].push_back( @@ -517,7 +513,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [paramNames, commandName(commandName), overloadFunc, e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { - auto cmd = ll::command::CommandRegistrar::getInstance() + auto cmd = CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); for (auto& paramName : paramNames) { @@ -533,7 +529,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [commandName(commandName), e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { getEngineData(e)->plugin->registeredCommands[commandName].push_back({}); - auto cmd = ll::command::CommandRegistrar::getInstance() + auto cmd = CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); cmd.execute(onExecute); @@ -591,7 +587,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [commandName(commandName), e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { getEngineData(e)->plugin->registeredCommands[commandName].push_back({}); - auto cmd = ll::command::CommandRegistrar::getInstance() + auto cmd = CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); cmd.execute(onExecute); @@ -691,11 +687,11 @@ Local CommandClass::setSoftEnum(const Arguments& args) { auto enums = parseStringList(args[1].asArray()); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([name, enums]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().tryRegisterSoftEnum(name, std::move(enums)); + CommandRegistrar::getInstance(false).tryRegisterSoftEnum(name, std::move(enums)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); } else { - CommandRegistrar::getInstance().tryRegisterSoftEnum(name, std::move(enums)); + CommandRegistrar::getInstance(false).tryRegisterSoftEnum(name, std::move(enums)); } return Boolean::newBoolean(true); } @@ -711,11 +707,11 @@ Local CommandClass::addSoftEnumValues(const Arguments& args) { auto enums = parseStringList(args[1].asArray()); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([name, enums]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().addSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).addSoftEnumValues(name, std::move(enums)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); } else { - CommandRegistrar::getInstance().addSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).addSoftEnumValues(name, std::move(enums)); } return Boolean::newBoolean(true); } @@ -731,11 +727,11 @@ Local CommandClass::removeSoftEnumValues(const Arguments& args) { auto enums = parseStringList(args[1].asArray()); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([name, enums]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().removeSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).removeSoftEnumValues(name, std::move(enums)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); } else { - CommandRegistrar::getInstance().removeSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).removeSoftEnumValues(name, std::move(enums)); } return Boolean::newBoolean(true); } @@ -746,12 +742,11 @@ Local CommandClass::getSoftEnumValues(const Arguments& args) { CHECK_ARGS_COUNT(args, 1); CHECK_ARG_TYPE(args[0], ValueKind::kString); try { - auto name = args[0].asString().toString(); - auto registry = ll::service::getCommandRegistry(); - if (registry) { + auto name = args[0].asString().toString(); + if (auto registry = ll::service::getCommandRegistry()) { auto& lookup = registry->mSoftEnumLookup; auto& softEnums = registry->mSoftEnums; - if (lookup.find(name) != lookup.end()) { + if (lookup.contains(name)) { return getStringArray(softEnums[lookup[name]].mValues); } } diff --git a/src/legacy/api/CommandAPI.h b/src/legacy/api/CommandAPI.h index 6e8ba34b..1e014b2f 100644 --- a/src/legacy/api/CommandAPI.h +++ b/src/legacy/api/CommandAPI.h @@ -51,7 +51,7 @@ class CommandClass : public ScriptClass { std::string commandName; std::string description; inline ll::command::CommandHandle& get() { - return ll::command::CommandRegistrar::getInstance().getOrCreateCommand(commandName); + return ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand(commandName); } inline std::vector parseStringList(Local arr) { if (arr.size() == 0 || !arr.get(0).isString()) return {}; diff --git a/src/legacy/api/CommandCompatibleAPI.cpp b/src/legacy/api/CommandCompatibleAPI.cpp index 1aa594f1..b4a6fff8 100644 --- a/src/legacy/api/CommandCompatibleAPI.cpp +++ b/src/legacy/api/CommandCompatibleAPI.cpp @@ -100,7 +100,7 @@ Local McClass::regConsoleCmd(const Arguments& args) { // Helper bool SendCmdOutput(const std::string& output) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info(output); + lse::LegacyScriptEngine::getLogger().info(output); return true; } // Helper diff --git a/src/legacy/api/CommandOutputAPI.cpp b/src/legacy/api/CommandOutputAPI.cpp index 08e3a0e3..e6c010a1 100644 --- a/src/legacy/api/CommandOutputAPI.cpp +++ b/src/legacy/api/CommandOutputAPI.cpp @@ -39,7 +39,7 @@ Local CommandOutputClass::empty() { Local CommandOutputClass::getSuccessCount() { try { - return Number::newNumber(get()->mSuccessCount); + return Number::newNumber(static_cast(get()->mSuccessCount)); } CATCH("Fail in getSuccessCount!"); }; diff --git a/src/legacy/api/DataAPI.cpp b/src/legacy/api/DataAPI.cpp index 10d0b3c3..da9fa1a9 100644 --- a/src/legacy/api/DataAPI.cpp +++ b/src/legacy/api/DataAPI.cpp @@ -206,8 +206,8 @@ Local ConfJsonClass::reload(const Arguments&) { try { return Boolean::newBoolean(reload()); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail to parse json content in file!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail to parse json content in file!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in confJsonReload!"); @@ -254,8 +254,8 @@ bool ConfJsonClass::reload() { try { jsonConf = ordered_json::parse(*jsonTexts, nullptr, true, true); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in confJsonReload!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail in confJsonReload!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); return false; } @@ -534,12 +534,12 @@ Local MoneyClass::set(const Arguments& args) { EconomySystem::setMoney(args[0].asString().toString(), args[1].asNumber().toInt64()) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneySet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneySet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneySet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneySet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneySet!"); @@ -552,12 +552,12 @@ Local MoneyClass::get(const Arguments& args) { try { return Number::newNumber(EconomySystem::getMoney(args[0].asString().toString())); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Number::newNumber(0); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Number::newNumber(0); } CATCH("Fail in MoneyGet!"); @@ -573,12 +573,12 @@ Local MoneyClass::add(const Arguments& args) { EconomySystem::addMoney(args[0].asString().toString(), args[1].asNumber().toInt64()) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyAdd!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyAdd!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyAdd!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyAdd!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneyAdd!"); @@ -594,12 +594,12 @@ Local MoneyClass::reduce(const Arguments& args) { EconomySystem::reduceMoney(args[0].asString().toString(), args[1].asNumber().toInt64()) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyReduce!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyReduce!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyReduce!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyReduce!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneyReduce!"); @@ -623,12 +623,12 @@ Local MoneyClass::trans(const Arguments& args) { ) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyTrans!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyTrans!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyTrans!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyTrans!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneyTrans!"); @@ -665,12 +665,12 @@ Local MoneyClass::getHistory(const Arguments& args) { string res{EconomySystem::getMoneyHist(args[0].asString().toString(), args[1].asNumber().toInt32())}; return objectificationMoneyHistory(res); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGetHistory!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGetHistory!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Local(); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGetHistory!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGetHistory!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Local(); } CATCH("Fail in MoneyGetHistory!"); @@ -837,7 +837,7 @@ Local DataClass::toJson(const Arguments& args) { try { return String::newString(ValueToJson(args[0], spaces)); } catch (...) { - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, "Failed to transform into Json."); return Local(); } @@ -853,7 +853,7 @@ Local DataClass::parseJson(const Arguments& args) { try { return JsonToValue(args[0].asString().toString()); } catch (...) { - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, "Failed to parse from Json."); return Local(); } diff --git a/src/legacy/api/DatabaseAPI.cpp b/src/legacy/api/DatabaseAPI.cpp index 2e0925ac..fdee2520 100644 --- a/src/legacy/api/DatabaseAPI.cpp +++ b/src/legacy/api/DatabaseAPI.cpp @@ -4,9 +4,9 @@ using namespace DB; #define CATCH_AND_THROW(LOG) \ catch (const Exception& e) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ return Local(); \ @@ -15,10 +15,10 @@ using namespace DB; throw Exception(ll::string_utils::tou8str(e.what())); \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Uncaught Exception Detected!"); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In API: " __FUNCTION__); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error("Uncaught Exception Detected!"); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error("In API: " __FUNCTION__); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ return Local(); \ diff --git a/src/legacy/api/EntityAPI.cpp b/src/legacy/api/EntityAPI.cpp index 01b426e5..ddc6a831 100644 --- a/src/legacy/api/EntityAPI.cpp +++ b/src/legacy/api/EntityAPI.cpp @@ -12,11 +12,11 @@ #include "ll/api/service/Bedrock.h" #include "lse/api/MoreGlobal.h" #include "lse/api/helper/AttributeHelper.h" -#include "lse/api/helper/BlockHelper.h" #include "mc/deps/core/math/Vec2.h" #include "mc/deps/shared_types/legacy/actor/ActorDamageCause.h" #include "mc/deps/vanilla_components/ActorDataFlagComponent.h" #include "mc/deps/vanilla_components/StateVectorComponent.h" +#include "mc/entity/components/AttributesComponent.h" #include "mc/entity/components/InsideBlockComponent.h" #include "mc/entity/components/IsOnHotBlockFlagComponent.h" #include "mc/entity/components/TagsComponent.h" @@ -34,10 +34,9 @@ #include "mc/world/actor/Mob.h" #include "mc/world/actor/item/ItemActor.h" #include "mc/world/actor/player/Player.h" -#include "mc/world/actor/provider/ActorAttribute.h" #include "mc/world/actor/provider/ActorEquipment.h" #include "mc/world/actor/provider/SynchedActorDataAccess.h" -#include "mc/world/attribute/MutableAttributeWithContext.h" +#include "mc/world/attribute/Attribute.h" #include "mc/world/attribute/SharedAttributes.h" #include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" @@ -480,7 +479,7 @@ Local EntityClass::getHealth() { Actor* entity = get(); if (!entity) return Local(); - return Number::newNumber(ActorAttribute::getHealth(entity->getEntityContext())); + return Number::newNumber(entity->getHealth()); } CATCH("Fail in GetHealth!") } @@ -1017,9 +1016,16 @@ Local EntityClass::setHealth(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setHealth!"); } @@ -1032,10 +1038,16 @@ Local EntityClass::setAbsorption(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::ABSORPTION()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ABSORPTION(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAbsorptionAttribute!"); } @@ -1048,10 +1060,16 @@ Local EntityClass::setAttackDamage(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAttackDamage!"); } @@ -1064,10 +1082,16 @@ Local EntityClass::setMaxAttackDamage(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxAttackDamage!"); } @@ -1080,10 +1104,16 @@ Local EntityClass::setFollowRange(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::FOLLOW_RANGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::FOLLOW_RANGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setFollowRange!"); } @@ -1096,10 +1126,16 @@ Local EntityClass::setKnockbackResistance(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::KNOCKBACK_RESISTANCE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::KNOCKBACK_RESISTANCE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setKnockbackResistance!"); } @@ -1112,10 +1148,16 @@ Local EntityClass::setLuck(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::LUCK()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LUCK(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLuck!"); } @@ -1128,9 +1170,15 @@ Local EntityClass::setMovementSpeed(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } return Boolean::newBoolean(false); } CATCH("Fail in setMovementSpeed!"); @@ -1144,11 +1192,16 @@ Local EntityClass::setUnderwaterMovementSpeed(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = - entity->getMutableAttribute(SharedAttributes::UNDERWATER_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::UNDERWATER_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setUnderwaterMovementSpeed!"); } @@ -1161,10 +1214,16 @@ Local EntityClass::setLavaMovementSpeed(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::LAVA_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LAVA_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLavaMovementSpeed!"); } @@ -1177,10 +1236,16 @@ Local EntityClass::setMaxHealth(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setMaxValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxHealth!"); } @@ -1403,8 +1468,7 @@ Local EntityClass::getBlockFromViewVector(const Arguments& args) { } Block const& bl = actor->getDimensionBlockSource().getBlock(bp); BlockType const& legacy = bl.getBlockType(); - if (bl.isAir() - || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { + if (bl.isAir() || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { return Local(); } return BlockClass::newBlock(bl, bp, actor->getDimensionId()); diff --git a/src/legacy/api/EventAPI.cpp b/src/legacy/api/EventAPI.cpp index f5a0d173..e9e9a926 100644 --- a/src/legacy/api/EventAPI.cpp +++ b/src/legacy/api/EventAPI.cpp @@ -41,6 +41,7 @@ #include "ll/api/service/Bedrock.h" #include "ll/api/thread/ServerThreadExecutor.h" #include "lse/Entry.h" +#include "lse/api/Thread.h" #include "lse/events/BlockEvents.h" #include "lse/events/EntityEvents.h" #include "lse/events/OtherEvents.h" @@ -49,10 +50,13 @@ #include "mc/server/commands/CommandOriginType.h" #include "mc/world/actor/player/Player.h" #include "mc/world/attribute/AttributeInstance.h" +#include "mc/world/attribute/AttributeInstanceConstRef.h" #include "mc/world/item/Item.h" #include "mc/world/item/VanillaItemNames.h" #include "mc/world/level/dimension/Dimension.h" +#include + #ifdef LSE_BACKEND_NODEJS #include "legacy/main/NodeJsHelper.h" #endif @@ -64,6 +68,8 @@ #include #include +using lse::api::thread::checkClientIsServerThread; + //////////////////// Listeners //////////////////// // 监听器表 @@ -101,10 +107,8 @@ LLSEAddEventListener(ScriptEngine* engine, const string& eventName, const Local< } return {listener}; } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Event {} not found!"_tr(eventName)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( - "In Plugin: " + getEngineData(engine)->pluginName - ); + lse::LegacyScriptEngine::getLogger().error("Event {} not found!"_tr(eventName)); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + getEngineData(engine)->pluginName); return std::nullopt; } } @@ -157,8 +161,10 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onJoin: bus.emplaceListener([](PlayerJoinEvent& ev) { IF_LISTENED(EVENT_TYPES::onJoin) { - if (!CallEvent(EVENT_TYPES::onJoin, PlayerClass::newPlayer(&ev.self()))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onJoin, PlayerClass::newPlayer(&ev.self()))) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onJoin); @@ -168,8 +174,10 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPreJoin: bus.emplaceListener([](PlayerConnectEvent& ev) { IF_LISTENED(EVENT_TYPES::onPreJoin) { - if (!CallEvent(EVENT_TYPES::onPreJoin, PlayerClass::newPlayer(&ev.self()))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onPreJoin, PlayerClass::newPlayer(&ev.self()))) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onPreJoin); @@ -179,7 +187,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onLeft: bus.emplaceListener([](PlayerDisconnectEvent& ev) { IF_LISTENED(EVENT_TYPES::onLeft) { - CallEvent(EVENT_TYPES::onLeft, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread() && ll::getGamingStatus() != ll::GamingStatus::Stopping) { + CallEvent(EVENT_TYPES::onLeft, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onLeft); }); @@ -188,12 +198,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onChat: bus.emplaceListener([](PlayerChatEvent& ev) { IF_LISTENED(EVENT_TYPES::onChat) { - if (!CallEvent( - EVENT_TYPES::onChat, - PlayerClass::newPlayer(&ev.self()), - String::newString(ev.message()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onChat, + PlayerClass::newPlayer(&ev.self()), + String::newString(ev.message()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onChat); @@ -207,7 +219,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPlayerSwing: bus.emplaceListener([](PlayerSwingEvent& ev) { IF_LISTENED(EVENT_TYPES::onPlayerSwing) { - CallEvent(EVENT_TYPES::onPlayerSwing, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onPlayerSwing, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onPlayerSwing); }); @@ -216,12 +230,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onAttackEntity: bus.emplaceListener([](PlayerAttackEvent& ev) { IF_LISTENED(EVENT_TYPES::onAttackEntity) { - if (!CallEvent( - EVENT_TYPES::onAttackEntity, - PlayerClass::newPlayer(&ev.self()), - EntityClass::newEntity(&ev.target()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onAttackEntity, + PlayerClass::newPlayer(&ev.self()), + EntityClass::newEntity(&ev.target()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onAttackEntity); @@ -236,12 +252,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPlayerDie: bus.emplaceListener([](ll::event::PlayerDieEvent& ev) { IF_LISTENED(EVENT_TYPES::onPlayerDie) { - Actor* source = ev.self().getDimension().fetchEntity(ev.source().getEntityUniqueID(), false); - CallEvent( - EVENT_TYPES::onPlayerDie, - PlayerClass::newPlayer(&ev.self()), - (source ? EntityClass::newEntity(source) : Local()) - ); // Not cancellable + if (checkClientIsServerThread()) { + Actor* source = ev.self().getDimension().fetchEntity(ev.source().getEntityUniqueID(), false); + CallEvent( + EVENT_TYPES::onPlayerDie, + PlayerClass::newPlayer(&ev.self()), + (source ? EntityClass::newEntity(source) : Local()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onPlayerDie); }); @@ -250,7 +268,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onRespawn: bus.emplaceListener([](ll::event::PlayerRespawnEvent& ev) { IF_LISTENED(EVENT_TYPES::onRespawn) { - CallEvent(EVENT_TYPES::onRespawn, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onRespawn, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onRespawn) }); @@ -263,12 +283,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onDestroyBlock: bus.emplaceListener([](PlayerDestroyBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onDestroyBlock) { - if (!CallEvent( - EVENT_TYPES::onDestroyBlock, - PlayerClass::newPlayer(&ev.self()), - BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onDestroyBlock, + PlayerClass::newPlayer(&ev.self()), + BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onDestroyBlock); @@ -278,36 +300,38 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPlaceBlock: bus.emplaceListener([](PlayerPlacingBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onPlaceBlock) { - BlockPos truePos = ev.pos(); - switch (ev.face()) { - case 0: - --truePos.y; - break; - case 1: - ++truePos.y; - break; - case 2: - --truePos.z; - break; - case 3: - ++truePos.z; - break; - case 4: - --truePos.x; - break; - case 5: - ++truePos.x; - break; - } - auto block = ev.self().getCarriedItem().mBlock; - if (!CallEvent( - EVENT_TYPES::onPlaceBlock, - PlayerClass::newPlayer(&ev.self()), - block ? BlockClass::newBlock(*block, truePos, ev.self().getDimensionId().id) - : BlockClass::newBlock(truePos, ev.self().getDimensionId().id), - Number::newNumber((schar)ev.face()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + BlockPos truePos = ev.pos(); + switch (ev.face()) { + case 0: + --truePos.y; + break; + case 1: + ++truePos.y; + break; + case 2: + --truePos.z; + break; + case 3: + ++truePos.z; + break; + case 4: + --truePos.x; + break; + case 5: + ++truePos.x; + break; + } + auto block = ev.self().getCarriedItem().mBlock; + if (!CallEvent( + EVENT_TYPES::onPlaceBlock, + PlayerClass::newPlayer(&ev.self()), + block ? BlockClass::newBlock(*block, truePos, ev.self().getDimensionId().id) + : BlockClass::newBlock(truePos, ev.self().getDimensionId().id), + Number::newNumber((schar)ev.face()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onPlaceBlock); @@ -317,11 +341,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::afterPlaceBlock: bus.emplaceListener([](PlayerPlacedBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::afterPlaceBlock) { - CallEvent( - EVENT_TYPES::afterPlaceBlock, - PlayerClass::newPlayer(&ev.self()), - BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::afterPlaceBlock, + PlayerClass::newPlayer(&ev.self()), + BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::afterPlaceBlock); }); @@ -329,7 +355,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onJump: bus.emplaceListener([](PlayerJumpEvent& ev) { IF_LISTENED(EVENT_TYPES::onJump) { - CallEvent(EVENT_TYPES::onJump, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onJump, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onJump); }); @@ -342,13 +370,15 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onTakeItem: bus.emplaceListener([](PlayerPickUpItemEvent& ev) { IF_LISTENED(EVENT_TYPES::onTakeItem) { - if (!CallEvent( - EVENT_TYPES::onTakeItem, - PlayerClass::newPlayer(&ev.self()), - EntityClass::newEntity(&ev.itemActor()), - ItemClass::newItem(&ev.itemActor().item()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onTakeItem, + PlayerClass::newPlayer(&ev.self()), + EntityClass::newEntity(&ev.itemActor()), + ItemClass::newItem(&ev.itemActor().item()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onTakeItem); @@ -370,12 +400,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onUseItem: bus.emplaceListener([](PlayerUseItemEvent& ev) { IF_LISTENED(EVENT_TYPES::onUseItem) { - if (!CallEvent( - EVENT_TYPES::onUseItem, - PlayerClass::newPlayer(&ev.self()), - ItemClass::newItem(&ev.item()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseItem, + PlayerClass::newPlayer(&ev.self()), + ItemClass::newItem(&ev.item()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onUseItem); @@ -385,15 +417,18 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onUseItemOn: bus.emplaceListener([](PlayerInteractBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onUseItemOn) { - if (!CallEvent( - EVENT_TYPES::onUseItemOn, - PlayerClass::newPlayer(&ev.self()), - ItemClass::newItem(&ev.item()), - BlockClass::newBlock(ev.block(), ev.blockPos(), ev.self().getDimensionId().id), - Number::newNumber((schar)ev.face()), - FloatPos::newPos(ev.clickPos(), ev.self().getDimensionId().id) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseItemOn, + PlayerClass::newPlayer(&ev.self()), + ItemClass::newItem(&ev.item()), + ev.block() ? BlockClass::newBlock(ev.block(), ev.blockPos(), ev.self().getDimensionId().id) + : BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id), + Number::newNumber((schar)ev.face()), + FloatPos::newPos(ev.clickPos(), ev.self().getDimensionId().id) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onUseItemOn); @@ -418,21 +453,25 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onChangeSprinting: bus.emplaceListener([](PlayerSprintingEvent& ev) { IF_LISTENED(EVENT_TYPES::onChangeSprinting) { - CallEvent( - EVENT_TYPES::onChangeSprinting, - PlayerClass::newPlayer(&ev.self()), - Boolean::newBoolean(true) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onChangeSprinting, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(true) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onChangeSprinting); }); bus.emplaceListener([](PlayerSprintedEvent& ev) { IF_LISTENED(EVENT_TYPES::onChangeSprinting) { - CallEvent( - EVENT_TYPES::onChangeSprinting, - PlayerClass::newPlayer(&ev.self()), - Boolean::newBoolean(false) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onChangeSprinting, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(false) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onChangeSprinting); }); @@ -441,16 +480,28 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onSneak: bus.emplaceListener([](PlayerSneakingEvent& ev) { IF_LISTENED(EVENT_TYPES::onSneak) { - if (!CallEvent(EVENT_TYPES::onSneak, PlayerClass::newPlayer(&ev.self()), Boolean::newBoolean(true))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSneak, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(true) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onSneak); }); bus.emplaceListener([](PlayerSneakedEvent& ev) { IF_LISTENED(EVENT_TYPES::onSneak) { - if (!CallEvent(EVENT_TYPES::onSneak, PlayerClass::newPlayer(&ev.self()), Boolean::newBoolean(false))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSneak, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(false) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onSneak); @@ -468,16 +519,18 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onEat: bus.emplaceListener([](PlayerUseItemEvent& ev) { IF_LISTENED(EVENT_TYPES::onEat) { - if (ev.item().getItem()->isFood() || ev.item().isPotionItem() - || ev.item().getTypeName() == VanillaItemNames::MilkBucket().getString()) { - auto attribute = ev.self().getAttribute(Player::HUNGER()); - if (attribute.mCurrentMaxValue > attribute.mCurrentValue) { - if (!CallEvent( - EVENT_TYPES::onEat, - PlayerClass::newPlayer(&ev.self()), - ItemClass::newItem(&ev.item()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (ev.item().getItem()->isFood() || ev.item().isPotionItem() + || ev.item().getTypeName() == VanillaItemNames::MilkBucket().getString()) { + auto attribute = ev.self().getAttribute(Player::HUNGER()); + if (attribute.mPtr->mCurrentMaxValue > attribute.mPtr->mCurrentValue) { + if (!CallEvent( + EVENT_TYPES::onEat, + PlayerClass::newPlayer(&ev.self()), + ItemClass::newItem(&ev.item()) + )) { + ev.cancel(); + } } } } @@ -550,20 +603,22 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onMobDie: bus.emplaceListener([](MobDieEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobDie) { - Actor* source = nullptr; - if (ev.source().isEntitySource()) { - source = ll::service::getLevel()->fetchEntity(ev.source().getDamagingEntityUniqueID(), false); - if (source) { - if (ev.source().isChildEntitySource()) source = source->getOwner(); + if (checkClientIsServerThread()) { + Actor* source = nullptr; + if (ev.source().isEntitySource()) { + source = ll::service::getLevel()->fetchEntity(ev.source().getDamagingEntityUniqueID(), false); + if (source) { + if (ev.source().isChildEntitySource()) source = source->getOwner(); + } } - } - CallEvent( - EVENT_TYPES::onMobDie, - EntityClass::newEntity(&ev.self()), - (source ? EntityClass::newEntity(source) : Local()), - Number::newNumber((int)ev.source().mCause) - ); // Not cancellable + CallEvent( + EVENT_TYPES::onMobDie, + EntityClass::newEntity(&ev.self()), + (source ? EntityClass::newEntity(source) : Local()), + Number::newNumber((int)ev.source().mCause) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onMobDie); }); @@ -600,12 +655,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onBlockInteracted: bus.emplaceListener([](PlayerInteractBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onBlockInteracted) { - if (!CallEvent( - EVENT_TYPES::onBlockInteracted, - PlayerClass::newPlayer(&ev.self()), - BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onBlockInteracted, + PlayerClass::newPlayer(&ev.self()), + BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onBlockInteracted); @@ -633,11 +690,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onFireSpread: bus.emplaceListener([](FireSpreadEvent& ev) { IF_LISTENED(EVENT_TYPES::onFireSpread) { - if (!CallEvent( - EVENT_TYPES::onFireSpread, - IntPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onFireSpread, + IntPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onFireSpread); @@ -647,11 +706,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onBlockChanged: bus.emplaceListener([](BlockChangedEvent& ev) { IF_LISTENED(EVENT_TYPES::onBlockChanged) { - CallEvent( - EVENT_TYPES::onBlockChanged, - BlockClass::newBlock(ev.previousBlock(), ev.pos(), ev.blockSource()), - BlockClass::newBlock(ev.newBlock(), ev.pos(), ev.blockSource()) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onBlockChanged, + BlockClass::newBlock(ev.previousBlock(), ev.pos(), ev.blockSource()), + BlockClass::newBlock(ev.newBlock(), ev.pos(), ev.blockSource()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onBlockChanged); }); @@ -662,16 +723,18 @@ void EnableEventListener(int eventId) { break; case EVENT_TYPES::onMobSpawn: - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "Event 'onMobSpawn' is outdated, please use 'onMobTrySpawn' instead." ); bus.emplaceListener([](SpawningMobEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobSpawn) { - CallEvent( - EVENT_TYPES::onMobSpawn, - String::newString(ev.identifier().mFullName), - FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onMobSpawn, + String::newString(ev.identifier().mFullName), + FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onMobSpawn); }); @@ -680,12 +743,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onMobTrySpawn: bus.emplaceListener([](SpawningMobEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobTrySpawn) { - if (!CallEvent( - EVENT_TYPES::onMobTrySpawn, - String::newString(ev.identifier().mFullName), - FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onMobTrySpawn, + String::newString(ev.identifier().mFullName), + FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onMobTrySpawn); @@ -695,11 +760,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onMobSpawned: bus.emplaceListener([](SpawnedMobEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobSpawned) { - CallEvent( - EVENT_TYPES::onMobSpawned, - EntityClass::newEntity(ev.mob().has_value() ? ev.mob().as_ptr() : nullptr), - FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onMobSpawned, + EntityClass::newEntity(ev.mob().has_value() ? ev.mob().as_ptr() : nullptr), + FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onMobSpawned); }); @@ -708,12 +775,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onExperienceAdd: bus.emplaceListener([](PlayerAddExperienceEvent& ev) { IF_LISTENED(EVENT_TYPES::onExperienceAdd) { - if (!CallEvent( - EVENT_TYPES::onExperienceAdd, - PlayerClass::newPlayer(&ev.self()), - Number::newNumber(ev.experience()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onExperienceAdd, + PlayerClass::newPlayer(&ev.self()), + Number::newNumber(ev.experience()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onExperienceAdd); @@ -897,10 +966,8 @@ void InitBasicEventListeners() { } } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( - "Error occurred in Engine Message Loop!" - ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Error occurred in Engine Message Loop!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } #endif diff --git a/src/legacy/api/EventAPI.h b/src/legacy/api/EventAPI.h index b2354424..6fd65f96 100644 --- a/src/legacy/api/EventAPI.h +++ b/src/legacy/api/EventAPI.h @@ -176,17 +176,17 @@ void CallEventImpl(EventListener& listener, bool& returnValue, EVENT_TYPES type, returnValue = false; } } catch (const Exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("CallEvent Callback Failed!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("CallEvent Callback Failed!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("CallEvent Callback Failed!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("CallEvent Callback Failed!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } @@ -205,17 +205,17 @@ void FakeCallEventImpl(EventListener& listener, ScriptEngine* engine, EVENT_TYPE try { listener.func.get().call({}, args...); } catch (const Exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("FakeCallEvent Callback Failed!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("FakeCallEvent Callback Failed!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("FakeCallEvent Callback Failed!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("FakeCallEvent Callback Failed!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } @@ -228,8 +228,8 @@ void FakeCallEventImpl(EventListener& listener, ScriptEngine* engine, EVENT_TYPE try #define IF_LISTENED_END(TYPE) \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Event Callback Failed!"); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(TYPE)); \ + lse::LegacyScriptEngine::getLogger().error("Event Callback Failed!"); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(TYPE)); \ } \ } diff --git a/src/legacy/api/ItemAPI.cpp b/src/legacy/api/ItemAPI.cpp index 8a328895..0f52976e 100644 --- a/src/legacy/api/ItemAPI.cpp +++ b/src/legacy/api/ItemAPI.cpp @@ -7,6 +7,7 @@ #include "api/NbtAPI.h" #include "ll/api/service/Bedrock.h" #include "lse/api/helper/ItemHelper.h" +#include "mc/common/SharedPtr.h" #include "mc/safety/RedactableString.h" #include "mc/world/actor/item/ItemActor.h" #include "mc/world/item/Item.h" @@ -469,7 +470,9 @@ Local McClass::newItem(const Arguments& args) { std::string type = args[0].asString().toString(); int cnt = args[1].asNumber().toInt32(); - return ItemClass::newItem(std::make_unique(type, cnt, 0, nullptr)); + if (auto itemPtr = ll::service::getLevel()->getItemRegistry().getItem(HashedString(type)).lock()) { + return ItemClass::newItem(std::make_unique(*itemPtr)); + } } else { LOG_TOO_FEW_ARGS(__FUNCTION__); return Local(); diff --git a/src/legacy/api/NbtAPI.cpp b/src/legacy/api/NbtAPI.cpp index fcb786fc..08067af7 100644 --- a/src/legacy/api/NbtAPI.cpp +++ b/src/legacy/api/NbtAPI.cpp @@ -1335,7 +1335,7 @@ Local NbtListClass::getTag(const Arguments& args) { } Local res; - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + // lse::LegacyScriptEngine::getLogger().info( // "getListTag Type {}", // magic_enum::enum_name(getPtr()->at(index)->getId()) // ); @@ -1739,7 +1739,7 @@ Local NbtCompoundClass::getTag(const Arguments& args) { auto key = args[0].asString().toString(); Local res; - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + // lse::LegacyScriptEngine::getLogger().info( // "getCompoundTag Type {}", // magic_enum::enum_name(getPtr()->at(key).getId()) // ); diff --git a/src/legacy/api/NetworkAPI.cpp b/src/legacy/api/NetworkAPI.cpp index de8e6755..747422c5 100644 --- a/src/legacy/api/NetworkAPI.cpp +++ b/src/legacy/api/NetworkAPI.cpp @@ -23,13 +23,13 @@ using namespace ll::coro; #define CATCH_CALLBACK(LOG) \ catch (const Exception& e) { \ EngineScope enter(engine); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ return; \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ EngineScope enter(engine); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__); \ return; \ @@ -38,13 +38,13 @@ using namespace ll::coro; #define CATCH_CALLBACK_IN_CORO(LOG) \ catch (const Exception& e) { \ EngineScope enterCoro(engine); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ co_return; \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ EngineScope enterCoro(engine); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__); \ co_return; \ @@ -361,11 +361,11 @@ Local WSClientClass::connectAsync(const Arguments& args) { if (callback.isEmpty()) return; NewTimeout(callback.get(), {Boolean::newBoolean(result)}, 0); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "WSClientClass::connectAsync Failed!" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Plugin: " + pluginName); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + pluginName); } }).detach(); return Boolean::newBoolean(true); @@ -771,7 +771,7 @@ Local HttpServerClass::listen(const Arguments& args) { svr->stop(); svr->listen(addr, port); } catch (...) { - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } }).detach(); return this->getScriptObject(); // return self diff --git a/src/legacy/api/PlayerAPI.cpp b/src/legacy/api/PlayerAPI.cpp index 530e4ebd..56f4c68b 100644 --- a/src/legacy/api/PlayerAPI.cpp +++ b/src/legacy/api/PlayerAPI.cpp @@ -22,20 +22,18 @@ #include "ll/api/service/Bedrock.h" #include "ll/api/service/GamingStatus.h" #include "ll/api/service/PlayerInfo.h" -#include "ll/api/service/ServerInfo.h" #include "ll/api/thread/ServerThreadExecutor.h" #include "lse/api/MoreGlobal.h" #include "lse/api/NetworkPacket.h" #include "lse/api/helper/AttributeHelper.h" -#include "lse/api/helper/BlockHelper.h" #include "lse/api/helper/PlayerHelper.h" #include "lse/api/helper/ScoreboardHelper.h" #include "main/EconomicSystem.h" #include "main/SafeGuardRecord.h" -#include "mc/certificates/WebToken.h" #include "mc/deps/core/math/Vec2.h" #include "mc/deps/core/utility/MCRESULT.h" #include "mc/entity/components/ActorRotationComponent.h" +#include "mc/entity/components/AttributesComponent.h" #include "mc/entity/components/InsideBlockComponent.h" #include "mc/entity/components/IsOnHotBlockFlagComponent.h" #include "mc/entity/components/TagsComponent.h" @@ -47,7 +45,6 @@ #include "mc/network/ConnectionRequest.h" #include "mc/network/MinecraftPacketIds.h" #include "mc/network/MinecraftPackets.h" -#include "mc/network/NetEventCallback.h" #include "mc/network/ServerNetworkHandler.h" #include "mc/network/packet/BossEventPacket.h" #include "mc/network/packet/ClientboundCloseFormPacket.h" @@ -83,10 +80,10 @@ #include "mc/world/actor/player/PermissionsHandler.h" #include "mc/world/actor/player/Player.h" #include "mc/world/actor/player/PlayerInventory.h" -#include "mc/world/actor/provider/ActorAttribute.h" #include "mc/world/actor/provider/ActorEquipment.h" #include "mc/world/actor/provider/SynchedActorDataAccess.h" -#include "mc/world/attribute/AttributeInstance.h" +#include "mc/world/attribute/Attribute.h" +#include "mc/world/attribute/AttributeInstanceConstRef.h" #include "mc/world/attribute/SharedAttributes.h" #include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" @@ -102,7 +99,6 @@ #include "mc/world/phys/HitResult.h" #include "mc/world/scores/IdentityDefinition.h" #include "mc/world/scores/Objective.h" -#include "mc/world/scores/ObjectiveCriteria.h" #include "mc/world/scores/PlayerScoreSetFunction.h" #include "mc/world/scores/PlayerScoreboardId.h" #include "mc/world/scores/ScoreInfo.h" @@ -110,6 +106,9 @@ #include "mc/world/scores/ScoreboardId.h" #include "mc/world/scores/ScoreboardOperationResult.h" +#include +#include + SetScorePacket::SetScorePacket() = default; //////////////////// Class Definition //////////////////// @@ -353,8 +352,8 @@ Local McClass::getPlayerNbt(const Arguments& args) { CHECK_ARGS_COUNT(args, 1); CHECK_ARG_TYPE(args[0], ValueKind::kString); try { - auto uuid = mce::UUID::fromString(args[0].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto uuid = mce::UUID::fromString(args[0].asString().toString()); + auto db = ll::service::getDBStorage(); if (db && db->hasKey("player_" + uuid.asString(), DBHelpers::Category::Player)) { std::unique_ptr playerTag = db->getCompoundTag("player_" + uuid.asString(), DBHelpers::Category::Player); @@ -380,7 +379,7 @@ Local McClass::setPlayerNbt(const Arguments& args) { if (player && tag) { player->load(*tag, MoreGlobal::defaultDataLoadHelper()); } else if (tag) { - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (db && db->hasKey("player_" + uuid.asString(), DBHelpers::Category::Player)) { std::unique_ptr playerTag = db->getCompoundTag("player_" + uuid.asString(), DBHelpers::Category::Player); @@ -421,7 +420,7 @@ Local McClass::setPlayerNbtTags(const Arguments& args) { } player->load(loadedTag, MoreGlobal::defaultDataLoadHelper()); } else if (tag) { - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (db && db->hasKey("player_" + uuid.asString(), DBHelpers::Category::Player)) { std::unique_ptr playerTag = db->getCompoundTag("player_" + uuid.asString(), DBHelpers::Category::Player); @@ -492,7 +491,7 @@ Local McClass::getPlayerScore(const Arguments& args) { auto obj = args[1].asString().toString(); Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(obj); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Number::newNumber(0); } @@ -527,7 +526,7 @@ Local McClass::setPlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -565,7 +564,7 @@ Local McClass::addPlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -603,7 +602,7 @@ Local McClass::reducePlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -645,7 +644,7 @@ Local McClass::deletePlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -747,9 +746,8 @@ Local McClass::broadcast(const Arguments& args) { int newType = args[1].asNumber().toInt32(); if (newType >= 0 && newType <= 11) type = (TextPacketType)newType; } - TextPacket pkt = TextPacket(); - pkt.mType = type; - pkt.mMessage = args[0].asString().toString(); + TextPacket pkt; + pkt.mBody = TextPacket::MessageOnly(type, args[0].asString().toString()); pkt.sendToClients(); return Boolean::newBoolean(true); } @@ -830,7 +828,7 @@ Local PlayerClass::getXuid() { try { xuid = player->getXuid(); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Fail in getXuid!"); + lse::LegacyScriptEngine::getLogger().debug("Fail in getXuid!"); xuid = ll::service::PlayerInfo::getInstance().fromName(player->getRealName())->xuid; } return String::newString(xuid); @@ -847,7 +845,7 @@ Local PlayerClass::getUuid() { try { uuid = player->getUuid().asString(); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Fail in getUuid!"); + lse::LegacyScriptEngine::getLogger().debug("Fail in getUuid!"); uuid = ll::service::PlayerInfo::getInstance().fromName(player->getRealName())->uuid.asString(); } return String::newString(uuid); @@ -1040,7 +1038,7 @@ Local PlayerClass::getHealth() { Player* player = get(); if (!player) return Local(); - return Number::newNumber(ActorAttribute::getHealth(player->getEntityContext())); + return Number::newNumber(player->getHealth()); } CATCH("Fail in GetHealth!") } @@ -1224,7 +1222,7 @@ Local PlayerClass::isHurt() { return Local(); } - int health = ActorAttribute::getHealth(player->getEntityContext()); + int health = player->getHealth(); if (health > 0 && health < player->getMaxHealth()) { return Boolean::newBoolean(true); } @@ -1266,8 +1264,10 @@ Local PlayerClass::isHungry() { return Local(); } - auto attribute = player->getAttribute(Player::HUNGER()); - return Boolean::newBoolean(attribute.mCurrentMaxValue > attribute.mCurrentValue); + if (auto attribute = player->getAttribute(Player::HUNGER()).mPtr) { + return Boolean::newBoolean(attribute->mCurrentMaxValue > attribute->mCurrentValue); + } + return Boolean::newBoolean(false); } CATCH("Fail in isHungry!") } @@ -1592,7 +1592,7 @@ Local PlayerClass::runcmd(const Arguments& args) { if (!player) return Local(); CommandContext context = CommandContext( args[0].asString().toString(), - std::make_unique(*get()), + std::make_unique(ll::service::getLevel(), player->getOrCreateUniqueID()), CommandVersion::CurrentVersion() ); ll::service::getMinecraft()->mCommands->executeCommand(context, false); @@ -1632,8 +1632,7 @@ Local PlayerClass::tell(const Arguments& args) { } TextPacket pkt = TextPacket(); - pkt.mType = type; - pkt.mMessage.assign(args[0].asString().toString()); + pkt.mBody = TextPacket::MessageOnly(type, args[0].asString().toString()); player->sendNetworkPacket(pkt); return Boolean::newBoolean(true); } @@ -1715,8 +1714,10 @@ Local PlayerClass::talkTo(const Arguments& args) { Player* player = get(); if (!player) return Local(); - TextPacket pkt = - TextPacket::createWhisper(player->getRealName(), args[0].asString().toString(), {}, player->getXuid(), {}); + TextPacket pkt; + pkt.mXuid = player->getXuid(); + pkt.mBody = + TextPacket::AuthorAndMessage(TextPacketType::Whisper, player->getRealName(), args[0].asString().toString()); target->sendNetworkPacket(pkt); return Boolean::newBoolean(true); } @@ -1894,7 +1895,7 @@ Local PlayerClass::getLevel(const Arguments&) { Player* player = get(); if (!player) return Local(); - return Number::newNumber(player->getAttribute(Player::LEVEL()).mCurrentValue); + return Number::newNumber(player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue); } CATCH("Fail in getLevel!") } @@ -1907,7 +1908,9 @@ Local PlayerClass::setLevel(const Arguments& args) { Player* player = get(); if (!player) return Local(); - player->addLevels(args[0].asNumber().toInt32() - (int)player->getAttribute(Player::LEVEL()).mCurrentValue); + player->addLevels( + args[0].asNumber().toInt32() - (int)player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue + ); return Boolean::newBoolean(true); } CATCH("Fail in setLevel!"); @@ -1962,30 +1965,39 @@ Local PlayerClass::reduceExperience(const Arguments& args) { return Local(); } - float exp = args[0].asNumber().toFloat(); - auto attribute = player->getMutableAttribute(Player::EXPERIENCE()); - auto instance = attribute.mInstance; - if (!instance) { - return Boolean::newBoolean(false); - } - int neededExp = player->getXpNeededForNextLevel(); - int currentExp = static_cast(instance->mCurrentValue * neededExp); - if (exp <= currentExp) { - AttributeHelper::setCurrentValue(attribute, static_cast(currentExp - exp) / neededExp); - return Boolean::newBoolean(true); - } - AttributeHelper::setCurrentValue(attribute, 0.0f); - size_t needExp = exp - currentExp; - int level = player->getAttribute(Player::LEVEL()).mCurrentValue; - while (level > 0) { - player->addLevels(-1); - int levelXp = player->getXpNeededForNextLevel(); - if (needExp < levelXp) { - AttributeHelper::setCurrentValue(attribute, static_cast(levelXp - needExp) / levelXp); + float exp = args[0].asNumber().toFloat(); + if (auto component = player->getEntityContext().tryGetComponent()) { + auto instance = component->mAttributes->getMutableInstance(Player::EXPERIENCE().mIDValue).mPtr; + if (!instance) { + return Boolean::newBoolean(false); + } + int neededExp = player->getXpNeededForNextLevel(); + int currentExp = static_cast(instance->mCurrentValue * neededExp); + if (exp <= currentExp) { + AttributeHelper::setCurrentValue( + component->mAttributes, + Player::EXPERIENCE(), + static_cast(currentExp - exp) / neededExp + ); return Boolean::newBoolean(true); } - needExp -= levelXp; - level = player->getAttribute(Player::LEVEL()).mCurrentValue; + AttributeHelper::setCurrentValue(component->mAttributes, Player::EXPERIENCE(), 0.0f); + size_t needExp = exp - currentExp; + int level = player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; + while (level > 0) { + player->addLevels(-1); + int levelXp = player->getXpNeededForNextLevel(); + if (needExp < levelXp) { + AttributeHelper::setCurrentValue( + component->mAttributes, + Player::EXPERIENCE(), + static_cast(levelXp - needExp) / levelXp + ); + return Boolean::newBoolean(true); + } + needExp -= levelXp; + level = player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; + } } return Boolean::newBoolean(false); } @@ -2028,7 +2040,7 @@ Local PlayerClass::getTotalExperience(const Arguments&) { } int startLevel = 0; - int endLevel = (int)player->getAttribute(Player::LEVEL()).mCurrentValue; + int endLevel = (int)player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; unsigned int totalXp = 0; for (int level = startLevel; level < endLevel; ++level) { @@ -2585,10 +2597,8 @@ Local PlayerClass::sendCustomForm(const Arguments& args) { return Number::newNumber(3); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( - "Fail to parse Json string in sendCustomForm!" - ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail to parse Json string in sendCustomForm!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return {}; } CATCH("Fail in sendCustomForm!"); @@ -2750,10 +2760,16 @@ Local PlayerClass::setHealth(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setHealth!"); } @@ -2766,10 +2782,16 @@ Local PlayerClass::setMaxHealth(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setMaxValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxHealth!"); } @@ -2782,10 +2804,16 @@ Local PlayerClass::setAbsorption(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::ABSORPTION()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ABSORPTION(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAbsorptionAttribute!"); } @@ -2798,10 +2826,16 @@ Local PlayerClass::setAttackDamage(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAttackDamage!"); } @@ -2814,10 +2848,16 @@ Local PlayerClass::setMaxAttackDamage(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setMaxValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxAttackDamage!"); } @@ -2830,10 +2870,16 @@ Local PlayerClass::setFollowRange(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::FOLLOW_RANGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::FOLLOW_RANGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setFollowRange!"); } @@ -2846,10 +2892,16 @@ Local PlayerClass::setKnockbackResistance(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::KNOCKBACK_RESISTANCE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::KNOCKBACK_RESISTANCE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setKnockbackResistance!"); } @@ -2862,10 +2914,16 @@ Local PlayerClass::setLuck(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::LUCK()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LUCK(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLuck!"); } @@ -2878,9 +2936,15 @@ Local PlayerClass::setMovementSpeed(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } return Boolean::newBoolean(false); } CATCH("Fail in setMovementSpeed!"); @@ -2894,10 +2958,16 @@ Local PlayerClass::setUnderwaterMovementSpeed(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::UNDERWATER_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::UNDERWATER_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setUnderwaterMovementSpeed!"); } @@ -2910,10 +2980,16 @@ Local PlayerClass::setLavaMovementSpeed(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::LAVA_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LAVA_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLavaMovementSpeed!"); } @@ -2926,10 +3002,12 @@ Local PlayerClass::setHungry(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(Player::HUNGER()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue(component->mAttributes, Player::HUNGER(), args[0].asNumber().toFloat()) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setHungry!"); } @@ -3279,8 +3357,7 @@ Local PlayerClass::getBlockFromViewVector(const Arguments& args) { Block const& bl = player->getDimensionBlockSource().getBlock(bp); BlockType const& legacy = bl.getBlockType(); // isEmpty() - if (bl.isAir() - || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { + if (bl.isAir() || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { return Local(); } return BlockClass::newBlock(bl, bp, player->getDimensionBlockSource()); diff --git a/src/legacy/api/RemoteCallAPI.cpp b/src/legacy/api/RemoteCallAPI.cpp index b8894e27..625c8476 100644 --- a/src/legacy/api/RemoteCallAPI.cpp +++ b/src/legacy/api/RemoteCallAPI.cpp @@ -177,12 +177,12 @@ Local extract(RemoteCall::ValueType&& val) { Local MakeRemoteCall(const string& nameSpace, const string& funcName, const Arguments& args) { auto& func = RemoteCall::importFunc(nameSpace, funcName); if (!func) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to import! Function [{}::{}] has not been exported!", nameSpace, funcName ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "In plugin <{}>", getEngineOwnData()->pluginName ); @@ -216,7 +216,7 @@ bool LLSEExportFunc( try { auto iter = getEngineData(engine)->exportFuncs.find(identifier); if (iter == getEngineData(engine)->exportFuncs.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug(""); + lse::LegacyScriptEngine::getLogger().debug(""); return ""; } auto scriptCallback = iter->second.callback.get(); diff --git a/src/legacy/api/ScoreboardAPI.cpp b/src/legacy/api/ScoreboardAPI.cpp index d7ef451a..da8d88c8 100644 --- a/src/legacy/api/ScoreboardAPI.cpp +++ b/src/legacy/api/ScoreboardAPI.cpp @@ -4,7 +4,6 @@ #include "api/McAPI.h" #include "api/PlayerAPI.h" #include "ll/api/service/Bedrock.h" -#include "mc/world/actor/player/Player.h" #include "mc/world/scores/DisplayObjective.h" #include "mc/world/scores/Objective.h" #include "mc/world/scores/ScoreInfo.h" diff --git a/src/legacy/api/SimulatedPlayerAPI.cpp b/src/legacy/api/SimulatedPlayerAPI.cpp index 1d1ddb60..b0e6b91c 100644 --- a/src/legacy/api/SimulatedPlayerAPI.cpp +++ b/src/legacy/api/SimulatedPlayerAPI.cpp @@ -9,15 +9,11 @@ #include "engine/GlobalShareData.h" #include "ll/api/service/Bedrock.h" #include "lse/api/helper/SimulatedPlayerHelper.h" -#include "mc/nbt/CompoundTag.h" #include "mc/network/ServerNetworkHandler.h" #include "mc/scripting/modules/gametest/ScriptNavigationResult.h" #include "mc/server/SimulatedPlayer.h" #include "mc/server/sim/LookDuration.h" -#include "mc/world/Container.h" -#include "mc/world/Minecraft.h" #include "mc/world/actor/Actor.h" -#include "mc/world/level/BlockSource.h" #include "mc/world/level/dimension/Dimension.h" #include @@ -91,7 +87,7 @@ Local PlayerClass::simulateAttack(const Arguments& args) { if (args.size() == 0) return Boolean::newBoolean(sp->simulateAttack()); if (auto actor = EntityClass::tryExtractActor(args[0])) { - sp->_trySwing(); + sp->swing(ActorSwingSource::Attack); return Boolean::newBoolean(sp->attack(*actor, SharedTypes::Legacy::ActorDamageCause::EntityAttack)); } @@ -389,9 +385,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getBlockPos(), lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( - "Can't simulate look at other dimension!" - ); + lse::LegacyScriptEngine::getLogger().debug("Can't simulate look at other dimension!"); return Boolean::newBoolean(false); } else if (IsInstanceOf(args[0])) { auto pos = FloatPos::extractPos(args[0]); @@ -400,9 +394,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getVec3(), (sim::LookDuration)lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( - "Can't simulate look at other dimension!" - ); + lse::LegacyScriptEngine::getLogger().debug("Can't simulate look at other dimension!"); return Boolean::newBoolean(false); } else if (IsInstanceOf(args[0])) { auto block = EngineScope::currentEngine()->getNativeInstance(args[0]); @@ -412,9 +404,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getBlockPos(), (sim::LookDuration)lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( - "Can't simulate look at other dimension!" - ); + lse::LegacyScriptEngine::getLogger().debug("Can't simulate look at other dimension!"); return Boolean::newBoolean(false); } else if (auto actor = EntityClass::tryExtractActor(args[0])) { sp->simulateLookAt(*actor, (sim::LookDuration)lookDuration); diff --git a/src/legacy/api/SystemAPI.cpp b/src/legacy/api/SystemAPI.cpp index 3b35cca9..8bb8942b 100644 --- a/src/legacy/api/SystemAPI.cpp +++ b/src/legacy/api/SystemAPI.cpp @@ -84,8 +84,8 @@ bool NewProcess( try { if (callback) callback(static_cast(exitCode), std::move(strOutput)); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("NewProcess Callback Failed!"); - ll::utils::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("NewProcess Callback Failed!"); + ll::utils::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } }).detach(); diff --git a/src/legacy/engine/EngineOwnData.h b/src/legacy/engine/EngineOwnData.h index 8ab62e10..95090c2c 100644 --- a/src/legacy/engine/EngineOwnData.h +++ b/src/legacy/engine/EngineOwnData.h @@ -1,6 +1,6 @@ #pragma once #include "legacy/main/Global.h" -#include "lse/Plugin.h" +#include "lse/ScriptPlugin.h" #include "utils/UsingScriptX.h" #include @@ -34,7 +34,7 @@ struct EngineOwnData { ll::i18n::I18n i18n; std::string defaultLocaleName; - std::shared_ptr plugin; + std::shared_ptr plugin; // Use standalone logger in EngineOwnData instead of plugin.getLogger() for allowing modify logger title. std::shared_ptr logger; diff --git a/src/legacy/engine/GlobalShareData.cpp b/src/legacy/engine/GlobalShareData.cpp index 81809f06..cb8d08f0 100644 --- a/src/legacy/engine/GlobalShareData.cpp +++ b/src/legacy/engine/GlobalShareData.cpp @@ -23,14 +23,14 @@ void InitGlobalShareData() { (LLSE_GLOBAL_DATA_NAME + std::to_wstring(GetCurrentProcessId())).c_str() ); if (hGlobalData == NULL) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Failed to initialize file mapping"_tr()); + lse::LegacyScriptEngine::getLogger().error("Failed to initialize file mapping"_tr()); localShareData->isFirstInstance = true; return; } LPVOID address = MapViewOfFile(hGlobalData, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (address == NULL) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Failed to initialize map file"_tr()); + lse::LegacyScriptEngine::getLogger().error("Failed to initialize map file"_tr()); localShareData->isFirstInstance = true; return; } diff --git a/src/legacy/engine/MessageSystem.cpp b/src/legacy/engine/MessageSystem.cpp index fc43faf3..2b4194a3 100644 --- a/src/legacy/engine/MessageSystem.cpp +++ b/src/legacy/engine/MessageSystem.cpp @@ -105,18 +105,18 @@ ModuleMessageResult ModuleMessage::broadcastLocal(MessageType type, string data, engineList.push_back(engine); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } return ModuleMessageResult(msgId, engineList); @@ -136,18 +136,18 @@ ModuleMessageResult ModuleMessage::broadcastGlobal(MessageType type, string data engineList.push_back(engine); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } return ModuleMessageResult(msgId, engineList); @@ -168,18 +168,18 @@ ModuleMessageResult ModuleMessage::broadcastTo(std::string toModuleType, Message engineList.push_back(engine); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } } @@ -199,18 +199,18 @@ ModuleMessage::sendTo(std::shared_ptr engine, MessageType type, st return ModuleMessageResult(msgId, {engine}); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } return ModuleMessageResult(msgId, {}); } @@ -230,18 +230,18 @@ ModuleMessage::sendToRandom(std::string toModuleType, MessageType type, std::str return ModuleMessageResult(msgId, {engine}); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } } @@ -260,17 +260,17 @@ bool ModuleMessage::sendResult(MessageType typ, std::string dat, int64_t delay) return true; } catch (const Exception& e) { EngineScope scope(engine); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } return false; } @@ -339,23 +339,23 @@ void MessageSystemLoopOnce() { } } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error occurred in Engine Message Loop!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error occurred in Engine Message Loop!" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } } // messageLoopLock.unlock(); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Engine-{} Message Loop.", LLSE_BACKEND_TYPE); + // lse::LegacyScriptEngine::getLogger().debug("Engine-{} Message Loop.", LLSE_BACKEND_TYPE); } void InitMessageSystem() { diff --git a/src/legacy/engine/RemoteCall.cpp b/src/legacy/engine/RemoteCall.cpp index 0ccb4069..b69a16c1 100644 --- a/src/legacy/engine/RemoteCall.cpp +++ b/src/legacy/engine/RemoteCall.cpp @@ -19,8 +19,8 @@ void inline StringTrim(string& str) { } void RemoteSyncCallRequest(ModuleMessage& msg) { - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Remote call request received."); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Current Module:{}", LLSE_BACKEND_TYPE); + // lse::LegacyScriptEngine::getLogger().debug("*** Remote call request received."); + // lse::LegacyScriptEngine::getLogger().debug("*** Current Module:{}", LLSE_BACKEND_TYPE); std::istringstream sin(msg.getData()); @@ -42,52 +42,52 @@ void RemoteSyncCallRequest(ModuleMessage& msg) { argsVector.push_back(JsonToValue(arg)); } - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Before remote call execute"); + // lse::LegacyScriptEngine::getLogger().debug("*** Before remote call execute"); Local result = funcData->func.get().call({}, argsVector); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** After remote call execute"); + // lse::LegacyScriptEngine::getLogger().debug("*** After remote call execute"); // Feedback - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Before remote call result return"); + // lse::LegacyScriptEngine::getLogger().debug("*** Before remote call result return"); if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, ValueToJson(result))) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** After remote call result return"); + // lse::LegacyScriptEngine::getLogger().debug("*** After remote call result return"); } catch (const Exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in remote engine!"); + lse::LegacyScriptEngine::getLogger().error("Error occurred in remote engine!"); if (engine) { EngineScope enter(engine); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error( "[Error] In Plugin: " + getEngineOwnData()->pluginName ); } // Feedback if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, "[null]")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } } catch (const std::out_of_range&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( string("Fail to import! Function [") + funcName + "] has not been exported!" ); // Feedback if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, "[null]")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in remote engine!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Error occurred in remote engine!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); // Feedback if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, "[null]")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } @@ -95,8 +95,8 @@ void RemoteSyncCallRequest(ModuleMessage& msg) { } void RemoteSyncCallReturn(ModuleMessage& msg) { - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Remote call result message received."); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Result: {}", msg.getData()); + // lse::LegacyScriptEngine::getLogger().debug("*** Remote call result message received."); + // lse::LegacyScriptEngine::getLogger().debug("*** Result: {}", msg.getData()); remoteResultMap[msg.getId()] = msg.getData(); OperationCount(std::to_string(msg.getId())).done(); } @@ -108,7 +108,7 @@ Local MakeRemoteCall(const string& funcName, const Arguments& args) auto data = globalShareData->exportedFuncs.find(funcName); if (data == globalShareData->exportedFuncs.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail to import! Function [{}] has not been exported!", funcName); + lse::LegacyScriptEngine::getLogger().error("Fail to import! Function [{}] has not been exported!", funcName); return Local(); } @@ -132,7 +132,7 @@ bool LLSEExportFunc(ScriptEngine *engine, const Local &func, const str auto data = globalShareData->exportedFuncs.find(exportName); if (data == globalShareData->exportedFuncs.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Exported function \"{}\" not found", exportName); + lse::LegacyScriptEngine::getLogger().error("Exported function \"{}\" not found", exportName); return ""; } auto engine = data->second.engine; @@ -184,7 +184,7 @@ Local LlClass::importFunc(const Arguments &args) #ifdef DEBUG auto startTime = clock(); auto res = MakeRemoteCall(funcName, args); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info("MakeRemoteCall time: {}s", (clock() - startTime) / 1000.0); + lse::LegacyScriptEngine::getLogger().info("MakeRemoteCall time: {}s", (clock() - startTime) / 1000.0); return res; #endif // DEBUG return MakeRemoteCall(funcName, args); diff --git a/src/legacy/engine/TimeTaskSystem.cpp b/src/legacy/engine/TimeTaskSystem.cpp index b596f9fb..9855bd7c 100644 --- a/src/legacy/engine/TimeTaskSystem.cpp +++ b/src/legacy/engine/TimeTaskSystem.cpp @@ -26,16 +26,16 @@ std::unordered_map timeTaskMap; #define TIMETASK_CATCH(TASK_TYPE) \ catch (const Exception& e) { \ EngineScope scope(data.engine); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in {}", TASK_TYPE); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error("Error occurred in {}", TASK_TYPE); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineData(data.engine)->pluginName \ ); \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in {}", TASK_TYPE); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error("Error occurred in {}", TASK_TYPE); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineData(data.engine)->pluginName \ ); \ } @@ -199,8 +199,8 @@ bool ClearTimeTask(int const& id) { timeTaskMap.erase(id); } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in ClearTimeTask"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail in ClearTimeTask"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } return true; } @@ -218,7 +218,7 @@ void LLSERemoveTimeTaskData(std::shared_ptr engine) { } } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info("Fail in LLSERemoveTimeTaskData"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().info("Fail in LLSERemoveTimeTaskData"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } diff --git a/src/legacy/legacyapi/db/Session.cpp b/src/legacy/legacyapi/db/Session.cpp index 563b7443..fcb73ab8 100644 --- a/src/legacy/legacyapi/db/Session.cpp +++ b/src/legacy/legacyapi/db/Session.cpp @@ -1,9 +1,7 @@ #include "legacyapi/db/Session.h" #include "lse/Entry.h" -#ifndef LSE_BACKEND_NODEJS #include "legacyapi/db/impl/mysql/Session.h" -#endif #include "legacyapi/db/impl/sqlite/Session.h" #include "ll/api/io/LoggerRegistry.h" #include "ll/api/utils/StringUtils.h" @@ -29,12 +27,12 @@ ResultSet Session::query(const std::string& query) { }); IF_ENDBG { if (result.valid()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Session::query: Results >"); + lse::LegacyScriptEngine::getLogger().debug("Session::query: Results >"); for (auto& str : ll::string_utils::splitByPattern(result.toTableString(), "\n")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug(str); + lse::LegacyScriptEngine::getLogger().debug(str); } } else { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Session::query: Query returned no result" ); } @@ -46,7 +44,7 @@ std::string Session::getLastError() const { throw std::runtime_error("Session::g std::weak_ptr Session::getOrSetSelf() { if (self.expired()) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "Session::getOrSetSelf: `self` expired, trying fetching" ); return self = getSession(this); @@ -110,16 +108,10 @@ SharedPointer Session::_Create(DBType type, const ConnParams& params) { session = params.empty() ? std::make_shared() : std::make_shared(params); break; case DBType::MySQL: -#ifdef LSE_BACKEND_NODEJS - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( - "Session::_Create: MySQL is disabled in NodeJS backend because its OpenSSL has conflicts with libnode" - ); -#else session = params.empty() ? std::make_shared() : std::make_shared(params); -#endif break; default: - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Session::_Create: Unknown/Unsupported database type" ); } diff --git a/src/legacy/legacyapi/db/impl/mysql/Session.cpp b/src/legacy/legacyapi/db/impl/mysql/Session.cpp index 3304c805..12248492 100644 --- a/src/legacy/legacyapi/db/impl/mysql/Session.cpp +++ b/src/legacy/legacyapi/db/impl/mysql/Session.cpp @@ -8,14 +8,14 @@ namespace DB { MySQLSession::MySQLSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + IF_ENDBG lse::LegacyScriptEngine::getLogger().info( "MySQLSession::MySQLSession: Constructed! this: {}", (void*)this ); conn = mysql_init(nullptr); } MySQLSession::MySQLSession(const ConnParams& params) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + IF_ENDBG lse::LegacyScriptEngine::getLogger().info( "MySQLSession::MySQLSession: Constructed! this: {}", (void*)this ); @@ -24,7 +24,7 @@ MySQLSession::MySQLSession(const ConnParams& params) { } MySQLSession::~MySQLSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + IF_ENDBG lse::LegacyScriptEngine::getLogger().info( "MySQLSession::MySQLSession: Destructor: this: {}", (void*)this ); @@ -79,7 +79,7 @@ void MySQLSession::open(const ConnParams& params) { "true", "utf8" ); - // IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLSession::open: MySQL default + // IF_ENDBG lse::LegacyScriptEngine::getLogger().debug("MySQLSession::open: MySQL default // charset name : {}", defaultCharset); mysql_options(conn, MYSQL_SET_CHARSET_NAME, charset.c_str()); auto res = mysql_real_connect( @@ -97,7 +97,7 @@ void MySQLSession::open(const ConnParams& params) { "MySQLSession::MySQLSession: Failed to open database: " + std::string(mysql_error(conn)) ); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::open: Opened database: " + std::string(p.getHost()) + ":" + std::to_string(port) + "/" + db ); #if defined(LLDB_DEBUG_MODE) @@ -106,7 +106,7 @@ void MySQLSession::open(const ConnParams& params) { } bool MySQLSession::execute(const std::string& query) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::execute: Executing > " + query ); auto res = mysql_query(conn, query.c_str()); @@ -114,7 +114,7 @@ bool MySQLSession::execute(const std::string& query) { } bool MySQLSession::relogin(const std::string& user, const std::string& password, const std::string& db) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::change: Changing user to{} and database to {} ", user, db @@ -124,7 +124,7 @@ bool MySQLSession::relogin(const std::string& user, const std::string& password, } Session& MySQLSession::query(const std::string& query, std::function callback) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::query: Querying > " + query ); auto res = mysql_query(conn, query.c_str()); @@ -140,7 +140,7 @@ Session& MySQLSession::query(const std::string& query, std::function, std::size_t> AllocateBuffer(const MYSQL_FIELD if (len) { auto buffer = std::shared_ptr(new char[len]); #if defined(LLDB_DEBUG_MODE) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("AllocateBuffer: Allocated! Buffer size: + lse::LegacyScriptEngine::getLogger().debug("AllocateBuffer: Allocated! Buffer size: {}", len); #endif return std::make_pair(buffer, len); @@ -235,7 +235,7 @@ Any ReceiverToAny(const Receiver& rec) { // case MYSQL_TYPE_GEOMETRY: case MYSQL_TYPE_JSON: #if defined(LLDB_DEBUG_MODE) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("ReceiverToAny: string: length: {}, buffer + lse::LegacyScriptEngine::getLogger().debug("ReceiverToAny: string: length: {}, buffer {}", rec.length, rec.buffer.get()); #endif return Any(std::string(rec.buffer.get())); @@ -244,7 +244,7 @@ Any ReceiverToAny(const Receiver& rec) { case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: #if defined(LLDB_DEBUG_MODE) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("ReceiverToAny: blob: length: {}, buffer + lse::LegacyScriptEngine::getLogger().debug("ReceiverToAny: blob: length: {}, buffer {}", rec.length, rec.buffer.get()); #endif // Unknown bug: rec.length is 0 @@ -252,7 +252,7 @@ Any ReceiverToAny(const Receiver& rec) { case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: // TODO: Decimal - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQL_Decimal: {}", + lse::LegacyScriptEngine::getLogger().debug("MySQL_Decimal: {}", std::string(rec.buffer.get(), rec.length)); return Any(); default: throw std::runtime_error("ReceiverToAny: Unsupported MySQL data type: " + std::to_string(rec.field.type)); @@ -278,7 +278,7 @@ int MySQLStmt::getNextParamIndex() { result++; } } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::getNextParamIndex: The next param index is {}", result + 1 ); @@ -293,7 +293,7 @@ void MySQLStmt::bindResult() { ); } if (!metadata) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bindResult: No result metadata" ); return; @@ -306,7 +306,7 @@ void MySQLStmt::bindResult() { // later mysql_stmt_store_result(stmt); auto cnt = mysql_num_fields(metadata); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bindResult: mysql_num_fields : {} ", cnt ); @@ -334,7 +334,7 @@ void MySQLStmt::bindResult() { rec.field = field; // Save the field resultHeader->add(field.name); // Add the field name to the header - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bindResult: Bind result {} (type {}) at index {}", field.name, (int)field.type, @@ -413,7 +413,7 @@ Stmt& MySQLStmt::bind(const Any& value, int index) { params[index].buffer_length = sz; params[index].is_null = 0; params[index].length = (unsigned long*)¶m.length; - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bind: Bound string param at {}: {}", index, param.buffer.get() @@ -508,10 +508,10 @@ Row MySQLStmt::_Fetch() { if (fetched) { throw std::runtime_error("MySQLStmt::_Fetch: No more rows"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLStmt::_Fetch: Fetching row..."); + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug("MySQLStmt::_Fetch: Fetching row..."); Row row(resultHeader); IF_ENDBG - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::_Fetch: RowHeader size {}", row.header->size() ); @@ -523,7 +523,7 @@ Row MySQLStmt::_Fetch() { col.length = length; auto v = ReceiverToAny(col); row.push_back(v); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::_Fetch: Fetched column `{}`, type {}, value {}", col.field.name, Any::type2str(v.type), @@ -612,15 +612,15 @@ SharedPointer MySQLStmt::create(const std::weak_ptr& session, con auto query = sql; auto params = ParseStmtParams(query); if (raw->debugOutput && !params.empty()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::create: Parsed named parameters in query: " ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::create: - SQL without named parameters: {}", query ); for (auto& [k, v] : params) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLStmt::create: - {}: {}", k, v); + lse::LegacyScriptEngine::getLogger().debug("MySQLStmt::create: - {}: {}", k, v); } } auto res = mysql_stmt_prepare(stmt, query.c_str(), query.size()); @@ -632,7 +632,7 @@ SharedPointer MySQLStmt::create(const std::weak_ptr& session, con result->paramIndexes = params; result->setDebugOutput(raw->debugOutput); if (raw->debugOutput) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLStmt::create: Prepared > " + query); + lse::LegacyScriptEngine::getLogger().debug("MySQLStmt::create: Prepared > " + query); auto shared = SharedPointer(result); result->self = shared; return shared; diff --git a/src/legacy/legacyapi/db/impl/sqlite/Session.cpp b/src/legacy/legacyapi/db/impl/sqlite/Session.cpp index c752bef4..c0075685 100644 --- a/src/legacy/legacyapi/db/impl/sqlite/Session.cpp +++ b/src/legacy/legacyapi/db/impl/sqlite/Session.cpp @@ -8,13 +8,13 @@ namespace DB { SQLiteSession::SQLiteSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession: Constructed! this: {}", (void*)this ); } SQLiteSession::SQLiteSession(const ConnParams& params) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession: Constructed! this: {}", (void*)this ); @@ -22,7 +22,7 @@ SQLiteSession::SQLiteSession(const ConnParams& params) { } SQLiteSession::~SQLiteSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::~SQLiteSession: Destructor: this: {}", (void*)this ); @@ -73,13 +73,13 @@ void SQLiteSession::open(const ConnParams& params) { if (res != SQLITE_OK) { throw std::runtime_error("SQLiteSession::open: Failed to open database: " + std::string(sqlite3_errmsg(conn))); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::open: Opened database: " + std::string(path) ); } bool SQLiteSession::execute(const std::string& query) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::execute: Executing > " + query ); auto res = sqlite3_exec(conn, query.c_str(), nullptr, nullptr, nullptr); @@ -87,7 +87,7 @@ bool SQLiteSession::execute(const std::string& query) { } Session& SQLiteSession::query(const std::string& query, std::function callback) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::query: Querying > " + query ); auto stmt = prepare(query); @@ -125,7 +125,7 @@ void SQLiteSession::close() { ); } conn = nullptr; - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::close: Closed database" ); } diff --git a/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp b/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp index 9b9b9468..7ba23158 100644 --- a/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp +++ b/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp @@ -12,7 +12,7 @@ namespace DB { SQLiteStmt::SQLiteStmt(sqlite3_stmt* stmt, const std::weak_ptr parent, bool autoExecute) : Stmt(parent, autoExecute), stmt(stmt) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::SQLiteStmt: Constructed! this: {}", (void*)this ); @@ -27,7 +27,7 @@ int SQLiteStmt::getNextParamIndex() { result++; } } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::getNextParamIndex: The next param index is {}", result + 1 ); @@ -39,7 +39,7 @@ void SQLiteStmt::fetchResultHeader() { int colCnt = sqlite3_column_count(stmt); for (int i = 0; i < colCnt; i++) { auto name = sqlite3_column_name(stmt, i); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::fetchResultHeader: Column Name[{}]: {}", i, name @@ -49,7 +49,7 @@ void SQLiteStmt::fetchResultHeader() { } SQLiteStmt::~SQLiteStmt() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::~SQLiteStmt: Destructor: this: {}", (void*)this ); @@ -138,7 +138,7 @@ Stmt& SQLiteStmt::bind(const Any& value, const std::string& name) { // second is the key! throw std::invalid_argument("SQLiteStmt::bind: There isn't any statement parameter named `" + name + "`!"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::bind: Parameter `{}` is at index {}", name, index @@ -167,11 +167,11 @@ bool SQLiteStmt::step() { if (!resultHeader || resultHeader->empty()) { fetchResultHeader(); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("SQLiteStmt::step: Successfully"); + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug("SQLiteStmt::step: Successfully"); stepped = true; return true; } else if (res == SQLITE_DONE) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::step: The statment is done" ); stepped = false; @@ -204,7 +204,7 @@ Row SQLiteStmt::_Fetch() { break; case SQLITE_TEXT: { std::string text(reinterpret_cast(sqlite3_column_text(stmt, i))); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::_Fetch: Fetched TEXT type column: {} {}", i, text @@ -222,7 +222,7 @@ Row SQLiteStmt::_Fetch() { for (auto& byte : arr) { out += ll::string_utils::intToHexStr(byte, true, true, false) + ' '; } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug(out); + lse::LegacyScriptEngine::getLogger().debug(out); } row.push_back(arr); break; @@ -242,7 +242,7 @@ Stmt& SQLiteStmt::reset() { if (res != SQLITE_OK) { throw std::runtime_error("SQLiteStmt::reexec: Failed to reset"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::reexec: Reset successfully" ); resultHeader.reset(); @@ -265,14 +265,14 @@ Stmt& SQLiteStmt::clear() { if (res != SQLITE_OK) { throw std::runtime_error("SQLiteStmt::clear: Failed to reset"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::clear: Reset successfully" ); res = sqlite3_clear_bindings(stmt); if (res != SQLITE_OK) { throw std::runtime_error("SQLiteStmt::clear: Failed to clear bindings"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::clear: Cleared bindings successfully" ); boundParamsCount = 0; @@ -332,7 +332,7 @@ SQLiteStmt::create(const std::weak_ptr& session, const std::string& sql result->parent = session; result->setDebugOutput(raw->debugOutput); if (raw->debugOutput) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("SQLiteStmt::create: Prepared > " + sql); + lse::LegacyScriptEngine::getLogger().debug("SQLiteStmt::create: Prepared > " + sql); auto shared = SharedPointer(result); result->self = shared; return shared; diff --git a/src/legacy/main/BuiltinCommands.cpp b/src/legacy/main/BuiltinCommands.cpp index ff254e8c..e6deb5fe 100644 --- a/src/legacy/main/BuiltinCommands.cpp +++ b/src/legacy/main/BuiltinCommands.cpp @@ -29,7 +29,7 @@ bool ProcessDebugEngine(const std::string& cmd) { #endif if (InConsoleDebugMode) { EngineScope enter(DebugEngine.get()); - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); try { if (cmd == "stop" || cmd == LLSE_DEBUG_CMD) { return true; @@ -57,14 +57,14 @@ void RegisterDebugCommand() { DebugCmdLogger->setFormatter(ll::makePolymorphic()); // Node.js engine doesn't support debug engine, Python engine don't need to register command. #if (!defined LSE_BACKEND_NODEJS) && (!defined LSE_BACKEND_PYTHON) - auto& command = ll::command::CommandRegistrar::getInstance().getOrCreateCommand( + auto& command = ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand( LLSE_DEBUG_CMD, "Debug LegacyScriptEngine", static_cast(lse::LegacyScriptEngine::getInstance().getConfig().debugCommandLevel) ); command.overload().optional("eval").execute( [](CommandOrigin const&, CommandOutput& output, EngineDebugCommand const& param) { - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); if (!param.eval.mText.empty()) { EngineScope enter(DebugEngine.get()); try { diff --git a/src/legacy/main/NodeJsHelper.cpp b/src/legacy/main/NodeJsHelper.cpp index 45639f07..e77a3bf1 100644 --- a/src/legacy/main/NodeJsHelper.cpp +++ b/src/legacy/main/NodeJsHelper.cpp @@ -98,7 +98,7 @@ LL_STATIC_HOOK( if (!(hAddon && hLibNode)) return hAddon; auto res = PatchDelayImport(hAddon, hLibNode); if (res) return hAddon; - res.error().log(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + res.error().log(lse::LegacyScriptEngine::getLogger()); } } return hAddon; @@ -130,11 +130,11 @@ bool initNodeJs() { node::ProcessInitializationFlags::kNoInitializeNodeV8Platform} ); if (result->exit_code() != 0) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Failed to initialize node! NodeJs plugins won't be loaded" ); for (const std::string& error : result->errors()) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(error); + lse::LegacyScriptEngine::getLogger().error(error); return false; } args = result->args(); @@ -173,7 +173,7 @@ std::shared_ptr newEngine() { if (!setup) { for (const std::string& err : errors) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "CommonEnvironmentSetup Error: {}", err.c_str() ); @@ -192,7 +192,7 @@ std::shared_ptr newEngine() { ScriptEngine::Deleter() ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Initialize ScriptEngine for node.js [{}]", (void*)engine.get() ); @@ -204,11 +204,11 @@ std::shared_ptr newEngine() { isolate, [](void* arg) { static_cast(arg)->destroy(); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Destroy ScriptEngine for node.js [{}]", arg ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Destroy EnvironmentCleanupHook"); + lse::LegacyScriptEngine::getLogger().debug("Destroy EnvironmentCleanupHook"); }, engine.get() ); @@ -304,7 +304,7 @@ bool loadPluginCode( // Set exit handler node::SetProcessExitHandler(env, [](node::Environment* env_, int exit_code) { auto engine = getEngine(env_); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().log( + lse::LegacyScriptEngine::getLogger().log( exit_code == 0 ? ll::io::LogLevel::Debug : ll::io::LogLevel::Error, "NodeJs plugin {} exited with code {}.", getEngineData(engine)->pluginName, @@ -317,7 +317,7 @@ bool loadPluginCode( MaybeLocal loadenv_ret = node::LoadEnvironment(env, compiler); bool loadFailed = loadenv_ret.IsEmpty(); - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); if (!loadFailed) { v8::Local errorMsg = loadenv_ret.ToLocalChecked(); @@ -365,7 +365,7 @@ bool loadPluginCode( } if ((ll::getGamingStatus() != ll::GamingStatus::Running)) { uv_stop(eventLoop); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Destroy ServerStopping"); + lse::LegacyScriptEngine::getLogger().debug("Destroy ServerStopping"); } } } @@ -406,8 +406,8 @@ bool stopEngine(node::Environment* env) { return true; } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail to stop engine {}", (void*)env); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail to stop engine {}", (void*)env); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); return false; } } @@ -551,7 +551,7 @@ int executeNpmCommand(std::vector npmArgs, std::string workingDir) if (!setup) { for (const std::string& err : errors) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "CommonEnvironmentSetup Error: {}", err.c_str() ); @@ -609,10 +609,10 @@ int executeNpmCommand(std::vector npmArgs, std::string workingDir) throw std::runtime_error("Failed at LoadEnvironment"); exit_code = node::SpinEventLoop(env).FromMaybe(exit_code); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to execute NPM command. Error occurs" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } node::Stop(env); } diff --git a/src/legacy/main/PythonHelper.cpp b/src/legacy/main/PythonHelper.cpp index cbfa50cd..a9edde87 100644 --- a/src/legacy/main/PythonHelper.cpp +++ b/src/legacy/main/PythonHelper.cpp @@ -69,7 +69,7 @@ bool loadPluginCode( engine->loadFile(String::newString(entryScriptPath)); } catch (const Exception& e1) { // Fail - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in Loading Script Plugin!"); + lse::LegacyScriptEngine::getLogger().error("Fail in Loading Script Plugin!"); throw e1; } return true; @@ -160,7 +160,7 @@ static PyObject* getPyGlobalDict() { } bool processPythonDebugEngine(const std::string& cmd) { - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); if (cmd == LLSE_DEBUG_CMD) { if (InConsoleDebugMode) { // EndDebug diff --git a/src/legacy/utils/IniHelper.cpp b/src/legacy/utils/IniHelper.cpp index 9f4937e7..c147162b 100644 --- a/src/legacy/utils/IniHelper.cpp +++ b/src/legacy/utils/IniHelper.cpp @@ -22,8 +22,8 @@ std::unique_ptr SimpleIni::create(const std::string& path, const std: root->SetUnicode(true); auto res = root->LoadFile(path.c_str()); if (res < 0) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Failed in loading ini file"); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("Failed in loading ini file"); + lse::LegacyScriptEngine::getLogger().error( std::string("Error Code:") + std::to_string((int)res) ); return nullptr; diff --git a/src/legacy/utils/JsonHelper.h b/src/legacy/utils/JsonHelper.h index 8a9fa7be..f3abe37c 100644 --- a/src/legacy/utils/JsonHelper.h +++ b/src/legacy/utils/JsonHelper.h @@ -29,8 +29,8 @@ inline ordered_json CreateJson(const std::string& path, const std::string& defCo std::filesystem::create_directories(dirPath); } } else { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in create json file!"); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("invalid path"); + lse::LegacyScriptEngine::getLogger().error("Fail in create json file!"); + lse::LegacyScriptEngine::getLogger().error("invalid path"); jsonConf = ordered_json::object(); } @@ -38,10 +38,10 @@ inline ordered_json CreateJson(const std::string& path, const std::string& defCo try { jsonConf = ordered_json::parse(defContent, nullptr, true, allowComment); } catch (std::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to parse default json content!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); jsonConf = ordered_json::object(); } } else { @@ -60,10 +60,10 @@ inline ordered_json CreateJson(const std::string& path, const std::string& defCo try { jsonConf = ordered_json::parse(*jsonTexts, nullptr, true, allowComment); } catch (std::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to parse json content in file!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); jsonConf = ordered_json::object(); } } diff --git a/src/lse/Config.h b/src/lse/Config.h index 05f1c019..321798a7 100644 --- a/src/lse/Config.h +++ b/src/lse/Config.h @@ -2,16 +2,18 @@ #include +#include "mc/server/commands/CommandPermissionLevel.h" + namespace lse { struct Config { - int version = 2; + int version = 3; bool migratePlugins = true; #ifdef LSE_BACKEND_NODEJS // fix addons that build with node-gyp version < 11.1.0, default: true std::optional fixLegacyAddons{std::nullopt}; #endif - int debugCommandLevel = 4; + CommandPermissionLevel debugCommandLevel = CommandPermissionLevel::GameDirectors; }; } // namespace lse diff --git a/src/lse/Entry.cpp b/src/lse/Entry.cpp index ea4018c8..3eafd34f 100644 --- a/src/lse/Entry.cpp +++ b/src/lse/Entry.cpp @@ -1,7 +1,5 @@ -#include "Entry.h" +#include "lse/Entry.h" -#include "PluginManager.h" -#include "PluginMigration.h" #include "legacy/engine/EngineManager.h" #include "legacy/engine/EngineOwnData.h" #include "legacy/main/EconomicSystem.h" @@ -13,7 +11,8 @@ #include "ll/api/mod/RegisterHelper.h" #include "ll/api/service/PlayerInfo.h" #include "ll/api/utils/ErrorUtils.h" -#include "lse/api/MoreGlobal.h" +#include "lse/PluginManager.h" +#include "lse/PluginMigration.h" #include #include @@ -72,9 +71,6 @@ LegacyScriptEngine& LegacyScriptEngine::getInstance() { bool LegacyScriptEngine::enable() { auto& logger = getSelf().getLogger(); try { - if (!api::MoreGlobal::onEnable()) { - logger.error("Failed to enable MoreGlobal"_tr()); - } ll::service::PlayerInfo::getInstance(); RegisterDebugCommand(); } catch (...) { @@ -96,7 +92,6 @@ void initializeLegacyStuff() { InitBasicEventListeners(); InitMessageSystem(); - api::MoreGlobal::onLoad(); } bool LegacyScriptEngine::load() { @@ -130,7 +125,10 @@ bool LegacyScriptEngine::load() { } } -bool LegacyScriptEngine::disable() { return true; } +bool LegacyScriptEngine::unload() { + DebugEngine.reset(); + return true; +} Config const& LegacyScriptEngine::getConfig() { return config; } @@ -158,7 +156,7 @@ void loadDebugEngine(const ll::mod::NativeMod& self) { // Init plugin instance for debug engine to prevent something unexpected. ll::mod::Manifest manifest; manifest.name = "DebugEngine"; - getEngineOwnData()->plugin = std::make_shared(manifest); + getEngineOwnData()->plugin = std::make_shared(manifest); // Init logger getEngineOwnData()->logger = ll::io::LoggerRegistry::getInstance().getOrCreate("DebugEngine"); @@ -186,4 +184,4 @@ void registerPluginManager(const std::shared_ptr& pm) { } // namespace lse -LL_REGISTER_MOD(lse::LegacyScriptEngine, lse::LegacyScriptEngine::getInstance()); \ No newline at end of file +LL_REGISTER_MOD(lse::LegacyScriptEngine, lse::LegacyScriptEngine::getInstance()); diff --git a/src/lse/Entry.h b/src/lse/Entry.h index d03f7b1d..c9c4dece 100644 --- a/src/lse/Entry.h +++ b/src/lse/Entry.h @@ -1,8 +1,8 @@ #pragma once -#include "Config.h" -#include "PluginManager.h" #include "ll/api/mod/NativeMod.h" +#include "lse/Config.h" +#include "lse/PluginManager.h" namespace lse { @@ -10,6 +10,8 @@ class LegacyScriptEngine { public: static LegacyScriptEngine& getInstance(); + static inline ll::io::Logger& getLogger() { return getInstance().getSelf().getLogger(); } + LegacyScriptEngine() : mSelf(*ll::mod::NativeMod::current()) {} [[nodiscard]] ll::mod::NativeMod& getSelf() const { return mSelf; } @@ -22,9 +24,7 @@ class LegacyScriptEngine { bool enable(); - bool disable(); - - // bool unload(); + bool unload(); private: ll::mod::NativeMod& mSelf; diff --git a/src/lse/Plugin.cpp b/src/lse/Plugin.cpp deleted file mode 100644 index a3482f57..00000000 --- a/src/lse/Plugin.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "Plugin.h" - -#include "Entry.h" -#include "legacy/engine/EngineOwnData.h" -#include "ll/api/mod/Manifest.h" -#include "ll/api/mod/Mod.h" - -namespace lse { - -Plugin::Plugin(ll::mod::Manifest manifest) : ll::mod::Mod(std::move(manifest)) {} - -Plugin::~Plugin() { release(); } - -std::shared_ptr Plugin::current() { - return lse::LegacyScriptEngine::getInstance().getManager().getMod(getEngineOwnData()->pluginName); -} -} // namespace lse diff --git a/src/lse/PluginMigration.cpp b/src/lse/PluginMigration.cpp index e1087122..2ab2b51e 100644 --- a/src/lse/PluginMigration.cpp +++ b/src/lse/PluginMigration.cpp @@ -1,10 +1,10 @@ -#include "PluginMigration.h" +#include "lse/PluginMigration.h" -#include "Entry.h" #include "ll/api/i18n/I18n.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/Mod.h" #include "ll/api/reflection/Serialization.h" +#include "lse/Entry.h" #include #include diff --git a/src/lse/PluginMigration.h b/src/lse/PluginMigration.h index 66de0146..163f16bc 100644 --- a/src/lse/PluginMigration.h +++ b/src/lse/PluginMigration.h @@ -1,6 +1,6 @@ #pragma once -#include "PluginManager.h" +#include "lse/PluginManager.h" namespace lse { diff --git a/src/lse/ScriptPlugin.cpp b/src/lse/ScriptPlugin.cpp new file mode 100644 index 00000000..739ab141 --- /dev/null +++ b/src/lse/ScriptPlugin.cpp @@ -0,0 +1,16 @@ +#include "legacy/engine/EngineOwnData.h" +#include "ll/api/mod/Manifest.h" +#include "ll/api/mod/Mod.h" +#include "lse/Entry.h" +#include "lse/ScriptPlugin.h" + +namespace lse { + +ScriptPlugin::ScriptPlugin(ll::mod::Manifest manifest) : ll::mod::Mod(std::move(manifest)) {} + +ScriptPlugin::~ScriptPlugin() { release(); } + +std::shared_ptr ScriptPlugin::current() { + return lse::LegacyScriptEngine::getInstance().getManager().getMod(getEngineOwnData()->pluginName); +} +} // namespace lse diff --git a/src/lse/Plugin.h b/src/lse/ScriptPlugin.h similarity index 80% rename from src/lse/Plugin.h rename to src/lse/ScriptPlugin.h index 77886d4c..dc05b514 100644 --- a/src/lse/Plugin.h +++ b/src/lse/ScriptPlugin.h @@ -1,13 +1,13 @@ #pragma once -#include "PluginManager.h" #include "ll/api/command/runtime/ParamKind.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/Mod.h" +#include "lse/PluginManager.h" namespace lse { -class Plugin : public ll::mod::Mod { +class ScriptPlugin : public ll::mod::Mod { friend PluginManager; public: @@ -22,8 +22,8 @@ class Plugin : public ll::mod::Mod { std::unordered_map> registeredCommands; - explicit Plugin(ll::mod::Manifest manifest); - ~Plugin(); + explicit ScriptPlugin(ll::mod::Manifest manifest); + ~ScriptPlugin(); static std::shared_ptr current(); }; diff --git a/src/lse/api/MoreGlobal.cpp b/src/lse/api/MoreGlobal.cpp index 5f4aeaf9..5008c185 100644 --- a/src/lse/api/MoreGlobal.cpp +++ b/src/lse/api/MoreGlobal.cpp @@ -2,34 +2,10 @@ #include "ll/api/memory/Hook.h" #include "mc/dataloadhelper/DefaultDataLoadHelper.h" -#include "mc/world/level/storage/DBStorage.h" -#include "mc/world/level/storage/DBStorageConfig.h" namespace lse::api::MoreGlobal { -DBStorage* dbStorage; + DefaultDataLoadHelper helper; DefaultDataLoadHelper& defaultDataLoadHelper() { return helper; } -LL_TYPE_INSTANCE_HOOK( - DBStorageHook, - HookPriority::Normal, - DBStorage, - &DBStorage::$ctor, - void*, - ::DBStorageConfig config, - ::Bedrock::NotNullNonOwnerPtr<::LevelDbEnv> levelDbEnv -) { - void* ori = origin(std::move(config), levelDbEnv); - MoreGlobal::dbStorage = (DBStorage*)ori; - return ori; -}; - -void onLoad() { DBStorageHook::hook(); } - -bool onEnable() { - if (dbStorage && DBStorageHook::unhook()) { - return true; - } - return false; -} } // namespace lse::api::MoreGlobal diff --git a/src/lse/api/MoreGlobal.h b/src/lse/api/MoreGlobal.h index bdd35541..ad501bc7 100644 --- a/src/lse/api/MoreGlobal.h +++ b/src/lse/api/MoreGlobal.h @@ -1,8 +1,7 @@ #include "mc/dataloadhelper/DefaultDataLoadHelper.h" -class DBStorage; + namespace lse::api::MoreGlobal { -extern DBStorage* dbStorage; + extern DefaultDataLoadHelper& defaultDataLoadHelper(); -extern void onLoad(); -extern bool onEnable(); + }; // namespace lse::api::MoreGlobal diff --git a/src/lse/api/Thread.cpp b/src/lse/api/Thread.cpp new file mode 100644 index 00000000..b9955734 --- /dev/null +++ b/src/lse/api/Thread.cpp @@ -0,0 +1,11 @@ +#include "lse/api/Thread.h" + +#include "ll/api/service/Bedrock.h" +#include "mc/server/ServerInstance.h" + +namespace lse::api::thread { +bool isServerThread() { + auto instance = ll::service::getServerInstance(); + return instance && std::this_thread::get_id() == instance->mServerInstanceThread->get_id(); +} +} // namespace lse::api::thread diff --git a/src/lse/api/Thread.h b/src/lse/api/Thread.h new file mode 100644 index 00000000..91a5357a --- /dev/null +++ b/src/lse/api/Thread.h @@ -0,0 +1,12 @@ +#pragma once + +namespace lse::api::thread { +bool isServerThread(); +inline bool checkClientIsServerThread() { +#ifdef LL_PLAT_C + return isServerThread(); +#else + return true; +#endif +} +} // namespace lse::api::thread diff --git a/src/lse/api/helper/AttributeHelper.cpp b/src/lse/api/helper/AttributeHelper.cpp index 1737057f..c4d4d3e8 100644 --- a/src/lse/api/helper/AttributeHelper.cpp +++ b/src/lse/api/helper/AttributeHelper.cpp @@ -1,39 +1,46 @@ #include "AttributeHelper.h" +#include "mc/world/attribute/Attribute.h" #include "mc/world/attribute/AttributeInstance.h" -#include "mc/world/attribute/AttributeModificationContext.h" +#include "mc/world/attribute/AttributeInstanceRef.h" #include "mc/world/attribute/BaseAttributeMap.h" namespace lse::api { -inline void AttributeHelper::setDirty(MutableAttributeWithContext& attribute) { - auto map = attribute.mContext->mAttributeMap; - if (map) { - map->_onAttributeModified(*attribute.mInstance); - } +inline void AttributeHelper::setDirty(BaseAttributeMap& map, AttributeInstance const* attribute) { + map._onAttributeModified(*attribute); } -void AttributeHelper::setCurrentValue(MutableAttributeWithContext& attribute, float value) { - auto& instance = attribute.mInstance; - instance->mCurrentValue = value; - setDirty(attribute); +bool AttributeHelper::setCurrentValue(BaseAttributeMap& map, Attribute const& attribute, float value) { + if (auto ptr = map.getMutableInstance(attribute.mIDValue).mPtr) { + ptr->mCurrentValue = value; + setDirty(map, ptr); + return true; + } + return false; } -void AttributeHelper::setMaxValue(MutableAttributeWithContext& attribute, float value) { - auto& instance = attribute.mInstance; - instance->mCurrentMaxValue = value; - instance->mDefaultMaxValue = value; - float& currentValue = instance->mCurrentValue; - currentValue = std::max(currentValue, instance->mCurrentMinValue); - setDirty(attribute); +bool AttributeHelper::setMaxValue(BaseAttributeMap& map, Attribute const& attribute, float value) { + if (auto ptr = map.getMutableInstance(attribute.mIDValue).mPtr) { + ptr->mCurrentMaxValue = value; + ptr->mDefaultMaxValue = value; + float& currentValue = ptr->mCurrentValue; + currentValue = std::max(currentValue, ptr->mCurrentMinValue); + setDirty(map, ptr); + return true; + } + return false; } -void AttributeHelper::setDefaultValue(MutableAttributeWithContext& attribute, float value) { - auto& instance = attribute.mInstance; - float& defaultValue = instance->mDefaultValue; - if (value != defaultValue) { - defaultValue = value; - instance->mCurrentValue = value; - setDirty(attribute); +bool AttributeHelper::setDefaultValue(BaseAttributeMap& map, Attribute const& attribute, float value) { + if (auto ptr = map.getMutableInstance(attribute.mIDValue).mPtr) { + float& defaultValue = ptr->mDefaultValue; + if (value != defaultValue) { + defaultValue = value; + ptr->mCurrentValue = value; + setDirty(map, ptr); + return true; + } } + return false; } -} // namespace lse::api::AttributeHelper \ No newline at end of file +} // namespace lse::api diff --git a/src/lse/api/helper/AttributeHelper.h b/src/lse/api/helper/AttributeHelper.h index 61e93e08..fe2b542d 100644 --- a/src/lse/api/helper/AttributeHelper.h +++ b/src/lse/api/helper/AttributeHelper.h @@ -1,13 +1,13 @@ #pragma once -#include "mc/world/attribute/MutableAttributeWithContext.h" +#include "mc/world/attribute/BaseAttributeMap.h" namespace lse::api { class AttributeHelper { - static void setDirty(MutableAttributeWithContext& attribute); + static void setDirty(BaseAttributeMap& map, AttributeInstance const* attribute); public: - static void setCurrentValue(MutableAttributeWithContext& attribute, float value); - static void setMaxValue(MutableAttributeWithContext& attribute, float value); - static void setDefaultValue(MutableAttributeWithContext& attribute, float value); + static bool setCurrentValue(BaseAttributeMap& map, Attribute const& attribute, float value); + static bool setMaxValue(BaseAttributeMap& map, Attribute const& attribute, float value); + static bool setDefaultValue(BaseAttributeMap& map, Attribute const& attribute, float value); }; -} // namespace lse::api \ No newline at end of file +} // namespace lse::api diff --git a/src/lse/api/helper/BlockHelper.cpp b/src/lse/api/helper/BlockHelper.cpp index 4bd28cdf..f1ba4183 100644 --- a/src/lse/api/helper/BlockHelper.cpp +++ b/src/lse/api/helper/BlockHelper.cpp @@ -5,8 +5,7 @@ namespace lse::api { bool BlockHelper::isValidHeight(WeakRef dimension, std::variant height) { - auto dim = dimension.lock(); - if (dim) { + if (auto dim = dimension.lock()) { if (std::holds_alternative(height)) { int y = std::get(height); return dim->mHeightRange->mMin <= y && dim->mHeightRange->mMax >= y; @@ -18,4 +17,4 @@ bool BlockHelper::isValidHeight(WeakRef dimension, std::variantmPreviousLevelRequirement; if (player->mPlayerLevelChanged) { - int curLvl = player->getAttribute(Player::LEVEL()).mCurrentValue; + int curLvl = player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; int plus = (curLvl / 15 == 1) ? (curLvl * 4 - 38) : (curLvl * 8 - 158); prevLevelReq = (curLvl / 15) ? (curLvl + plus) : (curLvl * 2 + 7); player->mPlayerLevelChanged = false; @@ -21,16 +21,22 @@ unsigned int PlayerHelper::getPreviousLevelRequirement(Player* player) { } unsigned int PlayerHelper::getXpEarnedAtCurrentLevel(Player* player) { - unsigned int prevLevelReq = PlayerHelper::getPreviousLevelRequirement(player); - auto& attribute = player->getAttribute(Player::EXPERIENCE()); - return (unsigned int)roundf(attribute.mCurrentValue * (float)prevLevelReq); + unsigned int prevLevelReq = getPreviousLevelRequirement(player); + auto attribute = player->getAttribute(Player::EXPERIENCE()); + return static_cast(roundf(attribute.mPtr->mCurrentValue * static_cast(prevLevelReq))); } bool PlayerHelper::setXpEarnedAtCurrentLevel(Player* player, unsigned int xp) { - unsigned int prevLevelReq = PlayerHelper::getPreviousLevelRequirement(player); - auto attribute = player->getMutableAttribute(Player::EXPERIENCE()); - AttributeHelper::setCurrentValue(attribute, (float)xp / (float)prevLevelReq); - return true; + if (auto component = player->getEntityContext().tryGetComponent()) { + unsigned int prevLevelReq = getPreviousLevelRequirement(player); + AttributeHelper::setCurrentValue( + component->mAttributes, + Player::EXPERIENCE(), + static_cast(xp) / static_cast(prevLevelReq) + ); + return true; + } + return false; } -} // namespace lse::api \ No newline at end of file +} // namespace lse::api diff --git a/src/lse/events/BlockEvents.cpp b/src/lse/events/BlockEvents.cpp index b5e34ed9..86a22c3e 100644 --- a/src/lse/events/BlockEvents.cpp +++ b/src/lse/events/BlockEvents.cpp @@ -7,10 +7,9 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" -#include "lse/api/helper/BlockHelper.h" +#include "lse/api/Thread.h" #include "mc/legacy/ActorUniqueID.h" #include "mc/scripting/modules/minecraft/events/ScriptBlockGlobalEventListener.h" -#include "mc/server/ServerInstance.h" #include "mc/server/commands/CommandOrigin.h" #include "mc/server/commands/CommandOriginType.h" #include "mc/world/actor/ArmorStand.h" @@ -30,7 +29,6 @@ #include "mc/world/level/block/ComparatorBlock.h" #include "mc/world/level/block/CopperBulbBlock.h" #include "mc/world/level/block/CrafterBlock.h" -#include "mc/world/level/block/DiodeBlock.h" #include "mc/world/level/block/DispenserBlock.h" #include "mc/world/level/block/DoorBlock.h" #include "mc/world/level/block/FarmBlock.h" @@ -48,10 +46,13 @@ #include "mc/world/level/block/TrapDoorBlock.h" #include "mc/world/level/block/actor/BaseCommandBlock.h" #include "mc/world/level/block/actor/PistonBlockActor.h" +#include "mc/world/level/block/block_events/BlockRedstoneUpdateEvent.h" #include "mc/world/level/dimension/Dimension.h" #include "mc/world/level/material/Material.h" namespace lse::events::block { +using api::thread::checkClientIsServerThread; + LL_TYPE_INSTANCE_HOOK( ContainerChangeHook, HookPriority::Normal, @@ -63,20 +64,22 @@ LL_TYPE_INSTANCE_HOOK( ItemStack const& newItem ) { IF_LISTENED(EVENT_TYPES::onContainerChange) { - if (*reinterpret_cast(this) != LevelContainerModel::$vftable()) - return origin(slotNumber, oldItem, newItem); + if (checkClientIsServerThread()) { + if (*reinterpret_cast(this) != LevelContainerModel::$vftable()) + return origin(slotNumber, oldItem, newItem); - // Player::hasOpenContainer() - if (mPlayer.mContainerManager) { - if (!CallEvent( - EVENT_TYPES::onContainerChange, - PlayerClass::newPlayer(&mPlayer), - BlockClass::newBlock(mBlockPos, mPlayer.getDimensionId().id), - Number::newNumber(slotNumber + this->_getContainerOffset()), - ItemClass::newItem(&const_cast(oldItem)), - ItemClass::newItem(&const_cast(newItem)) - )) { - return; + // Player::hasOpenContainer() + if (mPlayer.mContainerManager) { + if (!CallEvent( + EVENT_TYPES::onContainerChange, + PlayerClass::newPlayer(&mPlayer), + BlockClass::newBlock(mBlockPos, mPlayer.getDimensionId().id), + Number::newNumber(slotNumber + this->_getContainerOffset()), + ItemClass::newItem(&const_cast(oldItem)), + ItemClass::newItem(&const_cast(newItem)) + )) { + return; + } } } } @@ -94,13 +97,15 @@ LL_TYPE_INSTANCE_HOOK( ::SharedTypes::Legacy::EquipmentSlot slot ) { IF_LISTENED(EVENT_TYPES::onChangeArmorStand) { - if (!CallEvent( - EVENT_TYPES::onChangeArmorStand, - EntityClass::newEntity(this), - PlayerClass::newPlayer(&player), - Number::newNumber((int)slot) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onChangeArmorStand, + EntityClass::newEntity(this), + PlayerClass::newPlayer(&player), + Number::newNumber((int)slot) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onChangeArmorStand); @@ -118,12 +123,14 @@ LL_TYPE_INSTANCE_HOOK( Actor& entity ) { IF_LISTENED(EVENT_TYPES::onStepOnPressurePlate) { - if (!CallEvent( - EVENT_TYPES::onStepOnPressurePlate, - EntityClass::newEntity(&entity), - BlockClass::newBlock(pos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onStepOnPressurePlate, + EntityClass::newEntity(&entity), + BlockClass::newBlock(pos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onStepOnPressurePlate); @@ -142,12 +149,14 @@ LL_TYPE_INSTANCE_HOOK( float fallDistance ) { IF_LISTENED(EVENT_TYPES::onFarmLandDecay) { - if (!CallEvent( - EVENT_TYPES::onFarmLandDecay, - IntPos::newPos(pos, region.getDimensionId()), - EntityClass::newEntity(actor) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onFarmLandDecay, + IntPos::newPos(pos, region.getDimensionId()), + EntityClass::newEntity(actor) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onFarmLandDecay); @@ -166,21 +175,23 @@ LL_TYPE_INSTANCE_HOOK( uchar pistonMoveFacing ) { IF_LISTENED(EVENT_TYPES::onPistonTryPush) { - if (region.getBlock(curPos).isAir()) { - return origin(region, curPos, curBranchFacing, pistonMoveFacing); - } - if (!CallEvent( - EVENT_TYPES::onPistonTryPush, - IntPos::newPos(this->mPosition, region.getDimensionId()), - BlockClass::newBlock(curPos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (region.getBlock(curPos).isAir()) { + return origin(region, curPos, curBranchFacing, pistonMoveFacing); + } + if (!CallEvent( + EVENT_TYPES::onPistonTryPush, + IntPos::newPos(this->mPosition, region.getDimensionId()), + BlockClass::newBlock(curPos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onPistonTryPush); bool shouldPush = origin(region, curPos, curBranchFacing, pistonMoveFacing); IF_LISTENED(EVENT_TYPES::onPistonPush) { - if (shouldPush) { + if (checkClientIsServerThread() && shouldPush) { CallEvent( // Not cancellable EVENT_TYPES::onPistonPush, IntPos::newPos(this->mPosition, region.getDimensionId()), @@ -194,10 +205,29 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(ExplodeHook, HookPriority::Normal, Explosion, &Explosion::explode, bool, ::IRandom& random) { IF_LISTENED(EVENT_TYPES::onEntityExplode) { - if (mSourceID->rawID != ActorUniqueID::INVALID_ID().rawID) { + if (checkClientIsServerThread()) { + if (mSourceID->rawID != ActorUniqueID::INVALID_ID().rawID) { + if (!CallEvent( + EVENT_TYPES::onEntityExplode, + EntityClass::newEntity(ll::service::getLevel()->fetchEntity(mSourceID, false)), + FloatPos::newPos(mPos, mRegion.getDimensionId()), + Number::newNumber(mRadius), + Number::newNumber(mMaxResistance), + Boolean::newBoolean(mBreaking), + Boolean::newBoolean(mFire) + )) { + return false; + } + } + } + } + IF_LISTENED_END(EVENT_TYPES::onEntityExplode); + + IF_LISTENED(EVENT_TYPES::onBlockExplode) { + if (checkClientIsServerThread()) { if (!CallEvent( - EVENT_TYPES::onEntityExplode, - EntityClass::newEntity(ll::service::getLevel()->fetchEntity(mSourceID, false)), + EVENT_TYPES::onBlockExplode, + BlockClass::newBlock(*mPos, mRegion.getDimensionId()), FloatPos::newPos(mPos, mRegion.getDimensionId()), Number::newNumber(mRadius), Number::newNumber(mMaxResistance), @@ -208,21 +238,6 @@ LL_TYPE_INSTANCE_HOOK(ExplodeHook, HookPriority::Normal, Explosion, &Explosion:: } } } - IF_LISTENED_END(EVENT_TYPES::onEntityExplode); - - IF_LISTENED(EVENT_TYPES::onBlockExplode) { - if (!CallEvent( - EVENT_TYPES::onBlockExplode, - BlockClass::newBlock(*mPos, mRegion.getDimensionId()), - FloatPos::newPos(mPos, mRegion.getDimensionId()), - Number::newNumber(mRadius), - Number::newNumber(mMaxResistance), - Boolean::newBoolean(mBreaking), - Boolean::newBoolean(mFire) - )) { - return false; - } - } IF_LISTENED_END(EVENT_TYPES::onBlockExplode); return origin(random); } @@ -239,12 +254,14 @@ LL_TYPE_STATIC_HOOK( Level& level ) { IF_LISTENED(EVENT_TYPES::onRespawnAnchorExplode) { - if (!CallEvent( - EVENT_TYPES::onRespawnAnchorExplode, - IntPos::newPos(pos, region.getDimensionId()), - PlayerClass::newPlayer(&player) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onRespawnAnchorExplode, + IntPos::newPos(pos, region.getDimensionId()), + PlayerClass::newPlayer(&player) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onRespawnAnchorExplode); @@ -263,14 +280,16 @@ LL_TYPE_INSTANCE_HOOK( Actor* source ) { IF_LISTENED(EVENT_TYPES::onBlockExploded) { - if (destroyedBlock.isAir()) { - return origin(dimension, blockPos, destroyedBlock, source); + if (checkClientIsServerThread()) { + if (destroyedBlock.isAir()) { + return origin(dimension, blockPos, destroyedBlock, source); + } + CallEvent( + EVENT_TYPES::onBlockExploded, + BlockClass::newBlock(destroyedBlock, blockPos, dimension.getDimensionId()), + EntityClass::newEntity(source) + ); } - CallEvent( - EVENT_TYPES::onBlockExploded, - BlockClass::newBlock(destroyedBlock, blockPos, dimension.getDimensionId()), - EntityClass::newEntity(source) - ); } IF_LISTENED_END(EVENT_TYPES::onBlockExploded); return origin(dimension, blockPos, destroyedBlock, source); @@ -289,7 +308,7 @@ inline bool RedstoneUpdateEvent(BlockSource& region, BlockPos const& pos, int& s return true; } -#define REDSTONEHOOK(BLOCK) \ +#define REDSTONE_EVNET_HOOK_OLD(BLOCK) \ LL_TYPE_INSTANCE_HOOK( \ BLOCK##Hook, \ HookPriority::Normal, \ @@ -302,36 +321,90 @@ inline bool RedstoneUpdateEvent(BlockSource& region, BlockPos const& pos, int& s bool isFirstTime \ ) { \ IF_LISTENED(EVENT_TYPES::onRedStoneUpdate) { \ - if (!RedstoneUpdateEvent(region, pos, strength, isFirstTime)) { \ - return; \ + if (checkClientIsServerThread()) { \ + if (!RedstoneUpdateEvent(region, pos, strength, isFirstTime)) { \ + return; \ + } \ } \ } \ IF_LISTENED_END(EVENT_TYPES::onRedStoneUpdate); \ origin(region, pos, strength, isFirstTime); \ } -REDSTONEHOOK(RedStoneWireBlock) -REDSTONEHOOK(DiodeBlock) -REDSTONEHOOK(RedstoneTorchBlock) -REDSTONEHOOK(ComparatorBlock) -REDSTONEHOOK(HopperBlock) -REDSTONEHOOK(CrafterBlock) -REDSTONEHOOK(CommandBlock) -REDSTONEHOOK(BaseRailBlock) -REDSTONEHOOK(PoweredRailBlock) -REDSTONEHOOK(BigDripleafBlock) -REDSTONEHOOK(CopperBulbBlock) -REDSTONEHOOK(DoorBlock) -REDSTONEHOOK(FenceGateBlock) -REDSTONEHOOK(DispenserBlock) -REDSTONEHOOK(StructureBlock) -REDSTONEHOOK(TrapDoorBlock) -REDSTONEHOOK(NoteBlock) -REDSTONEHOOK(ActivatorRailBlock) -REDSTONEHOOK(RedstoneLampBlock) -REDSTONEHOOK(TntBlock) +#define REDSTONE_EVNET_HOOK_1(BLOCK) \ + LL_TYPE_INSTANCE_HOOK( \ + BLOCK##Hook, \ + HookPriority::Normal, \ + BLOCK, \ + &BLOCK::$_onRedstoneUpdate, \ + void, \ + BlockEvents::BlockRedstoneUpdateEvent& blockEvent \ + ) { \ + IF_LISTENED(EVENT_TYPES::onRedStoneUpdate) { \ + if (checkClientIsServerThread()) { \ + if (!RedstoneUpdateEvent( \ + blockEvent.mRegion, \ + blockEvent.mPos, \ + blockEvent.mSignalLevel, \ + blockEvent.mIsFirstTime \ + )) { \ + return; \ + } \ + } \ + } \ + IF_LISTENED_END(EVENT_TYPES::onRedStoneUpdate); \ + origin(blockEvent); \ + } + +#define REDSTONE_EVNET_HOOK_2(BLOCK) \ + LL_TYPE_INSTANCE_HOOK( \ + BLOCK##Hook, \ + HookPriority::Normal, \ + BLOCK, \ + &BLOCK::_onRedstoneUpdate, \ + void, \ + BlockEvents::BlockRedstoneUpdateEvent& blockEvent \ + ) { \ + IF_LISTENED(EVENT_TYPES::onRedStoneUpdate) { \ + if (checkClientIsServerThread()) { \ + if (!RedstoneUpdateEvent( \ + blockEvent.mRegion, \ + blockEvent.mPos, \ + blockEvent.mSignalLevel, \ + blockEvent.mIsFirstTime \ + )) { \ + return; \ + } \ + } \ + } \ + IF_LISTENED_END(EVENT_TYPES::onRedStoneUpdate); \ + origin(blockEvent); \ + } + +REDSTONE_EVNET_HOOK_OLD(HopperBlock) +REDSTONE_EVNET_HOOK_OLD(CrafterBlock) +REDSTONE_EVNET_HOOK_OLD(CommandBlock) +REDSTONE_EVNET_HOOK_OLD(BigDripleafBlock) +REDSTONE_EVNET_HOOK_OLD(CopperBulbBlock) +REDSTONE_EVNET_HOOK_OLD(DoorBlock) +REDSTONE_EVNET_HOOK_OLD(FenceGateBlock) +REDSTONE_EVNET_HOOK_OLD(DispenserBlock) +REDSTONE_EVNET_HOOK_OLD(StructureBlock) +REDSTONE_EVNET_HOOK_OLD(TrapDoorBlock) +REDSTONE_EVNET_HOOK_OLD(NoteBlock) +REDSTONE_EVNET_HOOK_OLD(RedstoneLampBlock) +REDSTONE_EVNET_HOOK_OLD(TntBlock) + +REDSTONE_EVNET_HOOK_1(BaseRailBlock) +REDSTONE_EVNET_HOOK_1(PoweredRailBlock) +REDSTONE_EVNET_HOOK_1(ActivatorRailBlock) + +REDSTONE_EVNET_HOOK_2(RedStoneWireBlock) +REDSTONE_EVNET_HOOK_2(RedstoneTorchBlock) +REDSTONE_EVNET_HOOK_2(ComparatorBlock) -#undef REDSTONEHOOK +#undef REDSTONE_EVNET_HOOK_OLD +#undef REDSTONE_EVNET_HOOK } // namespace redstone @@ -373,9 +446,7 @@ LL_TYPE_INSTANCE_HOOK( uchar flowFromDirection ) { IF_LISTENED(EVENT_TYPES::onLiquidFlow) { - auto ins = ll::service::getServerInstance(); - if (ins && std::this_thread::get_id() == ins->mServerInstanceThread->get_id() - && liquidBlockCanSpreadTo(*this, region, pos, flowFromPos, flowFromDirection)) { + if (checkClientIsServerThread() && liquidBlockCanSpreadTo(*this, region, pos, flowFromPos, flowFromDirection)) { if (!CallEvent( EVENT_TYPES::onLiquidFlow, region.isInstaticking(pos) ? Local() : BlockClass::newBlock(pos, region.getDimensionId()), @@ -400,23 +471,25 @@ LL_TYPE_INSTANCE_HOOK( bool& markForSaving ) { IF_LISTENED(EVENT_TYPES::onCmdBlockExecute) { - if (commandOrigin.getOriginType() == CommandOriginType::MinecartCommandBlock) { - if (!CallEvent( - EVENT_TYPES::onCmdBlockExecute, - String::newString(this->mCommand), - FloatPos::newPos(commandOrigin.getEntity()->getPosition(), region.getDimensionId()), - Boolean::newBoolean(true) - )) { - return false; - } - } else { - if (!CallEvent( - EVENT_TYPES::onCmdBlockExecute, - String::newString(this->mCommand), - FloatPos::newPos(commandOrigin.getBlockPosition(), region.getDimensionId()), - Boolean::newBoolean(false) - )) { - return false; + if (checkClientIsServerThread()) { + if (commandOrigin.getOriginType() == CommandOriginType::MinecartCommandBlock) { + if (!CallEvent( + EVENT_TYPES::onCmdBlockExecute, + String::newString(this->mCommand), + FloatPos::newPos(commandOrigin.getEntity()->getPosition(), region.getDimensionId()), + Boolean::newBoolean(true) + )) { + return false; + } + } else { + if (!CallEvent( + EVENT_TYPES::onCmdBlockExecute, + String::newString(this->mCommand), + FloatPos::newPos(commandOrigin.getBlockPosition(), region.getDimensionId()), + Boolean::newBoolean(false) + )) { + return false; + } } } } @@ -438,8 +511,10 @@ LL_TYPE_INSTANCE_HOOK( Container& toContainer, Vec3 const& pos ) { - hopperStatus = HopperStatus::PullIn; - hopperPos = pos; + if (checkClientIsServerThread()) { + hopperStatus = HopperStatus::PullIn; + hopperPos = pos; + } return origin(region, toContainer, pos); } @@ -454,8 +529,10 @@ LL_TYPE_INSTANCE_HOOK( Vec3 const& position, int attachedFace ) { - hopperStatus = HopperStatus::PullOut; - hopperPos = position; + if (checkClientIsServerThread()) { + hopperStatus = HopperStatus::PullOut; + hopperPos = position; + } return origin(region, fromContainer, position, attachedFace); } @@ -473,7 +550,7 @@ LL_TYPE_INSTANCE_HOOK( int itemCount ) { IF_LISTENED(EVENT_TYPES::onHopperSearchItem) { - if (hopperStatus == HopperStatus::PullIn) { + if (checkClientIsServerThread() && hopperStatus == HopperStatus::PullIn) { if (!CallEvent( EVENT_TYPES::onHopperSearchItem, FloatPos::newPos(hopperPos, region.getDimensionId()), @@ -486,7 +563,7 @@ LL_TYPE_INSTANCE_HOOK( } IF_LISTENED_END(EVENT_TYPES::onHopperSearchItem); IF_LISTENED(EVENT_TYPES::onHopperPushOut) { - if (hopperStatus == HopperStatus::PullOut) { + if (checkClientIsServerThread() && hopperStatus == HopperStatus::PullOut) { if (!CallEvent( EVENT_TYPES::onHopperPushOut, FloatPos::newPos(hopperPos, region.getDimensionId()), @@ -514,7 +591,6 @@ void BlockExplodedEvent() { BlockExplodedHook ::hook(); } void RedstoneUpdateEvent() { redstone::RedstoneTorchBlockHook::hook(); redstone::RedStoneWireBlockHook::hook(); - redstone::DiodeBlockHook::hook(); redstone::ComparatorBlockHook::hook(); redstone::HopperBlockHook::hook(); redstone::CrafterBlockHook::hook(); @@ -543,4 +619,4 @@ void HopperEvent(bool pullIn) { hopper::HopperPushOutHook::hook(); } } -} // namespace lse::events::block \ No newline at end of file +} // namespace lse::events::block diff --git a/src/lse/events/EntityEvents.cpp b/src/lse/events/EntityEvents.cpp index c409e1c0..6e919cfe 100644 --- a/src/lse/events/EntityEvents.cpp +++ b/src/lse/events/EntityEvents.cpp @@ -6,10 +6,9 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" -#include "ll/api/service/GamingStatus.h" +#include "lse/api/Thread.h" #include "lse/api/helper/BlockHelper.h" #include "mc/common/Globals.h" -#include "mc/deps/ecs/gamerefs_entity/EntityContext.h" #include "mc/deps/shared_types/legacy/actor/ActorDamageCause.h" #include "mc/entity/components_json_legacy/NpcComponent.h" #include "mc/entity/components_json_legacy/ProjectileComponent.h" @@ -21,12 +20,10 @@ #include "mc/world/actor/Mob.h" #include "mc/world/actor/VanillaActorRendererId.h" #include "mc/world/actor/boss/WitherBoss.h" -#include "mc/world/actor/npc/ActionContainer.h" #include "mc/world/actor/npc/CommandAction.h" #include "mc/world/actor/npc/StoredCommand.h" #include "mc/world/actor/npc/UrlAction.h" #include "mc/world/actor/player/Player.h" -#include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" #include "mc/world/events/ActorEventCoordinator.h" #include "mc/world/item/CrossbowItem.h" @@ -40,6 +37,8 @@ #include "mc/world/phys/HitResult.h" namespace lse::events::entity { +using api::thread::checkClientIsServerThread; + LL_TYPE_INSTANCE_HOOK( ProjectileSpawnHook1, HookPriority::Normal, @@ -53,25 +52,29 @@ LL_TYPE_INSTANCE_HOOK( Vec3 const& direction ) { IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { - static auto& tridentName = EntityCanonicalName(ActorType::Trident); - if (id.mCanonicalName.get() != tridentName) { - if (!CallEvent( - EVENT_TYPES::onSpawnProjectile, - EntityClass::newEntity(spawner), - String::newString(id.mCanonicalName->getString()) - )) { - return nullptr; + if (checkClientIsServerThread()) { + static auto& tridentName = EntityCanonicalName(ActorType::Trident); + if (id.mCanonicalName != tridentName) { + if (!CallEvent( + EVENT_TYPES::onSpawnProjectile, + EntityClass::newEntity(spawner), + String::newString(id.mCanonicalName->getString()) + )) { + return nullptr; + } } } } IF_LISTENED_END(EVENT_TYPES::onSpawnProjectile); Actor* projectile = origin(region, id, spawner, position, direction); IF_LISTENED(EVENT_TYPES::onProjectileCreated) { - CallEvent( // Not nancellable + if (checkClientIsServerThread()) { + CallEvent( // Not nancellable EVENT_TYPES::onProjectileCreated, EntityClass::newEntity(spawner), EntityClass::newEntity(projectile) ); + } } IF_LISTENED_END(EVENT_TYPES::onProjectileCreated); return projectile; @@ -87,12 +90,14 @@ LL_TYPE_INSTANCE_HOOK( Player& player ) { IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { - if (!CallEvent( - EVENT_TYPES::onSpawnProjectile, - EntityClass::newEntity(&player), - String::newString(projectileInstance.getTypeName()) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSpawnProjectile, + EntityClass::newEntity(&player), + String::newString(projectileInstance.getTypeName()) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onSpawnProjectile); @@ -110,12 +115,14 @@ LL_TYPE_INSTANCE_HOOK( int durationLeft ) { IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { - if (!CallEvent( - EVENT_TYPES::onSpawnProjectile, - EntityClass::newEntity(player), - String::newString(VanillaActorRendererId::trident().getString()) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSpawnProjectile, + EntityClass::newEntity(player), + String::newString(VanillaActorRendererId::trident().getString()) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onSpawnProjectile); @@ -124,8 +131,10 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(ActorRideHook, HookPriority::Normal, Actor, &Actor::$canAddPassenger, bool, Actor& passenger) { IF_LISTENED(EVENT_TYPES::onRide) { - if (!CallEvent(EVENT_TYPES::onRide, EntityClass::newEntity(&passenger), EntityClass::newEntity(this))) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onRide, EntityClass::newEntity(&passenger), EntityClass::newEntity(this))) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onRide); @@ -145,13 +154,15 @@ LL_TYPE_INSTANCE_HOOK( WitherBoss::WitherAttackType type ) { IF_LISTENED(EVENT_TYPES::onWitherBossDestroy) { - if (!CallEvent( - EVENT_TYPES::onWitherBossDestroy, - EntityClass::newEntity(this), - IntPos::newPos(bb.min, region.getDimensionId()), - IntPos::newPos(bb.max, region.getDimensionId()) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onWitherBossDestroy, + EntityClass::newEntity(this), + IntPos::newPos(bb.min, region.getDimensionId()), + IntPos::newPos(bb.max, region.getDimensionId()) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onWitherBossDestroy); @@ -168,7 +179,7 @@ LL_TYPE_INSTANCE_HOOK( HitResult const& res ) { IF_LISTENED(EVENT_TYPES::onProjectileHitEntity) { - if (res.getEntity()) { + if (checkClientIsServerThread() && res.getEntity()) { if (!CallEvent( EVENT_TYPES::onProjectileHitEntity, EntityClass::newEntity(res.getEntity()), @@ -192,15 +203,17 @@ LL_TYPE_INSTANCE_HOOK( ::HitResult const& res ) { IF_LISTENED(EVENT_TYPES::onProjectileHitBlock) { - auto& region = owner.getDimensionBlockSourceConst(); - auto& block = region.getBlock(res.mBlock); - if (res.mType == HitResultType::Tile && res.mBlock != BlockPos::ZERO() && !block.isAir()) { - if (!CallEvent( - EVENT_TYPES::onProjectileHitBlock, - BlockClass::newBlock(block, res.mBlock, region), - EntityClass::newEntity(&owner) - )) { - return; + if (checkClientIsServerThread()) { + auto& region = owner.getDimensionBlockSourceConst(); + auto& block = region.getBlock(res.mBlock); + if (res.mType == HitResultType::Tile && res.mBlock != BlockPos::ZERO() && !block.isAir()) { + if (!CallEvent( + EVENT_TYPES::onProjectileHitBlock, + BlockClass::newBlock(block, res.mBlock, region), + EntityClass::newEntity(&owner) + )) { + return; + } } } } @@ -220,24 +233,26 @@ LL_TYPE_INSTANCE_HOOK( bool ignite ) { IF_LISTENED(EVENT_TYPES::onMobHurt) { - // LeviLamina's ActorHurtEvent can't handle fire hurt, so we just hook Mob::$_hurt. - Actor* damageSource = nullptr; - if (source.isEntitySource()) { - if (source.isChildEntitySource()) { - damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); - } else { - damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + if (checkClientIsServerThread()) { + // LeviLamina's ActorHurtEvent can't handle fire hurt, so we just hook Mob::$_hurt. + Actor* damageSource = nullptr; + if (source.isEntitySource()) { + if (source.isChildEntitySource()) { + damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); + } else { + damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + } } - } - if (!CallEvent( - EVENT_TYPES::onMobHurt, - EntityClass::newEntity(this), - damageSource ? EntityClass::newEntity(damageSource) : Local(), - Number::newNumber(damage < 0.0f ? -damage : damage), - Number::newNumber((int)source.mCause) - )) { - return false; + if (!CallEvent( + EVENT_TYPES::onMobHurt, + EntityClass::newEntity(this), + damageSource ? EntityClass::newEntity(damageSource) : Local(), + Number::newNumber(damage < 0.0f ? -damage : damage), + Number::newNumber((int)source.mCause) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onMobHurt) @@ -254,27 +269,29 @@ LL_TYPE_INSTANCE_HOOK( float damage ) { IF_LISTENED(EVENT_TYPES::onMobHurt) { - // Mob is still hurt after hook Mob::$hurtEffects, and all hurt events are handled by this function, but we just - // need magic damage. - if (source.mCause == SharedTypes::Legacy::ActorDamageCause::Magic - || source.mCause == SharedTypes::Legacy::ActorDamageCause::Wither) { - Actor* damageSource = nullptr; - if (source.isEntitySource()) { - if (source.isChildEntitySource()) { - damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); - } else { - damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + if (checkClientIsServerThread()) { + // Mob is still hurt after hook Mob::$hurtEffects, and all hurt events are handled by this function, but we + // just need magic damage. + if (source.mCause == SharedTypes::Legacy::ActorDamageCause::Magic + || source.mCause == SharedTypes::Legacy::ActorDamageCause::Wither) { + Actor* damageSource = nullptr; + if (source.isEntitySource()) { + if (source.isChildEntitySource()) { + damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); + } else { + damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + } } - } - if (!CallEvent( - EVENT_TYPES::onMobHurt, - EntityClass::newEntity(this), - damageSource ? EntityClass::newEntity(damageSource) : Local(), - Number::newNumber(damage < 0.0f ? -damage : damage), - Number::newNumber((int)source.mCause) - )) { - return 0.0f; + if (!CallEvent( + EVENT_TYPES::onMobHurt, + EntityClass::newEntity(this), + damageSource ? EntityClass::newEntity(damageSource) : Local(), + Number::newNumber(damage < 0.0f ? -damage : damage), + Number::newNumber((int)source.mCause) + )) { + return 0.0f; + } } } } @@ -294,24 +311,26 @@ LL_TYPE_INSTANCE_HOOK( ::std::string const& sceneName ) { IF_LISTENED(EVENT_TYPES::onNpcCmd) { - auto& action = - owner.getEntityContext().tryGetComponent()->mActionsContainer->mActions->at(actionIndex); - if (std::holds_alternative(action)) { - auto& commands = std::get(action).commands; - std::string command; - for (auto& cmd : commands.get()) { - command += cmd.rawCommand.get() + ";"; - } - if (!commands->empty()) { - command.pop_back(); - } - if (!CallEvent( - EVENT_TYPES::onNpcCmd, - EntityClass::newEntity(&owner), - PlayerClass::newPlayer(&sourcePlayer), - String::newString(command) - )) { - return; + if (checkClientIsServerThread()) { + auto& action = + owner.getEntityContext().tryGetComponent()->mActionsContainer->mActions->at(actionIndex); + if (std::holds_alternative(action)) { + auto& commands = std::get(action).commands; + std::string command; + for (auto& cmd : commands.get()) { + command += cmd.rawCommand.get() + ";"; + } + if (!commands->empty()) { + command.pop_back(); + } + if (!CallEvent( + EVENT_TYPES::onNpcCmd, + EntityClass::newEntity(&owner), + PlayerClass::newPlayer(&sourcePlayer), + String::newString(command) + )) { + return; + } } } } @@ -328,7 +347,7 @@ LL_TYPE_INSTANCE_HOOK( MobEffectInstance& effect ) { IF_LISTENED(EVENT_TYPES::onEffectUpdated) { - if (isPlayer()) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onEffectUpdated, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -357,11 +376,13 @@ LL_TYPE_INSTANCE_HOOK( ::Level const& level ) { IF_LISTENED(EVENT_TYPES::onEntityTransformation) { - CallEvent( - EVENT_TYPES::onEntityTransformation, - String::newString(std::to_string(originalActor.getOrCreateUniqueID().rawID)), - EntityClass::newEntity(&transformed) - ); + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onEntityTransformation, + String::newString(std::to_string(originalActor.getOrCreateUniqueID().rawID)), + EntityClass::newEntity(&transformed) + ); + } } IF_LISTENED_END(EVENT_TYPES::onEntityTransformation); @@ -376,31 +397,37 @@ LL_TYPE_INSTANCE_HOOK( CoordinatorResult, EventRef> const& event ) { - bool canceled = event.get().visit([&](auto&& arg) { - if constexpr (std::is_same_v, Details::ValueOrRef>) { - IF_LISTENED(EVENT_TYPES::onEndermanTakeBlock) { - auto& griefingEvent = arg.value(); - auto entity = griefingEvent.mActorContext->tryUnwrap(); - if (entity && entity->isType(ActorType::EnderMan)) { - if (!CallEvent( - EVENT_TYPES::onEndermanTakeBlock, - EntityClass::newEntity(entity.as_ptr()), - BlockClass::newBlock( - *griefingEvent.mBlock, - BlockPos(griefingEvent.mPos), - entity->getDimensionId().id - ), - IntPos::newPos(BlockPos(griefingEvent.mPos), entity->getDimensionId().id) - )) { - return true; + + IF_LISTENED(EVENT_TYPES::onEndermanTakeBlock) { + if (checkClientIsServerThread()) { + bool canceled = event.get().visit([&](auto&& arg) { + if constexpr (std::is_same_v< + std::decay_t, + Details::ValueOrRef>) { + auto& griefingEvent = arg.value(); + auto entity = griefingEvent.mActorContext->tryUnwrap(); + if (entity && entity->isType(ActorType::EnderMan)) { + if (!CallEvent( + EVENT_TYPES::onEndermanTakeBlock, + EntityClass::newEntity(entity.as_ptr()), + BlockClass::newBlock( + *griefingEvent.mBlock, + BlockPos(griefingEvent.mPos), + entity->getDimensionId().id + ), + IntPos::newPos(BlockPos(griefingEvent.mPos), entity->getDimensionId().id) + )) { + return true; + } } } - } - IF_LISTENED_END(EVENT_TYPES::onEndermanTakeBlock); + return false; + }); + if (canceled) return CoordinatorResult::Cancel; } - return false; - }); - if (canceled) return CoordinatorResult::Cancel; + } + IF_LISTENED_END(EVENT_TYPES::onEndermanTakeBlock); + return origin(event); } @@ -422,4 +449,4 @@ void NpcCommandEvent() { NpcCommandHook::hook(); } void EndermanTakeBlockEvent() { EndermanTakeBlockHook::hook(); } void EffectUpdateEvent() { EffectUpdateHook::hook(); } void TransformationEvent() { TransformationHook::hook(); } -} // namespace lse::events::entity \ No newline at end of file +} // namespace lse::events::entity diff --git a/src/lse/events/OtherEvents.cpp b/src/lse/events/OtherEvents.cpp index 2e83c0ff..83e6e0a1 100644 --- a/src/lse/events/OtherEvents.cpp +++ b/src/lse/events/OtherEvents.cpp @@ -2,11 +2,10 @@ #include "legacy/api/PlayerAPI.h" #include "ll/api/memory/Hook.h" #include "ll/api/service/Bedrock.h" -#include "mc/legacy/ActorRuntimeID.h" +#include "lse/api/Thread.h" #include "mc/legacy/ActorUniqueID.h" #include "mc/world/scores/IdentityDefinition.h" #include "mc/world/scores/Objective.h" -#include "mc/world/scores/PlayerScoreboardId.h" #include "mc/world/scores/ScoreInfo.h" #include "mc/world/scores/ScoreboardId.h" #include "mc/world/scores/ServerScoreboard.h" @@ -22,18 +21,20 @@ LL_TYPE_INSTANCE_HOOK( Objective const& obj ) { IF_LISTENED(EVENT_TYPES::onScoreChanged) { - auto& idRef = id.mIdentityDef; - if (idRef && idRef->mIdentityType == IdentityDefinition::Type::Player) { - if (!CallEvent( - EVENT_TYPES::onScoreChanged, - PlayerClass::newPlayer( - ll::service::getLevel()->getPlayer(ActorUniqueID(idRef->mPlayerId->mActorUniqueId)) - ), - Number::newNumber(obj.getPlayerScore(id).mValue), - String::newString(obj.mName), - String::newString(obj.mDisplayName) - )) { - return; + if (api::thread::checkClientIsServerThread()) { + auto& idRef = id.mIdentityDef; + if (idRef && idRef->mIdentityType == IdentityDefinition::Type::Player) { + if (!CallEvent( + EVENT_TYPES::onScoreChanged, + PlayerClass::newPlayer( + ll::service::getLevel()->getPlayer(ActorUniqueID(idRef->mPlayerId->mActorUniqueId)) + ), + Number::newNumber(obj.getPlayerScore(id).mValue), + String::newString(obj.mName), + String::newString(obj.mDisplayName) + )) { + return; + } } } } @@ -42,4 +43,4 @@ LL_TYPE_INSTANCE_HOOK( } void ScoreChangedEvent() { ScoreChangedHook::hook(); } -} // namespace lse::events::other \ No newline at end of file +} // namespace lse::events::other diff --git a/src/lse/events/PlayerEvents.cpp b/src/lse/events/PlayerEvents.cpp index e6734ead..80bc5c8f 100644 --- a/src/lse/events/PlayerEvents.cpp +++ b/src/lse/events/PlayerEvents.cpp @@ -7,8 +7,10 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" +#include "lse/api/Thread.h" #include "mc/deps/ecs/WeakEntityRef.h" #include "mc/network/ServerPlayerBlockUseHandler.h" +#include "mc/server/ServerInstance.h" #include "mc/server/ServerPlayer.h" #include "mc/server/module/VanillaServerGameplayEventListener.h" #include "mc/world/ContainerID.h" @@ -19,8 +21,6 @@ #include "mc/world/actor/player/Inventory.h" #include "mc/world/actor/player/Player.h" #include "mc/world/actor/player/PlayerInventory.h" -#include "mc/world/actor/player/PlayerItemInUse.h" -#include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" #include "mc/world/events/BlockEventCoordinator.h" #include "mc/world/events/EventResult.h" @@ -52,6 +52,8 @@ #include "mc/world/phys/HitResult.h" namespace lse::events::player { +using api::thread::checkClientIsServerThread; + LL_TYPE_INSTANCE_HOOK( DropItemHook1, HookPriority::Normal, @@ -62,12 +64,14 @@ LL_TYPE_INSTANCE_HOOK( bool randomly ) { IF_LISTENED(EVENT_TYPES::onDropItem) { - if (!CallEvent( - EVENT_TYPES::onDropItem, - PlayerClass::newPlayer(this), - ItemClass::newItem(&const_cast(item)) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onDropItem, + PlayerClass::newPlayer(this), + ItemClass::newItem(&const_cast(item)) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onDropItem); @@ -83,8 +87,9 @@ LL_TYPE_INSTANCE_HOOK( Player& player, bool isSenderAuthority ) { - if (mType == ComplexInventoryTransaction::Type::NormalTransaction) { - IF_LISTENED(EVENT_TYPES::onDropItem) { + + IF_LISTENED(EVENT_TYPES::onDropItem) { + if (checkClientIsServerThread() && mType == ComplexInventoryTransaction::Type::NormalTransaction) { InventorySource source{ InventorySourceType::ContainerInventory, ContainerID::Inventory, @@ -103,8 +108,8 @@ LL_TYPE_INSTANCE_HOOK( } } } - IF_LISTENED_END(EVENT_TYPES::onDropItem); } + IF_LISTENED_END(EVENT_TYPES::onDropItem); return origin(player, isSenderAuthority); } @@ -117,14 +122,16 @@ LL_TYPE_INSTANCE_HOOK( struct PlayerOpenContainerEvent const& playerOpenContainerEvent ) { IF_LISTENED(EVENT_TYPES::onOpenContainer) { - Actor* actor = static_cast((void*)&playerOpenContainerEvent)->tryUnwrap(); - if (actor && actor->isType(ActorType::Player)) { - if (!CallEvent( - EVENT_TYPES::onOpenContainer, - PlayerClass::newPlayer(static_cast(actor)), - BlockClass::newBlock(playerOpenContainerEvent.mBlockPos, actor->getDimensionId().id) - )) { - return EventResult::StopProcessing; + if (checkClientIsServerThread()) { + Actor* actor = static_cast((void*)&playerOpenContainerEvent)->tryUnwrap(); + if (actor && actor->isType(ActorType::Player)) { + if (!CallEvent( + EVENT_TYPES::onOpenContainer, + PlayerClass::newPlayer(static_cast(actor)), + BlockClass::newBlock(playerOpenContainerEvent.mBlockPos, actor->getDimensionId().id) + )) { + return EventResult::StopProcessing; + } } } } @@ -141,7 +148,7 @@ LL_TYPE_INSTANCE_HOOK( Actor& actor ) { IF_LISTENED(EVENT_TYPES::onCloseContainer) { - if (actor.isPlayer()) { + if (checkClientIsServerThread() && actor.isPlayer()) { Player& player = static_cast(actor); if (!CallEvent( EVENT_TYPES::onCloseContainer, @@ -165,7 +172,7 @@ LL_TYPE_INSTANCE_HOOK( Actor& actor ) { IF_LISTENED(EVENT_TYPES::onCloseContainer) { - if (actor.isPlayer()) { + if (checkClientIsServerThread() && actor.isPlayer()) { Player& player = static_cast(actor); if (!CallEvent( EVENT_TYPES::onCloseContainer, @@ -193,14 +200,16 @@ LL_TYPE_INSTANCE_HOOK( bool forceBalanced ) { IF_LISTENED(EVENT_TYPES::onInventoryChange) { - if (!CallEvent( - EVENT_TYPES::onInventoryChange, - PlayerClass::newPlayer(this), - slot, - ItemClass::newItem(&const_cast(oldItem)), - ItemClass::newItem(&const_cast(newItem)) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onInventoryChange, + PlayerClass::newPlayer(this), + slot, + ItemClass::newItem(&const_cast(oldItem)), + ItemClass::newItem(&const_cast(newItem)) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onInventoryChange); @@ -216,31 +225,33 @@ LL_STATIC_HOOK( const BlockPos& pos, int face ) { - bool isCancelled = false; - IF_LISTENED(EVENT_TYPES::onAttackBlock) { - ItemStack const& item = player.getSelectedItem(); - if (!CallEvent( - EVENT_TYPES::onAttackBlock, - PlayerClass::newPlayer(&player), - BlockClass::newBlock(pos, player.getDimensionId().id), - !item.isNull() ? ItemClass::newItem(&const_cast(item)) : Local() - )) { - isCancelled = true; + if (checkClientIsServerThread()) { + bool isCancelled = false; + IF_LISTENED(EVENT_TYPES::onAttackBlock) { + ItemStack const& item = player.getSelectedItem(); + if (!CallEvent( + EVENT_TYPES::onAttackBlock, + PlayerClass::newPlayer(&player), + BlockClass::newBlock(pos, player.getDimensionId().id), + !item.isNull() ? ItemClass::newItem(&const_cast(item)) : Local() + )) { + isCancelled = true; + } } - } - IF_LISTENED_END(EVENT_TYPES::onAttackBlock); - IF_LISTENED(EVENT_TYPES::onStartDestroyBlock) { - if (!CallEvent( - EVENT_TYPES::onStartDestroyBlock, - PlayerClass::newPlayer(&player), - BlockClass::newBlock(pos, player.getDimensionId().id) - )) { - isCancelled = true; + IF_LISTENED_END(EVENT_TYPES::onAttackBlock); + IF_LISTENED(EVENT_TYPES::onStartDestroyBlock) { + if (!CallEvent( + EVENT_TYPES::onStartDestroyBlock, + PlayerClass::newPlayer(&player), + BlockClass::newBlock(pos, player.getDimensionId().id) + )) { + isCancelled = true; + } + } + IF_LISTENED_END(EVENT_TYPES::onStartDestroyBlock) + if (isCancelled) { + return; } - } - IF_LISTENED_END(EVENT_TYPES::onStartDestroyBlock) - if (isCancelled) { - return; } return origin(player, pos, face); } @@ -254,13 +265,15 @@ LL_TYPE_INSTANCE_HOOK( BlockEvents::BlockPlayerInteractEvent& eventData ) { IF_LISTENED(EVENT_TYPES::onUseFrameBlock) { - Player& player = eventData.mPlayer; - if (!CallEvent( - EVENT_TYPES::onUseFrameBlock, - PlayerClass::newPlayer(&player), - BlockClass::newBlock(eventData.mPos, player.getDimensionId().id) - )) { - return; + if (checkClientIsServerThread()) { + Player& player = eventData.mPlayer; + if (!CallEvent( + EVENT_TYPES::onUseFrameBlock, + PlayerClass::newPlayer(&player), + BlockClass::newBlock(eventData.mPos, player.getDimensionId().id) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onUseFrameBlock); @@ -277,12 +290,14 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onUseFrameBlock) { - if (!CallEvent( - EVENT_TYPES::onUseFrameBlock, - PlayerClass::newPlayer(player), - BlockClass::newBlock(pos, player->getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseFrameBlock, + PlayerClass::newPlayer(player), + BlockClass::newBlock(pos, player->getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseFrameBlock); @@ -291,13 +306,20 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(EatHook, HookPriority::Normal, Player, &Player::completeUsingItem, void) { IF_LISTENED(EVENT_TYPES::onAte) { - const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; - auto checked = mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); - if (checked - && !CallEvent(EVENT_TYPES::onAte, PlayerClass::newPlayer(this), ItemClass::newItem(&*mItemInUse->mItem))) - stopUsingItem(); - else origin(); - return; + if (checkClientIsServerThread()) { + const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; + auto checked = + mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); + if (checked + && !CallEvent( + EVENT_TYPES::onAte, + PlayerClass::newPlayer(this), + ItemClass::newItem(&*mItemInUse->mItem) + )) + stopUsingItem(); + else origin(); + return; + } } IF_LISTENED_END(EVENT_TYPES::onAte); origin(); @@ -313,12 +335,14 @@ LL_TYPE_INSTANCE_HOOK( ChangeDimensionRequest&& changeRequest ) { IF_LISTENED(EVENT_TYPES::onChangeDim) { - if (!CallEvent( - EVENT_TYPES::onChangeDim, - PlayerClass::newPlayer(&player), - Number::newNumber(changeRequest.mToDimensionId->id) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onChangeDim, + PlayerClass::newPlayer(&player), + Number::newNumber(changeRequest.mToDimensionId->id) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onChangeDim); @@ -334,8 +358,10 @@ LL_TYPE_INSTANCE_HOOK( ContainerScreenContext const& screenContext ) { IF_LISTENED(EVENT_TYPES::onOpenContainerScreen) { - if (!CallEvent(EVENT_TYPES::onOpenContainerScreen, PlayerClass::newPlayer(&mPlayer))) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onOpenContainerScreen, PlayerClass::newPlayer(&mPlayer))) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onOpenContainerScreen); @@ -354,12 +380,14 @@ LL_TYPE_STATIC_HOOK( class Level& level ) { IF_LISTENED(EVENT_TYPES::onUseRespawnAnchor) { - if (!CallEvent( - EVENT_TYPES::onUseRespawnAnchor, - PlayerClass::newPlayer(&player), - IntPos::newPos(pos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseRespawnAnchor, + PlayerClass::newPlayer(&player), + IntPos::newPos(pos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseRespawnAnchor); @@ -375,12 +403,14 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onBedEnter) { - if (!CallEvent( - EVENT_TYPES::onBedEnter, - PlayerClass::newPlayer(this), - IntPos::newPos(pos, this->getDimensionId().id) - )) { - return BedSleepingResult::Ok; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onBedEnter, + PlayerClass::newPlayer(this), + IntPos::newPos(pos, this->getDimensionId().id) + )) { + return BedSleepingResult::Ok; + } } } IF_LISTENED_END(EVENT_TYPES::onBedEnter); @@ -388,8 +418,10 @@ LL_TYPE_INSTANCE_HOOK( } LL_TYPE_INSTANCE_HOOK(OpenInventoryHook, HookPriority::Normal, ServerPlayer, &ServerPlayer::$openInventory, void, ) { IF_LISTENED(EVENT_TYPES::onOpenInventory) { - if (!CallEvent(EVENT_TYPES::onOpenInventory, PlayerClass::newPlayer(this))) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onOpenInventory, PlayerClass::newPlayer(this))) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onOpenInventory); @@ -406,14 +438,17 @@ LL_TYPE_INSTANCE_HOOK( float inSpeed ) { IF_LISTENED(EVENT_TYPES::onPlayerPullFishingHook) { - if (!CallEvent( - EVENT_TYPES::onPlayerPullFishingHook, - PlayerClass::newPlayer(this->getPlayerOwner()), - EntityClass::newEntity(&inEntity), - inEntity.isType(ActorType::ItemEntity) ? ItemClass::newItem(&static_cast(inEntity).item()) - : Local() - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onPlayerPullFishingHook, + PlayerClass::newPlayer(this->getPlayerOwner()), + EntityClass::newEntity(&inEntity), + inEntity.isType(ActorType::ItemEntity) + ? ItemClass::newItem(&static_cast(inEntity).item()) + : Local() + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onPlayerPullFishingHook); @@ -434,15 +469,17 @@ LL_TYPE_INSTANCE_HOOK( uchar face ) { IF_LISTENED(EVENT_TYPES::onUseBucketPlace) { - if (!CallEvent( - EVENT_TYPES::onUseBucketPlace, - PlayerClass::newPlayer(static_cast(placer)), - ItemClass::newItem(&const_cast(instance)), - BlockClass::newBlock(contents, pos, region), - Number::newNumber(face), - FloatPos::newPos(pos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseBucketPlace, + PlayerClass::newPlayer(static_cast(placer)), + ItemClass::newItem(&const_cast(instance)), + BlockClass::newBlock(contents, pos, region), + Number::newNumber(face), + FloatPos::newPos(pos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseBucketPlace); @@ -460,15 +497,17 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onUseBucketTake) { - if (!CallEvent( - EVENT_TYPES::onUseBucketTake, - PlayerClass::newPlayer(&static_cast(entity)), - ItemClass::newItem(&item), - BlockClass::newBlock(pos, entity.getDimensionId().id), - Number::newNumber(-1), - FloatPos::newPos(pos, entity.getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseBucketTake, + PlayerClass::newPlayer(&static_cast(entity)), + ItemClass::newItem(&item), + BlockClass::newBlock(pos, entity.getDimensionId().id), + Number::newNumber(-1), + FloatPos::newPos(pos, entity.getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseBucketTake); @@ -486,52 +525,29 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onUseBucketTake) { - if (!CallEvent( - EVENT_TYPES::onUseBucketTake, - PlayerClass::newPlayer(&static_cast(entity)), - ItemClass::newItem(&item), - BlockClass::newBlock(pos, entity.getDimensionId().id), - Number::newNumber(-1), - FloatPos::newPos(pos, entity.getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseBucketTake, + PlayerClass::newPlayer(&static_cast(entity)), + ItemClass::newItem(&item), + BlockClass::newBlock(pos, entity.getDimensionId().id), + Number::newNumber(-1), + FloatPos::newPos(pos, entity.getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseBucketTake); return origin(item, entity, pos); } -// LL_TYPE_INSTANCE_HOOK( -// UseBucketTakeHook3, -// HookPriority::Normal, -// BucketItem, -// &BucketItem::_useOn, -// InteractionResult, -// ItemStack& instance, -// Actor& entity, -// BlockPos pos, -// uchar face, -// Vec3 const& clickPos -// ) { -// IF_LISTENED(EVENT_TYPES::onUseBucketTake) { -// CallEventRtnValue( -// EVENT_TYPES::onUseBucketTake, -// InteractionResult{InteractionResult::Result::Fail}, -// PlayerClass::newPlayer(), -// ItemClass::newItem(&instance, false), -// EntityClass::newEntity(&entity), -// Number::newNumber(face), -// FloatPos::newPos(pos, entity.getDimensionId().id) -// ); -// } -// IF_LISTENED_END(EVENT_TYPES::onUseBucketTake); -// return origin(instance, entity, pos, face, clickPos); -// } - LL_TYPE_INSTANCE_HOOK(ConsumeTotemHook, HookPriority::Normal, Player, &Player::$consumeTotem, bool) { IF_LISTENED(EVENT_TYPES::onConsumeTotem) { - if (!CallEvent(EVENT_TYPES::onConsumeTotem, PlayerClass::newPlayer(this))) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onConsumeTotem, PlayerClass::newPlayer(this))) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onConsumeTotem); @@ -547,8 +563,9 @@ LL_TYPE_INSTANCE_HOOK( SharedTypes::Legacy::ArmorSlot const armorSlot, ItemStack const& item ) { - if (isPlayer()) { - IF_LISTENED(EVENT_TYPES::onSetArmor) { + + IF_LISTENED(EVENT_TYPES::onSetArmor) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onSetArmor, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -558,8 +575,8 @@ LL_TYPE_INSTANCE_HOOK( return; } } - IF_LISTENED_END(EVENT_TYPES::onSetArmor); } + IF_LISTENED_END(EVENT_TYPES::onSetArmor); origin(armorSlot, item); } @@ -573,13 +590,15 @@ LL_TYPE_INSTANCE_HOOK( Vec3 const& location ) { IF_LISTENED(EVENT_TYPES::onPlayerInteractEntity) { - if (!CallEvent( - EVENT_TYPES::onPlayerInteractEntity, - PlayerClass::newPlayer(this), - EntityClass::newEntity(&actor), - FloatPos::newPos(location, getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onPlayerInteractEntity, + PlayerClass::newPlayer(this), + EntityClass::newEntity(&actor), + FloatPos::newPos(location, getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onPlayerInteractEntity) @@ -594,8 +613,8 @@ LL_TYPE_INSTANCE_HOOK( void, ::MobEffectInstance const& effect ) { - if (isPlayer()) { - IF_LISTENED(EVENT_TYPES::onEffectAdded) { + IF_LISTENED(EVENT_TYPES::onEffectAdded) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onEffectAdded, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -606,8 +625,8 @@ LL_TYPE_INSTANCE_HOOK( return; } } - IF_LISTENED_END(EVENT_TYPES::onEffectAdded); } + IF_LISTENED_END(EVENT_TYPES::onEffectAdded); origin(effect); } @@ -619,8 +638,8 @@ LL_TYPE_INSTANCE_HOOK( void, ::MobEffectInstance& effect ) { - if (isPlayer()) { - IF_LISTENED(EVENT_TYPES::onEffectRemoved) { + IF_LISTENED(EVENT_TYPES::onEffectRemoved) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onEffectRemoved, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -629,8 +648,8 @@ LL_TYPE_INSTANCE_HOOK( return; } } - IF_LISTENED_END(EVENT_TYPES::onEffectRemoved); } + IF_LISTENED_END(EVENT_TYPES::onEffectRemoved); origin(effect); } diff --git a/src/tests/LSETests/PlayerTests.js b/src/tests/LSETests/PlayerTests.js index 41fdb739..c0d577c2 100644 --- a/src/tests/LSETests/PlayerTests.js +++ b/src/tests/LSETests/PlayerTests.js @@ -1,83 +1,83 @@ -export function TestPlayer(players) { +export function TestPlayer(output, players) { for (let player of players) { - GetFromViewVector(player) - PrintPlayerAttributes(player) + GetFromViewVector(output, player) + PrintPlayerAttributes(output, player) } } -function GetFromViewVector(player) { +function GetFromViewVector(output, player) { let en = player.getEntityFromViewVector(5.25); if (en) { - logger.info(`Entity looking at: ${en.name}`); - logBlock(player.getBlockFromViewVector(true, false, player.distanceTo(en), false)); + output.success(`Entity looking at: ${en.name}`); + logBlock(output, player.getBlockFromViewVector(true, false, player.distanceTo(en), false)); } else { - logger.info(`No entity looking at found`); - logBlock(player.getBlockFromViewVector(true, false, 5.25, false)); + output.success(`No entity looking at found`); + logBlock(output, player.getBlockFromViewVector(true, false, 5.25, false)); } - function logBlock(bl) { + function logBlock(output, bl) { if (bl) { - logger.info(`Block looking at: ${bl.name} ${bl.pos}`); + output.success(`Block looking at: ${bl.name} ${bl.pos}`); } else { - logger.info(`No Block looking at found`); + output.success(`No Block looking at found`); } } } -function PrintPlayerAttributes(player) { - logger.info(`Name: ${player.name}`); - logger.info(`Position: ${player.pos}`); - logger.info(`Feet Position: ${player.feetPos}`); - logger.info(`Block Position: ${player.blockPos}`); - logger.info(`Last Death Position: ${player.lastDeathPos}`); - logger.info(`Real Name: ${player.realName}`); - logger.info(`XUID: ${player.xuid}`); - logger.info(`UUID: ${player.uuid}`); - logger.info(`Permission Level: ${player.permLevel}`); - logger.info(`Game Mode: ${player.gameMode}`); - logger.info(`Can Sleep: ${player.canSleep}`); - logger.info(`Can Fly: ${player.canFly}`); - logger.info(`Can Be Seen On Map: ${player.canBeSeenOnMap}`); - logger.info(`Can Freeze: ${player.canFreeze}`); - logger.info(`Can See Daylight: ${player.canSeeDaylight}`); - logger.info(`Can Show Name Tag: ${player.canShowNameTag}`); - logger.info(`Can Start Sleep In Bed: ${player.canStartSleepInBed}`); - logger.info(`Can Pickup Items: ${player.canPickupItems}`); - logger.info(`Max Health: ${player.maxHealth}`); - logger.info(`Health: ${player.health}`); - logger.info(`In Air: ${player.inAir}`); - logger.info(`In Water: ${player.inWater}`); - logger.info(`In Lava: ${player.inLava}`); - logger.info(`In Rain: ${player.inRain}`); - logger.info(`In Snow: ${player.inSnow}`); - logger.info(`In Wall: ${player.inWall}`); - logger.info(`In Water Or Rain: ${player.inWaterOrRain}`); - logger.info(`In World: ${player.inWorld}`); - logger.info(`In Clouds: ${player.inClouds}`); - logger.info(`Speed: ${player.speed}`); - logger.info(`Direction: ${player.direction}`); - logger.info(`Unique ID: ${player.uniqueId}`); - logger.info(`Language Code: ${player.langCode}`); - logger.info(`Is Loading: ${player.isLoading}`); - logger.info(`Is Invisible: ${player.isInvisible}`); - logger.info(`Is Inside Portal: ${player.isInsidePortal}`); - logger.info(`Is Hurt: ${player.isHurt}`); - logger.info(`Is Trusting: ${player.isTrusting}`); - logger.info(`Is Touching Damage Block: ${player.isTouchingDamageBlock}`); - logger.info(`Is Hungry: ${player.isHungry}`); - logger.info(`Is On Fire: ${player.isOnFire}`); - logger.info(`Is On Ground: ${player.isOnGround}`); - logger.info(`Is On Hot Block: ${player.isOnHotBlock}`); - logger.info(`Is Trading: ${player.isTrading}`); - logger.info(`Is Adventure: ${player.isAdventure}`); - logger.info(`Is Gliding: ${player.isGliding}`); - logger.info(`Is Survival: ${player.isSurvival}`); - logger.info(`Is Spectator: ${player.isSpectator}`); - logger.info(`Is Riding: ${player.isRiding}`); - logger.info(`Is Dancing: ${player.isDancing}`); - logger.info(`Is Creative: ${player.isCreative}`); - logger.info(`Is Flying: ${player.isFlying}`); - logger.info(`Is Sleeping: ${player.isSleeping}`); - logger.info(`Is Moving: ${player.isMoving}`); - logger.info(`Is Sneaking: ${player.isSneaking}`); -} \ No newline at end of file +function PrintPlayerAttributes(output, player) { + output.success(`Name: ${player.name}`); + output.success(`Position: ${player.pos}`); + output.success(`Feet Position: ${player.feetPos}`); + output.success(`Block Position: ${player.blockPos}`); + output.success(`Last Death Position: ${player.lastDeathPos}`); + output.success(`Real Name: ${player.realName}`); + output.success(`XUID: ${player.xuid}`); + output.success(`UUID: ${player.uuid}`); + output.success(`Permission Level: ${player.permLevel}`); + output.success(`Game Mode: ${player.gameMode}`); + output.success(`Can Sleep: ${player.canSleep}`); + output.success(`Can Fly: ${player.canFly}`); + output.success(`Can Be Seen On Map: ${player.canBeSeenOnMap}`); + output.success(`Can Freeze: ${player.canFreeze}`); + output.success(`Can See Daylight: ${player.canSeeDaylight}`); + output.success(`Can Show Name Tag: ${player.canShowNameTag}`); + output.success(`Can Start Sleep In Bed: ${player.canStartSleepInBed}`); + output.success(`Can Pickup Items: ${player.canPickupItems}`); + output.success(`Max Health: ${player.maxHealth}`); + output.success(`Health: ${player.health}`); + output.success(`In Air: ${player.inAir}`); + output.success(`In Water: ${player.inWater}`); + output.success(`In Lava: ${player.inLava}`); + output.success(`In Rain: ${player.inRain}`); + output.success(`In Snow: ${player.inSnow}`); + output.success(`In Wall: ${player.inWall}`); + output.success(`In Water Or Rain: ${player.inWaterOrRain}`); + output.success(`In World: ${player.inWorld}`); + output.success(`In Clouds: ${player.inClouds}`); + output.success(`Speed: ${player.speed}`); + output.success(`Direction: ${player.direction}`); + output.success(`Unique ID: ${player.uniqueId}`); + output.success(`Language Code: ${player.langCode}`); + output.success(`Is Loading: ${player.isLoading}`); + output.success(`Is Invisible: ${player.isInvisible}`); + output.success(`Is Inside Portal: ${player.isInsidePortal}`); + output.success(`Is Hurt: ${player.isHurt}`); + output.success(`Is Trusting: ${player.isTrusting}`); + output.success(`Is Touching Damage Block: ${player.isTouchingDamageBlock}`); + output.success(`Is Hungry: ${player.isHungry}`); + output.success(`Is On Fire: ${player.isOnFire}`); + output.success(`Is On Ground: ${player.isOnGround}`); + output.success(`Is On Hot Block: ${player.isOnHotBlock}`); + output.success(`Is Trading: ${player.isTrading}`); + output.success(`Is Adventure: ${player.isAdventure}`); + output.success(`Is Gliding: ${player.isGliding}`); + output.success(`Is Survival: ${player.isSurvival}`); + output.success(`Is Spectator: ${player.isSpectator}`); + output.success(`Is Riding: ${player.isRiding}`); + output.success(`Is Dancing: ${player.isDancing}`); + output.success(`Is Creative: ${player.isCreative}`); + output.success(`Is Flying: ${player.isFlying}`); + output.success(`Is Sleeping: ${player.isSleeping}`); + output.success(`Is Moving: ${player.isMoving}`); + output.success(`Is Sneaking: ${player.isSneaking}`); +} diff --git a/src/tests/LSETests/main.js b/src/tests/LSETests/main.js index 7bb3c40a..29bb39ab 100644 --- a/src/tests/LSETests/main.js +++ b/src/tests/LSETests/main.js @@ -5,7 +5,7 @@ import {TestPlayer} from './plugins/LSETests/PlayerTests.js'; RegisterEvents(); mc.listen('onServerStarted', () => { - let cmd = mc.newCommand('lsetests', "LegacyScriptEngine tests", PermType.Console); + let cmd = mc.newCommand('lsetests', "LegacyScriptEngine tests", PermType.GameMasters); cmd.setEnum('testOption', ['logger', 'events', 'player']); cmd.mandatory('testOption', ParamType.Enum, 'testOption'); cmd.optional('player', ParamType.Player); @@ -18,10 +18,10 @@ mc.listen('onServerStarted', () => { case 'events': const notTriggeredEvents = events.filter(event => !triggeredEvents.has(event)); - logger.info(`Events not triggered: ${notTriggeredEvents.join(', ')}`); + output.success(`Events not triggered: ${notTriggeredEvents.join(', ')}`); break; case 'player': - TestPlayer(results.player); + TestPlayer(output, results.player); break; default: logger.error(`Invalid test option ${results.testOption}`); diff --git a/tooth.json b/tooth.json index a083c336..44537ac7 100644 --- a/tooth.json +++ b/tooth.json @@ -2,7 +2,7 @@ "format_version": 3, "format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d", "tooth": "github.com/LiteLDev/LegacyScriptEngine", - "version": "0.16.8", + "version": "0.17.0", "info": { "name": "LegacyScriptEngine", "description": "A plugin engine for running LLSE plugins on LeviLamina", @@ -17,23 +17,34 @@ { "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina": "1.9.*", "github.com/LiteLDev/LegacyScriptEngine#quickjs": "{{version}}", "github.com/LiteLDev/LegacyScriptEngine#lua": "{{version}}" } }, + { + "label": "client", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", + "github.com/LiteLDev/LegacyScriptEngine#client_quickjs": "{{version}}", + "github.com/LiteLDev/LegacyScriptEngine#client_lua": "{{version}}" + } + }, { "label": "nodejs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*", + "github.com/LiteLDev/LeviLamina": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*", "git.levimc.org/ShrBox/7-zip": "24.*" }, "assets": [ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-nodejs-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-nodejs-windows-x64.zip" ], "placements": [ { @@ -62,14 +73,15 @@ "label": "quickjs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*" + "github.com/LiteLDev/LeviLamina": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*" }, "assets": [ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-quickjs-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-quickjs-windows-x64.zip" ], "placements": [ { @@ -85,14 +97,15 @@ "label": "lua", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*" + "github.com/LiteLDev/LeviLamina": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*" }, "assets": [ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-lua-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-lua-windows-x64.zip" ], "placements": [ { @@ -108,14 +121,15 @@ "label": "python", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*" + "github.com/LiteLDev/LeviLamina": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*" }, "assets": [ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-python-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-python-windows-x64.zip" ], "placements": [ { @@ -126,6 +140,116 @@ ] } ] + }, + { + "label": "client_nodejs", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*", + "git.levimc.org/ShrBox/7-zip": "24.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-nodejs-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-nodejs/", + "dest": "mods/legacy-script-engine-nodejs/" + } + ] + }, + { + "type": "zip", + "urls": [ + "https://github.com/LiteLDev/node/releases/download/v22.12.0/node-prebuilt.zip" + ], + "placements": [ + { + "type": "dir", + "src": "", + "dest": "mods/legacy-script-engine-nodejs/" + } + ] + } + ] + }, + { + "label": "client_quickjs", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-quickjs-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-quickjs/", + "dest": "mods/legacy-script-engine-quickjs/" + } + ] + } + ] + }, + { + "label": "client_lua", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-lua-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-lua/", + "dest": "mods/legacy-script-engine-lua/" + } + ] + } + ] + }, + { + "label": "client_python", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-python-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-python/", + "dest": "mods/legacy-script-engine-python/" + } + ] + } + ] } ] -} \ No newline at end of file +} diff --git a/xmake.lua b/xmake.lua index baa3e176..d395faff 100644 --- a/xmake.lua +++ b/xmake.lua @@ -1,11 +1,11 @@ add_rules("mode.debug", "mode.release") -add_repositories("levimc-repo https://github.com/LiteLDev/xmake-repo.git") +add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina 1.7.7", {configs = {target_type = "server"}}) + add_requires("levilamina 1.9.0", {configs = {target_type = "server"}}) else - add_requires("levilamina 1.7.7", {configs = {target_type = "client"}}) + add_requires("levilamina 1.9.0", {configs = {target_type = "client"}}) end add_requires("levibuildscript") @@ -22,33 +22,36 @@ add_requires( "ctre 3.8.1" ) +add_requires("openssl3") +add_requires("cpp-httplib 0.26.0", { configs = { ssl = true, zlib = true } }) + if is_config("backend", "lua") then - add_requires("openssl 1.1.1-w") - add_requires("mariadb-connector-c 3.3.9") - add_requires("scriptx 2026.1.10", {configs={backend="Lua"}}) + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "Lua" } }) elseif is_config("backend", "quickjs") then - add_requires("openssl 1.1.1-w") - add_requires("mariadb-connector-c 3.3.9") - add_requires("scriptx 2026.1.10", {configs={backend="QuickJs"}}) + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "QuickJs" } }) elseif is_config("backend", "python") then - add_requires("openssl 1.1.1-w") - add_requires("mariadb-connector-c 3.3.9") - add_requires("scriptx 2026.1.10", {configs={backend="Python"}}) + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "Python" } }) elseif is_config("backend", "nodejs") then - add_requires("scriptx 2026.1.10", {configs={backend="V8"}}) - + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "V8" } }) end -add_requires("openssl3") -add_requires("cpp-httplib 0.26.0", {configs = {ssl = true, zlib = true}}) - if not has_config("vs_runtime") then set_runtimes("MD") end +option("levimc_repo") + set_default("https://github.com/LiteLDev/xmake-repo.git") + set_showmenu(true) + set_description("Set the levimc-repo path or url") +option_end() + option("publish") set_default(false) set_showmenu(true) @@ -64,7 +67,7 @@ option("backend") set_default("lua") set_values("lua", "quickjs", "python", "nodejs") -target("legacy-script-engine") +target("LegacyScriptEngine") add_rules("@levibuildscript/linkrule") add_cxflags( "/EHa", @@ -116,6 +119,15 @@ target("legacy-script-engine") "src/legacy", "$(builddir)/config" ) + if is_config("target_type", "server") then + add_defines("LL_PLAT_S") + add_files("src-server/**.cpp") + add_includedirs("src-server") + else + add_defines("LL_PLAT_C") + add_files("src-client/**.cpp") + add_includedirs("src-client") + end if has_config("publish") then add_defines("LSE_VERSION_PUBLISH") end @@ -206,7 +218,6 @@ target("legacy-script-engine") "LSE_BACKEND_NODEJS" ) remove_files("src/legacy/main/PythonHelper.cpp") - remove_files("src/legacy/legacyapi/db/impl/mysql/*.cpp") set_basename("legacy-script-engine-nodejs") after_build(function(target) local langPath = path.join(os.projectdir(), "src/lang/") @@ -214,4 +225,4 @@ target("legacy-script-engine") os.mkdir(outputPath) os.cp(langPath, outputPath) end) - end \ No newline at end of file + end