diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..faa5215 --- /dev/null +++ b/.clang-format @@ -0,0 +1,5 @@ +Language: Cpp +BasedOnStyle: Google +UseTab: Never +IndentWidth: 4 +NamespaceIndentation: All \ No newline at end of file diff --git a/.gitignore b/.gitignore index 749267a..32839db 100644 --- a/.gitignore +++ b/.gitignore @@ -46,4 +46,5 @@ log/ /trapdoor-0.9.50-1.17.1.01.vcxproj.filters /trapdoor-0.9.50-1.17.1.01.vcxproj *.zip -/vsbuild \ No newline at end of file +/vsbuild +/sym \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 70903be..ecda2cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,6 @@ add_library(${MOD_API_NAME} STATIC api/block/BlockLegacy.cpp api/block/BlockSource.cpp api/block/VanillaBlockType.cpp - api/block/CircuitComponent.cpp api/commands/CommandNode.cpp api/commands/Command.cpp api/commands/CommandManager.cpp @@ -43,7 +42,6 @@ add_library(${MOD_API_NAME} STATIC api/tools/MsgBuilder.cpp api/tools/ThreadPool.h api/lib/Remotery.c - api/world/LevelChunk.cpp api/language/I18nManager.cpp api/language/I18nManager.h api/tools/CastHelper.h @@ -65,8 +63,8 @@ target_include_directories(${MOD_API_NAME} target_link_libraries(${MOD_API_NAME} ${PROJECT_SOURCE_DIR}/api/lib/detours.lib) ####################这里是具体功能########################## -set(TRAPDOOR_VERSION 0.9.71) -set(MCBE_VERSION 1.17.10.04) +set(TRAPDOOR_VERSION 0.9.73) +set(MCBE_VERSION 1.17.11.01) set(BETA OFF) set(TEST_NUMBER 3) add_definitions(-DTD_VERSION="${TRAPDOOR_VERSION}") @@ -120,7 +118,7 @@ target_include_directories( mod/dirtyLitematica mod/eval mod/fakePlayer - + api api/block api/commands diff --git a/api/BDSMod.cpp b/api/BDSMod.cpp index af71b26..a4d3743 100644 --- a/api/BDSMod.cpp +++ b/api/BDSMod.cpp @@ -3,84 +3,86 @@ // #include "BDSMod.h" + #include "SymHook.h" #include "lib/mod.h" #include "tools/DirtyLogger.h" #include "tools/Message.h" namespace trapdoor { -//全局模组对象 -BDSMod *bdsMod = nullptr; - -void initializeMod(BDSMod *BDSMod) { - L_DEBUG("create BDS mod instance"); - trapdoor::bdsMod = BDSMod; -} + //全局模组对象 + BDSMod *bdsMod = nullptr; -Level *BDSMod::getLevel() { return this->serverLevel; } + void initializeMod(BDSMod *BDSMod) { + L_DEBUG("create BDS mod instance"); + trapdoor::bdsMod = BDSMod; + } -void BDSMod::setCommandRegistry(void *registry) { - L_DEBUG("set commandRegistry"); - this->commandRegistry = registry; -} + Level *BDSMod::getLevel() { return this->serverLevel; } -void *BDSMod::getCommandRegistry() { return this->commandRegistry; } + void BDSMod::setCommandRegistry(void *registry) { + L_DEBUG("set commandRegistry"); + this->commandRegistry = registry; + } -void BDSMod::setLevel(Level *level) { - L_DEBUG("init server level"); - this->serverLevel = level; -} + void *BDSMod::getCommandRegistry() { return this->commandRegistry; } -CommandManager &BDSMod::getCommandManager() { return this->commandManager; } + void BDSMod::setLevel(Level *level) { + L_DEBUG("init server level"); + this->serverLevel = level; + } -void BDSMod::registerCommands() { + CommandManager &BDSMod::getCommandManager() { return this->commandManager; } - if (!this->commandRegistry) { - L_ERROR("fail to register command!![commandRegistry is null ptr]"); + void BDSMod::registerCommands() { + if (!this->commandRegistry) { + L_ERROR("fail to register command!![commandRegistry is null ptr]"); + } + L_DEBUG("begin register command"); + this->registerLangCommand(); + getCommandManager() + .registerCmd("apicfg", "command.apicfg.desc") + ->then(ARG( + "pvd", "command.apicfg.pvd.desc", INT, + { this->getCfg().particleViewDistance = holder->getInt(); })) + ->then(ARG("pm", "command.apicfg.pm.desc", BOOL, { + this->getCfg().particlePerformanceMode = holder->getBool(); + })); } - L_DEBUG("begin register command"); - this->registerLangCommand(); - getCommandManager() - .registerCmd("apicfg", "command.apicfg.desc") - ->then(ARG("pvd", "command.apicfg.pvd.desc", INT, - { this->getCfg().particleViewDistance = holder->getInt(); })) - ->then(ARG("pm", "command.apicfg.pm.desc", BOOL, { - this->getCfg().particlePerformanceMode = holder->getBool(); - })); -} -std::map &BDSMod::getPlayerBuffer() { - return this->playerCache; -} + std::map &BDSMod::getPlayerBuffer() { + return this->playerCache; + } -void BDSMod::initialize() { - L_DEBUG("init thread pool"); - this->threadPool = new ThreadPool(std::thread::hardware_concurrency()); -} + void BDSMod::initialize() { + L_DEBUG("init thread pool"); + this->threadPool = new ThreadPool(std::thread::hardware_concurrency()); + } -trapdoor::Actor *BDSMod::fetchEntity(int64_t id, bool b) { - using namespace SymHook; - return SYM_CALL( - Actor * (*)(Level *, int64_t, bool), - MSSYM_B1QE11fetchEntityB1AA5LevelB2AAE13UEBAPEAVActorB2AAE14UActorUniqueIDB3AAUA1NB1AA1Z, - this->getLevel(), id, b); -} + trapdoor::Actor *BDSMod::fetchEntity(int64_t id, bool b) { + using namespace SymHook; + return SYM_CALL(Actor * (*)(Level *, int64_t, bool), + SymHook::Level_fetchEntity_ff3466ce, this->getLevel(), + id, b); + } -void BDSMod::registerLangCommand() { - this->commandManager.registerCmd("lang", "command.lang.desc") - ->then(ARG( - "list", "command.lang.list.desc", NONE, - { trapdoor::info(player, this->i18NManager.getAllLanguages()); })) - ->then(ARG("set", "command.lang.set.desc", STR, { - auto result = - this->i18NManager.tryChangeLanguage(holder->getString()); - if (result) { - info(player, LANG("command.lang.set.success")); - } else { - info(player, LANG("command.lang.set.failure")); - } - })); -} + void BDSMod::registerLangCommand() { + this->commandManager.registerCmd("lang", "command.lang.desc") + ->then(ARG("list", "command.lang.list.desc", NONE, + { + trapdoor::info(player, + this->i18NManager.getAllLanguages()); + })) + ->then(ARG("set", "command.lang.set.desc", STR, { + auto result = + this->i18NManager.tryChangeLanguage(holder->getString()); + if (result) { + info(player, LANG("command.lang.set.success")); + } else { + info(player, LANG("command.lang.set.failure")); + } + })); + } -void BDSMod::tick() { ++this->trapdoorTick; } -} // namespace trapdoor + void BDSMod::tick() { ++this->trapdoorTick; } +} // namespace trapdoor diff --git a/api/BDSMod.h b/api/BDSMod.h index 53cc59f..c1c76d4 100644 --- a/api/BDSMod.h +++ b/api/BDSMod.h @@ -8,22 +8,22 @@ #ifndef TRAPDOOR_TRAPDOOR_H #define TRAPDOOR_TRAPDOOR_H -#include #include #include +#include #include -#include "commands/CommandManager.h" -#include "world/Level.h" + #include "PlayerBuffer.h" +#include "commands/CommandManager.h" +#include "language/I18nManager.h" #include "tools/ThreadPool.h" #include "tools/noncopyable .h" -#include "language/I18nManager.h" +#include "world/Level.h" namespace trapdoor { - class BDSMod : public noncopyable { - public: + public: struct ModConfig { size_t particleViewDistance = 256; bool particlePerformanceMode = false; @@ -31,7 +31,7 @@ namespace trapdoor { void registerLangCommand(); - protected: + protected: typedef void CommandRegistry; Level *serverLevel{}; CommandRegistry *commandRegistry{}; @@ -42,8 +42,7 @@ namespace trapdoor { I18nManager i18NManager; size_t trapdoorTick = 0; - public: - + public: void tick(); inline size_t getTrapdoorTick() { return this->trapdoorTick; } @@ -52,7 +51,6 @@ namespace trapdoor { void setLevel(Level *level); - CommandRegistry *getCommandRegistry(); void setCommandRegistry(CommandRegistry *registry); @@ -65,27 +63,27 @@ namespace trapdoor { virtual void registerCommands(); - - virtual void useOnHook(Actor *player, const std::string &itemName, BlockPos &pos, - unsigned int facing, + virtual void useOnHook(Actor *player, const std::string &itemName, + BlockPos &pos, unsigned int facing, const Vec3 &) = 0; virtual bool attackEntityHook(Actor *player, Actor *entity) = 0; - virtual CommandPermissionLevel - resetVanillaCommandLevel(const std::string &name, CommandPermissionLevel oldLevel) { return oldLevel; } + virtual CommandPermissionLevel resetVanillaCommandLevel( + const std::string &name, CommandPermissionLevel oldLevel) { + return oldLevel; + } std::map &getPlayerBuffer(); - template + template Mod *asInstance() { return reinterpret_cast(this); } ModConfig &getCfg() { return this->config; } - - public: + public: trapdoor::Actor *fetchEntity(int64_t id, bool b); inline I18nManager &getI18NManager() { return this->i18NManager; } @@ -94,6 +92,6 @@ namespace trapdoor { void initializeMod(BDSMod *bdsMod); extern BDSMod *bdsMod; -} +} // namespace trapdoor -#endif //TRAPDOOR_TRAPDOOR_H +#endif // TRAPDOOR_TRAPDOOR_H diff --git a/api/Offset.h b/api/Offset.h index a4f7252..ad480d8 100644 --- a/api/Offset.h +++ b/api/Offset.h @@ -1,61 +1,61 @@ +#pragma once +#include +#include namespace off { -// OK -//! BlockLegacy::getVariant(BlockLegacy *this, char *a2) -constexpr uint64_t BLOCK_GET_VARIANT = 0x8; + // BlockLegacy::getVariant(BlockLegacy *this, char *a2); + constexpr uint64_t BLOCK_GET_VARIANT = 0x8; -// OK -//! BlockActor::tick -constexpr uint64_t BLOCKACTOR_GET_POSITION = 0x2c; + // BlockActor::tick + constexpr uint64_t BLOCKACTOR_GET_POSITION = 0x2c; -//)OK -constexpr uint64_t BLOCK_GET_LEGACY = 0x10; + constexpr uint64_t BLOCK_GET_LEGACY = 0x10; -// todo:BlockLegacy::getBlockItemId(BlockLegacy *this) -constexpr uint64_t BLOCKLEGACY_GET_BLOCK_ID = 0x14C; + // BlockLegacy::getBlockItemId(BlockLegacy *this) + constexpr uint64_t BLOCKLEGACY_GET_BLOCK_ID = 0x14C; -// -constexpr uint64_t BASECIRCUITCOMPONENT_GET_STRENGTH = 0x34; + // TODO + constexpr uint64_t BASECIRCUITCOMPONENT_GET_STRENGTH = 0x34; -// todo -constexpr std::pair BASECIRCUITCOMPONENT_SOURCE_RANGE = { - 0x1, 0x2}; + // todo + constexpr std::pair BASECIRCUITCOMPONENT_SOURCE_RANGE = + {0x1, 0x2}; -// OK -//! CommandRequestPacket::createCommandContext( -constexpr uint64_t COMMAND_PACKET_STR = 0x30; + // OK + // CommandRequestPacket::createCommandContext( + constexpr uint64_t COMMAND_PACKET_STR = 0x30; -// OK -//! from Player::tickWorld -constexpr uint64_t PLAYER_GET_BLOCKSOURCE = 109; + // OK + // Player::tickWorld + constexpr uint64_t PLAYER_GET_BLOCKSOURCE = 109; -// OK -//! Actor::getDimensionId -constexpr uint64_t ACTOR_GET_DIMENSION_ID = 0xEC; + // OK + // Actor::getDimensionId + constexpr uint64_t ACTOR_GET_DIMENSION_ID = 0xEC; -// OK -//! from ServerPlayer::isHostingPlayer -constexpr uint64_t ACTOR_GET_CLIENT_ID = 2712; + // OK + // from ServerPlayer::isHostingPlayer + constexpr uint64_t ACTOR_GET_CLIENT_ID = 2712; -// todo -constexpr uint64_t ACTOR_ID_GET_NAME = 0x20; + // todo + constexpr uint64_t ACTOR_ID_GET_NAME = 0x20; -// todo -constexpr uint64_t ITEM_GET_NUM = 0x22; + // todo + constexpr uint64_t ITEM_GET_NUM = 0x22; -constexpr uint64_t BIOME_GET_NAME = 0x8; + constexpr uint64_t BIOME_GET_NAME = 0x8; -constexpr uint64_t DIMENSION_GET_CIRCUIT_SYSTEM = 0x21; + constexpr uint64_t DIMENSION_GET_CIRCUIT_SYSTEM = 0x21; -constexpr uint64_t CIRCUIT_GET_GRAPH = 0x8; + constexpr uint64_t CIRCUIT_GET_GRAPH = 0x8; -constexpr uint64_t DIMENSION_IS_RS_TICK = 0x4B; -//! Spawner::_spawnMobCluster -constexpr uint64_t MOB_SPAWN_DATA_GET_RULE = 184; + constexpr uint64_t DIMENSION_IS_RS_TICK = 0x4B; + // Spawner::_spawnMobCluster + constexpr uint64_t MOB_SPAWN_DATA_GET_RULE = 184; -constexpr std::pair LEVEL_FOREACH_PLAYER = {0xE, 0xF}; + constexpr std::pair LEVEL_FOREACH_PLAYER = {0xE, 0xF}; -//! MobSpawnData::MobSpawnData -constexpr uint64_t MOB_SPAWN_DATA_GET_ACTOR_ID = 0x8; + // MobSpawnData::MobSpawnData + constexpr uint64_t MOB_SPAWN_DATA_GET_ACTOR_ID = 0x8; -}; // namespace off \ No newline at end of file +}; // namespace off \ No newline at end of file diff --git a/api/block/Block.cpp b/api/block/Block.cpp index f535ee1..efccee6 100644 --- a/api/block/Block.cpp +++ b/api/block/Block.cpp @@ -2,43 +2,38 @@ // Created by xhy on 2020/8/26. // #include "Block.h" + #include "Offset.h" -#include "block/BlockLegacy.h" -#include "lib/SymHook.h" -#include "lib/mod.h" #include "tools/CastHelper.h" #include "tools/DirtyLogger.h" #include "tools/Message.h" -#include namespace trapdoor { -using namespace SymHook; + using namespace SymHook; -//获取方块legacy -BlockLegacy *Block::getLegacy() { - return *offset_cast(this, off::BLOCK_GET_LEGACY); -} + //获取方块legacy + BlockLegacy *Block::getLegacy() { + return *offset_cast(this, off::BLOCK_GET_LEGACY); + } -//获取方块名字 -std::string Block::getName() { - std::string debugStr; - SYM_CALL( - void (*)(void *block, std::string &), - MSSYM_B1QE13toDebugStringB1AA5BlockB2AAA4QEBAB1QA2AVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB2AAA2XZ, - this, debugStr); - // return debugStr.erase(0, 6); - return debugStr; -} + //获取方块名字 + std::string Block::getName() { + std::string debugStr; + SYM_CALL(void (*)(void *block, std::string &), + Block_toDebugString_522cb860, this, debugStr); + // return debugStr.erase(0, 6); + return debugStr; + } -//获取特殊值 -int Block::getVariant() { - return *offset_cast(this, off::BLOCK_GET_VARIANT); -} + //获取特殊值 + int Block::getVariant() { + return *offset_cast(this, off::BLOCK_GET_VARIANT); + } -//获取方块实体的位置 -BlockPos *BlockActor::getPosition() { - return offset_cast(this, off::BLOCKACTOR_GET_POSITION); - // return reinterpret_cast(reinterpret_cast(this) + 44); -} + //获取方块实体的位置 + BlockPos *BlockActor::getPosition() { + return offset_cast(this, off::BLOCKACTOR_GET_POSITION); + // return reinterpret_cast(reinterpret_cast(this) + 44); + } -} // namespace trapdoor +} // namespace trapdoor diff --git a/api/block/Block.h b/api/block/Block.h index be28657..092c41a 100644 --- a/api/block/Block.h +++ b/api/block/Block.h @@ -1,44 +1,41 @@ + #pragma once -#include "lib/mod.h" -#include "lib/SymHook.h" -#include "graphics/BlockPos.h" -#include "BlockLegacy.h" #include -struct Biome; - +#include "BlockLegacy.h" +#include "graphics/BlockPos.h" +#include "lib/SymHook.h" +#include "lib/mod.h" namespace trapdoor { class BlockLegacy; class Block { - public: + public: // 获取方块legacy - BlockLegacy *getLegacy(); + BlockLegacy* getLegacy(); //获取方块名称(和item返回的名称不一样,不知道Mojang怎么想的) std::string getName(); //获取特殊值 int getVariant(); - }; - -/* - * 方块实体接口 - */ + /* + * 方块实体接口 + */ class BlockActor { - public: + public: //获取位置 - BlockPos *getPosition(); + BlockPos* getPosition(); //获取方块对象 // Block *getBlock(); }; -} +} // namespace trapdoor typedef trapdoor::Block Block; typedef trapdoor::BlockActor BlockActor; diff --git a/api/block/BlockLegacy.cpp b/api/block/BlockLegacy.cpp index e6b17d4..1ecb25c 100644 --- a/api/block/BlockLegacy.cpp +++ b/api/block/BlockLegacy.cpp @@ -3,33 +3,24 @@ // #include "BlockLegacy.h" + #include "Offset.h" #include "lib/SymHook.h" #include "lib/mod.h" #include "tools/CastHelper.h" -#include namespace trapdoor { -using namespace SymHook; - -std::string BlockLegacy::getDebugText() { - std::vector vector; - SYM_CALL(void (*)(BlockLegacy *, std::vector &), - MSSYM_MD5_794b421b4bf67101f7418cd0d78bad83, this, vector); - // return "this api was removed"; - return vector.empty() ? "unknown" : vector[0]; -} + using namespace SymHook; -//获取某个特殊值状态下的方块对象 -Block *BlockLegacy::tryGetStateBlock(unsigned short state) { - return SYM_CALL( - Block * (*)(BlockLegacy *, unsigned short), - MSSYM_B1QE25tryGetStateFromLegacyDataB1AE11BlockLegacyB2AAE13QEBAPEBVBlockB2AAA1GB1AA1Z, - this, state); -} + //获取某个特殊值状态下的方块对象 + Block* BlockLegacy::tryGetStateBlock(unsigned short state) { + return SYM_CALL(Block * (*)(BlockLegacy*, unsigned short), + BlockLegacy_tryGetStateFromLegacyData_ad225111, this, + state); + } -BlockType BlockLegacy::getBlockID() { - return (BlockType)*offset_cast(this, - off::BLOCKLEGACY_GET_BLOCK_ID); -} -} // namespace trapdoor + BlockType BlockLegacy::getBlockID() { + return (BlockType)*offset_cast(this, + off::BLOCKLEGACY_GET_BLOCK_ID); + } +} // namespace trapdoor diff --git a/api/block/BlockLegacy.h b/api/block/BlockLegacy.h index fb04afd..cf4e59d 100644 --- a/api/block/BlockLegacy.h +++ b/api/block/BlockLegacy.h @@ -5,26 +5,24 @@ #ifndef TRAPDOOR_BLOCKLEGACY_H #define TRAPDOOR_BLOCKLEGACY_H -#include "VanillaBlockType.h" #include +#include "VanillaBlockType.h" + /* * 所有方块的父类 */ namespace trapdoor { -class Block; - -class BlockLegacy { - public: - //获取调试信息 - std::string getDebugText(); + class Block; - //获取具有特殊值状态的方块对象 - Block *tryGetStateBlock(unsigned short state); + class BlockLegacy { + public: + //获取具有特殊值状态的方块对象 + Block *tryGetStateBlock(unsigned short state); - BlockType getBlockID(); -}; -} // namespace trapdoor + BlockType getBlockID(); + }; +} // namespace trapdoor typedef trapdoor::BlockLegacy BlockLegacy; -#endif // TRAPDOOR_BLOCKLEGACY_H +#endif // TRAPDOOR_BLOCKLEGACY_H diff --git a/api/block/BlockSource.cpp b/api/block/BlockSource.cpp index dc2bb78..65f43b2 100644 --- a/api/block/BlockSource.cpp +++ b/api/block/BlockSource.cpp @@ -2,87 +2,45 @@ // Created by xhy on 2020/12/16. // #include "BlockSource.h" + #include "Block.h" #include "lib/SymHook.h" #include "lib/mod.h" #include "world/Biome.h" -#include "world/LevelChunk.h" namespace trapdoor { -using namespace SymHook; - -Block *BlockSource::getBlock(int x, int y, int z) { - return getBlock({x, y, z}); -} - -Block *BlockSource::getBlock(const BlockPos &blockPos) { - return SYM_CALL( - Block * (*)(void *, const BlockPos &), - MSSYM_B1QA8getBlockB1AE11BlockSourceB2AAE13QEBAAEBVBlockB2AAE12AEBVBlockPosB3AAAA1Z, - this, blockPos); -} + using namespace SymHook; -void BlockSource::setBlock(BlockPos *blockPos, Block *block) { - // SYM_CALL( - // void(*)(void * , BlockPos *, void *, int, void *), - // MSSYM_B1QA8setBlockB1AE11BlockSourceB2AAA4QEAAB1UE13NAEBVBlockPosB2AAA9AEBVBlockB2AAE26HPEBUActorBlockSyncMessageB3AAAA1Z, - // this, blockPos, block, 3, nullptr - // ); - // this->updateNeighborsAt(blockPos); + Block *BlockSource::getBlock(int x, int y, int z) { + return getBlock({x, y, z}); + } - SYM_CALL( - void (*)(void *, int, int, int, Block *, int), - MSSYM_B1QA8setBlockB1AE11BlockSourceB2AAA4QEAAB1UE13NHHHAEBVBlockB2AAA1HB1AA1Z, - this, blockPos->x, blockPos->y, blockPos->z, block, 3); -} + Block *BlockSource::getBlock(const BlockPos &blockPos) { + return SYM_CALL(Block * (*)(void *, const BlockPos &), + BlockSource_getBlock_fd731636, this, blockPos); + } -void BlockSource::updateNeighborsAt(const BlockPos *pos) { - SYM_CALL( - void (*)(BlockSource * self, const BlockPos *pos), - MSSYM_B1QE17updateNeighborsAtB1AE11BlockSourceB2AAE17QEAAXAEBVBlockPosB3AAAA1Z, - this, pos); -} + void BlockSource::setBlock(BlockPos *blockPos, Block *block) { + SYM_CALL(void (*)(void *, int, int, int, Block *, int), -void BlockSource::updateNeighbors(BlockPos *pos) { - auto blockList = pos->getNeighbourPos(); - for (auto &p : blockList) { - this->updateNeighborsAt(&p); + BlockSource_setBlock_71ce9a25, this, blockPos->x, blockPos->y, + blockPos->z, block, 3); } -} -Biome *BlockSource::getBiome(const BlockPos *pos) { - return SYM_CALL( - Biome * (*)(BlockSource *, const BlockPos *), - MSSYM_B1QA8getBiomeB1AE11BlockSourceB2AAE13QEAAAEAVBiomeB2AAE12AEBVBlockPosB3AAAA1Z, - this, pos); -} + void BlockSource::updateNeighborsAt(const BlockPos *pos) { + SYM_CALL(void (*)(BlockSource * self, const BlockPos *pos), + BlockSource_updateNeighborsAt_4c3f8cf7, this, pos); + } -// uint8_t BlockSource::getRawBrightness(const BlockPos *pos) { -// uint8_t result = 255; -// auto r = SYM_CALL( -// uint8_t * (*)(BlockSource * , uint8_t *, -// const BlockPos *, bool, bool), -// MSSYM_B1QE16getRawBrightnessB1AE11BlockSourceB2AAA4QEBAB1QE12AUBrightnessB2AAE12AEBVBlockPosB3AAUA2N1B1AA1Z, -// this, -// &result, -// pos, -// true, -// true -// ); -// printf("%d %d\n", result, *r); -// return result; -// -// } -// -// int BlockSource::getMaterial(const BlockPos *pos) { -// return -// *SYM_CALL(int * (*)(BlockSource * , int, int, int), -// MSSYM_B1QE11getMaterialB1AE11BlockSourceB2AAE16QEBAAEBVMaterialB2AAA3HHHB1AA1Z, -// this, -// pos->x, -// pos->y, -// pos->z -// ); -// } + void BlockSource::updateNeighbors(BlockPos *pos) { + auto blockList = pos->getNeighbourPos(); + for (auto &p : blockList) { + this->updateNeighborsAt(&p); + } + } -} // namespace trapdoor + Biome *BlockSource::getBiome(const BlockPos *pos) { + return SYM_CALL(Biome * (*)(BlockSource *, const BlockPos *), + BlockSource_getBiome_967864de, this, pos); + } +} // namespace trapdoor diff --git a/api/block/BlockSource.h b/api/block/BlockSource.h index 147cda5..e8d3907 100644 --- a/api/block/BlockSource.h +++ b/api/block/BlockSource.h @@ -15,9 +15,8 @@ namespace trapdoor { class BlockPos; - class BlockSource { - public: + public: //获取某个位置的方块对象 Block *getBlock(int x, int y, int z); @@ -27,7 +26,6 @@ namespace trapdoor { //设置某个位置为某方块 void setBlock(BlockPos *, Block *block); - //更新某个方块(NC更新) void updateNeighborsAt(const BlockPos *pos); @@ -37,14 +35,13 @@ namespace trapdoor { //获取某个位置的群系 Biome *getBiome(const BlockPos *pos); -// uint8_t getRawBrightness(const BlockPos *pos); -// -// int getMaterial(const BlockPos *pos); + // uint8_t getRawBrightness(const BlockPos *pos); + // + // int getMaterial(const BlockPos *pos); // LevelChunk *getLevelChunk(const ChunkPos &chunkPos); - }; -} +} // namespace trapdoor typedef trapdoor::BlockSource BlockSource; -#endif //TRAPDOOR_BLOCKSOURCE_H +#endif // TRAPDOOR_BLOCKSOURCE_H diff --git a/api/block/CircuitComponent.cpp b/api/block/CircuitComponent.cpp deleted file mode 100644 index ab8377d..0000000 --- a/api/block/CircuitComponent.cpp +++ /dev/null @@ -1,66 +0,0 @@ -// -// Created by xhy on 2021/1/20. -// - -#include "lib/mod.h" -#include "lib/SymHook.h" -#include "CircuitComponent.h" -#include "tools/DirtyLogger.h" -#include "graphics/Vec3.h" -#include "graphics/Particle.h" -#include "tools/Message.h" -#include "tools/MsgBuilder.h" -#include "CastHelper.h" -#include "BlockSource.h" -#include "Offset.h" - -namespace trapdoor { - - //获取能量等级 - int BaseCircuitComponent::getStrength() { - return *offset_cast(this, off::BASECIRCUITCOMPONENT_GET_STRENGTH); - } - - - //打印信号源等信息 - void BaseCircuitComponent::basePrint(CircuitSceneGraph *graph, trapdoor::Actor *player) { - MessageBuilder builder; - std::string stringBuilder; - stringBuilder += trapdoor::format("Signal " C_INT, this->getStrength()); - builder.text("Signal: ").num(this->getStrength()); - //todo rewrite - auto begin = (uint32_t *) *((uint64_t *) this + off::BASECIRCUITCOMPONENT_SOURCE_RANGE.first); - auto end = (uint32_t *) *((uint64_t *) this + off::BASECIRCUITCOMPONENT_SOURCE_RANGE.second); - int num = 0; - std::string particleType = "minecraft:silverfish_grief_emitter"; - trapdoor::Vec3 vec3{}; - for (; begin != end; begin += 8) { - auto val = (int *) begin; - BlockPos pos = BlockPos(val[3], val[4], val[5]); - auto comp = graph->getBaseCircuitComponent(&pos); - if (comp) { - stringBuilder += trapdoor::format("\n - " C_POS " <==> " C_INT, pos.x, pos.y, pos.z, - comp->getStrength()); - vec3.x = (float) pos.x + 0.5f; - vec3.y = (float) pos.y + 0.7f; - vec3.z = (float) pos.z + 0.5f; - spawnParticle(vec3, particleType, player->getDimensionID()); - } - num++; - } - trapdoor::info(player, stringBuilder); - } - - //从电路图中获取电路组件 - BaseCircuitComponent *CircuitSceneGraph::getBaseCircuitComponent(BlockPos *pos) { - using namespace SymHook; - return SYM_CALL( - BaseCircuitComponent * (*)(CircuitSceneGraph * graph, - const BlockPos *pos), - MSSYM_B1QE16getBaseComponentB1AE17CircuitSceneGraphB2AAE28QEAAPEAVBaseCircuitComponentB2AAE12AEBVBlockPosB3AAAA1Z, - this, pos - ); - } -} - - diff --git a/api/block/CircuitComponent.h b/api/block/CircuitComponent.h deleted file mode 100644 index 4109b5f..0000000 --- a/api/block/CircuitComponent.h +++ /dev/null @@ -1,40 +0,0 @@ -// -// Created by xhy on 2021/1/20. -// - -#ifndef MOD_CIRCUITCOMPONENT_H -#define MOD_CIRCUITCOMPONENT_H - -#include "graphics/BlockPos.h" -#include "entity/Actor.h" - -namespace trapdoor { - class CircuitSceneGraph; - - class BaseCircuitComponent { - public: - int getStrength(); - - //int getVar2(); - - // int getPowerCount(); - - // int getAcceptHalfPulse(); - - // int getHalfPulse(); - - void basePrint(CircuitSceneGraph *graph, trapdoor::Actor *player); - - // void printRepeater(); - - // void printTorch(BlockPos blockPos); - }; - - //红石电路图组件 - class CircuitSceneGraph { - public: - BaseCircuitComponent *getBaseCircuitComponent(BlockPos *pos); - }; -} - -#endif //MOD_CIRCUITCOMPONENT_H diff --git a/api/block/VanillaBlockType.cpp b/api/block/VanillaBlockType.cpp index 1d6fddb..5d495df 100644 --- a/api/block/VanillaBlockType.cpp +++ b/api/block/VanillaBlockType.cpp @@ -3,6 +3,7 @@ // #include "VanillaBlockType.h" + #include "BDSMod.h" #include "tools/DirtyLogger.h" @@ -12,7 +13,7 @@ namespace trapdoor { static std::unordered_map map; return map; } - } + } // namespace trapdoor::BlockLegacy *getBlockLegacyByID(BlockType type) { auto iter = getBlockMap().find(type); @@ -25,20 +26,18 @@ namespace trapdoor { void initBlockMap() { L_DEBUG("init block map"); using namespace SymHook; - std::function < bool(trapdoor::BlockLegacy & b) > function( - [&](trapdoor::BlockLegacy &l) { - getBlockMap()[l.getBlockID()] = &l; - return true; - }); - SYM_CALL( - void(*)(const std::function < bool(BlockLegacy &)> *), - MSSYM_B1QE12forEachBlockB1AE17BlockTypeRegistryB2AAA4SAXVB2QDA8functionB3ADDA3A6AB1UE16NAEBVBlockLegacyB3AAAA1ZB1AA3stdB3AAAA1Z, - &function - ); + std::function function( + [&](trapdoor::BlockLegacy &l) { + getBlockMap()[l.getBlockID()] = &l; + return true; + }); + + SYM_CALL(void (*)(const std::function *), + SymHook::BlockTypeRegistry_forEachBlock_7f891f2d, &function); } trapdoor::Block *getBlockByID(BlockType type, unsigned short variant) { auto *blockLegacy = getBlockLegacyByID(type); return blockLegacy->tryGetStateBlock(variant); } -} \ No newline at end of file +} // namespace trapdoor \ No newline at end of file diff --git a/api/block/VanillaBlockType.h b/api/block/VanillaBlockType.h index 074cf82..5dda922 100644 --- a/api/block/VanillaBlockType.h +++ b/api/block/VanillaBlockType.h @@ -569,14 +569,12 @@ namespace trapdoor { QUARTZ_BRICKS = 559, }; - trapdoor::Block *getBlockByID(BlockType type, unsigned short variant = 0); trapdoor::BlockLegacy *getBlockLegacyByID(BlockType type); void initBlockMap(); -} - +} // namespace trapdoor -#endif //MOD_VANILLABLOCKTYPE_H +#endif // MOD_VANILLABLOCKTYPE_H diff --git a/api/commands/ArgHolder.cpp b/api/commands/ArgHolder.cpp index a10599f..f8fa0bb 100644 --- a/api/commands/ArgHolder.cpp +++ b/api/commands/ArgHolder.cpp @@ -5,28 +5,15 @@ #include "ArgHolder.h" namespace trapdoor { - ArgHolder *integerArg(int val) { - return new ArgHolder(val); - } + ArgHolder *integerArg(int val) { return new ArgHolder(val); } - ArgHolder *strArg(const std::string &val) { - return new ArgHolder(val); - } + ArgHolder *strArg(const std::string &val) { return new ArgHolder(val); } - ArgHolder *boolArg(bool val) { - return new ArgHolder(val); - } + ArgHolder *boolArg(bool val) { return new ArgHolder(val); } - bool ArgHolder::getBool() const { - return boolVal; - } + bool ArgHolder::getBool() const { return boolVal; } - std::string ArgHolder::getString() const { - return strVal; - } - - int ArgHolder::getInt() const { - return intVal; - } -} + std::string ArgHolder::getString() const { return strVal; } + int ArgHolder::getInt() const { return intVal; } +} // namespace trapdoor diff --git a/api/commands/ArgHolder.h b/api/commands/ArgHolder.h index f7c0e54..eea7a57 100644 --- a/api/commands/ArgHolder.h +++ b/api/commands/ArgHolder.h @@ -5,7 +5,6 @@ #ifndef COMMANDMANAGER_ARGTYPE_H #define COMMANDMANAGER_ARGTYPE_H - #include #include @@ -20,7 +19,8 @@ namespace trapdoor { int intVal = 0; std::string strVal; bool boolVal = true; - public: + + public: explicit ArgHolder(int arg) : intVal(arg) {} explicit ArgHolder(const char *arg) : strVal(arg) {} @@ -34,14 +34,13 @@ namespace trapdoor { std::string getString() const; bool getBool() const; - }; - //y1s1下面这三个方法都可以不要了,懒得换了 + // y1s1下面这三个方法都可以不要了,懒得换了 ArgHolder *integerArg(int val); ArgHolder *strArg(const std::string &val); ArgHolder *boolArg(bool val); -} -#endif //COMMANDMANAGER_ARGTYPE_H +} // namespace trapdoor +#endif // COMMANDMANAGER_ARGTYPE_H diff --git a/api/commands/Command.cpp b/api/commands/Command.cpp index 4a630ba..4fd77f5 100644 --- a/api/commands/Command.cpp +++ b/api/commands/Command.cpp @@ -2,6 +2,10 @@ // Created by xhy on 2020/8/26. // #include "Command.h" + +#include +#include + #include "BDSMod.h" #include "CommandNode.h" #include "Offset.h" @@ -9,38 +13,36 @@ #include "lib/SymHook.h" #include "lib/mod.h" #include "tools/DirtyLogger.h" -#include -#include namespace trapdoor { -//注册命令 -// 调用下面的hook函数来吧自定义字符串和提示信息当作参数注入到游戏中 -// 注释这个函数一级指令就没提示了 -void regMCBECommand(const std::string &command, const char *description, - CommandPermissionLevel level, bool noCheat) { - using namespace SymHook; - if (!trapdoor::bdsMod) { - L_ERROR("get a nullptr of trapdoor::mod"); - return; - } - if (!trapdoor::bdsMod->getCommandRegistry()) { - L_ERROR("get a nullptr of trapdoor::mod::getCommandRegistry"); - return; + //注册命令 + // 调用下面的hook函数来吧自定义字符串和提示信息当作参数注入到游戏中 + // 注释这个函数一级指令就没提示了 + void regMCBECommand(const std::string &command, const char *description, + CommandPermissionLevel level, bool noCheat) { + using namespace SymHook; + if (!trapdoor::bdsMod) { + L_ERROR("get a nullptr of trapdoor::mod"); + return; + } + if (!trapdoor::bdsMod->getCommandRegistry()) { + L_ERROR("get a nullptr of trapdoor::mod::getCommandRegistry"); + return; + } + auto cheatOption = noCheat ? NoCheat : CommandFlag2::Cheat; + SYM_CALL(void (*)(void *cmdReg, const std::string &, const char *, char, + char, char), + CommandRegistry_registerCommand_8574de98, + trapdoor::bdsMod->getCommandRegistry(), command, description, + level, None, cheatOption); } - auto cheatOption = noCheat ? NoCheat : CommandFlag2::Cheat; - SYM_CALL(void (*)(void *cmdReg, const std::string &, const char *, char, - char, char), - MSSYM_MD5_8574de98358ff66b5a913417f44dd706, - trapdoor::bdsMod->getCommandRegistry(), command, description, - level, None, cheatOption); -} -} // namespace trapdoor +} // namespace trapdoor //? hook: //命令注册过程,服务器的命令注册和命令执行是分开的,二者并不绑定,因此可以直接调用这个函数来获得基本的命令提示 using namespace SymHook; -THook(void, MSSYM_MD5_8574de98358ff66b5a913417f44dd706, void *commandRegistry, +THook(void, CommandRegistry_registerCommand_8574de98, void *commandRegistry, const std::string &name, const char *str, trapdoor::CommandPermissionLevel level, trapdoor::CommandFlag1 flag1, trapdoor::CommandFlag2 flag2) { @@ -61,12 +63,9 @@ THook(void, MSSYM_MD5_8574de98358ff66b5a913417f44dd706, void *commandRegistry, } //这个函数用来处理BDS中的命令发送数据包,也就是命令接口 -THook( - void, - MSSYM_B1QA6handleB1AE20ServerNetworkHandlerB2AAE26UEAAXAEBVNetworkIdentifierB2AAE24AEBVCommandRequestPacketB3AAAA1Z, - void *handler, trapdoor::NetworkIdentifier *id, void *commandPacket) { +THook(void, ServerNetworkHandler_handle_1a4c2996, void *handler, + trapdoor::NetworkIdentifier *id, void *commandPacket) { //找到发送命令的玩家 - trapdoor::Actor *source = nullptr; trapdoor::bdsMod->getLevel()->forEachPlayer( [&id, &source](trapdoor::Actor *player) { diff --git a/api/commands/Command.h b/api/commands/Command.h index 8de1568..cb79cf3 100644 --- a/api/commands/Command.h +++ b/api/commands/Command.h @@ -5,13 +5,14 @@ #ifndef TRAPDOOR_COMMAND_H #define TRAPDOOR_COMMAND_H -#include "CommandNode.h" #include +#include "CommandNode.h" + //初始化命令 namespace trapdoor { -//注册mcbe命令,说白了就是给一级指令加tab功能,这个注释也不影响啥 -void regMCBECommand(const std::string &command, const char *description, - CommandPermissionLevel level, bool cheat); -} // namespace trapdoor -#endif // TRAPDOOR_COMMAND_H + //注册mcbe命令,说白了就是给一级指令加tab功能,这个注释也不影响啥 + void regMCBECommand(const std::string &command, const char *description, + CommandPermissionLevel level, bool cheat); +} // namespace trapdoor +#endif // TRAPDOOR_COMMAND_H diff --git a/api/commands/CommandManager.cpp b/api/commands/CommandManager.cpp index 7aa31e4..6ce75e5 100644 --- a/api/commands/CommandManager.cpp +++ b/api/commands/CommandManager.cpp @@ -3,147 +3,126 @@ // #include "CommandManager.h" + #include "Command.h" #include "mod.h" #include "tools/DirtyLogger.h" #include "tools/Message.h" namespace trapdoor { -namespace { -//字符串转为tokens列表 -std::vector tokenize(const std::string &commandString) { - std::vector tokens; - std::stringstream str(commandString); - std::string command; - while (str >> command) - tokens.push_back(command); - return tokens; -} - -VA cmdQueue = 0; -} // namespace + namespace { + //字符串转为tokens列表 + std::vector tokenize(const std::string &commandString) { + std::vector tokens; + std::stringstream str(commandString); + std::string command; + while (str >> command) tokens.push_back(command); + return tokens; + } -//解析玩家命令字符串 -int CommandManager::parse(Actor *player, const std::string &cmd) { - auto tokens = tokenize(cmd); - if (tokens.empty()) - return -1; - auto iter = this->commandList.find(tokens[0]); - if (iter != commandList.end()) { - //这里进行权限检查 - if (!this->checkCommandPermission(tokens[0], player)) { - return -2; + } // namespace + + //解析玩家命令字符串 + int CommandManager::parse(Actor *player, const std::string &cmd) { + auto tokens = tokenize(cmd); + if (tokens.empty()) return -1; + auto iter = this->commandList.find(tokens[0]); + if (iter != commandList.end()) { + //这里进行权限检查 + if (!this->checkCommandPermission(tokens[0], player)) { + return -2; + } + //检查通过转发给命令解析器 + return iter->second->parse(player, tokens, 1); } - //检查通过转发给命令解析器 - return iter->second->parse(player, tokens, 1); + return -3; } - return -3; -} - -//注册命令 -CommandNode *CommandManager::registerCmd(const std::string &cmd, - const std::string &description, - CommandPermissionLevel level, - ArgType type) { - //创建当前命令的根节点 - auto *rootNode = new CommandNode(cmd, description); - rootNode->setArgType(type); - commandList["/" + cmd] = rootNode; //加个/方便查找 - //给根节点添加一个默认的?选项方便打印帮助信息 - auto *helpNode = new CommandNode("?", "print help info"); - //打印帮助信息 - helpNode->execute([rootNode](ArgHolder *holder, Actor *player) { - std::string s; - rootNode->getHelpInfo(0, s); - trapdoor::info(player, s); - }); - rootNode->then(helpNode); - //注册命令到游戏中 - L_DEBUG("register command %s", cmd.c_str()); - regMCBECommand(cmd, LANG(description).c_str(), level, true); - return rootNode; -} - -bool CommandManager::findCommand(const std::string &cmd) { - auto tokens = tokenize(cmd); - if (tokens.empty()) - return false; - return this->commandList.find(tokens[0]) != this->commandList.end(); -} -//递归打印命令帮助 -void CommandManager::printfHelpInfo(Actor *actor) { - std::string buffer; - for (const auto &cmd : this->commandList) { - //只打印自己有权限执行的指令 - if (!this->enablePermissionCheck || - this->checkCommandPermission(cmd.first, actor, false)) - cmd.second->getHelpInfo(0, buffer); + //注册命令 + CommandNode *CommandManager::registerCmd(const std::string &cmd, + const std::string &description, + CommandPermissionLevel level, + ArgType type) { + //创建当前命令的根节点 + auto *rootNode = new CommandNode(cmd, description); + rootNode->setArgType(type); + commandList["/" + cmd] = rootNode; //加个/方便查找 + //给根节点添加一个默认的?选项方便打印帮助信息 + auto *helpNode = new CommandNode("?", "print help info"); + //打印帮助信息 + helpNode->execute([rootNode](ArgHolder *holder, Actor *player) { + std::string s; + rootNode->getHelpInfo(0, s); + trapdoor::info(player, s); + }); + rootNode->then(helpNode); + //注册命令到游戏中 + L_DEBUG("register command %s", cmd.c_str()); + regMCBECommand(cmd, LANG(description).c_str(), level, true); + return rootNode; } - trapdoor::info(actor, buffer); -} -bool CommandManager::checkCommandPermission(const std::string &command, - Actor *player, bool showInfo) { - if (!this->enablePermissionCheck) - return true; - auto cmdCfg = this->commandConfigList.find(command); - if (cmdCfg == commandConfigList.end()) { - L_WARNING("command %s was not config", command.c_str()); - if (showInfo) - error(player, LANG("command.error.config")); - return false; + bool CommandManager::findCommand(const std::string &cmd) { + auto tokens = tokenize(cmd); + if (tokens.empty()) return false; + return this->commandList.find(tokens[0]) != this->commandList.end(); } - // todo game mode check - if (!cmdCfg->second.enable) { - if (showInfo) - error(player, LANG("command.error.config")); - return false; + //递归打印命令帮助 + void CommandManager::printfHelpInfo(Actor *actor) { + std::string buffer; + for (const auto &cmd : this->commandList) { + //只打印自己有权限执行的指令 + if (!this->enablePermissionCheck || + this->checkCommandPermission(cmd.first, actor, false)) + cmd.second->getHelpInfo(0, buffer); + } + trapdoor::info(actor, buffer); } - // todo level cheat check; + bool CommandManager::checkCommandPermission(const std::string &command, + Actor *player, bool showInfo) { + if (!this->enablePermissionCheck) return true; + auto cmdCfg = this->commandConfigList.find(command); + if (cmdCfg == commandConfigList.end()) { + L_WARNING("command %s was not config", command.c_str()); + if (showInfo) error(player, LANG("command.error.config")); + return false; + } + // todo game mode check + + if (!cmdCfg->second.enable) { + if (showInfo) error(player, LANG("command.error.config")); + return false; + } - auto playerLevel = static_cast(player->getCommandLevel()); - auto commandLevel = static_cast(cmdCfg->second.permissionLevel); - if (playerLevel < commandLevel) { + // todo level cheat check; - if (showInfo) { - L_DEBUG("server reject the execute of command [%s] for player %s", + auto playerLevel = static_cast(player->getCommandLevel()); + auto commandLevel = static_cast(cmdCfg->second.permissionLevel); + if (playerLevel < commandLevel) { + if (showInfo) { + L_DEBUG( + "server reject the execute of command [%s] for player %s", command.c_str(), player->getNameTag().c_str()); - error(player, LANG("command.error.permission"), playerLevel, - commandLevel); + error(player, LANG("command.error.permission"), playerLevel, + commandLevel); + } + return false; } - return false; + return true; } - return true; -} -void CommandManager::setCommandConfig( - std::map &cmdConfigList) { - this->commandConfigList = cmdConfigList; - L_DEBUG("set command permission info"); -} - -using namespace SymHook; - -//获取指令队列 -THook( - VA, - MSSYM_B2QQA10B2QDA9SPSCQueueB1AA1VB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB3AADA40CAAB3AAAA4QEAAB2AUA1KB1AA1Z, - VA self) { - cmdQueue = original(self); - return cmdQueue; -} + void CommandManager::setCommandConfig( + std::map &cmdConfigList) { + this->commandConfigList = cmdConfigList; + L_DEBUG("set command permission info"); + } -//执行原版指令 -bool CommandManager::runVanillaCommand(const std::string &command) { - if (cmdQueue) { - SYM_CALL(bool (*)(VA, std::string), - MSSYM_MD5_b5c9e566146b3136e6fb37f0c080d91e, cmdQueue, command); - return true; + using namespace SymHook; + //执行原版指令 + bool CommandManager::runVanillaCommand(const std::string &command) { + return false; } - return false; -} -} // namespace trapdoor +} // namespace trapdoor diff --git a/api/commands/CommandManager.h b/api/commands/CommandManager.h index 4ea8522..b674b20 100644 --- a/api/commands/CommandManager.h +++ b/api/commands/CommandManager.h @@ -8,63 +8,65 @@ #define EXE(S) execute([&](ArgHolder *holder, Actor *player) { S }) #define ARG(arg, desc, type, work) Arg(arg, desc, ArgType::type)->EXE(work) -#include "CommandNode.h" -#include "entity/Actor.h" -#include "tools/noncopyable .h" #include #include #include +#include "CommandNode.h" +#include "entity/Actor.h" +#include "tools/noncopyable .h" + namespace trapdoor { -struct CommandConfig { - bool enable = true; //是否启用 - CommandPermissionLevel permissionLevel = Admin; //权限等级 - //下面两个还没启用,主要是还没获取游戏模式的接口(设置游戏模式的都有了) - bool needCheat = false; - bool survival = false; //生存中是否可用 -}; + struct CommandConfig { + bool enable = true; //是否启用 + CommandPermissionLevel permissionLevel = Admin; //权限等级 + //下面两个还没启用,主要是还没获取游戏模式的接口(设置游戏模式的都有了) + bool needCheat = false; + bool survival = false; //生存中是否可用 + }; -class CommandManager : public trapdoor::noncopyable { - //命令列表 - std::map commandList; - //命令配置文件列表 - std::map commandConfigList; + class CommandManager : public trapdoor::noncopyable { + //命令列表 + std::map commandList; + //命令配置文件列表 + std::map commandConfigList; - public: - CommandNode *registerCmd(const std::string &cmd, - const std::string &description = "no description", - CommandPermissionLevel level = Any, - ArgType type = ArgType::NONE); + public: + CommandNode *registerCmd( + const std::string &cmd, + const std::string &description = "no description", + CommandPermissionLevel level = Any, ArgType type = ArgType::NONE); - bool enablePermissionCheck = true; + bool enablePermissionCheck = true; - //解析命令 - int parse(Actor *player, const std::string &cmd); + //解析命令 + int parse(Actor *player, const std::string &cmd); - inline void setEnablePermissionCheck(bool able) { - this->enablePermissionCheck = able; - } + inline void setEnablePermissionCheck(bool able) { + this->enablePermissionCheck = able; + } - //设置命令配置 - void setCommandConfig(std::map &cmdConfigList); + //设置命令配置 + void setCommandConfig( + std::map &cmdConfigList); - //打印帮助信息 - void printfHelpInfo(Actor *player); + //打印帮助信息 + void printfHelpInfo(Actor *player); - //在当前命令列表里面查找命令 - bool findCommand(const std::string &cmd); + //在当前命令列表里面查找命令 + bool findCommand(const std::string &cmd); - //检查权限等级 - bool checkCommandPermission(const std::string &command, Actor *player, - bool showInfo = true); + //检查权限等级 + bool checkCommandPermission(const std::string &command, Actor *player, + bool showInfo = true); - //执行原版命令 - static bool runVanillaCommand(const std::string &command); -}; + //执行原版命令 + static bool runVanillaCommand(const std::string &command); + }; -} // namespace trapdoor +} // namespace trapdoor typedef trapdoor::CommandManager CommandManager; -#endif // COMMANDMANAGER_COMMANDMANAGER_H +#endif // COMMANDMANAGER_COMMANDMANAGER_H diff --git a/api/commands/CommandNode.cpp b/api/commands/CommandNode.cpp index ce9f175..97989c6 100644 --- a/api/commands/CommandNode.cpp +++ b/api/commands/CommandNode.cpp @@ -3,57 +3,66 @@ // #include "CommandNode.h" -#include "tools/Message.h" + #include #include -#include "tools/MsgBuilder.h" +#include "tools/Message.h" +#include "tools/MsgBuilder.h" namespace trapdoor { namespace { bool isValidIntString(const std::string &str) { - return std::all_of(str.begin(), str.end(), - [](char c) { return ('0' <= c && c <= '9') || c == '-'; }); + return std::all_of(str.begin(), str.end(), [](char c) { + return ('0' <= c && c <= '9') || c == '-'; + }); } - } + } // namespace - CommandNode *Arg(const std::string &args, const std::string &desc, ArgType type) { + CommandNode *Arg(const std::string &args, const std::string &desc, + ArgType type) { auto *node = new CommandNode(args, desc); node->setArgType(type); return node; } - CommandNode::CommandNode(std::string name, std::string description) - : name(std::move(name)), - work([this](ArgHolder *holder, Actor *actor) { - error(actor, LANG("command.error.moreTokenRequired"), this->name.c_str()); - }), - description(std::move(description)) {} - - CommandNode::CommandNode(std::string name) : CommandNode(std::move(name), LANG("command.error.noDesc")) {} - - int CommandNode::parse(Actor *player, const std::vector &tokens, size_t idx) { + : name(std::move(name)), + work([this](ArgHolder *holder, Actor *actor) { + error(actor, LANG("command.error.moreTokenRequired"), + this->name.c_str()); + }), + description(std::move(description)) {} + + CommandNode::CommandNode(std::string name) + : CommandNode(std::move(name), LANG("command.error.noDesc")) {} + + int CommandNode::parse(Actor *player, + const std::vector &tokens, size_t idx) { bool executeNow = false; - if (idx == tokens.size()) { //当前位置已经没tokens了 + if (idx == tokens.size()) { //当前位置已经没tokens了 executeNow = true; if (this->argType == ArgType::NONE) { ArgHolder holder(0); this->run(&holder, player); } else { - error(player, LANG("command.error.moreTokenRequired"), tokens[idx - 1].c_str()); + error(player, LANG("command.error.moreTokenRequired"), + tokens[idx - 1].c_str()); } - } else if (idx == tokens.size() - 1) { //当前是最后一个token + } else if (idx == tokens.size() - 1) { //当前是最后一个token ArgHolder *holder = nullptr; switch (this->argType) { case ArgType::INT: executeNow = isValidIntString(tokens[idx]); - holder = integerArg(strtol(tokens[idx].c_str(), nullptr, 10)); + holder = + integerArg(strtol(tokens[idx].c_str(), nullptr, 10)); break; case ArgType::BOOL: - executeNow = - tokens[idx] == "true" || tokens[idx] == "false" || tokens[idx] == "1" || tokens[idx] == "0"; - holder = boolArg(tokens[idx] == "true" || tokens[idx] == "1"); + executeNow = tokens[idx] == "true" || + tokens[idx] == "false" || tokens[idx] == "1" || + tokens[idx] == "0"; + holder = + boolArg(tokens[idx] == "true" || tokens[idx] == "1"); break; case ArgType::STR: executeNow = true; @@ -69,13 +78,13 @@ namespace trapdoor { } } if (!executeNow) { - for (const auto &node:this->nextNodes) { + for (const auto &node : this->nextNodes) { if (node.second->getName() == tokens[idx]) { return node.second->parse(player, tokens, idx + 1); } } std::string s = LANG("command.error.noSubCommand"); - for (auto &node:this->nextNodes) { + for (auto &node : this->nextNodes) { s += "["; s += node.first; s += "] "; @@ -86,7 +95,7 @@ namespace trapdoor { } void CommandNode::getHelpInfo(int idx, std::string &buffer) const { - if (this->getName() == "?")return; + if (this->getName() == "?") return; MessageBuilder builder; if (idx != 0) { builder += std::string(idx * 4, ' '); @@ -112,7 +121,7 @@ namespace trapdoor { builder += this->getDescription(); builder += "\n"; buffer += builder.get(); - for (auto &node: this->nextNodes) { + for (auto &node : this->nextNodes) { node.second->getHelpInfo(idx + 1, buffer); } } @@ -127,9 +136,8 @@ namespace trapdoor { } void CommandNode::run(ArgHolder *holder, Actor *player) { - if (!player)return; + if (!player) return; this->work(holder, player); - } const char *commandPermissionLevelToStr(CommandPermissionLevel level) { @@ -151,4 +159,4 @@ namespace trapdoor { } } -} \ No newline at end of file +} // namespace trapdoor \ No newline at end of file diff --git a/api/commands/CommandNode.h b/api/commands/CommandNode.h index 941888b..9fb1a21 100644 --- a/api/commands/CommandNode.h +++ b/api/commands/CommandNode.h @@ -6,21 +6,16 @@ #ifndef COMMANDMANAGER_COMMANDNODE_H #define COMMANDMANAGER_COMMANDNODE_H +#include +#include #include #include -#include #include -#include #include -#include "ArgHolder.h" -enum class ArgType { - INT, - BOOL, - STR, - NONE -}; +#include "ArgHolder.h" +enum class ArgType { INT, BOOL, STR, NONE }; /* * 命令节点 @@ -41,7 +36,7 @@ namespace trapdoor { }; enum CommandPermissionLevel : uint8_t { - Any = 0, //Tell + Any = 0, // Tell GameMasters = 1, Admin = 2, Host = 3, @@ -49,12 +44,10 @@ namespace trapdoor { Internal = 5 }; - inline const char *commandPermissionLevelToStr(CommandPermissionLevel level); + inline const char *commandPermissionLevelToStr( + CommandPermissionLevel level); - enum CommandFlag1 : uint8_t { - None = 0, - Message = 0x20 - }; + enum CommandFlag1 : uint8_t { None = 0, Message = 0x20 }; inline const char *CommandFlag1ToStr(CommandFlag1 flag1) { switch (flag1) { @@ -67,7 +60,6 @@ namespace trapdoor { } } - enum CommandFlag2 : uint8_t { Cheat = 0x0, NoCheat = 0x80, @@ -91,23 +83,20 @@ namespace trapdoor { std::function work; ArgType argType = ArgType::NONE; - public: + public: explicit CommandNode(std::string name); CommandNode(std::string name, std::string description); - CommandNode *execute(const std::function &task) { + CommandNode *execute( + const std::function &task) { this->work = task; return this; } - inline std::string getName() const { - return this->name; - } + inline std::string getName() const { return this->name; } - inline void setArgType(ArgType type) { - this->argType = type; - } + inline void setArgType(ArgType type) { this->argType = type; } CommandNode *then(CommandNode *node); @@ -115,11 +104,13 @@ namespace trapdoor { std::string getDescription() const; - int parse(Actor *player, const std::vector &tokens, size_t idx); + int parse(Actor *player, const std::vector &tokens, + size_t idx); void run(ArgHolder *holder, Actor *player); }; - CommandNode *Arg(const std::string &args, const std::string &desc, ArgType type = ArgType::NONE); -} -#endif //COMMANDMANAGER_COMMANDNODE_H + CommandNode *Arg(const std::string &args, const std::string &desc, + ArgType type = ArgType::NONE); +} // namespace trapdoor +#endif // COMMANDMANAGER_COMMANDNODE_H diff --git a/api/entity/Actor.cpp b/api/entity/Actor.cpp index 585707b..adf1f45 100644 --- a/api/entity/Actor.cpp +++ b/api/entity/Actor.cpp @@ -3,151 +3,109 @@ // #include "Actor.h" + +#include + #include "Dimension.h" #include "Offset.h" #include "block/BlockSource.h" +#include "lib/SymHook.h" #include "lib/mod.h" #include "tools/CastHelper.h" #include "tools/MsgBuilder.h" #include "world/Biome.h" -#include namespace trapdoor { -using namespace SymHook; - -uint64_t NetworkIdentifier::getHash() { - return SYM_CALL( - uint64_t(*)(NetworkIdentifier *), - SymHook::MSSYM_B1QA7getHashB1AE17NetworkIdentifierB2AAA4QEBAB1UA3KXZ, - this); -} - -Vec3 *Actor::getPos() { - return SYM_CALL( - Vec3 * (*)(void *), - SymHook::MSSYM_B1QA6getPosB1AA5ActorB2AAE12UEBAAEBVVec3B2AAA2XZ, this); -} - -void Actor::getViewActor(Vec3 *vec3, float val) { - SYM_CALL( - Vec3 * (*)(Actor *, Vec3 *, float), - SymHook:: - MSSYM_B1QE13getViewVectorB1AA5ActorB2AAA4QEBAB1QA6AVVec3B2AAA1MB1AA1Z, - this, vec3, val); -} - -std::string Actor::getNameTag() { - return *SYM_CALL( - std::string * (*)(Actor *), - SymHook:: - MSSYM_B1QE10getNameTagB1AA5ActorB2AAA8UEBAAEBVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB2AAA2XZ, - this); -} - -BlockSource *Actor::getBlockSource() { - //! from Player::tickWorld - // return offset_cast(this, 100); - return *((struct BlockSource **)this + off::PLAYER_GET_BLOCKSOURCE); -} - -void Actor::setGameMode(int mode) { - SYM_CALL( - void (*)(Actor *, int), - SymHook:: - MSSYM_B1QE17setPlayerGameTypeB1AE12ServerPlayerB2AAE15UEAAXW4GameTypeB3AAAA1Z, - this, mode); -} - -int Actor::getDimensionID() { - return *offset_cast(this, off::ACTOR_GET_DIMENSION_ID); -} - -Dimension *Actor::getDimension() { - return this->getLevel()->getDimFromID(this->getDimensionID()); -} - -std::string Actor::getDimensionName() { - auto id = this->getDimensionID(); - if (id == 0) - return "Overworld"; - if (id == 1) - return "Nether"; - if (id == 2) - return "The end"; - return "Unknown"; -} - -NetworkIdentifier *Actor::getClientID() { - //! from ServerPlayer::isHostingPlayer - return offset_cast(this, off::ACTOR_GET_CLIENT_ID); -} - -PlayerPermissionLevel Actor::getCommandLevel() { - return SYM_CALL( - PlayerPermissionLevel(*)(Actor *), - SymHook:: - MSSYM_B1QE25getCommandPermissionLevelB1AA6PlayerB2AAA4UEBAB1QE25AW4CommandPermissionLevelB2AAA2XZ, - this); -} - -PlayerInventory *Actor::getPlayerInventory() { - return SYM_CALL( - PlayerInventory * (*)(Actor *), - SymHook:: - MSSYM_B1QE11getSuppliesB1AA6PlayerB2AAE23QEAAAEAVPlayerInventoryB2AAA2XZ, - this); -} - -// from: Actor::getLevel -Level *Actor::getLevel() { // NOLINT - return bdsMod->getLevel(); - // return *reinterpret_cast((VA) this + 816); -} - -std::string Actor::getActorId() { - std::vector info; - SYM_CALL(void (*)(void *, std::vector &), - SymHook::MSSYM_MD5_f04fad6bac034f1e861181d3580320f2, this, info); - if (info.empty()) - return "null"; - std::string name = info[0]; - name.erase(0, 23); // remove:Entity:minecraft - name.pop_back(); - name.pop_back(); // remove <> - return name; -} - -BlockPos Actor::getStandPosition() { - auto headPos = this->getPos()->toBlockPos(); - return {headPos.x, headPos.y - 2, headPos.z}; -} - -void Actor::setNameTag(const std::string &name) { - SYM_CALL( - void (*)(void *actor, const std::string &str), - MSSYM_B1QE10setNameTagB1AA5ActorB2AAA9UEAAXAEBVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB3AAAA1Z, - this, name); -} - -std::string ActorDefinitionIdentifier::getName() { - auto str = offset_cast(this, off::ACTOR_ID_GET_NAME); - return std::string(*str); -} - -} // namespace trapdoor - -using namespace SymHook; - -// THook(void, MSSYM_B1QA6attackB1AA6PlayerB2AAA4UEAAB1UE10NAEAVActorB3AAAA1Z, -// trapdoor::Actor *p1, trapdoor::Actor *p2) { -// if (p2) { -// auto result = trapdoor::bdsMod->attackEntityHook(p1, p2); -// if (result) { -// original(p1, p2); -// } -// } else { -// original(p1, p2); -// } -// } -// spawn mob + using namespace SymHook; + + uint64_t NetworkIdentifier::getHash() { + return SYM_CALL(uint64_t(*)(NetworkIdentifier *), + SymHook::NetworkIdentifier_getHash_d932dec8, this); + } + + Vec3 *Actor::getPos() { + return SYM_CALL(Vec3 * (*)(void *), SymHook::Actor_getPos_cecb628b, + this); + } + + void Actor::getViewActor(Vec3 *vec3, float val) { + SYM_CALL(Vec3 * (*)(Actor *, Vec3 *, float), + SymHook::Actor_getViewVector_01c92121, this, vec3, val); + } + + std::string Actor::getNameTag() { + return *SYM_CALL(std::string * (*)(Actor *), + SymHook::Actor_getNameTag_7044ab83, this); + } + + BlockSource *Actor::getBlockSource() { + //! from Player::tickWorld + // return offset_cast(this, 100); + return *((struct BlockSource **)this + off::PLAYER_GET_BLOCKSOURCE); + } + + void Actor::setGameMode(int mode) { + SYM_CALL(void (*)(Actor *, int), + SymHook::ServerPlayer_setPlayerGameType_058d8c73, this, mode); + } + + int Actor::getDimensionID() { + return *offset_cast(this, off::ACTOR_GET_DIMENSION_ID); + } + + Dimension *Actor::getDimension() { + return this->getLevel()->getDimFromID(this->getDimensionID()); + } + + std::string Actor::getDimensionName() { + auto id = this->getDimensionID(); + if (id == 0) return "Overworld"; + if (id == 1) return "Nether"; + if (id == 2) return "The end"; + return "Unknown"; + } + + NetworkIdentifier *Actor::getClientID() { + //! from ServerPlayer::isHostingPlayer + return offset_cast(this, off::ACTOR_GET_CLIENT_ID); + } + + PlayerPermissionLevel Actor::getCommandLevel() { + return SYM_CALL(PlayerPermissionLevel(*)(Actor *), + SymHook::Player_getCommandPermissionLevel_40b0e608, + this); + } + + // from: Actor::getLevel + Level *Actor::getLevel() { // NOLINT + return bdsMod->getLevel(); + // return *reinterpret_cast((VA) this + 816); + } + + std::string Actor::getActorId() { + std::vector info; + SYM_CALL(void (*)(void *, std::vector &), + SymHook::Actor_getDebugText_f04fad6b, this, info); + if (info.empty()) return "null"; + std::string name = info[0]; + name.erase(0, 23); // remove:Entity:minecraft + return name.substr(0, name.size() - 2); + } + + BlockPos Actor::getStandPosition() { + auto headPos = this->getPos()->toBlockPos(); + return {headPos.x, headPos.y - 2, headPos.z}; + } + + void Actor::setNameTag(const std::string &name) { + SYM_CALL(void (*)(void *actor, const std::string &str), + Actor_setNameTag_2f9772d3, this, name); + } + + std::string ActorDefinitionIdentifier::getName() { + auto str = offset_cast(this, off::ACTOR_ID_GET_NAME); + return std::string(*str); + } + +} // namespace trapdoor diff --git a/api/entity/Actor.h b/api/entity/Actor.h index 1689189..7af9d25 100644 --- a/api/entity/Actor.h +++ b/api/entity/Actor.h @@ -3,100 +3,101 @@ #ifndef TRAPDOOR_ACTOR_H #define TRAPDOOR_ACTOR_H -#include "commands/CommandNode.h" -#include "graphics/Vec3.h" #include #include -namespace trapdoor { -class PlayerInventory; +#include "commands/CommandNode.h" +#include "graphics/Vec3.h" -class Dimension; +namespace trapdoor { + class PlayerInventory; -class BlockSource; //玩家网络id -struct NetworkIdentifier { - uint64_t getHash(); -}; + class Dimension; -struct ActorUniqueID { - int64_t uid; + class BlockSource; //玩家网络id + struct NetworkIdentifier { + uint64_t getHash(); + }; - bool operator==(const ActorUniqueID &u) const { return this->uid == u.uid; } -}; + struct ActorUniqueID { + int64_t uid; -struct ActorUniqueIDHash { - static uint64_t mceHaseAccLong(uint64_t a1, uint64_t a2) { - return ((a1 >> 2) + (a1 << 6) + a2 + 2654435769u) ^ a1; - } + bool operator==(const ActorUniqueID &u) const { + return this->uid == u.uid; + } + }; - static uint64_t mceHsaLongLong(uint64_t a1, uint64_t a2) { - auto x = mceHaseAccLong(0, a1); - return mceHaseAccLong(x, a2); - } + struct ActorUniqueIDHash { + static uint64_t mceHaseAccLong(uint64_t a1, uint64_t a2) { + return ((a1 >> 2) + (a1 << 6) + a2 + 2654435769u) ^ a1; + } - std::size_t operator()(const ActorUniqueID &key) const { - return mceHsaLongLong(key.uid >> 32, key.uid); - } -}; + static uint64_t mceHsaLongLong(uint64_t a1, uint64_t a2) { + auto x = mceHaseAccLong(0, a1); + return mceHaseAccLong(x, a2); + } -class Level; + std::size_t operator()(const ActorUniqueID &key) const { + return mceHsaLongLong(key.uid >> 32, key.uid); + } + }; -//实体对象(主要指的玩家,懒得做类型判定了) -class Actor { - public: - //获取头部坐标 - Vec3 *getPos(); + class Level; - //获取视角 - void getViewActor(Vec3 *vec3, float val); + //实体对象(主要指的玩家,懒得做类型判定了) + class Actor { + public: + //获取头部坐标 + Vec3 *getPos(); - //获取头顶tag名字 - std::string getNameTag(); + //获取视角 + void getViewActor(Vec3 *vec3, float val); - //设置游戏模式 - void setGameMode(int mode); + //获取头顶tag名字 + std::string getNameTag(); - //获取 blocksource - BlockSource *getBlockSource(); + //设置游戏模式 + void setGameMode(int mode); - //获取维度id - int getDimensionID(); + //获取 blocksource + BlockSource *getBlockSource(); - //获取维度对象 - Dimension *getDimension(); + //获取维度id + int getDimensionID(); - //获取维度名字 - std::string getDimensionName(); + //获取维度对象 + Dimension *getDimension(); - //获取客户端网络id - NetworkIdentifier *getClientID(); + //获取维度名字 + std::string getDimensionName(); - //获取玩家权限等级 - PlayerPermissionLevel getCommandLevel(); + //获取客户端网络id + NetworkIdentifier *getClientID(); - //获取玩家背包 - PlayerInventory *getPlayerInventory(); + //获取玩家权限等级 + PlayerPermissionLevel getCommandLevel(); - //获取站立位置 - BlockPos getStandPosition(); + //获取站立位置 + BlockPos getStandPosition(); - //获取实体类型id - std::string getActorId(); + //获取实体类型id + std::string getActorId(); - //获取level对象 - Level *getLevel(); + //获取level对象 + Level *getLevel(); - //设置头顶的tag - void setNameTag(const std::string &name); -}; + //设置头顶的tag + void setNameTag(const std::string &name); + }; -/** - * 实体标签 - * todo: 重写这个结构,因为已经知道这个东西的具体结构,因此不再需要reinterrupt了 - */ -class ActorDefinitionIdentifier { - public: - std::string getName(); -}; -} // namespace trapdoor + /** + * 实体标签 + * todo: + * 重写这个结构,因为已经知道这个东西的具体结构,因此不再需要reinterrupt了 + */ + class ActorDefinitionIdentifier { + public: + std::string getName(); + }; +} // namespace trapdoor #endif diff --git a/api/entity/Item.cpp b/api/entity/Item.cpp index 111e7ef..0fddd4c 100644 --- a/api/entity/Item.cpp +++ b/api/entity/Item.cpp @@ -3,6 +3,9 @@ // #include "Item.h" + +#include + #include "Offset.h" #include "PlayerBuffer.h" #include "block/Block.h" @@ -12,38 +15,28 @@ #include "tools/DirtyLogger.h" #include "tools/Message.h" #include "tools/MsgBuilder.h" -#include namespace trapdoor { -using namespace SymHook; + using namespace SymHook; -std::string ItemStackBase::getItemName() { - std::string name; - SYM_CALL( - void (*)(ItemStackBase *, std::string *), - MSSYM_B1QA7getNameB1AE13ItemStackBaseB2AAA4QEBAB1QA2AVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB2AAA2XZ, - this, &name); - return name; -} + std::string ItemStackBase::getItemName() { + std::string name; + SYM_CALL(void (*)(ItemStackBase *, std::string *), + SymHook::ItemStackBase_getName_6d581a35, this, &name); + return name; + } -int ItemStackBase::getNum() { - return *offset_cast(this, off::ITEM_GET_NUM); -} + int ItemStackBase::getNum() { + return *offset_cast(this, off::ITEM_GET_NUM); + } -// void ItemStackBase::setNull() { -// SYM_CALL(void(*)(ItemStackBase * ), -// SymHook::MSSYM_B1QA7setNullB1AE13ItemStackBaseB2AAA7UEAAXXZ, -// this); -// } -} // namespace trapdoor +} // namespace trapdoor using namespace SymHook; //右键代理类 -THook( - void, - MSSYM_B1QA5useOnB1AA4ItemB2AAA4QEBAB1UE14NAEAVItemStackB2AAA9AEAVActorB2AAA7HHHEMMMB1AA1Z, - void *item, trapdoor::ItemStackBase *itemStack, trapdoor::Actor *player, - int x, int y, int z, unsigned int facing, float dx, float dy, float dz) { +THook(void, Item_useOn_35e33f80, void *item, trapdoor::ItemStackBase *itemStack, + trapdoor::Actor *player, int x, int y, int z, unsigned int facing, + float dx, float dy, float dz) { uint64_t gameTick = trapdoor::bdsMod->getTrapdoorTick(); // L_INFO("%.2f %.2f %.2f,tick = %llu", x, y, z, gameTick); trapdoor::RightClickCache targetCache{gameTick, x, y, z}; diff --git a/api/entity/Item.h b/api/entity/Item.h index fb4741b..814055d 100644 --- a/api/entity/Item.h +++ b/api/entity/Item.h @@ -5,8 +5,8 @@ #ifndef TRAPDOOR_ITEM_H #define TRAPDOOR_ITEM_H - #include + #include "Block.h" namespace trapdoor { @@ -17,7 +17,6 @@ namespace trapdoor { // void setNull(); }; -} - +} // namespace trapdoor -#endif //TRAPDOOR_ITEM_H +#endif // TRAPDOOR_ITEM_H diff --git a/api/entity/PlayerBuffer.h b/api/entity/PlayerBuffer.h index 0f410c3..7ac1196 100644 --- a/api/entity/PlayerBuffer.h +++ b/api/entity/PlayerBuffer.h @@ -5,8 +5,8 @@ #ifndef TRAPDOOR_PLAYER_BUFFER_H #define TRAPDOOR_PLAYER_BUFFER_H -#include "graphics/BlockPos.h" #include "Actor.h" +#include "graphics/BlockPos.h" namespace trapdoor { struct RightClickCache { @@ -20,11 +20,10 @@ namespace trapdoor { bool operator!=(const RightClickCache &rhs) const; }; - //这个结构专门存储玩家个人相关的缓存信息(相当于玩家的一个私人空间),后面可能加新东西 struct PlayerBuffer { RightClickCache rightClickCache; //玩家右键缓存,作为右键检测使用 }; } // namespace trapdoor -#endif // TRAPDOOR_PLAYER_BUFFER_H +#endif // TRAPDOOR_PLAYER_BUFFER_H diff --git a/api/graphics/AABB.h b/api/graphics/AABB.h index 3b0e488..bbe1ac0 100644 --- a/api/graphics/AABB.h +++ b/api/graphics/AABB.h @@ -17,10 +17,7 @@ namespace trapdoor { p2 = _p2; } - Vec3 getCenter() const { - return (p1 + p2) * 0.5; - } - + Vec3 getCenter() const { return (p1 + p2) * 0.5; } }; struct BoundingBox { @@ -34,7 +31,8 @@ namespace trapdoor { AABB getSpawnArea() const { int x = (this->maxPos.x - this->minPos.x + 1) / 2 + this->minPos.x; - int z = (this->maxPos.z - this->minPos.z + 1) / 2 + this->minPos.z + 1; + int z = + (this->maxPos.z - this->minPos.z + 1) / 2 + this->minPos.z + 1; Vec3 minPoint{x, minPos.y, z - 1}; Vec3 maxPoint{x + 1, maxPos.y + 1, z}; return {minPoint, maxPoint}; @@ -45,14 +43,12 @@ namespace trapdoor { } bool operator<(const BoundingBox &rhs) const { - if (minPos < rhs.minPos) - return true; - if (rhs.minPos < minPos) - return false; + if (minPos < rhs.minPos) return true; + if (rhs.minPos < minPos) return false; return maxPos < rhs.maxPos; } }; -} +} // namespace trapdoor typedef trapdoor::AABB AABB; typedef trapdoor::BoundingBox BoundingBox; -#endif // TRAPDOOR_AABB_H +#endif // TRAPDOOR_AABB_H diff --git a/api/graphics/BlockPos.cpp b/api/graphics/BlockPos.cpp index 66351bf..d8c3e05 100644 --- a/api/graphics/BlockPos.cpp +++ b/api/graphics/BlockPos.cpp @@ -10,183 +10,183 @@ #include "Vec3.h" namespace trapdoor { -bool BlockPos::operator==(const BlockPos &v) const { - return x == v.x && y == v.y && z == v.z; -} - -bool BlockPos::operator!=(const BlockPos &v) const { - return x != v.x || y != v.y || z != v.z; -} - -float BlockPos::distanceTo(const BlockPos &blockPos) const { - return (float)sqrt((blockPos.x - x) * (blockPos.x - x) + - (blockPos.y - y) * (blockPos.y - y) + - (blockPos.z - z) * (blockPos.z - z)); -} - -std::ostream &operator<<(std::ostream &os, const BlockPos &vec3) { - os << "[" << vec3.x << "," << vec3.y << "," << vec3.z << "]"; - return os; -} - -Vec3 BlockPos::toVec3() const { return {x, y, z}; } - -std::string BlockPos::toString() const { - return "[" + std::to_string(x) + "," + std::to_string(y) + "," + - std::to_string(z) + "]"; -} - -std::vector BlockPos::getNeighbourPos() { - return {{x + 1, y, z}, {x - 1, y, z}, {x, y + 1, z}, - {x, y - 1, z}, {x, y, z + 1}, {x, y, z - 1}}; -} - -std::vector BlockPos::getPlainNeighbourPos() { - return {{x + 1, y, z}, {x - 1, y, z}, {x, y, z + 1}, {x, y, z - 1}}; -} - -BlockPos2 BlockPos::InChunkOffset() const { - auto newX = x % 16; - auto newZ = z % 16; - if (newX < 0) newX += 16; - if (newZ < 0) newZ += 16; - return {newX, newZ}; -} - -BlockPos2 BlockPos::toChunkPos() const { - auto cx = x < 0 ? x - 15 : x; - auto cz = z < 0 ? z - 15 : z; - return {cx / 16, cz / 16}; -} - -bool BlockPos::operator<(const BlockPos &rhs) const { - if (x < rhs.x) return true; - if (rhs.x < x) return false; - if (y < rhs.y) return true; - if (rhs.y < y) return false; - return z < rhs.z; -} - -int BlockPos::operator*(const BlockPos &pos) const { - return this->x * pos.x + this->y * pos.y + this->z * pos.z; -} - -BlockPos BlockPos::operator+(const BlockPos &pos) const { - return {x + pos.x, y + pos.y, z + pos.z}; -} - -std::string BlockPos2::toString() const { - return "[" + std::to_string(x) + "," + std::to_string(z) + "]"; -} - -bool BlockPos2::isSlimeChunk() const { - auto seed = (x * 0x1f1f1f1fu) ^ (uint32_t)z; - std::mt19937 mt(seed); - return mt() % 10 == 0; -} - -bool BlockPos2::operator<(const BlockPos2 &rhs) const { - if (x < rhs.x) return true; - if (rhs.x < x) return false; - return z < rhs.z; -} - -std::string facingToString(FACING facing) { - switch (facing) { - case FACING::POS_X: - return "+x"; - case FACING::NEG_X: - return "-x"; - case FACING::POS_Y: - return "+y"; - case FACING::POS_Z: - return "+z"; - case FACING::NEG_Y: - return "-y"; - case FACING::NEG_Z: - return "-z"; - default: - return "unknown"; - } -} - -std::string facingToDirString(FACING facing) { - switch (facing) { - case FACING::POS_X: - return "west"; - case FACING::NEG_X: - return "east"; - case FACING::POS_Y: - return "up"; - case FACING::POS_Z: - return "south"; - case FACING::NEG_Y: - return "down"; - case FACING::NEG_Z: - return "north"; - default: - return "unknown"; - } -} - -BlockPos facingToBlockPos(FACING facing) { - switch (facing) { - case FACING::NEG_Y: - return {0, -1, 0}; - case FACING::POS_Y: - return {0, 1, 0}; - case FACING::NEG_Z: - return {0, 0, -1}; - case FACING::POS_Z: - return {0, 0, 1}; - case FACING::NEG_X: - return {-1, 0, 0}; - case FACING::POS_X: - return {1, 0, 0}; - } - return {0, 0, 0}; -} - -bool facingIsPos(FACING facing) { - return facing == FACING::POS_X || facing == FACING::POS_Y || - facing == FACING::POS_Z; -} - -bool facingIsNeg(FACING facing) { - return facing == FACING::NEG_X || facing == FACING::NEG_Y || - facing == FACING::NEG_Z; -} - -bool facingIsX(FACING facing) { - return facing == FACING::POS_X || facing == FACING::NEG_X; -} - -bool facingIsY(FACING facing) { - return facing == FACING::POS_Y || facing == FACING::NEG_Y; -} - -bool facingIsZ(FACING facing) { - return facing == FACING::POS_Z || facing == FACING::NEG_Z; -} - -FACING invFacing(FACING facing) { - switch (facing) { - case FACING::NEG_Y: - return FACING::POS_Y; - case FACING::POS_Y: - return FACING::NEG_Y; - case FACING::NEG_Z: - return FACING::POS_Z; - case FACING::POS_Z: - return FACING::NEG_Z; - case FACING::NEG_X: - return FACING::POS_X; - case FACING::POS_X: - return FACING::NEG_X; - default: - return FACING::POS_X; - } -} + bool BlockPos::operator==(const BlockPos &v) const { + return x == v.x && y == v.y && z == v.z; + } + + bool BlockPos::operator!=(const BlockPos &v) const { + return x != v.x || y != v.y || z != v.z; + } + + float BlockPos::distanceTo(const BlockPos &blockPos) const { + return (float)sqrt((blockPos.x - x) * (blockPos.x - x) + + (blockPos.y - y) * (blockPos.y - y) + + (blockPos.z - z) * (blockPos.z - z)); + } + + std::ostream &operator<<(std::ostream &os, const BlockPos &vec3) { + os << "[" << vec3.x << "," << vec3.y << "," << vec3.z << "]"; + return os; + } + + Vec3 BlockPos::toVec3() const { return {x, y, z}; } + + std::string BlockPos::toString() const { + return "[" + std::to_string(x) + "," + std::to_string(y) + "," + + std::to_string(z) + "]"; + } + + std::vector BlockPos::getNeighbourPos() { + return {{x + 1, y, z}, {x - 1, y, z}, {x, y + 1, z}, + {x, y - 1, z}, {x, y, z + 1}, {x, y, z - 1}}; + } + + std::vector BlockPos::getPlainNeighbourPos() { + return {{x + 1, y, z}, {x - 1, y, z}, {x, y, z + 1}, {x, y, z - 1}}; + } + + BlockPos2 BlockPos::InChunkOffset() const { + auto newX = x % 16; + auto newZ = z % 16; + if (newX < 0) newX += 16; + if (newZ < 0) newZ += 16; + return {newX, newZ}; + } + + BlockPos2 BlockPos::toChunkPos() const { + auto cx = x < 0 ? x - 15 : x; + auto cz = z < 0 ? z - 15 : z; + return {cx / 16, cz / 16}; + } + + bool BlockPos::operator<(const BlockPos &rhs) const { + if (x < rhs.x) return true; + if (rhs.x < x) return false; + if (y < rhs.y) return true; + if (rhs.y < y) return false; + return z < rhs.z; + } + + int BlockPos::operator*(const BlockPos &pos) const { + return this->x * pos.x + this->y * pos.y + this->z * pos.z; + } + + BlockPos BlockPos::operator+(const BlockPos &pos) const { + return {x + pos.x, y + pos.y, z + pos.z}; + } + + std::string BlockPos2::toString() const { + return "[" + std::to_string(x) + "," + std::to_string(z) + "]"; + } + + bool BlockPos2::isSlimeChunk() const { + auto seed = (x * 0x1f1f1f1fu) ^ (uint32_t)z; + std::mt19937 mt(seed); + return mt() % 10 == 0; + } + + bool BlockPos2::operator<(const BlockPos2 &rhs) const { + if (x < rhs.x) return true; + if (rhs.x < x) return false; + return z < rhs.z; + } + + std::string facingToString(FACING facing) { + switch (facing) { + case FACING::POS_X: + return "+x"; + case FACING::NEG_X: + return "-x"; + case FACING::POS_Y: + return "+y"; + case FACING::POS_Z: + return "+z"; + case FACING::NEG_Y: + return "-y"; + case FACING::NEG_Z: + return "-z"; + default: + return "unknown"; + } + } + + std::string facingToDirString(FACING facing) { + switch (facing) { + case FACING::POS_X: + return "west"; + case FACING::NEG_X: + return "east"; + case FACING::POS_Y: + return "up"; + case FACING::POS_Z: + return "south"; + case FACING::NEG_Y: + return "down"; + case FACING::NEG_Z: + return "north"; + default: + return "unknown"; + } + } + + BlockPos facingToBlockPos(FACING facing) { + switch (facing) { + case FACING::NEG_Y: + return {0, -1, 0}; + case FACING::POS_Y: + return {0, 1, 0}; + case FACING::NEG_Z: + return {0, 0, -1}; + case FACING::POS_Z: + return {0, 0, 1}; + case FACING::NEG_X: + return {-1, 0, 0}; + case FACING::POS_X: + return {1, 0, 0}; + } + return {0, 0, 0}; + } + + bool facingIsPos(FACING facing) { + return facing == FACING::POS_X || facing == FACING::POS_Y || + facing == FACING::POS_Z; + } + + bool facingIsNeg(FACING facing) { + return facing == FACING::NEG_X || facing == FACING::NEG_Y || + facing == FACING::NEG_Z; + } + + bool facingIsX(FACING facing) { + return facing == FACING::POS_X || facing == FACING::NEG_X; + } + + bool facingIsY(FACING facing) { + return facing == FACING::POS_Y || facing == FACING::NEG_Y; + } + + bool facingIsZ(FACING facing) { + return facing == FACING::POS_Z || facing == FACING::NEG_Z; + } + + FACING invFacing(FACING facing) { + switch (facing) { + case FACING::NEG_Y: + return FACING::POS_Y; + case FACING::POS_Y: + return FACING::NEG_Y; + case FACING::NEG_Z: + return FACING::POS_Z; + case FACING::POS_Z: + return FACING::NEG_Z; + case FACING::NEG_X: + return FACING::POS_X; + case FACING::POS_X: + return FACING::NEG_X; + default: + return FACING::POS_X; + } + } } // namespace trapdoor typedef trapdoor::BlockPos BlockPos; typedef trapdoor::BlockPos2 BlockPos2; diff --git a/api/graphics/BlockPos.h b/api/graphics/BlockPos.h index b221a15..c40804c 100644 --- a/api/graphics/BlockPos.h +++ b/api/graphics/BlockPos.h @@ -55,9 +55,8 @@ namespace trapdoor { typedef BlockPos2 ChunkPos; - class BlockPos { - public: + public: int x = 0; int y = 0; int z = 0; @@ -70,7 +69,8 @@ namespace trapdoor { explicit BlockPos(float x) : BlockPos(x, x, x) {} - BlockPos(float _x, float _y, float _z) : x((int) _x), y((int) _y), z((int) _z) {} + BlockPos(float _x, float _y, float _z) + : x((int)_x), y((int)_y), z((int)_z) {} bool operator==(const BlockPos &v) const; @@ -92,7 +92,6 @@ namespace trapdoor { BlockPos2 InChunkOffset() const; - int operator*(const BlockPos &pos) const; BlockPos operator+(const BlockPos &pos) const; @@ -100,5 +99,5 @@ namespace trapdoor { bool operator<(const BlockPos &rhs) const; }; -} -#endif //LIBMCBEMOD_BLOCKPOS_H +} // namespace trapdoor +#endif // LIBMCBEMOD_BLOCKPOS_H diff --git a/api/graphics/Graphics.cpp b/api/graphics/Graphics.cpp index 92ecfb7..4a09509 100644 --- a/api/graphics/Graphics.cpp +++ b/api/graphics/Graphics.cpp @@ -2,11 +2,13 @@ // Created by xhy on 2020/12/12. // -#include #include "Graphics.h" + +#include + +#include "BDSMod.h" #include "Particle.h" #include "Vec3.h" -#include "BDSMod.h" namespace trapdoor { @@ -27,7 +29,7 @@ namespace trapdoor { if (length >= defaultLength) { length -= defaultLength; auto point = - static_cast(0.5 * defaultLength + start); + static_cast(0.5 * defaultLength + start); start += defaultLength; lengthMap.insert({point, defaultLength}); } @@ -35,8 +37,7 @@ namespace trapdoor { return lengthMap; } - std::string getLineParticleType(int length, - FACING direction, + std::string getLineParticleType(int length, FACING direction, GRAPHIC_COLOR color) { std::string str = "trapdoor:line"; str += std::to_string(length); @@ -82,13 +83,9 @@ namespace trapdoor { } } // namespace - void drawLine(const Vec3 &originPoint, - FACING direction, - float length, - GRAPHIC_COLOR color, - int dimType) { - if (length <= 0) - return; + void drawLine(const Vec3 &originPoint, FACING direction, float length, + GRAPHIC_COLOR color, int dimType) { + if (length <= 0) return; float start = 0, end = 0; switch (direction) { case FACING::NEG_Y: @@ -122,22 +119,22 @@ namespace trapdoor { if (facingIsX(direction)) { for (auto i : list) positionList.insert( - {{i.first, originPoint.y, originPoint.z}, i.second}); + {{i.first, originPoint.y, originPoint.z}, i.second}); } else if (facingIsY(direction)) { for (auto i : list) positionList.insert( - {{originPoint.x, i.first, originPoint.z}, i.second}); + {{originPoint.x, i.first, originPoint.z}, i.second}); } else if (facingIsZ(direction)) { for (auto i : list) positionList.insert( - {{originPoint.x, originPoint.y, i.first}, i.second}); + {{originPoint.x, originPoint.y, i.first}, i.second}); } for (auto points : positionList) { auto particleType = - getLineParticleType(points.second, direction, color); + getLineParticleType(points.second, direction, color); auto particleTypeInv = - getLineParticleType(points.second, invFacing(direction), color); + getLineParticleType(points.second, invFacing(direction), color); spawnParticle(points.first, particleType, dimType); if (!bdsMod->getCfg().particlePerformanceMode) spawnParticle(points.first, particleTypeInv, dimType); diff --git a/api/graphics/Graphics.h b/api/graphics/Graphics.h index 7538aab..afe9a48 100644 --- a/api/graphics/Graphics.h +++ b/api/graphics/Graphics.h @@ -6,9 +6,10 @@ #define TRAPDOOR_GRAPHICS_H //#include "Particle.h" -#include "BlockPos.h" -#include #include +#include + +#include "BlockPos.h" namespace trapdoor { enum class GRAPHIC_COLOR { @@ -19,11 +20,8 @@ namespace trapdoor { GREEN = 4 }; - void drawLine(const Vec3 &originPoint, - FACING direction, - float length, - GRAPHIC_COLOR color, - int dimType = 0); + void drawLine(const Vec3 &originPoint, FACING direction, float length, + GRAPHIC_COLOR color, int dimType = 0); void drawPoint(const Vec3 &point, GRAPHIC_COLOR color, int dimType = 0); } // namespace trapdoor diff --git a/api/graphics/Particle.cpp b/api/graphics/Particle.cpp index ef8b629..abf86c4 100644 --- a/api/graphics/Particle.cpp +++ b/api/graphics/Particle.cpp @@ -2,99 +2,102 @@ // Created by xhy on 2020/8/25. // #include "Particle.h" -#include "lib/SymHook.h" -#include "lib/mod.h" + #include #include "BDSMod.h" #include "Graphics.h" #include "entity/Actor.h" +#include "lib/SymHook.h" +#include "lib/mod.h" #include "tools/DirtyLogger.h" #include "world/Level.h" namespace trapdoor { -using namespace SymHook; + using namespace SymHook; -void spawnParticle(Vec3 p, std::string &type, int dimType) { - auto pos = p.toBlockPos(); - auto level = trapdoor::bdsMod->getLevel(); - if (!level) { - L_ERROR("level is null"); - return; - } - auto player = level->getNearestDimensionPlayer(pos, dimType); - if (!player) { - return; - } - auto maxDist = trapdoor::bdsMod->getCfg().particleViewDistance; - if (p.distanceTo(*player->getPos()) > static_cast(maxDist)) - return; + void spawnParticle(Vec3 p, std::string &type, int dimType) { + auto pos = p.toBlockPos(); + auto level = trapdoor::bdsMod->getLevel(); + if (!level) { + L_ERROR("level is null"); + return; + } + auto player = level->getNearestDimensionPlayer(pos, dimType); + if (!player) { + return; + } + auto maxDist = trapdoor::bdsMod->getCfg().particleViewDistance; + if (p.distanceTo(*player->getPos()) > static_cast(maxDist)) + return; - SYM_CALL(void (*)(Level *, const std::string &, Vec3 *, void *), - MSSYM_MD5_52e7de092fab8d042fb516e31fc9756f, level, type, &p, - player->getDimension()); -} + SYM_CALL(void (*)(Level *, const std::string &, Vec3 *, void *), + Level_spawnParticleEffect_52e7de09, level, type, &p, + player->getDimension()); + } -void spawnRectangleParticle(const AABB &aabb, GRAPHIC_COLOR color, - int dimType) { - auto p1 = aabb.p1, p2 = aabb.p2; - auto dx = p2.x - p1.x; - auto dy = p2.y - p1.y; - auto dz = p2.z - p1.z; - drawLine(p1, FACING::POS_X, dx, color, dimType); - drawLine(p1, FACING::POS_Y, dy, color, dimType); - drawLine(p1, FACING::POS_Z, dz, color, dimType); - Vec3 p3{p2.x, p1.y, p2.z}; - drawLine(p3, FACING::NEG_X, dx, color, dimType); - drawLine(p3, FACING::POS_Y, dy, color, dimType); - drawLine(p3, FACING::NEG_Z, dz, color, dimType); - Vec3 p4{p2.x, p2.y, p1.z}; - drawLine(p4, FACING::NEG_X, dx, color, dimType); - drawLine(p4, FACING::NEG_Y, dy, color, dimType); - drawLine(p4, FACING::POS_Z, dz, color, dimType); + void spawnRectangleParticle(const AABB &aabb, GRAPHIC_COLOR color, + int dimType) { + auto p1 = aabb.p1, p2 = aabb.p2; + auto dx = p2.x - p1.x; + auto dy = p2.y - p1.y; + auto dz = p2.z - p1.z; + drawLine(p1, FACING::POS_X, dx, color, dimType); + drawLine(p1, FACING::POS_Y, dy, color, dimType); + drawLine(p1, FACING::POS_Z, dz, color, dimType); + Vec3 p3{p2.x, p1.y, p2.z}; + drawLine(p3, FACING::NEG_X, dx, color, dimType); + drawLine(p3, FACING::POS_Y, dy, color, dimType); + drawLine(p3, FACING::NEG_Z, dz, color, dimType); + Vec3 p4{p2.x, p2.y, p1.z}; + drawLine(p4, FACING::NEG_X, dx, color, dimType); + drawLine(p4, FACING::NEG_Y, dy, color, dimType); + drawLine(p4, FACING::POS_Z, dz, color, dimType); - Vec3 p5{p1.x, p2.y, p2.z}; - drawLine(p5, FACING::POS_X, dx, color, dimType); - drawLine(p5, FACING::NEG_Y, dy, color, dimType); - drawLine(p5, FACING::NEG_Z, dz, color, dimType); -} + Vec3 p5{p1.x, p2.y, p2.z}; + drawLine(p5, FACING::POS_X, dx, color, dimType); + drawLine(p5, FACING::NEG_Y, dy, color, dimType); + drawLine(p5, FACING::NEG_Z, dz, color, dimType); + } -void spawnLineParticle(const Vec3 &p, FACING facing, float length, - GRAPHIC_COLOR color, int dimType) { - drawLine(p, facing, length, color, dimType); -} + void spawnLineParticle(const Vec3 &p, FACING facing, float length, + GRAPHIC_COLOR color, int dimType) { + drawLine(p, facing, length, color, dimType); + } -void spawnChunkSurfaceParticle(const ChunkPos &p, int dimID) { - bool isSlime = p.isSlimeChunk(); - std::string pName2 = isSlime ? "trapdoor:chunkslimep" : "trapdoor:chunkp"; - std::string pName1 = isSlime ? "trapdoor:chunkslimem" : "trapdoor:chunkm"; - float x = static_cast(p.x) * 16.0f; - float z = static_cast(p.z) * 16.0f; - Vec3 p1{x + 0.01f, 128.0f, z + 8.0f}; - Vec3 p2{x + 15.99f, 128.0f, z + 8.0f}; - Vec3 p3{x + 8.0f, 128.0f, z + 0.01f}; - Vec3 p4{x + 8.0f, 128.0f, z + 15.99f}; - spawnParticle(p1, pName1, dimID); - spawnParticle(p2, pName1, dimID); - spawnParticle(p3, pName2, dimID); - spawnParticle(p4, pName2, dimID); -} + void spawnChunkSurfaceParticle(const ChunkPos &p, int dimID) { + bool isSlime = p.isSlimeChunk(); + std::string pName2 = + isSlime ? "trapdoor:chunkslimep" : "trapdoor:chunkp"; + std::string pName1 = + isSlime ? "trapdoor:chunkslimem" : "trapdoor:chunkm"; + float x = static_cast(p.x) * 16.0f; + float z = static_cast(p.z) * 16.0f; + Vec3 p1{x + 0.01f, 128.0f, z + 8.0f}; + Vec3 p2{x + 15.99f, 128.0f, z + 8.0f}; + Vec3 p3{x + 8.0f, 128.0f, z + 0.01f}; + Vec3 p4{x + 8.0f, 128.0f, z + 15.99f}; + spawnParticle(p1, pName1, dimID); + spawnParticle(p2, pName1, dimID); + spawnParticle(p3, pName2, dimID); + spawnParticle(p4, pName2, dimID); + } -void spawnSlimeChunkParticle(const ChunkPos &p) { - float x = static_cast(p.x) * 16.0f; - float z = static_cast(p.z) * 16.0f; - Vec3 p1{x + 0.01f, 0.0f, z + 8.0f}; - Vec3 p2{x + 15.99f, 0.0f, z + 8.0f}; - Vec3 p3{x + 8.0f, 0.0f, z + 0.01f}; - Vec3 p4{x + 8.0f, 0.0f, z + 15.99f}; - Vec3 top{x + 8.0f, 128.0f, z + 8.0f}; - std::string pName1 = "trapdoor:slime_side1"; - std::string pName2 = "trapdoor:slime_side2"; - std::string pName3 = "trapdoor:slime_top"; - spawnParticle(p1, pName1); - spawnParticle(p2, pName1); - spawnParticle(p3, pName2); - spawnParticle(p4, pName2); - spawnParticle(top, pName3); -} -} // namespace trapdoor \ No newline at end of file + void spawnSlimeChunkParticle(const ChunkPos &p) { + float x = static_cast(p.x) * 16.0f; + float z = static_cast(p.z) * 16.0f; + Vec3 p1{x + 0.01f, 0.0f, z + 8.0f}; + Vec3 p2{x + 15.99f, 0.0f, z + 8.0f}; + Vec3 p3{x + 8.0f, 0.0f, z + 0.01f}; + Vec3 p4{x + 8.0f, 0.0f, z + 15.99f}; + Vec3 top{x + 8.0f, 128.0f, z + 8.0f}; + std::string pName1 = "trapdoor:slime_side1"; + std::string pName2 = "trapdoor:slime_side2"; + std::string pName3 = "trapdoor:slime_top"; + spawnParticle(p1, pName1); + spawnParticle(p2, pName1); + spawnParticle(p3, pName2); + spawnParticle(p4, pName2); + spawnParticle(top, pName3); + } +} // namespace trapdoor \ No newline at end of file diff --git a/api/graphics/Particle.h b/api/graphics/Particle.h index 9986505..5cf0639 100644 --- a/api/graphics/Particle.h +++ b/api/graphics/Particle.h @@ -6,18 +6,21 @@ #define TRAPDOOR_PARTICLE_H #include -#include "Graphics.h" + #include "AABB.h" +#include "Graphics.h" namespace trapdoor { void spawnParticle(Vec3 p, std::string &type, int dimType = 0); - void spawnRectangleParticle(const AABB &aabb, GRAPHIC_COLOR color, int dimType = 0); + void spawnRectangleParticle(const AABB &aabb, GRAPHIC_COLOR color, + int dimType = 0); void spawnChunkSurfaceParticle(const ChunkPos &pos, int dimID); void spawnSlimeChunkParticle(const ChunkPos &pos); - void spawnLineParticle(const Vec3 &p, FACING facing, float length, GRAPHIC_COLOR color, int dimType = 0); -} -#endif // TRAPDOOR_PARTICLE_H + void spawnLineParticle(const Vec3 &p, FACING facing, float length, + GRAPHIC_COLOR color, int dimType = 0); +} // namespace trapdoor +#endif // TRAPDOOR_PARTICLE_H diff --git a/api/graphics/Vec3.cpp b/api/graphics/Vec3.cpp index c970d1c..4d67c03 100644 --- a/api/graphics/Vec3.cpp +++ b/api/graphics/Vec3.cpp @@ -3,6 +3,7 @@ // #include "Vec3.h" + #include "BlockPos.h" namespace trapdoor { @@ -11,12 +12,10 @@ namespace trapdoor { Vec3::Vec3(float _x) : Vec3(_x, _x, _x) {} float Vec3::distanceTo(const Vec3 &vec3) const { - return sqrt((vec3.x - x) * (vec3.x - x) + - (vec3.y - y) * (vec3.y - y) + + return sqrt((vec3.x - x) * (vec3.x - x) + (vec3.y - y) * (vec3.y - y) + (vec3.z - z) * (vec3.z - z)); } - std::string Vec3::toString() const { char buffer[64]; sprintf(buffer, "[%.2f %.2f %.2f]", x, y, z); @@ -30,15 +29,15 @@ namespace trapdoor { bool Vec3::operator==(const Vec3 &v) const { return x == v.x && y == v.y && z == v.z; } - - BlockPos Vec3::toBlockPos() const { - auto cx = x < 0 ? x - 1 : x; - auto cy = y < 0 ? y - 1 : y; - auto cz = z < 0 ? z - 1 : z; - return {cx, cy, cz}; - } - std::string Vec3::toDirString() const { + BlockPos Vec3::toBlockPos() const { + auto cx = x < 0 ? x - 1 : x; + auto cy = y < 0 ? y - 1 : y; + auto cz = z < 0 ? z - 1 : z; + return {cx, cy, cz}; + } + + std::string Vec3::toDirString() const { FACING fx = this->x > 0 ? FACING::POS_X : FACING::NEG_X; FACING fz = this->x > 0 ? FACING::POS_Z : FACING::NEG_Z; std::string s; @@ -57,14 +56,10 @@ namespace trapdoor { } bool Vec3::operator<(const Vec3 &rhs) const { - if (x < rhs.x) - return true; - if (rhs.x < x) - return false; - if (y < rhs.y) - return true; - if (rhs.y < y) - return false; + if (x < rhs.x) return true; + if (rhs.x < x) return false; + if (y < rhs.y) return true; + if (rhs.y < y) return false; return z < rhs.z; } @@ -79,4 +74,4 @@ namespace trapdoor { Vec3 Vec3::operator*(float times) const { return {x * times, y * times, z * times}; } -} \ No newline at end of file +} // namespace trapdoor \ No newline at end of file diff --git a/api/graphics/Vec3.h b/api/graphics/Vec3.h index 516d10c..6f47812 100644 --- a/api/graphics/Vec3.h +++ b/api/graphics/Vec3.h @@ -21,7 +21,8 @@ namespace trapdoor { explicit Vec3(float _x); - Vec3(int _x, int _y, int _z) : x((float) _x), y((float) _y), z((float) _z) {} + Vec3(int _x, int _y, int _z) + : x((float)_x), y((float)_y), z((float)_z) {} Vec3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} @@ -39,15 +40,13 @@ namespace trapdoor { float distanceTo(const Vec3 &vec3) const; - std::string toString() const; BlockPos toBlockPos() const; std::string toDirString() const; }; -} - +} // namespace trapdoor typedef trapdoor::Vec3 Vec3; -#endif //LIBMCBEMOD_VEC3_H +#endif // LIBMCBEMOD_VEC3_H diff --git a/api/language/I18nManager.cpp b/api/language/I18nManager.cpp index 96a7ca0..d579c9b 100644 --- a/api/language/I18nManager.cpp +++ b/api/language/I18nManager.cpp @@ -3,89 +3,90 @@ // #include "I18nManager.h" -#include "BDSMod.h" -#include "tools/DirtyLogger.h" + #include #include #include +#include "BDSMod.h" +#include "tools/DirtyLogger.h" + namespace trapdoor { -void I18nManager::findLanguageFile() { - namespace fs = std::filesystem; - fs::path path("plugins/trapdoor/lang"); - if (!fs::exists(path)) { - L_WARNING("can't find the language dictionary"); - return; - } - fs::directory_entry entry(path); //文件入口 - if (entry.status().type() == fs::file_type::directory) { - for (const auto &iter : fs::directory_iterator(path)) { - if (fs::is_regular_file(iter.path())) { - readLanguageFile(iter.path().string()); + void I18nManager::findLanguageFile() { + namespace fs = std::filesystem; + fs::path path("plugins/trapdoor/lang"); + if (!fs::exists(path)) { + L_WARNING("can't find the language dictionary"); + return; + } + fs::directory_entry entry(path); //文件入口 + if (entry.status().type() == fs::file_type::directory) { + for (const auto &iter : fs::directory_iterator(path)) { + if (fs::is_regular_file(iter.path())) { + readLanguageFile(iter.path().string()); + } } } } -} -void I18nManager::readLanguageFile(const std::string &path) { - if (path.size() < 10) { - return; - } - // auto langName = path.substr(5, path.size() - 10); - auto langName = path.substr(path.find_last_of('\\') + 1, - path.size() - path.find_last_of('.')); - // L_WARNING("find language file [%s]", langName.c_str()); - json langJson; - try { - std::ifstream i(path); - i >> langJson; - } catch (std::exception &e) { - L_ERROR("can not read config file %s ", path.c_str()); - return; - } + void I18nManager::readLanguageFile(const std::string &path) { + if (path.size() < 10) { + return; + } + // auto langName = path.substr(5, path.size() - 10); + auto langName = path.substr(path.find_last_of('\\') + 1, + path.size() - path.find_last_of('.')); + // L_WARNING("find language file [%s]", langName.c_str()); + json langJson; + try { + std::ifstream i(path); + i >> langJson; + } catch (std::exception &e) { + L_ERROR("can not read config file %s ", path.c_str()); + return; + } - this->languages.insert(langName); - try { - for (auto &[key, value] : langJson.items()) { - this->strings[langName][key] = value.get(); + this->languages.insert(langName); + try { + for (auto &[key, value] : langJson.items()) { + this->strings[langName][key] = value.get(); + } + } catch (std::exception &e) { + L_ERROR("can not read config file %s ", path.c_str()); } - } catch (std::exception &e) { - L_ERROR("can not read config file %s ", path.c_str()); } -} -bool I18nManager::tryChangeLanguage(const std::string &language) { - auto iter = this->languages.find(language); - if (iter == this->languages.end()) - return false; - this->current_lang = language; - return true; -} + bool I18nManager::tryChangeLanguage(const std::string &language) { + auto iter = this->languages.find(language); + if (iter == this->languages.end()) return false; + this->current_lang = language; + return true; + } -std::string I18nManager::get(const std::string &id) { - //找不到就按照原样返回 - auto iter = this->strings[current_lang].find(id); - if (iter != this->strings[current_lang].end()) { - return iter->second; + std::string I18nManager::get(const std::string &id) { + //找不到就按照原样返回 + auto iter = this->strings[current_lang].find(id); + if (iter != this->strings[current_lang].end()) { + return iter->second; + } + return id; } - return id; -} -void I18nManager::getSystemLangAndSet() { - LCID localeID = GetUserDefaultLCID(); - unsigned short lang = localeID & 0xFF; - if (lang == LANG_CHINESE) { - this->tryChangeLanguage("zh_cn"); - } else { - this->tryChangeLanguage("en_us"); + void I18nManager::getSystemLangAndSet() { + LCID localeID = GetUserDefaultLCID(); + unsigned short lang = localeID & 0xFF; + if (lang == LANG_CHINESE) { + this->tryChangeLanguage("zh_cn"); + } else { + this->tryChangeLanguage("en_us"); + } } -} -std::string LANG(const std::string &l) { - return trapdoor::bdsMod->getI18NManager().get(l); -} + std::string LANG(const std::string &l) { + return trapdoor::bdsMod->getI18NManager().get(l); + } -} // namespace trapdoor +} // namespace trapdoor std::string operator""_i18(const char *key, unsigned long long) { return trapdoor::LANG(key); diff --git a/api/language/I18nManager.h b/api/language/I18nManager.h index c0b8044..4f13066 100644 --- a/api/language/I18nManager.h +++ b/api/language/I18nManager.h @@ -5,47 +5,47 @@ #ifndef MOD_I18NMANAGER_H #define MOD_I18NMANAGER_H -#include "tools/json.hpp" #include #include +#include "tools/json.hpp" + namespace trapdoor { -using json = nlohmann::json; + using json = nlohmann::json; -class I18nManager { - std::string current_lang = "zh_cn"; - std::set languages; - std::unordered_map> - strings; + class I18nManager { + std::string current_lang = "zh_cn"; + std::set languages; + std::unordered_map> + strings; - void findLanguageFile(); + void findLanguageFile(); - void readLanguageFile(const std::string &langName); + void readLanguageFile(const std::string &langName); - void getSystemLangAndSet(); + void getSystemLangAndSet(); - public: - std::string get(const std::string &id); + public: + std::string get(const std::string &id); - bool tryChangeLanguage(const std::string &language); + bool tryChangeLanguage(const std::string &language); - std::string getAllLanguages() { - std::string s; - for (const auto &lang : this->languages) - s += lang + "\n"; - return s; - } + std::string getAllLanguages() { + std::string s; + for (const auto &lang : this->languages) s += lang + "\n"; + return s; + } - inline void initialize() { - this->getSystemLangAndSet(); - this->findLanguageFile(); - } -}; + inline void initialize() { + this->getSystemLangAndSet(); + this->findLanguageFile(); + } + }; -std::string LANG(const std::string &l); -} // namespace trapdoor + std::string LANG(const std::string &l); +} // namespace trapdoor std::string operator""_i18(const char *key, unsigned long long); -#endif // MOD_I18NMANAGER_H +#endif // MOD_I18NMANAGER_H diff --git a/api/lib/SymHook.h b/api/lib/SymHook.h index 66cd337..1cf1e9d 100644 Binary files a/api/lib/SymHook.h and b/api/lib/SymHook.h differ diff --git a/api/lib/SymHook.h.bak b/api/lib/SymHook.h.bak new file mode 100644 index 0000000..6d684cf --- /dev/null +++ b/api/lib/SymHook.h.bak @@ -0,0 +1,315 @@ +#pragma once + +namespace SymHook { +using RVA = unsigned int; + +// [] public: virtual class Actor * __ptr64 __cdecl Level::fetchEntity(struct +// ActorUniqueID,bool)const __ptr64 [] +// ?fetchEntity@Level@@UEBAPEAVActor@@UActorUniqueID@@_N@Z +constexpr RVA + MSSYM_B1QE11fetchEntityB1AA5LevelB2AAE13UEBAPEAVActorB2AAE14UActorUniqueIDB3AAUA1NB1AA1Z = + 0x00F87EA0; + +// TODO: 生成例子效果 +constexpr RVA MSSYM_MD5_52e7de092fab8d042fb516e31fc9756f = 0x00F9B190; + +// [] void __cdecl CommandUtils::displayLocalizableMessage(bool,class Player & +// __ptr64,class std::basic_string,class +// std::allocator > const & __ptr64,class std::vector,class +// std::allocator >,class std::allocator,class +// std::allocator > > > const & __ptr64) [] +// ?displayLocalizableMessage@CommandUtils@@YAX_NAEAVPlayer@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEBV?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@4@@Z +constexpr RVA MSSYM_MD5_24be62e9330073695808606844de0d99 = 0x007815B0; + +// [] public: virtual void __cdecl ServerLevel::tick(void) __ptr64 +// [] ?tick@ServerLevel@@UEAAXXZ +constexpr RVA MSSYM_B1QA4tickB1AE11ServerLevelB2AAA7UEAAXXZ = 0x0079BC60; + +// [] public: virtual int __cdecl ServerPlayer::tickWorld(struct Tick const & +// __ptr64) __ptr64 [] ?tickWorld@ServerPlayer@@UEAAHAEBUTick@@@Z +constexpr RVA + MSSYM_B1QA9tickWorldB1AE12ServerPlayerB2AAE13UEAAHAEBUTickB3AAAA1Z = + 0x0079BE90; + +// [] public: virtual void __cdecl Dimension::tick(void) __ptr64 +// [] ?tick@Dimension@@UEAAXXZ +constexpr RVA MSSYM_B1QA4tickB1AA9DimensionB2AAA7UEAAXXZ = 0x01004E10; + +// [] public: void __cdecl LevelChunk::tick(class BlockSource & __ptr64,struct +// Tick const & __ptr64) __ptr64 [] +// ?tick@LevelChunk@@QEAAXAEAVBlockSource@@AEBUTick@@@Z +constexpr RVA + MSSYM_B1QA4tickB1AE10LevelChunkB2AAE20QEAAXAEAVBlockSourceB2AAA8AEBUTickB3AAAA1Z = + 0x00F59910; + +// [] public: void __cdecl LevelChunk::tickBlocks(class BlockSource & __ptr64) +// __ptr64 [] ?tickBlocks@LevelChunk@@QEAAXAEAVBlockSource@@@Z +constexpr RVA + MSSYM_B1QE10tickBlocksB1AE10LevelChunkB2AAE20QEAAXAEAVBlockSourceB3AAAA1Z = + 0x00F5A6D0; + +// [] public: void __cdecl LevelChunk::tickBlockEntities(class BlockSource & +// __ptr64) __ptr64 [] +// ?tickBlockEntities@LevelChunk@@QEAAXAEAVBlockSource@@@Z +constexpr RVA + MSSYM_B1QE17tickBlockEntitiesB1AE10LevelChunkB2AAE20QEAAXAEAVBlockSourceB3AAAA1Z = + 0x00F5A380; + +// [] public: bool __cdecl BlockTickingQueue::tickPendingTicks(class BlockSource +// & __ptr64,struct Tick const & __ptr64,int,bool) __ptr64 [] +// ?tickPendingTicks@BlockTickingQueue@@QEAA_NAEAVBlockSource@@AEBUTick@@H_N@Z +constexpr RVA + MSSYM_B1QE16tickPendingTicksB1AE17BlockTickingQueueB2AAA4QEAAB1UE16NAEAVBlockSourceB2AAA8AEBUTickB2AAA1HB1UA1NB1AA1Z = + 0x00F9D180; + +// [] public: virtual void __cdecl Dimension::tickRedstone(void) __ptr64 +// [] ?tickRedstone@Dimension@@UEAAXXZ +constexpr RVA MSSYM_B1QE12tickRedstoneB1AA9DimensionB2AAA7UEAAXXZ = 0x01005190; + + +// [] public: bool __cdecl Actor::tick(class BlockSource & __ptr64) __ptr64 +// [] ?tick@Actor@@QEAA_NAEAVBlockSource@@@Z +constexpr RVA + MSSYM_B1QA4tickB1AA5ActorB2AAA4QEAAB1UE16NAEAVBlockSourceB3AAAA1Z = + 0x00BC5C20; + +// [] public: virtual void __cdecl Actor::getDebugText(class std::vector,class +// std::allocator >,class std::allocator,class +// std::allocator > > > & __ptr64) __ptr64 [] +// ?getDebugText@Actor@@UEAAXAEAV?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@@Z +constexpr RVA MSSYM_MD5_f04fad6bac034f1e861181d3580320f2 = 0x00B9FCF0; + +// [] public: virtual class Vec3 const & __ptr64 __cdecl +// Actor::getPos(void)const __ptr64 [] ?getPos@Actor@@UEBAAEBVVec3@@XZ +constexpr RVA MSSYM_B1QA6getPosB1AA5ActorB2AAE12UEBAAEBVVec3B2AAA2XZ = + 0x00BA29C0; + +// [TODO:] public: virtual bool __cdecl Player::attack(class Actor & __ptr64) +// __ptr64 [] ?attack@Player@@UEAA_NAEAVActor@@@Z +constexpr RVA MSSYM_B1QA6attackB1AA6PlayerB2AAA4UEAAB1UE10NAEAVActorB3AAAA1Z = + 0x00BB8AC0; + +// [] public: void __cdecl Explosion::explode(void) __ptr64 +// [] ?explode@Explosion@@QEAAXXZ +constexpr RVA MSSYM_B1QA7explodeB1AA9ExplosionB2AAA7QEAAXXZ = 0x00F83DE0; + +// [] public: virtual void __cdecl Actor::setNameTag(class +// std::basic_string,class +// std::allocator > const & __ptr64) __ptr64 [] +// ?setNameTag@Actor@@UEAAXAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z +constexpr RVA + MSSYM_B1QE10setNameTagB1AA5ActorB2AAA9UEAAXAEBVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB3AAAA1Z = + 0x00BBEB30; + +// [] public: class Vec3 __cdecl Actor::getViewVector(float)const __ptr64 +// [] ?getViewVector@Actor@@QEBA?AVVec3@@M@Z +constexpr RVA + MSSYM_B1QE13getViewVectorB1AA5ActorB2AAA4QEBAB1QA6AVVec3B2AAA1MB1AA1Z = + 0x00BA38E0; + +// [] public: virtual class std::basic_string,class std::allocator > const & __ptr64 __cdecl +// Actor::getNameTag(void)const __ptr64 [] +// ?getNameTag@Actor@@UEBAAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ +constexpr RVA + MSSYM_B1QE10getNameTagB1AA5ActorB2AAA8UEBAAEBVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB2AAA2XZ = + 0x00BA2660; + + +// [] public: virtual void __cdecl ServerPlayer::setPlayerGameType(enum +// GameType) __ptr64 [] ?setPlayerGameType@ServerPlayer@@UEAAXW4GameType@@@Z +constexpr RVA + MSSYM_B1QE17setPlayerGameTypeB1AE12ServerPlayerB2AAE15UEAAXW4GameTypeB3AAAA1Z = + 0x00799170; + +// [] public: class Block const & __ptr64 __cdecl BlockSource::getBlock(class +// BlockPos const & __ptr64)const __ptr64 [] +// ?getBlock@BlockSource@@QEBAAEBVBlock@@AEBVBlockPos@@@Z +constexpr RVA + MSSYM_B1QA8getBlockB1AE11BlockSourceB2AAE13QEBAAEBVBlockB2AAE12AEBVBlockPosB3AAAA1Z = + 0x00F8A4C0; + +// [] public: bool __cdecl BlockSource::setBlock(int,int,int,class Block const & +// __ptr64,int) __ptr64 [] ?setBlock@BlockSource@@QEAA_NHHHAEBVBlock@@H@Z +constexpr RVA + MSSYM_B1QA8setBlockB1AE11BlockSourceB2AAA4QEAAB1UE13NHHHAEBVBlockB2AAA1HB1AA1Z = + 0x00F99E20; + +// [] public: void __cdecl BlockSource::updateNeighborsAt(class BlockPos const & +// __ptr64) __ptr64 [] ?updateNeighborsAt@BlockSource@@QEAAXAEBVBlockPos@@@Z +constexpr RVA + MSSYM_B1QE17updateNeighborsAtB1AE11BlockSourceB2AAE17QEAAXAEBVBlockPosB3AAAA1Z = + 0x00F9E610; + +// [] public: virtual enum EventResult __cdecl +// VanillaServerGameplayEventListener::onBlockPlacedByPlayer(class Player & +// __ptr64,class Block const & __ptr64,class BlockPos const & __ptr64,bool) +// __ptr64 [] +// ?onBlockPlacedByPlayer@VanillaServerGameplayEventListener@@UEAA?AW4EventResult@@AEAVPlayer@@AEBVBlock@@AEBVBlockPos@@_N@Z +constexpr RVA + MSSYM_B1QE21onBlockPlacedByPlayerB1AE34VanillaServerGameplayEventListenerB2AAA4UEAAB1QE14AW4EventResultB2AAE10AEAVPlayerB2AAA9AEBVBlockB2AAE12AEBVBlockPosB3AAUA1NB1AA1Z = + 0x003C7FF0; + +// [] public: class std::basic_string,class +// std::allocator > __cdecl Block::toDebugString(void)const __ptr64 [] +// ?toDebugString@Block@@QEBA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ +constexpr RVA + MSSYM_B1QE13toDebugStringB1AA5BlockB2AAA4QEBAB1QA2AVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB2AAA2XZ = + 0x010AC360; + + +// [] public: class Block const * __ptr64 __cdecl +// BlockLegacy::tryGetStateFromLegacyData(unsigned short)const __ptr64 [] +// ?tryGetStateFromLegacyData@BlockLegacy@@QEBAPEBVBlock@@G@Z +constexpr RVA + MSSYM_B1QE25tryGetStateFromLegacyDataB1AE11BlockLegacyB2AAE13QEBAPEBVBlockB2AAA1GB1AA1Z = + 0x010AD410; + +// [] public: class Biome & __ptr64 __cdecl BlockSource::getBiome(class BlockPos +// const & __ptr64) __ptr64 [] +// ?getBiome@BlockSource@@QEAAAEAVBiome@@AEBVBlockPos@@@Z +constexpr RVA + MSSYM_B1QA8getBiomeB1AE11BlockSourceB2AAE13QEAAAEAVBiomeB2AAE12AEBVBlockPosB3AAAA1Z = + 0x00F8A3C0; + +// [] public: void __cdecl Village::tick(struct Tick,class BlockSource & +// __ptr64) __ptr64 [] ?tick@Village@@QEAAXUTick@@AEAVBlockSource@@@Z +constexpr RVA + MSSYM_B1QA4tickB1AA7VillageB2AAE10QEAAXUTickB2AAE15AEAVBlockSourceB3AAAA1Z = + 0x00DAA0E0; + +// [] public: float __cdecl Village::getApproximateRadius(void)const __ptr64 +// [] ?getApproximateRadius@Village@@QEBAMXZ +constexpr RVA MSSYM_B1QE20getApproximateRadiusB1AA7VillageB2AAA7QEBAMXZ = + 0x00DA2F00; + +// [] public: unsigned __int64 __cdecl Village::getBedPOICount(void)const +// __ptr64 [] ?getBedPOICount@Village@@QEBA_KXZ +constexpr RVA MSSYM_B1QE14getBedPOICountB1AA7VillageB2AAA4QEBAB1UA3KXZ = + 0x00DA3070; + +// [] public: virtual class MobSpawnerData const * __ptr64 __cdecl +// BlockLegacy::getMobToSpawn(class SpawnConditions const & __ptr64,class +// BlockSource & __ptr64)const __ptr64 [] +// ?getMobToSpawn@BlockLegacy@@UEBAPEBVMobSpawnerData@@AEBVSpawnConditions@@AEAVBlockSource@@@Z +constexpr RVA + MSSYM_B1QE13getMobToSpawnB1AE11BlockLegacyB2AAE22UEBAPEBVMobSpawnerDataB2AAE19AEBVSpawnConditionsB2AAE15AEAVBlockSourceB3AAAA1Z = + 0x010A3C30; + +// [] private: void __cdecl Spawner::_spawnStructureMob(class BlockSource & +// __ptr64,class BlockPos const & __ptr64,struct +// LevelChunk::HardcodedSpawningArea const & __ptr64,class SpawnConditions const +// & __ptr64) __ptr64 [] +// ?_spawnStructureMob@Spawner@@AEAAXAEAVBlockSource@@AEBVBlockPos@@AEBUHardcodedSpawningArea@LevelChunk@@AEBVSpawnConditions@@@Z +constexpr RVA + MSSYM_B2QUE17spawnStructureMobB1AA7SpawnerB2AAE20AEAAXAEAVBlockSourceB2AAE12AEBVBlockPosB2AAE25AEBUHardcodedSpawningAreaB1AE10LevelChunkB2AAE19AEBVSpawnConditionsB3AAAA1Z = + 0x01121720; + +// [] public: static bool __cdecl Spawner::findNextSpawnBlockUnder(class +// BlockSource const & __ptr64,class BlockPos & __ptr64,enum MaterialType,enum +// SpawnBlockRequirements) [] +// ?findNextSpawnBlockUnder@Spawner@@SA_NAEBVBlockSource@@AEAVBlockPos@@W4MaterialType@@W4SpawnBlockRequirements@@@Z +constexpr RVA + MSSYM_B1QE23findNextSpawnBlockUnderB1AA7SpawnerB2AAA2SAB1UE16NAEBVBlockSourceB2AAE12AEAVBlockPosB2AAE14W4MaterialTypeB2AAE24W4SpawnBlockRequirementsB3AAAA1Z = + 0x011236A0; + +// [] public: virtual void __cdecl HopperBlockActor::setItem(int,class ItemStack +// const & __ptr64) __ptr64 [] +// ?setItem@HopperBlockActor@@UEAAXHAEBVItemStack@@@Z +constexpr RVA + MSSYM_B1QA7setItemB1AE16HopperBlockActorB2AAE19UEAAXHAEBVItemStackB3AAAA1Z = + 0x010F1140; + +// [] public: class std::basic_string,class +// std::allocator > __cdecl ItemStackBase::getName(void)const __ptr64 +// [] +// ?getName@ItemStackBase@@QEBA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ +constexpr RVA + MSSYM_B1QA7getNameB1AE13ItemStackBaseB2AAA4QEBAB1QA2AVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB2AAA2XZ = + 0x00C86470; + +// [] public: bool __cdecl Item::useOn(class ItemStack & __ptr64,class Actor & +// __ptr64,int,int,int,unsigned char,float,float,float)const __ptr64 [] +// ?useOn@Item@@QEBA_NAEAVItemStack@@AEAVActor@@HHHEMMM@Z +constexpr RVA + MSSYM_B1QA5useOnB1AA4ItemB2AAA4QEBAB1UE14NAEAVItemStackB2AAA9AEAVActorB2AAA7HHHEMMMB1AA1Z = + 0x00E34C90; + +// [] public: class BaseCircuitComponent * __ptr64 __cdecl +// CircuitSceneGraph::getBaseComponent(class BlockPos const & __ptr64) __ptr64 +// [] +// ?getBaseComponent@CircuitSceneGraph@@QEAAPEAVBaseCircuitComponent@@AEBVBlockPos@@@Z +constexpr RVA + MSSYM_B1QE16getBaseComponentB1AE17CircuitSceneGraphB2AAE28QEAAPEAVBaseCircuitComponentB2AAE12AEBVBlockPosB3AAAA1Z = + 0x0106D4F0; + +// [] public: enum VanillaBiomeTypes __cdecl Biome::getBiomeType(void)const +// __ptr64 [] ?getBiomeType@Biome@@QEBA?AW4VanillaBiomeTypes@@XZ +constexpr RVA + MSSYM_B1QE12getBiomeTypeB1AA5BiomeB2AAA4QEBAB1QE20AW4VanillaBiomeTypesB2AAA2XZ = + 0x01123A60; + +// [] public: unsigned __int64 __cdecl NetworkIdentifier::getHash(void)const +// __ptr64 [] ?getHash@NetworkIdentifier@@QEBA_KXZ +constexpr RVA MSSYM_B1QA7getHashB1AE17NetworkIdentifierB2AAA4QEBAB1UA3KXZ = + 0x006BB710; + +// [] public: virtual void __cdecl ServerNetworkHandler::handle(class +// NetworkIdentifier const & __ptr64,class CommandRequestPacket const & __ptr64) +// __ptr64 [] +// ?handle@ServerNetworkHandler@@UEAAXAEBVNetworkIdentifier@@AEBVCommandRequestPacket@@@Z +constexpr RVA + MSSYM_B1QA6handleB1AE20ServerNetworkHandlerB2AAE26UEAAXAEBVNetworkIdentifierB2AAE24AEBVCommandRequestPacketB3AAAA1Z = + 0x006EA700; + +// [] public: void __cdecl CommandRegistry::registerCommand(class +// std::basic_string,class +// std::allocator > const & __ptr64,char const * __ptr64,enum +// CommandPermissionLevel,struct CommandFlag,struct CommandFlag) __ptr64 [] +// ?registerCommand@CommandRegistry@@QEAAXAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PEBDW4CommandPermissionLevel@@UCommandFlag@@3@Z +constexpr RVA MSSYM_MD5_8574de98358ff66b5a913417f44dd706 = 0x00793530; + +// [] public: virtual enum CommandPermissionLevel __cdecl +// Player::getCommandPermissionLevel(void)const __ptr64 [] +// ?getCommandPermissionLevel@Player@@UEBA?AW4CommandPermissionLevel@@XZ +constexpr RVA + MSSYM_B1QE25getCommandPermissionLevelB1AA6PlayerB2AAA4UEBAB1QE25AW4CommandPermissionLevelB2AAA2XZ = + 0x00BF9460; + + +// [] public: static void __cdecl BlockTypeRegistry::forEachBlock(class +// std::function) [] +// ?forEachBlock@BlockTypeRegistry@@SAXV?$function@$$A6A_NAEBVBlockLegacy@@@Z@std@@@Z +constexpr RVA + MSSYM_B1QE12forEachBlockB1AE17BlockTypeRegistryB2AAA4SAXVB2QDA8functionB3ADDA3A6AB1UE16NAEBVBlockLegacyB3AAAA1ZB1AA3stdB3AAAA1Z = + 0x00F0F0A0; + +// [] private: void __cdecl CircuitSceneGraph::removeComponent(class BlockPos +// const & __ptr64) __ptr64 [] +// ?removeComponent@CircuitSceneGraph@@AEAAXAEBVBlockPos@@@Z +constexpr RVA + MSSYM_B1QE15removeComponentB1AE17CircuitSceneGraphB2AAE17AEAAXAEBVBlockPosB3AAAA1Z = + 0x0106FB40; + +// [] private: void __cdecl CircuitSceneGraph::processPendingAdds(void) __ptr64 +// [] ?processPendingAdds@CircuitSceneGraph@@AEAAXXZ +constexpr RVA + MSSYM_B1QE18processPendingAddsB1AE17CircuitSceneGraphB2AAA7AEAAXXZ = + 0x0106EC50; + + +// [TODO:] public: virtual class Dimension * __ptr64 __cdecl +// Level::getDimension(class AutomaticID)const __ptr64 +// [] +// ?getDimension@Level@@UEBAPEAVDimension@@V?$AutomaticID@VDimension@@H@@@Z +constexpr RVA + MSSYM_B1QE12getDimensionB1AA5LevelB2AAE17UEBAPEAVDimensionB2AAA1VB2QDE11AutomaticIDB1AE10VDimensionB2AAA1HB3AAAA1Z = + 0x00F8AE90; + +constexpr RVA MSSYM_tickEntitySystemsLevelUEAAXXZ = 0x00F9CFE0; + +} // namespace SymHook diff --git a/api/tools/CastHelper.h b/api/tools/CastHelper.h index 6595767..04b3132 100644 --- a/api/tools/CastHelper.h +++ b/api/tools/CastHelper.h @@ -7,7 +7,7 @@ #include -template +template /* * [ ] * |<----bytes---->| @@ -18,4 +18,4 @@ T offset_cast(void *ptr, size_t bytes) { return reinterpret_cast(reinterpret_cast(ptr) + bytes); } -#endif //MOD_CASTHELPER_H +#endif // MOD_CASTHELPER_H diff --git a/api/tools/DirtyLogger.cpp b/api/tools/DirtyLogger.cpp index 17f1b50..db10c32 100644 --- a/api/tools/DirtyLogger.cpp +++ b/api/tools/DirtyLogger.cpp @@ -5,92 +5,93 @@ // #define _WINSOCKAPI_ +#include "DirtyLogger.h" + #include + #include #include -#include "DirtyLogger.h" - namespace trapdoor { -namespace { -LOG_LEVEL logLevel = LOG_LEVEL::LOG_INFO; -FILE *logger = nullptr; -bool devMode = false; + namespace { + LOG_LEVEL logLevel = LOG_LEVEL::LOG_INFO; + FILE *logger = nullptr; + bool devMode = false; -void setColor(int k) { - HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(hConsole, k); -} -} // namespace + void setColor(int k) { + HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + SetConsoleTextAttribute(hConsole, k); + } + } // namespace -//初始化日志,不然不能使用 -void initLogger(const std::string &logFileName) { - logger = fopen(logFileName.c_str(), "a+"); - L_DEBUG("\n-------------------------TRAPDOOR LOG " + //初始化日志,不然不能使用 + void initLogger(const std::string &logFileName) { + logger = fopen(logFileName.c_str(), "a+"); + L_DEBUG( + "\n-------------------------TRAPDOOR LOG " "FILE---------------------------\n " "-----------------------------init " "BDS------------------------------- \n"); - if (!logger) - logger = stderr; -} - -//向日志里面打印信息 -//如果是开发者模式就打印所有日志,无视日志等级 -void logInfo(LOG_LEVEL level, const char *functionName, const char *fmt, ...) { - if (logLevel > level && !devMode) - return; - switch (level) { - case LOG_LEVEL::LOG_DEBUG: - setColor(10); // green - break; - case LOG_LEVEL::LOG_INFO: - setColor(7); // white - break; - case LOG_LEVEL::LOG_WARNING: - setColor(6); - break; - case LOG_LEVEL::LOG_ERROR: - setColor(4); - break; - case LOG_LEVEL::NO_LOG: - break; - } - va_list args; - va_start(args, fmt); - time_t rawTime; - time(&rawTime); - struct tm *t = localtime(&rawTime); - fprintf(logger, "[%.2d-%.2d %.2d:%.2d:%.2d]", t->tm_mon + 1, t->tm_mday, - t->tm_hour, t->tm_min, t->tm_sec); - switch (logLevel) { - case LOG_LEVEL::LOG_ERROR: - fprintf(logger, "[ERROR] "); - break; - case LOG_LEVEL::LOG_DEBUG: - fprintf(logger, "[DEBUG] "); - break; - case LOG_LEVEL::LOG_INFO: - fprintf(logger, "[INFO] "); - break; - case LOG_LEVEL::LOG_WARNING: - fprintf(logger, "[WARN] "); - break; - case LOG_LEVEL::NO_LOG: - break; + if (!logger) logger = stderr; } - fprintf(logger, "(%s) ", functionName); - //输出到桌面(桌面输出不需要输出时间和函数名称) - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - fflush(stdout); - //输出到日志文件 - vfprintf(logger, fmt, args); - fprintf(logger, "\n"); - fflush(logger); -} + //向日志里面打印信息 + //如果是开发者模式就打印所有日志,无视日志等级 + void logInfo(LOG_LEVEL level, const char *functionName, const char *fmt, + ...) { + if (logLevel > level && !devMode) return; + switch (level) { + case LOG_LEVEL::LOG_DEBUG: + setColor(10); // green + break; + case LOG_LEVEL::LOG_INFO: + setColor(7); // white + break; + case LOG_LEVEL::LOG_WARNING: + setColor(6); + break; + case LOG_LEVEL::LOG_ERROR: + setColor(4); + break; + case LOG_LEVEL::NO_LOG: + break; + } + va_list args; + va_start(args, fmt); + time_t rawTime; + time(&rawTime); + struct tm *t = localtime(&rawTime); + fprintf(logger, "[%.2d-%.2d %.2d:%.2d:%.2d]", t->tm_mon + 1, t->tm_mday, + t->tm_hour, t->tm_min, t->tm_sec); + switch (logLevel) { + case LOG_LEVEL::LOG_ERROR: + fprintf(logger, "[ERROR] "); + break; + case LOG_LEVEL::LOG_DEBUG: + fprintf(logger, "[DEBUG] "); + break; + case LOG_LEVEL::LOG_INFO: + fprintf(logger, "[INFO] "); + break; + case LOG_LEVEL::LOG_WARNING: + fprintf(logger, "[WARN] "); + break; + case LOG_LEVEL::NO_LOG: + break; + } + + fprintf(logger, "(%s) ", functionName); + //输出到桌面(桌面输出不需要输出时间和函数名称) + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + fflush(stdout); + //输出到日志文件 + vfprintf(logger, fmt, args); + fprintf(logger, "\n"); + fflush(logger); + } -void setLogLevel(LOG_LEVEL log_level) { logLevel = log_level; } + void setLogLevel(LOG_LEVEL log_level) { logLevel = log_level; } -void setDevMode(bool useDevMode) { devMode = useDevMode; } -} // namespace trapdoor + void setDevMode(bool useDevMode) { devMode = useDevMode; } +} // namespace trapdoor diff --git a/api/tools/DirtyLogger.h b/api/tools/DirtyLogger.h index a9bb72b..7d2dd2a 100644 --- a/api/tools/DirtyLogger.h +++ b/api/tools/DirtyLogger.h @@ -8,22 +8,35 @@ #include #include -#define L_DEBUG(fmt, ...) trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_DEBUG, __FUNCTION__, fmt, __VA_ARGS__) -#define L_INFO(fmt, ...) trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_INFO, __FUNCTION__, fmt, __VA_ARGS__) -#define L_WARNING(fmt, ...) trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_WARNING, __FUNCTION__, fmt, __VA_ARGS__) -#define L_ERROR(fmt, ...) trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_ERROR, __FUNCTION__, fmt, __VA_ARGS__) +#define L_DEBUG(fmt, ...) \ + trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_DEBUG, __FUNCTION__, fmt, \ + __VA_ARGS__) +#define L_INFO(fmt, ...) \ + trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_INFO, __FUNCTION__, fmt, \ + __VA_ARGS__) +#define L_WARNING(fmt, ...) \ + trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_WARNING, __FUNCTION__, fmt, \ + __VA_ARGS__) +#define L_ERROR(fmt, ...) \ + trapdoor::logInfo(trapdoor::LOG_LEVEL::LOG_ERROR, __FUNCTION__, fmt, \ + __VA_ARGS__) namespace trapdoor { enum class LOG_LEVEL { - LOG_DEBUG = 0, LOG_INFO = 1, LOG_WARNING = 2, LOG_ERROR = 3, NO_LOG = 4 + LOG_DEBUG = 0, + LOG_INFO = 1, + LOG_WARNING = 2, + LOG_ERROR = 3, + NO_LOG = 4 }; void initLogger(const std::string &logFileName); void setLogLevel(LOG_LEVEL level); - void logInfo(LOG_LEVEL logLevel, const char *functionName, const char *fmt, ...); + void logInfo(LOG_LEVEL logLevel, const char *functionName, const char *fmt, + ...); void setDevMode(bool useDevMode); -} -#endif //TRAPDOOR_DIRTYLOGGER_H +} // namespace trapdoor +#endif // TRAPDOOR_DIRTYLOGGER_H diff --git a/api/tools/Message.cpp b/api/tools/Message.cpp index 15129eb..2d4414c 100644 --- a/api/tools/Message.cpp +++ b/api/tools/Message.cpp @@ -3,25 +3,29 @@ // #include "Message.h" + +#include + #include "DirtyLogger.h" #include "entity/Actor.h" #include "lib/SymHook.h" -#include namespace trapdoor { -using namespace SymHook; + using namespace SymHook; -void mcbe_sendMessage(const std::string &s, Actor *player) { - if (!player) { - L_DEBUG("send message [%s] to a nullptr player", s.c_str()); - return; + void mcbe_sendMessage(const std::string &s, Actor *player) { + if (!player) { + L_DEBUG("send message [%s] to a nullptr player", s.c_str()); + return; + } + L_DEBUG("send message [%s] to %s", s.c_str(), + player->getNameTag().c_str()); + std::vector v; + v.emplace_back("test"); + SYM_CALL(void (*)(bool, Actor *, const std::string &, + std::vector &), + CommandUtils_displayLocalizableMessage_24be62e9, true, player, + s, v); } - L_DEBUG("send message [%s] to %s", s.c_str(), player->getNameTag().c_str()); - std::vector v; - v.emplace_back("test"); - SYM_CALL(void (*)(bool, Actor *, const std::string &, - std::vector &), - MSSYM_MD5_24be62e9330073695808606844de0d99, true, player, s, v); -} -} // namespace trapdoor +} // namespace trapdoor diff --git a/api/tools/Message.h b/api/tools/Message.h index 95de7a4..4b268b3 100644 --- a/api/tools/Message.h +++ b/api/tools/Message.h @@ -5,10 +5,11 @@ #ifndef TRAPDOOR_MESSAGE_H #define TRAPDOOR_MESSAGE_H +#include + +#include "BDSMod.h" #include "lib/mod.h" #include "world/Level.h" -#include "BDSMod.h" -#include #define STR(x) #x #define C_DARK_RED(x) "§4" STR(x) "§r" @@ -21,61 +22,58 @@ #define C_LIGHT_PURPLE(x) "§d" STR(x) "§r" #define C_WHITE(x) "§f" STR(x) "§r" #define C_GRAY(x) "§7" STR(x) "§r" -#define C_BLACK(x) "§0" STR(x) "§r" +#define C_BLACK(x) "§0" STR(x) "§r" #define C_BOLD(x) "§l" STR(x) "§r" -#define C_ITALIC "§o" STR(x) "§r" -#define C_INT C_GREEN( %d ) -#define C_FLOAT C_GREEN( %.3f ) -#define C_POS C_AQUA(%d %d %d) -#define C_VEC3 C_LIGHT_PURPLE(%.2f %.2f %.2f) +#define C_ITALIC "§o" STR(x) "§r" +#define C_INT C_GREEN(% d) +#define C_FLOAT C_GREEN(% .3f) +#define C_POS C_AQUA(% d % d % d) +#define C_VEC3 C_LIGHT_PURPLE(% .2f % .2f % .2f) namespace trapdoor { class Actor; - void mcbe_sendMessage(const std::string &s, Actor *player); - template - std::string format(const std::string &format, Args ... args) { - int size = snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0' - if (size <= 0) - return ""; + template + std::string format(const std::string &format, Args... args) { + int size = snprintf(nullptr, 0, format.c_str(), args...) + + 1; // Extra space for '\0' + if (size <= 0) return ""; std::unique_ptr buf(new char[size]); - snprintf(buf.get(), size, format.c_str(), args ...); - return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside + snprintf(buf.get(), size, format.c_str(), args...); + return std::string( + buf.get(), buf.get() + size - 1); // We don't want the '\0' inside } - template - void gamePrintf(Actor *player, const std::string &prefix, const std::string &fmt, Args ...args) { + template + void gamePrintf(Actor *player, const std::string &prefix, + const std::string &fmt, Args... args) { const std::string message = prefix + format(fmt, args...); mcbe_sendMessage(message, player); } - - template - void warning(Actor *player, const std::string &format, Args ... args) { + template + void warning(Actor *player, const std::string &format, Args... args) { gamePrintf(player, "§6", format, args...); } - template - void error(Actor *player, const std::string &format, Args ... args) { + template + void error(Actor *player, const std::string &format, Args... args) { gamePrintf(player, "§c", format, args...); } - template - void info(Actor *player, const std::string &format, Args ... args) { + template + void info(Actor *player, const std::string &format, Args... args) { gamePrintf(player, "", format, args...); } - - template + template void broadcastMsg(const std::string &fmt, Args... args) { auto msg = format(fmt, args...); - trapdoor::bdsMod->getLevel()->forEachPlayer([&msg](Actor *player) { - mcbe_sendMessage(msg, player); - }); + trapdoor::bdsMod->getLevel()->forEachPlayer( + [&msg](Actor *player) { mcbe_sendMessage(msg, player); }); } -} - +} // namespace trapdoor -#endif //TRAPDOOR_MESSAGE_H +#endif // TRAPDOOR_MESSAGE_H diff --git a/api/tools/MsgBuilder.cpp b/api/tools/MsgBuilder.cpp index 633bc3e..c9a9277 100644 --- a/api/tools/MsgBuilder.cpp +++ b/api/tools/MsgBuilder.cpp @@ -4,78 +4,78 @@ // todo // 这个builder要重写,因为不够实用,尽量用模板重新实现一个类printf接口的Buider #include "MsgBuilder.h" + #include "Message.h" #include "entity/Actor.h" namespace trapdoor { -const uint8_t MessageBuilder::BLACK = 0x0; -const uint8_t MessageBuilder::DARK_GREEN = 0x2; -const uint8_t MessageBuilder::DARK_READ = 0x4; -const uint8_t MessageBuilder::GOLD = 0x6; -const uint8_t MessageBuilder::GRAY = 0x7; -const uint8_t MessageBuilder::BLUE = 0x9; -const uint8_t MessageBuilder::GREEN = 0xa; -const uint8_t MessageBuilder::AQUA = 0xb; -const uint8_t MessageBuilder::RED = 0xc; -const uint8_t MessageBuilder::LIGHT_PURPLE = 0xd; -const uint8_t MessageBuilder::YELLOW = 0xe; -const uint8_t MessageBuilder::WHITE = 0xf; + const uint8_t MessageBuilder::BLACK = 0x0; + const uint8_t MessageBuilder::DARK_GREEN = 0x2; + const uint8_t MessageBuilder::DARK_READ = 0x4; + const uint8_t MessageBuilder::GOLD = 0x6; + const uint8_t MessageBuilder::GRAY = 0x7; + const uint8_t MessageBuilder::BLUE = 0x9; + const uint8_t MessageBuilder::GREEN = 0xa; + const uint8_t MessageBuilder::AQUA = 0xb; + const uint8_t MessageBuilder::RED = 0xc; + const uint8_t MessageBuilder::LIGHT_PURPLE = 0xd; + const uint8_t MessageBuilder::YELLOW = 0xe; + const uint8_t MessageBuilder::WHITE = 0xf; -const uint8_t MessageBuilder::BOLD = 0x10; -const uint8_t MessageBuilder::ITALIC = 0x20; -const uint8_t MessageBuilder::RESET = 0x30; + const uint8_t MessageBuilder::BOLD = 0x10; + const uint8_t MessageBuilder::ITALIC = 0x20; + const uint8_t MessageBuilder::RESET = 0x30; -const std::map MessageBuilder::STYLE_MAP = { - {BLACK, "§0"}, {DARK_GREEN, "§2"}, {DARK_READ, "§4"}, {GOLD, "§6"}, - {GRAY, "§7"}, {BLUE, "§9"}, {GREEN, "§a"}, {AQUA, "§b"}, - {RED, "§c"}, {LIGHT_PURPLE, "§d"}, {YELLOW, "§e"}, {WHITE, "§f"}, - {BOLD, "§l"}, {ITALIC, "§o"}, {RESET, "§r"}}; + const std::map MessageBuilder::STYLE_MAP = { + {BLACK, "§0"}, {DARK_GREEN, "§2"}, {DARK_READ, "§4"}, {GOLD, "§6"}, + {GRAY, "§7"}, {BLUE, "§9"}, {GREEN, "§a"}, {AQUA, "§b"}, + {RED, "§c"}, {LIGHT_PURPLE, "§d"}, {YELLOW, "§e"}, {WHITE, "§f"}, + {BOLD, "§l"}, {ITALIC, "§o"}, {RESET, "§r"}}; -MessageBuilder &MessageBuilder::text(const std::string &s) { - messageBuffer.emplace_back(s); - return *this; -} + MessageBuilder &MessageBuilder::text(const std::string &s) { + messageBuffer.emplace_back(s); + return *this; + } -MessageBuilder &MessageBuilder::pos(const BlockPos &pos) { - return this->sText(pos.toString(), WHITE | BOLD); -} + MessageBuilder &MessageBuilder::pos(const BlockPos &pos) { + return this->sText(pos.toString(), WHITE | BOLD); + } -MessageBuilder &MessageBuilder::vec3(const Vec3 &vec3) { - return this->sText(vec3.toString(), WHITE | BOLD); -} + MessageBuilder &MessageBuilder::vec3(const Vec3 &vec3) { + return this->sText(vec3.toString(), WHITE | BOLD); + } -MessageBuilder &MessageBuilder::aabb(AABB aabb) { - auto str = "[" + aabb.p1.toString() + "," + aabb.p2.toString() + "]"; - return this->sText(str, WHITE); -} + MessageBuilder &MessageBuilder::aabb(AABB aabb) { + auto str = "[" + aabb.p1.toString() + "," + aabb.p2.toString() + "]"; + return this->sText(str, WHITE); + } -std::string MessageBuilder::get() { - std::string s; - for (const auto &i : messageBuffer) { - s.append(i); + std::string MessageBuilder::get() { + std::string s; + for (const auto &i : messageBuffer) { + s.append(i); + } + return s; } - return s; -} -MessageBuilder &MessageBuilder::sText(const std::string &s, uint8_t style) { - auto fontColor = style & 0x0fu; - auto fontStyle = style & 0xf0u; - auto iter = STYLE_MAP.find(fontColor); - if (iter != STYLE_MAP.end()) - messageBuffer.push_back(iter->second); - iter = STYLE_MAP.find(fontStyle); - if (iter != STYLE_MAP.end() && fontStyle != 0x0) - messageBuffer.push_back(iter->second); - messageBuffer.push_back(s); - messageBuffer.push_back(STYLE_MAP.at(RESET)); - return *this; -} + MessageBuilder &MessageBuilder::sText(const std::string &s, uint8_t style) { + auto fontColor = style & 0x0fu; + auto fontStyle = style & 0xf0u; + auto iter = STYLE_MAP.find(fontColor); + if (iter != STYLE_MAP.end()) messageBuffer.push_back(iter->second); + iter = STYLE_MAP.find(fontStyle); + if (iter != STYLE_MAP.end() && fontStyle != 0x0) + messageBuffer.push_back(iter->second); + messageBuffer.push_back(s); + messageBuffer.push_back(STYLE_MAP.at(RESET)); + return *this; + } -void MessageBuilder::send(Actor *actor) { - info(actor, get()); - // todo: rewrite - // info(get()); -} + void MessageBuilder::send(Actor *actor) { + info(actor, get()); + // todo: rewrite + // info(get()); + } -void MessageBuilder::broadcast() { broadcastMsg(this->get()); } -} // namespace trapdoor + void MessageBuilder::broadcast() { broadcastMsg(this->get()); } +} // namespace trapdoor diff --git a/api/tools/MsgBuilder.h b/api/tools/MsgBuilder.h index 47497f7..0f5d103 100644 --- a/api/tools/MsgBuilder.h +++ b/api/tools/MsgBuilder.h @@ -5,89 +5,91 @@ #ifndef TRAPDOOR_MSGBUILDER_H #define TRAPDOOR_MSGBUILDER_H -#include "Message.h" -#include "graphics/AABB.h" -#include "graphics/BlockPos.h" -#include "graphics/Vec3.h" #include #include #include #include +#include "Message.h" +#include "graphics/AABB.h" +#include "graphics/BlockPos.h" +#include "graphics/Vec3.h" + namespace trapdoor { -class Actor; - -class MessageBuilder { - public: - static const uint8_t DARK_READ; - static const uint8_t RED; - static const uint8_t GOLD; - static const uint8_t YELLOW; - static const uint8_t GREEN; - static const uint8_t DARK_GREEN; - static const uint8_t AQUA; - static const uint8_t BLUE; - static const uint8_t LIGHT_PURPLE; - static const uint8_t WHITE; - static const uint8_t GRAY; - static const uint8_t BLACK; - - static const uint8_t BOLD; - static const uint8_t ITALIC; - static const uint8_t RESET; - - MessageBuilder &text(const std::string &s); - - template - MessageBuilder &textF(const std::string &format, Args... args) { - this->text(trapdoor::format(format, args...)); - return *this; - } - - template - MessageBuilder &sTextF(uint8_t style, const std::string &format, - Args... args) { - this->sText(trapdoor::format(format, args...), style); - return *this; - } - - MessageBuilder &sText(const std::string &s, uint8_t style); - - MessageBuilder &pos(const BlockPos &pos); - - template MessageBuilder &num(T x) { - if (std::is_arithmetic()) { - if (std::is_floating_point()) { - char buffer[32]; - sprintf(buffer, "%.3f", (double)x); - std::string s(buffer); - sText(s, DARK_GREEN | BOLD); - } else { - sText(std::to_string(x), DARK_GREEN | BOLD); + class Actor; + + class MessageBuilder { + public: + static const uint8_t DARK_READ; + static const uint8_t RED; + static const uint8_t GOLD; + static const uint8_t YELLOW; + static const uint8_t GREEN; + static const uint8_t DARK_GREEN; + static const uint8_t AQUA; + static const uint8_t BLUE; + static const uint8_t LIGHT_PURPLE; + static const uint8_t WHITE; + static const uint8_t GRAY; + static const uint8_t BLACK; + + static const uint8_t BOLD; + static const uint8_t ITALIC; + static const uint8_t RESET; + + MessageBuilder &text(const std::string &s); + + template + MessageBuilder &textF(const std::string &format, Args... args) { + this->text(trapdoor::format(format, args...)); + return *this; + } + + template + MessageBuilder &sTextF(uint8_t style, const std::string &format, + Args... args) { + this->sText(trapdoor::format(format, args...), style); + return *this; + } + + MessageBuilder &sText(const std::string &s, uint8_t style); + + MessageBuilder &pos(const BlockPos &pos); + + template + MessageBuilder &num(T x) { + if (std::is_arithmetic()) { + if (std::is_floating_point()) { + char buffer[32]; + sprintf(buffer, "%.3f", (double)x); + std::string s(buffer); + sText(s, DARK_GREEN | BOLD); + } else { + sText(std::to_string(x), DARK_GREEN | BOLD); + } } + return *this; } - return *this; - } - MessageBuilder &vec3(const Vec3 &vec3); + MessageBuilder &vec3(const Vec3 &vec3); - MessageBuilder &aabb(AABB aabb); + MessageBuilder &aabb(AABB aabb); - inline void clear() { this->messageBuffer.clear(); } + inline void clear() { this->messageBuffer.clear(); } - std::string get(); + std::string get(); - void send(Actor *player); + void send(Actor *player); - void broadcast(); + void broadcast(); - void operator+=(const std::string &str) { this->text(str); } + void operator+=(const std::string &str) { this->text(str); } - private: - const static std::map STYLE_MAP; - std::vector messageBuffer; -}; + private: + const static std::map STYLE_MAP; + std::vector messageBuffer; + }; -typedef MessageBuilder MSG_COLOR; -} // namespace trapdoor -#endif // TRAPDOOR_MSGBUILDER_H + typedef MessageBuilder MSG_COLOR; +} // namespace trapdoor +#endif // TRAPDOOR_MSGBUILDER_H diff --git a/api/tools/noncopyable .h b/api/tools/noncopyable .h index 4349456..9b9809a 100644 --- a/api/tools/noncopyable .h +++ b/api/tools/noncopyable .h @@ -4,20 +4,19 @@ #ifndef MOD_NONCOPYABLE_H #define MOD_NONCOPYABLE_H -//from boost +// from boost namespace trapdoor { class noncopyable { - protected: + protected: noncopyable() {} ~noncopyable() {} - private: // emphasize the following members are private + private: // emphasize the following members are private noncopyable(const noncopyable &); const noncopyable &operator=(const noncopyable &); }; -} +} // namespace trapdoor typedef trapdoor::noncopyable noncopyable; -#endif //MOD_NONCOPYABLE_H - +#endif // MOD_NONCOPYABLE_H diff --git a/api/trapdoor.h b/api/trapdoor.h index c6aee12..d2e7dd8 100644 --- a/api/trapdoor.h +++ b/api/trapdoor.h @@ -6,21 +6,20 @@ #define MOD_TRAPDOOR_H #include "Actor.h" -#include "graphics/BlockPos.h" -#include "graphics/Vec3.h" -#include "graphics/AABB.h" -#include "graphics/Particle.h" -#include "tools/Message.h" -#include "tools/MsgBuilder.h" #include "CommandManager.h" +#include "block/Block.h" #include "block/BlockLegacy.h" #include "block/BlockSource.h" #include "block/VanillaBlockType.h" -#include "block/Block.h" +#include "graphics/AABB.h" +#include "graphics/BlockPos.h" +#include "graphics/Particle.h" +#include "graphics/Vec3.h" #include "tools/CastHelper.h" +#include "tools/Message.h" +#include "tools/MsgBuilder.h" +#define FUNC_DISABLED(p) \ + trapdoor::warning(p, "this function is blocked by developer"); -#define FUNC_DISABLED(p) trapdoor::warning(p,"this function is blocked by developer"); - -#endif //MOD_TRAPDOOR_H - +#endif // MOD_TRAPDOOR_H diff --git a/api/world/Biome.cpp b/api/world/Biome.cpp index b3b3545..e00bd0e 100644 --- a/api/world/Biome.cpp +++ b/api/world/Biome.cpp @@ -4,10 +4,9 @@ #include "Biome.h" - -#include "lib/mod.h" -#include "lib/SymHook.h" #include "Offset.h" +#include "lib/SymHook.h" +#include "lib/mod.h" namespace trapdoor { using namespace SymHook; @@ -18,11 +17,7 @@ namespace trapdoor { } int Biome::getBiomeType() { - return SYM_CALL( - int(*)(Biome * ), - MSSYM_B1QE12getBiomeTypeB1AA5BiomeB2AAA4QEBAB1QE20AW4VanillaBiomeTypesB2AAA2XZ, - this - ); + return SYM_CALL(int (*)(Biome *), Biome_getBiomeType_bb099b78, this); } -} \ No newline at end of file +} // namespace trapdoor \ No newline at end of file diff --git a/api/world/Biome.h b/api/world/Biome.h index 389a4c8..b963785 100644 --- a/api/world/Biome.h +++ b/api/world/Biome.h @@ -10,13 +10,12 @@ namespace trapdoor { class Biome { - - public: + public: int getBiomeType(); std::string getBiomeName(); }; -} +} // namespace trapdoor -#endif //TRAPDOOR_BIOME_H +#endif // TRAPDOOR_BIOME_H diff --git a/api/world/Dimension.cpp b/api/world/Dimension.cpp index 944cbc5..d074b83 100644 --- a/api/world/Dimension.cpp +++ b/api/world/Dimension.cpp @@ -3,32 +3,26 @@ // #include "Dimension.h" + +#include + #include "Offset.h" #include "tools/DirtyLogger.h" -#include + namespace trapdoor { -//打印维度上限,目前没屌用 -void Dimension::printBaseTypeLimit() { - // from Spawner::_popCapAllows - char *dim = reinterpret_cast(this); - auto *surface = (float *)(dim + 80); - auto *underground = (float *)(dim + 108); - for (int i = 0; i < 7; i++) { - printf("%.3f %.3f\n", surface[i], underground[i]); + //打印维度上限,目前没屌用 + void Dimension::printBaseTypeLimit() { + // from Spawner::_popCapAllows + char *dim = reinterpret_cast(this); + auto *surface = (float *)(dim + 80); + auto *underground = (float *)(dim + 108); + for (int i = 0; i < 7; i++) { + printf("%.3f %.3f\n", surface[i], underground[i]); + } } -} - -CircuitSceneGraph *Dimension::getGraph() { - //这种代码真的写的人瘆得慌 - //! from Dimension::tickRedstone(Dimension *this) - uint64_t *circuitSystem = - reinterpret_cast(this) + off::DIMENSION_GET_CIRCUIT_SYSTEM; - return reinterpret_cast(*circuitSystem + - off::CIRCUIT_GET_GRAPH); -} -bool Dimension::isRedstoneTick() { - //为1是红石刻2是非红石刻 - return *((uint32_t *)this + off::DIMENSION_IS_RS_TICK) == 1; -} -} // namespace trapdoor + bool Dimension::isRedstoneTick() { + //为1是红石刻2是非红石刻 + return *((uint32_t *)this + off::DIMENSION_IS_RS_TICK) == 1; + } +} // namespace trapdoor diff --git a/api/world/Dimension.h b/api/world/Dimension.h index 2d19213..bae6270 100644 --- a/api/world/Dimension.h +++ b/api/world/Dimension.h @@ -5,25 +5,17 @@ #ifndef TRAPDOOR_DIMENSION_H #define TRAPDOOR_DIMENSION_H -#include "block/CircuitComponent.h" - namespace trapdoor { - enum DimensionType { - OverWorld = 0, - Nether = 1, - TheEnd = 2 - }; + enum DimensionType { OverWorld = 0, Nether = 1, TheEnd = 2 }; class Dimension { - public: + public: void printBaseTypeLimit(); - CircuitSceneGraph *getGraph(); - bool isRedstoneTick(); }; -} +} // namespace trapdoor -#endif //TRAPDOOR_DIMENSION_H +#endif // TRAPDOOR_DIMENSION_H diff --git a/api/world/Level.cpp b/api/world/Level.cpp index 9a1eebb..83d9408 100644 --- a/api/world/Level.cpp +++ b/api/world/Level.cpp @@ -3,6 +3,7 @@ // #include "Level.h" + #include "Block.h" #include "Dimension.h" #include "Offset.h" @@ -13,65 +14,56 @@ #include "tools/DirtyLogger.h" namespace trapdoor { -using namespace SymHook; - -void Level::forEachPlayer(const std::function &todo) { - //!硬编码 - auto begin = - (uint64_t *)*((uint64_t *)this + off::LEVEL_FOREACH_PLAYER.first); - auto end = - (uint64_t *)*((uint64_t *)this + off::LEVEL_FOREACH_PLAYER.second); - while (begin != end) { - auto *player = (Actor *)(*begin); - if (player) - todo(player); - ++begin; - } -} + using namespace SymHook; -Actor *Level::getNearestPlayer(BlockPos &pos) { - Actor *nearest = nullptr; - float minDistance = 512; - this->forEachPlayer([&pos, &minDistance, &nearest](Actor *player) { - BlockPos p(player->getPos()->x, player->getPos()->y, - player->getPos()->z); - auto d = p.distanceTo(pos); - if (d < minDistance) { - minDistance = d; - nearest = player; + void Level::forEachPlayer(const std::function &todo) { + //!硬编码 + auto begin = + (uint64_t *)*((uint64_t *)this + off::LEVEL_FOREACH_PLAYER.first); + auto end = + (uint64_t *)*((uint64_t *)this + off::LEVEL_FOREACH_PLAYER.second); + while (begin != end) { + auto *player = (Actor *)(*begin); + if (player) todo(player); + ++begin; } - }); - return nearest; -} - -Dimension *Level::getDimFromID(int id) { - return SYM_CALL( - Dimension * (*)(Level *, int), - MSSYM_B1QE12getDimensionB1AA5LevelB2AAE17UEBAPEAVDimensionB2AAA1VB2QDE11AutomaticIDB1AE10VDimensionB2AAA1HB3AAAA1Z, - this, id); -} + } -Actor *Level::getNearestDimensionPlayer(const BlockPos &pos, int dimID) { - Actor *nearest = nullptr; - float minDistance = 512; - this->forEachPlayer([&nearest, &pos, &dimID, &minDistance](Actor *player) { - if (player->getDimensionID() == dimID) { - BlockPos p = player->getPos()->toBlockPos(); + Actor *Level::getNearestPlayer(BlockPos &pos) { + Actor *nearest = nullptr; + float minDistance = 512; + this->forEachPlayer([&pos, &minDistance, &nearest](Actor *player) { + BlockPos p(player->getPos()->x, player->getPos()->y, + player->getPos()->z); auto d = p.distanceTo(pos); if (d < minDistance) { minDistance = d; nearest = player; } - } - }); - return nearest; -} + }); + return nearest; + } -uint64_t Level::getGameTick() { - // return *SYM_CALL(uint64_t*(*)(Level * ), - // MSSYM_B1QE14getCurrentTickB1AA5LevelB2AAE12QEBAAEBUTickB2AAA2XZ, - // this); - return 0; -} + Dimension *Level::getDimFromID(int id) { + return SYM_CALL(Dimension * (*)(Level *, int), + Level_getDimension_6fab9459, this, id); + } + + Actor *Level::getNearestDimensionPlayer(const BlockPos &pos, int dimID) { + Actor *nearest = nullptr; + float minDistance = 512; + this->forEachPlayer( + [&nearest, &pos, &dimID, &minDistance](Actor *player) { + if (player->getDimensionID() == dimID) { + BlockPos p = player->getPos()->toBlockPos(); + auto d = p.distanceTo(pos); + if (d < minDistance) { + minDistance = d; + nearest = player; + } + } + }); + return nearest; + } -} // namespace trapdoor +} // namespace trapdoor diff --git a/api/world/Level.h b/api/world/Level.h index 41e1e02..2ff5e87 100644 --- a/api/world/Level.h +++ b/api/world/Level.h @@ -5,10 +5,11 @@ #ifndef TRAPDOOR_LEVEL_H #define TRAPDOOR_LEVEL_H -#include -#include "block/Block.h" #include #include +#include + +#include "block/Block.h" namespace trapdoor { class BlockPos; @@ -19,44 +20,31 @@ namespace trapdoor { class ActorUniqueID; - class Tick { - public: + public: uint64_t tick; uint64_t operator%(size_t num) const { return tick % num; } - bool operator<(const Tick &rhs) const { - return tick < rhs.tick; - } + bool operator<(const Tick &rhs) const { return tick < rhs.tick; } inline uint64_t getTimeStamp() const { return this->tick; } - bool operator==(const Tick &rhs) const { - return tick == rhs.tick; - } - + bool operator==(const Tick &rhs) const { return tick == rhs.tick; } }; class Level { - - public: + public: Level() = delete; void forEachPlayer(const std::function &todo); - Actor *getNearestPlayer(BlockPos &pos); - Actor *getNearestDimensionPlayer(const BlockPos &pos, int dimID); - Dimension *getDimFromID(int id); - - - uint64_t getGameTick(); }; -} +} // namespace trapdoor -#endif //TRAPDOOR_LEVEL_H +#endif // TRAPDOOR_LEVEL_H diff --git a/api/world/LevelChunk.cpp b/api/world/LevelChunk.cpp deleted file mode 100644 index e560ee3..0000000 --- a/api/world/LevelChunk.cpp +++ /dev/null @@ -1,5 +0,0 @@ -// -// Created by xhy on 2020/11/9. -// - -#include "LevelChunk.h" diff --git a/api/world/LevelChunk.h b/api/world/LevelChunk.h deleted file mode 100644 index 0c54f1d..0000000 --- a/api/world/LevelChunk.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Created by xhy on 2020/11/9. -// - -#ifndef TRAPDOOR_LEVELCHUNK_H -#define TRAPDOOR_LEVELCHUNK_H - -namespace trapdoor { - class LevelChunk { - - }; -} - - -#endif //TRAPDOOR_LEVELCHUNK_H diff --git a/changelog.md b/changelog.md index 5b848f9..ef29b25 100644 --- a/changelog.md +++ b/changelog.md @@ -1,36 +1,50 @@ +# 1.17.11.01-0.9.73 + +2021-08-15 + +- 修复仙人掌能转动蛋糕的问题 +- 支持1.17.11.01() +- 添加clang-format用来约束代码格式 +- 采用了新的符号生成器以提高开发效率 + # 1.17.10.04-0.9.71 + 2021-07-30 -- 修复开启`village v`后打掉POI的闪退以及杀死村民后的概率性闪退问题 +- 修复开启`village v`后打掉POI的闪退以及杀死村民后的概率性闪退问题 # 1.17.10.04-0.9.7 + 2021-07-28 + - 修复假人CPU占用过高的问题 - 给配置文件添加了假人ws链接选项使用`/fakeplayer c`即可连接 - 区块填充功能添加翻译 # 1.17.1.01-0.9.6.1 + 2021-07-26 + - 修复MSPT的概率性闪退 - 修复NCUD无法使用的问题 - 修复实体系统tick时间无法测试的问题 - # 1.17.1.01-0.9.6 + 2021-07-14 - 修复`village n`和`village v`,新增村庄居民TS值的显示 - 现在把所有的trapdoor相关文件放到了`bds_root\plugins\trapdoor\`下(#26),使用方法将release解压到bds根目录即可 - # 1.17.1.01-0.9.51 + 2021-07-14 - 修复`village n`和`village v`的闪退问题,但是还是不能用 - 现在把所有的trapdoor相关文件放到了`bds_root\plugins\trapdoor\`下(#26),使用方法将release解压到bds根目录即可 - # 1.17.1.01-0.9.50 + 2021-06-20 - 支持1.17.1.01 diff --git a/mod/TrapdoorMod.cpp b/mod/TrapdoorMod.cpp index 601d28c..b983caf 100644 --- a/mod/TrapdoorMod.cpp +++ b/mod/TrapdoorMod.cpp @@ -3,6 +3,7 @@ // #include "TrapdoorMod.h" + #include "VanillaBlockType.h" #include "commands/Command.h" #include "eval/Eval.h" @@ -13,268 +14,276 @@ #include "test/TrapdoorTest.h" #include "tick/GameTick.h" #include "trapdoor.h" -namespace mod { -void TrapdoorMod::heavyTick() { - rmt_ScopedCPUSample(MOD_TICK, 0); - this->villageHelper.tick(); - this->hsaManager.tick(); - this->spawnHelper.tick(); - this->playerFunctions.tick(); - this->slimeChunkHelper.tick(); - this->fakePlayerClient->tick(); -} +namespace mod { -void TrapdoorMod::lightTick() { - this->tick(); - this->hopperChannelManager.tick(); - // this->spawnAnalyzer.tick(); -} + void TrapdoorMod::heavyTick() { + rmt_ScopedCPUSample(MOD_TICK, 0); + this->villageHelper.tick(); + this->hsaManager.tick(); + this->spawnHelper.tick(); + this->playerFunctions.tick(); + this->slimeChunkHelper.tick(); + if (this->fakePlayerClient) this->fakePlayerClient->tick(); + } -//这个函数会在初始化Level对象后执行 -void TrapdoorMod::initialize() { - L_DEBUG("init -1"); - BDSMod::initialize(); - this->commandManager.setCommandConfig( - this->configManager.getCommandsConfig()); - mod::initBackup(); - this->villageHelper.setConfig(this->configManager.getVillageConfig()); - get_cpu_usage(); - this->initFunctionEnable(); - initBlockMap(); - //初始化假人客户端的线程池 - this->fakePlayerClient = new FakePlayerClient(this->getThreadPool()); - this->fakePlayerClient->registerFakePlayerCommand(commandManager); - L_INFO("[INFO] Trapdoor init finish,Server Start"); -} + void TrapdoorMod::lightTick() { + this->tick(); + this->hopperChannelManager.tick(); + // this->spawnAnalyzer.tick(); + } -void TrapdoorMod::registerCommands() { - using namespace trapdoor; - BDSMod::registerCommands(); - tick::registerTickCommand(this->commandManager); - tick::registerProfileCommand(this->commandManager); - mod::test::registerTestCommand(this->commandManager); - mod::registerBackupCommand(this->commandManager); - this->hsaManager.registerCommand(this->commandManager); - this->simpleBuilder.registerDrawCommand(this->commandManager); - // this->simpleLitematica.registerCommand(this->commandManager); - this->villageHelper.registerCommand(this->commandManager); - this->hopperChannelManager.registerCommand(this->commandManager); - registerGamemodeSwitchCommand(this->commandManager); - this->slimeChunkHelper.registerCommand(this->commandManager); - //功能开关命令 - commandManager.registerCmd("func", "command.func.desc") - ->then(ARG("hopper", "command.func.hopper.desc", BOOL, - { - this->hopperChannelManager.setAble(holder->getBool()); - info(player, LANG("command.func.hopper.set"), - holder->getBool()); - })) - ->then(ARG("spawn", "command.func.spawn.desc", BOOL, - { - this->spawnHelper.setAble(holder->getBool()); - info(player, LANG("command.func.spawn.set"), - holder->getBool()); - })) - ->then(ARG("rotate", "command.func.rotate.desc", BOOL, - { - this->rotationHelper.setAble(holder->getBool()); - info(player, LANG("command.func.rotate.set"), - holder->getBool()); - })) - ->then(ARG("draw", "command.func.draw.desc", BOOL, - { - this->simpleBuilder.setAble(holder->getBool()); - info(player, LANG("command.func.draw.set"), - holder->getBool()); - })) + //这个函数会在初始化Level对象后执行 + void TrapdoorMod::initialize() { + BDSMod::initialize(); + this->commandManager.setCommandConfig( + this->configManager.getCommandsConfig()); + mod::initBackup(); + this->villageHelper.setConfig(this->configManager.getVillageConfig()); + get_cpu_usage(); + this->initFunctionEnable(); + initBlockMap(); + //初始化假人客户端的线程池 + this->fakePlayerClient = new FakePlayerClient(this->getThreadPool()); + this->fakePlayerClient->registerFakePlayerCommand(commandManager); + L_INFO("[INFO] Trapdoor init finish,Server Start"); + } - ->then(ARG("expl", "command.func.expl.desc", BOOL, - { - this->singleFunctions.preventExplosion = - holder->getBool(); - info(player, LANG("command.func.expl.set"), - holder->getBool()); - })) + void TrapdoorMod::registerCommands() { + using namespace trapdoor; + BDSMod::registerCommands(); + tick::registerTickCommand(this->commandManager); + tick::registerProfileCommand(this->commandManager); + mod::test::registerTestCommand(this->commandManager); + mod::registerBackupCommand(this->commandManager); + this->hsaManager.registerCommand(this->commandManager); + this->simpleBuilder.registerDrawCommand(this->commandManager); + // this->simpleLitematica.registerCommand(this->commandManager); + this->villageHelper.registerCommand(this->commandManager); + this->hopperChannelManager.registerCommand(this->commandManager); + registerGamemodeSwitchCommand(this->commandManager); + this->slimeChunkHelper.registerCommand(this->commandManager); + //功能开关命令 + commandManager.registerCmd("func", "command.func.desc") + ->then(ARG("hopper", "command.func.hopper.desc", BOOL, + { + this->hopperChannelManager.setAble( + holder->getBool()); + info(player, LANG("command.func.hopper.set"), + holder->getBool()); + })) + ->then(ARG("spawn", "command.func.spawn.desc", BOOL, + { + this->spawnHelper.setAble(holder->getBool()); + info(player, LANG("command.func.spawn.set"), + holder->getBool()); + })) + ->then(ARG("rotate", "command.func.rotate.desc", BOOL, + { + this->rotationHelper.setAble(holder->getBool()); + info(player, LANG("command.func.rotate.set"), + holder->getBool()); + })) + ->then(ARG("draw", "command.func.draw.desc", BOOL, + { + this->simpleBuilder.setAble(holder->getBool()); + info(player, LANG("command.func.draw.set"), + holder->getBool()); + })) - ->then(ARG("ncud", "command.func.ncud.desc", BOOL, { - // FUNC_DISABLED(player) - this->singleFunctions.preventNCUpdate = holder->getBool(); - info(player, LANG("command.func.ncud.set"), holder->getBool()); - })); + ->then(ARG("expl", "command.func.expl.desc", BOOL, + { + this->singleFunctions.preventExplosion = + holder->getBool(); + info(player, LANG("command.func.expl.set"), + holder->getBool()); + })) - commandManager.registerCmd("self", "command.self.desc") - ->then(ARG( - "chunk", "command.self.chunk.desc", BOOL, - { - if (!configManager.getSelfEnableConfig().enableChunkShow) { - error(player, LANG("command.error.config")); - return; - } - this->playerFunctions.setShowChunkAble(player->getNameTag(), - holder->getBool()); - info(player, LANG("command.self.chunk.set"), holder->getBool()); - })) - ->then(ARG( - "me", "command.self.me.desc", BOOL, - { - if (!configManager.getSelfEnableConfig() - .enableDistanceMeasure) { - error(player, LANG("command.error.config")); - return; - } - this->playerFunctions.getMeasureData(player->getNameTag()) - .enableMeasure = holder->getBool(); - info(player, LANG("command.self.me.set"), holder->getBool()); - })) - ->then(ARG( - "rs", "command.self.rs.desc", BOOL, - { - FUNC_DISABLED(player) - return; - if (!configManager.getSelfEnableConfig().enableRedstoneStick) { - error(player, LANG("command.error.config")); - return; - } - this->playerFunctions.setRedstoneHelperAble( - player->getNameTag(), holder->getBool()); - info(player, LANG("command.self.rs.set"), holder->getBool()); - })) - ->EXE({ PlayerFunction::printDebugInfo(player); }); + ->then(ARG("ncud", "command.func.ncud.desc", BOOL, { + // FUNC_DISABLED(player) + this->singleFunctions.preventNCUpdate = holder->getBool(); + info(player, LANG("command.func.ncud.set"), holder->getBool()); + })); - commandManager.registerCmd("here", "command.here.desc")->EXE({ - PlayerFunction::broadcastSimpleInfo(player); - }); - commandManager.registerCmd("l", "command.l.desc")->EXE({ - PlayerFunction::listAllPlayers(player); - }); - commandManager.registerCmd("os", "command.os.desc")->EXE({ - TrapdoorMod::printOSInfo(player); - }); - commandManager.registerCmd("cl", "command.cl.desc", Any, ArgType::STR) - ->EXE({ mod::eval(player, holder->getString()); }); - commandManager.registerCmd("td?", "command.td?.desc")->EXE({ - this->commandManager.printfHelpInfo(player); - }); -} + commandManager.registerCmd("self", "command.self.desc") + ->then(ARG( + "chunk", "command.self.chunk.desc", BOOL, + { + if (!configManager.getSelfEnableConfig().enableChunkShow) { + error(player, LANG("command.error.config")); + return; + } + this->playerFunctions.setShowChunkAble(player->getNameTag(), + holder->getBool()); + info(player, LANG("command.self.chunk.set"), + holder->getBool()); + })) + ->then(ARG("me", "command.self.me.desc", BOOL, + { + if (!configManager.getSelfEnableConfig() + .enableDistanceMeasure) { + error(player, LANG("command.error.config")); + return; + } + this->playerFunctions + .getMeasureData(player->getNameTag()) + .enableMeasure = holder->getBool(); + info(player, LANG("command.self.me.set"), + holder->getBool()); + })) + ->then(ARG("rs", "command.self.rs.desc", BOOL, + { + FUNC_DISABLED(player) + return; + if (!configManager.getSelfEnableConfig() + .enableRedstoneStick) { + error(player, LANG("command.error.config")); + return; + } + this->playerFunctions.setRedstoneHelperAble( + player->getNameTag(), holder->getBool()); + info(player, LANG("command.self.rs.set"), + holder->getBool()); + })) + ->EXE({ PlayerFunction::printDebugInfo(player); }); -void TrapdoorMod::printCopyRightInfo() { + commandManager.registerCmd("here", "command.here.desc")->EXE({ + PlayerFunction::broadcastSimpleInfo(player); + }); + commandManager.registerCmd("l", "command.l.desc")->EXE({ + PlayerFunction::listAllPlayers(player); + }); + commandManager.registerCmd("os", "command.os.desc")->EXE({ + TrapdoorMod::printOSInfo(player); + }); + commandManager.registerCmd("cl", "command.cl.desc", Any, ArgType::STR) + ->EXE({ mod::eval(player, holder->getString()); }); + commandManager.registerCmd("td?", "command.td?.desc")->EXE({ + this->commandManager.printfHelpInfo(player); + }); + } - const char *banner = "\n" - " _______ _ \n" - " |__ __| | | \n" - " | |_ __ __ _ _ __ __| | ___ ___ _ __ \n" - " | | '__/ _` | '_ \\ / _` |/ _ \\ / _ \\| '__| \n" - " | | | | (_| | |_) | (_| | (_) | (_) | | \n" - " |_|_| \\__,_| .__/ \\__,_|\\___/ \\___/|_| \n" - " | | \n" - " |_| "; - printf("%s\n " - "\ngithub:https://github.com/hhhxiao/TrapDoor\nLicense: GPL\n", - banner); - printf("trapdoor version: %s\n", getModVersion().c_str()); - printf("build time: %s " - "%s\n-----------------------------------------------\n", - __DATE__, __TIME__); - fflush(stdout); -} + void TrapdoorMod::printCopyRightInfo() { + const char *banner = + "\n" + " _______ _ \n" + " |__ __| | | \n" + " | |_ __ __ _ _ __ __| | ___ ___ _ __ \n" + " | | '__/ _` | '_ \\ / _` |/ _ \\ / _ \\| '__| \n" + " | | | | (_| | |_) | (_| | (_) | (_) | | \n" + " |_|_| \\__,_| .__/ \\__,_|\\___/ \\___/|_| \n" + " | | \n" + " |_| "; + printf( + "%s\n " + "\ngithub:https://github.com/hhhxiao/TrapDoor\nLicense: GPL\n", + banner); + printf("trapdoor version: %s\n", getModVersion().c_str()); + printf( + "build time: %s " + "%s\n-----------------------------------------------\n", + __DATE__, __TIME__); + fflush(stdout); + } -void TrapdoorMod::useOnHook(Actor *player, const std::string &itemName, - BlockPos &pos, unsigned int facing, const Vec3 &v) { - // L_INFO("%.2f %.2f %.2f %s", v.x, v.y, v.z, itemName.c_str()); - //取消注释这一行可以看到右击地面的是什么东西 - if (itemName == "Bone" && this->spawnHelper.isEnable()) { - spawnHelper.updateVerticalSpawnPositions(pos, player); - } else if (itemName == "Gunpowder") { - this->spawnHelper.printSpawnProbability(player, pos, 0); - } else if (itemName == "Leather") { - this->spawnHelper.printSpawnProbability(player, pos, 15); - } else if (itemName == "Cactus") { - this->hopperChannelManager.quickPrintData(player, pos); - this->rotationHelper.rotate(pos, player->getBlockSource()); - } else if (itemName == "Wooden Sword") { - this->playerFunctions.getMeasureData(player->getNameTag()) - .setPosition1(pos, player); - // this->simpleLitematica.getSelectRegion().setPos1(pos, player); - } else if (itemName == "Stone Sword") { - this->playerFunctions.getMeasureData(player->getNameTag()) - .setPosition2(pos, player); - // this->simpleLitematica.getSelectRegion().setPos2(pos, player); - } else if (itemName == "Stick") { - this->playerFunctions.printRedstoneInfo(player, pos); + void TrapdoorMod::useOnHook(Actor *player, const std::string &itemName, + BlockPos &pos, unsigned int facing, + const Vec3 &v) { + // L_INFO("%.2f %.2f %.2f %s", v.x, v.y, v.z, itemName.c_str()); + //取消注释这一行可以看到右击地面的是什么东西 + if (itemName == "Bone" && this->spawnHelper.isEnable()) { + spawnHelper.updateVerticalSpawnPositions(pos, player); + } else if (itemName == "Gunpowder") { + this->spawnHelper.printSpawnProbability(player, pos, 0); + } else if (itemName == "Leather") { + this->spawnHelper.printSpawnProbability(player, pos, 15); + } else if (itemName == "Cactus") { + this->hopperChannelManager.quickPrintData(player, pos); + this->rotationHelper.rotate(pos, player->getBlockSource()); + } else if (itemName == "Wooden Sword") { + this->playerFunctions.getMeasureData(player->getNameTag()) + .setPosition1(pos, player); + // this->simpleLitematica.getSelectRegion().setPos1(pos, player); + } else if (itemName == "Stone Sword") { + this->playerFunctions.getMeasureData(player->getNameTag()) + .setPosition2(pos, player); + // this->simpleLitematica.getSelectRegion().setPos2(pos, player); + } else if (itemName == "Stick") { + this->playerFunctions.printRedstoneInfo(player, pos); + } } -} -CommandPermissionLevel -TrapdoorMod::resetVanillaCommandLevel(const std::string &name, - CommandPermissionLevel oldLevel) { - auto lowLevelConfig = this->configManager.getLowLevelCommands(); - if (lowLevelConfig.find(name) != lowLevelConfig.end()) { - L_DEBUG("set command %s level to gameMaster", name.c_str()); - return CommandPermissionLevel::GameMasters; - } else { - return oldLevel; + CommandPermissionLevel TrapdoorMod::resetVanillaCommandLevel( + const std::string &name, CommandPermissionLevel oldLevel) { + auto lowLevelConfig = this->configManager.getLowLevelCommands(); + if (lowLevelConfig.find(name) != lowLevelConfig.end()) { + L_DEBUG("set command %s level to gameMaster", name.c_str()); + return CommandPermissionLevel::GameMasters; + } else { + return oldLevel; + } } -} -void TrapdoorMod::printOSInfo(trapdoor::Actor *player) { - int CPUUsage = get_cpu_usage(); - uint64_t memory, virtualMemory, ioRead, ioWrite; - get_memory_usage(&memory, &virtualMemory); - get_io_bytes(&ioRead, &ioWrite); - std::string stringBuilder; - stringBuilder += - trapdoor::format("CPU " C_INT "%%%%" - "Mem: " C_INT " MB VMem; " C_INT " MB\n" - "Read/Write" C_INT "KB / " C_INT " KB", - CPUUsage, memory >> 20u, virtualMemory >> 20u, - ioRead >> 10u, ioWrite >> 10u); - trapdoor::info(player, stringBuilder); -} + void TrapdoorMod::printOSInfo(trapdoor::Actor *player) { + int CPUUsage = get_cpu_usage(); + uint64_t memory, virtualMemory, ioRead, ioWrite; + get_memory_usage(&memory, &virtualMemory); + get_io_bytes(&ioRead, &ioWrite); + std::string stringBuilder; + stringBuilder += + trapdoor::format("CPU " C_INT + "%%%%" + "Mem: " C_INT " MB VMem; " C_INT + " MB\n" + "Read/Write" C_INT "KB / " C_INT " KB", + CPUUsage, memory >> 20u, virtualMemory >> 20u, + ioRead >> 10u, ioWrite >> 10u); + trapdoor::info(player, stringBuilder); + } -/* - * 实体攻击接口 -@ return 返回false会阻止掉血,返回true会正常掉血 - @ entity1 进行攻击的实体 - @entity2 被攻击的实体 -*/ -bool TrapdoorMod::attackEntityHook(Actor *entity1, Actor *entity2) { - if (entity1->getActorId() != "player") - return true; //非玩家攻击直接忽略 - //开了居民村庄中心显示 - if (villageHelper.getShowDwellerStatus() && - (entity2->getActorId() == "iron_golem" || - entity2->getActorId() == "villager_v2")) { - villageHelper.printDwellerInfo(entity1, entity2); - return false; - } else { - return true; + /* + * 实体攻击接口 + @ return 返回false会阻止掉血,返回true会正常掉血 + @ entity1 进行攻击的实体 + @entity2 被攻击的实体 + */ + bool TrapdoorMod::attackEntityHook(Actor *entity1, Actor *entity2) { + if (entity1->getActorId() != "player") + return true; //非玩家攻击直接忽略 + //开了居民村庄中心显示 + if (villageHelper.getShowDwellerStatus() && + (entity2->getActorId() == "iron_golem" || + entity2->getActorId() == "villager_v2")) { + villageHelper.printDwellerInfo(entity1, entity2); + return false; + } else { + return true; + } } -} -void TrapdoorMod::initFunctionEnable() { - auto functionCfg = this->configManager.getFunctionConfig(); - this->spawnHelper.setAble(functionCfg.spawnHelper); - this->rotationHelper.setAble(functionCfg.cactusRotation); - this->simpleBuilder.setAble(functionCfg.simpleDraw); - this->hopperChannelManager.setAble(functionCfg.hopperCounter); -} + void TrapdoorMod::initFunctionEnable() { + auto functionCfg = this->configManager.getFunctionConfig(); + this->spawnHelper.setAble(functionCfg.spawnHelper); + this->rotationHelper.setAble(functionCfg.cactusRotation); + this->simpleBuilder.setAble(functionCfg.simpleDraw); + this->hopperChannelManager.setAble(functionCfg.hopperCounter); + } -std::string TrapdoorMod::getModVersion() { + std::string TrapdoorMod::getModVersion() { #ifdef TD_VERSION - const char *modVersion = TD_VERSION; + const char *modVersion = TD_VERSION; #else - const char *modVersion = "unknown_mod_version"; + const char *modVersion = "unknown_mod_version"; #endif #ifdef MC_VERSION - const char *gameVersion = MC_VERSION; + const char *gameVersion = MC_VERSION; #else - const char *gameVersion = "unknown_mcbe_version"; + const char *gameVersion = "unknown_mcbe_version"; #endif - std::string version = std::string(modVersion) + "-" + gameVersion; + std::string version = std::string(modVersion) + "-" + gameVersion; #ifdef BETA - version += "-test"; + version += "-test"; #endif - return version; -} -} // namespace mod \ No newline at end of file + return version; + } +} // namespace mod \ No newline at end of file diff --git a/mod/TrapdoorMod.h b/mod/TrapdoorMod.h index e2f391b..65b3e32 100644 --- a/mod/TrapdoorMod.h +++ b/mod/TrapdoorMod.h @@ -13,7 +13,6 @@ #include "function/SimpleBuilder.h" #include "player/PlayerFunction.h" #include "spawn/HsaManager.h" -#include "spawn/SpawnAnalyzer.h" #include "spawn/SpawnHelper.h" #include "village/Village.h" //#include "dirtyLitematica/SimpleLitematica.h" @@ -22,72 +21,74 @@ namespace mod { -struct SingleFunction { - bool preventExplosion = false; - bool preventNCUpdate = false; - bool enableBetterMspt = false; -}; + struct SingleFunction { + bool preventExplosion = false; + bool preventNCUpdate = false; + bool enableBetterMspt = false; + }; -class TrapdoorMod : public trapdoor::BDSMod { - private: - SingleFunction singleFunctions; - HopperChannelManager hopperChannelManager; - VillageHelper villageHelper; - HsaManager hsaManager; - ConfigManager configManager; - SpawnHelper spawnHelper; - BlockRotationHelper rotationHelper; - PlayerFunction playerFunctions; - SimpleBuilder simpleBuilder; - SlimeChunkHelper slimeChunkHelper; - FakePlayerClient *fakePlayerClient = nullptr; + class TrapdoorMod : public trapdoor::BDSMod { + private: + SingleFunction singleFunctions; + HopperChannelManager hopperChannelManager; + VillageHelper villageHelper; + HsaManager hsaManager; + ConfigManager configManager; + SpawnHelper spawnHelper; + BlockRotationHelper rotationHelper; + PlayerFunction playerFunctions; + SimpleBuilder simpleBuilder; + SlimeChunkHelper slimeChunkHelper; + FakePlayerClient *fakePlayerClient = nullptr; - void initFunctionEnable(); + void initFunctionEnable(); - public: - static void printCopyRightInfo(); + public: + static void printCopyRightInfo(); - static std::string getModVersion(); + static std::string getModVersion(); - static void printOSInfo(trapdoor::Actor *player); + static void printOSInfo(trapdoor::Actor *player); - void initialize() override; + void initialize() override; - void registerCommands() override; + void registerCommands() override; - void useOnHook(Actor *player, const std::string &itemName, BlockPos &pos, - unsigned int facing, const Vec3 &) override; + void useOnHook(Actor *player, const std::string &itemName, + BlockPos &pos, unsigned int facing, + const Vec3 &) override; - CommandPermissionLevel - resetVanillaCommandLevel(const std::string &name, - CommandPermissionLevel oldLevel) override; + CommandPermissionLevel resetVanillaCommandLevel( + const std::string &name, CommandPermissionLevel oldLevel) override; - void heavyTick(); + void heavyTick(); - void lightTick(); + void lightTick(); - inline bool readConfigFile(const std::string &configFileName) { - return this->configManager.initialize(configFileName); - } + inline bool readConfigFile(const std::string &configFileName) { + return this->configManager.initialize(configFileName); + } - bool attackEntityHook(Actor *entity1, Actor *entity2) override; + bool attackEntityHook(Actor *entity1, Actor *entity2) override; - // get functions - inline HopperChannelManager &getHopperChannelManager() { - return this->hopperChannelManager; - } + // get functions + inline HopperChannelManager &getHopperChannelManager() { + return this->hopperChannelManager; + } - inline VillageHelper &getVillageHelper() { return this->villageHelper; } + inline VillageHelper &getVillageHelper() { return this->villageHelper; } - inline HsaManager &getHsaManager() { return this->hsaManager; } + inline HsaManager &getHsaManager() { return this->hsaManager; } - inline std::string getLevelName() { - return this->configManager.getServerConfig().levelName; - } - inline ConfigManager &getConfigManager() { return this->configManager; } + inline std::string getLevelName() { + return this->configManager.getServerConfig().levelName; + } + inline ConfigManager &getConfigManager() { return this->configManager; } - inline SingleFunction &getSingFunction() { return this->singleFunctions; } -}; -} // namespace mod + inline SingleFunction &getSingFunction() { + return this->singleFunctions; + } + }; +} // namespace mod -#endif // MOD_TRAPDOORMOD_H \ No newline at end of file +#endif // MOD_TRAPDOORMOD_H \ No newline at end of file diff --git a/mod/config/ConfigManager.cpp b/mod/config/ConfigManager.cpp index 31a2609..1d62149 100644 --- a/mod/config/ConfigManager.cpp +++ b/mod/config/ConfigManager.cpp @@ -3,238 +3,236 @@ // #include "ConfigManager.h" + +#include + #include "commands/CommandManager.h" #include "graphics/Graphics.h" #include "graphics/Particle.h" #include "tools/DirtyLogger.h" -#include - namespace mod { -namespace { - -trapdoor::GRAPHIC_COLOR str2color(std::string &color) { - if (color == "red") { - return GRAPH_COLOR::RED; - } else if (color == "green") { - return GRAPH_COLOR::GREEN; - } else if (color == "yellow") { - return GRAPH_COLOR::YELLOW; - } else if (color == "blue") { - return GRAPH_COLOR::BLUE; - } - return GRAPH_COLOR::WHITE; -} -} // namespace - -bool ConfigManager::initialize(const std::string &configFileName) { - L_DEBUG("begin read config file %s", configFileName.c_str()); - if (!this->readConfigFile(configFileName)) - return false; - if (!this->readEULA()) - return false; - if (!this->readCommandConfig()) - return false; - if (!this->readLowLevelVanillaCommands()) - return false; - if (!this->readServerConfig()) - return false; - if (!this->readVillageConfig()) - return false; - if (!this->readFunctionConfig()) - return false; - if (!this->readSelfConfig()) - return false; - this->printAllConfig(); - return true; -} - -bool ConfigManager::readCommandConfig() { - L_DEBUG("begin read command permission info"); - auto commandConfigs = this->configJson["commands"]; - trapdoor::CommandConfig tempConfig; - try { - for (const auto &i : commandConfigs.items()) { - const auto &value = i.value(); - tempConfig.enable = value["enable"].get(); - tempConfig.permissionLevel = - static_cast( - value["permissionLevel"].get()); - //关闭了生存模式和作弊检查 - // tempConfig.survival = value["survival"].get(); - // tempConfig.needCheat = value["needCheat"].get(); - this->commandsConfig.insert({i.key(), tempConfig}); + namespace { + + trapdoor::GRAPHIC_COLOR str2color(std::string &color) { + if (color == "red") { + return GRAPH_COLOR::RED; + } else if (color == "green") { + return GRAPH_COLOR::GREEN; + } else if (color == "yellow") { + return GRAPH_COLOR::YELLOW; + } else if (color == "blue") { + return GRAPH_COLOR::BLUE; + } + return GRAPH_COLOR::WHITE; } + } // namespace + + bool ConfigManager::initialize(const std::string &configFileName) { + L_DEBUG("begin read config file %s", configFileName.c_str()); + if (!this->readConfigFile(configFileName)) return false; + if (!this->readEULA()) return false; + if (!this->readCommandConfig()) return false; + if (!this->readLowLevelVanillaCommands()) return false; + if (!this->readServerConfig()) return false; + if (!this->readVillageConfig()) return false; + if (!this->readFunctionConfig()) return false; + if (!this->readSelfConfig()) return false; + this->printAllConfig(); + return true; + } - for (const auto &item : this->commandsConfig) { - L_DEBUG(" - %-10s enable:%d level:%d", item.first.c_str(), - item.second.enable, item.second.permissionLevel); + bool ConfigManager::readCommandConfig() { + L_DEBUG("begin read command permission info"); + auto commandConfigs = this->configJson["commands"]; + trapdoor::CommandConfig tempConfig; + try { + for (const auto &i : commandConfigs.items()) { + const auto &value = i.value(); + tempConfig.enable = value["enable"].get(); + tempConfig.permissionLevel = + static_cast( + value["permissionLevel"].get()); + //关闭了生存模式和作弊检查 + // tempConfig.survival = value["survival"].get(); + // tempConfig.needCheat = value["needCheat"].get(); + this->commandsConfig.insert({i.key(), tempConfig}); + } + + for (const auto &item : this->commandsConfig) { + L_DEBUG(" - %-10s enable:%d level:%d", item.first.c_str(), + item.second.enable, item.second.permissionLevel); + } + L_DEBUG("read command permission info successfully\n"); + } catch (const std::exception &e) { + L_ERROR("error read command config : %s", e.what()); + return false; } - L_DEBUG("read command permission info successfully\n"); - } catch (const std::exception &e) { - L_ERROR("error read command config : %s", e.what()); - return false; - } - return true; -} - -bool ConfigManager::readConfigFile(const std::string &configFileName) { - try { - std::ifstream i(configFileName); - i >> this->configJson; - L_DEBUG("read config file %s successfully\n", configFileName.c_str()); return true; - } catch (std::exception &e) { - L_ERROR("can not read config file %s with error %s", - configFileName.c_str(), e.what()); - return false; - } -} - -bool ConfigManager::readFunctionConfig() { - L_DEBUG("begin read function config"); - try { - auto funcConfig = this->configJson["functionsEnable"]; - this->functionConfig.hopperCounter = - funcConfig["hopperCounter"].get(); - // this->functionConfig.explosion = - // funcConfig["explosion"].get(); - this->functionConfig.spawnHelper = - funcConfig["spawnHelper"].get(); - this->functionConfig.cactusRotation = - funcConfig["cactusRotate"].get(); - this->functionConfig.simpleDraw = funcConfig["simpleDraw"].get(); - this->functionConfig.playerStat = funcConfig["playerStat"].get(); - - L_DEBUG("read function config successfully\n"); - } catch (std::exception &e) { - L_ERROR("can not read function config: %s", e.what()); - return false; } - return true; -} - -bool ConfigManager::readParticleConfig() { - try { - auto partConfig = this->configJson["particle"]; - auto particleShowFrequency = partConfig["frequency"].get(); - this->particleConfig.frequency = particleShowFrequency; - if (particleShowFrequency <= 0) { - L_WARNING("invalid frequency value,set to default 40"); - this->particleConfig.frequency = 40; + + bool ConfigManager::readConfigFile(const std::string &configFileName) { + try { + std::ifstream i(configFileName); + i >> this->configJson; + L_DEBUG("read config file %s successfully\n", + configFileName.c_str()); + return true; + } catch (std::exception &e) { + L_ERROR("can not read config file %s with error %s", + configFileName.c_str(), e.what()); + return false; } - auto pvd = partConfig["defaultViewDistance"].get(); - this->particleConfig.defaultViewDistance = pvd; - if (pvd <= 0) { - L_WARNING("invalid pvd value,set to default 128"); - this->particleConfig.frequency = 128; + } + + bool ConfigManager::readFunctionConfig() { + L_DEBUG("begin read function config"); + try { + auto funcConfig = this->configJson["functionsEnable"]; + this->functionConfig.hopperCounter = + funcConfig["hopperCounter"].get(); + // this->functionConfig.explosion = + // funcConfig["explosion"].get(); + this->functionConfig.spawnHelper = + funcConfig["spawnHelper"].get(); + this->functionConfig.cactusRotation = + funcConfig["cactusRotate"].get(); + this->functionConfig.simpleDraw = + funcConfig["simpleDraw"].get(); + this->functionConfig.playerStat = + funcConfig["playerStat"].get(); + + L_DEBUG("read function config successfully\n"); + } catch (std::exception &e) { + L_ERROR("can not read function config: %s", e.what()); + return false; } - this->particleConfig.performanceMode = - partConfig["performanceMode"].get(); - } catch (std::exception &e) { - L_ERROR("%s", e.what()); - return false; + return true; } - return true; -} - -void ConfigManager::printAllConfig() const {} - -bool ConfigManager::readLowLevelVanillaCommands() { - L_DEBUG("begin read low level vanilla command info"); - try { - auto lowLevelVanillaCommandsConfig = - this->configJson["lowLevelVanillaCommands"]; - for (const auto &i : lowLevelVanillaCommandsConfig) { - this->lowerLevelVanillaCommands.insert(i.get()); + + bool ConfigManager::readParticleConfig() { + try { + auto partConfig = this->configJson["particle"]; + auto particleShowFrequency = partConfig["frequency"].get(); + this->particleConfig.frequency = particleShowFrequency; + if (particleShowFrequency <= 0) { + L_WARNING("invalid frequency value,set to default 40"); + this->particleConfig.frequency = 40; + } + auto pvd = partConfig["defaultViewDistance"].get(); + this->particleConfig.defaultViewDistance = pvd; + if (pvd <= 0) { + L_WARNING("invalid pvd value,set to default 128"); + this->particleConfig.frequency = 128; + } + this->particleConfig.performanceMode = + partConfig["performanceMode"].get(); + } catch (std::exception &e) { + L_ERROR("%s", e.what()); + return false; } - L_DEBUG("here are the all low level commands:"); - for (const auto &item : this->lowerLevelVanillaCommands) { - L_DEBUG("- %s", item.c_str()); + return true; + } + + void ConfigManager::printAllConfig() const {} + + bool ConfigManager::readLowLevelVanillaCommands() { + L_DEBUG("begin read low level vanilla command info"); + try { + auto lowLevelVanillaCommandsConfig = + this->configJson["lowLevelVanillaCommands"]; + for (const auto &i : lowLevelVanillaCommandsConfig) { + this->lowerLevelVanillaCommands.insert(i.get()); + } + L_DEBUG("here are the all low level commands:"); + for (const auto &item : this->lowerLevelVanillaCommands) { + L_DEBUG("- %s", item.c_str()); + } + L_DEBUG("read low level vanilla commands successfully\n"); + } catch (std::exception &e) { + L_ERROR("error read low level vanilla command info : %s", e.what()); + return false; } - L_DEBUG("read low level vanilla commands successfully\n"); - } catch (std::exception &e) { - L_ERROR("error read low level vanilla command info : %s", e.what()); - return false; + return true; } - return true; -} - -bool ConfigManager::readServerConfig() { - L_DEBUG("begin read server info"); - try { - auto config = this->configJson["server"]; - //以后可能会有其它配置项 - this->serverConfig.levelName = config["levelName"].get(); - this->serverConfig.wsUrl = config["ws"].get(); - L_DEBUG(" - levelMame : %s\nread server info successfully\n", - serverConfig.levelName.c_str()); - } catch (std::exception &e) { - L_ERROR("can not read server config : %s", e.what()); - return false; + + bool ConfigManager::readServerConfig() { + L_DEBUG("begin read server info"); + try { + auto config = this->configJson["server"]; + //以后可能会有其它配置项 + this->serverConfig.levelName = + config["levelName"].get(); + this->serverConfig.wsUrl = config["ws"].get(); + L_DEBUG(" - levelMame : %s\nread server info successfully\n", + serverConfig.levelName.c_str()); + } catch (std::exception &e) { + L_ERROR("can not read server config : %s", e.what()); + return false; + } + return true; } - return true; -} - -bool ConfigManager::readVillageConfig() { - L_DEBUG("begin read village config info"); - try { - auto config = this->configJson["village"]; - //以后可能会有其它配置项 - auto boundColor = config["bound"].get(); - auto spawnColor = config["spawn"].get(); - auto poiQuery = config["poiQuery"].get(); - auto centerParticle = config["center"].get(); - this->villageHelperConfig = {str2color(boundColor), - str2color(spawnColor), str2color(poiQuery), - centerParticle}; - L_DEBUG(" - bound color: %s\n - spawn color: %s\n - poiQueryColor: " + + bool ConfigManager::readVillageConfig() { + L_DEBUG("begin read village config info"); + try { + auto config = this->configJson["village"]; + //以后可能会有其它配置项 + auto boundColor = config["bound"].get(); + auto spawnColor = config["spawn"].get(); + auto poiQuery = config["poiQuery"].get(); + auto centerParticle = config["center"].get(); + this->villageHelperConfig = {str2color(boundColor), + str2color(spawnColor), + str2color(poiQuery), centerParticle}; + L_DEBUG( + " - bound color: %s\n - spawn color: %s\n - poiQueryColor: " "%s\n - center:%s", boundColor.c_str(), spawnColor.c_str(), poiQuery.c_str(), centerParticle.c_str()); - L_DEBUG("read village color successfully\n"); - } catch (std::exception &e) { - L_ERROR("can not read village config : %s", e.what()); - return false; + L_DEBUG("read village color successfully\n"); + } catch (std::exception &e) { + L_ERROR("can not read village config : %s", e.what()); + return false; + } + return true; } - return true; -} - -bool ConfigManager::readSelfConfig() { - L_DEBUG("begin read self command config"); - try { - auto funcConfig = this->configJson["selfEnable"]; - this->selfEnableConfig.enableChunkShow = - funcConfig["chunkShow"].get(); - this->selfEnableConfig.enableDistanceMeasure = - funcConfig["distanceMeasure"].get(); - this->selfEnableConfig.enableRedstoneStick = - funcConfig["redstoneStick"].get(); - L_DEBUG("read self command config successfully\n"); - } catch (std::exception &e) { - L_ERROR("can not read self config: %s", e.what()); - return false; + + bool ConfigManager::readSelfConfig() { + L_DEBUG("begin read self command config"); + try { + auto funcConfig = this->configJson["selfEnable"]; + this->selfEnableConfig.enableChunkShow = + funcConfig["chunkShow"].get(); + this->selfEnableConfig.enableDistanceMeasure = + funcConfig["distanceMeasure"].get(); + this->selfEnableConfig.enableRedstoneStick = + funcConfig["redstoneStick"].get(); + L_DEBUG("read self command config successfully\n"); + } catch (std::exception &e) { + L_ERROR("can not read self config: %s", e.what()); + return false; + } + return true; } - return true; -} - -bool ConfigManager::readEULA() { - L_DEBUG("begin read EULA"); - try { - auto config = this->configJson["EULA"]; - //以后可能会有其它配置项 - auto acceptEULA = config.get(); - if (!acceptEULA) { - L_ERROR("you need to accept the EULA before use trapdoor mod"); - } else { - L_DEBUG("read eula success"); + + bool ConfigManager::readEULA() { + L_DEBUG("begin read EULA"); + try { + auto config = this->configJson["EULA"]; + //以后可能会有其它配置项 + auto acceptEULA = config.get(); + if (!acceptEULA) { + L_ERROR("you need to accept the EULA before use trapdoor mod"); + } else { + L_DEBUG("read eula success"); + } + return acceptEULA; + } catch (std::exception &e) { + L_ERROR("can not read server config : %s", e.what()); + return false; } - return acceptEULA; - } catch (std::exception &e) { - L_ERROR("can not read server config : %s", e.what()); - return false; + return true; } - return true; -} -} // namespace mod \ No newline at end of file +} // namespace mod \ No newline at end of file diff --git a/mod/config/ConfigManager.h b/mod/config/ConfigManager.h index 3b7965d..77c642d 100644 --- a/mod/config/ConfigManager.h +++ b/mod/config/ConfigManager.h @@ -5,109 +5,111 @@ #ifndef TRAPDOOR_CONFIGMANAGER_H #define TRAPDOOR_CONFIGMANAGER_H +#include +#include +#include + #include "Village.h" #include "commands/CommandManager.h" #include "tools/DirtyLogger.h" #include "tools/json.hpp" #include "tools/noncopyable .h" -#include -#include -#include namespace mod { -using json = nlohmann::json; - -class ConfigManager : public noncopyable { - public: - //命令配置选项结构体 - struct FunctionEnableConfig { - bool hopperCounter = true; //漏斗计数器 - bool explosion = true; //爆炸破坏地形 - bool spawnHelper = true; //刷怪指示器 - bool cactusRotation = false; //仙人掌转方块 - bool playerStat = false; //玩家行为统计 - bool simpleDraw = true; //画圆 - }; + using json = nlohmann::json; - struct SelfEnableConfig { - bool enableChunkShow = true; //区块显示 - bool enableDistanceMeasure = true; //距离测量 - bool enableRedstoneStick = true; //信号源提示 - }; + class ConfigManager : public noncopyable { + public: + //命令配置选项结构体 + struct FunctionEnableConfig { + bool hopperCounter = true; //漏斗计数器 + bool explosion = true; //爆炸破坏地形 + bool spawnHelper = true; //刷怪指示器 + bool cactusRotation = false; //仙人掌转方块 + bool playerStat = false; //玩家行为统计 + bool simpleDraw = true; //画圆 + }; - struct ParticleConfig { - size_t frequency = 40; //显示频率(gt) - size_t defaultViewDistance = 128; // blockpos - bool performanceMode = false; - }; + struct SelfEnableConfig { + bool enableChunkShow = true; //区块显示 + bool enableDistanceMeasure = true; //距离测量 + bool enableRedstoneStick = true; //信号源提示 + }; - struct ServerConfig { - std::string levelName; - std::string wsUrl; - }; + struct ParticleConfig { + size_t frequency = 40; //显示频率(gt) + size_t defaultViewDistance = 128; // blockpos + bool performanceMode = false; + }; + + struct ServerConfig { + std::string levelName; + std::string wsUrl; + }; - private: - json configJson; - std::map commandsConfig; - std::set lowerLevelVanillaCommands; + private: + json configJson; + std::map commandsConfig; + std::set lowerLevelVanillaCommands; - FunctionEnableConfig functionConfig; - ParticleConfig particleConfig; - VillageHelperConfig villageHelperConfig; - ServerConfig serverConfig; - SelfEnableConfig selfEnableConfig; + FunctionEnableConfig functionConfig; + ParticleConfig particleConfig; + VillageHelperConfig villageHelperConfig; + ServerConfig serverConfig; + SelfEnableConfig selfEnableConfig; - bool readCommandConfig(); + bool readCommandConfig(); - bool readConfigFile(const std::string &configFileName); + bool readConfigFile(const std::string &configFileName); - bool readFunctionConfig(); + bool readFunctionConfig(); - bool readSelfConfig(); + bool readSelfConfig(); - bool readParticleConfig(); + bool readParticleConfig(); - bool readEULA(); + bool readEULA(); - bool readLowLevelVanillaCommands(); + bool readLowLevelVanillaCommands(); - bool readServerConfig(); + bool readServerConfig(); - bool readVillageConfig(); + bool readVillageConfig(); - public: - inline const FunctionEnableConfig &getFunctionConfig() { - return this->functionConfig; - } + public: + inline const FunctionEnableConfig &getFunctionConfig() { + return this->functionConfig; + } - inline std::map &getCommandsConfig() { - return this->commandsConfig; - } + inline std::map + &getCommandsConfig() { + return this->commandsConfig; + } - inline const ParticleConfig &getParticleConfig() { - return this->particleConfig; - } + inline const ParticleConfig &getParticleConfig() { + return this->particleConfig; + } - bool initialize(const std::string &configFileName); + bool initialize(const std::string &configFileName); - void printAllConfig() const; + void printAllConfig() const; - inline const std::set &getLowLevelCommands() const { - return this->lowerLevelVanillaCommands; - } + inline const std::set &getLowLevelCommands() const { + return this->lowerLevelVanillaCommands; + } - inline const VillageHelperConfig &getVillageConfig() const { - return this->villageHelperConfig; - } + inline const VillageHelperConfig &getVillageConfig() const { + return this->villageHelperConfig; + } - inline const ServerConfig &getServerConfig() const { - return this->serverConfig; - } + inline const ServerConfig &getServerConfig() const { + return this->serverConfig; + } - inline const SelfEnableConfig &getSelfEnableConfig() const { - return this->selfEnableConfig; - } -}; -} // namespace mod + inline const SelfEnableConfig &getSelfEnableConfig() const { + return this->selfEnableConfig; + } + }; +} // namespace mod -#endif // TRAPDOOR_CONFIGMANAGER_H +#endif // TRAPDOOR_CONFIGMANAGER_H diff --git a/mod/dllmain.cpp b/mod/dllmain.cpp index af79754..f5fc129 100644 --- a/mod/dllmain.cpp +++ b/mod/dllmain.cpp @@ -1,10 +1,11 @@ #define _WINSOCKAPI_ +#include + #include "BDSMod.h" #include "TrapdoorMod.h" #include "lib/Remotery.h" #include "tools/DirtyLogger.h" -#include /* * 设置所有输出为utf8,设置支持彩色输出 @@ -15,7 +16,7 @@ void initConsole() { HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); DWORD dwMode; GetConsoleMode(hOutput, &dwMode); - dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; // NOLINT + dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; // NOLINT SetConsoleMode(hOutput, dwMode); } @@ -28,15 +29,15 @@ void mod_init() { rmt_CreateGlobalInstance(&rmt); // displayDisclaimerMessageBox(); //免责声明窗口 initConsole(); - trapdoor::initLogger("plugins/trapdoor/trapdoor.log"); //初始化日志 + trapdoor::initLogger("plugins/trapdoor/trapdoor.log"); //初始化日志 #ifdef BETA trapdoor::setDevMode(true); #endif - mod::TrapdoorMod::printCopyRightInfo(); //打印日志 + mod::TrapdoorMod::printCopyRightInfo(); //打印日志 auto *mod = createBDSModInstance(); mod->getI18NManager().initialize(); auto result = mod->asInstance()->readConfigFile( - "plugins/trapdoor/trapdoor-config.json"); //读取配置文件 + "plugins/trapdoor/trapdoor-config.json"); //读取配置文件 if (!result) { L_ERROR("can not read configFile, trapdoor won't be injected"); return; @@ -48,17 +49,17 @@ void mod_exit() { rmt_DestroyGlobalInstance(rmt); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { - switch (ul_reason_for_call) { // NOLINT - case DLL_PROCESS_ATTACH: - mod_init(); - break; - case DLL_THREAD_ATTACH: // NOLINT - break; - case DLL_THREAD_DETACH: - break; - case DLL_PROCESS_DETACH: - mod_exit(); - break; + switch (ul_reason_for_call) { // NOLINT + case DLL_PROCESS_ATTACH: + mod_init(); + break; + case DLL_THREAD_ATTACH: // NOLINT + break; + case DLL_THREAD_DETACH: + break; + case DLL_PROCESS_DETACH: + mod_exit(); + break; } return TRUE; } diff --git a/mod/fakePlayer/FakePlayerClient.cpp b/mod/fakePlayer/FakePlayerClient.cpp index 39a40c9..cffa4c6 100644 --- a/mod/fakePlayer/FakePlayerClient.cpp +++ b/mod/fakePlayer/FakePlayerClient.cpp @@ -3,6 +3,7 @@ // #include "FakePlayerClient.h" + #include "ConfigManager.h" #include "TrapdoorMod.h" #include "entity/Actor.h" @@ -12,156 +13,158 @@ namespace mod { -void FakePlayerClient::registerFakePlayerCommand(CommandManager &manager) { - using namespace trapdoor; - manager.registerCmd("fakeplayer", "command.fakeplayer.desc") - ->then(ARG("c", "command.fakeplayer.c.desc", NONE, - { this->connect(player, ""); })) - ->then(ARG("conn", "command.fakeplayer.conn.desc", STR, - { this->connect(player, holder->getString()); })) - ->then(ARG("list", "command.fakeplayer.list.desc", NONE, - { - this->sendMessage(player, FakePlayerClient::buildMessage( - MessageType::PLAYER_LIST)); - })) - ->then(ARG("add", "command.fakeplayer.add.desc", STR, - { - this->sendMessage(player, FakePlayerClient::buildMessage( - MessageType::ADD_PLAYER, - holder->getString())); - })) - ->then(ARG("rm", "command.fakeplayer.remove.desc", STR, - { - this->sendMessage(player, FakePlayerClient::buildMessage( - MessageType::REMOVE_PLAYER, - holder->getString())); - })) - ->then(ARG("tp", "command.fakeplayer.tp.desc", STR, - { this->tpFakePlayer(player, holder->getString()); })); -} - -//发送消息 -bool FakePlayerClient::sendMessage(trapdoor::Actor *player, - const std::string &msg) { - //如果可以发送消息就发送,不能发送就gg - if (!webSocket || - webSocket->getReadyState() == easywsclient::WebSocket::CLOSED) { - trapdoor::error(player, trapdoor::LANG("fp.error.noConnect")); - return false; - } - if (this->clientStatus != ClientStatus::READY) { - trapdoor::error(player, trapdoor::LANG("fp.error.status")); + void FakePlayerClient::registerFakePlayerCommand(CommandManager &manager) { + using namespace trapdoor; + manager.registerCmd("fakeplayer", "command.fakeplayer.desc") + ->then(ARG("c", "command.fakeplayer.c.desc", NONE, + { this->connect(player, ""); })) + ->then(ARG("conn", "command.fakeplayer.conn.desc", STR, + { this->connect(player, holder->getString()); })) + ->then(ARG("list", "command.fakeplayer.list.desc", NONE, + { + this->sendMessage(player, + FakePlayerClient::buildMessage( + MessageType::PLAYER_LIST)); + })) + ->then(ARG("add", "command.fakeplayer.add.desc", STR, + { + this->sendMessage(player, + FakePlayerClient::buildMessage( + MessageType::ADD_PLAYER, + holder->getString())); + })) + ->then(ARG("rm", "command.fakeplayer.remove.desc", STR, + { + this->sendMessage(player, + FakePlayerClient::buildMessage( + MessageType::REMOVE_PLAYER, + holder->getString())); + })) + ->then(ARG("tp", "command.fakeplayer.tp.desc", STR, + { this->tpFakePlayer(player, holder->getString()); })); } - this->webSocket->send(msg); - this->source = player; - this->clientStatus = ClientStatus::WAITING_MESSAGE; - return true; -} - -//在单独的线程中来进行消息的收取 -void FakePlayerClient::run() { - this->pool->enqueue([&] { - //如果socket 是处于开启状态就一直监听作为事件循环 - while (this->webSocket && this->webSocket->getReadyState() != - easywsclient::WebSocket::CLOSED) { - this->webSocket->poll(50); - this->webSocket->dispatch([&](const std::string &msg) { - if (this->clientStatus == ClientStatus::WAITING_MESSAGE) { - //改变状态来通知消息到了 - this->clientStatus = ClientStatus::NEED_CONSUME; - this->message = msg; - } - //这里可能是有超时的消息,就不处理了,防止消息出现错乱 - //也就是丢弃超时的消息 - }); + //发送消息 + bool FakePlayerClient::sendMessage(trapdoor::Actor *player, + const std::string &msg) { + //如果可以发送消息就发送,不能发送就gg + if (!webSocket || + webSocket->getReadyState() == easywsclient::WebSocket::CLOSED) { + trapdoor::error(player, trapdoor::LANG("fp.error.noConnect")); + return false; } - this->disconnectCallBack(); - }); -} - -bool FakePlayerClient::consume() { - bool status = true; - auto msg = FakePlayerClient::parseResponse(this->message, status); - //处理服务端的回复消息 - if (source) { - if (status) { - trapdoor::info(this->source, "%s", msg.c_str()); - } else { - trapdoor::error(this->source, "%s", msg.c_str()); + if (this->clientStatus != ClientStatus::READY) { + trapdoor::error(player, trapdoor::LANG("fp.error.status")); } - } else { - trapdoor::broadcastMsg(trapdoor::LANG("fp.error.noSource"), - msg.c_str()); + this->webSocket->send(msg); + this->source = player; + this->clientStatus = ClientStatus::WAITING_MESSAGE; + return true; } - return true; -} - -void FakePlayerClient::connect(trapdoor::Actor *player, - const std::string &url) { - auto wsUrl = url; - if (wsUrl.empty()) { - auto mod = trapdoor::bdsMod->asInstance(); - wsUrl = mod->getConfigManager().getServerConfig().wsUrl; + + //在单独的线程中来进行消息的收取 + void FakePlayerClient::run() { + this->pool->enqueue([&] { + //如果socket 是处于开启状态就一直监听作为事件循环 + while (this->webSocket && this->webSocket->getReadyState() != + easywsclient::WebSocket::CLOSED) { + this->webSocket->poll(50); + this->webSocket->dispatch([&](const std::string &msg) { + if (this->clientStatus == ClientStatus::WAITING_MESSAGE) { + //改变状态来通知消息到了 + this->clientStatus = ClientStatus::NEED_CONSUME; + this->message = msg; + } + + //这里可能是有超时的消息,就不处理了,防止消息出现错乱 + //也就是丢弃超时的消息 + }); + } + this->disconnectCallBack(); + }); } - L_INFO("ws url is %s\n", wsUrl.c_str()); - this->webSocket = easywsclient::WebSocket::from_url(wsUrl); - if (this->webSocket) { - this->clientStatus = ClientStatus::READY; - trapdoor::info(player, trapdoor::LANG("fp.info.connected"), - wsUrl.c_str()); - this->run(); - } else { - trapdoor::info(player, trapdoor::LANG("fp.error.connect"), - wsUrl.c_str()); + + bool FakePlayerClient::consume() { + bool status = true; + auto msg = FakePlayerClient::parseResponse(this->message, status); + //处理服务端的回复消息 + if (source) { + if (status) { + trapdoor::info(this->source, "%s", msg.c_str()); + } else { + trapdoor::error(this->source, "%s", msg.c_str()); + } + } else { + trapdoor::broadcastMsg(trapdoor::LANG("fp.error.noSource"), + msg.c_str()); + } + return true; } -} - -//更新状态,查询和消费消息队列 -void FakePlayerClient::tick() { - //如果是等待消息的状态就增加计时器如果五秒内收不到消息就说明消息发送失败 - if (this->clientStatus == ClientStatus::WAITING_MESSAGE) { - this->timer++; - //超过100gt没有回复就说明连接炸了 - if (this->timer == 100) { - this->message = trapdoor::LANG("fp.tick.timeout"); - this->clientStatus = ClientStatus::NEED_CONSUME; + + void FakePlayerClient::connect(trapdoor::Actor *player, + const std::string &url) { + auto wsUrl = url; + if (wsUrl.empty()) { + auto mod = trapdoor::bdsMod->asInstance(); + wsUrl = mod->getConfigManager().getServerConfig().wsUrl; + } + L_INFO("ws url is %s\n", wsUrl.c_str()); + this->webSocket = easywsclient::WebSocket::from_url(wsUrl); + if (this->webSocket) { + this->clientStatus = ClientStatus::READY; + trapdoor::info(player, trapdoor::LANG("fp.info.connected"), + wsUrl.c_str()); + this->run(); + } else { + trapdoor::info(player, trapdoor::LANG("fp.error.connect"), + wsUrl.c_str()); } } - //如果有消息需要消费就消费消息 - if (this->clientStatus == ClientStatus::NEED_CONSUME) { - this->consume(); - //重置状态和计时器 - this->clientStatus = ClientStatus::READY; - this->timer = 0; + //更新状态,查询和消费消息队列 + void FakePlayerClient::tick() { + //如果是等待消息的状态就增加计时器如果五秒内收不到消息就说明消息发送失败 + if (this->clientStatus == ClientStatus::WAITING_MESSAGE) { + this->timer++; + //超过100gt没有回复就说明连接炸了 + if (this->timer == 100) { + this->message = trapdoor::LANG("fp.tick.timeout"); + this->clientStatus = ClientStatus::NEED_CONSUME; + } + } + + //如果有消息需要消费就消费消息 + if (this->clientStatus == ClientStatus::NEED_CONSUME) { + this->consume(); + //重置状态和计时器 + this->clientStatus = ClientStatus::READY; + this->timer = 0; + } } -} - -FakePlayerClient::~FakePlayerClient() { disconnect(); } - -//断开连接 -void FakePlayerClient::disconnect() { - if (webSocket) - webSocket->close(); - delete webSocket; - this->disconnectCallBack(); -} - -void FakePlayerClient::disconnectCallBack() { - trapdoor::broadcastMsg(trapdoor::LANG("fp.info.disconnectCallBack")); - this->clientStatus = ClientStatus::NOT_OPEN; -} - -std::string FakePlayerClient::buildMessage(FakePlayerClient::MessageType type, - const std::string ¶m) { - switch (type) { - case MessageType::PLAYER_LIST: - return R"({ + + FakePlayerClient::~FakePlayerClient() { disconnect(); } + + //断开连接 + void FakePlayerClient::disconnect() { + if (webSocket) webSocket->close(); + delete webSocket; + this->disconnectCallBack(); + } + + void FakePlayerClient::disconnectCallBack() { + trapdoor::broadcastMsg(trapdoor::LANG("fp.info.disconnectCallBack")); + this->clientStatus = ClientStatus::NOT_OPEN; + } + + std::string FakePlayerClient::buildMessage( + FakePlayerClient::MessageType type, const std::string ¶m) { + switch (type) { + case MessageType::PLAYER_LIST: + return R"({ "type": "list" })"; - case MessageType::ADD_PLAYER: - return trapdoor::format(R"( + case MessageType::ADD_PLAYER: + return trapdoor::format(R"( { "type": "add", "data": { @@ -170,9 +173,9 @@ std::string FakePlayerClient::buildMessage(FakePlayerClient::MessageType type, } } )", - param.c_str()); - case MessageType::REMOVE_PLAYER: - return trapdoor::format(R"( + param.c_str()); + case MessageType::REMOVE_PLAYER: + return trapdoor::format(R"( { "type": "remove", "data": { @@ -180,72 +183,74 @@ std::string FakePlayerClient::buildMessage(FakePlayerClient::MessageType type, } } )", - param.c_str()); + param.c_str()); + } + return "{}"; } - return "{}"; -} - -std::string FakePlayerClient::parseResponse(const std::string &response, - bool &status) { - using json = nlohmann::json; - try { - json jsonMsg = json::parse(response); - auto respType = jsonMsg["type"].get(); - auto respData = jsonMsg["data"]; - if (respType == "list") { - status = true; - std::string strBuilder = - trapdoor::LANG("fp.info.list"); //下面是所有的假人玩家 - this->fakePlayerList.clear(); - for (auto &i : respData["list"]) { - strBuilder += "\n"; - strBuilder += i.get(); - this->fakePlayerList.insert(i.get()); - } - return strBuilder; - } else if (respType == "add" || respType == "remove") { - const std::string type = - respType == "add" - ? trapdoor::LANG("fp.added") - : trapdoor::LANG("fp.remove"); // 添加" : "移除 - auto name = respData["name"].get(); - auto success = respData["success"].get(); - if (success) { + + std::string FakePlayerClient::parseResponse(const std::string &response, + bool &status) { + using json = nlohmann::json; + try { + json jsonMsg = json::parse(response); + auto respType = jsonMsg["type"].get(); + auto respData = jsonMsg["data"]; + if (respType == "list") { status = true; - return trapdoor::format(trapdoor::LANG("fp.connect.success"), - type.c_str(), - name.c_str()); // 成功%s假人[%s] + std::string strBuilder = + trapdoor::LANG("fp.info.list"); //下面是所有的假人玩家 + this->fakePlayerList.clear(); + for (auto &i : respData["list"]) { + strBuilder += "\n"; + strBuilder += i.get(); + this->fakePlayerList.insert(i.get()); + } + return strBuilder; + } else if (respType == "add" || respType == "remove") { + const std::string type = + respType == "add" + ? trapdoor::LANG("fp.added") + : trapdoor::LANG("fp.remove"); // 添加" : "移除 + auto name = respData["name"].get(); + auto success = respData["success"].get(); + if (success) { + status = true; + return trapdoor::format( + trapdoor::LANG("fp.connect.success"), type.c_str(), + name.c_str()); // 成功%s假人[%s] + } else { + status = false; + auto reason = respData["reason"].get(); + return trapdoor::format( + trapdoor::LANG("fp.connect.fail"), type.c_str(), + name.c_str(), + reason.c_str()); //无法%s假人[%s],原因: %s + } } else { status = false; - auto reason = respData["reason"].get(); - return trapdoor::format( - trapdoor::LANG("fp.connect.fail"), type.c_str(), - name.c_str(), - reason.c_str()); //无法%s假人[%s],原因: %s + return "unknown message"; } - } else { + } catch (std::exception &e) { status = false; - return "unknown message"; + return trapdoor::format("message error: %s", e.what()); } - } catch (std::exception &e) { - status = false; - return trapdoor::format("message error: %s", e.what()); } -} - -void FakePlayerClient::tpFakePlayer(trapdoor::Actor *player, - const std::string &playerName) { - trapdoor::warning(player, "this function is blocked by developer"); - if (this->fakePlayerList.count(playerName)) { - std::string tpCmd = "tp " + playerName + " " + player->getNameTag(); - CommandManager::runVanillaCommand(tpCmd); - trapdoor::info(this->source, trapdoor::LANG("fp.tp.success"), - player->getNameTag().c_str()); //假人已被tp到[%s]所在位置 - } else { - trapdoor::info( - this->source, - trapdoor::LANG("fp.tp.fail")); //找不到假人,请尝试执行fakeplayer - // list指令后再试 + + void FakePlayerClient::tpFakePlayer(trapdoor::Actor *player, + const std::string &playerName) { + trapdoor::warning(player, "this function is blocked by developer"); + if (this->fakePlayerList.count(playerName)) { + std::string tpCmd = "tp " + playerName + " " + player->getNameTag(); + CommandManager::runVanillaCommand(tpCmd); + trapdoor::info( + this->source, trapdoor::LANG("fp.tp.success"), + player->getNameTag().c_str()); //假人已被tp到[%s]所在位置 + } else { + trapdoor::info( + this->source, + trapdoor::LANG( + "fp.tp.fail")); //找不到假人,请尝试执行fakeplayer + // list指令后再试 + } } -} -} // namespace mod +} // namespace mod diff --git a/mod/fakePlayer/FakePlayerClient.h b/mod/fakePlayer/FakePlayerClient.h index d536398..a75a9d9 100644 --- a/mod/fakePlayer/FakePlayerClient.h +++ b/mod/fakePlayer/FakePlayerClient.h @@ -5,21 +5,22 @@ #ifndef MOD_FAKEPLAYERCLIENT_H #define MOD_FAKEPLAYERCLIENT_H #ifdef _WIN32 -#pragma comment( lib, "ws2_32") +#pragma comment(lib, "ws2_32") #include #endif -#include "easywsclient.hpp" -#include "ThreadPool.h" -#include "CommandManager.h" #include #include #include -#include #include #include +#include + +#include "CommandManager.h" +#include "ThreadPool.h" +#include "easywsclient.hpp" namespace mod { //和falePlayer进行通信的客户端 @@ -30,13 +31,11 @@ namespace mod { WAITING_MESSAGE, NEED_CONSUME }; - enum class MessageType { - PLAYER_LIST, - ADD_PLAYER, - REMOVE_PLAYER - }; - private: - static std::string buildMessage(MessageType type, const std::string ¶m = ""); + enum class MessageType { PLAYER_LIST, ADD_PLAYER, REMOVE_PLAYER }; + + private: + static std::string buildMessage(MessageType type, + const std::string ¶m = ""); std::string parseResponse(const std::string &response, bool &status); @@ -62,7 +61,7 @@ namespace mod { this->source = player; } - public: + public: void registerFakePlayerCommand(trapdoor::CommandManager &manager); explicit FakePlayerClient(ThreadPool *threadPool) : pool(threadPool) {} @@ -73,10 +72,11 @@ namespace mod { void tick(); - void tpFakePlayer(trapdoor::Actor *player, const std::string &playerName); + void tpFakePlayer(trapdoor::Actor *player, + const std::string &playerName); ~FakePlayerClient(); }; -} -#endif //MOD_FAKEPLAYERCLIENT_H +} // namespace mod +#endif // MOD_FAKEPLAYERCLIENT_H diff --git a/mod/function/BackupHelper.cpp b/mod/function/BackupHelper.cpp index 1f7712b..576d713 100644 --- a/mod/function/BackupHelper.cpp +++ b/mod/function/BackupHelper.cpp @@ -3,142 +3,149 @@ // #include "BackupHelper.h" -#include "BDSMod.h" -#include "TrapdoorMod.h" -#include "language/I18nManager.h" -#include "tick/SimpleProfiler.h" -#include "tools/DirtyLogger.h" -#include "tools/Message.h" + #include + #include #include #include #include #include +#include "BDSMod.h" +#include "TrapdoorMod.h" +#include "language/I18nManager.h" +#include "tick/SimpleProfiler.h" +#include "tools/DirtyLogger.h" +#include "tools/Message.h" + namespace mod { -namespace { -bool isValidWorldFolder(const std::filesystem::path &path) { - // check - return true; -} - -void writeBackupScript() { - L_DEBUG("begin write backup script"); - std::ofstream out("./plugins/trapdoor/backup.ps1"); - auto levelName = - trapdoor::bdsMod->asInstance()->getLevelName(); - std::string backupScript = trapdoor::format(R"( + namespace { + bool isValidWorldFolder(const std::filesystem::path &path) { + // check + return true; + } + + void writeBackupScript() { + L_DEBUG("begin write backup script"); + std::ofstream out("./plugins/trapdoor/backup.ps1"); + auto levelName = trapdoor::bdsMod->asInstance() + ->getLevelName(); + std::string backupScript = trapdoor::format(R"( $Date = $(get-date -f yyyy-MM-dd)+" "+$(get-date -f HH-mm-ss) $SourcePath = "worlds/%s" $Destination = "plugins\trapdoor\backup\$Date" New-Item -Path "plugins\trapdoor\backup" -Name "$Date" -ItemType "directory" | Out-Null Copy-Item -Path $SourcePath -Destination "$Destination" -Recurse | Out-Null )", - levelName.c_str()); - out << backupScript; - out.close(); -} - -std::vector getAllBackups(trapdoor::Actor *player) { - namespace fs = std::filesystem; - fs::path backupRootPath("./plugins/trapdoor/backup"); - if (!fs::exists(backupRootPath)) { - trapdoor::error(player, trapdoor::LANG("backup.error.dictNotExist")); - return {}; - } - std::vector backupList; - fs::directory_entry entry(backupRootPath); //文件入口 - if (entry.status().type() == fs::file_type::directory) { - for (const auto &iter : fs::directory_iterator(backupRootPath)) { - if (fs::is_directory(iter.path()) && - isValidWorldFolder(iter.path())) { - auto str = iter.path().string(); - auto p1 = str.rfind('\\'); - backupList.push_back(str.substr(p1 + 1, str.size() - p1)); + levelName.c_str()); + out << backupScript; + out.close(); + } + + std::vector getAllBackups(trapdoor::Actor *player) { + namespace fs = std::filesystem; + fs::path backupRootPath("./plugins/trapdoor/backup"); + if (!fs::exists(backupRootPath)) { + trapdoor::error(player, + trapdoor::LANG("backup.error.dictNotExist")); + return {}; } + std::vector backupList; + fs::directory_entry entry(backupRootPath); //文件入口 + if (entry.status().type() == fs::file_type::directory) { + for (const auto &iter : + fs::directory_iterator(backupRootPath)) { + if (fs::is_directory(iter.path()) && + isValidWorldFolder(iter.path())) { + auto str = iter.path().string(); + auto p1 = str.rfind('\\'); + backupList.push_back( + str.substr(p1 + 1, str.size() - p1)); + } + } + } + return backupList; } + + } // namespace + + void backup(trapdoor::Actor *player) { + trapdoor::broadcastMsg(LANG("backup.info.start")); + //我也不知道为啥不会崩服 + trapdoor::bdsMod->getThreadPool()->enqueue([&]() { + const std::string backupScript = + R"(powershell ./plugins/trapdoor/backup.ps1)"; + writeBackupScript(); + int r = system(backupScript.c_str()); + if (r == 0) { + trapdoor::broadcastMsg(LANG("backup.info.end")); + } else { + trapdoor::broadcastMsg(LANG("backup.error.failure"), r); + } + }); } - return backupList; -} - -} // namespace - -void backup(trapdoor::Actor *player) { - trapdoor::broadcastMsg(LANG("backup.info.start")); - //我也不知道为啥不会崩服 - trapdoor::bdsMod->getThreadPool()->enqueue([&]() { - const std::string backupScript = - R"(powershell ./plugins/trapdoor/backup.ps1)"; - writeBackupScript(); - int r = system(backupScript.c_str()); - if (r == 0) { - trapdoor::broadcastMsg(LANG("backup.info.end")); - } else { - trapdoor::broadcastMsg(LANG("backup.error.failure"), r); - } - }); -} -void initBackup() { - L_DEBUG("create backup folder"); + void initBackup() { + L_DEBUG("create backup folder"); - namespace fs = std::filesystem; - std::filesystem::create_directory("./plugins/trapdoor/backup"); + namespace fs = std::filesystem; + std::filesystem::create_directory("./plugins/trapdoor/backup"); - //往当前目录写入backup.ps1 -} + //往当前目录写入backup.ps1 + } -void listAllBackups(trapdoor::Actor *player) { - auto backupList = getAllBackups(player); - if (backupList.empty()) { - trapdoor::error(player, LANG("backup.info.noBackups")); - return; + void listAllBackups(trapdoor::Actor *player) { + auto backupList = getAllBackups(player); + if (backupList.empty()) { + trapdoor::error(player, LANG("backup.info.noBackups")); + return; + } + trapdoor::MessageBuilder builder; + int totalSize = backupList.size(); + int maxNum = totalSize < 10 ? totalSize : 10; + std::string stringBuilder; + for (int i = 0; i < maxNum; i++) { + builder.num(i).textF(" %s\n", + backupList[totalSize - i - 1].c_str()); + stringBuilder += trapdoor::format( + C_INT "\n", backupList[totalSize - i - 1].c_str()); + } + if (totalSize > 10) { + builder.textF(LANG("backup.info.moreBackups"), totalSize - 10); + } + builder.send(player); } - trapdoor::MessageBuilder builder; - int totalSize = backupList.size(); - int maxNum = totalSize < 10 ? totalSize : 10; - std::string stringBuilder; - for (int i = 0; i < maxNum; i++) { - - builder.num(i).textF(" %s\n", backupList[totalSize - i - 1].c_str()); - stringBuilder += - trapdoor::format(C_INT "\n", backupList[totalSize - i - 1].c_str()); + + void restore(trapdoor::Actor *player, int index) { + trapdoor::warning(player, "咕咕咕"); + // return; + // namespace fs = std::filesystem; + // auto backupList = getAllBackups(player); + // if (index < 0 || index >= backupList.size() || + // backupList.empty()) + // { + // trapdoor::error(player, "该备份不存在"); + // } else { + // trapdoor::info(player, "正在恢复备份: %s", + // backupList[backupList.size() - 1 - index].c_str()); + // } } - if (totalSize > 10) { - builder.textF(LANG("backup.info.moreBackups"), totalSize - 10); + + void registerBackupCommand(CommandManager &commandManager) { + commandManager.registerCmd("backup", "command.backup.desc") + ->then(ARG("b", "command.backup.b.desc", NONE, + { mod::backup(player); })) + ->then(ARG("l", "command.backup.l.desc", NONE, + { mod::listAllBackups(player); })) + ->then(ARG("r", "command.backup.r.desc", INT, + { mod::restore(player, holder->getInt()); })) + ->then(ARG("crash", "command.backup.crash.desc", NONE, { + //这种指令的存在真的好吗 + // trapdoor::warning(player, "this command has been removed"); + *((char *)(0)) = 0; + })); } - builder.send(player); -} - -void restore(trapdoor::Actor *player, int index) { - trapdoor::warning(player, "咕咕咕"); - // return; - // namespace fs = std::filesystem; - // auto backupList = getAllBackups(player); - // if (index < 0 || index >= backupList.size() || backupList.empty()) - // { - // trapdoor::error(player, "该备份不存在"); - // } else { - // trapdoor::info(player, "正在恢复备份: %s", - // backupList[backupList.size() - 1 - index].c_str()); - // } -} - -void registerBackupCommand(CommandManager &commandManager) { - commandManager.registerCmd("backup", "command.backup.desc") - ->then( - ARG("b", "command.backup.b.desc", NONE, { mod::backup(player); })) - ->then(ARG("l", "command.backup.l.desc", NONE, - { mod::listAllBackups(player); })) - ->then(ARG("r", "command.backup.r.desc", INT, - { mod::restore(player, holder->getInt()); })) - ->then(ARG("crash", "command.backup.crash.desc", NONE, { - //这种指令的存在真的好吗 - // trapdoor::warning(player, "this command has been removed"); - *((char *)(0)) = 0; - })); -} - -} // namespace mod + +} // namespace mod diff --git a/mod/function/BackupHelper.h b/mod/function/BackupHelper.h index 01a8be1..a950041 100644 --- a/mod/function/BackupHelper.h +++ b/mod/function/BackupHelper.h @@ -9,15 +9,15 @@ #include "entity/Actor.h" namespace mod { -void backup(trapdoor::Actor *player); + void backup(trapdoor::Actor *player); -void listAllBackups(trapdoor::Actor *player); + void listAllBackups(trapdoor::Actor *player); -void initBackup(); + void initBackup(); -void restore(trapdoor::Actor *player, int index = 0); + void restore(trapdoor::Actor *player, int index = 0); -void registerBackupCommand(trapdoor::CommandManager &commandManager); -} // namespace mod + void registerBackupCommand(trapdoor::CommandManager &commandManager); +} // namespace mod -#endif // MOD_BACKUPHELPER_H +#endif // MOD_BACKUPHELPER_H diff --git a/mod/function/BlockRotationHelper.cpp b/mod/function/BlockRotationHelper.cpp index f8b4c93..8912bc5 100644 --- a/mod/function/BlockRotationHelper.cpp +++ b/mod/function/BlockRotationHelper.cpp @@ -3,116 +3,118 @@ // #include "BlockRotationHelper.h" + #include "block/Block.h" #include "block/BlockSource.h" #include "block/VanillaBlockType.h" #include "graphics/BlockPos.h" namespace mod { -//我有点后悔搞个单独的类了 -void BlockRotationHelper::rotate(trapdoor::BlockPos &pos, - trapdoor::BlockSource *blockSource) const { - using trapdoor::BlockSource; - if (!this->enable) - return; - auto block = blockSource->getBlock(pos); - auto air = trapdoor::getBlockByID(trapdoor::AIR); - auto variant = block->getVariant(); - auto name = block->getName(); - if (name.find("slab") != std::string::npos) { - auto newState = (variant + 8) % 16; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("stonecutter_block") != std::string::npos) { - auto newState = 0; - if (variant < 4) - newState = 4; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("bell") != std::string::npos) { - auto newState = (variant + 1) % 16; - blockSource->setBlock(&pos, air); - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("stairs") != std::string::npos) { - auto newState = (variant + 1) % 8; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("sea") == std::string::npos && - name.find("lantern") != std::string::npos) { - auto newState = (variant + 1) % 2; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("torch") != std::string::npos) { - auto newState = (variant + 1) % 5; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, air); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("cake") != std::string::npos) { - auto newState = (variant + 1) % 7; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("grindstone") != std::string::npos) { - auto newState = (variant + 1) % 12; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("_rail") != std::string::npos || - name.find("dropper") != std::string::npos || - name.find("dispenser") != std::string::npos || - name.find("observer") != std::string::npos || - name.find("piston") != std::string::npos || - name.find("lever") != std::string::npos || - name.find("button") != std::string::npos || - name.find("rod") != std::string::npos || - name.find("barrel") != std::string::npos || - name.find("glazed_terracotta") != std::string::npos) { - auto newState = (variant % 8 + 1) % 6 + (variant / 8) * 8; + //我有点后悔搞个单独的类了 + void BlockRotationHelper::rotate(trapdoor::BlockPos &pos, + trapdoor::BlockSource *blockSource) const { + using trapdoor::BlockSource; + if (!this->enable) return; + auto block = blockSource->getBlock(pos); + auto air = trapdoor::getBlockByID(trapdoor::AIR); + auto variant = block->getVariant(); + auto name = block->getName(); + if (name.find("slab") != std::string::npos) { + auto newState = (variant + 8) % 16; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("stonecutter_block") != std::string::npos) { + auto newState = 0; + if (variant < 4) newState = 4; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("bell") != std::string::npos) { + auto newState = (variant + 1) % 16; + blockSource->setBlock(&pos, air); + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("stairs") != std::string::npos) { + auto newState = (variant + 1) % 8; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("sea") == std::string::npos && + name.find("lantern") != std::string::npos) { + auto newState = (variant + 1) % 2; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("torch") != std::string::npos) { + auto newState = (variant + 1) % 5; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, air); + blockSource->setBlock(&pos, newBlock); + } + + // else if (name.find("cake") != std::string::npos) { + // auto newState = (variant + 1) % 7; + // auto newBlock = + // block->getLegacy()->tryGetStateBlock(newState); + // blockSource->setBlock(&pos, newBlock); + // } + else if (name.find("grindstone") != std::string::npos) { + auto newState = (variant + 1) % 12; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("_rail") != std::string::npos || + name.find("dropper") != std::string::npos || + name.find("dispenser") != std::string::npos || + name.find("observer") != std::string::npos || + name.find("piston") != std::string::npos || + name.find("lever") != std::string::npos || + name.find("button") != std::string::npos || + name.find("rod") != std::string::npos || + name.find("barrel") != std::string::npos || + name.find("glazed_terracotta") != std::string::npos) { + auto newState = (variant % 8 + 1) % 6 + (variant / 8) * 8; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, air); - // blockSource->setBlock(&pos, blockSource->getBlock(pos + - // trapdoor::BlockPos(0, 1, 0))); - blockSource->setBlock(&pos, newBlock); + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, air); + // blockSource->setBlock(&pos, blockSource->getBlock(pos + + // trapdoor::BlockPos(0, 1, 0))); + blockSource->setBlock(&pos, newBlock); - } else if (name.find("rail") != std::string::npos) { - auto newState = (variant + 1) % 10; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, air); - blockSource->setBlock(&pos, newBlock); - // blockSource->updateNeighbors(&pos); - } else if ((name.find("log") != std::string::npos && - name.find("stripped") != std::string::npos) || - name.find("basalt") != std::string::npos || - name.find("crimson_stem") != std::string::npos || - name.find("warped_stem") != std::string::npos) { - auto newState = (variant + 1) % 3; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("log") != std::string::npos) { - auto newState = (variant + 4) % 16; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("powered") != std::string::npos || - name.find("anvil") != std::string::npos || - name.find("lectern") != std::string::npos || - name.find("_door") != std::string::npos || - name.find("loom") != std::string::npos) { - auto newState = (variant % 4 + 1) % 4 + (variant / 4) * 4; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, air); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("trapdoor") != std::string::npos) { - auto newState = (variant % 8 + 1) % 8 + (variant / 8) * 8; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, air); - blockSource->setBlock(&pos, newBlock); - } else if (name.find("hopper") != std::string::npos) { - auto newState = (variant % 8 + 1) % 6 + (variant / 8) * 8; - if (newState % 8 == 1) - newState += 1; - auto newBlock = block->getLegacy()->tryGetStateBlock(newState); - blockSource->setBlock(&pos, air); - blockSource->setBlock(&pos, newBlock); + } else if (name.find("rail") != std::string::npos) { + auto newState = (variant + 1) % 10; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, air); + blockSource->setBlock(&pos, newBlock); + // blockSource->updateNeighbors(&pos); + } else if ((name.find("log") != std::string::npos && + name.find("stripped") != std::string::npos) || + name.find("basalt") != std::string::npos || + name.find("crimson_stem") != std::string::npos || + name.find("warped_stem") != std::string::npos) { + auto newState = (variant + 1) % 3; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("log") != std::string::npos) { + auto newState = (variant + 4) % 16; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("powered") != std::string::npos || + name.find("anvil") != std::string::npos || + name.find("lectern") != std::string::npos || + name.find("_door") != std::string::npos || + name.find("loom") != std::string::npos) { + auto newState = (variant % 4 + 1) % 4 + (variant / 4) * 4; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, air); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("trapdoor") != std::string::npos) { + auto newState = (variant % 8 + 1) % 8 + (variant / 8) * 8; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, air); + blockSource->setBlock(&pos, newBlock); + } else if (name.find("hopper") != std::string::npos) { + auto newState = (variant % 8 + 1) % 6 + (variant / 8) * 8; + if (newState % 8 == 1) newState += 1; + auto newBlock = block->getLegacy()->tryGetStateBlock(newState); + blockSource->setBlock(&pos, air); + blockSource->setBlock(&pos, newBlock); + } } -} -} // namespace mod +} // namespace mod diff --git a/mod/function/BlockRotationHelper.h b/mod/function/BlockRotationHelper.h index cd43e1d..41ee88a 100644 --- a/mod/function/BlockRotationHelper.h +++ b/mod/function/BlockRotationHelper.h @@ -5,23 +5,22 @@ #ifndef MOD_BLOCKROTATIONHELPER_H #define MOD_BLOCKROTATIONHELPER_H - -#include "graphics/BlockPos.h" #include "block/BlockSource.h" +#include "graphics/BlockPos.h" #include "tools/noncopyable .h" namespace mod { class BlockRotationHelper : noncopyable { bool enable = true; - public: + public: inline bool inEnable() const { return this->enable; } inline void setAble(bool able) { this->enable = able; } - void rotate(trapdoor::BlockPos &pos, trapdoor::BlockSource *blockSource) const; - + void rotate(trapdoor::BlockPos &pos, + trapdoor::BlockSource *blockSource) const; }; -} +} // namespace mod -#endif //MOD_BLOCKROTATIONHELPER_H +#endif // MOD_BLOCKROTATIONHELPER_H diff --git a/mod/function/FunctionCommands.cpp b/mod/function/FunctionCommands.cpp index 269fd66..696559d 100644 --- a/mod/function/FunctionCommands.cpp +++ b/mod/function/FunctionCommands.cpp @@ -1,27 +1,28 @@ #include "FunctionCommands.h" + #include "commands/ArgHolder.h" #include "commands/CommandNode.h" #include "language/I18nManager.h" #include "tools/Message.h" namespace mod { -//便捷模式切换 -void registerGamemodeSwitchCommand(CommandManager &commandManager) { - using namespace trapdoor; - commandManager.registerCmd("o", "command.o.desc")->EXE({ - player->setGameMode(4); - broadcastMsg(LANG("command.o.set"), player->getNameTag().c_str()); - }); + //便捷模式切换 + void registerGamemodeSwitchCommand(CommandManager &commandManager) { + using namespace trapdoor; + commandManager.registerCmd("o", "command.o.desc")->EXE({ + player->setGameMode(4); + broadcastMsg(LANG("command.o.set"), player->getNameTag().c_str()); + }); - commandManager.registerCmd("s", "command.s.desc")->EXE({ - player->setGameMode(0); - broadcastMsg(LANG("command.s.set"), player->getNameTag().c_str()); - }); + commandManager.registerCmd("s", "command.s.desc")->EXE({ + player->setGameMode(0); + broadcastMsg(LANG("command.s.set"), player->getNameTag().c_str()); + }); - commandManager.registerCmd("c", "command.c.desc")->EXE({ - player->setGameMode(1); - broadcastMsg(LANG("command.c.set"), player->getNameTag().c_str()); - }); -} -} // namespace mod + commandManager.registerCmd("c", "command.c.desc")->EXE({ + player->setGameMode(1); + broadcastMsg(LANG("command.c.set"), player->getNameTag().c_str()); + }); + } +} // namespace mod diff --git a/mod/function/FunctionCommands.h b/mod/function/FunctionCommands.h index 94721bc..d60c91e 100644 --- a/mod/function/FunctionCommands.h +++ b/mod/function/FunctionCommands.h @@ -3,8 +3,8 @@ #include "commands/CommandManager.h" -namespace mod{ - void registerGamemodeSwitchCommand(CommandManager & commandManager); - } +namespace mod { + void registerGamemodeSwitchCommand(CommandManager& commandManager); +} #endif diff --git a/mod/function/HopperCounter.cpp b/mod/function/HopperCounter.cpp index 244886b..d8f33e2 100644 --- a/mod/function/HopperCounter.cpp +++ b/mod/function/HopperCounter.cpp @@ -3,6 +3,7 @@ // #include "HopperCounter.h" + #include "BDSMod.h" #include "TrapdoorMod.h" #include "block/BlockSource.h" @@ -17,97 +18,95 @@ using namespace SymHook; namespace mod { -const size_t HopperChannelManager::TOTAL_CHANNEL_NUM = 16; -const trapdoor::BlockType HopperChannelManager::BLOCK_TYPE = trapdoor::CONCRETE; + const size_t HopperChannelManager::TOTAL_CHANNEL_NUM = 16; + const trapdoor::BlockType HopperChannelManager::BLOCK_TYPE = + trapdoor::CONCRETE; -void HopperChannelManager::tick() { - if (this->enable) { - for (auto &channel : channels) { - channel.tick(); + void HopperChannelManager::tick() { + if (this->enable) { + for (auto &channel : channels) { + channel.tick(); + } } } -} -void HopperChannelManager::printChannel(Actor *player, size_t channel) { - if (channel < 0 || channel > 15) { - error(player, "该频道不存在[0-15]"); - } else { - getChannel(channel).print(player); + void HopperChannelManager::printChannel(Actor *player, size_t channel) { + if (channel < 0 || channel > 15) { + error(player, "该频道不存在[0-15]"); + } else { + getChannel(channel).print(player); + } } -} -void HopperChannelManager::resetChannel(Actor *player, size_t channel) { - if (channel < 0 || channel > 15) { - error(player, "该频道不存在"); - } else { - getChannel(channel).reset(); - trapdoor::broadcastMsg("频道[%zu] 数据已重置", channel); + void HopperChannelManager::resetChannel(Actor *player, size_t channel) { + if (channel < 0 || channel > 15) { + error(player, "该频道不存在"); + } else { + getChannel(channel).reset(); + trapdoor::broadcastMsg("频道[%zu] 数据已重置", channel); + } } -} - -void HopperChannelManager::registerCommand(CommandManager &commandManager) { - commandManager.registerCmd("counter", "command.counter.desc") - ->then(Arg("r", "command.counter.r.desc", ArgType::INT) - ->execute([this](ArgHolder *holder, Actor *player) { - this->resetChannel(player, holder->getInt()); - })) - ->then(Arg("p", "command.counter.p.desc", ArgType::INT) - ->execute([this](ArgHolder *holder, Actor *player) { - this->printChannel(player, holder->getInt()); - })); -} - -void HopperChannelManager::quickPrintData(trapdoor::Actor *player, - trapdoor::BlockPos &pos) { - if (!this->enable) - return; - auto *block = player->getBlockSource()->getBlock(pos); - if (block->getLegacy()->getBlockID() != HopperChannelManager::BLOCK_TYPE) - return; - this->printChannel(player, block->getVariant()); -} - -void CounterChannel::add(const std::string &itemName, size_t num) { - counterList[itemName] += num; -} -void CounterChannel::reset() { - gameTick = 0; - counterList.clear(); -} + void HopperChannelManager::registerCommand(CommandManager &commandManager) { + commandManager.registerCmd("counter", "command.counter.desc") + ->then(Arg("r", "command.counter.r.desc", ArgType::INT) + ->execute([this](ArgHolder *holder, Actor *player) { + this->resetChannel(player, holder->getInt()); + })) + ->then(Arg("p", "command.counter.p.desc", ArgType::INT) + ->execute([this](ArgHolder *holder, Actor *player) { + this->printChannel(player, holder->getInt()); + })); + } -void CounterChannel::print(Actor *actor) { - int n = 0; - for (const auto &i : this->counterList) { - n += i.second; + void HopperChannelManager::quickPrintData(trapdoor::Actor *player, + trapdoor::BlockPos &pos) { + if (!this->enable) return; + auto *block = player->getBlockSource()->getBlock(pos); + if (block->getLegacy()->getBlockID() != + HopperChannelManager::BLOCK_TYPE) + return; + this->printChannel(player, block->getVariant()); } - if (this->gameTick == 0 || n == 0) { - L_DEBUG("tick = %d num = %d", gameTick, n); - info(actor, "no data in this channel"); - return; + void CounterChannel::add(const std::string &itemName, size_t num) { + counterList[itemName] += num; } - std::string stringBuilder; - trapdoor::MessageBuilder builder; - stringBuilder += - trapdoor::format("channel: " C_INT "\ntotal " C_INT " items in " C_INT - " gt(" C_FLOAT "min)\n", - channel, n, gameTick, gameTick / 1200.0); - for (const auto &i : counterList) { - stringBuilder += trapdoor::format("- %s " C_INT "(" C_FLOAT "/hour)\n", - i.first.c_str(), i.second, - i.second * 1.0 / gameTick * 72000); + + void CounterChannel::reset() { + gameTick = 0; + counterList.clear(); } - trapdoor::info(actor, stringBuilder); -} -} // namespace mod -THook( - void, - MSSYM_B1QA7setItemB1AE16HopperBlockActorB2AAE19UEAAXHAEBVItemStackB3AAAA1Z, - trapdoor::BlockActor *hopperActor, unsigned int index, - trapdoor::ItemStackBase *itemStack) { + void CounterChannel::print(Actor *actor) { + int n = 0; + for (const auto &i : this->counterList) { + n += i.second; + } + + if (this->gameTick == 0 || n == 0) { + L_DEBUG("tick = %d num = %d", gameTick, n); + info(actor, "no data in this channel"); + return; + } + std::string stringBuilder; + trapdoor::MessageBuilder builder; + stringBuilder += + trapdoor::format("channel: " C_INT "\ntotal " C_INT + " items in " C_INT " gt(" C_FLOAT "min)\n", + channel, n, gameTick, gameTick / 1200.0); + for (const auto &i : counterList) { + stringBuilder += trapdoor::format( + "- %s " C_INT "(" C_FLOAT "/hour)\n", i.first.c_str(), + i.second, i.second * 1.0 / gameTick * 72000); + } + trapdoor::info(actor, stringBuilder); + } +} // namespace mod +THook(void, HopperBlockActor_setItem_c0e5f3ce, + trapdoor::BlockActor *hopperActor, unsigned int index, + trapdoor::ItemStackBase *itemStack) { //计数器没开启,直接返回 auto modInstance = trapdoor::bdsMod->asInstance(); if (!modInstance->getHopperChannelManager().isEnable()) { diff --git a/mod/function/HopperCounter.h b/mod/function/HopperCounter.h index e8013bd..bebde5d 100644 --- a/mod/function/HopperCounter.h +++ b/mod/function/HopperCounter.h @@ -5,16 +5,16 @@ #ifndef TRAPDOOR_HOPPER_H #define TRAPDOOR_HOPPER_H -#include "lib/mod.h" -#include #include +#include #include -#include "entity/Actor.h" + #include "block/Block.h" +#include "commands/CommandManager.h" +#include "entity/Actor.h" +#include "lib/mod.h" #include "tools/noncopyable .h" #include "trapdoor.h" -#include "commands/CommandManager.h" -#include //漏斗计数器频道 namespace mod { @@ -23,10 +23,10 @@ namespace mod { using BlockPos = trapdoor::BlockPos; class CounterChannel { - const size_t channel; //频道号 - std::map counterList; //数据 - size_t gameTick = 0; //游戏刻 - public: + const size_t channel; //频道号 + std::map counterList; //数据 + size_t gameTick = 0; //游戏刻 + public: explicit CounterChannel(size_t ch) : channel(ch), gameTick(0) {} void reset(); @@ -35,22 +35,20 @@ namespace mod { void add(const std::string &itemName, size_t num); - inline void tick() { - ++gameTick; - } + inline void tick() { ++gameTick; } }; -//漏斗频道管理器 + //漏斗频道管理器 class HopperChannelManager : noncopyable { std::vector channels; bool enable = false; - public: + + public: static const size_t TOTAL_CHANNEL_NUM; static const trapdoor::BlockType BLOCK_TYPE; HopperChannelManager() { - for (int i = 0; i < 16; i++) - channels.emplace_back(i); + for (int i = 0; i < 16; i++) channels.emplace_back(i); } inline CounterChannel &getChannel(const int &ch) { @@ -74,5 +72,5 @@ namespace mod { void quickPrintData(trapdoor::Actor *player, trapdoor::BlockPos &pos); }; -} -#endif //TRAPDOOR_HOPPER_H +} // namespace mod +#endif // TRAPDOOR_HOPPER_H diff --git a/mod/function/SimpleBuilder.cpp b/mod/function/SimpleBuilder.cpp index e76638d..2c0be80 100644 --- a/mod/function/SimpleBuilder.cpp +++ b/mod/function/SimpleBuilder.cpp @@ -13,209 +13,206 @@ namespace mod { -bool SimpleBuilder::preCheck(trapdoor::Actor *player, size_t radius) const { - if (!player) { - return false; - } - if (!this->enable) { - info(player, "builder未开启"); - return false; - } - if (radius > this->maxCircleRadius) { - info(player, "半径过大(必须<= 30000000)"); - return false; - } - return true; -} -void SimpleBuilder::buildCircle(trapdoor::Actor *player, size_t radius, - bool hollow) const { - if (!this->preCheck(player, radius)) { - return; + bool SimpleBuilder::preCheck(trapdoor::Actor *player, size_t radius) const { + if (!player) { + return false; + } + if (!this->enable) { + info(player, "builder未开启"); + return false; + } + if (radius > this->maxCircleRadius) { + info(player, "半径过大(必须<= 30000000)"); + return false; + } + return true; } - trapdoor::BlockPos standPos = player->getStandPosition(); - auto block = - player->getBlockSource()->getBlock(standPos.x, standPos.y, standPos.z); - trapdoor::BlockPos pos = standPos; - // printf("%d %d %d %s", pos.x,pos.y,pos.z, block->getName().c_str()); - float R = radius; - R += 0.5; - int X, Y, p; - X = 0; - Y = R; - p = 3 - 2 * R; - if (!hollow) { - for (; X <= Y; X++) { - for (int Yi = X; Yi <= Y; Yi++) { + void SimpleBuilder::buildCircle(trapdoor::Actor *player, size_t radius, + bool hollow) const { + if (!this->preCheck(player, radius)) { + return; + } + trapdoor::BlockPos standPos = player->getStandPosition(); + auto block = player->getBlockSource()->getBlock(standPos.x, standPos.y, + standPos.z); + trapdoor::BlockPos pos = standPos; + // printf("%d %d %d %s", pos.x,pos.y,pos.z, block->getName().c_str()); + float R = radius; + R += 0.5; + int X, Y, p; + X = 0; + Y = R; + p = 3 - 2 * R; + if (!hollow) { + for (; X <= Y; X++) { + for (int Yi = X; Yi <= Y; Yi++) { + pos.x = standPos.x + X; + pos.z = standPos.z + Yi; + player->getBlockSource()->setBlock(&pos, block); + pos.z = standPos.z - Yi; + player->getBlockSource()->setBlock(&pos, block); + pos.x = standPos.x - X; + player->getBlockSource()->setBlock(&pos, block); + pos.z = standPos.z + Yi; + player->getBlockSource()->setBlock(&pos, block); + pos.x = standPos.x + Yi; + pos.z = standPos.z + X; + player->getBlockSource()->setBlock(&pos, block); + pos.z = standPos.z - X; + player->getBlockSource()->setBlock(&pos, block); + pos.x = standPos.x - Yi; + player->getBlockSource()->setBlock(&pos, block); + pos.z = standPos.z + X; + player->getBlockSource()->setBlock(&pos, block); + } + if (p >= 0) { + p += 4 * (X - Y) + 10; + Y--; + } else { + p += 4 * X + 6; + } + } + } else { + for (; X <= Y; X++) { pos.x = standPos.x + X; - pos.z = standPos.z + Yi; + pos.z = standPos.z + Y; player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z - Yi; + pos.z = standPos.z - Y; player->getBlockSource()->setBlock(&pos, block); pos.x = standPos.x - X; player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z + Yi; + pos.z = standPos.z + Y; player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x + Yi; + pos.x = standPos.x + Y; pos.z = standPos.z + X; player->getBlockSource()->setBlock(&pos, block); pos.z = standPos.z - X; player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x - Yi; + pos.x = standPos.x - Y; player->getBlockSource()->setBlock(&pos, block); pos.z = standPos.z + X; player->getBlockSource()->setBlock(&pos, block); - } - if (p >= 0) { - p += 4 * (X - Y) + 10; - Y--; - } else { - p += 4 * X + 6; - } - } - } else { - for (; X <= Y; X++) { - pos.x = standPos.x + X; - pos.z = standPos.z + Y; - player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z - Y; - player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x - X; - player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z + Y; - player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x + Y; - pos.z = standPos.z + X; - player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z - X; - player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x - Y; - player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z + X; - player->getBlockSource()->setBlock(&pos, block); - if (p >= 0) { - p += 4 * (X - Y) + 10; - Y--; - } else { - p += 4 * X + 6; + if (p >= 0) { + p += 4 * (X - Y) + 10; + Y--; + } else { + p += 4 * X + 6; + } } } } -} -void SimpleBuilder::buildSphere(trapdoor::Actor *player, size_t radius, - bool hollow) const { - if (!this->preCheck(player, radius)) { - return; - } + void SimpleBuilder::buildSphere(trapdoor::Actor *player, size_t radius, + bool hollow) const { + if (!this->preCheck(player, radius)) { + return; + } - trapdoor::BlockPos standPos = player->getStandPosition(); - auto block = - player->getBlockSource()->getBlock(standPos.x, standPos.y, standPos.z); - trapdoor::BlockPos pos = standPos; - float R = radius; - R += 0.5; - int Radius = (int)ceil(radius); - float nextXn = 0; - for (int x = 0; x <= Radius; ++x) { - float xn = nextXn; - nextXn = (x + 1) / R; - float nextYn = 0; - for (int y = 0; y <= Radius; ++y) { - float yn = nextYn; - nextYn = (y + 1) / R; - float nextZn = 0; - for (int z = 0; z <= Radius; ++z) { - float zn = nextZn; - nextZn = (z + 1) / R; - if (xn * xn + yn * yn + zn * zn > 1) - continue; - if (hollow) { - if (nextXn * nextXn + yn * yn + zn * zn <= 1 && - xn * xn + nextYn * nextYn + zn * zn <= 1 && - xn * xn + yn * yn + nextZn * nextZn <= 1) { - continue; + trapdoor::BlockPos standPos = player->getStandPosition(); + auto block = player->getBlockSource()->getBlock(standPos.x, standPos.y, + standPos.z); + trapdoor::BlockPos pos = standPos; + float R = radius; + R += 0.5; + int Radius = (int)ceil(radius); + float nextXn = 0; + for (int x = 0; x <= Radius; ++x) { + float xn = nextXn; + nextXn = (x + 1) / R; + float nextYn = 0; + for (int y = 0; y <= Radius; ++y) { + float yn = nextYn; + nextYn = (y + 1) / R; + float nextZn = 0; + for (int z = 0; z <= Radius; ++z) { + float zn = nextZn; + nextZn = (z + 1) / R; + if (xn * xn + yn * yn + zn * zn > 1) continue; + if (hollow) { + if (nextXn * nextXn + yn * yn + zn * zn <= 1 && + xn * xn + nextYn * nextYn + zn * zn <= 1 && + xn * xn + yn * yn + nextZn * nextZn <= 1) { + continue; + } } + pos.x = standPos.x + x; + pos.y = standPos.y + y; + pos.z = standPos.z + z; + player->getBlockSource()->setBlock(&pos, block); + pos.y = standPos.y - y; + player->getBlockSource()->setBlock(&pos, block); + pos.z = standPos.z - z; + player->getBlockSource()->setBlock(&pos, block); + pos.x = standPos.x - x; + player->getBlockSource()->setBlock(&pos, block); + pos.y = standPos.y + y; + player->getBlockSource()->setBlock(&pos, block); + pos.x = standPos.x + x; + player->getBlockSource()->setBlock(&pos, block); + pos.x = standPos.x - x; + pos.z = standPos.z + z; + player->getBlockSource()->setBlock(&pos, block); + pos.y = standPos.y - y; + player->getBlockSource()->setBlock(&pos, block); } - pos.x = standPos.x + x; - pos.y = standPos.y + y; - pos.z = standPos.z + z; - player->getBlockSource()->setBlock(&pos, block); - pos.y = standPos.y - y; - player->getBlockSource()->setBlock(&pos, block); - pos.z = standPos.z - z; - player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x - x; - player->getBlockSource()->setBlock(&pos, block); - pos.y = standPos.y + y; - player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x + x; - player->getBlockSource()->setBlock(&pos, block); - pos.x = standPos.x - x; - pos.z = standPos.z + z; - player->getBlockSource()->setBlock(&pos, block); - pos.y = standPos.y - y; - player->getBlockSource()->setBlock(&pos, block); } } } -} -void SimpleBuilder::chunksFill(trapdoor::Actor *player, size_t size, - bool hollow) const { - if (!this->preCheck(player, size)) { - return; - } + void SimpleBuilder::chunksFill(trapdoor::Actor *player, size_t size, + bool hollow) const { + if (!this->preCheck(player, size)) { + return; + } - auto standPos = player->getStandPosition(); - auto block = - player->getBlockSource()->getBlock(standPos.x, standPos.y, standPos.z); - auto chunkPos = standPos.toChunkPos(); - auto cx = chunkPos.x * 16; - auto cz = chunkPos.z * 16; - for (auto i = 0; i < 16; i++) { - for (auto j = 0; j < 16; j++) { - trapdoor::BlockPos p = {cx + i, standPos.y, cz + j}; - player->getBlockSource()->setBlock(&p, block); + auto standPos = player->getStandPosition(); + auto block = player->getBlockSource()->getBlock(standPos.x, standPos.y, + standPos.z); + auto chunkPos = standPos.toChunkPos(); + auto cx = chunkPos.x * 16; + auto cz = chunkPos.z * 16; + for (auto i = 0; i < 16; i++) { + for (auto j = 0; j < 16; j++) { + trapdoor::BlockPos p = {cx + i, standPos.y, cz + j}; + player->getBlockSource()->setBlock(&p, block); + } } } -} -void SimpleBuilder::registerDrawCommand(CommandManager &commandManager) { - using namespace trapdoor; - commandManager.registerCmd("draw", "command.draw.desc") - ->then(ARG("ci", "command.draw.ci.desc", INT, - { - auto radius = holder->getInt(); - bool hollow = holder->getInt() < 0; - if (radius < 0) - radius = -radius; - buildCircle(player, radius, hollow); - })) - ->then(ARG("sp", "command.draw.sp.desc", INT, - { - auto radius = holder->getInt(); - bool hollow = holder->getInt() < 0; - if (radius < 0) - radius = -radius; - buildSphere(player, radius, hollow); - })) - ->then(ARG("ch", "command.draw.ch.desc", NONE, - { - // auto radius = holder->getInt(); - // bool hollow = holder->getInt() < 0; - // if (radius < 0) - // radius = -radius; - chunksFill(player, 0, false); - })) - ->then(ARG("mr", "command.draw.mr.desc", INT, { - auto radius = holder->getInt(); - if (radius < 0) { - error(player, "参数不合法(必须>=1)"); - } else { - info(player, "已设置最大半径为%d", radius); - setMaxRadius(radius); - } - })); -} + void SimpleBuilder::registerDrawCommand(CommandManager &commandManager) { + using namespace trapdoor; + commandManager.registerCmd("draw", "command.draw.desc") + ->then(ARG("ci", "command.draw.ci.desc", INT, + { + auto radius = holder->getInt(); + bool hollow = holder->getInt() < 0; + if (radius < 0) radius = -radius; + buildCircle(player, radius, hollow); + })) + ->then(ARG("sp", "command.draw.sp.desc", INT, + { + auto radius = holder->getInt(); + bool hollow = holder->getInt() < 0; + if (radius < 0) radius = -radius; + buildSphere(player, radius, hollow); + })) + ->then(ARG("ch", "command.draw.ch.desc", NONE, + { + // auto radius = holder->getInt(); + // bool hollow = holder->getInt() < 0; + // if (radius < 0) + // radius = -radius; + chunksFill(player, 0, false); + })) + ->then(ARG("mr", "command.draw.mr.desc", INT, { + auto radius = holder->getInt(); + if (radius < 0) { + error(player, "参数不合法(必须>=1)"); + } else { + info(player, "已设置最大半径为%d", radius); + setMaxRadius(radius); + } + })); + } -} // namespace mod +} // namespace mod diff --git a/mod/function/SimpleBuilder.h b/mod/function/SimpleBuilder.h index 9aa8ee1..442a4b2 100644 --- a/mod/function/SimpleBuilder.h +++ b/mod/function/SimpleBuilder.h @@ -11,26 +11,29 @@ #include "trapdoor.h" namespace mod { -class SimpleBuilder : noncopyable { - size_t maxCircleRadius = 30000000; - bool enable = false; + class SimpleBuilder : noncopyable { + size_t maxCircleRadius = 30000000; + bool enable = false; - bool preCheck(trapdoor::Actor *player, size_t radius) const; + bool preCheck(trapdoor::Actor *player, size_t radius) const; - public: - inline void setAble(bool able) { this->enable = able; } + public: + inline void setAble(bool able) { this->enable = able; } - inline void setMaxRadius(int radius) { this->maxCircleRadius = radius; } + inline void setMaxRadius(int radius) { this->maxCircleRadius = radius; } - void buildSphere(trapdoor::Actor *player, size_t size, bool hollow) const; + void buildSphere(trapdoor::Actor *player, size_t size, + bool hollow) const; - void buildCircle(trapdoor::Actor *player, size_t size, bool hollow) const; + void buildCircle(trapdoor::Actor *player, size_t size, + bool hollow) const; - //按照区块进行fill - void chunksFill(trapdoor::Actor *player, size_t size, bool hollow) const; + //按照区块进行fill + void chunksFill(trapdoor::Actor *player, size_t size, + bool hollow) const; - void registerDrawCommand(trapdoor::CommandManager &commandManager); -}; + void registerDrawCommand(trapdoor::CommandManager &commandManager); + }; } // namespace mod #endif // MOD_SIMPLEBUILDER_H diff --git a/mod/function/SingleFunctions.cpp b/mod/function/SingleFunctions.cpp index 161f1bf..40a7151 100644 --- a/mod/function/SingleFunctions.cpp +++ b/mod/function/SingleFunctions.cpp @@ -8,13 +8,14 @@ #include "lib/mod.h" namespace mod { -using namespace SymHook; + using namespace SymHook; -THook(void, MSSYM_B1QA7explodeB1AA9ExplosionB2AAA7QEAAXXZ, void *exp) { - auto modInstance = trapdoor::bdsMod->asInstance(); - if (!modInstance->getSingFunction().preventExplosion) - original(exp); -} + THook(void, + Explosion_explode_5adcea90, void *exp) { + auto modInstance = trapdoor::bdsMod->asInstance(); + if (!modInstance->getSingFunction().preventExplosion) + original(exp); + } /** * SYM_CALL( @@ -24,12 +25,12 @@ THook(void, MSSYM_B1QA7explodeB1AA9ExplosionB2AAA7QEAAXXZ, void *exp) { ); */ -THook( - void, - MSSYM_B1QE17updateNeighborsAtB1AE11BlockSourceB2AAE17QEAAXAEBVBlockPosB3AAAA1Z, - trapdoor::BlockSource *source, trapdoor::BlockPos *pos) { - auto modInstance = trapdoor::bdsMod->asInstance(); - if (!modInstance->getSingFunction().preventNCUpdate) - original(source, pos); -} + THook( + void, + BlockSource_updateNeighborsAt_4c3f8cf7, + trapdoor::BlockSource *source, trapdoor::BlockPos *pos) { + auto modInstance = trapdoor::bdsMod->asInstance(); + if (!modInstance->getSingFunction().preventNCUpdate) + original(source, pos); + } } // namespace mod \ No newline at end of file diff --git a/mod/os/process_stat.cpp b/mod/os/process_stat.cpp index 393a2ce..def6df5 100644 --- a/mod/os/process_stat.cpp +++ b/mod/os/process_stat.cpp @@ -1,9 +1,11 @@ #define _WINSOCKAPI_ -#include +#include "process_stat.h" + #include +#include + #include -#include "process_stat.h" #include #include @@ -16,17 +18,15 @@ static uint64_t file_time_2_utc(const FILETIME *ftime) { return li.QuadPart; } - /// 获得CPU的核数 static int get_processor_number() { SYSTEM_INFO info; GetSystemInfo(&info); - return (int) info.dwNumberOfProcessors; + return (int)info.dwNumberOfProcessors; } - int get_cpu_usage() { - //cpu数量 + // cpu数量 static int processor_count_ = -1; //上一次的时间 static int64_t last_time_ = 0; @@ -53,9 +53,9 @@ int get_cpu_usage() { return -1; } - system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time)) - / - processor_count_; + system_time = + (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time)) / + processor_count_; time = file_time_2_utc(&now); if ((last_system_time_ == 0) || (last_time_ == 0)) { @@ -74,13 +74,12 @@ int get_cpu_usage() { } // We add time_delta / 2 so the result is rounded. - cpu = (int) ((system_time_delta * 100 + time_delta / 2) / time_delta); + cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta); last_system_time_ = system_time; last_time_ = time; return cpu; } - int get_memory_usage(uint64_t *mem, uint64_t *vmem) { PROCESS_MEMORY_COUNTERS pmc; if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) { @@ -91,7 +90,6 @@ int get_memory_usage(uint64_t *mem, uint64_t *vmem) { return -1; } - int get_io_bytes(uint64_t *read_bytes, uint64_t *write_bytes) { IO_COUNTERS io_counter; if (GetProcessIoCounters(GetCurrentProcess(), &io_counter)) { diff --git a/mod/os/process_stat.h b/mod/os/process_stat.h index e8abbfc..07ff276 100644 --- a/mod/os/process_stat.h +++ b/mod/os/process_stat.h @@ -1,7 +1,6 @@ #ifndef PROCESS_STAT_H #define PROCESS_STAT_H - #ifdef __cplusplus extern "C" { #endif @@ -9,19 +8,15 @@ extern "C" { typedef long long int64_t; typedef unsigned long long uint64_t; - /// 获取当前进程的cpu使用率,返回-1失败 int get_cpu_usage(); /// 获取当前进程内存和虚拟内存使用量,返回-1失败,0成功 int get_memory_usage(uint64_t *mem, uint64_t *vmem); - /// 获取当前进程总共读和写的IO字节数,返回-1失败,0成功 int get_io_bytes(uint64_t *read_bytes, uint64_t *write_bytes); - -#ifdef __cplusplus +#ifdef __cplusplus } #endif #endif - diff --git a/mod/player/Player.cpp b/mod/player/Player.cpp deleted file mode 100644 index 5a25f1a..0000000 --- a/mod/player/Player.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// -// Created by xhy on 2020/8/29. -// - - - -#include -#include "entity/Actor.h" -#include "graphics/BlockPos.h" -#include "lib/mod.h" -#include "lib/SymHook.h" -#include "block/Block.h" -#include "BDSMod.h" -#include "TrapdoorMod.h" -#include "PlayerStatisticManager.h" -#include "Player.h" -#include "lib/Remotery.h" -//player place block -using namespace SymHook; -// -//THook( -// int64_t, -// MSSYM_B1QE21onBlockPlacedByPlayerB1AE34VanillaServerGameplayEventListenerB2AAA4UEAAB1QE14AW4EventResultB2AAE10AEAVPlayerB2AAA9AEBVBlockB2AAE12AEBVBlockPosB3AAUA1NB1AA1Z, -// void *self, -// trapdoor::Actor *player, -// trapdoor::Block &block, -// const trapdoor::BlockPos &pos, -// bool flag -//) { -// auto modInstance = trapdoor::bdsMod->asInstance(); -// rmt_ScopedCPUSample(DESTORY_BLOCK, 0); -// if (modInstance->getPlayerStatisticManager().isEnable()) { -// modInstance->getPlayerStatisticManager().insetPlayerAction(player->getNameTag(), pos, -// mod::PlayerStatisticManager::PLACE_BLOCK, -// player->getDimensionID(), -// block.getName()); -// } -// -// return original(self, player, block, pos, flag); -//} -////player destroy block -// -//THook( -// void, -// MSSYM_B2QUE20destroyBlockInternalB1AA8GameModeB2AAA4AEAAB1UE13NAEBVBlockPosB2AAA1EB1AA1Z, -// uint64_t *self, -// const trapdoor::BlockPos *pos, -// int64_t a3, -// int a4 -//) { -// -// rmt_ScopedCPUSample(DESTORY_BLOCK, 0); -// auto modInstance = trapdoor::bdsMod->asInstance(); -// if (modInstance->getPlayerStatisticManager().isEnable()) { -// rmt_ScopedCPUSample(INSERT_SQL, 0); -// uint64_t *ptr = self + 1; -// auto player = reinterpret_cast(*ptr); -// -// auto block = player->getBlockSource()->getBlock(pos->x, pos->y, pos->z); -// modInstance->getPlayerStatisticManager().insetPlayerAction(player->getNameTag(), *pos, -// mod::PlayerStatisticManager::DESTROY_BLOCK, -// player->getDimensionID(), -// block->getName()); -// } -// -// original(self, pos, a3, a4); -//} -// -// diff --git a/mod/player/Player.h b/mod/player/Player.h deleted file mode 100644 index bbdaa91..0000000 --- a/mod/player/Player.h +++ /dev/null @@ -1,8 +0,0 @@ -// -// Created by xhy on 2020/8/29. -// - -#ifndef TRAPDOOR_PLAYER_H -#define TRAPDOOR_PLAYER_H - -#endif //TRAPDOOR_PLAYER_H diff --git a/mod/player/PlayerFunction.cpp b/mod/player/PlayerFunction.cpp index e33505a..0e33cc5 100644 --- a/mod/player/PlayerFunction.cpp +++ b/mod/player/PlayerFunction.cpp @@ -1,37 +1,37 @@ // // Created by xhy on 2021/1/3. // -#include "entity/Actor.h" -#include "graphics/Graphics.h" #include "PlayerFunction.h" + #include "BDSMod.h" #include "TrapdoorMod.h" +#include "entity/Actor.h" #include "graphics/BlockPos.h" +#include "graphics/Graphics.h" #include "graphics/Particle.h" +#include "language/I18nManager.h" +#include "lib/Remotery.h" #include "tools/Message.h" #include "tools/MsgBuilder.h" #include "world/Biome.h" -#include "block/CircuitComponent.h" #include "world/Dimension.h" -#include "lib/Remotery.h" -#include "language/I18nManager.h" namespace mod { void PlayerFunction::tick() { rmt_ScopedCPUSample(PLAYER_FUNC, 0); if (gameTick % 20 == 0) { auto modInstance = trapdoor::bdsMod->asInstance(); - modInstance->getLevel()->forEachPlayer([&](trapdoor::Actor *player) { - if (this->enableShowChunk[player->getNameTag()]) { - drawChunkBound(player); - } - //add other functions here - }); + modInstance->getLevel()->forEachPlayer( + [&](trapdoor::Actor *player) { + if (this->enableShowChunk[player->getNameTag()]) { + drawChunkBound(player); + } + // add other functions here + }); } this->gameTick = (this->gameTick + 1) % 40; } - void PlayerFunction::drawChunkBound(trapdoor::Actor *player) { int dimensionID = player->getDimensionID(); auto playerPos = player->getPos()->toBlockPos(); @@ -53,90 +53,104 @@ namespace mod { auto modInstance = trapdoor::bdsMod->asInstance(); - std::string xyz = format("XYZ: %.2f / %.2f / %.2f\n", position->x, position->y, position->z); - std::string block = format("Block: %d %d %d\n", playerBlockPos.x, playerBlockPos.y, playerBlockPos.z); - std::string chunk = "Chunk: " + inChunkOffset.toString() + " in " + chunkPos.toString() + "\n"; + std::string xyz = format("XYZ: %.2f / %.2f / %.2f\n", position->x, + position->y, position->z); + std::string block = format("Block: %d %d %d\n", playerBlockPos.x, + playerBlockPos.y, playerBlockPos.z); + std::string chunk = "Chunk: " + inChunkOffset.toString() + " in " + + chunkPos.toString() + "\n"; std::string facing = "Facing: " + viewVec.toDirString(); - facing += format("(%.2f / %.2f / %.2f)\n", viewVec.x, viewVec.y, viewVec.z); - std::string biomeString = format("Biome: minecraft:%s (%d)\n", name.c_str(), biome->getBiomeType()); - std::string dimString = format("Dimension: %s (%d)\n", player->getDimensionName().c_str(), - player->getDimensionID()); - builder.textF("Minecraft BDS %s \n", TrapdoorMod::getModVersion().c_str()) - .text(xyz) - .text(block); + facing += + format("(%.2f / %.2f / %.2f)\n", viewVec.x, viewVec.y, viewVec.z); + std::string biomeString = format("Biome: minecraft:%s (%d)\n", + name.c_str(), biome->getBiomeType()); + std::string dimString = + format("Dimension: %s (%d)\n", player->getDimensionName().c_str(), + player->getDimensionID()); + builder + .textF("Minecraft BDS %s \n", TrapdoorMod::getModVersion().c_str()) + .text(xyz) + .text(block); if (inSlimeChunk) { builder.sText(chunk, MSG_COLOR::GREEN); } else { builder.text(chunk); } - builder.text(facing).text(biomeString).text(dimString) - .send(player); + builder.text(facing).text(biomeString).text(dimString).send(player); } - void PlayerFunction::printRedstoneInfo(trapdoor::Actor *player, BlockPos &pos) { - if (!this->enableRedstoneHelper[player->getNameTag()])return; - auto graph = player->getDimension()->getGraph(); - auto component = graph->getBaseCircuitComponent(&pos); - if (!component) { - trapdoor::warning(player, "self.rs.error"); - return; - } - component->basePrint(graph, player); + void PlayerFunction::printRedstoneInfo(trapdoor::Actor *player, + BlockPos &pos) { + // if (!this->enableRedstoneHelper[player->getNameTag()])return; + // auto graph = player->getDimension()->getGraph(); + // auto component = graph->getBaseCircuitComponent(&pos); + // if (!component) { + // trapdoor::warning(player, "self.rs.error"); + // return; + // } + // component->basePrint(graph, player); } - void PlayerFunction::broadcastSimpleInfo(trapdoor::Actor *player) { auto pos = player->getPos()->toBlockPos(); - auto dim = (DimensionType) player->getDimensionID(); + auto dim = (DimensionType)player->getDimensionID(); trapdoor::MessageBuilder builder; int nX = 0, nZ = 0; builder.text(player->getNameTag()).text(" @ "); switch (dim) { case OverWorld: - builder.sText(trapdoor::LANG("dimension.overworld"), MSG_COLOR::GREEN); + builder.sText(trapdoor::LANG("dimension.overworld"), + MSG_COLOR::GREEN); nX = pos.x / 8, nZ = pos.z / 8; break; case Nether: - builder.sText(trapdoor::LANG("dimension.nether"), MSG_COLOR::RED); + builder.sText(trapdoor::LANG("dimension.nether"), + MSG_COLOR::RED); nX = pos.x * 8, nZ = pos.z * 8; break; case TheEnd: - builder.sText(trapdoor::LANG("dimension.end"), MSG_COLOR::YELLOW); + builder.sText(trapdoor::LANG("dimension.end"), + MSG_COLOR::YELLOW); break; } builder.sTextF(MSG_COLOR::AQUA, " [%d %d %d] ", pos.x, pos.y, pos.z); if (dim == OverWorld) { - builder.text("==> ").sText(trapdoor::LANG("dimension.nether"), MSG_COLOR::RED).sTextF(MSG_COLOR::AQUA, " [%d %d]", nX, nZ); + builder.text("==> ") + .sText(trapdoor::LANG("dimension.nether"), MSG_COLOR::RED) + .sTextF(MSG_COLOR::AQUA, " [%d %d]", nX, nZ); } if (dim == Nether) { - builder.text("==> ").sText(trapdoor::LANG("dimension.overworld"), MSG_COLOR::GREEN).sTextF(MSG_COLOR::AQUA, " [%d %d]", nX, nZ); + builder.text("==> ") + .sText(trapdoor::LANG("dimension.overworld"), MSG_COLOR::GREEN) + .sTextF(MSG_COLOR::AQUA, " [%d %d]", nX, nZ); } builder.broadcast(); } void PlayerFunction::listAllPlayers(trapdoor::Actor *player) { trapdoor::MessageBuilder builder; - trapdoor::bdsMod->getLevel()->forEachPlayer([&](trapdoor::Actor *actor) { - auto pos = actor->getPos()->toBlockPos(); - builder.textF("%s @ %s => [%d %d %d]\n", actor->getNameTag().c_str(), actor->getDimensionName().c_str(), - pos.x, - pos.y, - pos.z - ); - }); + trapdoor::bdsMod->getLevel()->forEachPlayer( + [&](trapdoor::Actor *actor) { + auto pos = actor->getPos()->toBlockPos(); + builder.textF( + "%s @ %s => [%d %d %d]\n", actor->getNameTag().c_str(), + actor->getDimensionName().c_str(), pos.x, pos.y, pos.z); + }); builder.send(player); } - void MeasureData::setPosition2(const BlockPos &pos, trapdoor::Actor *player) { - if (!this->enableMeasure)return; + void MeasureData::setPosition2(const BlockPos &pos, + trapdoor::Actor *player) { + if (!this->enableMeasure) return; this->pos2 = pos; this->hasSetPos2 = true; this->trySendDistanceInfo(player); } - void MeasureData::setPosition1(const BlockPos &pos, trapdoor::Actor *player) { - if (!this->enableMeasure)return; + void MeasureData::setPosition1(const BlockPos &pos, + trapdoor::Actor *player) { + if (!this->enableMeasure) return; this->pos1 = pos; this->hasSetPos1 = true; this->trySendDistanceInfo(player); @@ -150,17 +164,25 @@ namespace mod { builder.text("set p2 ").pos(this->pos2).send(player); } else if (hasSetPos1 && hasSetPos2) { float distance = pos1.distanceTo(pos2); - int distance2 = abs(pos1.x - pos2.x) + abs(pos1.y - pos2.y) + abs(pos1.z - pos2.z); + int distance2 = abs(pos1.x - pos2.x) + abs(pos1.y - pos2.y) + + abs(pos1.z - pos2.z); trapdoor::BlockPos pos = {pos1.x, pos2.y, pos1.z}; float distance3 = pos.distanceTo(pos2); int distance4 = abs(pos1.x - pos2.x) + abs(pos1.z - pos2.z); - builder.pos(pos1).text(" -").pos(pos2).text("\n - ") - .num(distance).text(" ").num(distance2).text("\n - ") - .num(distance3).text(" ").num(distance4).send(player); + builder.pos(pos1) + .text(" -") + .pos(pos2) + .text("\n - ") + .num(distance) + .text(" ") + .num(distance2) + .text("\n - ") + .num(distance3) + .text(" ") + .num(distance4) + .send(player); } } - -} - +} // namespace mod diff --git a/mod/player/PlayerFunction.h b/mod/player/PlayerFunction.h index 85290ac..e98800b 100644 --- a/mod/player/PlayerFunction.h +++ b/mod/player/PlayerFunction.h @@ -7,11 +7,11 @@ #include #include + +#include "block/BlockSource.h" #include "entity/Actor.h" -#include "tools/noncopyable .h" #include "graphics/BlockPos.h" -#include "block/BlockSource.h" -#include "block/CircuitComponent.h" +#include "tools/noncopyable .h" #include "world/Dimension.h" //#include "dirtyLitematica/SelectRegion.h" @@ -23,9 +23,11 @@ namespace mod { trapdoor::BlockPos pos2; bool hasSetPos2 = false; - void setPosition1(const trapdoor::BlockPos &pos, trapdoor::Actor *player); + void setPosition1(const trapdoor::BlockPos &pos, + trapdoor::Actor *player); - void setPosition2(const trapdoor::BlockPos &pos, trapdoor::Actor *player); + void setPosition2(const trapdoor::BlockPos &pos, + trapdoor::Actor *player); void trySendDistanceInfo(trapdoor::Actor *player) const; }; @@ -38,13 +40,19 @@ namespace mod { static void drawChunkBound(trapdoor::Actor *player); - public: - inline void setShowChunkAble(const std::string &playerName, bool able) { enableShowChunk[playerName] = able; } + public: + inline void setShowChunkAble(const std::string &playerName, bool able) { + enableShowChunk[playerName] = able; + } - inline void - setRedstoneHelperAble(const std::string &playerName, bool able) { enableRedstoneHelper[playerName] = able; } + inline void setRedstoneHelperAble(const std::string &playerName, + bool able) { + enableRedstoneHelper[playerName] = able; + } - MeasureData &getMeasureData(const std::string &playerName) { return playerMeasureData[playerName]; } + MeasureData &getMeasureData(const std::string &playerName) { + return playerMeasureData[playerName]; + } void tick(); @@ -52,14 +60,12 @@ namespace mod { static void broadcastSimpleInfo(trapdoor::Actor *player); - void printRedstoneInfo(trapdoor::Actor *player, trapdoor::BlockPos &pos); + void printRedstoneInfo(trapdoor::Actor *player, + trapdoor::BlockPos &pos); static void listAllPlayers(trapdoor::Actor *player); - }; +} // namespace mod -} - - -#endif //MOD_PLAYERFUNCTION_H +#endif // MOD_PLAYERFUNCTION_H diff --git a/mod/spawn/HsaManager.cpp b/mod/spawn/HsaManager.cpp index c97e971..5918e1d 100644 --- a/mod/spawn/HsaManager.cpp +++ b/mod/spawn/HsaManager.cpp @@ -3,6 +3,9 @@ // #include "HsaManager.h" + +#include + #include "BDSMod.h" #include "Particle.h" #include "TrapdoorMod.h" @@ -18,147 +21,142 @@ #include "tools/MsgBuilder.h" #include "world/Biome.h" #include "world/Level.h" -#include namespace mod { -bool HsaInfo::operator<(const mod::HsaInfo &rhs) const { - return boundingBox < rhs.boundingBox; -} - -trapdoor::BlockPos HsaManager::findB(trapdoor::Actor *player) { - trapdoor::BoundingBox hsaBoundingBox; - auto firsthsa = *((this->hsaList).begin()); - hsaBoundingBox.minPos = firsthsa.boundingBox.minPos; - hsaBoundingBox.maxPos = firsthsa.boundingBox.maxPos; - for (const auto &hsa : this->hsaList) { - hsaBoundingBox.minPos.x = - min(hsaBoundingBox.minPos.x, hsa.boundingBox.minPos.x); - hsaBoundingBox.minPos.y = - min(hsaBoundingBox.minPos.y, hsa.boundingBox.minPos.y); - hsaBoundingBox.minPos.z = - min(hsaBoundingBox.minPos.z, hsa.boundingBox.minPos.z); - hsaBoundingBox.maxPos.x = - max(hsaBoundingBox.maxPos.x, hsa.boundingBox.maxPos.x); - hsaBoundingBox.maxPos.y = - max(hsaBoundingBox.maxPos.y, hsa.boundingBox.maxPos.y); - hsaBoundingBox.maxPos.z = - max(hsaBoundingBox.maxPos.z, hsa.boundingBox.maxPos.z); + bool HsaInfo::operator<(const mod::HsaInfo &rhs) const { + return boundingBox < rhs.boundingBox; } - info(player, "%s %s", hsaBoundingBox.minPos.toString().c_str(), - hsaBoundingBox.maxPos.toString().c_str()); - info(player, "%d", firsthsa.dimensionID); - int points = 0, maxPoints = 0; - trapdoor::BlockPos pos; - for (int x = hsaBoundingBox.minPos.x - 44; - x <= hsaBoundingBox.maxPos.x + 44; x++) - for (int y = max(hsaBoundingBox.minPos.y - 44, 0); - y <= min(hsaBoundingBox.maxPos.y + 44, - 127 + firsthsa.dimensionID == 1 ? 0 : 128); - y++) - for (int z = hsaBoundingBox.minPos.z - 44; - z <= hsaBoundingBox.maxPos.z + 44; z++) { - points = 0; - for (const auto &hsa : this->hsaList) { - float dis = - hsa.boundingBox.getSpawnArea().getCenter().distanceTo( - {x, y, z}); - if (dis >= 24.0 && dis <= 44.0) { - points += 1; + + trapdoor::BlockPos HsaManager::findB(trapdoor::Actor *player) { + trapdoor::BoundingBox hsaBoundingBox; + auto firsthsa = *((this->hsaList).begin()); + hsaBoundingBox.minPos = firsthsa.boundingBox.minPos; + hsaBoundingBox.maxPos = firsthsa.boundingBox.maxPos; + for (const auto &hsa : this->hsaList) { + hsaBoundingBox.minPos.x = + min(hsaBoundingBox.minPos.x, hsa.boundingBox.minPos.x); + hsaBoundingBox.minPos.y = + min(hsaBoundingBox.minPos.y, hsa.boundingBox.minPos.y); + hsaBoundingBox.minPos.z = + min(hsaBoundingBox.minPos.z, hsa.boundingBox.minPos.z); + hsaBoundingBox.maxPos.x = + max(hsaBoundingBox.maxPos.x, hsa.boundingBox.maxPos.x); + hsaBoundingBox.maxPos.y = + max(hsaBoundingBox.maxPos.y, hsa.boundingBox.maxPos.y); + hsaBoundingBox.maxPos.z = + max(hsaBoundingBox.maxPos.z, hsa.boundingBox.maxPos.z); + } + info(player, "%s %s", hsaBoundingBox.minPos.toString().c_str(), + hsaBoundingBox.maxPos.toString().c_str()); + info(player, "%d", firsthsa.dimensionID); + int points = 0, maxPoints = 0; + trapdoor::BlockPos pos; + for (int x = hsaBoundingBox.minPos.x - 44; + x <= hsaBoundingBox.maxPos.x + 44; x++) + for (int y = max(hsaBoundingBox.minPos.y - 44, 0); + y <= min(hsaBoundingBox.maxPos.y + 44, + 127 + firsthsa.dimensionID == 1 ? 0 : 128); + y++) + for (int z = hsaBoundingBox.minPos.z - 44; + z <= hsaBoundingBox.maxPos.z + 44; z++) { + points = 0; + for (const auto &hsa : this->hsaList) { + float dis = hsa.boundingBox.getSpawnArea() + .getCenter() + .distanceTo({x, y, z}); + if (dis >= 24.0 && dis <= 44.0) { + points += 1; + } + } + if (points > maxPoints) { + maxPoints = points; + pos = trapdoor::BlockPos(x, y, z); } } - if (points > maxPoints) { - maxPoints = points; - pos = trapdoor::BlockPos(x, y, z); - } - } - broadcastMsg("N=%d", maxPoints); - return pos; -} - -void HsaManager::draw(trapdoor::Actor *player) { - trapdoor::BlockPos standPos = player->getStandPosition(); - auto block = - player->getBlockSource()->getBlock(standPos.x, standPos.y, standPos.z); - for (const auto &hsa : this->hsaList) { - trapdoor::BlockPos pos = - hsa.boundingBox.getSpawnArea().getCenter().toBlockPos(); - player->getBlockSource()->setBlock(&pos, block); + broadcastMsg("N=%d", maxPoints); + return pos; } -} - -void HsaManager::tick() { - rmt_ScopedCPUSample(HSA_TICK, 0); - if (!this->enable) - return; - if (gameTick % 40 == 0) { - trapdoor::GRAPHIC_COLOR color = trapdoor::GRAPHIC_COLOR::WHITE; + + void HsaManager::draw(trapdoor::Actor *player) { + trapdoor::BlockPos standPos = player->getStandPosition(); + auto block = player->getBlockSource()->getBlock(standPos.x, standPos.y, + standPos.z); for (const auto &hsa : this->hsaList) { - switch (hsa.type) { - case PillagerOutpost: - color = trapdoor::GRAPHIC_COLOR::YELLOW; - break; - case SwampHut: - color = trapdoor::GRAPHIC_COLOR::GREEN; - break; - case NetherFortress: - color = trapdoor::GRAPHIC_COLOR::RED; - break; - case OceanMonument: - color = trapdoor::GRAPHIC_COLOR::BLUE; - break; - default: - break; + trapdoor::BlockPos pos = + hsa.boundingBox.getSpawnArea().getCenter().toBlockPos(); + player->getBlockSource()->setBlock(&pos, block); + } + } + + void HsaManager::tick() { + rmt_ScopedCPUSample(HSA_TICK, 0); + if (!this->enable) return; + if (gameTick % 40 == 0) { + trapdoor::GRAPHIC_COLOR color = trapdoor::GRAPHIC_COLOR::WHITE; + for (const auto &hsa : this->hsaList) { + switch (hsa.type) { + case PillagerOutpost: + color = trapdoor::GRAPHIC_COLOR::YELLOW; + break; + case SwampHut: + color = trapdoor::GRAPHIC_COLOR::GREEN; + break; + case NetherFortress: + color = trapdoor::GRAPHIC_COLOR::RED; + break; + case OceanMonument: + color = trapdoor::GRAPHIC_COLOR::BLUE; + break; + default: + break; + } + trapdoor::spawnRectangleParticle(hsa.boundingBox.getSpawnArea(), + color, hsa.dimensionID); } - trapdoor::spawnRectangleParticle(hsa.boundingBox.getSpawnArea(), - color, hsa.dimensionID); } + this->gameTick = (this->gameTick + 1) % 80; + } + + bool HsaManager::findHsa(const HsaInfo &hsaInfo) { + return this->hsaList.find(hsaInfo) != this->hsaList.end(); } - this->gameTick = (this->gameTick + 1) % 80; -} - -bool HsaManager::findHsa(const HsaInfo &hsaInfo) { - return this->hsaList.find(hsaInfo) != this->hsaList.end(); -} - -void HsaManager::list(Actor *player) { - // todo - info(player, "developing"); -} - -void HsaManager::registerCommand(trapdoor::CommandManager &commandManager) { - commandManager.registerCmd("hsa", "command.hsa.desc") - ->then(ARG("clear", "command.hsa.clear.desc", NONE, - { - auto num = this->clear(); - broadcastMsg("一共 %d 个hsa区域被清空", num); - })) - ->then( - ARG("list", "command.hsa.list.desc", NONE, { this->list(player); })) - ->then(ARG("show", "command.hsa.show.desc", BOOL, - { - this->setAble(holder->getBool()); - info(player, "设置HSA显示为 %d", holder->getBool()); - })) - ->then(ARG("find", "command.hsa.find.desc", NONE, - { - broadcastMsg("find %s", - this->findB(player).toString().c_str()); - })) - ->then(ARG("draw", "command.hsa.draw.desc", NONE, - { this->draw(player); })); -} - -} // namespace mod + + void HsaManager::list(Actor *player) { + // todo + info(player, "developing"); + } + + void HsaManager::registerCommand(trapdoor::CommandManager &commandManager) { + commandManager.registerCmd("hsa", "command.hsa.desc") + ->then(ARG("clear", "command.hsa.clear.desc", NONE, + { + auto num = this->clear(); + broadcastMsg("一共 %d 个hsa区域被清空", num); + })) + ->then(ARG("list", "command.hsa.list.desc", NONE, + { this->list(player); })) + ->then(ARG("show", "command.hsa.show.desc", BOOL, + { + this->setAble(holder->getBool()); + info(player, "设置HSA显示为 %d", holder->getBool()); + })) + ->then(ARG("find", "command.hsa.find.desc", NONE, + { + broadcastMsg("find %s", + this->findB(player).toString().c_str()); + })) + ->then(ARG("draw", "command.hsa.draw.desc", NONE, + { this->draw(player); })); + } + +} // namespace mod using namespace SymHook; // HSA collector -THook( - void, - MSSYM_B2QUE17spawnStructureMobB1AA7SpawnerB2AAE20AEAAXAEAVBlockSourceB2AAE12AEBVBlockPosB2AAE25AEBUHardcodedSpawningAreaB1AE10LevelChunkB2AAE19AEBVSpawnConditionsB3AAAA1Z, - void *spawner, trapdoor::BlockSource *blockSource, - trapdoor::BlockPos *blockPos, trapdoor::BoundingBox *hsa, - void *spawnConditions) { +THook(void, Spawner_spawnStructureMob_98a1693e, void *spawner, + trapdoor::BlockSource *blockSource, trapdoor::BlockPos *blockPos, + trapdoor::BoundingBox *hsa, void *spawnConditions) { // todo add hsa here original(spawner, blockSource, blockPos, hsa, spawnConditions); auto modInstance = trapdoor::bdsMod->asInstance(); @@ -166,8 +164,7 @@ THook( mod::HsaInfo info; info.boundingBox = {hsa->minPos, hsa->maxPos}; //已有了就不加入了//为了节省一下群系计算时间? - if (hsaManager.findHsa(info)) - return; + if (hsaManager.findHsa(info)) return; auto biome = blockSource->getBiome(blockPos); auto type = biome->getBiomeType(); diff --git a/mod/spawn/HsaManager.h b/mod/spawn/HsaManager.h index b8f2ab2..93d4e44 100644 --- a/mod/spawn/HsaManager.h +++ b/mod/spawn/HsaManager.h @@ -6,6 +6,7 @@ #define MOD_HSAMANAGER_H #include + #include "BDSMod.h" #include "graphics/AABB.h" #include "tools/noncopyable .h" @@ -32,7 +33,7 @@ namespace mod { std::set hsaList; size_t gameTick; - public: + public: inline void insert(HsaInfo info) { this->hsaList.insert(info); } bool findHsa(const HsaInfo &hsaInfo); @@ -57,4 +58,4 @@ namespace mod { }; } // namespace mod -#endif // MOD_HSAMANAGER_H +#endif // MOD_HSAMANAGER_H diff --git a/mod/spawn/SlimeChunkHelper.cpp b/mod/spawn/SlimeChunkHelper.cpp index ea61254..209ae97 100644 --- a/mod/spawn/SlimeChunkHelper.cpp +++ b/mod/spawn/SlimeChunkHelper.cpp @@ -3,15 +3,16 @@ // #include "SlimeChunkHelper.h" + #include "BDSMod.h" -#include "TrapdoorMod.h" #include "Particle.h" +#include "TrapdoorMod.h" #include "lib/Remotery.h" namespace mod { void SlimeChunkHelper::tick() { rmt_ScopedCPUSample(SLIME, 0); constexpr int frequency = 100; - if (!this->enable)return; + if (!this->enable) return; if (gameTick % frequency == 0) { this->updateChunkPosList(); this->draw(); @@ -20,59 +21,56 @@ namespace mod { } void SlimeChunkHelper::updateChunkPosList() { - if (!this->enable)return; + if (!this->enable) return; this->posList.clear(); auto modInstance = trapdoor::bdsMod->asInstance(); modInstance->getLevel()->forEachPlayer([&](trapdoor::Actor *player) { - if (player->getDimensionID() == 0) { //遍历主世界玩家 - int num = 0; - auto playerChunkPos = player->getPos()->toBlockPos().toChunkPos(); - auto pos = playerChunkPos; - for (int i = -showRadius; i < showRadius; i++) { - for (int j = -showRadius; j < showRadius; j++) { - pos.x = playerChunkPos.x + i; - pos.z = playerChunkPos.z + j; - if (pos.isSlimeChunk()) { - ++num; - this->posList.insert(pos); - } - } - } - } - } - ); + if (player->getDimensionID() == 0) { //遍历主世界玩家 + int num = 0; + auto playerChunkPos = + player->getPos()->toBlockPos().toChunkPos(); + auto pos = playerChunkPos; + for (int i = -showRadius; i < showRadius; i++) { + for (int j = -showRadius; j < showRadius; j++) { + pos.x = playerChunkPos.x + i; + pos.z = playerChunkPos.z + j; + if (pos.isSlimeChunk()) { + ++num; + this->posList.insert(pos); + } + } + } + } + }); } void SlimeChunkHelper::draw() { - for (const auto i:this->posList) - trapdoor::spawnSlimeChunkParticle(i); + for (const auto i : this->posList) trapdoor::spawnSlimeChunkParticle(i); } - void SlimeChunkHelper::setRadius(int r) { - this->showRadius = r; - } + void SlimeChunkHelper::setRadius(int r) { this->showRadius = r; } void SlimeChunkHelper::registerCommand(CommandManager &commandManager) { commandManager.registerCmd("slime", "command.slime.desc") - ->then(ARG("show", "command.slime.show.desc", BOOL, - { - this->setAble(holder->getBool()); - // this->slimeChunkHelper.updateChunkPosList(); - // this->slimeChunkHelper.draw(); - broadcastMsg("设置史莱姆区块显示为 %d", - holder->getBool()); - })) - ->then(ARG("c", "command.slime.c.desc", NONE, - { - this->updateChunkPosList(); - this->draw(); - broadcastMsg("已经清除史莱姆区块缓存"); - })) - ->then(ARG("r", "command.slime.r.desc", INT, { - this->setRadius(holder->getInt()); - this->updateChunkPosList(); - this->draw(); - broadcastMsg("已经清除史莱姆区块缓存"); - })); + ->then(ARG("show", "command.slime.show.desc", BOOL, + { + this->setAble(holder->getBool()); + // this->slimeChunkHelper.updateChunkPosList(); + // this->slimeChunkHelper.draw(); + broadcastMsg("设置史莱姆区块显示为 %d", + holder->getBool()); + })) + ->then(ARG("c", "command.slime.c.desc", NONE, + { + this->updateChunkPosList(); + this->draw(); + broadcastMsg("已经清除史莱姆区块缓存"); + })) + ->then(ARG("r", "command.slime.r.desc", INT, { + this->setRadius(holder->getInt()); + this->updateChunkPosList(); + this->draw(); + broadcastMsg("已经清除史莱姆区块缓存"); + })); } -} +} // namespace mod diff --git a/mod/spawn/SlimeChunkHelper.h b/mod/spawn/SlimeChunkHelper.h index eac6eee..6031485 100644 --- a/mod/spawn/SlimeChunkHelper.h +++ b/mod/spawn/SlimeChunkHelper.h @@ -5,11 +5,12 @@ #ifndef MOD_SLIMECHUNKHELPER_H #define MOD_SLIMECHUNKHELPER_H -#include "graphics/BlockPos.h" #include + +#include "commands/CommandManager.h" +#include "graphics/BlockPos.h" #include "tools/noncopyable .h" #include "trapdoor.h" -#include "commands/CommandManager.h" namespace mod { @@ -18,7 +19,8 @@ namespace mod { bool enable = false; size_t gameTick = 0; std::set posList; - public: + + public: inline void setAble(bool able) { this->enable = able; } void updateChunkPosList(); @@ -31,5 +33,5 @@ namespace mod { void draw(); }; -} -#endif //MOD_SLIMECHUNKHELPER_H +} // namespace mod +#endif // MOD_SLIMECHUNKHELPER_H diff --git a/mod/spawn/SpawnAnalyzer.cpp b/mod/spawn/SpawnAnalyzer.cpp deleted file mode 100644 index c4e468d..0000000 --- a/mod/spawn/SpawnAnalyzer.cpp +++ /dev/null @@ -1,142 +0,0 @@ -//// -//// Created by xhy on 2021/1/1. -//// -// -//#include "SpawnAnalyzer.h" -//#include "entity/Actor.h" -//#include "lib/SymHook.h" -//#include "lib/mod.h" -//#include "tools/Message.h" -//#include "TrapdoorMod.h" -//#include "tools/MsgBuilder.h" -//#include -// -//namespace mod { -// -// -// void SpawnAnalyzer::start(trapdoor::Actor *player) { -// if (this->inAnalyzing) { -// trapdoor::warning(player, "生物生成分析器在运行中"); -// } else { -// this->gameTick = 0; -// this->spawnData.clear(); -// inAnalyzing = true; -// trapdoor::info(player, "生物生成分析器已经开始,生物生成分析器数据已经被自动清空"); -// } -// } -// -// void SpawnAnalyzer::end(trapdoor::Actor *player) { -// if (!this->inAnalyzing) { -// trapdoor::warning(player, "生物生成分析器没有在运行"); -// } else { -// inAnalyzing = false; -// trapdoor::info(player, "生物生成分析器已经停止运行"); -// } -// } -// -// void SpawnAnalyzer::addMobData(const SpawnAnalyzer::MobSpawnInfo &info) { -// this->spawnData.push_back(info); -// } -// -// void SpawnAnalyzer::clearData(trapdoor::Actor *player) { -// this->gameTick = 0; -// this->spawnData.clear(); -// trapdoor::info(player, "数据已经清空"); -// } -// -// void SpawnAnalyzer::printSimpleData(trapdoor::Actor *player, const std::string &typePatten) const { -// trapdoor::MessageBuilder builder; -// std::map successSurface; -// std::map successUnderGround; -// std::map failSurface; -// std::map failUnderGround; -// std::map unSuccessData; -// -// int successSNum = 0, successUNum = 0, failSNum = 0, failUNum = 0; -// for (const auto &data:this->spawnData) { -// if (data.isSurface) { -// if (data.success) { -// successSurface[data.type]++; -// successSNum++; -// } else { -// failSurface[data.type]++; -// failSNum++; -// } -// } else { -// if (data.success) { -// successUnderGround[data.type]++; -// successUNum++; -// } else { -// failUnderGround[data.type]++; -// failUNum++; -// } -// } -// } -// int successTotal = successSNum + successUNum; -// int failTotal = failSNum + failUNum; -// builder.textF("total %d success, %d fail (%.2f %%%%)\n", successTotal, failTotal, -// successTotal * 100.0 / (successTotal + failTotal)). -// text("----------Surface----------\n") -// .textF("%d success %d fail (%.2f %%%%)\n", successSNum, failSNum, -// successSNum * 100.0 / (successSNum + failSNum)); -// for (const auto &data:successSurface) { -// int failNum = failSurface[data.first]; -// builder.text(" - ").text(data.first).text(" ").num(data.second).text("/").num( -// failNum + data.second).text( -// "(") -// .num(data.second * 100 / (failNum + data.second)).text("%%%%)\n"); -// } -// -// builder.text("----------Underground----------\n") -// .textF("%d success %d fail (%.2f%%%%)\n", successUNum, failUNum, -// successUNum * 100.0 / (successUNum + failUNum)); -// -// for (const auto &data:successUnderGround) { -// int failNum = failUnderGround[data.first]; -// builder.text(" - ").text(data.first).text(" ").num(data.second).text("/").num( -// failNum + data.second).text( -// "(") -// .num(data.second * 100 / (failNum + data.second)).text("%%%%)\n"); -// } -// builder.send(player); -// } -// -// void SpawnAnalyzer::printSpeedGraph(trapdoor::Actor *player, size_t freq) const { -// //这里本想打印速度曲线的,不想做了 -// } -//} -// -//using namespace SymHook; - - -//THook( -// bool, -// MSSYM_B1QA8spawnMobB1AA7SpawnerB2AAE11QEAAPEAVMobB2AAE15AEAVBlockSourceB2AAE29AEBUActorDefinitionIdentifierB2AAA9PEAVActorB2AAA8AEBVVec3B3AAUA3N44B1AA1Z, -// void *spawner, -// trapdoor::BlockSource *bs, -// trapdoor::ActorDefinitionIdentifier *actorId, -// trapdoor::Actor *actor, -// trapdoor::Vec3 *pos, -// bool naturalSpawn, -// bool surface, -// bool fromSpawner -//) { -// if (!naturalSpawn || fromSpawner) { -// return original(spawner, bs, actorId, actor, pos, naturalSpawn, surface, fromSpawner); -// } else { -// auto success = original(spawner, bs, actorId, actor, pos, naturalSpawn, surface, fromSpawner); -// auto modInstance = trapdoor::bdsMod->asInstance(); -// if (modInstance->getSpawnAnalyzer().isRunning()) { -// mod::SpawnAnalyzer::MobSpawnInfo info{ -// modInstance->getSpawnAnalyzer().getTick(), -// actorId->getName(), -// {pos->x, pos->y, pos->z}, -// surface, -// success -// }; -// modInstance->getSpawnAnalyzer().addMobData(info); -// } -// return success; -// } -//} - diff --git a/mod/spawn/SpawnAnalyzer.h b/mod/spawn/SpawnAnalyzer.h deleted file mode 100644 index ac95301..0000000 --- a/mod/spawn/SpawnAnalyzer.h +++ /dev/null @@ -1,53 +0,0 @@ -//// -//// Created by xhy on 2021/1/1. -//// -// -//#ifndef MOD_SPAWNANALYZER_H -//#define MOD_SPAWNANALYZER_H -// -//#include -//#include "graphics/BlockPos.h" -//#include "graphics/Vec3.h" -//#include -//#include "entity/Actor.h" -// -//namespace mod { -// class SpawnAnalyzer { -// bool inAnalyzing = false; -// size_t gameTick = 0; -// public: -// public: -// struct MobSpawnInfo { -// size_t tick = 0; -// std::string type; //类型 -// trapdoor::Vec3 position; //位置 -// bool isSurface; //是否露天 -// bool success; //是否生成成功 -// }; -// -// void start(trapdoor::Actor *player); -// -// void end(trapdoor::Actor *player); -// -// inline bool isRunning() const { return this->inAnalyzing; } -// -// -// void addMobData(const SpawnAnalyzer::MobSpawnInfo &info); -// -// inline size_t getTick() const { return this->gameTick; } -// -// inline void clearData(trapdoor::Actor *player); -// -// inline void tick() { ++this->gameTick; } -// -// void printSimpleData(trapdoor::Actor *player, const std::string &typePatten = "null") const; -// -// void printSpeedGraph(trapdoor::Actor *player, size_t freq) const; -// -// private: -// std::vector spawnData; -// }; -//} -// -// -//#endif //MOD_SPAWNANALYZER_H diff --git a/mod/spawn/SpawnHelper.cpp b/mod/spawn/SpawnHelper.cpp index c68851c..c8c77f8 100644 --- a/mod/spawn/SpawnHelper.cpp +++ b/mod/spawn/SpawnHelper.cpp @@ -3,29 +3,28 @@ // #include "SpawnHelper.h" -#include "graphics/Particle.h" -#include "graphics/Graphics.h" + +#include "BlockSource.h" +#include "Message.h" +#include "MsgBuilder.h" +#include "Offset.h" +#include "block/Block.h" +#include "block/BlockLegacy.h" #include "graphics/AABB.h" +#include "graphics/Graphics.h" +#include "graphics/Particle.h" #include "lib/SymHook.h" #include "lib/mod.h" +#include "tools/DirtyLogger.h" #include "tools/Message.h" #include "tools/MsgBuilder.h" -#include "tools/DirtyLogger.h" -#include "block/BlockLegacy.h" -#include "block/Block.h" -#include "BlockSource.h" -#include "Message.h" -#include "MsgBuilder.h" -#include "Offset.h" namespace mod { - - namespace { - } + namespace {} void SpawnHelper::tick() { - if (!this->enable)return; + if (!this->enable) return; if (gameTick % 40 == 0) { this->draw(); } @@ -33,19 +32,26 @@ namespace mod { } void SpawnHelper::draw() { - if (!this->enable)return; + if (!this->enable) return; if (!verticalSpawnPositions.empty()) { - trapdoor::BoundingBox boundingBox{verticalSpawnPositions[0], verticalSpawnPositions[0]}; - trapdoor::spawnRectangleParticle(boundingBox.toAABB(), trapdoor::GRAPHIC_COLOR::GREEN, dimensionID); + trapdoor::BoundingBox boundingBox{verticalSpawnPositions[0], + verticalSpawnPositions[0]}; + trapdoor::spawnRectangleParticle(boundingBox.toAABB(), + trapdoor::GRAPHIC_COLOR::GREEN, + dimensionID); } for (auto i = 1; i < verticalSpawnPositions.size(); i++) { - trapdoor::BoundingBox boundingBox{verticalSpawnPositions[i], verticalSpawnPositions[i]}; - trapdoor::spawnRectangleParticle(boundingBox.toAABB(), trapdoor::GRAPHIC_COLOR::RED, dimensionID); + trapdoor::BoundingBox boundingBox{verticalSpawnPositions[i], + verticalSpawnPositions[i]}; + trapdoor::spawnRectangleParticle(boundingBox.toAABB(), + trapdoor::GRAPHIC_COLOR::RED, + dimensionID); } } - void SpawnHelper::updateVerticalSpawnPositions(const trapdoor::BlockPos &pos, trapdoor::Actor *player) { - if (!this->enable)return; + void SpawnHelper::updateVerticalSpawnPositions( + const trapdoor::BlockPos &pos, trapdoor::Actor *player) { + if (!this->enable) return; this->verticalSpawnPositions.clear(); auto dim = player->getDimensionID(); this->dimensionID = dim; @@ -55,14 +61,15 @@ namespace mod { findNextSpawnPosition(player->getBlockSource(), &topPos, 41); // L_INFO("find pos %d %d %d", topPos.x, topPos.y, topPos.z); if (topPos.y > 0) - this->verticalSpawnPositions.emplace_back(topPos.x, topPos.y, topPos.z); + this->verticalSpawnPositions.emplace_back(topPos.x, topPos.y, + topPos.z); } while (topPos.y > 0); } - - void - SpawnHelper::printSpawnProbability(trapdoor::Actor *player, const trapdoor::BlockPos &pos, uint32_t bright) const { - if (!this->enable)return; + void SpawnHelper::printSpawnProbability(trapdoor::Actor *player, + const trapdoor::BlockPos &pos, + uint32_t bright) const { + if (!this->enable) return; auto dim = player->getDimensionID(); int maxY = dim != 1 ? 255 : 127; trapdoor::BlockPos topPos = {pos.x, maxY, pos.z}; @@ -71,83 +78,81 @@ namespace mod { while (topPos.y > 0) { findNextSpawnPosition(player->getBlockSource(), &topPos, 41); if (topPos.y == pos.y) { - // L_INFO("pos %d %d %d is valid spawn position surface: %d", pos.x, pos.y, pos.z, isSurface); + // L_INFO("pos %d %d %d is valid spawn position surface: %d", + // pos.x, pos.y, pos.z, isSurface); hasFound = true; break; } isSurface = false; } if (!hasFound) { - trapdoor::warning(player, "pos [%d %d %d] is not valid spawn position ", pos.x, pos.y, pos.z); + trapdoor::warning(player, + "pos [%d %d %d] is not valid spawn position ", + pos.x, pos.y, pos.z); return; } - SpawnConditions conditions{ - isSurface, - false, - false, - !isSurface, - 0, 0, bright, - pos - }; + SpawnConditions conditions{isSurface, false, false, !isSurface, + 0, 0, bright, pos}; auto *bs = player->getBlockSource(); auto *block = bs->getBlock(pos); std::map spawnMap; for (int i = 0; i < 200; ++i) { auto mobData = getMobToSpawn(block->getLegacy(), conditions, bs); - if (mobData) - spawnMap[mobData->getActorID()->getName()]++; + if (mobData) spawnMap[mobData->getActorID()->getName()]++; } int totalCount = 0; - for (const auto &mob:spawnMap) - totalCount += mob.second; + for (const auto &mob : spawnMap) totalCount += mob.second; trapdoor::MessageBuilder builder; - builder.sTextF(trapdoor::MSG_COLOR::BOLD | trapdoor::MSG_COLOR::WHITE, "-- [%d %d %d] ", pos.x, pos.y, pos.z); + builder.sTextF(trapdoor::MSG_COLOR::BOLD | trapdoor::MSG_COLOR::WHITE, + "-- [%d %d %d] ", pos.x, pos.y, pos.z); if (isSurface) { - builder.sTextF(trapdoor::MSG_COLOR::GREEN | trapdoor::MSG_COLOR::BOLD, "surface"); + builder.sTextF( + trapdoor::MSG_COLOR::GREEN | trapdoor::MSG_COLOR::BOLD, + "surface"); } else { - builder.sTextF(trapdoor::MSG_COLOR::RED | trapdoor::MSG_COLOR::BOLD, "underground"); + builder.sTextF(trapdoor::MSG_COLOR::RED | trapdoor::MSG_COLOR::BOLD, + "underground"); } builder.text(" --\n"); - for (const auto &mob:spawnMap) { - builder.text(mob.first).text(" ").num(mob.second * 100 / totalCount).text("%%%%\n"); + for (const auto &mob : spawnMap) { + builder.text(mob.first) + .text(" ") + .num(mob.second * 100 / totalCount) + .text("%%%%\n"); } builder.send(player); } - - void findNextSpawnPosition(trapdoor::BlockSource *source, trapdoor::BlockPos *pos, unsigned int material) { + void findNextSpawnPosition(trapdoor::BlockSource *source, + trapdoor::BlockPos *pos, unsigned int material) { using namespace SymHook; - SYM_CALL( - void(*)(trapdoor::BlockSource * , trapdoor::BlockPos *, unsigned int), - MSSYM_B1QE23findNextSpawnBlockUnderB1AA7SpawnerB2AAA2SAB1UE16NAEBVBlockSourceB2AAE12AEAVBlockPosB2AAE14W4MaterialTypeB2AAE24W4SpawnBlockRequirementsB3AAAA1Z, - source, pos, material - ); + SYM_CALL(void (*)(trapdoor::BlockSource *, trapdoor::BlockPos *, + unsigned int), + SymHook::Spawner_findNextSpawnBlockUnder_65b36c80, source, pos, + material); } - MobSpawnData * - getMobToSpawn(trapdoor::BlockLegacy *legacy, const SpawnConditions &spawnConditions, - trapdoor::BlockSource *blockSource) { + MobSpawnData *getMobToSpawn(trapdoor::BlockLegacy *legacy, + const SpawnConditions &spawnConditions, + trapdoor::BlockSource *blockSource) { using namespace SymHook; return SYM_CALL( - MobSpawnData*(*)(trapdoor::BlockLegacy * ,const SpawnConditions&, trapdoor::BlockSource*source), - MSSYM_B1QE13getMobToSpawnB1AE11BlockLegacyB2AAE22UEBAPEBVMobSpawnerDataB2AAE19AEBVSpawnConditionsB2AAE15AEAVBlockSourceB3AAAA1Z, - legacy, - spawnConditions, - blockSource - ); + MobSpawnData * (*)(trapdoor::BlockLegacy *, const SpawnConditions &, + trapdoor::BlockSource *source), + SymHook::BlockLegacy_getMobToSpawn_dd8ce374, legacy, + spawnConditions, blockSource); } MobSpawnRules *MobSpawnData::getSpawnRules() { //! Spawner::_spawnMobCluster - return reinterpret_cast(reinterpret_cast(this) + off::MOB_SPAWN_DATA_GET_RULE); + return reinterpret_cast( + reinterpret_cast(this) + off::MOB_SPAWN_DATA_GET_RULE); } trapdoor::ActorDefinitionIdentifier *MobSpawnData::getActorID() { - //!MobSpawnData::MobSpawnData - return reinterpret_cast(reinterpret_cast(this) + - off::MOB_SPAWN_DATA_GET_ACTOR_ID); + //! MobSpawnData::MobSpawnData + return reinterpret_cast( + reinterpret_cast(this) + off::MOB_SPAWN_DATA_GET_ACTOR_ID); } -} - - +} // namespace mod diff --git a/mod/spawn/SpawnHelper.h b/mod/spawn/SpawnHelper.h index d08d0bc..9a34895 100644 --- a/mod/spawn/SpawnHelper.h +++ b/mod/spawn/SpawnHelper.h @@ -6,10 +6,11 @@ #define MOD_SPAWNHELPER_H #include -#include "graphics/BlockPos.h" -#include "entity/Actor.h" -#include "block/BlockLegacy.h" + #include "block/Block.h" +#include "block/BlockLegacy.h" +#include "entity/Actor.h" +#include "graphics/BlockPos.h" #include "tools/noncopyable .h" namespace mod { @@ -26,9 +27,7 @@ namespace mod { trapdoor::BlockPos pos{}; }; - struct MobSpawnRules { - - }; + struct MobSpawnRules {}; struct MobSpawnData { MobSpawnRules *getSpawnRules(); @@ -41,7 +40,8 @@ namespace mod { bool enable = false; int dimensionID = 0; unsigned long long gameTick; - public: + + public: inline void setAble(bool able) { this->enable = able; } inline bool isEnable() const { return this->enable; } @@ -50,19 +50,21 @@ namespace mod { void draw(); - void updateVerticalSpawnPositions(const trapdoor::BlockPos &pos, trapdoor::Actor *player); - - void printSpawnProbability(trapdoor::Actor *player, const trapdoor::BlockPos &pos, uint32_t bright) const; + void updateVerticalSpawnPositions(const trapdoor::BlockPos &pos, + trapdoor::Actor *player); + void printSpawnProbability(trapdoor::Actor *player, + const trapdoor::BlockPos &pos, + uint32_t bright) const; }; - void findNextSpawnPosition(trapdoor::BlockSource *source, trapdoor::BlockPos *pos, unsigned int material); - - MobSpawnData * - getMobToSpawn(trapdoor::BlockLegacy *legacy, const SpawnConditions &spawnConditions, - trapdoor::BlockSource *blockSource); + void findNextSpawnPosition(trapdoor::BlockSource *source, + trapdoor::BlockPos *pos, unsigned int material); -} + MobSpawnData *getMobToSpawn(trapdoor::BlockLegacy *legacy, + const SpawnConditions &spawnConditions, + trapdoor::BlockSource *blockSource); +} // namespace mod -#endif //MOD_SPAWNHELPER_H +#endif // MOD_SPAWNHELPER_H diff --git a/mod/test/TrapdoorTest.cpp b/mod/test/TrapdoorTest.cpp index 0657bf9..c003f93 100644 --- a/mod/test/TrapdoorTest.cpp +++ b/mod/test/TrapdoorTest.cpp @@ -4,9 +4,15 @@ #include "TrapdoorTest.h" -#define COMMAND_TEST(TEST_NAME) void commandTest_##TEST_NAME (trapdoor::CommandManager &manager, trapdoor::Actor *player) -#define TEST(TEST_NAME) commandTest_##TEST_NAME (manager,player); -#define RUN_CMD(cmd) { trapdoor::info(player,"TEST: [" cmd "]\n");manager.parse(player, cmd);} +#define COMMAND_TEST(TEST_NAME) \ + void commandTest_##TEST_NAME(trapdoor::CommandManager &manager, \ + trapdoor::Actor *player) +#define TEST(TEST_NAME) commandTest_##TEST_NAME(manager, player); +#define RUN_CMD(cmd) \ + { \ + trapdoor::info(player, "TEST: [" cmd "]\n"); \ + manager.parse(player, cmd); \ + } namespace mod::test { namespace { std::map &getNeedMoreTestItems() { @@ -17,11 +23,13 @@ namespace mod::test { void printTestStatus(trapdoor::Actor *actor) { const auto &items = getNeedMoreTestItems(); std::string stringBuilder; - for (const auto &i:items) { + for (const auto &i : items) { if (i.second) { - stringBuilder += trapdoor::format("- %s " C_GREEN(%d) "\n", i.first.c_str(), i.second); + stringBuilder += trapdoor::format( + "- %s " C_GREEN(% d) "\n", i.first.c_str(), i.second); } else { - stringBuilder += trapdoor::format("- %s " C_RED(%d) "\n", i.first.c_str(), i.second); + stringBuilder += trapdoor::format( + "- %s " C_RED(% d) "\n", i.first.c_str(), i.second); } } trapdoor::info(actor, stringBuilder); @@ -52,25 +60,29 @@ namespace mod::test { } void buildTestPlatform(trapdoor::Actor *player) { - //build space + // build space auto *bs = player->getBlockSource(); for (int i = -16; i < 16; i++) { for (int j = -16; j < 16; j++) { for (int k = -1; k < 30; k++) { - trapdoor::BlockPos pos = player->getStandPosition() + trapdoor::BlockPos(i, k, j); + trapdoor::BlockPos pos = player->getStandPosition() + + trapdoor::BlockPos(i, k, j); bs->setBlock(&pos, getBlockByID(AIR)); } } } - //hopper test + // hopper test for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { - trapdoor::BlockPos pos = player->getStandPosition() + trapdoor::BlockPos(2 * i - 16, 2, 2 * j - 16); - trapdoor::Block *b = getBlockByID(CONCRETE, (unsigned short) (i * 4 + j)); + trapdoor::BlockPos pos = + player->getStandPosition() + + trapdoor::BlockPos(2 * i - 16, 2, 2 * j - 16); + trapdoor::Block *b = + getBlockByID(CONCRETE, (unsigned short)(i * 4 + j)); bs->setBlock(&pos, b); auto hopperV = rand() % 6; auto pos2 = pos + trapdoor::BlockPos(0, 1, 0); - auto *b2 = getBlockByID(HOPPER, (unsigned short) hopperV); + auto *b2 = getBlockByID(HOPPER, (unsigned short)hopperV); bs->setBlock(&pos2, b2); auto *wool = getBlockByID(WOOL, hopperV == 0 ? 0 : 4); auto pos3 = pos + trapdoor::BlockPos(0, -1, 0); @@ -78,100 +90,80 @@ namespace mod::test { } } - //village test + // village test auto bedPos = player->getStandPosition(); player->getBlockSource()->setBlock(&bedPos, getBlockByID(BED)); - trapdoor::CommandManager::runVanillaCommand("execute @p ~ ~ ~ summon ~ ~2 ~ villager"); + trapdoor::CommandManager::runVanillaCommand( + "execute @p ~ ~ ~ summon ~ ~2 ~ villager"); - //rotate - trapdoor::CommandManager::runVanillaCommand("give " + player->getNameTag() + " cactus"); - std::vector blocks = { - PISTON, STICKY_PISTON, DISPENSER, - REDSTONE_TORCH, CHEST, OBSERVER, - WOODEN_SLAB, ACACIA_STAIRS, BARREL, - ACACIA_BUTTON, DROPPER, POWERED_REPEATER, UNPOWERED_REPEATER, - POWERED_COMPARATOR, POWERED_REPEATER - }; + // rotate + trapdoor::CommandManager::runVanillaCommand( + "give " + player->getNameTag() + " cactus"); + std::vector blocks = {PISTON, + STICKY_PISTON, + DISPENSER, + REDSTONE_TORCH, + CHEST, + OBSERVER, + WOODEN_SLAB, + ACACIA_STAIRS, + BARREL, + ACACIA_BUTTON, + DROPPER, + POWERED_REPEATER, + UNPOWERED_REPEATER, + POWERED_COMPARATOR, + POWERED_REPEATER}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { auto index = i * 4 + j; if (index < blocks.size()) { - trapdoor::BlockPos p = player->getStandPosition() + trapdoor::BlockPos(i + 2, 0, j + 2); + trapdoor::BlockPos p = + player->getStandPosition() + + trapdoor::BlockPos(i + 2, 0, j + 2); bs->setBlock(&p, getBlockByID(blocks[index])); } } } - //redstone signal - trapdoor::CommandManager::runVanillaCommand("give " + player->getNameTag() + " stick"); - + // redstone signal + trapdoor::CommandManager::runVanillaCommand( + "give " + player->getNameTag() + " stick"); } - } + } // namespace - COMMAND_TEST(apicfg) { - RUN_CMD("/apicfg") - RUN_CMD("/apicfg ?") - RUN_CMD("/apicfg pm 1") - RUN_CMD("/apicfg pm 0") - RUN_CMD("/apicfg pvd 1") - RUN_CMD("/apicfg pvd 12") - RUN_CMD("/apicfg pvd -12") - } + COMMAND_TEST(apicfg){ + RUN_CMD("/apicfg") RUN_CMD("/apicfg ?") RUN_CMD("/apicfg pm 1") + RUN_CMD("/apicfg pm 0") RUN_CMD("/apicfg pvd 1") + RUN_CMD("/apicfg pvd 12") RUN_CMD("/apicfg pvd -12")} - COMMAND_TEST(td) { - RUN_CMD("/td?") - } + COMMAND_TEST(td){RUN_CMD("/td?")} - COMMAND_TEST(func) { - RUN_CMD("/func") - RUN_CMD("/func ?") - RUN_CMD("/func hopper 1") - RUN_CMD("/func hopper 0") - RUN_CMD("/func spawn true") - RUN_CMD("/func spawn false") - RUN_CMD("/func rotate 1") - RUN_CMD("/func rotate 0") - RUN_CMD("/func ncud 1") - RUN_CMD("/func ncud 0") - RUN_CMD("/func expl true") - RUN_CMD("/func expl false") - } + COMMAND_TEST(func){ + RUN_CMD("/func") RUN_CMD("/func ?") RUN_CMD("/func hopper 1") + RUN_CMD("/func hopper 0") RUN_CMD("/func spawn true") + RUN_CMD("/func spawn false") RUN_CMD("/func rotate 1") + RUN_CMD("/func rotate 0") RUN_CMD("/func ncud 1") + RUN_CMD("/func ncud 0") RUN_CMD("/func expl true") + RUN_CMD("/func expl false")} - COMMAND_TEST(lang) { - RUN_CMD("/lang") - RUN_CMD("/lang list") - RUN_CMD("/lang set zh_cn") - } + COMMAND_TEST(lang){RUN_CMD("/lang") RUN_CMD("/lang list") + RUN_CMD("/lang set zh_cn")} - COMMAND_TEST(tick) { - RUN_CMD("/tick") - RUN_CMD("/tick ?") - RUN_CMD("/tick fz") - RUN_CMD("/tick fw 20") - RUN_CMD("/tick fw 601") - RUN_CMD("/tick r") - RUN_CMD("/tick acc 30") - RUN_CMD("/tick acc -1") - RUN_CMD("/tick acc 3") - RUN_CMD("/tick r") - RUN_CMD("/tick slow 67") - RUN_CMD("/tick slow 1") - RUN_CMD("/tick slow 4") - RUN_CMD("/tick r") - } + COMMAND_TEST(tick){ + RUN_CMD("/tick") RUN_CMD("/tick ?") RUN_CMD("/tick fz") + RUN_CMD("/tick fw 20") RUN_CMD("/tick fw 601") RUN_CMD("/tick r") + RUN_CMD("/tick acc 30") RUN_CMD("/tick acc -1") + RUN_CMD("/tick acc 3") RUN_CMD("/tick r") + RUN_CMD("/tick slow 67") RUN_CMD("/tick slow 1") + RUN_CMD("/tick slow 4") RUN_CMD("/tick r")} - COMMAND_TEST(counter) { - RUN_CMD("/counter") - RUN_CMD("/counter p 15") - RUN_CMD("/counter p -1") - RUN_CMD("/counter p 16") - RUN_CMD("/counter p 7") - RUN_CMD("/counter r 7") - } + COMMAND_TEST(counter){RUN_CMD("/counter") RUN_CMD("/counter p 15") + RUN_CMD("/counter p -1") RUN_CMD("/counter p 16") + RUN_CMD("/counter p 7") + RUN_CMD("/counter r 7")} - COMMAND_TEST(os) { - RUN_CMD("/os") - } + COMMAND_TEST(os){RUN_CMD("/os")} COMMAND_TEST(self) { RUN_CMD("/self") @@ -183,60 +175,30 @@ namespace mod::test { RUN_CMD("/self chunk 0"); } - COMMAND_TEST(gameMode) { - RUN_CMD("/o") - RUN_CMD("/s") - RUN_CMD("/c") - } + COMMAND_TEST(gameMode){RUN_CMD("/o") RUN_CMD("/s") RUN_CMD("/c")} - COMMAND_TEST(list) { - RUN_CMD("/l") - RUN_CMD("/here") - } + COMMAND_TEST(list){RUN_CMD("/l") RUN_CMD("/here")} - COMMAND_TEST(village) { - RUN_CMD("/village") - RUN_CMD("/village list") - RUN_CMD("/village b true") - RUN_CMD("/village b false") - RUN_CMD("/village s 1") - RUN_CMD("/village s 0") - RUN_CMD("/village p true") - RUN_CMD("/village p false") - RUN_CMD("/village v true") - RUN_CMD("/village v false") - RUN_CMD("/village n") - } + COMMAND_TEST(village){ + RUN_CMD("/village") RUN_CMD("/village list") RUN_CMD("/village b true") + RUN_CMD("/village b false") RUN_CMD("/village s 1") + RUN_CMD("/village s 0") RUN_CMD("/village p true") + RUN_CMD("/village p false") RUN_CMD("/village v true") + RUN_CMD("/village v false") RUN_CMD("/village n")} - COMMAND_TEST(hsa) { - RUN_CMD("/hsa") - RUN_CMD("/hsa show 1") - RUN_CMD("/hsa show false") - RUN_CMD("/hsa clear") - RUN_CMD("/hsa draw") - RUN_CMD("/hsa list") - } + COMMAND_TEST(hsa){RUN_CMD("/hsa") RUN_CMD("/hsa show 1") + RUN_CMD("/hsa show false") RUN_CMD("/hsa clear") + RUN_CMD("/hsa draw") RUN_CMD("/hsa list")} - COMMAND_TEST(draw) { - RUN_CMD("/func") - RUN_CMD("/func draw false") - RUN_CMD("/func draw 1") - RUN_CMD("/draw sp 2") - RUN_CMD("/draw sp -3") - RUN_CMD("/draw ci 5") - RUN_CMD("/draw ci -10") - } + COMMAND_TEST(draw){RUN_CMD("/func") RUN_CMD("/func draw false") + RUN_CMD("/func draw 1") RUN_CMD("/draw sp 2") + RUN_CMD("/draw sp -3") RUN_CMD("/draw ci 5") + RUN_CMD("/draw ci -10")} - COMMAND_TEST(cl) { - RUN_CMD("/cl") - RUN_CMD("/cl 12+sin(0.5+2*pi)-log2(12)") - RUN_CMD("/cl 1/0") - RUN_CMD("/cl log(-1)") - } + COMMAND_TEST(cl){RUN_CMD("/cl") RUN_CMD("/cl 12+sin(0.5+2*pi)-log2(12)") + RUN_CMD("/cl 1/0") RUN_CMD("/cl log(-1)")} - COMMAND_TEST(mspt) { - RUN_CMD("/mspt") - } + COMMAND_TEST(mspt){RUN_CMD("/mspt")} COMMAND_TEST(slime) { RUN_CMD("/slime") @@ -266,7 +228,6 @@ namespace mod::test { trapdoor::info(player, "end Test"); } - void addManualTest() { addManualTestItem("backup"); addManualTestItem("village"); @@ -287,21 +248,17 @@ namespace mod::test { #ifdef BETA addManualTest(); manager.registerCmd("test") - ->then(ARG("p", "通过某项测试", STR, { - markPassed(holder->getString(), player); - })) - ->then(ARG("u", "通过某项测试", STR, { - markUnPassed(holder->getString(), player); - })) - ->then(ARG("l", "列出所有手动测试项", NONE, { - printTestStatus(player); - })) - ->then(ARG("b", "手动测试项", STR, { - buildTestPlatform(player); - })) - ->execute([&](trapdoor::ArgHolder *holder, trapdoor::Actor *player) { + ->then(ARG("p", "通过某项测试", STR, + { markPassed(holder->getString(), player); })) + ->then(ARG("u", "通过某项测试", STR, + { markUnPassed(holder->getString(), player); })) + ->then(ARG("l", "列出所有手动测试项", NONE, + { printTestStatus(player); })) + ->then(ARG("b", "手动测试项", STR, { buildTestPlatform(player); })) + ->execute( + [&](trapdoor::ArgHolder *holder, trapdoor::Actor *player) { testAll(player, manager); }); #endif } -} +} // namespace mod::test diff --git a/mod/test/TrapdoorTest.h b/mod/test/TrapdoorTest.h index f95c7a1..5367a83 100644 --- a/mod/test/TrapdoorTest.h +++ b/mod/test/TrapdoorTest.h @@ -7,11 +7,11 @@ #include "Actor.h" #include "BDSMod.h" -#include "TrapdoorMod.h" #include "CommandManager.h" +#include "TrapdoorMod.h" namespace mod::test { void registerTestCommand(trapdoor::CommandManager &); } -#endif //MOD_TRAPDOORTEST_H +#endif // MOD_TRAPDOORTEST_H diff --git a/mod/tick/ActorProfiler.cpp b/mod/tick/ActorProfiler.cpp index 10bc503..c49d42e 100644 --- a/mod/tick/ActorProfiler.cpp +++ b/mod/tick/ActorProfiler.cpp @@ -3,11 +3,13 @@ // #include "ActorProfiler.h" -#include "tools/Message.h" -#include "tools/MsgBuilder.h" + +#include + #include "GameTick.h" #include "tools/DirtyLogger.h" -#include +#include "tools/Message.h" +#include "tools/MsgBuilder.h" #include "tools/noncopyable .h" namespace mod { @@ -17,7 +19,7 @@ namespace mod { static ActorProfiler actorProfiler; return actorProfiler; } - } + } // namespace void profileEntities(trapdoor::Actor *player) { if (getActorProfiler().inProfiling) { @@ -26,7 +28,8 @@ namespace mod { } if (tick::getTickStatus() != tick::WorldTickStatus::Normal) { - trapdoor::warning(player, "现在游戏并没有处在正常模式,测量结果可能不准确"); + trapdoor::warning(player, + "现在游戏并没有处在正常模式,测量结果可能不准确"); } L_DEBUG("begin actor profiling"); info(player, "开始测试"); @@ -34,33 +37,35 @@ namespace mod { getActorProfiler().currentRound = getActorProfiler().totalRound; } - void ActorProfiler::print() const { trapdoor::MessageBuilder builder; microsecond_t totalTime = 0; size_t entityNum = 0; - auto rounds = static_cast(this->totalRound * 1000); + auto rounds = static_cast(this->totalRound * 1000); //统计总量 - for (const auto &item:this->entitiesTickingList) { + for (const auto &item : this->entitiesTickingList) { totalTime += item.second.time; entityNum += item.second.count; } - builder.sTextF(trapdoor::MessageBuilder::BOLD | trapdoor::MessageBuilder::AQUA, + builder.sTextF( + trapdoor::MessageBuilder::BOLD | trapdoor::MessageBuilder::AQUA, - "\n- %.3fms(%d) --\n", totalTime / rounds, entityNum / this->totalRound); + "\n- %.3fms(%d) --\n", totalTime / rounds, + entityNum / this->totalRound); //排序 - std::vector> info(entitiesTickingList.begin(), - entitiesTickingList.end()); + std::vector> info( + entitiesTickingList.begin(), entitiesTickingList.end()); //输出前num个 - std::sort(info.begin(), info.end(), [](const std::pair &i1, - const std::pair &i2 - ) { - return i1.second.time > i2.second.time; - }); + std::sort(info.begin(), info.end(), + [](const std::pair &i1, + const std::pair &i2) { + return i1.second.time > i2.second.time; + }); for (auto &item : info) { builder.textF(" - %s ", item.first.c_str()) - .sTextF(trapdoor::MessageBuilder::GREEN, "%.3fms/(%d)\n", - item.second.time / rounds, item.second.count / this->totalRound); + .sTextF(trapdoor::MessageBuilder::GREEN, "%.3fms/(%d)\n", + item.second.time / rounds, + item.second.count / this->totalRound); } builder.broadcast(); } @@ -70,11 +75,4 @@ namespace mod { this->entitiesTickingList.clear(); this->currentRound = 0; } -}; - - - - - - - +}; // namespace mod diff --git a/mod/tick/ActorProfiler.h b/mod/tick/ActorProfiler.h index fa24278..a019df3 100644 --- a/mod/tick/ActorProfiler.h +++ b/mod/tick/ActorProfiler.h @@ -5,14 +5,15 @@ #ifndef MOD_ACTORPROFILER_H #define MOD_ACTORPROFILER_H -#include "entity/Actor.h" -#include "SimpleProfiler.h" -#include #include +#include + +#include "SimpleProfiler.h" +#include "entity/Actor.h" namespace mod { class ActorProfiler : noncopyable { - public: + public: struct ActorProfilerInfo { microsecond_t time = 0; size_t count = 0; @@ -27,7 +28,6 @@ namespace mod { void reset(); }; -} - +} // namespace mod -#endif //MOD_ACTORPROFILER_H +#endif // MOD_ACTORPROFILER_H diff --git a/mod/tick/GameTick.cpp b/mod/tick/GameTick.cpp index 01b98cf..8788d5c 100644 --- a/mod/tick/GameTick.cpp +++ b/mod/tick/GameTick.cpp @@ -3,6 +3,7 @@ // #include "GameTick.h" + #include "ActorProfiler.h" #include "BDSMod.h" #include "TrapdoorMod.h" @@ -13,216 +14,217 @@ #include "tools/Message.h" namespace mod::tick { -using trapdoor::broadcastMsg; -using trapdoor::error; -using trapdoor::info; -using trapdoor::warning; -namespace { -WorldTickStatus tickStatus = WorldTickStatus::Normal; -WorldTickStatus lastTickStats = WorldTickStatus::Normal; - -mod::SimpleProfiler gameProfiler; -size_t wrapSpeed = 1; -int SlowDownTimes = 1; // slow down time -int slowDownCounter = 0; // slow down counter -int forwardTickNum = 0; // forward tick num -bool isMSPTing = false; - -mod::ActorProfiler &getActorProfiler() { - static mod::ActorProfiler actorProfiler; - return actorProfiler; -} - -/* - * 这个函数也是每gt执行一次的,但是不经过 TrapdoorMod,因此用static 来表示 - */ + using trapdoor::broadcastMsg; + using trapdoor::error; + using trapdoor::info; + using trapdoor::warning; + namespace { + WorldTickStatus tickStatus = WorldTickStatus::Normal; + WorldTickStatus lastTickStats = WorldTickStatus::Normal; + + mod::SimpleProfiler gameProfiler; + size_t wrapSpeed = 1; + int SlowDownTimes = 1; // slow down time + int slowDownCounter = 0; // slow down counter + int forwardTickNum = 0; // forward tick num + bool isMSPTing = false; + + mod::ActorProfiler &getActorProfiler() { + static mod::ActorProfiler actorProfiler; + return actorProfiler; + } -void staticWork() { - //实体性能分析的更新 - if (mod::tick::getActorProfiler().inProfiling) { - auto &actorProfiler = mod::tick::getActorProfiler(); - actorProfiler.currentRound--; - if (actorProfiler.currentRound == 0) { - actorProfiler.print(); - actorProfiler.reset(); + /* + * 这个函数也是每gt执行一次的,但是不经过 TrapdoorMod,因此用static + * 来表示 + */ + + void staticWork() { + //实体性能分析的更新 + if (mod::tick::getActorProfiler().inProfiling) { + auto &actorProfiler = mod::tick::getActorProfiler(); + actorProfiler.currentRound--; + if (actorProfiler.currentRound == 0) { + actorProfiler.print(); + actorProfiler.reset(); + } + } } - } -} -void sendMsptInfo(microsecond_t time, bool isRedstoneTick) { - auto mspt = (double)time / 1000; - int tps = mspt <= 50 ? 20 : (int)(1000.0 / mspt); - trapdoor::MessageBuilder builder; - auto color = MSG_COLOR::WHITE; - if (mspt > 40) { - if (mspt >= 50) { - color = MSG_COLOR::RED; - } else { - color = MSG_COLOR::YELLOW; + void sendMsptInfo(microsecond_t time, bool isRedstoneTick) { + auto mspt = (double)time / 1000; + int tps = mspt <= 50 ? 20 : (int)(1000.0 / mspt); + trapdoor::MessageBuilder builder; + auto color = MSG_COLOR::WHITE; + if (mspt > 40) { + if (mspt >= 50) { + color = MSG_COLOR::RED; + } else { + color = MSG_COLOR::YELLOW; + } + } + auto rColor = isRedstoneTick ? MSG_COLOR::RED : MSG_COLOR::WHITE; + builder.sText("#", rColor) + .text("mspt: ") + .sTextF(color, "%.3f ms ", mspt) + .text("tps: ") + .sTextF(color, "%d", tps) + .broadcast(); } - } - auto rColor = isRedstoneTick ? MSG_COLOR::RED : MSG_COLOR::WHITE; - builder.sText("#", rColor) - .text("mspt: ") - .sTextF(color, "%.3f ms ", mspt) - .text("tps: ") - .sTextF(color, "%d", tps) - .broadcast(); -} -} // namespace - -void freezeTick() { - if (tickStatus == WorldTickStatus::Normal) { - // info("world has frozen"); - if (tickStatus != WorldTickStatus::Frozen) { - tickStatus = WorldTickStatus::Frozen; - L_DEBUG("freeze world"); - broadcastMsg(LANG("tick.fz.set")); + } // namespace + + void freezeTick() { + if (tickStatus == WorldTickStatus::Normal) { + // info("world has frozen"); + if (tickStatus != WorldTickStatus::Frozen) { + tickStatus = WorldTickStatus::Frozen; + L_DEBUG("freeze world"); + broadcastMsg(LANG("tick.fz.set")); + } } } -} -void resetTick() { - if (tickStatus != WorldTickStatus::Normal) { - tickStatus = WorldTickStatus::Normal; - L_DEBUG("reset world"); + void resetTick() { + if (tickStatus != WorldTickStatus::Normal) { + tickStatus = WorldTickStatus::Normal; + L_DEBUG("reset world"); + } + broadcastMsg(LANG("tick.r.set")); } - broadcastMsg(LANG("tick.r.set")); -} -void wrapTick(size_t speed) { - if (tickStatus == WorldTickStatus::Normal) { - broadcastMsg(LANG("tick.acc.set"), speed); - tickStatus = WorldTickStatus::Wrap; - L_DEBUG("begin accelerate world %d", speed); - wrapSpeed = speed; - } else { - broadcastMsg(LANG("tick.acc.error")); + void wrapTick(size_t speed) { + if (tickStatus == WorldTickStatus::Normal) { + broadcastMsg(LANG("tick.acc.set"), speed); + tickStatus = WorldTickStatus::Wrap; + L_DEBUG("begin accelerate world %d", speed); + wrapSpeed = speed; + } else { + broadcastMsg(LANG("tick.acc.error")); + } } -} -void forwardTick(size_t tickNum) { - if (tickStatus == WorldTickStatus::Frozen || - tickStatus == WorldTickStatus::Normal) { - forwardTickNum = tickNum; - lastTickStats = tickStatus; - tickStatus = WorldTickStatus::Forward; - if (tickNum > 1200) - broadcastMsg(LANG("tick.fw.begin"), tickNum); - L_DEBUG("begin forward %d tick", tickNum); - } else { - broadcastMsg(LANG("tick.fw.error")); + void forwardTick(size_t tickNum) { + if (tickStatus == WorldTickStatus::Frozen || + tickStatus == WorldTickStatus::Normal) { + forwardTickNum = tickNum; + lastTickStats = tickStatus; + tickStatus = WorldTickStatus::Forward; + if (tickNum > 1200) broadcastMsg(LANG("tick.fw.begin"), tickNum); + L_DEBUG("begin forward %d tick", tickNum); + } else { + broadcastMsg(LANG("tick.fw.error")); + } } -} -void slowTick(size_t slowSpeed) { - if (tickStatus == WorldTickStatus::Normal) { - broadcastMsg(LANG("tick.slow.set"), slowSpeed); - L_DEBUG("slow world %d times", slowSpeed); - tickStatus = WorldTickStatus::Slow; - SlowDownTimes = slowSpeed; - } else { - broadcastMsg(LANG("tick.slow.error")); + void slowTick(size_t slowSpeed) { + if (tickStatus == WorldTickStatus::Normal) { + broadcastMsg(LANG("tick.slow.set"), slowSpeed); + L_DEBUG("slow world %d times", slowSpeed); + tickStatus = WorldTickStatus::Slow; + SlowDownTimes = slowSpeed; + } else { + broadcastMsg(LANG("tick.slow.error")); + } } -} -void profileWorld(trapdoor::Actor *player) { - if (gameProfiler.inProfiling) { - trapdoor::warning(player, LANG("prof.error")); - return; - } + void profileWorld(trapdoor::Actor *player) { + if (gameProfiler.inProfiling) { + trapdoor::warning(player, LANG("prof.error")); + return; + } - if (tickStatus != WorldTickStatus::Normal) { - trapdoor::warning(player, LANG("prof.warning")); + if (tickStatus != WorldTickStatus::Normal) { + trapdoor::warning(player, LANG("prof.warning")); + } + L_DEBUG("begin profiling"); + broadcastMsg(LANG("prof.start")); + gameProfiler.inProfiling = true; + gameProfiler.currentRound = gameProfiler.totalRound; } - L_DEBUG("begin profiling"); - broadcastMsg(LANG("prof.start")); - gameProfiler.inProfiling = true; - gameProfiler.currentRound = gameProfiler.totalRound; -} -void mspt() { tick::isMSPTing = true; } + void mspt() { tick::isMSPTing = true; } -WorldTickStatus getTickStatus() { return tickStatus; } + WorldTickStatus getTickStatus() { return tickStatus; } -void profileEntities(trapdoor::Actor *player) { - if (getActorProfiler().inProfiling) { - trapdoor::warning(player, LANG("prof.error")); - return; - } + void profileEntities(trapdoor::Actor *player) { + if (getActorProfiler().inProfiling) { + trapdoor::warning(player, LANG("prof.error")); + return; + } - if (tick::getTickStatus() != tick::WorldTickStatus::Normal) { - trapdoor::warning(player, LANG("prof.warning")); + if (tick::getTickStatus() != tick::WorldTickStatus::Normal) { + trapdoor::warning(player, LANG("prof.warning")); + } + L_DEBUG("begin profiling"); + info(player, LANG("prof.start")); + getActorProfiler().inProfiling = true; + getActorProfiler().currentRound = getActorProfiler().totalRound; } - L_DEBUG("begin profiling"); - info(player, LANG("prof.start")); - getActorProfiler().inProfiling = true; - getActorProfiler().currentRound = getActorProfiler().totalRound; -} -void queryStatus(trapdoor::Actor *player) { - switch (tickStatus) { - case Frozen: - info(player, "frozen"); - return; - case Normal: - info(player, "normal"); - return; - case Slow: - info(player, "slow %d times", tick::SlowDownTimes); - return; - case Forward: - info(player, "forwarding"); - return; - case Wrap: - info(player, "accelerate %d times", tick::wrapSpeed); - return; + void queryStatus(trapdoor::Actor *player) { + switch (tickStatus) { + case Frozen: + info(player, "frozen"); + return; + case Normal: + info(player, "normal"); + return; + case Slow: + info(player, "slow %d times", tick::SlowDownTimes); + return; + case Forward: + info(player, "forwarding"); + return; + case Wrap: + info(player, "accelerate %d times", tick::wrapSpeed); + return; + } } -} -void registerTickCommand(CommandManager &commandManager) { - commandManager.registerCmd("tick", "command.tick.desc") - ->then(ARG("fz", "command.tick.fw.desc", NONE, { tick::freezeTick(); })) - ->then(ARG("slow", "command.tick.slow.desc", INT, - { - auto slowTime = holder->getInt(); - if (slowTime > 1 && slowTime <= 64) { - tick::slowTick(slowTime); - } else { - error(player, LANG("command.tick.slow.error")); - } - })) - ->then(ARG("acc", "command.tick.acc.desc", INT, - { - auto wrapTime = holder->getInt(); - if (wrapTime > 1 && wrapTime <= 10) { - tick::wrapTick(wrapTime); - } else { - error(player, LANG("command.tick.acc.error")); - } - })) - ->then(ARG("r", "command.tick.r.desc", NONE, { tick::resetTick(); })) - ->then(ARG("fw", "command.tick.fw.desc", INT, - { tick::forwardTick(holder->getInt()); })) - ->then(ARG("q", "command.tick.q.desc", NONE, - { tick::queryStatus(player); })); -} + void registerTickCommand(CommandManager &commandManager) { + commandManager.registerCmd("tick", "command.tick.desc") + ->then(ARG("fz", "command.tick.fw.desc", NONE, + { tick::freezeTick(); })) + ->then(ARG("slow", "command.tick.slow.desc", INT, + { + auto slowTime = holder->getInt(); + if (slowTime > 1 && slowTime <= 64) { + tick::slowTick(slowTime); + } else { + error(player, LANG("command.tick.slow.error")); + } + })) + ->then(ARG("acc", "command.tick.acc.desc", INT, + { + auto wrapTime = holder->getInt(); + if (wrapTime > 1 && wrapTime <= 10) { + tick::wrapTick(wrapTime); + } else { + error(player, LANG("command.tick.acc.error")); + } + })) + ->then( + ARG("r", "command.tick.r.desc", NONE, { tick::resetTick(); })) + ->then(ARG("fw", "command.tick.fw.desc", INT, + { tick::forwardTick(holder->getInt()); })) + ->then(ARG("q", "command.tick.q.desc", NONE, + { tick::queryStatus(player); })); + } -void registerProfileCommand(CommandManager &commandManager) { - commandManager.registerCmd("prof", "command.prof.desc") - ->then(ARG("actor", "command.prof.actor.desc", NONE, - { tick::profileEntities(player); })) - ->EXE({ tick::profileWorld(player); }); - commandManager.registerCmd("mspt", "command.mspt.desc")->EXE({ - tick::mspt(); - }); -} -} // namespace mod::tick + void registerProfileCommand(CommandManager &commandManager) { + commandManager.registerCmd("prof", "command.prof.desc") + ->then(ARG("actor", "command.prof.actor.desc", NONE, + { tick::profileEntities(player); })) + ->EXE({ tick::profileWorld(player); }); + commandManager.registerCmd("mspt", "command.mspt.desc")->EXE({ + tick::mspt(); + }); + } +} // namespace mod::tick using namespace SymHook; -THook(void, MSSYM_B1QA4tickB1AE11ServerLevelB2AAA7UEAAXXZ, - trapdoor::Level *serverLevel) { +THook(void, ServerLevel_tick_86efb826, trapdoor::Level *serverLevel) { if (!trapdoor::bdsMod) { L_ERROR("mod is nullptr"); } @@ -235,78 +237,79 @@ THook(void, MSSYM_B1QA4tickB1AE11ServerLevelB2AAA7UEAAXXZ, auto modInstance = trapdoor::bdsMod->asInstance(); switch (mod::tick::tickStatus) { - case mod::tick::Frozen: - return; - case mod::tick::Normal: - - if (mod::tick::gameProfiler.inProfiling || mod::tick::isMSPTing) { - TIMER_START - original(serverLevel); - modInstance->lightTick(); - modInstance->heavyTick(); - mod::tick::staticWork(); - TIMER_END - if (mod::tick::isMSPTing) { - //发送mspt信息 - bool isRedstoneTick = - modInstance->getLevel()->getDimFromID(0)->isRedstoneTick(); - mod::tick::sendMsptInfo(timeReslut, isRedstoneTick); - mod::tick::isMSPTing = false; - } - if (mod::tick::gameProfiler.inProfiling) { - mod::tick::gameProfiler.serverLevelTickTime += timeReslut; - mod::tick::gameProfiler.currentRound--; - if (mod::tick::gameProfiler.currentRound == 0) { - mod::tick::gameProfiler.inProfiling = false; - mod::tick::gameProfiler.print(); - mod::tick::gameProfiler.reset(); + case mod::tick::Frozen: + return; + case mod::tick::Normal: + + if (mod::tick::gameProfiler.inProfiling || mod::tick::isMSPTing) { + TIMER_START + original(serverLevel); + modInstance->lightTick(); + modInstance->heavyTick(); + mod::tick::staticWork(); + TIMER_END + if (mod::tick::isMSPTing) { + //发送mspt信息 + bool isRedstoneTick = modInstance->getLevel() + ->getDimFromID(0) + ->isRedstoneTick(); + mod::tick::sendMsptInfo(timeReslut, isRedstoneTick); + mod::tick::isMSPTing = false; + } + if (mod::tick::gameProfiler.inProfiling) { + mod::tick::gameProfiler.serverLevelTickTime += timeReslut; + mod::tick::gameProfiler.currentRound--; + if (mod::tick::gameProfiler.currentRound == 0) { + mod::tick::gameProfiler.inProfiling = false; + mod::tick::gameProfiler.print(); + mod::tick::gameProfiler.reset(); + } } + } else { + original(serverLevel); + modInstance->lightTick(); + modInstance->heavyTick(); + mod::tick::staticWork(); } - } else { - original(serverLevel); - modInstance->lightTick(); - modInstance->heavyTick(); - mod::tick::staticWork(); - } - break; + break; - case mod::tick::Slow: - if (mod::tick::slowDownCounter % mod::tick::SlowDownTimes == 0) { - original(serverLevel); - modInstance->lightTick(); + case mod::tick::Slow: + if (mod::tick::slowDownCounter % mod::tick::SlowDownTimes == 0) { + original(serverLevel); + modInstance->lightTick(); + modInstance->heavyTick(); + } + mod::tick::slowDownCounter = + (mod::tick::slowDownCounter + 1) % mod::tick::SlowDownTimes; + break; + case mod::tick::Forward: + for (auto i = 0; i < mod::tick::forwardTickNum; i++) { + original(serverLevel); + modInstance->lightTick(); + } + trapdoor::broadcastMsg(trapdoor::LANG("tick.fw.end"), + mod::tick::forwardTickNum); + mod::tick::forwardTickNum = 0; + mod::tick::tickStatus = mod::tick::lastTickStats; + break; + case mod::tick::Wrap: + for (int i = 0; i < mod::tick::wrapSpeed; ++i) { + original(serverLevel); + modInstance->lightTick(); + } modInstance->heavyTick(); - } - mod::tick::slowDownCounter = - (mod::tick::slowDownCounter + 1) % mod::tick::SlowDownTimes; - break; - case mod::tick::Forward: - for (auto i = 0; i < mod::tick::forwardTickNum; i++) { - original(serverLevel); - modInstance->lightTick(); - } - trapdoor::broadcastMsg(trapdoor::LANG("tick.fw.end"), - mod::tick::forwardTickNum); - mod::tick::forwardTickNum = 0; - mod::tick::tickStatus = mod::tick::lastTickStats; - break; - case mod::tick::Wrap: - for (int i = 0; i < mod::tick::wrapSpeed; ++i) { - original(serverLevel); - modInstance->lightTick(); - } - modInstance->heavyTick(); - break; + break; } } -// ServerPlayer::tickWorld -THook(void, MSSYM_B1QA9tickWorldB1AE12ServerPlayerB2AAE13UEAAHAEBUTickB3AAAA1Z, - trapdoor::Actor *p, void *tick) { - original(p, tick); -} +//// ServerPlayer::tickWorld +// THook(void, SymHook::Serv , +// trapdoor::Actor *p, void *tick) { +// original(p, tick); +// } // Dimension::tick -THook(void, MSSYM_B1QA4tickB1AA9DimensionB2AAA7UEAAXXZ, void *dim) { +THook(void, Dimension_tick_39d89862, void *dim) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(dim); @@ -317,10 +320,8 @@ THook(void, MSSYM_B1QA4tickB1AA9DimensionB2AAA7UEAAXXZ, void *dim) { } } // LevelChunk::tick -THook( - void, - MSSYM_B1QA4tickB1AE10LevelChunkB2AAE20QEAAXAEAVBlockSourceB2AAA8AEBUTickB3AAAA1Z, - void *levelChunk, trapdoor::BlockSource *blockSource, size_t *tick) { +THook(void, LevelChunk_tick_9d729ccd, void *levelChunk, + trapdoor::BlockSource *blockSource, size_t *tick) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(levelChunk, blockSource, tick); @@ -333,10 +334,8 @@ THook( } // LevelChunk::tickBlocks -THook(void, - MSSYM_B1QE10tickBlocksB1AE10LevelChunkB2AAE20QEAAXAEAVBlockSourceB3AAAA1Z, - void *levelChunk, void *blockSource, INT64 a3, int a4) { - +THook(void, LevelChunk_tickBlocks_66280c26, void *levelChunk, void *blockSource, + INT64 a3, int a4) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(levelChunk, blockSource, a3, a4); @@ -348,10 +347,8 @@ THook(void, } // LevelChunk::tickBlockEntities -THook( - void, - MSSYM_B1QE17tickBlockEntitiesB1AE10LevelChunkB2AAE20QEAAXAEAVBlockSourceB3AAAA1Z, - void *levelChunk, void *blockSource) { +THook(void, LevelChunk_tickBlockEntities_41f9b2ca, void *levelChunk, + void *blockSource) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(levelChunk, blockSource); @@ -388,11 +385,9 @@ THook( // BlockTickingQueue::pendingTicks // the server will crash if hook this function -THook( - void, - MSSYM_B1QE16tickPendingTicksB1AE17BlockTickingQueueB2AAA4QEAAB1UE16NAEAVBlockSourceB2AAA8AEBUTickB2AAA1HB1UA1NB1AA1Z, - void *queue, trapdoor::BlockSource *source, const int *until, int max, - bool instalTick) { +THook(void, BlockTickingQueue_tickPendingTicks_e4625213, void *queue, + trapdoor::BlockSource *source, const int *until, int max, + bool instalTick) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(queue, source, until, max, instalTick); @@ -403,8 +398,8 @@ THook( } } -// Dimension::tick -THook(void, MSSYM_B1QE12tickRedstoneB1AA9DimensionB2AAA7UEAAXXZ, void *dim) { +// Dimension::tickRedstone +THook(void, Dimension_tickRedstone_c8a7e6e5, void *dim) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(dim); @@ -418,7 +413,7 @@ THook(void, MSSYM_B1QE12tickRedstoneB1AA9DimensionB2AAA7UEAAXXZ, void *dim) { // printf("69:%d 68:%d\n", v1, v2); } -THook(void, MSSYM_tickEntitySystemsLevelUEAAXXZ, void *level) { +THook(void, Level_tickEntitySystems_251e10ba, void *level) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(level); @@ -448,8 +443,7 @@ THook(void, MSSYM_tickEntitySystemsLevelUEAAXXZ, void *level) { //} // pendingAdd -THook(void, MSSYM_B1QE18processPendingAddsB1AE17CircuitSceneGraphB2AAA7AEAAXXZ, - void *graph) { +THook(void, CircuitSceneGraph_processPendingAdds_9d2954e5, void *graph) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(graph); @@ -461,10 +455,7 @@ THook(void, MSSYM_B1QE18processPendingAddsB1AE17CircuitSceneGraphB2AAA7AEAAXXZ, } // pnding remove -THook( - void, - MSSYM_B1QE15removeComponentB1AE17CircuitSceneGraphB2AAE17AEAAXAEBVBlockPosB3AAAA1Z, - void *graph, void *bs) { +THook(void, CircuitSceneGraph_removeComponent_1f06081d, void *graph, void *bs) { if (mod::tick::gameProfiler.inProfiling) { TIMER_START original(graph, bs); @@ -476,8 +467,8 @@ THook( } //实体性能分析的钩子函数 -THook(void, MSSYM_B1QA4tickB1AA5ActorB2AAA4QEAAB1UE16NAEAVBlockSourceB3AAAA1Z, - trapdoor::Actor *actor, trapdoor::BlockSource *blockSource) { +THook(void, Actor_tick_8589defc, trapdoor::Actor *actor, + trapdoor::BlockSource *blockSource) { if (mod::tick::getActorProfiler().inProfiling) { auto &profiler = mod::tick::getActorProfiler(); TIMER_START diff --git a/mod/tick/GameTick.h b/mod/tick/GameTick.h index f6c5df7..9965816 100644 --- a/mod/tick/GameTick.h +++ b/mod/tick/GameTick.h @@ -5,24 +5,18 @@ #ifndef TRAPDOOR_GAMETICK_H #define TRAPDOOR_GAMETICK_H +#include +#include #include "SimpleProfiler.h" -#include "lib/mod.h" +#include "entity/Actor.h" #include "lib/SymHook.h" -#include "village/Village.h" -#include -#include +#include "lib/mod.h" #include "tools/Message.h" -#include "entity/Actor.h" +#include "village/Village.h" namespace mod::tick { - enum WorldTickStatus { - Frozen, - Normal, - Slow, - Forward, - Wrap - }; + enum WorldTickStatus { Frozen, Normal, Slow, Forward, Wrap }; WorldTickStatus getTickStatus(); @@ -42,12 +36,11 @@ namespace mod::tick { void queryStatus(trapdoor::Actor *player); - void registerTickCommand(trapdoor::CommandManager &commandManager); void registerProfileCommand(trapdoor::CommandManager &commandManager); void mspt(); -} +} // namespace mod::tick -#endif //TRAPDOOR_GAMETICK_H +#endif // TRAPDOOR_GAMETICK_H diff --git a/mod/tick/SimpleProfiler.cpp b/mod/tick/SimpleProfiler.cpp index c36591b..e75f099 100644 --- a/mod/tick/SimpleProfiler.cpp +++ b/mod/tick/SimpleProfiler.cpp @@ -3,85 +3,90 @@ // #include "SimpleProfiler.h" + #include "Message.h" #include "entity/Actor.h" #include "tools/MsgBuilder.h" namespace mod { -namespace { - -void addShowItem(trapdoor::MessageBuilder &builder, const std::string &prefix, - const std::string &key, float value) { + namespace { - builder.sText(prefix, trapdoor::MSG_COLOR::GRAY) - .sText(key + ": ", trapdoor::MSG_COLOR::WHITE) - .sTextF(trapdoor::MSG_COLOR::WHITE | trapdoor::MessageBuilder::BOLD, - "%.3fms\n", value); -} -} // namespace + void addShowItem(trapdoor::MessageBuilder &builder, + const std::string &prefix, const std::string &key, + float value) { + builder.sText(prefix, trapdoor::MSG_COLOR::GRAY) + .sText(key + ": ", trapdoor::MSG_COLOR::WHITE) + .sTextF( + trapdoor::MSG_COLOR::WHITE | trapdoor::MessageBuilder::BOLD, + "%.3fms\n", value); + } + } // namespace -// serverLevelTickTime = 0; //mspt -// levelEntityTickTime = 0; //实体更新 O -// redstoneTickTime = 0; //红石更新O -// dimensionTickTime = 0; //区块加载卸载&村庄 O -// chunkTickTime = 0; //区块更新 O -// chunkBlockEntityTickTime = 0; //方块实体更新 -// chunkRandomTickTime = 0; //随机刻更新 -// chunkPendingTickTime = 0; //计划刻更新 -// chunkRandomPendingTickTime = 0; //随机计划刻更新 -// levelEntitySystemTickTime = 0; //实体系统更新 O + // serverLevelTickTime = 0; //mspt + // levelEntityTickTime = 0; //实体更新 O + // redstoneTickTime = 0; //红石更新O + // dimensionTickTime = 0; //区块加载卸载&村庄 O + // chunkTickTime = 0; //区块更新 O + // chunkBlockEntityTickTime = 0; //方块实体更新 + // chunkRandomTickTime = 0; //随机刻更新 + // chunkPendingTickTime = 0; //计划刻更新 + // chunkRandomPendingTickTime = 0; //随机计划刻更新 + // levelEntitySystemTickTime = 0; //实体系统更新 O -void SimpleProfiler::print() const { - auto rounds = static_cast(this->totalRound * 1000); - int tps = static_cast(1000.0 / (serverLevelTickTime / rounds)); - if (tps > 20) - tps = 20; - trapdoor::MessageBuilder builder; - auto totalRedstoneTickTime = - static_cast(redstoneTickTime + redstonePendingUpdateTime + - redstonePendingRemoveTime) / - rounds; + void SimpleProfiler::print() const { + auto rounds = static_cast(this->totalRound * 1000); + int tps = static_cast(1000.0 / (serverLevelTickTime / rounds)); + if (tps > 20) tps = 20; + trapdoor::MessageBuilder builder; + auto totalRedstoneTickTime = + static_cast(redstoneTickTime + redstonePendingUpdateTime + + redstonePendingRemoveTime) / + rounds; - builder.textF("MSPT: "); - auto color = - tps < 20 ? trapdoor::MSG_COLOR::RED : trapdoor::MSG_COLOR::WHITE; - builder.sTextF(color, "%.3fms", serverLevelTickTime / rounds) - .text(" TPS: ") - .sTextF(color, "%d", tps) - .textF(" Chunks: %d\n", tickChunkNum / this->totalRound); - addShowItem(builder, " - ", "Redstone", totalRedstoneTickTime); - addShowItem(builder, " - ", "SignalUpdate", redstoneTickTime / rounds); + builder.textF("MSPT: "); + auto color = + tps < 20 ? trapdoor::MSG_COLOR::RED : trapdoor::MSG_COLOR::WHITE; + builder.sTextF(color, "%.3fms", serverLevelTickTime / rounds) + .text(" TPS: ") + .sTextF(color, "%d", tps) + .textF(" Chunks: %d\n", tickChunkNum / this->totalRound); + addShowItem(builder, " - ", "Redstone", totalRedstoneTickTime); + addShowItem(builder, " - ", "SignalUpdate", + redstoneTickTime / rounds); - builder.sText(" - ", trapdoor::MSG_COLOR::GRAY) - .text("PendingUpdate: Invalid\n"); - addShowItem(builder, " - ", "PendingRemove", - redstonePendingRemoveTime / rounds); + builder.sText(" - ", trapdoor::MSG_COLOR::GRAY) + .text("PendingUpdate: Invalid\n"); + addShowItem(builder, " - ", "PendingRemove", + redstonePendingRemoveTime / rounds); - addShowItem(builder, " - ", "EntitySystem", - levelEntitySystemTickTime / rounds); - addShowItem(builder, " - ", "Chunk (un)load & village", - dimensionTickTime / rounds); + addShowItem(builder, " - ", "EntitySystem", + levelEntitySystemTickTime / rounds); + addShowItem(builder, " - ", "Chunk (un)load & village", + dimensionTickTime / rounds); - addShowItem(builder, " - ", "ChunkTick", chunkTickTime / rounds); + addShowItem(builder, " - ", "ChunkTick", chunkTickTime / rounds); - addShowItem(builder, " - ", "BlockEntities", - chunkBlockEntityTickTime / rounds); - addShowItem(builder, " - ", "RandomTick", chunkRandomTickTime / rounds); + addShowItem(builder, " - ", "BlockEntities", + chunkBlockEntityTickTime / rounds); + addShowItem(builder, " - ", "RandomTick", + chunkRandomTickTime / rounds); - addShowItem(builder, " - ", "PendingTick", chunkPendingTickTime / rounds); + addShowItem(builder, " - ", "PendingTick", + chunkPendingTickTime / rounds); - builder.broadcast(); + builder.broadcast(); - // .textF(" - Chunk tick: %.3fms (%d)\n", chunkTickTime / rounds, - // tickChunkNum / totalRound) - // .textF(" - Block entity: %.3fms\n", - // chunkBlockEntityTickTime / rounds) - // .textF(" - Random tick: %.3fms\n", chunkRandomTickTime / rounds) - // .textF(" - Pending tick: %.3f/%.3fms\n", - // chunkRandomPendingTickTime / rounds, - // chunkPendingTickTime / rounds) - // .text(" - Entity tick: may be the rest") - // .broadcast(); -} -} // namespace mod + // .textF(" - Chunk tick: %.3fms (%d)\n", chunkTickTime / rounds, + // tickChunkNum / totalRound) + // .textF(" - Block entity: %.3fms\n", + // chunkBlockEntityTickTime / rounds) + // .textF(" - Random tick: %.3fms\n", chunkRandomTickTime / + // rounds) + // .textF(" - Pending tick: %.3f/%.3fms\n", + // chunkRandomPendingTickTime / rounds, + // chunkPendingTickTime / rounds) + // .text(" - Entity tick: may be the rest") + // .broadcast(); + } +} // namespace mod diff --git a/mod/tick/SimpleProfiler.h b/mod/tick/SimpleProfiler.h index 2086043..9d9b504 100644 --- a/mod/tick/SimpleProfiler.h +++ b/mod/tick/SimpleProfiler.h @@ -6,26 +6,31 @@ #define MOD_SIMPLEPROFILER_H #include + #include "entity/Actor.h" #include "tools/noncopyable .h" typedef std::chrono::high_resolution_clock timer_clock; #define TIMER_START auto start = timer_clock::now(); -#define TIMER_END auto elapsed = timer_clock::now() - start; long long timeReslut = std::chrono::duration_cast(elapsed).count(); +#define TIMER_END \ + auto elapsed = timer_clock::now() - start; \ + long long timeReslut = \ + std::chrono::duration_cast(elapsed) \ + .count(); namespace mod { typedef long long microsecond_t; class SimpleProfiler : noncopyable { - public: - microsecond_t serverLevelTickTime = 0; //mspt - microsecond_t redstoneTickTime = 0; //红石更新 - microsecond_t dimensionTickTime = 0; //区块加载卸载&村庄 - microsecond_t chunkTickTime = 0; //区块更新 - microsecond_t chunkBlockEntityTickTime = 0; //方块实体更新 - microsecond_t chunkRandomTickTime = 0; //随机刻更新 - microsecond_t chunkPendingTickTime = 0; //计划刻更新 - microsecond_t chunkRandomPendingTickTime = 0; //随机计划刻更新 + public: + microsecond_t serverLevelTickTime = 0; // mspt + microsecond_t redstoneTickTime = 0; //红石更新 + microsecond_t dimensionTickTime = 0; //区块加载卸载&村庄 + microsecond_t chunkTickTime = 0; //区块更新 + microsecond_t chunkBlockEntityTickTime = 0; //方块实体更新 + microsecond_t chunkRandomTickTime = 0; //随机刻更新 + microsecond_t chunkPendingTickTime = 0; //计划刻更新 + microsecond_t chunkRandomPendingTickTime = 0; //随机计划刻更新 microsecond_t levelEntitySystemTickTime = 0; microsecond_t redstonePendingUpdateTime = 0; microsecond_t redstonePendingAddTime = 0; @@ -37,19 +42,19 @@ namespace mod { bool inProfiling = false; void reset() { - serverLevelTickTime = 0; //mspt - redstoneTickTime = 0; //红石更新 - dimensionTickTime = 0; //区块加载卸载&村庄 - chunkTickTime = 0; //区块更新 - chunkBlockEntityTickTime = 0; //方块实体更新 - chunkRandomTickTime = 0; //随机刻更新 - chunkPendingTickTime = 0; //计划刻更新 - chunkRandomPendingTickTime = 0; //随机计划刻更新 - levelEntitySystemTickTime = 0; //实体系统更新 + serverLevelTickTime = 0; // mspt + redstoneTickTime = 0; //红石更新 + dimensionTickTime = 0; //区块加载卸载&村庄 + chunkTickTime = 0; //区块更新 + chunkBlockEntityTickTime = 0; //方块实体更新 + chunkRandomTickTime = 0; //随机刻更新 + chunkPendingTickTime = 0; //计划刻更新 + chunkRandomPendingTickTime = 0; //随机计划刻更新 + levelEntitySystemTickTime = 0; //实体系统更新 redstonePendingAddTime = 0; redstonePendingRemoveTime = 0; redstonePendingUpdateTime = 0; - trapdoorModTickTime = 0; //模组自身的更新时间(heavy tick) + trapdoorModTickTime = 0; //模组自身的更新时间(heavy tick) tickChunkNum = 0; currentRound = 0; } @@ -57,7 +62,6 @@ namespace mod { void print() const; }; +} // namespace mod -} - -#endif //MOD_SIMPLEPROFILER_H +#endif // MOD_SIMPLEPROFILER_H diff --git a/mod/village/POIInstance.cpp b/mod/village/POIInstance.cpp index b62b7c8..e7abca2 100644 --- a/mod/village/POIInstance.cpp +++ b/mod/village/POIInstance.cpp @@ -3,27 +3,8 @@ // #include "POIInstance.h" -#include "lib/mod.h" -#include "lib/SymHook.h" - -namespace mod { - DwellerComponent *mod::getDwellerComponentFromActor(trapdoor::Actor *actor) { - return SYM_CALL( - mod::DwellerComponent*(*)(trapdoor::Actor * ), - SymHook::MSSYM_B3QQDE15tryGetComponentB1AE17VDwellerComponentB3AAAA5ActorB2AAE24QEAAPEAVDwellerComponentB2AAA2XZ, - actor - ); - } - trapdoor::BlockPos *DwellerComponent::getVillageCenter(trapdoor::Actor *actor) { - trapdoor::BlockPos pos; - return SYM_CALL( - trapdoor::BlockPos*(*)(DwellerComponent * , trapdoor::BlockPos *, trapdoor::Actor * actor), - SymHook::MSSYM_B1QE16getVillageCenterB1AE16DwellerComponentB2AAA4QEBAB1QE10AVBlockPosB2AAA9AEBVActorB3AAAA1Z, - this, - &pos, - actor - ); - } -}; +#include "lib/SymHook.h" +#include "lib/mod.h" +namespace mod {}; diff --git a/mod/village/POIInstance.h b/mod/village/POIInstance.h index b23d57e..3c24d13 100644 --- a/mod/village/POIInstance.h +++ b/mod/village/POIInstance.h @@ -10,35 +10,29 @@ namespace mod { -enum POIType : int32_t { - InvalidPOI = -1, - Bed = 0, - MeetingArea = 1, - JobSite = 2, - Count = 3 -}; - -//!这个类不要做任何修改 -class POIInstance { - public: - char gap[0x98]; - trapdoor::BlockPos poiPos; //位置 - uint64_t ownerCount = 0; //拥有者数量 - uint64_t ownerCapacity = 0; //容量 - uint64_t weight{}; //权重 - float radius = 0; //半径 - POIType poiType; //类型 - std::string soundEvent; - int16_t arriveFailureCount = 0; //到达失败的次数 - bool useBoundingBox = true; //? -}; - -class DwellerComponent { - public: - trapdoor::BlockPos *getVillageCenter(trapdoor::Actor *actor); -}; - -DwellerComponent *getDwellerComponentFromActor(trapdoor::Actor *actor); -} // namespace mod - -#endif // MOD_POIINSTANCE_H + enum POIType : int32_t { + InvalidPOI = -1, + Bed = 0, + MeetingArea = 1, + JobSite = 2, + Count = 3 + }; + + //!这个类不要做任何修改 + class POIInstance { + public: + char gap[0x98]; + trapdoor::BlockPos poiPos; //位置 + uint64_t ownerCount = 0; //拥有者数量 + uint64_t ownerCapacity = 0; //容量 + uint64_t weight{}; //权重 + float radius = 0; //半径 + POIType poiType; //类型 + std::string soundEvent; + int16_t arriveFailureCount = 0; //到达失败的次数 + bool useBoundingBox = true; //? + }; + +} // namespace mod + +#endif // MOD_POIINSTANCE_H diff --git a/mod/village/Village.cpp b/mod/village/Village.cpp index 3412ce7..659ef52 100644 --- a/mod/village/Village.cpp +++ b/mod/village/Village.cpp @@ -2,19 +2,25 @@ // Created by xhy on 2020/8/25. // #include "Village.h" + +#include + #include "BDSMod.h" #include "TrapdoorMod.h" #include "graphics/Graphics.h" #include "graphics/Particle.h" -#include "player/Player.h" #include "tools/Message.h" #include "tools/MsgBuilder.h" -#include using namespace SymHook; + #include -#include // for EXCEPTION_ACCESS_VIOLATION +#include // for EXCEPTION_ACCESS_VIOLATION // village tick +#include +#include +#include + #include "BDSMod.h" #include "POIInstance.h" #include "entity/Actor.h" @@ -22,478 +28,478 @@ using namespace SymHook; #include "lib/Remotery.h" #include "tools/MsgBuilder.h" #include "world/Level.h" -#include -#include -#include + namespace mod { -namespace { -const size_t BOUND_OFFSET = 104; -// from Village::_trySpawnDefenderDwellers -const size_t POPULATION_OFFSET = 22; -// from Village::_trySpawnDefenderDwellers -const size_t GOLEM_NUM_OFFSET = 30; -// from Village::_trySpawnDefenderDwellers -const size_t DWELLER_POI_MAP_OFFSET = 96; - -const size_t DWELLER_TICK_MAP_OFFSET = 160; - -struct DwellerData { - uint64_t tick; - trapdoor::BlockPos pos; -}; - -// typedef std::vector> DwellerData; -typedef std::array, - 4> - DwellerTickMapType; - -typedef std::unordered_map, 3>, - std::hash> - DwellerPOIMapType; - -DwellerPOIMapType *getDwellerPOIMap(Village *v) { - return reinterpret_cast((char *)v + - DWELLER_POI_MAP_OFFSET); -} + namespace { + const size_t BOUND_OFFSET = 104; + // from Village::_trySpawnDefenderDwellers + const size_t POPULATION_OFFSET = 22; + // from Village::_trySpawnDefenderDwellers + const size_t GOLEM_NUM_OFFSET = 30; + // from Village::_trySpawnDefenderDwellers + const size_t DWELLER_POI_MAP_OFFSET = 96; + + const size_t DWELLER_TICK_MAP_OFFSET = 160; + + struct DwellerData { + uint64_t tick; + trapdoor::BlockPos pos; + }; + + // typedef std::vector> DwellerData; + typedef std::array< + std::unordered_map, + 4> + DwellerTickMapType; + + typedef std::unordered_map, 3>, + std::hash> + DwellerPOIMapType; + + DwellerPOIMapType *getDwellerPOIMap(Village *v) { + return reinterpret_cast( + (char *)v + DWELLER_POI_MAP_OFFSET); + } -DwellerTickMapType *getDwellerTicklMap(Village *v) { - return reinterpret_cast((char *)v + - DWELLER_TICK_MAP_OFFSET); -} + DwellerTickMapType *getDwellerTicklMap(Village *v) { + return reinterpret_cast( + (char *)v + DWELLER_TICK_MAP_OFFSET); + } -} // namespace + } // namespace -// get village population -int Village::getPopulation() { - return (int)*((int64_t *)this + POPULATION_OFFSET); -} + // get village population + int Village::getPopulation() { + return (int)*((int64_t *)this + POPULATION_OFFSET); + } -// get village owned iron golem num -int Village::getIronGolemNum() { - return (int)*((int64_t *)this + GOLEM_NUM_OFFSET); -} + // get village owned iron golem num + int Village::getIronGolemNum() { + return (int)*((int64_t *)this + GOLEM_NUM_OFFSET); + } -// get village owned bed poi count(max is villager num + 32) -int Village::getBedPOICount() { - return SYM_CALL(int (*)(Village *), - MSSYM_B1QE14getBedPOICountB1AA7VillageB2AAA4QEBAB1UA3KXZ, - this); -} + // get village owned bed poi count(max is villager num + 32) + int Village::getBedPOICount() { + return SYM_CALL(int (*)(Village *), Village_getBedPOICount_016a7e2f, + this); + } -// get worked villager num -int Village::getWorkedVillagerNum() { - // from Village::_trySpawnDefenderDwellers - auto timeOfDay = *(reinterpret_cast(this) + 60) - 24000; - auto begin = *(reinterpret_cast(this) + 85); - auto end = *(reinterpret_cast(this) + 86); - int num; - for (num = 0; begin != end; begin += 16) { - if (*(int64_t *)(begin + 8) > timeOfDay) - ++num; + // get worked villager num + int Village::getWorkedVillagerNum() { + // from Village::_trySpawnDefenderDwellers + auto timeOfDay = *(reinterpret_cast(this) + 60) - 24000; + auto begin = *(reinterpret_cast(this) + 85); + auto end = *(reinterpret_cast(this) + 86); + int num; + for (num = 0; begin != end; begin += 16) { + if (*(int64_t *)(begin + 8) > timeOfDay) ++num; + } + return num; } - return num; -} -// check can actor iron golem -bool Village::canSpawnIronGolem() { - auto population = getPopulation(); - auto workedNum = getWorkedVillagerNum(); - auto golemNum = getIronGolemNum(); - auto bedNum = getBedPOICount(); - int maxValue = 20 > population ? 20 : population; - return (float)workedNum > population * 0.75 && golemNum < population / 10 && - bedNum > maxValue; -} + // check can actor iron golem + bool Village::canSpawnIronGolem() { + auto population = getPopulation(); + auto workedNum = getWorkedVillagerNum(); + auto golemNum = getIronGolemNum(); + auto bedNum = getBedPOICount(); + int maxValue = 20 > population ? 20 : population; + return (float)workedNum > population * 0.75 && + golemNum < population / 10 && bedNum > maxValue; + } -// get village center -trapdoor::Vec3 Village::getCenter() { return this->getBounds().getCenter(); } + // get village center + trapdoor::Vec3 Village::getCenter() { + return this->getBounds().getCenter(); + } -// get village bounds -trapdoor::AABB Village::getBounds() { - return *reinterpret_cast((float *)this + BOUND_OFFSET); -} + // get village bounds + trapdoor::AABB Village::getBounds() { + return *reinterpret_cast((float *)this + + BOUND_OFFSET); + } -// get village radius -float Village::getRadius() { - return SYM_CALL(float (*)(Village *), - MSSYM_B1QE20getApproximateRadiusB1AA7VillageB2AAA7QEBAMXZ, - this); -} + // get village radius + float Village::getRadius() { + return SYM_CALL(float (*)(Village *), + Village_getApproximateRadius_626d2648, this); + } -trapdoor::AABB Village::getPOIRange() { - auto bounds = this->getBounds(); - return trapdoor::AABB(bounds.p1 - Vec3(64, 64, 64), - bounds.p2 + Vec3(64, 64, 64)); -} + trapdoor::AABB Village::getPOIRange() { + auto bounds = this->getBounds(); + return trapdoor::AABB(bounds.p1 - Vec3(64, 64, 64), + bounds.p2 + Vec3(64, 64, 64)); + } -trapdoor::AABB Village::getGolemSpawnArea() { - auto center = this->getCenter(); - return trapdoor::AABB(center - Vec3(8, 3, 8), center + Vec3(8, 3, 8)); -} + trapdoor::AABB Village::getGolemSpawnArea() { + auto center = this->getCenter(); + return trapdoor::AABB(center - Vec3(8, 3, 8), center + Vec3(8, 3, 8)); + } -void Village::showVillagerStatus(int vIdx) { - auto *map = getDwellerPOIMap(this); - int idx = 1; - const char *icons[3] = {"☾", "⍾", "☕"}; - for (auto &villager : *map) { - auto actor = trapdoor::bdsMod->fetchEntity(villager.first.uid, false); - if (actor) { - trapdoor::MessageBuilder builder; - builder.textF("[%d] %d", vIdx, idx); - ++idx; - for (int index = 0; index < 3; ++index) { - auto poi = villager.second[index].lock(); - if (poi) { - builder.sTextF(MSG_COLOR::GREEN, " %s", icons[index]); - } else { - builder.sTextF(MSG_COLOR::RED, " %s", icons[index]); + void Village::showVillagerStatus(int vIdx) { + auto *map = getDwellerPOIMap(this); + int idx = 1; + const char *icons[3] = {"☾", "⍾", "☕"}; + for (auto &villager : *map) { + auto actor = + trapdoor::bdsMod->fetchEntity(villager.first.uid, false); + if (actor) { + trapdoor::MessageBuilder builder; + builder.textF("[%d] %d", vIdx, idx); + ++idx; + for (int index = 0; index < 3; ++index) { + auto poi = villager.second[index].lock(); + if (poi) { + builder.sTextF(MSG_COLOR::GREEN, " %s", icons[index]); + } else { + builder.sTextF(MSG_COLOR::RED, " %s", icons[index]); + } } + actor->setNameTag(builder.get()); } - actor->setNameTag(builder.get()); } + this->showTimeStamp(); } - this->showTimeStamp(); -} -// void Village::showTimeStamp() { -// auto *dwellerList = -// reinterpret_cast, 4> * >((char *) this + -// 152); -// for (int i = 1; i < 4; i++) { -// auto dwellers = dwellerList->operator[](i); -// for (const auto &d:dwellers) { -// auto actor = trapdoor::bdsMod->fetchEntity(d.first.uid, -// false); if (actor) { -// actor->setNameTag(std::to_string(d.second)); -// } -// } -// } -// } - -std::string Village::getDebugInfo() { - using namespace trapdoor; - trapdoor::MessageBuilder builder; - auto pos = this->getCenter().toBlockPos(); - auto minPos = this->getBounds().p1.toBlockPos(); - auto maxPos = this->getBounds().p2.toBlockPos(); - builder.text("Village: ") - .pos(pos) - .text("\n- Bounds: ") - .pos(minPos) - .text(" , ") - .pos(maxPos) - .text("\n") - .text("- Radius: ") - .num(this->getRadius()) - .text("\n") - .text("Dweller: ") - .sTextF(MSG_COLOR::GREEN, "%d / %d %d\n", getWorkedVillagerNum(), - getPopulation(), getIronGolemNum()) - .text("POIS:\n Bed | Work |\n"); - auto *map = getDwellerPOIMap(this); - bool existAlarm = false; - for (auto &villager : *map) { - for (int index = 0; index < 3; ++index) { - if (index == 0) { - builder.text("|"); - } + // void Village::showTimeStamp() { + // auto *dwellerList = + // reinterpret_cast, 4> * >((char *) + // this + 152); + // for (int i = 1; i < 4; i++) { + // auto dwellers = dwellerList->operator[](i); + // for (const auto &d:dwellers) { + // auto actor = trapdoor::bdsMod->fetchEntity(d.first.uid, + // false); if (actor) { + // actor->setNameTag(std::to_string(d.second)); + // } + // } + // } + // } + + std::string Village::getDebugInfo() { + using namespace trapdoor; + trapdoor::MessageBuilder builder; + auto pos = this->getCenter().toBlockPos(); + auto minPos = this->getBounds().p1.toBlockPos(); + auto maxPos = this->getBounds().p2.toBlockPos(); + builder.text("Village: ") + .pos(pos) + .text("\n- Bounds: ") + .pos(minPos) + .text(" , ") + .pos(maxPos) + .text("\n") + .text("- Radius: ") + .num(this->getRadius()) + .text("\n") + .text("Dweller: ") + .sTextF(MSG_COLOR::GREEN, "%d / %d %d\n", getWorkedVillagerNum(), + getPopulation(), getIronGolemNum()) + .text("POIS:\n Bed | Work |\n"); + auto *map = getDwellerPOIMap(this); + bool existAlarm = false; + for (auto &villager : *map) { + for (int index = 0; index < 3; ++index) { + if (index == 0) { + builder.text("|"); + } - auto poi = villager.second[index].lock(); - if (index == 1) { - if (poi) - existAlarm = true; - continue; - } - if (poi) { - builder - .sTextF(MSG_COLOR::WHITE, " %-4d %-4d %-4d ", - poi->poiPos.x, poi->poiPos.y, poi->poiPos.z) - .text("|"); - } else { - builder.sText(" (null) ", MSG_COLOR::GRAY) - .text("|"); - } - if (index == 2) { - builder.text("\n"); + auto poi = villager.second[index].lock(); + if (index == 1) { + if (poi) existAlarm = true; + continue; + } + if (poi) { + builder + .sTextF(MSG_COLOR::WHITE, " %-4d %-4d %-4d ", + poi->poiPos.x, poi->poiPos.y, poi->poiPos.z) + .text("|"); + } else { + builder.sText(" (null) ", MSG_COLOR::GRAY) + .text("|"); + } + if (index == 2) { + builder.text("\n"); + } } } + builder.textF("Alarm: %d", existAlarm); + return builder.get(); } - builder.textF("Alarm: %d", existAlarm); - return builder.get(); -} -bool Village::printVillagerInfo(trapdoor::Actor *player, trapdoor::Actor *v) { - // auto *map = getDwellerPOIMap(this); - // for (auto &villager : *map) { - // auto actor = trapdoor::bdsMod->fetchEntity(villager.first.uid, - // false); if (actor && v && actor == v) { - // trapdoor::MessageBuilder builder; - // auto center = this->getCenter().toBlockPos(); - // builder.textF("center: [%d %d %d]\n", center.x, center.y, - // center.z); auto bed = villager.second[0].lock(); auto alarm = - // villager.second[1].lock(); auto work = villager.second[2].lock(); - // if (bed) { - // builder.text("Bed position: ").pos(bed->poiPos); - // } - // if (alarm) { - // builder.text("\nAlarm position: ").pos(alarm->poiPos); - // } - // if (work) { - // builder.text("\nWork position: ").pos(work->poiPos); - // } - // builder.send(player); - // return true; - // } - // } - return false; -} + bool Village::printVillagerInfo(trapdoor::Actor *player, + trapdoor::Actor *v) { + // auto *map = getDwellerPOIMap(this); + // for (auto &villager : *map) { + // auto actor = trapdoor::bdsMod->fetchEntity(villager.first.uid, + // false); if (actor && v && actor == v) { + // trapdoor::MessageBuilder builder; + // auto center = this->getCenter().toBlockPos(); + // builder.textF("center: [%d %d %d]\n", center.x, center.y, + // center.z); auto bed = villager.second[0].lock(); auto alarm = + // villager.second[1].lock(); auto work = + // villager.second[2].lock(); if (bed) { + // builder.text("Bed position: ").pos(bed->poiPos); + // } + // if (alarm) { + // builder.text("\nAlarm position: ").pos(alarm->poiPos); + // } + // if (work) { + // builder.text("\nWork position: ").pos(work->poiPos); + // } + // builder.send(player); + // return true; + // } + // } + return false; + } -//这个96是一个POI分配表 -void Village::removeAllTags() { - auto *tickMap = getDwellerTicklMap(this); - for (auto i : *tickMap) { - for (auto &v : i) { - auto actor = trapdoor::bdsMod->fetchEntity(v.first.uid, false); - if (actor) { - actor->setNameTag(""); + //这个96是一个POI分配表 + void Village::removeAllTags() { + auto *tickMap = getDwellerTicklMap(this); + for (auto i : *tickMap) { + for (auto &v : i) { + auto actor = trapdoor::bdsMod->fetchEntity(v.first.uid, false); + if (actor) { + actor->setNameTag(""); + } } } } -} -void Village::showTimeStamp() { - auto *tickMap = getDwellerTicklMap(this); - int index = 0; - for (auto i : *tickMap) { - for (auto &v : i) { - auto actor = trapdoor::bdsMod->fetchEntity(v.first.uid, false); - if (actor) { - if (index == 0) { - actor->setNameTag(actor->getNameTag() + " " + - std::to_string(v.second.tick)); - } else { - actor->setNameTag(std::to_string(v.second.tick)); + void Village::showTimeStamp() { + auto *tickMap = getDwellerTicklMap(this); + int index = 0; + for (auto i : *tickMap) { + for (auto &v : i) { + auto actor = trapdoor::bdsMod->fetchEntity(v.first.uid, false); + if (actor) { + if (index == 0) { + actor->setNameTag(actor->getNameTag() + " " + + std::to_string(v.second.tick)); + } else { + actor->setNameTag(std::to_string(v.second.tick)); + } } } - } - index++; + index++; + } } -} -void VillageHelper::clear() { villageList.clear(); } + void VillageHelper::clear() { villageList.clear(); } -void VillageHelper::insert(const VillageWithColor &vw) { - villageList.insert(vw); -} - -void VillageHelper::draw() { - for (auto vw : villageList) { - auto village = vw.village; - if (village) { - if (this->showBounds) - trapdoor::spawnRectangleParticle( - village->getBounds(), villageHelperConfig.boundColor); - if (this->showVillageCenter) - trapdoor::spawnParticle(village->getCenter() + - Vec3(0.5f, 0.9f, 0.5f), - villageHelperConfig.centerParticle); - if (this->showGolemSpawnArea) - trapdoor::spawnRectangleParticle( - village->getGolemSpawnArea(), - villageHelperConfig.spawnColor); - - if (this->showPOIRange) - trapdoor::spawnRectangleParticle( - village->getPOIRange(), villageHelperConfig.poiQueryColor); - - if (this->showDwellerStatus) - this->showVillagerStatus(); - } + void VillageHelper::insert(const VillageWithColor &vw) { + villageList.insert(vw); } -} -void VillageHelper::list(trapdoor::Actor *player) { - trapdoor::MessageBuilder builder; - builder.text("village.info.allVillages"_i18); - int i = 0; - for (auto vw : villageList) { - auto village = vw.village; - if (village) { - i++; - auto aabb = village->getBounds(); - builder.num(i) - .text(": ") - .pos(village->getCenter().toBlockPos()) - .text(" r:") - .num(village->getRadius()) - .text(" p:") - .num(village->getWorkedVillagerNum()) - .text("/") - .num(village->getPopulation()) - .text(" g:") - .num(village->getIronGolemNum()) - .text(" b:") - .num(village->getBedPOICount()) - .text(" s:") - .num((int)village->canSpawnIronGolem()) - .text(" [") - .pos(aabb.p1.toBlockPos()) - .text("-") - .pos(aabb.p2.toBlockPos()) - .text("]\n"); + void VillageHelper::draw() { + for (auto vw : villageList) { + auto village = vw.village; + if (village) { + if (this->showBounds) + trapdoor::spawnRectangleParticle( + village->getBounds(), villageHelperConfig.boundColor); + if (this->showVillageCenter) + trapdoor::spawnParticle( + village->getCenter() + Vec3(0.5f, 0.9f, 0.5f), + villageHelperConfig.centerParticle); + if (this->showGolemSpawnArea) + trapdoor::spawnRectangleParticle( + village->getGolemSpawnArea(), + villageHelperConfig.spawnColor); + + if (this->showPOIRange) + trapdoor::spawnRectangleParticle( + village->getPOIRange(), + villageHelperConfig.poiQueryColor); + + if (this->showDwellerStatus) this->showVillagerStatus(); + } } } - builder.send(player); - // builder.send(); -} -void VillageHelper::tick() { - // rmt_ScopedCPUSample(VILLAGE_TICK, 0) - if (gameTick % 40 == 0) { - // todo clear village and draw village; - this->draw(); - this->clear(); + void VillageHelper::list(trapdoor::Actor *player) { + trapdoor::MessageBuilder builder; + builder.text("village.info.allVillages"_i18); + int i = 0; + for (auto vw : villageList) { + auto village = vw.village; + if (village) { + i++; + auto aabb = village->getBounds(); + builder.num(i) + .text(": ") + .pos(village->getCenter().toBlockPos()) + .text(" r:") + .num(village->getRadius()) + .text(" p:") + .num(village->getWorkedVillagerNum()) + .text("/") + .num(village->getPopulation()) + .text(" g:") + .num(village->getIronGolemNum()) + .text(" b:") + .num(village->getBedPOICount()) + .text(" s:") + .num((int)village->canSpawnIronGolem()) + .text(" [") + .pos(aabb.p1.toBlockPos()) + .text("-") + .pos(aabb.p2.toBlockPos()) + .text("]\n"); + } + } + builder.send(player); + // builder.send(); } - this->gameTick = (this->gameTick + 1) % 80; -} -void VillageHelper::test() { - for (auto &v : this->villageList) { - v.village->test(); + void VillageHelper::tick() { + // rmt_ScopedCPUSample(VILLAGE_TICK, 0) + if (gameTick % 40 == 0) { + // todo clear village and draw village; + this->draw(); + this->clear(); + } + this->gameTick = (this->gameTick + 1) % 80; } -} -void VillageHelper::showVillagerStatus() { - int idx = 0; - for (auto village : this->villageList) { - idx++; - __try { - village.village->showVillagerStatus(idx); - } __except (EXCEPTION_EXECUTE_HANDLER) { - // nothing + void VillageHelper::test() { + for (auto &v : this->villageList) { + v.village->test(); } } -} -void VillageHelper::printNearestVillageInfo(trapdoor::Actor *player, - const Vec3 &pos) { - mod::Village *target = nullptr; - float maxDistance = 1024; - for (auto village : this->villageList) { - auto dis = village.village->getCenter().distanceTo(pos); - if (dis < maxDistance) { - target = village.village; - maxDistance = dis; + void VillageHelper::showVillagerStatus() { + int idx = 0; + for (auto village : this->villageList) { + idx++; + __try { + village.village->showVillagerStatus(idx); + } __except (EXCEPTION_EXECUTE_HANDLER) { + // nothing + } } } - if (target) { - trapdoor::info(player, target->getDebugInfo()); - } else { - trapdoor::warning(player, LANG("village.error.noVillage")); - } -} -void Village::test() { - // finish - // auto *tickMap = getDwellerTicklMap(this); - // for (auto i : *tickMap) { - // for (auto &v : i) { - // auto actor = trapdoor::bdsMod->fetchEntity(v.first.uid, false); - // if (actor) { - // actor->setNameTag(std::to_string(v.second.tick)); - // } - // } - // } -} - -void VillageHelper::printDwellerInfo(trapdoor::Actor *player, - trapdoor::Actor *actor) { - - //试图获取居民组件 - auto component = getDwellerComponentFromActor(actor); - if (!component) { - trapdoor::warning(player, LANG("village.error.notDweller")); - } else { - if (actor->getActorId() == "villager_v2") { - for (auto villages : this->villageList) { - if (villages.village->printVillagerInfo(player, actor)) - return; + void VillageHelper::printNearestVillageInfo(trapdoor::Actor *player, + const Vec3 &pos) { + mod::Village *target = nullptr; + float maxDistance = 1024; + for (auto village : this->villageList) { + auto dis = village.village->getCenter().distanceTo(pos); + if (dis < maxDistance) { + target = village.village; + maxDistance = dis; } - trapdoor::warning(player, LANG("village.error.notDweller")); + } + if (target) { + trapdoor::info(player, target->getDebugInfo()); } else { - auto center = component->getVillageCenter(actor); - trapdoor::info(player, "[ %d %d %d]", center->x, center->y, - center->z); + trapdoor::warning(player, LANG("village.error.noVillage")); } } -} -void VillageHelper::removeAllNameTag() { - for (auto vill : this->villageList) { - vill.village->removeAllTags(); + void Village::test() { + // finish + // auto *tickMap = getDwellerTicklMap(this); + // for (auto i : *tickMap) { + // for (auto &v : i) { + // auto actor = trapdoor::bdsMod->fetchEntity(v.first.uid, + // false); if (actor) { + // actor->setNameTag(std::to_string(v.second.tick)); + // } + // } + // } + } + + void VillageHelper::printDwellerInfo(trapdoor::Actor *player, + trapdoor::Actor *actor) { + //试图获取居民组件 + // auto component = getDwellerComponentFromActor(actor); + // if (!component) { + // trapdoor::warning(player, LANG("village.error.notDweller")); + // } else { + // if (actor->getActorId() == "villager_v2") { + // for (auto villages : this->villageList) { + // if (villages.village->printVillagerInfo(player, + // actor)) + // return; + // } + // trapdoor::warning(player, + // LANG("village.error.notDweller")); + // } else { + // auto center = component->getVillageCenter(actor); + // trapdoor::info(player, "[ %d %d %d]", center->x, + // center->y, + // center->z); + // } + // } } -} -void VillageHelper::registerCommand(CommandManager &commandManager) { - commandManager.registerCmd("village", "command.village.desc") - ->then(ARG("list", "command.village.list.desc", NONE, - { this->list(player); })) - ->then(ARG("b", "command.village.b.desc", BOOL, - { - this->setShowBound(holder->getBool()); - info(player, LANG("command.village.b.set"), - holder->getBool()); - })) - ->then(ARG("p", "command.village.p.desc", BOOL, - { - this->setShowPOIRange(holder->getBool()); - info(player, LANG("command.village.p.set"), - holder->getBool()); - })) - ->then(ARG("s", "command.village.s.desc", BOOL, - { - this->setShowGolemSpawnArea(holder->getBool()); - info(player, LANG("command.village.s.set"), - holder->getBool()); - })) - ->then(ARG("c", "command.village.c.desc", BOOL, - { - this->setShowVillageCenter(holder->getBool()); - info(player, LANG("command.village.c.set"), - holder->getBool()); - })) - ->then(ARG("v", "command.village.v.desc", BOOL, - { - this->setShowDwellerStatus(holder->getBool()); - info(player, LANG("command.village.v.set"), - holder->getBool()); - })) - - ->then( - ARG("n", "command.village.n.desc", NONE, + void VillageHelper::removeAllNameTag() { + for (auto vill : this->villageList) { + vill.village->removeAllTags(); + } + } + + void VillageHelper::registerCommand(CommandManager &commandManager) { + commandManager.registerCmd("village", "command.village.desc") + ->then(ARG("list", "command.village.list.desc", NONE, + { this->list(player); })) + ->then(ARG("b", "command.village.b.desc", BOOL, + { + this->setShowBound(holder->getBool()); + info(player, LANG("command.village.b.set"), + holder->getBool()); + })) + ->then(ARG("p", "command.village.p.desc", BOOL, + { + this->setShowPOIRange(holder->getBool()); + info(player, LANG("command.village.p.set"), + holder->getBool()); + })) + ->then(ARG("s", "command.village.s.desc", BOOL, + { + this->setShowGolemSpawnArea(holder->getBool()); + info(player, LANG("command.village.s.set"), + holder->getBool()); + })) + ->then(ARG("c", "command.village.c.desc", BOOL, + { + this->setShowVillageCenter(holder->getBool()); + info(player, LANG("command.village.c.set"), + holder->getBool()); + })) + ->then(ARG("v", "command.village.v.desc", BOOL, + { + this->setShowDwellerStatus(holder->getBool()); + info(player, LANG("command.village.v.set"), + holder->getBool()); + })) + + ->then(ARG( + "n", "command.village.n.desc", NONE, { this->printNearestVillageInfo(player, *player->getPos()); })) - ->then(ARG("test", "???", NONE, { - // trapdoor::warning(player, "you are not developer"); - this->test(); - })); -} + ->then(ARG("test", "???", NONE, { + // trapdoor::warning(player, "you are not developer"); + this->test(); + })); + } -bool VillageWithColor::operator<(const VillageWithColor &rhs) const { - return this->village < rhs.village; -} + bool VillageWithColor::operator<(const VillageWithColor &rhs) const { + return this->village < rhs.village; + } -} // namespace mod +} // namespace mod -THook( - void, - MSSYM_B1QA4tickB1AA7VillageB2AAE10QEAAXUTickB2AAE15AEAVBlockSourceB3AAAA1Z, - mod::Village *vill, void *tick, void *blockSource) { +THook(void, Village_tick_2a1ecbf8, mod::Village *vill, void *tick, + void *blockSource) { // village tick original(vill, tick, blockSource); mod::VillageWithColor vw{vill, trapdoor::GRAPHIC_COLOR::GREEN}; diff --git a/mod/village/Village.h b/mod/village/Village.h index 5ce5d9a..98a7a1b 100644 --- a/mod/village/Village.h +++ b/mod/village/Village.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "commands/CommandManager.h" #include "entity/Actor.h" #include "graphics/AABB.h" @@ -10,120 +12,122 @@ #include "lib/mod.h" #include "tools/noncopyable .h" #include "world/Level.h" -#include namespace mod { -class Village { - public: - int getPopulation(); + class Village { + public: + int getPopulation(); - int getIronGolemNum(); + int getIronGolemNum(); - int getBedPOICount(); + int getBedPOICount(); - int getWorkedVillagerNum(); + int getWorkedVillagerNum(); - bool canSpawnIronGolem(); + bool canSpawnIronGolem(); - trapdoor::Vec3 getCenter(); + trapdoor::Vec3 getCenter(); - float getRadius(); + float getRadius(); - trapdoor::AABB getPOIRange(); + trapdoor::AABB getPOIRange(); - trapdoor::AABB getGolemSpawnArea(); + trapdoor::AABB getGolemSpawnArea(); - trapdoor::AABB getBounds(); + trapdoor::AABB getBounds(); - void printAllPOIs(); + void printAllPOIs(); - void showVillagerStatus(int vIdx); + void showVillagerStatus(int vIdx); - void showTimeStamp(); + void showTimeStamp(); - std::string getDebugInfo(); + std::string getDebugInfo(); - bool printVillagerInfo(trapdoor::Actor *player, trapdoor::Actor *actor); + bool printVillagerInfo(trapdoor::Actor *player, trapdoor::Actor *actor); - void removeAllTags(); + void removeAllTags(); - void test(); -}; + void test(); + }; -//这个其实蛮冗余的,懒得删了 -class VillageWithColor { - public: - Village *village; - trapdoor::GRAPHIC_COLOR color; + //这个其实蛮冗余的,懒得删了 + class VillageWithColor { + public: + Village *village; + trapdoor::GRAPHIC_COLOR color; - bool operator<(const VillageWithColor &rhs) const; -}; + bool operator<(const VillageWithColor &rhs) const; + }; -struct VillageHelperConfig { - trapdoor::GRAPHIC_COLOR boundColor = GRAPH_COLOR::BLUE; - trapdoor::GRAPHIC_COLOR spawnColor = GRAPH_COLOR::GREEN; - trapdoor::GRAPHIC_COLOR poiQueryColor = GRAPH_COLOR::WHITE; - std::string centerParticle = "minecraft:heart_particle"; -}; + struct VillageHelperConfig { + trapdoor::GRAPHIC_COLOR boundColor = GRAPH_COLOR::BLUE; + trapdoor::GRAPHIC_COLOR spawnColor = GRAPH_COLOR::GREEN; + trapdoor::GRAPHIC_COLOR poiQueryColor = GRAPH_COLOR::WHITE; + std::string centerParticle = "minecraft:heart_particle"; + }; -class VillageHelper : noncopyable { - VillageHelperConfig villageHelperConfig; - bool showBounds = false; //村庄边界 - bool showPOIRange = false; // poi查询范围 - bool showGolemSpawnArea = false; //铁傀儡刷出范围 - bool showVillageCenter = false; //显示村庄中心 - bool showDwellerStatus = false; - size_t gameTick = 0; + class VillageHelper : noncopyable { + VillageHelperConfig villageHelperConfig; + bool showBounds = false; //村庄边界 + bool showPOIRange = false; // poi查询范围 + bool showGolemSpawnArea = false; //铁傀儡刷出范围 + bool showVillageCenter = false; //显示村庄中心 + bool showDwellerStatus = false; + size_t gameTick = 0; - public: - inline void setShowBound(bool able) { showBounds = able; } + public: + inline void setShowBound(bool able) { showBounds = able; } - inline void setShowPOIRange(bool able) { showPOIRange = able; } + inline void setShowPOIRange(bool able) { showPOIRange = able; } - inline void setShowGolemSpawnArea(bool able) { showGolemSpawnArea = able; } + inline void setShowGolemSpawnArea(bool able) { + showGolemSpawnArea = able; + } - inline void setShowVillageCenter(bool able) { showVillageCenter = able; } + inline void setShowVillageCenter(bool able) { + showVillageCenter = able; + } - inline void setShowDwellerStatus(bool able) { - showDwellerStatus = able; - //关闭头顶显示后移除所有的命名 - if (!able) - this->removeAllNameTag(); - } + inline void setShowDwellerStatus(bool able) { + showDwellerStatus = able; + //关闭头顶显示后移除所有的命名 + if (!able) this->removeAllNameTag(); + } - inline bool getShowDwellerStatus() const { return showDwellerStatus; } + inline bool getShowDwellerStatus() const { return showDwellerStatus; } - VillageHelper() = default; + VillageHelper() = default; - std::set villageList; + std::set villageList; - void insert(const VillageWithColor &vw); + void insert(const VillageWithColor &vw); - void clear(); + void clear(); - void draw(); + void draw(); - void showVillagerStatus(); + void showVillagerStatus(); - void list(trapdoor::Actor *actor); + void list(trapdoor::Actor *actor); - void test(); + void test(); - void printNearestVillageInfo(trapdoor::Actor *player, - const trapdoor::Vec3 &pos); + void printNearestVillageInfo(trapdoor::Actor *player, + const trapdoor::Vec3 &pos); - inline void setConfig(const VillageHelperConfig &config) { - this->villageHelperConfig = config; - } + inline void setConfig(const VillageHelperConfig &config) { + this->villageHelperConfig = config; + } - void tick(); + void tick(); - void printDwellerInfo(trapdoor::Actor *player, trapdoor::Actor *actor); + void printDwellerInfo(trapdoor::Actor *player, trapdoor::Actor *actor); - void removeAllNameTag(); + void removeAllNameTag(); - void registerCommand(trapdoor::CommandManager &commandManager); -}; + void registerCommand(trapdoor::CommandManager &commandManager); + }; -} // namespace mod +} // namespace mod