id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,541,814
roomclientjoin.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/roomclientjoin.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "roomclientjoin.h" #include "log.h" #include "menucustomlobby.h" #include "menuphase.h" #include "midgard.h" #include "netcustomplayerclient.h" #include "netcustomservice.h" #include "netcustomsession.h" #include "netmessages.h" #include "settings.h" #include <fmt/format.h> namespace hooks { static CMenuCustomLobby* menuLobby{nullptr}; static SLNet::RakNetGUID playerServerGuid{}; static void registerClientPlayerAndJoin() { using namespace game; auto& midgardApi = CMidgardApi::get(); auto midgard = midgardApi.instance(); auto netService = getNetService(); // Create player using session logDebug("roomJoin.log", "Try create net client using midgard"); auto playerId = midgardApi.createNetClient(midgard, netService->loggedAccount.c_str(), false); logDebug("roomJoin.log", fmt::format("Check net client id 0x{:x}", playerId)); if (playerId == 0) { // Network id of zero is invalid logDebug("roomJoin.log", "Net client has zero id"); customLobbyProcessJoinError(menuLobby, "Created net client has net id 0"); return; } logDebug("roomJoin.log", "Set menu phase as a net client proxy"); auto menuPhase = menuLobby->menuBaseData->menuPhase; // Set menu phase as net proxy midgardApi.setClientsNetProxy(midgard, menuPhase); // Get max players from session auto netSession{netService->session}; auto maxPlayers = netSession->vftable->getMaxClients(netSession); logDebug("roomJoin.log", fmt::format("Get max number of players in session: {:d}", maxPlayers)); menuPhase->data->maxPlayers = maxPlayers; CMenusReqVersionMsg requestVersion; requestVersion.vftable = NetMessagesApi::getMenusReqVersionVftable(); logDebug("roomJoin.log", "Send version request message to server"); // Send CMenusReqVersionMsg to server // If failed, hide wait message and show error, enable join if (!midgardApi.sendNetMsgToServer(midgard, &requestVersion)) { customLobbyProcessJoinError(menuLobby, "Could not request game version from server"); return; } // Response will be handled by CMenuCustomLobby menuGameVersionMsgHandler logDebug("roomJoin.log", "Request sent, wait for callback"); } /** * Handles player client connection to player server. * Starts joining the game by player client using game-specific protocol. */ class ClientToServerConnectCallbacks : public NetworkPeerCallbacks { public: ClientToServerConnectCallbacks() = default; ~ClientToServerConnectCallbacks() override = default; void onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) override { auto service = getNetService(); auto playerClient{service->session->players[0]}; if (type == ID_CONNECTION_ATTEMPT_FAILED) { // Unsubscribe from callbacks playerClient->player.netPeer.removeCallback(this); customLobbyProcessJoinError(menuLobby, "Failed to connect player client to player server"); return; } if (type != ID_CONNECTION_REQUEST_ACCEPTED) { return; } auto& player{playerClient->player}; // Unsubscribe from callbacks player.netPeer.removeCallback(this); logDebug("roomJoin.log", "Player client finally connected to player server. " "Continue with game protocol"); // Fully connected! // Remember server playerNetId, and our netId player.netId = SLNet::RakNetGUID::ToUint32(peer->GetMyGUID()); auto serverGuid = peer->GetGuidFromSystemAddress(packet->systemAddress); playerClient->serverAddress = packet->systemAddress; playerClient->serverId = SLNet::RakNetGUID::ToUint32(serverGuid); playerClient->setupPacketCallbacks(); registerClientPlayerAndJoin(); } }; static ClientToServerConnectCallbacks clientToServerConnectCallback; /** * Handles NAT punchthrough responses. * Connects player client to player server on successfull NAT punch. */ class NATPunchCallbacks : public NetworkPeerCallbacks { public: NATPunchCallbacks() = default; ~NATPunchCallbacks() override = default; void onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) override { const char* error{nullptr}; switch (type) { default: return; case ID_NAT_TARGET_NOT_CONNECTED: error = "Player server is not connected\n" "to the lobby server"; break; case ID_NAT_TARGET_UNRESPONSIVE: error = "Player server is not responding"; break; case ID_NAT_CONNECTION_TO_TARGET_LOST: error = "Lobby server lost the connection\n" "to the player server\n" "while setting up punchthrough"; break; case ID_NAT_PUNCHTHROUGH_FAILED: error = "NAT punchthrough failed"; break; case ID_NAT_PUNCHTHROUGH_SUCCEEDED: { auto service = getNetService(); auto playerClient{service->session->players[0]}; auto& player{playerClient->player}; // Unsubscribe from callbacks player.netPeer.removeCallback(this); logDebug("roomJoin.log", fmt::format("NAT punch succeeded! Player server address {:s}, netId 0x{:x}", playerClient->serverAddress.ToString(), playerClient->serverId)); auto result{peer->Connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort(), nullptr, 0)}; if (result != SLNet::CONNECTION_ATTEMPT_STARTED) { const auto msg{fmt::format( "Failed to connect client player to server player after NAT punch.\nResult {:d}", (int)result)}; logError("roomJoin.log", msg); customLobbyProcessJoinError(menuLobby, msg.c_str()); return; } logDebug("roomJoin.log", "Connection attempt after NAT punch, wait response"); player.netPeer.addCallback(&clientToServerConnectCallback); return; } } if (error) { auto service = getNetService(); auto playerClient{service->session->players[0]}; // Unsubscribe from callbacks playerClient->player.netPeer.removeCallback(this); customLobbyProcessJoinError(menuLobby, error); } } }; static NATPunchCallbacks natPunchCallbacks; /** * Handles player client connection to lobby server. * Starts NAT punchthrough on successfull connection. */ class ClientConnectCallbacks : public NetworkPeerCallbacks { public: ClientConnectCallbacks() = default; ~ClientConnectCallbacks() override = default; void onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) override { auto service = getNetService(); auto playerClient{service->session->players[0]}; if (type == ID_CONNECTION_ATTEMPT_FAILED) { // Unsubscribe from callbacks playerClient->player.netPeer.removeCallback(this); customLobbyProcessJoinError(menuLobby, "Failed to connect player client to NAT server"); return; } if (type != ID_CONNECTION_REQUEST_ACCEPTED) { return; } logDebug("roomJoin.log", fmt::format("OpenNAT to player server with id 0x{:x}", SLNet::RakNetGUID::ToUint32(playerServerGuid))); // Unsubscribe from callbacks playerClient->player.netPeer.removeCallback(this); // Start NAT punchthrough peer->AttachPlugin(&playerClient->natClient); playerClient->natClient.OpenNAT(playerServerGuid, packet->systemAddress); // Attach callback, wait response playerClient->player.netPeer.addCallback(&natPunchCallbacks); } }; static ClientConnectCallbacks clientConnectCallbacks; void customLobbyProcessJoin(CMenuCustomLobby* menu, const char* roomName, const SLNet::RakNetGUID& serverGuid) { logDebug("roomJoin.log", "Unsubscribe from rooms list updates while joining the room"); // Unsubscribe from rooms list notification while we joining the room // Remove timer event game::UiEventApi::get().destructor(&menu->roomsListEvent); // Disconnect ui-related rooms callbacks removeRoomsCallback(menu->roomsCallbacks.get()); menu->roomsCallbacks.reset(nullptr); using namespace game; menuLobby = menu; playerServerGuid = serverGuid; // Create session ourselves logDebug("roomJoin.log", fmt::format("Process join to {:s}", roomName)); auto netService = getNetService(); logDebug("roomJoin.log", fmt::format("Get netService {:p}", (void*)netService)); if (!netService) { customLobbyProcessJoinError(menu, "Net service is null"); return; } auto netSession = (CNetCustomSession*)createCustomNetSession(netService, roomName, false); logDebug("roomJoin.log", fmt::format("Created netSession {:p}", (void*)netSession)); // If failed, hide wait message and show error, enable join if (!netSession) { customLobbyProcessJoinError(menu, "Could not create net session"); return; } // Set net session to midgard auto& midgardApi = CMidgardApi::get(); auto midgard = midgardApi.instance(); auto currentSession{midgard->data->netSession}; if (currentSession) { currentSession->vftable->destructor(currentSession, 1); } logDebug("roomJoin.log", "Set netSession to midgard"); midgard->data->netSession = netSession; netService->session = netSession; logDebug("roomJoin.log", "Mark self as client"); // Mark self as client midgard->data->host = false; logDebug("roomJoin.log", "Create player client beforehand"); // Create player client beforehand auto clientPlayer = createCustomPlayerClient(netSession, ""); netSession->players.push_back(clientPlayer); logDebug("roomJoin.log", "Connect to lobby server, wait response"); // Connect to lobby server, wait response const auto& lobbySettings = userSettings().lobby; const auto& serverIp = lobbySettings.server.ip; const auto& serverPort = lobbySettings.server.port; auto peer = clientPlayer->getPeer(); // Connect player server to lobby server, wait response. // We need this connection for NAT punchthrough if (peer->Connect(serverIp.c_str(), serverPort, nullptr, 0) != SLNet::CONNECTION_ATTEMPT_STARTED) { const std::string msg{"Failed to connect client player to lobby server"}; logError("roomJoin.log", msg); customLobbyProcessJoinError(menu, msg.c_str()); return; } clientPlayer->player.netPeer.addCallback(&clientConnectCallbacks); } } // namespace hooks
12,202
C++
.cpp
276
36.126812
101
0.673497
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,815
bestowwardshooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/bestowwardshooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bestowwardshooks.h" #include "attack.h" #include "batattackbestowwards.h" #include "batattackutils.h" #include "battleattackinfo.h" #include "game.h" #include "idvector.h" #include "midgardobjectmap.h" #include "modifierutils.h" #include "usunit.h" namespace hooks { bool canPerformSecondaryAttack(game::CBatAttackBestowWards* thisptr, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; const auto& fn = gameFunctions(); if (thisptr->attackImplMagic == -1) thisptr->attackImplMagic = fn.getAttackImplMagic(objectMap, &thisptr->attackImplUnitId, 0); if (thisptr->attackImplMagic <= 1) return false; if (thisptr->attackNumber != 1) return false; if (CMidgardIDApi::get().getType(&thisptr->attackImplUnitId) == IdType::Item) return false; if (!thisptr->attack2Initialized) { thisptr->attack2Impl = fn.getAttackById(objectMap, &thisptr->attackImplUnitId, thisptr->attackNumber + 1, true); thisptr->attack2Initialized = true; } if (thisptr->attack2Impl == nullptr) return false; const auto attack2 = thisptr->attack2Impl; const auto attack2Class = attack2->vftable->getAttackClass(attack2); const auto batAttack2 = fn.createBatAttack(objectMap, battleMsgData, &thisptr->unitId, &thisptr->attackImplUnitId, thisptr->attackNumber + 1, attack2Class, false); const auto& battle = BattleMsgDataApi::get(); bool result = battle.canPerformAttackOnUnitWithStatusCheck(objectMap, battleMsgData, batAttack2, targetUnitId); batAttack2->vftable->destructor(batAttack2, true); return result; } bool __fastcall bestowWardsAttackCanPerformHooked(game::CBatAttackBestowWards* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; CMidgardID targetGroupId{}; thisptr->vftable->getTargetGroupId(thisptr, &targetGroupId, battleMsgData); CMidgardID targetUnitGroupId{}; gameFunctions().getAllyOrEnemyGroupId(&targetUnitGroupId, battleMsgData, targetUnitId, true); if (targetUnitGroupId != targetGroupId) return false; if (canHeal(thisptr->attackImpl, objectMap, battleMsgData, targetUnitId)) return true; if (canApplyAnyModifier(thisptr->attackImpl, objectMap, battleMsgData, targetUnitId)) return true; return canPerformSecondaryAttack(thisptr, objectMap, battleMsgData, targetUnitId); } void __fastcall bestowWardsAttackOnHitHooked(game::CBatAttackBestowWards* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId, game::BattleAttackInfo** attackInfo) { using namespace game; auto targetUnit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectByIdForChange(objectMap, targetUnitId)); int qtyHealed = 0; if (BattleMsgDataApi::get().unitCanBeHealed(objectMap, battleMsgData, targetUnitId)) { const auto attack = thisptr->attackImpl; const auto qtyHeal = attack->vftable->getQtyHeal(attack); if (qtyHeal > 0) qtyHealed = heal(objectMap, battleMsgData, targetUnit, qtyHeal); } if (unitCanBeModified(battleMsgData, targetUnitId)) { const auto attack = thisptr->attackImpl; const auto wards = attack->vftable->getWards(attack); for (const CMidgardID* modifierId = wards->bgn; modifierId != wards->end; modifierId++) { if (canApplyModifier(battleMsgData, targetUnit, modifierId)) { if (!applyModifier(&thisptr->unitId, battleMsgData, targetUnit, modifierId)) break; } } } BattleAttackUnitInfo info{}; info.unitId = targetUnit->id; info.unitImplId = targetUnit->unitImpl->id; info.damage = qtyHealed; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); } bool __fastcall bestowWardsMethod15Hooked(game::CBatAttackBestowWards* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData) { return true; } } // namespace hooks
5,797
C++
.cpp
121
36.85124
100
0.636348
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,816
mideveffect.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/mideveffect.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mideveffect.h" #include "version.h" #include <array> namespace game::CMidEvEffectApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::CreateFromCategory)0x5f28e3, }, // Russobit Api{ (Api::CreateFromCategory)0x5f28e3, }, // Gog Api{ (Api::CreateFromCategory)0x5f15f2, }, // Scenario Editor Api{ (Api::CreateFromCategory)0x4f8781, (Api::GetInfoString)0x42e5b9, (Api::GetDescription)0x42e1d1, (Api::GetDescription)0x430d34, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidEvEffectApi
1,528
C++
.cpp
50
26.96
72
0.708079
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,817
racecategory.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/racecategory.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "racecategory.h" #include "version.h" #include <array> namespace game { namespace RaceCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LRaceCategory*)0x839310, (LRaceCategory*)0x839330, (LRaceCategory*)0x839320, (LRaceCategory*)0x8392e0, (LRaceCategory*)0x839300, (LRaceCategory*)0x8392f0 }, // Russobit Categories{ (LRaceCategory*)0x839310, (LRaceCategory*)0x839330, (LRaceCategory*)0x839320, (LRaceCategory*)0x8392e0, (LRaceCategory*)0x839300, (LRaceCategory*)0x8392f0 }, // Gog Categories{ (LRaceCategory*)0x8372c0, (LRaceCategory*)0x8372e0, (LRaceCategory*)0x8372d0, (LRaceCategory*)0x837290, (LRaceCategory*)0x8372b0, (LRaceCategory*)0x8372a0 }, // Scenario Editor Categories{ (LRaceCategory*)0x665010, (LRaceCategory*)0x665030, (LRaceCategory*)0x665020, (LRaceCategory*)0x664fe0, (LRaceCategory*)0x665000, (LRaceCategory*)0x664ff0 } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6ceae4, // Russobit (const void*)0x6ceae4, // Gog (const void*)0x6cca84, // Scenario Editor (const void*)0x5ca75c }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace RaceCategories namespace LRaceCategoryTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x57f4e1, (Api::Init)0x57f676, (Api::ReadCategory)0x57f6ee, (Api::InitDone)0x57f631, (Api::FindCategoryById)0x40acaa, }, // Russobit Api{ (Api::Constructor)0x57f4e1, (Api::Init)0x57f676, (Api::ReadCategory)0x57f6ee, (Api::InitDone)0x57f631, (Api::FindCategoryById)0x40acaa, }, // Gog Api{ (Api::Constructor)0x57eb99, (Api::Init)0x57e2de, (Api::ReadCategory)0x57eda6, (Api::InitDone)0x57ece9, (Api::FindCategoryById)0x40a936, }, // Scenario Editor Api{ (Api::Constructor)0x52c128, (Api::Init)0x52c2bd, (Api::ReadCategory)0x52c335, (Api::InitDone)0x52c278, (Api::FindCategoryById)0x4030b3, } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6e9294, // Russobit (const void*)0x6e9294, // Gog (const void*)0x6e7234, // Scenario Editor (const void*)0x5ddcd4 }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace LRaceCategoryTableApi } // namespace game
3,811
C++
.cpp
139
22.395683
72
0.664024
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,818
scriptutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/scriptutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "scriptutils.h" namespace hooks { std::vector<bindings::IdView> IdVectorToIds(const game::IdVector* src) { std::vector<bindings::IdView> value; for (const game::CMidgardID* it = src->bgn; it != src->end; it++) { value.push_back(it); } return value; } void IdsToIdVector(const std::vector<bindings::IdView>& src, game::IdVector* dst) { using namespace game; const auto& idVectorApi = IdVectorApi::get(); IdVector tmp{}; idVectorApi.reserve(&tmp, 1); for (const auto& id : src) { idVectorApi.pushBack(&tmp, &(const CMidgardID&)id); } idVectorApi.copy(dst, tmp.bgn, tmp.end); idVectorApi.destructor(&tmp); } } // namespace hooks
1,520
C++
.cpp
41
33.902439
81
0.720598
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,819
difficultylevel.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/difficultylevel.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "difficultylevel.h" #include "version.h" #include <array> namespace game::DifficultyLevelCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LDifficultyLevel*)0x8399d8, (LDifficultyLevel*)0x839a08, (LDifficultyLevel*)0x8399f8, (LDifficultyLevel*)0x8399e8 }, // Russobit Categories{ (LDifficultyLevel*)0x8399d8, (LDifficultyLevel*)0x839a08, (LDifficultyLevel*)0x8399f8, (LDifficultyLevel*)0x8399e8 }, // Gog Categories{ (LDifficultyLevel*)0x837988, (LDifficultyLevel*)0x8379b8, (LDifficultyLevel*)0x8379a8, (LDifficultyLevel*)0x837998 }, // Scenario Editor Categories{ (LDifficultyLevel*)0x6651d0, (LDifficultyLevel*)0x665200, (LDifficultyLevel*)0x6651f0, (LDifficultyLevel*)0x6651e0 } }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } } // namespace game::DifficultyLevelCategories
1,895
C++
.cpp
59
27.694915
72
0.712725
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,820
batattackdoppelganger.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batattackdoppelganger.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batattackdoppelganger.h" #include "version.h" #include <array> namespace game::CBatAttackDoppelgangerApi { // clang-format off static std::array<IBatAttackVftable*, 4> vftables = {{ // Akella (IBatAttackVftable*)0x6f54fc, // Russobit (IBatAttackVftable*)0x6f54fc, // Gog (IBatAttackVftable*)0x6f34ac, // Scenario Editor (IBatAttackVftable*)nullptr, }}; // clang-format on IBatAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CBatAttackDoppelgangerApi
1,372
C++
.cpp
39
32.692308
72
0.753012
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,821
dbfaccess.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/dbfaccess.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dbfaccess.h" #include "dbf/dbffile.h" #include "log.h" #include "midgardid.h" #include "utils.h" #include <fmt/format.h> #include <functional> namespace utils { template <typename T> using Convertor = std::function<bool(T&, const DbfRecord&, const DbfColumn&)>; template <typename T> bool dbRead(T& result, const DbfFile& database, size_t row, const std::string& columnName, const Convertor<T>& convertor) { if (row >= database.recordsTotal()) { return false; } DbfRecord record; if (!database.record(record, row)) { return false; } const DbfColumn* column{database.column(columnName)}; if (!column) { return false; } return convertor(result, record, *column); } bool dbRead(game::CMidgardID& id, const DbfFile& database, size_t row, const std::string& columnName) { auto convertId = [](game::CMidgardID& id, const DbfRecord& record, const DbfColumn& column) { std::string idString; if (!record.value(idString, column)) { return false; } const auto& idApi = game::CMidgardIDApi::get(); game::CMidgardID tmpId{}; idApi.fromString(&tmpId, idString.c_str()); if (tmpId == game::invalidId) { return false; } id = tmpId; return true; }; return dbRead<game::CMidgardID>(id, database, row, columnName, convertId); } bool dbRead(int& result, const DbfFile& database, size_t row, const std::string& columnName) { auto convertInt = [](int& result, const DbfRecord& record, const DbfColumn& column) { int tmp{}; if (!record.value(tmp, column)) { return false; } result = tmp; return true; }; return dbRead<int>(result, database, row, columnName, convertInt); } bool dbValueExists(const std::filesystem::path& dbfFilePath, const std::string& columnName, const std::string& value) { DbfFile dbf; if (!dbf.open(dbfFilePath)) { hooks::logError("mssProxyError.log", fmt::format("Could not open {:s}", dbfFilePath.filename().string())); return false; } for (std::uint32_t i = 0; i < dbf.recordsTotal(); ++i) { DbfRecord record; if (!dbf.record(record, i)) { hooks::logError("mssProxyError.log", fmt::format("Could not read record {:d} from {:s}", i, dbfFilePath.filename().string())); return false; } if (record.isDeleted()) { continue; } std::string text; if (record.value(text, columnName) && hooks::trimSpaces(text) == value) return true; } return false; } } // namespace utils
3,697
C++
.cpp
108
27.416667
100
0.625105
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,822
modifierutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/modifierutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "modifierutils.h" #include "attack.h" #include "attackmodified.h" #include "battlemsgdata.h" #include "custommodifier.h" #include "dynamiccast.h" #include "game.h" #include "globaldata.h" #include "idlistutils.h" #include "midgardobjectmap.h" #include "midunit.h" #include "modifgroup.h" #include "settings.h" #include "umattackhooks.h" #include "umunit.h" #include "unitmodifier.h" #include "ussoldier.h" namespace hooks { bool unitCanBeModified(game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); if (battle.getUnitStatus(battleMsgData, targetUnitId, BattleStatus::XpCounted) || battle.getUnitStatus(battleMsgData, targetUnitId, BattleStatus::Dead) || battle.getUnitStatus(battleMsgData, targetUnitId, BattleStatus::Retreat)) { return false; } return true; } game::CUmUnit* castUmModifierToUmUnit(game::CUmModifier* modifier) { using namespace game; if (castModifierToCustomModifier(modifier)) return nullptr; // CCustomModifier inherits type info from CUmUnit const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (CUmUnit*)dynamicCast(modifier, 0, rtti.CUmModifierType, rtti.CUmUnitType, 0); } game::CUmAttack* castUmModifierToUmAttack(game::CUmModifier* modifier) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (CUmAttack*)dynamicCast(modifier, 0, rtti.CUmModifierType, rtti.CUmAttackType, 0); } game::CUmStack* castUmModifierToUmStack(game::CUmModifier* modifier) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (CUmStack*)dynamicCast(modifier, 0, rtti.CUmModifierType, rtti.CUmStackType, 0); } game::IUsUnit* castUmModifierToUnit(game::CUmModifier* modifier) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (IUsUnit*)dynamicCast(modifier, 0, rtti.CUmModifierType, rtti.IUsUnitType, 0); } game::CUmModifier* castUnitToUmModifier(const game::IUsUnit* unit) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (CUmModifier*)dynamicCast(unit, 0, rtti.IUsUnitType, rtti.CUmModifierType, 0); } game::CUmModifier* getFirstUmModifier(const game::IUsUnit* unit) { using namespace game; CUmModifier* result = nullptr; for (auto curr = unit; curr; curr = result->data->prev) { auto modifier = castUnitToUmModifier(curr); if (!modifier) break; result = modifier; } return result; } const game::TUnitModifier* getUnitModifier(const game::CMidgardID* modifierId) { using namespace game; const auto& global = GlobalDataApi::get(); const auto modifiers = (*global.getGlobalData())->modifiers; const TUnitModifier* unitModifier = (TUnitModifier*)global.findById(modifiers, modifierId); return unitModifier; } void getModifierAttackSource(game::CUmUnit* modifier, game::LAttackSource* value) { using namespace game; const int attackSourceId = (int)modifier->data->immunity.data->id; const auto attackSourceTable = (*GlobalDataApi::get().getGlobalData())->attackSources; LAttackSourceTableApi::get().findCategoryById(attackSourceTable, value, &attackSourceId); } void getModifierAttackClass(game::CUmUnit* modifier, game::LAttackClass* value) { using namespace game; const int attackClassId = (int)modifier->data->immunityC.data->id; const auto attackClassTable = (*GlobalDataApi::get().getGlobalData())->attackClasses; LAttackClassTableApi::get().findCategoryById(attackClassTable, value, &attackClassId); } bool isUnitAttackSourceWardRemoved(game::AttackSourceImmunityStatusesPatched immunityStatuses, const game::LAttackSource* attackSource) { using namespace game; std::uint32_t flag = 1 << gameFunctions().getAttackSourceWardFlagPosition(attackSource); return immunityStatuses.patched & flag; } void resetUnitAttackSourceWard(game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId, game::CUmUnit* modifier) { using namespace game; LAttackSource attackSource{}; getModifierAttackSource(modifier, &attackSource); auto unitInfo = BattleMsgDataApi::get().getUnitInfoById(battleMsgData, unitId); std::uint32_t flag = 1 << gameFunctions().getAttackSourceWardFlagPosition(&attackSource); unitInfo->attackSourceImmunityStatuses.patched &= ~flag; } bool isUnitAttackClassWardRemoved(std::uint32_t immunityStatuses, const game::LAttackClass* attackClass) { using namespace game; std::uint32_t flag = 1 << gameFunctions().getAttackClassWardFlagPosition(attackClass); return immunityStatuses & flag; } void resetUnitAttackClassWard(game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId, game::CUmUnit* modifier) { using namespace game; LAttackClass attackClass{}; getModifierAttackClass(modifier, &attackClass); auto unitInfo = BattleMsgDataApi::get().getUnitInfoById(battleMsgData, unitId); std::uint32_t flag = 1 << gameFunctions().getAttackClassWardFlagPosition(&attackClass); unitInfo->attackClassImmunityStatuses &= ~flag; } bool canApplyImmunityModifier(game::BattleMsgData* battleMsgData, const game::CMidUnit* targetUnit, game::CUmUnit* modifier, game::ImmuneId immuneId) { using namespace game; LAttackSource attackSource{}; getModifierAttackSource(modifier, &attackSource); const auto targetSoldier = gameFunctions().castUnitImplToSoldier(targetUnit->unitImpl); const auto immuneCat = targetSoldier->vftable->getImmuneByAttackSource(targetSoldier, &attackSource); if (immuneCat->id == ImmuneCategories::get().notimmune->id) { return true; } else if (immuneCat->id == ImmuneCategories::get().once->id) { if (immuneId == ImmuneId::Always) return true; const auto& battle = BattleMsgDataApi::get(); if (battle.isUnitAttackSourceWardRemoved(battleMsgData, &targetUnit->id, &attackSource)) return true; } return false; } bool canApplyImmunityclassModifier(game::BattleMsgData* battleMsgData, const game::CMidUnit* targetUnit, game::CUmUnit* modifier, game::ImmuneId immuneId) { using namespace game; LAttackClass attackClass{}; getModifierAttackClass(modifier, &attackClass); const auto targetSoldier = gameFunctions().castUnitImplToSoldier(targetUnit->unitImpl); const auto immuneCat = targetSoldier->vftable->getImmuneByAttackClass(targetSoldier, &attackClass); if (immuneCat->id == ImmuneCategories::get().notimmune->id) { return true; } else if (immuneCat->id == ImmuneCategories::get().once->id) { if (immuneId == ImmuneId::Always) return true; const auto& battle = BattleMsgDataApi::get(); if (battle.isUnitAttackClassWardRemoved(battleMsgData, &targetUnit->id, &attackClass)) return true; } return false; } bool canApplyModifier(game::BattleMsgData* battleMsgData, const game::CMidUnit* targetUnit, const game::CMidgardID* modifierId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); if (battle.unitHasModifier(battleMsgData, modifierId, &targetUnit->id)) return false; CUmModifier* modifier = getUnitModifier(modifierId)->data->modifier; CUmUnit* umUnit = castUmModifierToUmUnit(modifier); if (umUnit) { if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::Hp) || modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::Regeneration) || modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::Armor)) return true; if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityOnce) && canApplyImmunityModifier(battleMsgData, targetUnit, umUnit, ImmuneId::Once)) return true; if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityAlways) && canApplyImmunityModifier(battleMsgData, targetUnit, umUnit, ImmuneId::Always)) return true; if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityclassOnce) && canApplyImmunityclassModifier(battleMsgData, targetUnit, umUnit, ImmuneId::Once)) return true; if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityclassAlways) && canApplyImmunityclassModifier(battleMsgData, targetUnit, umUnit, ImmuneId::Always)) return true; return false; } return true; } bool canApplyAnyModifier(game::IAttack* attack, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; if (!unitCanBeModified(battleMsgData, targetUnitId)) return false; const CMidUnit* targetUnit = gameFunctions().findUnitById(objectMap, targetUnitId); const auto wards = attack->vftable->getWards(attack); for (const CMidgardID* modifierId = wards->bgn; modifierId != wards->end; modifierId++) { if (canApplyModifier(battleMsgData, targetUnit, modifierId)) return true; } return false; } game::ModifiedUnitInfo* getModifiedUnits(game::UnitInfo* unitInfo, game::ModifiedUnitInfo** end) { using namespace game; auto& units = unitInfo->modifiedUnits; if (userSettings().unrestrictedBestowWards) { *end = units.patched + ModifiedUnitCountPatched; return units.patched; } else { *end = units.original + std::size(units.original); return units.original; } } void resetModifiedUnitsInfo(game::UnitInfo* unitInfo) { using namespace game; game::ModifiedUnitInfo* end; for (auto info = getModifiedUnits(unitInfo, &end); info < end; info++) { info->unitId = invalidId; info->modifierId = invalidId; } } bool addUnitModifierInfo(game::BattleMsgData* battleMsgData, game::CMidUnit* targetUnit, const game::CMidgardID* modifierId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); auto& modifierIds = battle.getUnitInfoById(battleMsgData, &targetUnit->id)->modifierIds; for (auto& id : modifierIds) { if (id == invalidId) { id = *modifierId; return true; } } return false; } bool addModifiedUnitInfo(const game::CMidgardID* unitId, game::BattleMsgData* battleMsgData, game::CMidUnit* targetUnit, const game::CMidgardID* modifierId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); auto unitInfo = battle.getUnitInfoById(battleMsgData, unitId); game::ModifiedUnitInfo* end; for (auto info = getModifiedUnits(unitInfo, &end); info < end; info++) { if (info->unitId == invalidId) { if (!addUnitModifierInfo(battleMsgData, targetUnit, modifierId)) return false; info->unitId = targetUnit->id; info->modifierId = *modifierId; return true; } } return false; } bool applyModifier(const game::CMidgardID* unitId, game::BattleMsgData* battleMsgData, game::CMidUnit* targetUnit, const game::CMidgardID* modifierId) { using namespace game; if (!addModifiedUnitInfo(unitId, battleMsgData, targetUnit, modifierId)) return false; CMidUnitApi::get().addModifier(targetUnit, modifierId); // Fixes modifiers getting lost after modified unit is untransformed if (targetUnit->transformed) addUniqueIdToList(targetUnit->origModifiers, modifierId); CUmModifier* modifier = getUnitModifier(modifierId)->data->modifier; // No ward reset in case of custom modifier because we don't know if it grants it or not CUmUnit* umUnit = castUmModifierToUmUnit(modifier); if (umUnit) { if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityOnce)) resetUnitAttackSourceWard(battleMsgData, &targetUnit->id, umUnit); if (modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityclassOnce)) resetUnitAttackClassWard(battleMsgData, &targetUnit->id, umUnit); } return true; } void removeModifier(game::BattleMsgData* battleMsgData, game::CMidUnit* unit, const game::CMidgardID* modifierId) { using namespace game; if (unit == nullptr) // Prevents the same crash with summoners that appears in removeModifier return; CMidUnitApi::get().removeModifier(unit, modifierId); // Fixes modifiers becoming permanent after modified unit is transformed removeIdFromList(unit->origModifiers, modifierId); BattleMsgDataApi::get().resetUnitModifierInfo(battleMsgData, &unit->id, modifierId); } void removeModifiers(game::BattleMsgData* battleMsgData, game::IMidgardObjectMap* objectMap, game::UnitInfo* unitInfo, const game::CMidgardID* modifiedUnitId) { using namespace game; auto modifiedUnit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectByIdForChange(objectMap, modifiedUnitId)); auto unitModifierIds = getUnitModifierIds(unitInfo, modifiedUnitId); for (auto it = unitModifierIds.begin(); it != unitModifierIds.end(); it++) removeModifier(battleMsgData, modifiedUnit, &(*it)); } game::CMidgardID validateId(game::CMidgardID src) { using namespace game; CMidgardID value; const auto& id = CMidgardIDApi::get(); id.validateId(&value, src); return value; } std::set<game::CMidgardID> getModifiedUnitIds(game::UnitInfo* unitInfo) { using namespace game; std::set<CMidgardID> result; game::ModifiedUnitInfo* end; for (auto info = getModifiedUnits(unitInfo, &end); info < end; info++) { if (info->unitId != invalidId) result.insert(validateId(info->unitId)); } return result; } std::set<game::CMidgardID> getUnitModifierIds(game::UnitInfo* unitInfo, const game::CMidgardID* modifiedUnitId) { using namespace game; std::set<CMidgardID> result; game::ModifiedUnitInfo* end; for (auto info = getModifiedUnits(unitInfo, &end); info < end; info++) { if (info->unitId == *modifiedUnitId) result.insert(validateId(info->modifierId)); } return result; } game::IAttack* wrapAltAttack(const game::IUsUnit* unit, game::IAttack* attack) { using namespace game; const auto& attackModifiedApi = CAttackModifiedApi::get(); auto result = attack; for (CUmModifier* curr = getFirstUmModifier(unit); curr; curr = curr->data->next) { auto umAttack = castUmModifierToUmAttack(curr); if (umAttack) { auto altAttackModified = getAltAttackModified(umAttack); attackModifiedApi.wrap(altAttackModified, result); result = altAttackModified; } else { auto custom = castModifierToCustomModifier(curr); if (custom) { result = custom->wrapAltAttack(result); } } } return result; } void getEditorModifiers(const game::CMidUnit* unit, game::IdList* value) { using namespace game; const auto& unitApi = CMidUnitApi::get(); const auto& idListApi = IdListApi::get(); const auto& idApi = CMidgardIDApi::get(); unitApi.getModifiers(value, unit); for (auto it = value->begin(); it != value->end();) { auto typeIndex = idApi.getTypeIndex(&(*it)); if (0x9000 <= typeIndex && typeIndex <= 0x9999) { // Scenario Editor modifiers ++it; } else { idListApi.erase(value, it++); } } } int applyModifiers(int base, const game::IdList& modifiers, game::ModifierElementTypeFlag type) { using namespace game; auto& globalApi{GlobalDataApi::get()}; auto globalData{*globalApi.getGlobalData()}; int result = base; for (const auto& modifier : modifiers) { auto unitModifier{(TUnitModifier*)globalApi.findById(globalData->modifiers, &modifier)}; auto umModifier{unitModifier->data->modifier}; if (!umModifier->vftable->hasElement(umModifier, type)) { continue; } bool percent = false; switch (type) { case ModifierElementTypeFlag::QtyDamage: case ModifierElementTypeFlag::Power: case ModifierElementTypeFlag::Initiative: percent = true; break; case ModifierElementTypeFlag::Hp: auto umUnit = castUmModifierToUmUnit(umModifier); percent = umUnit && umUnit->data->isPercentHp; break; } int value = umModifier->vftable->getFirstElementValue(umModifier); if (percent) { result += result * value / 100; } else { result += value; } } return result; } bool isImmunityModifier(const game::CMidgardID* modifierId, const game::LAttackSource* source, game::ImmuneId immuneId) { using namespace game; auto modifier = getUnitModifier(modifierId)->data->modifier; switch (immuneId) { case ImmuneId::Once: if (!modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityOnce)) { return false; } break; case ImmuneId::Always: if (!modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityAlways)) { return false; } break; default: return false; } auto umUnit = castUmModifierToUmUnit(modifier); if (!umUnit) { return false; } LAttackSource modifierSource{}; getModifierAttackSource(umUnit, &modifierSource); return modifierSource.id == source->id; } bool isImmunityclassModifier(const game::CMidgardID* modifierId, const game::LAttackClass* class_, game::ImmuneId immuneId) { using namespace game; auto modifier = getUnitModifier(modifierId)->data->modifier; switch (immuneId) { case ImmuneId::Once: if (!modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityclassOnce)) { return false; } break; case ImmuneId::Always: if (!modifier->vftable->hasElement(modifier, ModifierElementTypeFlag::ImmunityclassAlways)) { return false; } break; default: return false; } auto umUnit = castUmModifierToUmUnit(modifier); if (!umUnit) { return false; } LAttackClass modifierClass{}; getModifierAttackClass(umUnit, &modifierClass); return modifierClass.id == class_->id; } void notifyModifiersChanged(const game::IUsUnit* unitImpl) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; CUmModifier* modifier = nullptr; for (auto curr = unitImpl; curr; curr = modifier->data->prev) { modifier = (CUmModifier*)dynamicCast(curr, 0, rtti.IUsUnitType, rtti.CUmModifierType, 0); if (!modifier) { break; } auto customModifier = castModifierToCustomModifier(modifier); if (customModifier) { customModifier->notifyModifiersChanged(); } } } bool addModifier(game::CMidUnit* unit, const game::CMidgardID* modifierId, bool checkCanApply) { using namespace game; const auto unitModifier = getUnitModifier(modifierId); if (!unitModifier) { return false; } if (checkCanApply && !unitModifier->vftable->canApplyToUnit(unitModifier, unit->unitImpl)) { return false; } auto modifier = unitModifier->vftable->createModifier(unitModifier); auto prevModifier = castUnitToUmModifier(unit->unitImpl); if (prevModifier) prevModifier->data->next = modifier; CUmModifierApi::get().setPrev(modifier, unit->unitImpl); auto customModifier = castModifierToCustomModifier(modifier); if (customModifier) customModifier->setUnit(unit); unit->unitImpl = castUmModifierToUnit(modifier); if (userSettings().modifiers.notifyModifiersChanged) { notifyModifiersChanged(unit->unitImpl); } return true; } bool hasModifier(const game::IUsUnit* unitImpl, const game::CMidgardID* modifierId) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; const CUmModifier* modifier = nullptr; for (auto curr = unitImpl; curr; curr = modifier->data->prev) { modifier = static_cast<const CUmModifier*>( dynamicCast(curr, 0, rtti.IUsUnitType, rtti.CUmModifierType, 0)); if (!modifier) break; if (modifier->data->modifierId == *modifierId) { return true; } } return false; } } // namespace hooks
22,944
C++
.cpp
564
33.207447
99
0.678302
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,823
gameutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/gameutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "gameutils.h" #include "battlemsgdata.h" #include "buildingtype.h" #include "dynamiccast.h" #include "fortification.h" #include "game.h" #include "globalvariables.h" #include "idset.h" #include "leaderabilitycat.h" #include "lordtype.h" #include "midclient.h" #include "midclientcore.h" #include "middiplomacy.h" #include "midgard.h" #include "midgardmap.h" #include "midgardmapblock.h" #include "midgardmapfog.h" #include "midgardobjectmap.h" #include "midgardplan.h" #include "midgardscenariomap.h" #include "midplayer.h" #include "midrod.h" #include "midruin.h" #include "midscenvariables.h" #include "midserver.h" #include "midserverlogic.h" #include "midstack.h" #include "midunit.h" #include "playerbuildings.h" #include "scenarioinfo.h" #include "scenedit.h" #include "unitutils.h" #include "ussoldier.h" #include "utils.h" #include "version.h" #include <fmt/format.h> #include <thread> extern std::thread::id mainThreadId; namespace hooks { static game::CMidgardID createIdWithType(const game::IMidgardObjectMap* objectMap, game::IdType idType) { using namespace game; const auto& idApi{CMidgardIDApi::get()}; auto scenarioId{objectMap->vftable->getId(objectMap)}; CMidgardID id{}; idApi.fromParts(&id, idApi.getCategory(scenarioId), idApi.getCategoryIndex(scenarioId), idType, 0); return id; } bool isGreaterPickRandomIfEqual(int first, int second) { using namespace game; const auto& fn = gameFunctions(); return first > second || (first == second && fn.generateRandomNumber(2) == 1); } const game::IMidgardObjectMap* getObjectMap() { using namespace game; if (gameVersion() == GameVersion::ScenarioEditor) { auto editorData = CScenEditApi::get().instance()->data; if (!editorData->initialized) return nullptr; auto unknown2 = editorData->unknown2; if (!unknown2 || !unknown2->data) return nullptr; return unknown2->data->scenarioMap; } auto midgard = CMidgardApi::get().instance(); if (std::this_thread::get_id() == mainThreadId) { auto client = midgard->data->client; if (!client) return nullptr; return CMidClientCoreApi::get().getObjectMap(&client->core); } else { auto server = midgard->data->server; if (!server) return nullptr; return CMidServerLogicApi::get().getObjectMap(server->data->serverLogic); } } game::CMidUnitGroup* getGroup(game::IMidgardObjectMap* objectMap, const game::CMidgardID* groupId, bool forChange) { using namespace game; const auto& fn = gameFunctions(); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto obj = forChange ? objectMap->vftable->findScenarioObjectByIdForChange(objectMap, groupId) : objectMap->vftable->findScenarioObjectById(objectMap, groupId); switch (CMidgardIDApi::get().getType(groupId)) { case IdType::Stack: { auto stack = (CMidStack*)dynamicCast(obj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); return stack ? &stack->group : nullptr; } case IdType::Fortification: { auto fortification = static_cast<CFortification*>(obj); return fortification ? &fortification->group : nullptr; } case IdType::Ruin: auto ruin = static_cast<CMidRuin*>(obj); return ruin ? &ruin->group : nullptr; } return nullptr; } const game::CMidUnitGroup* getGroup(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* groupId) { return getGroup(const_cast<game::IMidgardObjectMap*>(objectMap), groupId, false); } const game::CMidUnitGroup* getAllyOrEnemyGroup(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId, bool ally) { using namespace game; const auto& fn = gameFunctions(); CMidgardID groupId{}; fn.getAllyOrEnemyGroupId(&groupId, battleMsgData, unitId, ally); void* tmp{}; return fn.getStackFortRuinGroup(tmp, objectMap, &groupId); } const game::CScenarioInfo* getScenarioInfo(const game::IMidgardObjectMap* objectMap) { const auto id{createIdWithType(objectMap, game::IdType::ScenarioInfo)}; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, &id); if (!obj) { return nullptr; } return static_cast<const game::CScenarioInfo*>(obj); } const game::CMidPlayer* getPlayer(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId) { using namespace game; auto playerObj = objectMap->vftable->findScenarioObjectById(objectMap, playerId); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (const CMidPlayer*)dynamicCast(playerObj, 0, rtti.IMidScenarioObjectType, rtti.CMidPlayerType, 0); } const game::CMidPlayer* getPlayer(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); CMidgardID playerId = battle.isUnitAttacker(battleMsgData, unitId) ? battleMsgData->attackerPlayerId : battleMsgData->defenderPlayerId; return getPlayer(objectMap, &playerId); } const game::CMidPlayer* getPlayerByUnitId(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; auto playerId = getPlayerIdByUnitId(objectMap, unitId); return playerId != emptyId ? getPlayer(objectMap, &playerId) : nullptr; } const game::CMidgardID getPlayerIdByUnitId(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; auto stack = getStackByUnitId(objectMap, unitId); if (stack) { return stack->ownerId; } auto fort = getFortByUnitId(objectMap, unitId); if (fort) { return fort->ownerId; } return emptyId; } const game::CMidScenVariables* getScenarioVariables(const game::IMidgardObjectMap* objectMap) { const auto id{createIdWithType(objectMap, game::IdType::ScenarioVariable)}; auto obj{objectMap->vftable->findScenarioObjectById(objectMap, &id)}; if (!obj) { return nullptr; } return static_cast<const game::CMidScenVariables*>(obj); } const game::CMidgardPlan* getMidgardPlan(const game::IMidgardObjectMap* objectMap) { const auto id{createIdWithType(objectMap, game::IdType::Plan)}; auto obj{objectMap->vftable->findScenarioObjectById(objectMap, &id)}; if (!obj) { return nullptr; } return static_cast<const game::CMidgardPlan*>(obj); } const game::CMidgardMap* getMidgardMap(const game::IMidgardObjectMap* objectMap) { const auto id{createIdWithType(objectMap, game::IdType::Map)}; auto obj{objectMap->vftable->findScenarioObjectById(objectMap, &id)}; if (!obj) { return nullptr; } return static_cast<const game::CMidgardMap*>(obj); } const game::CMidgardMapBlock* getMidgardMapBlock(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* mapId, int mapSize, int x, int y) { using namespace game; const auto& id = CMidgardIDApi::get(); if (x < 0 || x >= mapSize || y < 0 || y >= mapSize) { // Outside of map return nullptr; } CMidgardID blockId{}; const std::uint32_t blockX = x / 8 * 8; const std::uint32_t blockY = y / 4 * 4; id.fromParts(&blockId, IdCategory::Scenario, id.getCategoryIndex(mapId), IdType::MapBlock, blockX | (blockY << 8)); auto obj = objectMap->vftable->findScenarioObjectById(objectMap, &blockId); return static_cast<const CMidgardMapBlock*>(obj); } const game::LTerrainCategory* getTerrainCategory(const game::LRaceCategory* raceCategory) { using namespace game; const auto& terrains = TerrainCategories::get(); switch (raceCategory->id) { case RaceId::Human: return terrains.human; case RaceId::Heretic: return terrains.heretic; case RaceId::Undead: return terrains.undead; case RaceId::Dwarf: return terrains.dwarf; case RaceId::Elf: return terrains.elf; default: return terrains.neutral; } } game::CMidStack* getStack(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* stackId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, stackId); if (!obj) { return nullptr; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); return (CMidStack*)dynamicCast(obj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); } game::CMidStack* getStack(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); CMidgardID groupId = battle.isUnitAttacker(battleMsgData, unitId) ? battleMsgData->attackerGroupId : battleMsgData->defenderGroupId; return getStack(objectMap, &groupId); } const game::CMidStack* getStackByUnitId(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; auto stackId = gameFunctions().getStackIdByUnitId(objectMap, unitId); return stackId ? getStack(objectMap, stackId) : nullptr; } game::CFortification* getFort(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* fortId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, fortId); return static_cast<CFortification*>(obj); } game::CFortification* getFort(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); CMidgardID groupId = battle.isUnitAttacker(battleMsgData, unitId) ? battleMsgData->attackerGroupId : battleMsgData->defenderGroupId; return getFort(objectMap, &groupId); } const game::CFortification* getFortByUnitId(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; auto fortId = gameFunctions().getFortIdByUnitId(objectMap, unitId); return fortId ? getFort(objectMap, fortId) : nullptr; } game::CMidRuin* getRuin(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* ruinId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, ruinId); return static_cast<CMidRuin*>(obj); } game::CMidRuin* getRuin(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); CMidgardID groupId = battle.isUnitAttacker(battleMsgData, unitId) ? battleMsgData->attackerGroupId : battleMsgData->defenderGroupId; return getRuin(objectMap, &groupId); } const game::CMidRuin* getRuinByUnitId(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; auto ruinId = gameFunctions().getRuinIdByUnitId(objectMap, unitId); return ruinId ? getRuin(objectMap, ruinId) : nullptr; } game::CMidRod* getRod(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* rodId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, rodId); return static_cast<CMidRod*>(obj); } int getGroupXpKilled(const game::IMidgardObjectMap* objectMap, const game::CMidUnitGroup* group) { using namespace game; const auto& fn = gameFunctions(); int result = 0; for (const game::CMidgardID* it = group->units.bgn; it != group->units.end; ++it) { const auto unit = fn.findUnitById(objectMap, it); if (unit->currentHp <= 0) { continue; } const auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); result += soldier->vftable->getXpKilled(soldier); } return result; } game::CMidInventory* getInventory(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* groupId) { using namespace game; const auto& idApi = CMidgardIDApi::get(); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto groupObj = objectMap->vftable->findScenarioObjectById(objectMap, groupId); if (idApi.getType(groupId) == IdType::Stack) { auto stack = static_cast<CMidStack*>( dynamicCast(groupObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0)); return &stack->inventory; } else if (idApi.getType(groupId) == IdType::Fortification) { auto fort = static_cast<CFortification*>( dynamicCast(groupObj, 0, rtti.IMidScenarioObjectType, rtti.CFortificationType, 0)); return &fort->inventory; } return nullptr; } bool canGroupGainXp(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* groupId) { using namespace game; const auto& idApi = CMidgardIDApi::get(); if (idApi.getType(groupId) == IdType::Stack) { auto stack = getStack(objectMap, groupId); auto leader = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, &stack->leaderId)); if (!canUnitGainXp(leader->unitImpl)) { return false; } } return true; } int getWeaponMasterBonusXpPercent(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* groupId) { using namespace game; const auto& fn = gameFunctions(); const auto& idApi = CMidgardIDApi::get(); if (idApi.getType(groupId) == IdType::Stack) { auto stack = getStack(objectMap, groupId); auto leader = fn.findUnitById(objectMap, &stack->leaderId); if (hasLeaderAbility(leader->unitImpl, LeaderAbilityCategories::get().weaponMaster)) { const auto vars = *(*GlobalDataApi::get().getGlobalData())->globalVariables; return vars->weaponMaster; } } return 0; } int getEasyDifficultyBonusXpPercent(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId) { using namespace game; const auto& difficulties = DifficultyLevelCategories::get(); auto player = getPlayer(objectMap, playerId); if (player && player->isHuman) { auto scenarioInfo = getScenarioInfo(objectMap); if (scenarioInfo->gameDifficulty.id == difficulties.easy->id) { return 20; } } return 0; } int getAiBonusXpPercent(const game::IMidgardObjectMap* objectMap) { using namespace game; const auto& difficulties = DifficultyLevelCategories::get(); auto scenarioInfo = getScenarioInfo(objectMap); if (scenarioInfo->suggestedLevel >= 10) { auto difficultyId = scenarioInfo->gameDifficulty.id; if (difficultyId == difficulties.average->id) { return 25; } else if (difficultyId == difficulties.hard->id) { return 50; } else if (difficultyId == difficulties.veryHard->id) { return 100; } } return 0; } const game::TBuildingType* getBuilding(const game::CMidgardID* buildingId) { using namespace game; const auto& globalApi = GlobalDataApi::get(); const auto globalData = *globalApi.getGlobalData(); return (const TBuildingType*)globalApi.findById(globalData->buildings, buildingId); } int getBuildingLevel(const game::CMidgardID* buildingId) { auto building = getBuilding(buildingId); return building ? getBuildingLevel(building) : 0; } int getBuildingLevel(const game::TBuildingType* building) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto unitBuilding = (const TBuildingUnitUpgType*)dynamicCast(building, 0, rtti.TBuildingTypeType, rtti.TBuildingUnitUpgTypeType, 0); return unitBuilding ? unitBuilding->level : 0; } const game::CPlayerBuildings* getPlayerBuildings(const game::IMidgardObjectMap* objectMap, const game::CMidPlayer* player) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, &player->buildingsId); return (const CPlayerBuildings*)dynamicCast(obj, 0, rtti.IMidScenarioObjectType, rtti.CPlayerBuildingsType, 0); } bool playerHasBuilding(const game::IMidgardObjectMap* objectMap, const game::CMidPlayer* player, const game::CMidgardID* buildingId) { auto playerBuildings = getPlayerBuildings(objectMap, player); if (!playerBuildings) { return false; } const auto& buildings = playerBuildings->buildings; for (auto node = buildings.head->next; node != buildings.head; node = node->next) { if (node->data == *buildingId) { return true; } } return false; } bool playerHasSiblingUnitBuilding(const game::IMidgardObjectMap* objectMap, const game::CMidPlayer* player, const game::TBuildingType* building) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto unitBuilding = (const TBuildingUnitUpgType*)dynamicCast(building, 0, rtti.TBuildingTypeType, rtti.TBuildingUnitUpgTypeType, 0); if (!unitBuilding) { return false; } auto playerBuildings = getPlayerBuildings(objectMap, player); if (!playerBuildings) { return false; } const auto& buildings = playerBuildings->buildings; for (auto node = buildings.head->next; node != buildings.head; node = node->next) { auto otherBuilding = getBuilding(&node->data); if (otherBuilding->data->category.id == building->data->category.id) { auto otherUnitBuilding = (const TBuildingUnitUpgType*) dynamicCast(otherBuilding, 0, rtti.TBuildingTypeType, rtti.TBuildingUnitUpgTypeType, 0); if (otherUnitBuilding && otherUnitBuilding->level == unitBuilding->level && otherUnitBuilding->branch.id == unitBuilding->branch.id) { return true; } } } return false; } bool lordHasBuilding(const game::CMidgardID* lordId, const game::CMidgardID* buildingId) { using namespace game; const auto& globalApi = GlobalDataApi::get(); const auto& idSetApi = IdSetApi::get(); const GlobalData* globalData = *globalApi.getGlobalData(); auto lord = static_cast<const TLordType*>(globalApi.findById(globalData->lords, lordId)); if (!lord) { return false; } IdSetIterator it; auto buildings = lord->data->buildList->data; return *idSetApi.find(&buildings, &it, buildingId) != buildings.end(); } bool isBuildingBuildable(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* buildingId) { using namespace game; const auto& fn = gameFunctions(); const auto& globalApi = GlobalDataApi::get(); const auto globalData = *globalApi.getGlobalData(); const TBuildingType* building = nullptr; for (auto currentId = *buildingId; currentId != emptyId; currentId = building->data->requiredId) { building = (const TBuildingType*)globalApi.findById(globalData->buildings, &currentId); if (!building) { return false; } auto status = fn.getBuildingStatus(objectMap, playerId, &currentId, true); switch (status) { case BuildingStatus::CanBeBuilt: return true; case BuildingStatus::AlreadyBuilt: return currentId != *buildingId ? true : false; case BuildingStatus::PlayerHasNoRequiredBuilding: break; case BuildingStatus::ExceedsMaxLevel: case BuildingStatus::LordHasNoBuilding: case BuildingStatus::PlayerHasSiblingUnitBuilding: return false; case BuildingStatus::InsufficientBank: case BuildingStatus::PlayerAlreadyBuiltThisDay: showErrorMessageBox(fmt::format("Unexpected building status {:d}.", status)); return false; default: showErrorMessageBox(fmt::format("Unknown building status {:d}.", status)); return false; } } return false; } const game::CMidDiplomacy* getDiplomacy(const game::IMidgardObjectMap* objectMap) { using namespace game; const auto id{createIdWithType(objectMap, game::IdType::Diplomacy)}; auto obj{objectMap->vftable->findScenarioObjectById(objectMap, &id)}; if (!obj) { return nullptr; } return static_cast<const game::CMidDiplomacy*>(obj); } const game::CMidgardMapFog* getFog(const game::IMidgardObjectMap* objectMap, const game::CMidPlayer* player) { using namespace game; auto obj{objectMap->vftable->findScenarioObjectById(objectMap, &player->fogId)}; if (!obj) { return nullptr; } return static_cast<const CMidgardMapFog*>(obj); } } // namespace hooks
23,907
C++
.cpp
591
32.333333
100
0.657848
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,824
midserverlogichooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midserverlogichooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midserverlogichooks.h" #include "idset.h" #include "log.h" #include "logutils.h" #include "midgardscenariomap.h" #include "midserver.h" #include "midserverlogic.h" #include "originalfunctions.h" #include "refreshinfo.h" #include "settings.h" #include "unitstovalidate.h" #include "unitutils.h" #include "utils.h" #include <fmt/format.h> #include <process.h> namespace hooks { void addValidatedUnitsToChangedObjects(game::CMidgardScenarioMap* scenarioMap) { using namespace game; const auto& idSetApi = IdSetApi::get(); auto& changedObjects = scenarioMap->changedObjects; auto& unitsToValidate = getUnitsToValidate(); for (const auto& unitId : unitsToValidate) { auto unit = (CMidUnit*)scenarioMap->vftable->findScenarioObjectById(scenarioMap, &unitId); if (unit && validateUnit(unit)) { Pair<IdSetIterator, bool> tmp; idSetApi.insert(&changedObjects, &tmp, &unitId); } } unitsToValidate.clear(); } void logObjectsToSend(const game::CMidgardScenarioMap* scenarioMap) { const auto& addedObjects = scenarioMap->addedObjects; const auto& changedObjects = scenarioMap->changedObjects; const auto& objectsToErase = scenarioMap->objectsToErase; auto logFileName = fmt::format("netMessages{:d}.log", _getpid()); logDebug( logFileName, fmt::format("Sending scenario objects changes, added: {:d}, changed: {:d}, erased: {:d}", addedObjects.length, changedObjects.length, objectsToErase.length)); auto totalLength = addedObjects.length + changedObjects.length + objectsToErase.length; if (totalLength >= userSettings().debug.sendObjectsChangesTreshold) { for (auto obj : addedObjects) { logDebug(logFileName, fmt::format("Added\t{:s}\t{:s}", idToString(&obj), getMidgardIdTypeDesc(&obj))); } for (auto obj : changedObjects) { logDebug(logFileName, fmt::format("Changed\t{:s}\t{:s}", idToString(&obj), getMidgardIdTypeDesc(&obj))); } for (auto obj : objectsToErase) { logDebug(logFileName, fmt::format("Erased\t{:s}\t{:s}", idToString(&obj), getMidgardIdTypeDesc(&obj))); } } } bool __fastcall midServerLogicSendObjectsChangesHooked(game::IMidMsgSender* thisptr, int /*%edx*/) { using namespace game; const auto serverLogic = castMidMsgSenderToMidServerLogic(thisptr); auto scenarioMap = CMidServerLogicApi::get().getObjectMap(serverLogic); if (userSettings().modifiers.validateUnitsOnGroupChanged) { addValidatedUnitsToChangedObjects(scenarioMap); } if (userSettings().debugMode && userSettings().debug.sendObjectsChangesTreshold) { logObjectsToSend(scenarioMap); } return getOriginalFunctions().midServerLogicSendObjectsChanges(thisptr); } bool __fastcall midServerLogicSendRefreshInfoHooked(const game::CMidServerLogic* thisptr, int /*%edx*/, const game::Set<game::CMidgardID>* objectsList, std::uint32_t playerNetId) { using namespace game; const auto& refreshInfoApi = CRefreshInfoApi::get(); const auto scenarioMap = CMidServerLogicApi::get().getObjectMap(thisptr); const auto limit = userSettings().engine.sendRefreshInfoObjectCountLimit; auto it = objectsList->begin(); const auto end = objectsList->end(); auto sendRefreshInfo = [&](bool& proceed) { CRefreshInfo refreshInfo{}; refreshInfoApi.constructor2(&refreshInfo, &scenarioMap->scenarioFileId, thisptr->coreData->isExpansionContent); proceed = false; std::uint32_t count = 0; for (; it != end; ++it) { if (++count > limit) { proceed = true; break; } refreshInfoApi.addObject(&refreshInfo, scenarioMap, &(*it)); } auto server = thisptr->coreData->server; bool result = CMidServerApi::get().sendNetMsg(server, &refreshInfo, playerNetId); refreshInfoApi.destructor(&refreshInfo); return result; }; for (bool proceed = true; proceed;) { if (!sendRefreshInfo(proceed)) { return false; } } return true; } } // namespace hooks
5,346
C++
.cpp
125
34.832
99
0.659996
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,825
intintmap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/intintmap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "intintmap.h" #include "version.h" #include <array> namespace game::IntIntMapApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Insert)0x4ab2af, (Api::Find)0x56726b, }, // Russobit Api{ (Api::Insert)0x4ab2af, (Api::Find)0x56726b, }, // Gog Api{ (Api::Insert)0x4aaac9, (Api::Find)0x5f0560, }, // Scenario Editor Api{ (Api::Insert)0x55cef8, (Api::Find)0x4e9168, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IntIntMapApi
1,473
C++
.cpp
51
25.176471
72
0.687368
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,826
battlemsgdatahooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/battlemsgdatahooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "battlemsgdatahooks.h" #include "batattack.h" #include "customattacks.h" #include "gameutils.h" #include "intset.h" #include "log.h" #include "midstack.h" #include "modifierutils.h" #include "originalfunctions.h" #include "unitutils.h" #include <atomic> #include <fmt/format.h> namespace hooks { class ModifiedUnitsPatchedFactory { public: ModifiedUnitsPatchedFactory() : count(0) { } ~ModifiedUnitsPatchedFactory() { if (count != 0) { logError("mssProxyError.log", fmt::format("{:d} instances of ModifiedUnitsPatched remained on finalization", count)); } } game::ModifiedUnitInfo* create() { count++; return new game::ModifiedUnitInfo[game::ModifiedUnitCountPatched]; } void destroy(game::ModifiedUnitInfo* value) { count--; delete[] value; } private: std::atomic<int> count; } modifiedUnitsPatchedFactory; void resetUnitInfo(game::UnitInfo* unitInfo) { using namespace game; auto modifiedUnits = unitInfo->modifiedUnits; memset(unitInfo, 0, sizeof(UnitInfo)); unitInfo->unitId1 = invalidId; unitInfo->modifiedUnits = modifiedUnits; resetModifiedUnitsInfo(unitInfo); for (auto& modifierId : unitInfo->modifierIds) { modifierId = invalidId; } } game::BattleMsgData* __fastcall battleMsgDataCtorHooked(game::BattleMsgData* thisptr, int /*%edx*/) { using namespace game; getOriginalFunctions().battleMsgDataCtor(thisptr); for (auto& unitInfo : thisptr->unitsInfo) { memset(&unitInfo.modifiedUnits, 0, sizeof(ModifiedUnitsPatched)); unitInfo.modifiedUnits.patched = modifiedUnitsPatchedFactory.create(); resetModifiedUnitsInfo(&unitInfo); } return thisptr; } game::BattleMsgData* __fastcall battleMsgDataCopyCtorHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::BattleMsgData* src) { using namespace game; getOriginalFunctions().battleMsgDataCtor(thisptr); for (auto& unitInfo : thisptr->unitsInfo) { memset(&unitInfo.modifiedUnits, 0, sizeof(ModifiedUnitsPatched)); } return battleMsgDataCopyHooked(thisptr, 0, src); } game::BattleMsgData* __fastcall battleMsgDataCopyAssignHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::BattleMsgData* src) { using namespace game; if (thisptr == src) return thisptr; const size_t count = std::size(thisptr->unitsInfo); std::vector<ModifiedUnitInfo*> prev(count); for (size_t i = 0; i < count; i++) { prev[i] = thisptr->unitsInfo[i].modifiedUnits.patched; } *thisptr = *src; for (size_t i = 0; i < count; i++) { memcpy(prev[i], src->unitsInfo[i].modifiedUnits.patched, sizeof(ModifiedUnitInfo) * ModifiedUnitCountPatched); thisptr->unitsInfo[i].modifiedUnits.patched = prev[i]; } return thisptr; } game::BattleMsgData* __fastcall battleMsgDataCopyHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::BattleMsgData* src) { using namespace game; *thisptr = *src; const size_t count = std::size(thisptr->unitsInfo); for (size_t i = 0; i < count; i++) { auto modifiedUnits = modifiedUnitsPatchedFactory.create(); memcpy(modifiedUnits, src->unitsInfo[i].modifiedUnits.patched, sizeof(ModifiedUnitInfo) * ModifiedUnitCountPatched); thisptr->unitsInfo[i].modifiedUnits.patched = modifiedUnits; } return thisptr; } void __fastcall battleMsgDataDtorHooked(game::BattleMsgData* thisptr, int /*%edx*/) { using namespace game; for (auto& unitInfo : thisptr->unitsInfo) { modifiedUnitsPatchedFactory.destroy(unitInfo.modifiedUnits.patched); unitInfo.modifiedUnits.patched = nullptr; } } void __fastcall removeUnitInfoHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); size_t index; ModifiedUnitsPatched modifiedUnits{}; const size_t count = std::size(thisptr->unitsInfo); for (index = 0; index < count; ++index) { if (thisptr->unitsInfo[index].unitId1 == *unitId) { modifiedUnits = thisptr->unitsInfo[index].modifiedUnits; break; } } for (size_t i = index; i + 1 < count; ++i) { memcpy(&thisptr->unitsInfo[i], &thisptr->unitsInfo[i + 1], sizeof(UnitInfo)); } if (index < count) { auto lastInfo = &thisptr->unitsInfo[count - 1]; lastInfo->modifiedUnits = modifiedUnits; resetUnitInfo(lastInfo); } while (battle.decreaseUnitAttacks(thisptr, unitId)) ; } void updateDefendBattleAction(const game::UnitInfo* unitInfo, game::Set<game::BattleAction>* actions) { using namespace game; const auto& intSetApi = IntSetApi::get(); if (unitInfo->unitFlags.parts.attackedOnceOfTwice && actions->length) return; BattleAction defend = BattleAction::Defend; Pair<IntSetIterator, bool> tmp{}; intSetApi.insert((IntSet*)actions, &tmp, (int*)&defend); } void updateWaitBattleAction(const game::BattleMsgData* battleMsgData, const game::UnitInfo* unitInfo, game::Set<game::BattleAction>* actions) { using namespace game; const auto& intSetApi = IntSetApi::get(); if (battleMsgData->currentRound < 1) return; if (unitInfo->unitFlags.parts.waited || unitInfo->unitFlags.parts.attackedOnceOfTwice) return; BattleAction wait = BattleAction::Wait; Pair<IntSetIterator, bool> tmp{}; intSetApi.insert((IntSet*)actions, &tmp, (int*)&wait); } void updateUseItemBattleAction(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::UnitInfo* unitInfo, game::Set<game::BattleAction>* actions, game::GroupIdTargetsPair* item1Targets, game::GroupIdTargetsPair* item2Targets) { using namespace game; const auto& idApi = CMidgardIDApi::get(); const auto& battleApi = BattleMsgDataApi::get(); const auto& intSetApi = IntSetApi::get(); if (battleMsgData->currentRound < 1) return; auto groupId = unitInfo->unitFlags.parts.attacker ? &battleMsgData->attackerGroupId : &battleMsgData->defenderGroupId; if (idApi.getType(groupId) != IdType::Stack) return; if (!isStackLeaderAndAllowedToUseBattleItems(objectMap, &unitInfo->unitId1, battleMsgData)) return; auto stack = getStack(objectMap, groupId); GroupIdTargetsPair* itemTargets[] = {item1Targets, item2Targets}; EquippedItemIdx itemIndices[] = {EquippedItemIdx::Battle1, EquippedItemIdx::Battle2}; for (int i = 0; i < 2; ++i) { auto itemId = stack->leaderEquippedItems.bgn[itemIndices[i]]; if (itemId == emptyId) continue; auto& inventory = stack->inventory; if (inventory.vftable->getItemIndex(&inventory, &itemId) == -1) continue; bool used = false; for (const auto& usedItemId : battleMsgData->usedItemIds) { if (usedItemId == itemId) { used = true; break; } } if (used) continue; battleApi.getItemAttackTargets(objectMap, battleMsgData, &unitInfo->unitId1, &itemId, itemTargets[i]); } for (const auto targets : itemTargets) { if (targets->second.length > 0) { BattleAction useItem = BattleAction::UseItem; Pair<IntSetIterator, bool> tmp{}; intSetApi.insert((IntSet*)actions, &tmp, (int*)&useItem); break; } } } void updateRetreatBattleAction(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::UnitInfo* unitInfo, game::Set<game::BattleAction>* actions) { using namespace game; const auto& idApi = CMidgardIDApi::get(); const auto& battleApi = BattleMsgDataApi::get(); const auto& intSetApi = IntSetApi::get(); if (battleMsgData->currentRound < 1) return; if (unitInfo->unitFlags.parts.attackedOnceOfTwice) return; auto groupId = unitInfo->unitFlags.parts.attacker ? &battleMsgData->attackerGroupId : &battleMsgData->defenderGroupId; if (idApi.getType(groupId) != IdType::Stack) return; if (!unitInfo->unitFlags.parts.attacker) { auto stack = getStack(objectMap, groupId); if (stack && stack->insideId != emptyId) return; } BattleAction retreat = BattleAction::Retreat; Pair<IntSetIterator, bool> tmp{}; intSetApi.insert((IntSet*)actions, &tmp, (int*)&retreat); } void updateAttackBattleAction(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::UnitInfo* unitInfo, game::Set<game::BattleAction>* actions, game::GroupIdTargetsPair* attackTargets) { using namespace game; const auto& fn = gameFunctions(); const auto& intSetApi = IntSetApi::get(); const auto attack = fn.getAttackById(objectMap, &unitInfo->unitId1, 1, false); const auto attackClass = attack->vftable->getAttackClass(attack); const auto batAttack = fn.createBatAttack(objectMap, battleMsgData, &unitInfo->unitId1, &unitInfo->unitId1, 1, attackClass, false); batAttack->vftable->getTargetGroupId(batAttack, &attackTargets->first, battleMsgData); batAttack->vftable->fillTargetsList(batAttack, objectMap, battleMsgData, &attackTargets->second); batAttack->vftable->destructor(batAttack, true); if (attackTargets->second.length > 0) { BattleAction attack = BattleAction::Attack; Pair<IntSetIterator, bool> tmp{}; intSetApi.insert((IntSet*)actions, &tmp, (int*)&attack); } } void __stdcall updateBattleActionsHooked(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId, game::Set<game::BattleAction>* actions, game::GroupIdTargetsPair* attackTargets, game::GroupIdTargetsPair* item1Targets, game::GroupIdTargetsPair* item2Targets) { using namespace game; const auto& battleApi = BattleMsgDataApi::get(); const auto& intSetApi = IntSetApi::get(); intSetApi.clear((IntSet*)actions); auto unitInfo = battleApi.getUnitInfoById(battleMsgData, unitId); updateWaitBattleAction(battleMsgData, unitInfo, actions); updateUseItemBattleAction(objectMap, battleMsgData, unitInfo, actions, item1Targets, item2Targets); updateRetreatBattleAction(objectMap, battleMsgData, unitInfo, actions); updateAttackBattleAction(objectMap, battleMsgData, unitInfo, actions, attackTargets); updateDefendBattleAction(unitInfo, actions); } void __fastcall beforeBattleRoundHooked(game::BattleMsgData* thisptr, int /*%edx*/) { using namespace game; getOriginalFunctions().beforeBattleRound(thisptr); // Fix free transform-self to properly reset if the same unit has consequent turns in consequent // battles auto& freeTransformSelf = getCustomAttacks().freeTransformSelf; freeTransformSelf.unitId = emptyId; freeTransformSelf.turnCount = 0; freeTransformSelf.used = false; } } // namespace hooks
13,405
C++
.cpp
317
32.744479
100
0.633513
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,827
dbtable.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/dbtable.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dbtable.h" #include "version.h" #include <array> namespace game::CDBTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::FindBuildingCategory)0x58c041, (Api::FindUnitBranchCategory)0x58c0bf, (Api::FindModifGroupCategory)0x58aea0, (Api::ReadString)0x5b003c, (Api::ReadModifier)0x58ab19, (Api::ReadUnitLevel)0x58be7c, (Api::MissingValueException)0x5965ac, (Api::DuplicateRecordException)0x59d474, (Api::ReadId)0x596935, (Api::ReadText)0x596b67, (Api::FindAttackClass)0x59fad5, (Api::FindAttackSource)0x583f7d, (Api::FindAttackReach)0x5a6a31, (Api::ReadAttackIntValue)0x5a6409, (Api::ReadPower)0x5a64bc, (Api::ReadAttackIntValue)0x5a6505, (Api::ReadAttackIntValue)0x5a6548, (Api::ReadAttackLevel)0x5a657f, (Api::ReadBoolValue)0x5a6624, (Api::ReadIntWithBoundsCheck)0x5968cc, (Api::ReadBoolValue)0x596911, (Api::GetName)0x515760, (Api::Eof)0x5157ec, (Api::Next)0x51580e, }, // Russobit Api{ (Api::FindBuildingCategory)0x58c041, (Api::FindUnitBranchCategory)0x58c0bf, (Api::FindModifGroupCategory)0x58aea0, (Api::ReadString)0x5b003c, (Api::ReadModifier)0x58ab19, (Api::ReadUnitLevel)0x58be7c, (Api::MissingValueException)0x5965ac, (Api::DuplicateRecordException)0x59d474, (Api::ReadId)0x596935, (Api::ReadText)0x596b67, (Api::FindAttackClass)0x59fad5, (Api::FindAttackSource)0x583f7d, (Api::FindAttackReach)0x5a6a31, (Api::ReadAttackIntValue)0x5a6409, (Api::ReadPower)0x5a64bc, (Api::ReadAttackIntValue)0x5a6505, (Api::ReadAttackIntValue)0x5a6548, (Api::ReadAttackLevel)0x5a657f, (Api::ReadBoolValue)0x5a6624, (Api::ReadIntWithBoundsCheck)0x5968cc, (Api::ReadBoolValue)0x596911, (Api::GetName)0x515760, (Api::Eof)0x5157ec, (Api::Next)0x51580e, }, // Gog Api{ (Api::FindBuildingCategory)0x58b1cf, (Api::FindUnitBranchCategory)0x58b24d, (Api::FindModifGroupCategory)0x58a00c, (Api::ReadString)0x5af300, (Api::ReadModifier)0x589c88, (Api::ReadUnitLevel)0x58afd7, (Api::MissingValueException)0x5956d1, (Api::DuplicateRecordException)0x59c710, (Api::ReadId)0x595a5a, (Api::ReadText)0x595c8c, (Api::FindAttackClass)0x59ed57, (Api::FindAttackSource)0x583144, (Api::FindAttackReach)0x5a5c92, (Api::ReadAttackIntValue)0x5a5655, (Api::ReadPower)0x5a5708, (Api::ReadAttackIntValue)0x5a5751, (Api::ReadAttackIntValue)0x5a5794, (Api::ReadAttackLevel)0x5a57cb, (Api::ReadBoolValue)0x5a5870, (Api::ReadIntWithBoundsCheck)0x5959f1, (Api::ReadBoolValue)0x595a36, (Api::GetName)0x514c59, (Api::Eof)0x514ce5, (Api::Next)0x514d07, }, // Scenario Editor Api{ (Api::FindBuildingCategory)0x538bf7, (Api::FindUnitBranchCategory)0x538c75, (Api::FindModifGroupCategory)0x535c30, (Api::ReadString)0x55799d, (Api::ReadModifier)0x5358a5, (Api::ReadUnitLevel)0x538a1b, (Api::MissingValueException)0x536b7e, (Api::DuplicateRecordException)0x53f9b2, (Api::ReadId)0x536f07, (Api::ReadText)0x537139, (Api::FindAttackClass)0x547d4a, (Api::FindAttackSource)0x5325c0, (Api::FindAttackReach)0x54ec66, (Api::ReadAttackIntValue)0x54e637, (Api::ReadPower)0x54e6ea, (Api::ReadAttackIntValue)0x54e733, (Api::ReadAttackIntValue)0x54e776, (Api::ReadAttackLevel)0x54e7ad, (Api::ReadBoolValue)0x54e852, (Api::ReadIntWithBoundsCheck)0x536e9e, (Api::ReadBoolValue)0x536ee3, (Api::GetName)0x4ac3a3, (Api::Eof)0x4ac42f, (Api::Next)0x4ac451, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CDBTableApi
5,004
C++
.cpp
139
28.942446
72
0.673457
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,828
editboxinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/editboxinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "editboxinterf.h" #include "version.h" #include <array> namespace game::CEditBoxInterfApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetFilterAndLength)0x5c9c86, (Api::SetInputLength)0x5390dc, (Api::SetString)0x5391f9, (Api::Update)0x539468, (Api::UpdateFocus)0x5389e6, (Api::IsCharValid)0x538471, }, // Russobit Api{ (Api::SetFilterAndLength)0x5c9c86, (Api::SetInputLength)0x5390dc, (Api::SetString)0x5391f9, (Api::Update)0x539468, (Api::UpdateFocus)0x5389e6, (Api::IsCharValid)0x538471, }, // Gog Api{ (Api::SetFilterAndLength)0x5c8c54, (Api::SetInputLength)0x5386e4, (Api::SetString)0x538801, (Api::Update)0x538a8e, (Api::UpdateFocus)0x537fee, (Api::IsCharValid)0x537a79, }, // Scenario Editor Api{ (Api::SetFilterAndLength)0x4d18b8, (Api::SetInputLength)0x492cb3, (Api::SetString)0x492ddb, (Api::Update)0x493068, (Api::UpdateFocus)0x4925bd, (Api::IsCharValid)0x492048, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CEditBoxInterfApi
2,122
C++
.cpp
67
26.701493
72
0.682439
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,829
netmessages.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netmessages.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netmessages.h" #include "version.h" #include <array> namespace game::NetMessagesApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::SendStackExchangeItemMsg)0x406fef, (Api::SendSiteSellItemMsg)0x4066d9 }, // Russobit Api{ (Api::SendStackExchangeItemMsg)0x406fef, (Api::SendSiteSellItemMsg)0x4066d9 }, // Gog Api{ (Api::SendStackExchangeItemMsg)0x406c7b, (Api::SendSiteSellItemMsg)0x406365 } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } CNetMsgVftable* getMenusReqVersionVftable() { static std::array<CNetMsgVftable*, 3> vftables = {{ // Akella (CNetMsgVftable*)0x6d083c, // Russobit (CNetMsgVftable*)0x6d083c, // Gog (CNetMsgVftable*)0x6ce7dc, }}; return vftables[static_cast<int>(hooks::gameVersion())]; } CNetMsgVftable* getMenusReqInfoVftable() { static std::array<CNetMsgVftable*, 3> vftables = {{ // Akella (CNetMsgVftable*)0x6d080c, // Russobit (CNetMsgVftable*)0x6d080c, // Gog (CNetMsgVftable*)0x6ce7ac, }}; return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::NetMessagesApi
2,137
C++
.cpp
70
26.185714
72
0.694849
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,830
diplomacyhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/diplomacyhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "diplomacyhooks.h" #include "globaldata.h" #include "globalvariables.h" #include "middiplomacy.h" #include "racecategory.h" namespace hooks { static const game::DiplomacyRelation* findRelation( const game::Vector<game::DiplomacyRelation>& relations, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { if (!race1 || !race2) { return nullptr; } using namespace game; const std::uint8_t id1 = static_cast<std::uint8_t>(race1->id); const std::uint8_t id2 = static_cast<std::uint8_t>(race2->id); for (const DiplomacyRelation* i = relations.bgn; i != relations.end; ++i) { if (i->race1CategoryId == id1 && i->race2CategoryId == id2) { return i; } if (i->race1CategoryId == id2 && i->race2CategoryId == id1) { return i; } } return nullptr; } std::uint32_t* __fastcall getCurrentRelationHooked(const game::CMidDiplomacy* thisptr, int /*%edx*/, std::uint32_t* current, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { const auto* relation = findRelation(thisptr->relations, race1, race2); if (!relation) { *current = 0u; } else { *current = (relation->relation >> 1) & 0x7fu; } return current; } std::uint32_t* __fastcall getPreviousRelationHooked(const game::CMidDiplomacy* thisptr, int /*%edx*/, std::uint32_t* previous, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { const auto* relation = findRelation(thisptr->relations, race1, race2); if (!relation) { *previous = 0u; } else { *previous = (relation->relation >> 8) & 0x7fu; } return previous; } bool __fastcall areAlliesHooked(const game::CMidDiplomacy* thisptr, int /*%edx*/, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { const auto* relation = findRelation(thisptr->relations, race1, race2); if (!relation) { return false; } return relation->relation & 1u; } std::uint32_t* __fastcall getAllianceTurnHooked(const game::CMidDiplomacy* thisptr, int /*%edx*/, std::uint32_t* turn, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { const auto* relation = findRelation(thisptr->relations, race1, race2); if (!relation) { *turn = 0u; } else { *turn = (relation->relation << 2u) >> 17u; } return turn; } bool __fastcall areAlwaysAtWarHooked(const game::CMidDiplomacy* thisptr, int /*%edx*/, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { const auto* relation = findRelation(thisptr->relations, race1, race2); if (!relation) { return false; } return (relation->relation >> 30u) & 1u; } bool __fastcall aiCouldNotBreakAllianceHooked(const game::CMidDiplomacy* thisptr, int /*%edx*/, const game::LRaceCategory* race1, const game::LRaceCategory* race2) { const auto* relation = findRelation(thisptr->relations, race1, race2); if (!relation) { return false; } return relation->relation >> 31u; } bool __stdcall areRelationsAtWarHooked(const std::uint32_t* relation) { using namespace game; const GlobalData* data = *GlobalDataApi::get().getGlobalData(); const GlobalVariables* variables = *data->globalVariables; return *relation <= variables->diplomacyWar; } bool __stdcall areRelationsNeutralHooked(const std::uint32_t* relation) { using namespace game; const GlobalData* data = *GlobalDataApi::get().getGlobalData(); const GlobalVariables* variables = *data->globalVariables; return *relation > variables->diplomacyWar && *relation <= variables->diplomacyNeutral; } bool __stdcall areRelationsPeacefulHooked(const std::uint32_t* relation) { using namespace game; const GlobalData* data = *GlobalDataApi::get().getGlobalData(); const GlobalVariables* variables = *data->globalVariables; return *relation > variables->diplomacyNeutral; } }
5,743
C++
.cpp
142
30.070423
91
0.58794
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,831
transformselfhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/transformselfhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "transformselfhooks.h" #include "attack.h" #include "batattacktransformself.h" #include "battleattackinfo.h" #include "battlemsgdata.h" #include "battlemsgdataview.h" #include "customattacks.h" #include "game.h" #include "gameutils.h" #include "globaldata.h" #include "intset.h" #include "itemview.h" #include "log.h" #include "midgardobjectmap.h" #include "midplayer.h" #include "midunit.h" #include "scripts.h" #include "settings.h" #include "unitgenerator.h" #include "unitimplview.h" #include "unitutils.h" #include "unitview.h" #include "ussoldier.h" #include "usunitimpl.h" #include "utils.h" #include "visitors.h" #include <fmt/format.h> namespace hooks { static int getTransformSelfLevel(const game::CMidUnit* unit, game::TUsUnitImpl* transformImpl, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::BattleMsgData* battleMsgData) { using namespace game; // The function is only accessed by the server thread - the single instance is enough. static std::optional<sol::environment> env; static std::optional<sol::function> getLevel; const auto path{scriptsFolder() / "transformSelf.lua"}; if (!env && !getLevel) { getLevel = getScriptFunction(path, "getLevel", env, true, true); } if (!getLevel) { return 0; } try { const bindings::UnitView attacker{unit}; const bindings::UnitImplView impl{transformImpl}; const bindings::BattleMsgDataView battleView{battleMsgData, objectMap}; if (CMidgardIDApi::get().getType(unitOrItemId) == IdType::Item) { const bindings::ItemView itemView{unitOrItemId, objectMap}; return (*getLevel)(attacker, impl, &itemView, battleView); } else return (*getLevel)(attacker, impl, nullptr, battleView); } catch (const std::exception& e) { showErrorMessageBox(fmt::format("Failed to run '{:s}' script.\n" "Reason: '{:s}'", path.string(), e.what())); return 0; } } static int getTransformSelfFreeAttackNumberDefault(int attacksDone, int attacksRemain, bool hadDoubleAttack, bool hasDoubleAttack) { if (!hadDoubleAttack && hasDoubleAttack && attacksDone == 0) { // Give 2 extra attacks if transforming from single to double attack. // attacksDone prevents infinite abuse of 2 extra attacks: // do normal attack -> transform to single-attack -> transform back to double-attack // -> do normal attack -> ... return 2; } else if (hadDoubleAttack && !hasDoubleAttack && attacksRemain > 0) { // Give nothing if transforming from double to single attack with attacks remain return 0; } else { // Give 1 extra attack to compensate transformation return 1; } } static int getTransformSelfFreeAttackNumber(int attacksDone, int attacksRemain, bool hadDoubleAttack, bool hasDoubleAttack) { std::optional<sol::environment> env; auto f = getScriptFunction(scriptsFolder() / "transformSelf.lua", "getFreeAttackNumber", env, false, true); if (!f) return getTransformSelfFreeAttackNumberDefault(attacksDone, attacksRemain, hadDoubleAttack, hasDoubleAttack); try { return (*f)(attacksDone, attacksRemain, hadDoubleAttack, hasDoubleAttack); } catch (const std::exception& e) { showErrorMessageBox(fmt::format("Failed to run 'getFreeAttackNumber' script.\n" "Reason: '{:s}'", e.what())); return 0; } } void giveFreeTransformSelfAttack(game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, const game::CMidUnit* unit, bool prevAttackTwice) { using namespace game; const auto& battleApi = BattleMsgDataApi::get(); auto& freeTransformSelf = getCustomAttacks().freeTransformSelf; if (freeTransformSelf.turnCount > 0) // Can be 0 if this is the very first turn in battle freeTransformSelf.turnCount--; // Not counting transform action as a turn if (freeTransformSelf.used) { if (!userSettings().freeTransformSelfAttackInfinite) return; // Prevents AI from falling into infinite transforming in case of targeting malfunction if (battleApi.isAutoBattle(battleMsgData)) { return; } auto player = getPlayer(objectMap, battleMsgData, &unit->id); if (!player || !player->isHuman) return; } freeTransformSelf.used = true; for (auto& turn : battleMsgData->turnsOrder) { if (turn.unitId == unit->id) { const auto soldier = gameFunctions().castUnitImplToSoldier(unit->unitImpl); bool attackTwice = soldier && soldier->vftable->getAttackTwice(soldier); turn.attackCount += getTransformSelfFreeAttackNumber(freeTransformSelf.turnCount, turn.attackCount - 1, prevAttackTwice, attackTwice); break; } } } void __fastcall transformSelfAttackOnHitHooked(game::CBatAttackTransformSelf* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId, game::BattleAttackInfo** attackInfo) { using namespace game; const auto& fn = gameFunctions(); bool targetSelf = thisptr->unitId == *targetUnitId; if (!targetSelf) { auto altAttack = thisptr->altAttack; if (altAttack) { altAttack->vftable->onHit(altAttack, objectMap, battleMsgData, targetUnitId, attackInfo); return; } } auto attack = fn.getAttackById(objectMap, &thisptr->id2, thisptr->attackNumber, false); CMidgardID targetGroupId{emptyId}; fn.getAllyOrEnemyGroupId(&targetGroupId, battleMsgData, targetUnitId, true); const auto position = fn.getUnitPositionInGroup(objectMap, &targetGroupId, targetUnitId); const CMidUnit* targetUnit = fn.findUnitById(objectMap, targetUnitId); const CMidgardID targetUnitImplId{targetUnit->unitImpl->id}; CMidgardID transformImplId{emptyId}; fn.getSummonUnitImplIdByAttack(&transformImplId, &attack->id, position, isUnitSmall(targetUnit)); if (transformImplId == emptyId) { return; } if (userSettings().leveledTransformSelfAttack) { const auto& global = GlobalDataApi::get(); auto globalData = *global.getGlobalData(); auto transformImpl = static_cast<TUsUnitImpl*>( global.findById(globalData->units, &transformImplId)); const auto transformLevel = getTransformSelfLevel(targetUnit, transformImpl, objectMap, &thisptr->id2, battleMsgData); CUnitGenerator* unitGenerator = globalData->unitGenerator; CMidgardID leveledImplId{transformImplId}; unitGenerator->vftable->generateUnitImplId(unitGenerator, &leveledImplId, &transformImplId, transformLevel); unitGenerator->vftable->generateUnitImpl(unitGenerator, &leveledImplId); transformImplId = leveledImplId; } const auto targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); bool prevAttackTwice = targetSoldier && targetSoldier->vftable->getAttackTwice(targetSoldier); const auto& visitors = VisitorApi::get(); visitors.transformUnit(targetUnitId, &transformImplId, false, objectMap, 1); if (!targetSelf) updateAttackCountAfterTransformation(battleMsgData, targetUnit, prevAttackTwice); else if (userSettings().freeTransformSelfAttack) giveFreeTransformSelfAttack(objectMap, battleMsgData, targetUnit, prevAttackTwice); BattleAttackUnitInfo info{}; info.unitId = *targetUnitId; info.unitImplId = targetUnitImplId; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); const auto& battle = BattleMsgDataApi::get(); battle.removeTransformStatuses(targetUnitId, battleMsgData); battle.setUnitStatus(battleMsgData, targetUnitId, BattleStatus::TransformSelf, true); battle.setUnitHp(battleMsgData, targetUnitId, targetUnit->currentHp); } void __fastcall transformSelfAttackFillTargetsListHooked(game::CBatAttackTransformSelf* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::TargetSet* targetsList) { using namespace game; const auto& fn = gameFunctions(); const auto& intSetApi = IntSetApi::get(); CMidgardID unitGroupId{emptyId}; fn.getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, &thisptr->unitId, true); int unitPosition = fn.getUnitPositionInGroup(objectMap, &unitGroupId, &thisptr->unitId); auto altAttack = thisptr->altAttack; if (altAttack) { altAttack->vftable->fillTargetsList(altAttack, objectMap, battleMsgData, targetsList); CMidgardID targetGroupId{emptyId}; altAttack->vftable->getTargetGroupId(altAttack, &targetGroupId, battleMsgData); if (targetGroupId != unitGroupId) unitPosition = -(unitPosition + 1); } Pair<TargetSetIterator, bool> tmp{}; intSetApi.insert(targetsList, &tmp, &unitPosition); } } // namespace hooks
11,332
C++
.cpp
236
36.59322
99
0.62914
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,832
unitmodifier.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitmodifier.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitmodifier.h" #include "version.h" #include <array> namespace game::TUnitModifierApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x58aa75, }, // Russobit Api{ (Api::Constructor)0x58aa75, }, // Gog Api{ (Api::Constructor)0x589be4, }, // Scenario Editor Api{ (Api::Constructor)0x535801, }, }}; static std::array<TUnitModifierVftable*, 4> vftables = {{ // Akella (TUnitModifierVftable*)0x6ea674, // Russobit (TUnitModifierVftable*)0x6ea674, // Gog (TUnitModifierVftable*)0x6e8614, // Scenario Editor (TUnitModifierVftable*)0x5def8c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const TUnitModifierVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::TUnitModifierApi
1,767
C++
.cpp
61
25.606557
72
0.709829
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,833
eventeffectcat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/eventeffectcat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "eventeffectcat.h" #include "version.h" #include <array> namespace game { namespace EventEffectCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LEventEffectCategory*)0x839c58, (LEventEffectCategory*)0x839cf8, (LEventEffectCategory*)0x839c98, (LEventEffectCategory*)0x839ce8, (LEventEffectCategory*)0x839d48, (LEventEffectCategory*)0x839cb8, (LEventEffectCategory*)0x839c18, (LEventEffectCategory*)0x839ca8, (LEventEffectCategory*)0x839c68, (LEventEffectCategory*)0x839bf8, (LEventEffectCategory*)0x839c88, (LEventEffectCategory*)0x839c78, (LEventEffectCategory*)0x839cc8, (LEventEffectCategory*)0x839d28, (LEventEffectCategory*)0x839d08, (LEventEffectCategory*)0x839c28, (LEventEffectCategory*)0x839c48, (LEventEffectCategory*)0x839c08, (LEventEffectCategory*)0x839be8, (LEventEffectCategory*)0x839c38, (LEventEffectCategory*)0x839d38, (LEventEffectCategory*)0x839d18, (LEventEffectCategory*)0x839cd8, (LEventEffectCategory*)0x839d58, }, // Russobit Categories{ (LEventEffectCategory*)0x839c58, (LEventEffectCategory*)0x839cf8, (LEventEffectCategory*)0x839c98, (LEventEffectCategory*)0x839ce8, (LEventEffectCategory*)0x839d48, (LEventEffectCategory*)0x839cb8, (LEventEffectCategory*)0x839c18, (LEventEffectCategory*)0x839ca8, (LEventEffectCategory*)0x839c68, (LEventEffectCategory*)0x839bf8, (LEventEffectCategory*)0x839c88, (LEventEffectCategory*)0x839c78, (LEventEffectCategory*)0x839cc8, (LEventEffectCategory*)0x839d28, (LEventEffectCategory*)0x839d08, (LEventEffectCategory*)0x839c28, (LEventEffectCategory*)0x839c48, (LEventEffectCategory*)0x839c08, (LEventEffectCategory*)0x839be8, (LEventEffectCategory*)0x839c38, (LEventEffectCategory*)0x839d38, (LEventEffectCategory*)0x839d18, (LEventEffectCategory*)0x839cd8, (LEventEffectCategory*)0x839d58, }, // Gog Categories{ (LEventEffectCategory*)0x837c08, (LEventEffectCategory*)0x837ca8, (LEventEffectCategory*)0x837c48, (LEventEffectCategory*)0x837c98, (LEventEffectCategory*)0x837cf8, (LEventEffectCategory*)0x837c68, (LEventEffectCategory*)0x837bc8, (LEventEffectCategory*)0x837c58, (LEventEffectCategory*)0x837c18, (LEventEffectCategory*)0x837ba8, (LEventEffectCategory*)0x837c38, (LEventEffectCategory*)0x837c28, (LEventEffectCategory*)0x837c78, (LEventEffectCategory*)0x837cd8, (LEventEffectCategory*)0x837cb8, (LEventEffectCategory*)0x837bd8, (LEventEffectCategory*)0x837bf8, (LEventEffectCategory*)0x837bb8, (LEventEffectCategory*)0x837b98, (LEventEffectCategory*)0x837be8, (LEventEffectCategory*)0x837ce8, (LEventEffectCategory*)0x837cc8, (LEventEffectCategory*)0x837c88, (LEventEffectCategory*)0x837d08, }, // Scenario Editor Categories{ (LEventEffectCategory*)0x6654a8, (LEventEffectCategory*)0x665548, (LEventEffectCategory*)0x6654e8, (LEventEffectCategory*)0x665538, (LEventEffectCategory*)0x665598, (LEventEffectCategory*)0x665508, (LEventEffectCategory*)0x665468, (LEventEffectCategory*)0x6654f8, (LEventEffectCategory*)0x6654b8, (LEventEffectCategory*)0x665448, (LEventEffectCategory*)0x6654d8, (LEventEffectCategory*)0x6654c8, (LEventEffectCategory*)0x665518, (LEventEffectCategory*)0x665578, (LEventEffectCategory*)0x665558, (LEventEffectCategory*)0x665478, (LEventEffectCategory*)0x665498, (LEventEffectCategory*)0x665458, (LEventEffectCategory*)0x665438, (LEventEffectCategory*)0x665488, (LEventEffectCategory*)0x665588, (LEventEffectCategory*)0x665568, (LEventEffectCategory*)0x665528, (LEventEffectCategory*)0x6655a8, }, }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6eac24, // Russobit (const void*)0x6eac24, // Gog (const void*)0x6e8bc4, // Scenario Editor (const void*)0x5cf014, }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace EventEffectCategories namespace LEventEffectCategoryTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x58e57a, (Api::Init)0x58e8ad, (Api::ReadCategory)0x58e925, (Api::InitDone)0x58e868, (Api::FindCategoryById)nullptr, }, // Russobit Api{ (Api::Constructor)0x58e57a, (Api::Init)0x58e8ad, (Api::ReadCategory)0x58e925, (Api::InitDone)0x58e868, (Api::FindCategoryById)nullptr, }, // Gog Api{ (Api::Constructor)0x58d68f, (Api::Init)0x58d9c2, (Api::ReadCategory)0x58da3a, (Api::InitDone)0x58d97d, (Api::FindCategoryById)nullptr, }, // Scenario Editor Api{ (Api::Constructor)0x532bd7, (Api::Init)0x532f0a, (Api::ReadCategory)0x532f82, (Api::InitDone)0x532ec5, (Api::FindCategoryById)nullptr, }, }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6eac2c, // Russobit (const void*)0x6eac2c, // Gog (const void*)0x6e8bcc, // Scenario Editor (const void*)0x5de9cc, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace LEventEffectCategoryTableApi } // namespace game
6,966
C++
.cpp
211
26.630332
72
0.688279
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,834
isolayers.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/isolayers.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "isolayers.h" #include "version.h" #include <array> namespace game { // clang-format off static std::array<IsoLayers, 4> layers = {{ // Akella IsoLayers{ (CIsoLayer*)0x83a62c, (CIsoLayer*)0x83a654, (CIsoLayer*)0x83a5a4, (CIsoLayer*)0x83a5bc, (CIsoLayer*)0x83a594, (CIsoLayer*)0x83a5b4, (CIsoLayer*)0x83a610, (CIsoLayer*)0x83a5f8, (CIsoLayer*)0x83a5ac, (CIsoLayer*)0x83a5ec, (CIsoLayer*)0x83a68c, (CIsoLayer*)0x83a65c, (CIsoLayer*)0x83a630, (CIsoLayer*)0x83a5f0, (CIsoLayer*)0x83a628, (CIsoLayer*)0x83a660, (CIsoLayer*)0x83a608, (CIsoLayer*)0x83a680, (CIsoLayer*)0x83a5c4, (CIsoLayer*)0x83a580, (CIsoLayer*)0x83a624, (CIsoLayer*)0x83a658, (CIsoLayer*)0x83a684, (CIsoLayer*)0x83a5f4, (CIsoLayer*)0x83a604, (CIsoLayer*)0x83a5c0, (CIsoLayer*)0x83a5c8, (CIsoLayer*)0x83a668, (CIsoLayer*)0x83a5b8, (CIsoLayer*)0x83a67c, (CIsoLayer*)0x83a5fc, (CIsoLayer*)0x83a58c, (CIsoLayer*)0x83a690, (CIsoLayer*)0x83a614, (CIsoLayer*)0x83a674, (CIsoLayer*)0x83a5a0, (CIsoLayer*)0x83a678, (CIsoLayer*)0x83a588, (CIsoLayer*)0x83a59c, (CIsoLayer*)0x83a600, (CIsoLayer*)0x83a61c, (CIsoLayer*)0x83a5a8, (CIsoLayer*)0x83a670, (CIsoLayer*)0x83a664, (CIsoLayer*)0x83a584, (CIsoLayer*)0x83a688, (CIsoLayer*)0x83a5b0, (CIsoLayer*)0x83a620, (CIsoLayer*)0x83a66c, (CIsoLayer*)0x83a590, (CIsoLayer*)0x83a598, (CIsoLayer*)0x83a694, }, // Russobit IsoLayers{ (CIsoLayer*)0x83a62c, (CIsoLayer*)0x83a654, (CIsoLayer*)0x83a5a4, (CIsoLayer*)0x83a5bc, (CIsoLayer*)0x83a594, (CIsoLayer*)0x83a5b4, (CIsoLayer*)0x83a610, (CIsoLayer*)0x83a5f8, (CIsoLayer*)0x83a5ac, (CIsoLayer*)0x83a5ec, (CIsoLayer*)0x83a68c, (CIsoLayer*)0x83a65c, (CIsoLayer*)0x83a630, (CIsoLayer*)0x83a5f0, (CIsoLayer*)0x83a628, (CIsoLayer*)0x83a660, (CIsoLayer*)0x83a608, (CIsoLayer*)0x83a680, (CIsoLayer*)0x83a5c4, (CIsoLayer*)0x83a580, (CIsoLayer*)0x83a624, (CIsoLayer*)0x83a658, (CIsoLayer*)0x83a684, (CIsoLayer*)0x83a5f4, (CIsoLayer*)0x83a604, (CIsoLayer*)0x83a5c0, (CIsoLayer*)0x83a5c8, (CIsoLayer*)0x83a668, (CIsoLayer*)0x83a5b8, (CIsoLayer*)0x83a67c, (CIsoLayer*)0x83a5fc, (CIsoLayer*)0x83a58c, (CIsoLayer*)0x83a690, (CIsoLayer*)0x83a614, (CIsoLayer*)0x83a674, (CIsoLayer*)0x83a5a0, (CIsoLayer*)0x83a678, (CIsoLayer*)0x83a588, (CIsoLayer*)0x83a59c, (CIsoLayer*)0x83a600, (CIsoLayer*)0x83a61c, (CIsoLayer*)0x83a5a8, (CIsoLayer*)0x83a670, (CIsoLayer*)0x83a664, (CIsoLayer*)0x83a584, (CIsoLayer*)0x83a688, (CIsoLayer*)0x83a5b0, (CIsoLayer*)0x83a620, (CIsoLayer*)0x83a66c, (CIsoLayer*)0x83a590, (CIsoLayer*)0x83a598, (CIsoLayer*)0x83a694, }, // Gog IsoLayers{ (CIsoLayer*)0x8385d8, (CIsoLayer*)0x8385fc, (CIsoLayer*)0x838554, (CIsoLayer*)0x83856c, (CIsoLayer*)0x838544, (CIsoLayer*)0x838564, (CIsoLayer*)0x8385bc, (CIsoLayer*)0x838588, (CIsoLayer*)0x83855c, (CIsoLayer*)0x83857c, (CIsoLayer*)0x838638, (CIsoLayer*)0x838604, (CIsoLayer*)0x8385dc, (CIsoLayer*)0x838580, (CIsoLayer*)0x8385d4, (CIsoLayer*)0x838608, (CIsoLayer*)0x8385b8, (CIsoLayer*)0x83862c, (CIsoLayer*)0x838574, (CIsoLayer*)0x838530, (CIsoLayer*)0x8385d0, (CIsoLayer*)0x838600, (CIsoLayer*)0x838630, (CIsoLayer*)0x838584, (CIsoLayer*)0x8385b4, (CIsoLayer*)0x838570, (CIsoLayer*)0x838578, (CIsoLayer*)0x838614, (CIsoLayer*)0x838568, (CIsoLayer*)0x838628, (CIsoLayer*)0x83858c, (CIsoLayer*)0x83853c, (CIsoLayer*)0x83863c, (CIsoLayer*)0x8385c0, (CIsoLayer*)0x838620, (CIsoLayer*)0x838550, (CIsoLayer*)0x838624, (CIsoLayer*)0x838538, (CIsoLayer*)0x83854c, (CIsoLayer*)0x838590, (CIsoLayer*)0x8385c8, (CIsoLayer*)0x838558, (CIsoLayer*)0x83861c, (CIsoLayer*)0x838610, (CIsoLayer*)0x838534, (CIsoLayer*)0x838634, (CIsoLayer*)0x838560, (CIsoLayer*)0x8385cc, (CIsoLayer*)0x838618, (CIsoLayer*)0x838540, (CIsoLayer*)0x838548, (CIsoLayer*)0x838640, }, // Scenario Editor IsoLayers{ (CIsoLayer*)0x6661ac, (CIsoLayer*)0x6661d4, (CIsoLayer*)0x666124, (CIsoLayer*)0x66613c, (CIsoLayer*)0x666114, (CIsoLayer*)0x666134, (CIsoLayer*)0x666190, (CIsoLayer*)0x666178, (CIsoLayer*)0x66612c, (CIsoLayer*)0x66616c, (CIsoLayer*)0x66620c, (CIsoLayer*)0x6661dc, (CIsoLayer*)0x6661b0, (CIsoLayer*)0x666170, (CIsoLayer*)0x6661a8, (CIsoLayer*)0x6661e0, (CIsoLayer*)0x666188, (CIsoLayer*)0x666200, (CIsoLayer*)0x666144, (CIsoLayer*)0x666100, (CIsoLayer*)0x6661a4, (CIsoLayer*)0x6661d8, (CIsoLayer*)0x666204, (CIsoLayer*)0x666174, (CIsoLayer*)0x666184, (CIsoLayer*)0x666140, (CIsoLayer*)0x666148, (CIsoLayer*)0x6661e8, (CIsoLayer*)0x666138, (CIsoLayer*)0x6661fc, (CIsoLayer*)0x66617c, (CIsoLayer*)0x66610c, (CIsoLayer*)0x666210, (CIsoLayer*)0x666194, (CIsoLayer*)0x6661f4, (CIsoLayer*)0x666120, (CIsoLayer*)0x6661f8, (CIsoLayer*)0x666108, (CIsoLayer*)0x66611c, (CIsoLayer*)0x666180, (CIsoLayer*)0x66619c, (CIsoLayer*)0x666128, (CIsoLayer*)0x6661f0, (CIsoLayer*)0x6661e4, (CIsoLayer*)0x666104, (CIsoLayer*)0x666208, (CIsoLayer*)0x666130, (CIsoLayer*)0x6661a0, (CIsoLayer*)0x6661ec, (CIsoLayer*)0x666110, (CIsoLayer*)0x666118, (CIsoLayer*)0x666214, }, }}; // clang-format on IsoLayers& isoLayers() { return layers[static_cast<int>(hooks::gameVersion())]; } } // namespace game
7,480
C++
.cpp
251
21.876494
72
0.608112
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,835
batattackuntransformeffect.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batattackuntransformeffect.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batattackuntransformeffect.h" #include "version.h" #include <array> namespace game::CBatAttackUntransformEffectApi { // clang-format off static std::array<IBatAttackVftable*, 4> vftables = {{ // Akella (IBatAttackVftable*)0x6f5624, // Russobit (IBatAttackVftable*)0x6f5624, // Gog (IBatAttackVftable*)0x6f35d4, // Scenario Editor (IBatAttackVftable*)nullptr, }}; // clang-format on IBatAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CBatAttackUntransformEffectApi
1,388
C++
.cpp
39
33.102564
72
0.755952
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,836
groupupgradehooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/groupupgradehooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "groupupgradehooks.h" #include "battleattackinfo.h" #include "battlemsgdata.h" #include "battleutils.h" #include "game.h" #include "gameutils.h" #include "midunit.h" #include "settings.h" #include "unitutils.h" #include "usunitimpl.h" #include "visitors.h" namespace hooks { int changeUnitXpAndUpgrade(game::IMidgardObjectMap* objectMap, game::CMidUnit* unit, const game::CMidgardID* groupId, const game::CMidgardID* playerId, game::BattleAttackInfo** attackInfo, int xpReceived) { using namespace game; const auto& fn = gameFunctions(); int xpAdded = 0; bool infoAdded = false; while (xpReceived - xpAdded > 0) { if (fn.isUnitTierMax(objectMap, playerId, &unit->id) && !fn.isUnitLevelNotMax(objectMap, playerId, &unit->id)) { break; } auto previousXp = unit->currentXp; if (!fn.changeUnitXpCheckUpgrade(objectMap, playerId, &unit->id, xpReceived - xpAdded)) { break; } xpAdded += unit->currentXp - previousXp; auto upgradeUnitImpl = fn.getUpgradeUnitImplCheckXp(objectMap, unit); if (!upgradeUnitImpl) { break; } if (!infoAdded) { infoAdded = true; BattleAttackUnitInfo info{}; info.unitId = unit->id; info.unitImplId = unit->unitImpl->id; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); } if (!VisitorApi::get().upgradeUnit(&unit->id, &upgradeUnitImpl->id, groupId, objectMap, 1)) { break; } if (!userSettings().battle.allowMultiUpgrade) { break; } } if (userSettings().battle.carryXpOverUpgrade) { xpAdded += addUnitXpNoUpgrade(objectMap, unit, xpReceived - xpAdded); } return xpAdded; } void changeUnitXpAndUpgrade(game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::UnitInfo* unitInfo, const game::CMidgardID* groupId, const game::CMidgardID* playerId, int unitXp, game::BattleAttackInfo** attackInfo) { using namespace game; const auto& fn = gameFunctions(); const auto& battleApi = BattleMsgDataApi::get(); if (!unitXp) { unitInfo->unitXp = 0; return; } const auto unitId = unitInfo->unitId1; if (battleApi.getUnitStatus(battleMsgData, &unitId, BattleStatus::Dead) || battleApi.getUnitStatus(battleMsgData, &unitId, BattleStatus::Hidden) || battleApi.getUnitStatus(battleMsgData, &unitId, BattleStatus::Unsummoned) || battleApi.getUnitStatus(battleMsgData, &unitId, BattleStatus::Summon)) { unitInfo->unitXp = 0; return; } auto unit = fn.findUnitById(objectMap, &unitId); int xpReceived = adjustUnitXpReceived(battleMsgData, unit, unitXp); int xpAdded = changeUnitXpAndUpgrade(objectMap, unit, groupId, playerId, attackInfo, xpReceived); unitInfo->unitXp = xpAdded > 0 ? xpAdded : 0; // Negative xpAdded overflows unsigned unitXp unitInfo->unitHp = unit->currentHp; } void validateUnitAndUpdateInfo(game::IMidgardObjectMap* objectMap, game::UnitInfo* unitInfo) { using namespace game; const auto& fn = gameFunctions(); auto unit = fn.findUnitById(objectMap, &unitInfo->unitId1); if (validateUnit(unit)) { unitInfo->unitHp = unit->currentHp; } } int getXpPercent(game::IMidgardObjectMap* objectMap, const game::CMidgardID* groupId, const game::CMidgardID* playerId, bool playableRaceAi) { if (!canGroupGainXp(objectMap, groupId)) { return 0; } // Yes, xp bonuses are multiplicative int result = 100 + getWeaponMasterBonusXpPercent(objectMap, groupId); result += result * getEasyDifficultyBonusXpPercent(objectMap, playerId) / 100; if (playableRaceAi) { result += result * getAiBonusXpPercent(objectMap) / 100; } return result; } void __stdcall upgradeGroupHooked(game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, const game::CMidgardID* groupId, game::BattleAttackInfo** attackInfo, bool playableRaceAi) { using namespace game; bool isAttacker = battleMsgData->attackerGroupId == *groupId; auto playerId = isAttacker ? battleMsgData->attackerPlayerId : battleMsgData->defenderPlayerId; int xpPercent = getXpPercent(objectMap, groupId, &playerId, playableRaceAi); for (auto& unitInfo : battleMsgData->unitsInfo) { if (unitInfo.unitId1 != invalidId && !unitInfo.unknown2 && unitInfo.unitFlags.parts.attacker == isAttacker) { changeUnitXpAndUpgrade(objectMap, battleMsgData, &unitInfo, groupId, &playerId, unitInfo.unitXp * xpPercent / 100, attackInfo); } } for (auto& unitInfo : battleMsgData->unitsInfo) { if (unitInfo.unitId1 != invalidId && !unitInfo.unknown2 && unitInfo.unitFlags.parts.attacker == isAttacker) { validateUnitAndUpdateInfo(objectMap, &unitInfo); } } } } // namespace hooks
6,422
C++
.cpp
155
32.393548
99
0.635679
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,837
taskchangecolor.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/taskchangecolor.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "taskchangecolor.h" namespace game::editor::CTaskChangeColorApi { Api& get() { static Api api{(Api::Constructor)0x4065a2, (Api::GetTerrain)0x40679c}; return api; } } // namespace game::editor::CTaskChangeColorApi
1,047
C++
.cpp
26
38.115385
74
0.760827
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,838
summonhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/summonhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "summonhooks.h" #include "attack.h" #include "batattacksummon.h" #include "battleattackinfo.h" #include "battlemsgdata.h" #include "battlemsgdataview.h" #include "game.h" #include "globaldata.h" #include "itemview.h" #include "log.h" #include "midgardobjectmap.h" #include "midunit.h" #include "midunitgroup.h" #include "scripts.h" #include "unitgenerator.h" #include "unitimplview.h" #include "unitview.h" #include "ussoldier.h" #include "usunitimpl.h" #include "utils.h" #include "visitors.h" #include <fmt/format.h> namespace hooks { static int getSummonLevel(const game::CMidUnit* summoner, game::TUsUnitImpl* summonImpl, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::BattleMsgData* battleMsgData) { using namespace game; // The function is only accessed by the server thread - the single instance is enough. static std::optional<sol::environment> env; static std::optional<sol::function> getLevel; const auto path{scriptsFolder() / "summon.lua"}; if (!env && !getLevel) { getLevel = getScriptFunction(path, "getLevel", env, true, true); } if (!getLevel) { return 0; } try { const bindings::UnitView summonerUnit{summoner}; const bindings::UnitImplView impl{summonImpl}; const bindings::BattleMsgDataView battleView{battleMsgData, objectMap}; if (CMidgardIDApi::get().getType(unitOrItemId) == IdType::Item) { const bindings::ItemView itemView{unitOrItemId, objectMap}; return (*getLevel)(summonerUnit, impl, &itemView, battleView); } else return (*getLevel)(summonerUnit, impl, nullptr, battleView); } catch (const std::exception& e) { showErrorMessageBox(fmt::format("Failed to run '{:s}' script.\n" "Reason: '{:s}'", path.string(), e.what())); return 0; } } void __fastcall summonAttackOnHitHooked(game::CBatAttackSummon* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId, game::BattleAttackInfo** attackInfo) { using namespace game; CMidgardID targetGroupId{emptyId}; thisptr->vftable->getTargetGroupId(thisptr, &targetGroupId, battleMsgData); const auto& fn = gameFunctions(); void* tmp{}; auto targetGroup = fn.getStackFortRuinGroup(tmp, objectMap, &targetGroupId); const auto& idApi = CMidgardIDApi::get(); CMidgardID maybeSummonId{emptyId}; idApi.isSummonUnitId(&maybeSummonId, targetUnitId); const auto& groupApi = CMidUnitGroupApi::get(); int position{-1}; if (maybeSummonId == emptyId) { // Target unit exists, we can get its position from group directly position = groupApi.getUnitPosition(targetGroup, targetUnitId); } else { // Target unit does not exist, 'targetUnitId' contains special id for summon. position = idApi.summonUnitIdToPosition(&maybeSummonId); } if (position < 0 || position >= 6) { logError("mssProxyError.log", fmt::format("Wrong position for summon. Target unit id {:s}", idToString(targetUnitId))); return; } const bool positionEven = position % 2 == 0; const int bigUnitSecondPosition = positionEven ? position + 1 : position - 1; CMidgardID bigUnitSummonId{emptyId}; idApi.summonUnitIdFromPosition(&bigUnitSummonId, bigUnitSecondPosition); const bool canSummonBig = thisptr->vftable->canPerform(thisptr, objectMap, battleMsgData, &bigUnitSummonId); auto attackId = &thisptr->attack->id; CMidgardID summonImplId{emptyId}; fn.getSummonUnitImplId(&summonImplId, objectMap, attackId, &targetGroupId, targetUnitId, canSummonBig); if (summonImplId == emptyId) { logError("mssProxyError.log", fmt::format("Could not find unit impl id for summon. " "Attack {:s}, group {:s}, target unit {:s}, can summon big {:d}", idToString(attackId), idToString(&targetGroupId), idToString(targetUnitId), (int)canSummonBig)); return; } const auto& global = GlobalDataApi::get(); auto globalData = *global.getGlobalData(); auto summoner = fn.findUnitById(objectMap, &thisptr->unitId); auto summonImpl = static_cast<TUsUnitImpl*>(global.findById(globalData->units, &summonImplId)); const auto summonLevel = getSummonLevel(summoner, summonImpl, objectMap, &thisptr->unitOrItemId, battleMsgData); CUnitGenerator* unitGenerator = globalData->unitGenerator; CMidgardID leveledImplId{summonImplId}; unitGenerator->vftable->generateUnitImplId(unitGenerator, &leveledImplId, &summonImplId, summonLevel); unitGenerator->vftable->generateUnitImpl(unitGenerator, &leveledImplId); auto unitImpl = static_cast<TUsUnitImpl*>(global.findById(globalData->units, &leveledImplId)); if (!unitImpl) { logError("mssProxyError.log", fmt::format("Could not find unit impl by id {:s}. Base impl id {:s}, level {:d}", idToString(&leveledImplId), idToString(&summonImplId), summonLevel)); return; } auto soldier = fn.castUnitImplToSoldier(unitImpl); const auto summonIsBig = !soldier->vftable->getSizeSmall(soldier); if (summonIsBig && !positionEven) { position--; } const auto& visitors = VisitorApi::get(); visitors.forceUnitMax(&targetGroupId, 6, objectMap, 1); const auto& battle = BattleMsgDataApi::get(); auto existingUnitId = groupApi.getUnitIdByPosition(targetGroup, position); if (*existingUnitId != emptyId) { // Remember unit id before extraction. // 'existingUnitId' will point to another id after extraction. const CMidgardID unitIdToExtract = *existingUnitId; if (!visitors.extractUnitFromGroup(&unitIdToExtract, &targetGroupId, objectMap, 1)) { logError("mssProxyError.log", fmt::format("Failed to extract unit {:s} from group {:s}, position {:d}", idToString(&unitIdToExtract), idToString(&targetGroupId), position)); return; } battle.setUnitShown(battleMsgData, &unitIdToExtract, false); } if (summonIsBig) { auto secondExistingUnitId = groupApi.getUnitIdByPosition(targetGroup, position + 1); if (*secondExistingUnitId != emptyId) { const CMidgardID unitIdToExtract = *secondExistingUnitId; if (!visitors.extractUnitFromGroup(&unitIdToExtract, &targetGroupId, objectMap, 1)) { logError("mssProxyError.log", fmt::format("Failed to extract unit {:s} from group {:s}, position {:d}", idToString(&unitIdToExtract), idToString(&targetGroupId), position + 1)); return; } battle.setUnitShown(battleMsgData, &unitIdToExtract, false); } } CMidgardID newUnitId{emptyId}; objectMap->vftable->createScenarioId(objectMap, &newUnitId, IdType::Unit); int creationTurn{1}; if (!visitors.addUnitToGroup(&leveledImplId, &targetGroupId, position, &creationTurn, 1, objectMap, 1)) { logError("mssProxyError.log", fmt::format("Could not add unit impl {:s} to group {:s} at position {:d}", idToString(&leveledImplId), idToString(&targetGroupId), position)); return; } const CMidUnit* newUnit = fn.findUnitById(objectMap, &newUnitId); if (!newUnit) { logError("mssProxyError.log", fmt::format("Could not find unit with id {:s}", idToString(&newUnitId))); return; } BattleAttackUnitInfo info{}; info.unitId = newUnitId; info.unitImplId = newUnit->unitImpl->id; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); battle.addSummonedUnit(battleMsgData, objectMap, &newUnitId, &targetGroupId); battle.setUnitStatus(battleMsgData, &newUnitId, BattleStatus::Summon, true); battle.setSummonOwner(battleMsgData, &newUnitId, &thisptr->unitId); visitors.forceUnitMax(&targetGroupId, -1, objectMap, 1); } } // namespace hooks
9,764
C++
.cpp
202
38.346535
100
0.640412
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,839
idlist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/idlist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "idlist.h" #include "version.h" #include <array> namespace game::IdListApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x407b45, (Api::Destructor)0x407b7e, (Api::Clear)0x56ab57, (Api::PushBack)0x5c9ebd, (Api::PushFront)0x467bbb, (Api::Erase)0x408017, (Api::Find)0x40b8e2, (Api::Shuffle)0x46b079, }, // Russobit Api{ (Api::Constructor)0x407b45, (Api::Destructor)0x407b7e, (Api::Clear)0x56ab57, (Api::PushBack)0x5c9ebd, (Api::PushFront)0x467bbb, (Api::Erase)0x408017, (Api::Find)0x40b8e2, (Api::Shuffle)0x46b079, }, // Gog Api{ (Api::Constructor)0x4077cc, (Api::Destructor)0x407805, (Api::Clear)0x42c2c1, (Api::PushBack)0x56aff7, (Api::PushFront)0x467439, (Api::Erase)0x407ca2, (Api::Find)0x40b5c0, (Api::Shuffle)0x46a9f5, }, // Scenario Editor Api{ (Api::Constructor)0x5456c8, (Api::Destructor)0x4703d7, (Api::Clear)0x470799, (Api::PushBack)0x49bb17, (Api::PushFront)0x4962f4, (Api::Erase)0x408987, (Api::Find)0x440cd1, (Api::Shuffle)0x471a79, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IdListApi
2,259
C++
.cpp
75
24.72
72
0.653511
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,840
midcondgamemode.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midcondgamemode.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midcondgamemode.h" #include "button.h" #include "condinterf.h" #include "condinterfhandler.h" #include "d2string.h" #include "dialoginterf.h" #include "eventconditioncathooks.h" #include "game.h" #include "interfmanager.h" #include "mempool.h" #include "midevcondition.h" #include "midevent.h" #include "mideventhooks.h" #include "midgard.h" #include "midgardobjectmap.h" #include "midgardstream.h" #include "radiobuttoninterf.h" #include "testcondition.h" #include "textids.h" #include "utils.h" namespace hooks { /** Same as RAD_GAME_MODE button indices in DLG_COND_GAME_MODE from ScenEdit.dlg */ enum class GameMode : int { Single, Hotseat, Online, }; /** Custom event condition that checks current game mode. */ struct CMidCondGameMode : public game::CMidEvCondition { GameMode gameMode; }; void __fastcall condGameModeDestructor(CMidCondGameMode* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall condGameModeIsIdsEqual(const CMidCondGameMode*, int /*%edx*/, const game::CMidgardID*) { return false; } void __fastcall condGameModeAddToList(const CMidCondGameMode*, int /*%edx*/, game::Set<game::CMidgardID>*) { } bool __fastcall condGameModeIsValid(const CMidCondGameMode* thisptr, int /*%edx*/, const game::IMidgardObjectMap*) { const auto mode = thisptr->gameMode; return mode == GameMode::Single || mode == GameMode::Hotseat || mode == GameMode::Online; } bool __fastcall condGameModeMethod4(const CMidCondGameMode*, int /*%edx*/, int) { return false; } void __fastcall condGameModeStream(CMidCondGameMode* thisptr, int /*%edx*/, game::IMidgardStream** stream) { auto streamPtr = *stream; auto vftable = streamPtr->vftable; vftable->streamInt(streamPtr, "MODE", (int*)&thisptr->gameMode); } // clang-format off static game::CMidEvConditionVftable condGameModeVftable{ (game::CMidEvConditionVftable::Destructor)condGameModeDestructor, (game::CMidEvConditionVftable::IsIdsEqual)condGameModeIsIdsEqual, (game::CMidEvConditionVftable::AddToList)condGameModeAddToList, (game::CMidEvConditionVftable::IsValid)condGameModeIsValid, (game::CMidEvConditionVftable::Method4)condGameModeMethod4, (game::CMidEvConditionVftable::Stream)condGameModeStream, }; // clang-format on game::CMidEvCondition* createMidCondGameMode() { using namespace game; auto gameMode = (CMidCondGameMode*)Memory::get().allocate(sizeof(CMidCondGameMode)); gameMode->category.vftable = EventCondCategories::vftable(); gameMode->category.id = customEventConditions().gameMode.category.id; gameMode->category.table = customEventConditions().gameMode.category.table; gameMode->gameMode = GameMode::Single; gameMode->vftable = &condGameModeVftable; return gameMode; } void __stdcall midCondGameModeGetInfoString(game::String* info, const game::IMidgardObjectMap* objectMap, const game::CMidEvCondition* eventCondition) { const auto textInfoId = &customEventConditions().gameMode.infoText; std::string str{game::gameFunctions().getInterfaceText(textInfoId)}; const auto gameMode = static_cast<const CMidCondGameMode*>(eventCondition)->gameMode; std::string modeName; const auto& gameModeTextIds = textIds().events.conditions.gameMode; switch (gameMode) { case GameMode::Single: modeName = getInterfaceText(gameModeTextIds.single.c_str()); if (modeName.empty()) { modeName = "single player"; } break; case GameMode::Hotseat: modeName = getInterfaceText(gameModeTextIds.hotseat.c_str()); if (modeName.empty()) { modeName = "hotseat"; } break; case GameMode::Online: modeName = getInterfaceText(gameModeTextIds.online.c_str()); if (modeName.empty()) { modeName = "online"; } break; } replace(str, "%MODE%", modeName); game::StringApi::get().initFromStringN(info, str.c_str(), str.length()); } struct CCondGameModeInterf : public game::editor::CCondInterf { void* unknown; CMidCondGameMode* gameModeCondition; game::CMidgardID eventId; }; void __fastcall condGameModeInterfDestructor(CCondGameModeInterf* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } static game::CInterfaceVftable::OnVisibilityChanged onVisibilityChanged{}; void __fastcall condGameModeInterfOnVisibilityChanged(CCondGameModeInterf* thisptr, int /*%edx*/, int a2, int a3) { using namespace game; if (onVisibilityChanged) { onVisibilityChanged(thisptr, a2, a3); } if (!a2) { return; } if (!thisptr->gameModeCondition) { return; } auto gameMode = thisptr->gameModeCondition->gameMode; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); auto radioButton = dialogApi.findRadioButton(dialog, "RAD_GAME_MODE"); if (radioButton) { CRadioButtonInterfApi::get().setCheckedButton(radioButton, (int)gameMode); } } bool __fastcall condGameModeInterfSetEventCondition(CCondGameModeInterf* thisptr, int /*%edx*/, game::CMidEvCondition* eventCondition) { if (eventCondition->category.id == customEventConditions().gameMode.category.id) { thisptr->gameModeCondition = static_cast<CMidCondGameMode*>(eventCondition); return true; } return false; } static game::editor::CCondInterfVftable condGameModeInterfVftable{}; void __fastcall condGameModeInterfCancelButtonHandler(CCondGameModeInterf* thisptr, int /*%edx*/) { using namespace game; auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, false); } InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } void __fastcall condGameModeInterfOkButtonHandler(CCondGameModeInterf* thisptr, int /*%edx*/) { using namespace game; using namespace editor; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, true); } auto objectMap = CCondInterfApi::get().getObjectMap(thisptr->unknown); { auto midEvent = (const CMidEvent*)objectMap->vftable ->findScenarioObjectById(objectMap, &thisptr->eventId); const int conditionsTotal = midEvent->conditions.end - midEvent->conditions.bgn; if (conditionsTotal >= 10) { // Could not create new condition showMessageBox(getInterfaceText("X100TA0631")); return; } } auto midEvent = (CMidEvent*)objectMap->vftable ->findScenarioObjectByIdForChange(objectMap, &thisptr->eventId); auto gameMode = static_cast<CMidCondGameMode*>(createMidCondGameMode()); auto radioButton = dialogApi.findRadioButton(dialog, "RAD_GAME_MODE"); if (radioButton) { gameMode->gameMode = static_cast<GameMode>(radioButton->data->selectedButton); } CMidEventApi::get().addCondition(midEvent, nullptr, gameMode); InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } game::editor::CCondInterf* createCondGameModeInterf(game::ITask* task, void* a2, const game::CMidgardID* eventId) { using namespace game; using namespace editor; auto thisptr = (CCondGameModeInterf*)Memory::get().allocate(sizeof(CCondGameModeInterf)); static const char dialogName[]{"DLG_COND_GAME_MODE"}; CCondInterfApi::get().constructor(thisptr, dialogName, task); static bool initialized{false}; if (!initialized) { onVisibilityChanged = thisptr->CInterface::vftable->onVisibilityChanged; initialized = true; std::memcpy(&condGameModeInterfVftable, thisptr->CInterface::vftable, sizeof(CInterfaceVftable)); // Change methods that are specific for our custom class condGameModeInterfVftable .destructor = (CInterfaceVftable::Destructor)&condGameModeInterfDestructor; condGameModeInterfVftable .onVisibilityChanged = (CInterfaceVftable:: OnVisibilityChanged)&condGameModeInterfOnVisibilityChanged; condGameModeInterfVftable .setEventCondition = (CCondInterfVftable:: SetEventCondition)&condGameModeInterfSetEventCondition; } thisptr->CInterface::vftable = &condGameModeInterfVftable; thisptr->eventId = *eventId; thisptr->unknown = a2; thisptr->gameModeCondition = nullptr; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); if (dialogApi.findButton(dialog, "BTN_OK")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condGameModeInterfOkButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } if (dialogApi.findButton(dialog, "BTN_CANCEL")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condGameModeInterfCancelButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } return thisptr; } struct CTestGameMode : public game::ITestCondition { CMidCondGameMode* condition; }; void __fastcall testGameModeDestructor(CTestGameMode* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall testGameModeDoTest(const CTestGameMode* thisptr, int /*%edx*/, const game::IMidgardObjectMap*, const game::CMidgardID*, const game::CMidgardID*) { const auto* data = game::CMidgardApi::get().instance()->data; switch (thisptr->condition->gameMode) { case GameMode::Single: return !data->hotseatGame && !data->multiplayerGame; case GameMode::Hotseat: return data->hotseatGame; case GameMode::Online: return data->multiplayerGame && !data->hotseatGame; } return false; } static game::ITestConditionVftable testGameModeVftable{ (game::ITestConditionVftable::Destructor)testGameModeDestructor, (game::ITestConditionVftable::Test)testGameModeDoTest, }; game::ITestCondition* createTestGameMode(game::CMidEvCondition* eventCondition) { auto thisptr = (CTestGameMode*)game::Memory::get().allocate(sizeof(CTestGameMode)); thisptr->condition = static_cast<CMidCondGameMode*>(eventCondition); thisptr->vftable = &testGameModeVftable; return thisptr; } bool checkGameModeConditionValid(game::CDialogInterf*, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* eventId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, eventId); if (!obj) { return false; } const auto& category = customEventConditions().gameMode.category; auto event = static_cast<const CMidEvent*>(obj); std::vector<const CMidEvCondition*> conditions{}; getConditionsOfType(event, &category, conditions); if (conditions.size() > 1) { auto message = getInterfaceText(textIds().events.conditions.gameMode.tooMany.c_str()); if (message.empty()) { message = "Only one condition of type \"Game mode\" is allowed per event."; } showMessageBox(message); return false; } return true; } } // namespace hooks
14,489
C++
.cpp
353
33.300283
100
0.67153
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,841
custombuildingcategories.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/custombuildingcategories.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "custombuildingcategories.h" #include "dbfaccess.h" #include "log.h" #include <fmt/format.h> namespace hooks { static CustomBuildingCategories customBuildingCategories; CustomBuildingCategories& getCustomBuildingCategories() { return customBuildingCategories; } bool addCustomBuildingCategory(const std::filesystem::path& dbfFilePath, game::BuildingBranchNumber branchNumber, const char* text) { using namespace game; if (!utils::dbValueExists(dbfFilePath, "TEXT", text)) { return false; } customBuildingCategories[branchNumber] = {nullptr, nullptr, (BuildingId)emptyCategoryId, text}; logDebug("newBuildingType.log", fmt::format("Found custom building category {:s}", text)); return true; } bool isCustomBuildingCategory(const game::LBuildingCategory* category) { return std::find_if(customBuildingCategories.begin(), customBuildingCategories.end(), [category](const CustomBuildingCategories::value_type& x) -> bool { return x.second.id == category->id; }) != customBuildingCategories.end(); } game::BuildingId getCustomBuildingCategoryId(game::BuildingBranchNumber branchNumber) { using namespace game; auto category = customBuildingCategories.find(branchNumber); if (category != customBuildingCategories.end()) { return category->second.id; } return (BuildingId)emptyCategoryId; } } // namespace hooks
2,356
C++
.cpp
58
35.37931
99
0.723097
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,842
midunitdescriptorhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midunitdescriptorhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midunitdescriptorhooks.h" #include "attack.h" #include "dynamiccast.h" #include "game.h" #include "midgardobjectmap.h" #include "midstack.h" #include "midunit.h" #include "midunitdescriptor.h" #include "unitutils.h" namespace hooks { game::IAttack* __fastcall midUnitDescriptorGetAttackHooked(const game::CMidUnitDescriptor* thisptr, int /*%edx*/) { auto unit = thisptr->unit; if (!unit) return nullptr; return getAttack(unit->unitImpl, true, true); } int __fastcall midUnitDescriptorGetAttackInitiativeHooked(const game::CMidUnitDescriptor* thisptr, int /*%edx*/) { using namespace game; const auto& descriptorApi = CMidUnitDescriptorApi::get(); auto attack = descriptorApi.getAttack(thisptr); return attack->vftable->getInitiative(attack); } bool __fastcall midUnitDescriptorIsUnitLeaderHooked(const game::CMidUnitDescriptor* thisptr, int /*%edx*/) { using namespace game; const auto& fn = gameFunctions(); if (CMidgardIDApi::get().getType(&thisptr->groupId) != IdType::Stack) { // Only stacks can contain leader units return false; } // Fix crash on viewing stack leader transformed to ordinary soldier if (fn.castUnitImplToStackLeader(thisptr->unit->unitImpl) == nullptr) { return false; } auto objectMap{thisptr->objectMap}; auto stackObject{objectMap->vftable->findScenarioObjectById(objectMap, &thisptr->groupId)}; if (!stackObject) { return false; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto stack{(const CMidStack*)dynamicCast(stackObject, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0)}; if (!stack) { return false; } return stack->leaderId == thisptr->unitId; } } // namespace hooks
2,852
C++
.cpp
72
33.166667
99
0.68042
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,843
menurandomscenariomulti.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menurandomscenariomulti.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menurandomscenariomulti.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "gamesettings.h" #include "mempool.h" #include "menunewskirmishmulti.h" #include "menuphase.h" #include "menurandomscenario.h" #include "midgard.h" namespace hooks { static constexpr const char dialogName[] = "DLG_RANDOM_SCENARIO_MULTI"; static constexpr const int gameNameMaxLength{40}; static constexpr const int playerNameMaxLength{15}; static constexpr const int passwordMaxLength{8}; struct CMenuRandomScenarioMulti : public CMenuRandomScenario { CMenuRandomScenarioMulti(game::CMenuPhase* menuPhase); ~CMenuRandomScenarioMulti() = default; }; static void startScenarioNet(CMenuRandomScenario* menu) { prepareToStartRandomScenario(menu, true); using namespace game; // Setup game host: reuse original game logic that creates player server and client if (CMenuNewSkirmishMultiApi::get().createServer(menu)) { CMenuPhaseApi::get().setTransition(menu->menuBaseData->menuPhase, 0); } } CMenuRandomScenarioMulti::CMenuRandomScenarioMulti(game::CMenuPhase* menuPhase) : CMenuRandomScenario(menuPhase, startScenarioNet, dialogName) { using namespace game; const auto& menuBase{CMenuBaseApi::get()}; const auto& dialogApi{CDialogInterfApi::get()}; const auto& editBoxApi{CEditBoxInterfApi::get()}; CDialogInterf* dialog{menuBase.getDialogInterface(this)}; CEditBoxInterf* editName{editBoxApi.setFilterAndLength(dialog, "EDIT_NAME", dialogName, EditFilter::Names, playerNameMaxLength)}; if (editName) { const CMidgard* midgard{CMidgardApi::get().instance()}; const GameSettings* settings{*midgard->data->settings}; editBoxApi.setString(editName, settings->defaultPlayerName.string); } editBoxApi.setFilterAndLength(dialog, "EDIT_GAME", dialogName, EditFilter::Names, gameNameMaxLength); editBoxApi.setFilterAndLength(dialog, "EDIT_PASSWORD", dialogName, EditFilter::Names, passwordMaxLength); } game::CMenuBase* __stdcall createMenuRandomScenarioMulti(game::CMenuPhase* menuPhase) { const auto& allocateMem{game::Memory::get().allocate}; auto menu = (CMenuRandomScenarioMulti*)allocateMem(sizeof(CMenuRandomScenarioMulti)); new (menu) CMenuRandomScenarioMulti(menuPhase); return menu; } } // namespace hooks
3,279
C++
.cpp
74
39.513514
100
0.746863
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,844
itemutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/itemutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "itemutils.h" #include "globaldata.h" #include "itembattle.h" #include "itemequipment.h" #include "log.h" #include "midgardobjectmap.h" #include "miditem.h" #include "utils.h" #include <fmt/format.h> namespace hooks { const game::CItemBase* getGlobalItemById(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* itemId) { using namespace game; auto item = static_cast<CMidItem*>( objectMap->vftable->findScenarioObjectById(objectMap, itemId)); if (!item) { logError("mssProxyError.log", fmt::format("Could not find item {:s}", idToString(itemId))); return nullptr; } const auto& global = GlobalDataApi::get(); auto globalData = *global.getGlobalData(); auto globalItem = global.findItemById(globalData->itemTypes, &item->globalItemId); if (!globalItem) { logError("mssProxyError.log", fmt::format("Could not find global item {:s}", idToString(&item->globalItemId))); return nullptr; } return globalItem; } game::CMidgardID getAttackId(const game::IItem* item) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto itemBattle = (CItemBattle*)dynamicCast(item, 0, rtti.IItemType, rtti.CItemBattleType, 0); if (itemBattle) { return itemBattle->attackId; } auto itemEquipment = (CItemEquipment*)dynamicCast(item, 0, rtti.IItemType, rtti.CItemEquipmentType, 0); if (itemEquipment) { return itemEquipment->attackId; } return emptyId; } game::IItemExtension* castItem(const game::IItem* item, const game::TypeDescriptor* type) { using namespace game; auto& typeInfoRawName = *RttiApi::get().typeInfoRawName; return item ? item->vftable->cast(item, typeInfoRawName(type)) : nullptr; } game::IItemExPotionBoost* castItemToPotionBoost(const game::IItem* item) { using namespace game; const auto& rtti = RttiApi::rtti(); return (IItemExPotionBoost*)castItem(item, rtti.IItemExPotionBoostType); } } // namespace hooks
2,996
C++
.cpp
77
33.909091
99
0.705172
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,845
unitpositionlist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitpositionlist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitpositionlist.h" #include "version.h" #include <array> namespace game::UnitPositionListApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x640620, (Api::Destructor)0x6406b0, }, // Russobit Api{ (Api::Constructor)0x640620, (Api::Destructor)0x6406b0, }, // Gog Api{ (Api::Constructor)0x63eef0, (Api::Destructor)0x63ef80, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::UnitPositionListApi
1,428
C++
.cpp
46
27.652174
72
0.710966
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,846
logutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/logutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "logutils.h" #include "midgardid.h" #include "netmsg.h" #include <array> namespace hooks { const char* getNetPlayerIdDesc(int netPlayerId) { using namespace game; switch (netPlayerId) { case broadcastNetPlayerId: return "broadcast"; case serverNetPlayerId: return "server"; default: return "client"; } } const char* getMidgardIdTypeDesc(const game::CMidgardID* id) { using namespace game; static std::array<const char*, (size_t)IdType::Invalid + 1> descriptions = {{ "Empty", "ApplicationText", "Building", "Race", "Lord", "Spell", "UnitGlobal", "UnitGenerated", "UnitModifier", "Attack", "TextGlobal", "LandmarkGlobal", "ItemGlobal", "NobleAction", "DynamicUpgrade", "DynamicAttack", "DynamicAltAttack", "DynamicAttack2", "DynamicAltAttack2", "CampaignFile", "CW", "CO", "Plan", "ObjectCount", "ScenarioFile", "Map", "MapBlock", "ScenarioInfo", "SpellEffects", "Fortification", "Player", "PlayerKnownSpells", "Fog", "PlayerBuildings", "Road", "Stack", "Unit", "Landmark", "Item", "Bag", "Site", "Ruin", "Tomb", "Rod", "Crystal", "Diplomacy", "SpellCast", "Location", "StackTemplate", "Event", "StackDestroyed", "TalismanCharges", "MT", "Mountains", "SubRace", "BR", "QuestLog", "TurnSummary", "ScenarioVariable", "Invalid", }}; auto type = (std::uint32_t)CMidgardIDApi::get().getType(id); return type < descriptions.size() ? descriptions[type] : "UNKNOWN ID TYPE"; } } // namespace hooks
2,767
C++
.cpp
104
20.096154
81
0.601507
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,847
enclayoutspell.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutspell.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutspell.h" #include "version.h" #include <array> namespace game::CEncLayoutSpellApi { // clang-format off std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0 }, // Russobit Api{ (Api::Constructor)0 }, // Gog Api{ (Api::Constructor)0 }, // Scenario Editor { (Api::Constructor)0x4ceb2d } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CEncLayoutSpellApi
1,357
C++
.cpp
47
25.617021
72
0.704981
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,848
batattackutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batattackutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batattackutils.h" #include "batattacktransformself.h" #include "batattackuseorb.h" #include "batattackusetalisman.h" #include "dynamiccast.h" #include "visitors.h" namespace hooks { bool canHeal(game::IAttack* attack, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; const auto qtyHeal = attack->vftable->getQtyHeal(attack); if (qtyHeal <= 0) return false; return BattleMsgDataApi::get().unitCanBeHealed(objectMap, battleMsgData, targetUnitId); } int heal(game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidUnit* targetUnit, int qtyHeal) { using namespace game; int hpBefore = targetUnit->currentHp; const auto& visitors = VisitorApi::get(); visitors.changeUnitHp(&targetUnit->id, qtyHeal, objectMap, 1); int hpAfter = targetUnit->currentHp; BattleMsgDataApi::get().setUnitHp(battleMsgData, &targetUnit->id, hpAfter); return hpAfter - hpBefore; } const game::CMidgardID* getUnitId(const game::IBatAttack* batAttack) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto transformSelfAttack = (CBatAttackTransformSelf*) dynamicCast(batAttack, 0, rtti.IBatAttackType, rtti.CBatAttackTransformSelfType, 0); if (transformSelfAttack) { return &transformSelfAttack->unitId; } auto useOrbAttack = (CBatAttackUseOrb*)dynamicCast(batAttack, 0, rtti.IBatAttackType, rtti.CBatAttackUseOrbType, 0); if (useOrbAttack) { return &useOrbAttack->unitId; } auto useTalismanAttack = (CBatAttackUseTalisman*)dynamicCast(batAttack, 0, rtti.IBatAttackType, rtti.CBatAttackUseTalismanType, 0); if (useTalismanAttack) { return &useTalismanAttack->unitId; } // HACK: every other attack in the game has its unitId as a first field, but its not a part // of CBatAttackBase. return (CMidgardID*)(batAttack + 1); } const game::CMidgardID* getItemId(const game::IBatAttack* batAttack) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto useOrbAttack = (CBatAttackUseOrb*)dynamicCast(batAttack, 0, rtti.IBatAttackType, rtti.CBatAttackUseOrbType, 0); if (useOrbAttack) { return &useOrbAttack->itemId; } auto useTalismanAttack = (CBatAttackUseTalisman*)dynamicCast(batAttack, 0, rtti.IBatAttackType, rtti.CBatAttackUseTalismanType, 0); if (useTalismanAttack) { return &useTalismanAttack->itemId; } return &emptyId; } } // namespace hooks
3,796
C++
.cpp
91
34.725275
100
0.688298
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,849
eventeffectcathooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/eventeffectcathooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "eventeffectcathooks.h" #include "dbf/dbffile.h" #include "log.h" #include "utils.h" #include <fmt/format.h> namespace hooks { CustomEventEffects& customEventEffects() { static CustomEventEffects customEffects{}; return customEffects; } static void readCustomEffect(const utils::DbfRecord& record, CustomEventEffect& effect) { const auto& idApi = game::CMidgardIDApi::get(); std::string info; record.value(info, "INFO"); idApi.fromString(&effect.infoText, info.c_str()); std::string brief; record.value(brief, "BRIEF"); idApi.fromString(&effect.brief, brief.c_str()); std::string descr; record.value(descr, "DESCR"); idApi.fromString(&effect.description, descr.c_str()); } static bool readCustomEffects(const std::filesystem::path& dbfFilePath) { utils::DbfFile dbf; if (!dbf.open(dbfFilePath)) { logError("mssProxyError.log", fmt::format("Could not open {:s}", dbfFilePath.filename().string())); return false; } bool customEffects{false}; const auto recordsTotal{dbf.recordsTotal()}; for (std::uint32_t i = 0; i < recordsTotal; ++i) { utils::DbfRecord record; if (!dbf.record(record, i)) { logError("mssProxyError.log", fmt::format("Could not read record {:d} from {:s}", i, dbfFilePath.filename().string())); return false; } if (record.isDeleted()) { continue; } std::string categoryName; record.value(categoryName, "TEXT"); categoryName = trimSpaces(categoryName); } return customEffects; } game::LEventEffectCategoryTable* __fastcall eventEffectCategoryTableCtorHooked( game::LEventEffectCategoryTable* thisptr, int /*%edx*/, const char* globalsFolderPath, void* codeBaseEnvProxy) { using namespace game; static const char dbfFileName[] = "LEvEffct.dbf"; const bool customEffectsExist{false}; thisptr->bgn = nullptr; thisptr->end = nullptr; thisptr->allocatedMemEnd = nullptr; thisptr->allocator = nullptr; thisptr->vftable = LEventEffectCategoryTableApi::vftable(); const auto& table = LEventEffectCategoryTableApi::get(); const auto& effects = EventEffectCategories::get(); table.init(thisptr, codeBaseEnvProxy, globalsFolderPath, dbfFileName); table.readCategory(effects.win, thisptr, "L_WIN", dbfFileName); table.readCategory(effects.createStack, thisptr, "L_CREATE_STACK", dbfFileName); table.readCategory(effects.castSpell, thisptr, "L_CAST_SPELL", dbfFileName); table.readCategory(effects.castSpellMap, thisptr, "L_CAST_SPELL_MAP", dbfFileName); table.readCategory(effects.changeOwner, thisptr, "L_CHANGE_OWNER", dbfFileName); table.readCategory(effects.changeOrder, thisptr, "L_CHANGE_ORDER", dbfFileName); table.readCategory(effects.moveBeside, thisptr, "L_MOVE_BESIDE", dbfFileName); table.readCategory(effects.battle, thisptr, "L_BATTLE", dbfFileName); table.readCategory(effects.enableEvent, thisptr, "L_ENABLE_EVENT", dbfFileName); table.readCategory(effects.giveSpell, thisptr, "L_GIVE_SPELL", dbfFileName); table.readCategory(effects.giveItem, thisptr, "L_GIVE_ITEM", dbfFileName); table.readCategory(effects.moveStack, thisptr, "L_MOVE_STACK", dbfFileName); table.readCategory(effects.ally, thisptr, "L_ALLY", dbfFileName); table.readCategory(effects.diplomacy, thisptr, "L_DIPLOMACY", dbfFileName); table.readCategory(effects.unfog, thisptr, "L_UNFOG", dbfFileName); table.readCategory(effects.removeMountain, thisptr, "L_REMOVE_MOUNTAIN", dbfFileName); table.readCategory(effects.removeLmark, thisptr, "L_REMOVE_LMARK", dbfFileName); table.readCategory(effects.changeObjective, thisptr, "L_CHANGE_OBJECTIVE", dbfFileName); table.readCategory(effects.popup, thisptr, "L_POPUP", dbfFileName); table.readCategory(effects.destroyItem, thisptr, "L_DESTROY_ITEM", dbfFileName); table.readCategory(effects.removeStack, thisptr, "L_REMOVE_STACK", dbfFileName); table.readCategory(effects.changeLandmark, thisptr, "L_CHANGE_LANDMARK", dbfFileName); table.readCategory(effects.changeTerrain, thisptr, "L_CHANGE_TERRAIN", dbfFileName); table.readCategory(effects.modifyVariable, thisptr, "L_MODIFY_VARIABLE", dbfFileName); if (customEffectsExist) { } table.initDone(thisptr); return thisptr; } } // namespace hooks
5,309
C++
.cpp
115
41
96
0.722878
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,850
effectresulthooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/effectresulthooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "effectresulthooks.h" #include "eventeffectcathooks.h" #include "originalfunctions.h" namespace hooks { game::IEffectResult* __stdcall createEffectResultHooked(const game::CMidEvEffect* eventEffect) { const auto& effects = customEventEffects(); const auto id = eventEffect->category.id; return getOriginalFunctions().createEffectResult(eventEffect); } } // namespace hooks
1,211
C++
.cpp
29
39.586207
94
0.773152
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,851
image2text.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/image2text.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "image2text.h" #include "version.h" #include <array> namespace game::CImage2TextApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x534af8, (Api::SetText)0x534bcc, }, // Russobit Api{ (Api::Constructor)0x534af8, (Api::SetText)0x534bcc, }, // Gog Api{ (Api::Constructor)0x5340d6, (Api::SetText)0x5341aa, }, // Scenario Editor Api{ (Api::Constructor)0x48e80f, (Api::SetText)0x48e8e3, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CImage2TextApi
1,509
C++
.cpp
51
25.882353
72
0.695114
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,852
testcondition.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/testcondition.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "testcondition.h" #include "version.h" #include <array> namespace game::ITestConditionApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Create)0x4422b7, }, // Russobit Api{ (Api::Create)0x4422b7, }, // Gog Api{ (Api::Create)0x441f1c, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::ITestConditionApi
1,300
C++
.cpp
43
27.232558
72
0.713259
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,853
mqrect.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/mqrect.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mqrect.h" #include "version.h" #include <array> namespace game::MqRectApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x63e930, (Api::PtInRect)0x63fa70, (Api::GetCenter)0x63f790, }, // Russobit Api{ (Api::Constructor)0x63e930, (Api::PtInRect)0x63fa70, (Api::GetCenter)0x63f790, }, // Gog Api{ (Api::Constructor)0x63d3a0, (Api::PtInRect)0x63e460, (Api::GetCenter)0x63e180, }, // Scenario Editor Api{ (Api::Constructor)0x4cd3c1, (Api::PtInRect)nullptr, (Api::GetCenter)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::MqRectApi
1,634
C++
.cpp
55
25.618182
72
0.685515
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,854
midunit.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midunit.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midunit.h" #include "version.h" #include <array> namespace game::CMidUnitApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::AddRemoveModifier)0x5eabff, (Api::AddRemoveModifier)0x5eac81, (Api::GetHpMax)0x5eab79, (Api::Upgrade)0x5eb461, (Api::Transform)0x5eb559, (Api::Untransform)0x5eb6ba, (Api::GetModifiers)0x5eabc0, (Api::AddModifiers)0x5eb1df, (Api::RemoveModifiers)0x5ea9ea, (Api::ReplaceImpl)0x5eb4fc, (Api::StreamImpl)0x5eaf8d, (Api::StreamModifiers)0x5eb010, (Api::StreamImplIdAndLevel)0x6097ee, }, // Russobit Api{ (Api::AddRemoveModifier)0x5eabff, (Api::AddRemoveModifier)0x5eac81, (Api::GetHpMax)0x5eab79, (Api::Upgrade)0x5eb461, (Api::Transform)0x5eb559, (Api::Untransform)0x5eb6ba, (Api::GetModifiers)0x5eabc0, (Api::AddModifiers)0x5eb1df, (Api::RemoveModifiers)0x5ea9ea, (Api::ReplaceImpl)0x5eb4fc, (Api::StreamImpl)0x5eaf8d, (Api::StreamModifiers)0x5eb010, (Api::StreamImplIdAndLevel)0x6097ee, }, // Gog Api{ (Api::AddRemoveModifier)0x5e9902, (Api::AddRemoveModifier)0x5e9984, (Api::GetHpMax)0x5e987c, (Api::Upgrade)0x5ea164, (Api::Transform)0x5ea25c, (Api::Untransform)0x5ea3bd, (Api::GetModifiers)0x5e98c3, (Api::AddModifiers)0x5e9ee2, (Api::RemoveModifiers)0x5e96e9, (Api::ReplaceImpl)0x5ea1ff, (Api::StreamImpl)0x5e9c90, (Api::StreamModifiers)0x5e9d13, (Api::StreamImplIdAndLevel)0x6082b8, }, // Scenario Editor Api{ (Api::AddRemoveModifier)0x4ed994, (Api::AddRemoveModifier)0x4eda16, (Api::GetHpMax)0x4ed90e, (Api::Upgrade)nullptr, (Api::Transform)nullptr, (Api::Untransform)nullptr, (Api::GetModifiers)0x4ed955, (Api::AddModifiers)0x4edf15, (Api::RemoveModifiers)0x4ed77b, (Api::ReplaceImpl)nullptr, (Api::StreamImpl)0x4edcc3, (Api::StreamModifiers)0x4edd46, (Api::StreamImplIdAndLevel)0x50448d, }, }}; static std::array<CMidUnitVftable*, 4> vftables = {{ // Akella (CMidUnitVftable*)0x6f0914, // Russobit (CMidUnitVftable*)0x6f0914, // Gog (CMidUnitVftable*)0x6ee8b4, // Scenario Editor (CMidUnitVftable*)0x5da34c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } CMidUnitVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidUnitApi
3,524
C++
.cpp
109
26.486239
72
0.672535
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,855
enclayoutunit.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutunit.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutunit.h" #include "version.h" #include <array> namespace game::CEncLayoutUnitApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x574e9c, (Api::Constructor2)0x574fd5, (Api::DataConstructor)0x574f48, (Api::DataDestructor)0x577d72, (Api::Initialize)0x5750b1, (Api::Update)0x5757eb, (Api::CreateListBoxDisplayFunctor)0x577b6d, }, // Russobit Api{ (Api::Constructor)0x574e9c, (Api::Constructor2)0x574fd5, (Api::DataConstructor)0x574f48, (Api::DataDestructor)0x577d72, (Api::Initialize)0x5750b1, (Api::Update)0x5757eb, (Api::CreateListBoxDisplayFunctor)0x577b6d, }, // Gog Api{ (Api::Constructor)0x5744f1, (Api::Constructor2)0x57462a, (Api::DataConstructor)0x57459d, (Api::DataDestructor)0x57742d, (Api::Initialize)0x574706, (Api::Update)0x574e40, (Api::CreateListBoxDisplayFunctor)0x577228, }, // Scenario Editor Api{ (Api::Constructor)0x4c5915, (Api::Constructor2)0x4c5a71, (Api::DataConstructor)0x4c59c1, (Api::DataDestructor)0x4c8d48, (Api::Initialize)0x4c5b4d, (Api::Update)0x4c6287, (Api::CreateListBoxDisplayFunctor)0x4c885f, }, }}; static std::array<IEncLayoutVftable*, 4> vftables = {{ // Akella (IEncLayoutVftable*)0x6e7f7c, // Russobit (IEncLayoutVftable*)0x6e7f7c, // Gog (IEncLayoutVftable*)0x6e5f1c, // Scenario Editor (IEncLayoutVftable*)0x5d72bc, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } IEncLayoutVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CEncLayoutUnitApi
2,681
C++
.cpp
85
26.588235
72
0.689455
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,856
netmsgutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netmsgutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netmsgutils.h" #include "battlemsgdata.h" #include "mqstream.h" #include <vector> namespace hooks { void serializeMsgWithBattleMsgData(game::CNetMsg* msg, game::BattleMsgData* battleMsgData, game::CNetMsgVftable::Serialize method, game::CMqStream* stream) { using namespace game; if (stream->read) { const size_t count = std::size(battleMsgData->unitsInfo); std::vector<ModifiedUnitInfo*> prev(count); for (size_t i = 0; i < count; i++) { prev[i] = battleMsgData->unitsInfo[i].modifiedUnits.patched; } method(msg, stream); for (size_t i = 0; i < count; i++) { battleMsgData->unitsInfo[i].modifiedUnits.patched = prev[i]; } } else { method(msg, stream); } for (auto& unitInfo : battleMsgData->unitsInfo) { stream->vftable->serialize(stream, unitInfo.modifiedUnits.patched, sizeof(ModifiedUnitInfo) * ModifiedUnitCountPatched); } } } // namespace hooks
1,942
C++
.cpp
48
33.520833
88
0.658537
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,857
menuload.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menuload.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menuload.h" #include "version.h" #include <array> namespace game::CMenuLoadApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::ButtonCallback)0x4e0134, (Api::CreateHostPlayer)0x4e0ef9, }, // Russobit Api{ (Api::ButtonCallback)0x4e0134, (Api::CreateHostPlayer)0x4e0ef9, }, // Gog Api{ (Api::ButtonCallback)0x4df7b0, (Api::CreateHostPlayer)0x4e0575, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMenuLoadApi
1,432
C++
.cpp
46
27.73913
72
0.711803
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,858
enclayoutcity.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutcity.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutcity.h" #include "version.h" #include <array> namespace game::CEncLayoutCityApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Update)0x57b21a, (Api::UpdateGroupUi)0x57ba69, }, // Russobit Api{ (Api::Update)0x57b21a, (Api::UpdateGroupUi)0x57ba69, }, // Gog Api{ (Api::Update)0x57a8d5, (Api::UpdateGroupUi)0x57b124, }, // Scenario Editor Api{ (Api::Update)0x4cc638, (Api::UpdateGroupUi)0x4cce87, }, }}; static std::array<IEncLayoutVftable*, 4> vftables = {{ // Akella (IEncLayoutVftable*)0x6e8c64, // Russobit (IEncLayoutVftable*)0x6e8c64, // Gog (IEncLayoutVftable*)0x6e6c04, // Scenario Editor (IEncLayoutVftable*)0x5d801c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } IEncLayoutVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CEncLayoutCityApi
1,878
C++
.cpp
65
25.184615
72
0.698782
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,859
ordercat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/ordercat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ordercat.h" #include "version.h" #include <array> namespace game::OrderCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LOrderCategory*)0x839898, (LOrderCategory*)0x8398a8, (LOrderCategory*)0x8398b8, (LOrderCategory*)0x8398c8, (LOrderCategory*)0x8398d8, (LOrderCategory*)0x8398e8, (LOrderCategory*)0x8398f8, (LOrderCategory*)0x839908, (LOrderCategory*)0x839918, (LOrderCategory*)0x839928, (LOrderCategory*)0x839938, (LOrderCategory*)0x839948, (LOrderCategory*)0x839958, }, // Russobit Categories{ (LOrderCategory*)0x839898, (LOrderCategory*)0x8398a8, (LOrderCategory*)0x8398b8, (LOrderCategory*)0x8398c8, (LOrderCategory*)0x8398d8, (LOrderCategory*)0x8398e8, (LOrderCategory*)0x8398f8, (LOrderCategory*)0x839908, (LOrderCategory*)0x839918, (LOrderCategory*)0x839928, (LOrderCategory*)0x839938, (LOrderCategory*)0x839948, (LOrderCategory*)0x839958, }, // Gog Categories{ (LOrderCategory*)0x837848, (LOrderCategory*)0x837858, (LOrderCategory*)0x837868, (LOrderCategory*)0x837878, (LOrderCategory*)0x837888, (LOrderCategory*)0x837898, (LOrderCategory*)0x8378a8, (LOrderCategory*)0x8378b8, (LOrderCategory*)0x8378c8, (LOrderCategory*)0x8378d8, (LOrderCategory*)0x8378e8, (LOrderCategory*)0x8378f8, (LOrderCategory*)0x837908, }, // Scenario Editor Categories{ (LOrderCategory*)0x6655c0, (LOrderCategory*)0x6655d0, (LOrderCategory*)0x6655e0, (LOrderCategory*)0x6655f0, (LOrderCategory*)0x665600, (LOrderCategory*)0x665610, (LOrderCategory*)0x665620, (LOrderCategory*)0x665630, (LOrderCategory*)0x665640, (LOrderCategory*)0x665650, (LOrderCategory*)0x665660, (LOrderCategory*)0x665670, (LOrderCategory*)0x665680, }, }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } } // namespace game::OrderCategories
3,102
C++
.cpp
95
26.494737
72
0.679214
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,860
mqpresentationmanager.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/mqpresentationmanager.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mqpresentationmanager.h" #include "version.h" #include <array> namespace game::CMqPresentationManagerApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetPresentationManager)0x516bd0, (Api::PresentationMgrPtrSetData)0x4042ed, }, // Russobit Api{ (Api::GetPresentationManager)0x516bd0, (Api::PresentationMgrPtrSetData)0x4042ed, }, // Gog Api{ (Api::GetPresentationManager)0x5160e0, (Api::PresentationMgrPtrSetData)0x403f7d, }, // Scenario Editor Api{ (Api::GetPresentationManager)0x4ae820, (Api::PresentationMgrPtrSetData)0x4156c2, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMqPresentationManagerApi
1,658
C++
.cpp
51
28.803922
72
0.723471
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,861
smartptr.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/smartptr.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "smartptr.h" #include "version.h" #include <array> namespace game::SmartPointerApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::CreateOrFree)0x5e4830, (Api::CreateOrFreeNoDestructor)0x49c5d7, (Api::Copy)0x472528, }, // Russobit Api{ (Api::CreateOrFree)0x5e4830, (Api::CreateOrFreeNoDestructor)0x49c5d7, (Api::Copy)0x472528, }, // Gog Api{ (Api::CreateOrFree)0x55b7bc, (Api::CreateOrFreeNoDestructor)0x495146, (Api::Copy)0x5e357a, }, // Scenario Editor Api{ (Api::CreateOrFree)0x534aa4, (Api::CreateOrFreeNoDestructor)0x4575fe, (Api::Copy)nullptr, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::SmartPointerApi
1,695
C++
.cpp
55
26.727273
72
0.697859
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,862
attackimpl.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/attackimpl.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "attackimpl.h" #include "version.h" #include <array> namespace game::CAttackImplApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5a5f0a, (Api::Constructor2)0x5a66eb, (Api::InitData)0x5a6638 }, // Russobit Api{ (Api::Constructor)0x5a5f0a, (Api::Constructor2)0x5a66eb, (Api::InitData)0x5a6638 }, // Gog Api{ (Api::Constructor)0x5a5156, (Api::Constructor2)0x5a5937, (Api::InitData)0x5a5884 }, // Scenario Editor Api{ (Api::Constructor)0x54e138, (Api::Constructor2)0x54e919, (Api::InitData)0x54e866 } }}; static std::array<const IAttackVftable*, 4> vftables = {{ // Akella (const IAttackVftable*)0x6ed004, // Russobit (const IAttackVftable*)0x6ed004, // Gog (const IAttackVftable*)0x6eafa4, // Scenario Editor (const IAttackVftable*)0x5e11c4 }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const IAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CAttackImplApi
2,028
C++
.cpp
69
25.376812
72
0.694672
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,863
formattedtext.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/formattedtext.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "formattedtext.h" #include "version.h" #include <array> namespace game::IFormattedTextApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetFormattedText)0x529175, }, // Russobit Api{ (Api::GetFormattedText)0x529175, }, // Gog Api{ (Api::GetFormattedText)0x528680, }, // Scenario Editor Api{ (Api::GetFormattedText)0x4BCD6A, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IFormattedTextApi
1,410
C++
.cpp
47
26.744681
72
0.712077
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,864
tileprefixes.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/tileprefixes.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tileprefixes.h" #include "version.h" #include <array> namespace game::TilePrefixApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetTilePrefixByName)0x5bbb1c, (Api::GetTilePrefixName)0x5bb5d4, }, // Russobit Api{ (Api::GetTilePrefixByName)0x5bbb1c, (Api::GetTilePrefixName)0x5bb5d4, }, // Gog Api{ (Api::GetTilePrefixByName)0x5baacc, (Api::GetTilePrefixName)0x5ba584, }, // Scenario Editor Api{ (Api::GetTilePrefixByName)0x55c84c, (Api::GetTilePrefixName)0x55c304, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::TilePrefixApi
1,581
C++
.cpp
51
27.294118
72
0.709508
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,865
textboxinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/textboxinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "textboxinterf.h" #include "version.h" #include <array> namespace game::CTextBoxInterfApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetString)0x5341d6, }, // Russobit Api{ (Api::SetString)0x5341d6, }, // Gog Api{ (Api::SetString)0x5337b0, }, // Scenario Editor Api{ (Api::SetString)0x48f51b, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CTextBoxInterfApi
1,383
C++
.cpp
47
26.170213
72
0.706236
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,866
uimanager.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/uimanager.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "uimanager.h" #include "version.h" #include <array> namespace game::CUIManagerApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Get)0x561afc, (Api::CreateTimerEventFunctor)0x643370, (Api::CreateTimerEvent)0x561f57, (Api::CreateUpdateEventFunctor)0x4ef49d, (Api::CreateUiEvent)0x561d0d, (Api::CreateUiEvent)0x561d58, (Api::CreateUiEvent)0x561d92, (Api::CreateUiEvent)0x561dcc, (Api::CreateUiEvent)0x561e06, (Api::CreateUiEvent)0x561e40, (Api::CreateMessageEventFunctor)0x53f60b, (Api::CreateMessageEvent)0x561ccb, (Api::GetMousePosition)0x561c4f, (Api::RegisterMessage)0x561c1c, }, // Russobit Api{ (Api::Get)0x561afc, (Api::CreateTimerEventFunctor)0x643370, (Api::CreateTimerEvent)0x561f57, (Api::CreateUpdateEventFunctor)0x4ef49d, (Api::CreateUiEvent)0x561d0d, (Api::CreateUiEvent)0x561d58, (Api::CreateUiEvent)0x561d92, (Api::CreateUiEvent)0x561dcc, (Api::CreateUiEvent)0x561e06, (Api::CreateUiEvent)0x561e40, (Api::CreateMessageEventFunctor)0x53f60b, (Api::CreateMessageEvent)0x561ccb, (Api::GetMousePosition)0x561c4f, (Api::RegisterMessage)0x561c1c, }, // Gog Api{ (Api::Get)0x561299, (Api::CreateTimerEventFunctor)0x641bd0, (Api::CreateTimerEvent)0x5616f4, (Api::CreateUpdateEventFunctor)0x4ee943, (Api::CreateUiEvent)0x5614aa, (Api::CreateUiEvent)0x5614f5, (Api::CreateUiEvent)0x56152f, (Api::CreateUiEvent)0x561569, (Api::CreateUiEvent)0x5615a3, (Api::CreateUiEvent)0x5615dd, (Api::CreateMessageEventFunctor)0x53ecc0, (Api::CreateMessageEvent)0x561468, (Api::GetMousePosition)0x5613ec, (Api::RegisterMessage)0x5613b9, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CUIManagerApi
2,900
C++
.cpp
82
29.512195
72
0.692144
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,867
enclayoutstackhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutstackhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutstackhooks.h" #include "dialoginterf.h" #include "gameutils.h" #include "interfaceutils.h" #include "midstack.h" #include "originalfunctions.h" #include "textboxinterf.h" #include "utils.h" #include <string> namespace hooks { static std::string getXpKilledField(const game::IMidgardObjectMap* objectMap, const game::CMidStack* stack) { return getNumberText(getGroupXpKilled(objectMap, &stack->group), false); } static void setTxtXpKilled(game::CDialogInterf* dialog, const game::IMidgardObjectMap* objectMap, const game::CMidStack* stack) { if (!stack) { return; } using namespace game; static const char controlName[]{"TXT_XP_KILLED"}; const auto& dialogApi{CDialogInterfApi::get()}; if (!dialogApi.findControl(dialog, controlName)) { return; } auto textBox{dialogApi.findTextBox(dialog, controlName)}; if (!textBox) { return; } std::string text{textBox->data->text.string}; if (replace(text, "%XPKILL%", getXpKilledField(objectMap, stack))) { CTextBoxInterfApi::get().setString(textBox, text.c_str()); } } void __fastcall encLayoutStackUpdateHooked(game::CEncLayoutStack* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CMidStack* stack, game::CDialogInterf* dialog) { getOriginalFunctions().encLayoutStackUpdate(thisptr, objectMap, stack, dialog); setTxtXpKilled(thisptr->dialog, objectMap, stack); } } // namespace hooks
2,557
C++
.cpp
65
32.369231
84
0.669221
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,868
managestkinterfhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/managestkinterfhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "managestkinterfhooks.h" #include "managestkinterf.h" #include "middragdropinterfhooks.h" #include "originalfunctions.h" namespace hooks { void __fastcall manageStkInterfOnObjectChangedHooked(game::CManageStkInterf* thisptr, int /*%edx*/, game::IMidScenarioObject* obj) { getOriginalFunctions().manageStkInterfOnObjectChanged(thisptr, obj); midDragDropInterfResetCurrentSource(thisptr); } } // namespace hooks
1,351
C++
.cpp
31
38.193548
85
0.720152
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,869
movepathhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/movepathhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "movepathhooks.h" #include "dynamiccast.h" #include "game.h" #include "gameimages.h" #include "gamesettings.h" #include "groundcat.h" #include "image2text.h" #include "isolayers.h" #include "log.h" #include "mapgraphics.h" #include "mempool.h" #include "midgard.h" #include "midgardmap.h" #include "midgardobjectmap.h" #include "midgardplan.h" #include "midstack.h" #include "midunit.h" #include "multilayerimg.h" #include "pathinfolist.h" #include "settings.h" #include "ussoldier.h" #include "utils.h" #include <array> #include <cmath> #include <fmt/format.h> namespace hooks { static bool isIdsEqualOrBothNull(const game::CMidgardID* id1, const game::CMidgardID* id2) { if (!id1 && !id2) { // Both null, treat as equal return true; } if (id1 && id2) { return *id1 == *id2; } return false; }; void __stdcall showMovementPathHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* stackId, game::List<game::CMqPoint>* path, const game::CMqPoint* lastReachablePoint, const game::CMqPoint* pathEnd, bool a6) { using namespace game; const auto& fn = gameFunctions(); auto plan = fn.getMidgardPlan(objectMap); const auto& dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto stackObj = objectMap->vftable->findScenarioObjectById(objectMap, stackId); auto stack = static_cast<const CMidStack*>( dynamicCast(stackObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0)); auto leaderObj = objectMap->vftable->findScenarioObjectById(objectMap, &stack->leaderId); auto leader = static_cast<const CMidUnit*>(leaderObj); auto unitImpl = leader->unitImpl; const bool noble = fn.castUnitImplToNoble(unitImpl) != nullptr; auto soldier = fn.castUnitImplToSoldier(unitImpl); const bool waterOnly = soldier->vftable->getWaterOnly(soldier); const CMqPoint* positionPtr{}; bool pathLeadsToAction{}; if (!a6) { positionPtr = lastReachablePoint; } else { positionPtr = lastReachablePoint; pathLeadsToAction = fn.getBlockingPathNearbyStackId(objectMap, plan, stack, lastReachablePoint, pathEnd, 0) != nullptr; if (!pathLeadsToAction) { CMqPoint entrance{}; if (fn.getFortOrRuinEntrance(objectMap, plan, stack, pathEnd, &entrance) && std::abs(lastReachablePoint->x - entrance.x) <= 1 && std::abs(lastReachablePoint->y - entrance.y) <= 1) { pathLeadsToAction = true; } } } const auto& pathApi = PathInfoListApi::get(); PathInfoList pathInfo; pathApi.constructor(&pathInfo); { CMqPoint point{}; point.x = positionPtr->x; point.y = positionPtr->y; pathApi.populateFromPath(objectMap, stack, path, &point, waterOnly, &pathInfo); } const auto& imagesApi = GameImagesApi::get(); GameImagesPtr imagesPtr; imagesApi.getGameImages(&imagesPtr); auto images = *imagesPtr.data; const auto& memAlloc = Memory::get().allocate; auto gameSettings = *CMidgardApi::get().instance()->data->settings; const bool displayPathTurn{gameSettings->displayPathTurn}; CMidgardID turnStringId{}; CMidgardIDApi::get().fromString(&turnStringId, "X005TA0935"); const char* turnString{fn.getInterfaceText(&turnStringId)}; const auto& moveCostColor{userSettings().movementCost.textColor}; const auto& moveCostOutline{userSettings().movementCost.outlineColor}; bool firstNode{true}; bool pathAllowed{}; bool waterOnlyToLand{}; const auto stackPosition = fn.getStackPositionById(objectMap, stackId); bool v61 = *positionPtr != stackPosition; int turnNumber{}; bool manyTurnsToTravel{}; std::uint32_t index{}; for (auto node = pathInfo.head->next; node != pathInfo.head; node = node->next, firstNode = false, ++index) { const auto& currentPosition = node->data.position; if (!fn.stackCanMoveToPosition(objectMap, &currentPosition, stack, plan)) { continue; } pathAllowed = !waterOnlyToLand; if (waterOnly && !fn.isWaterTileSurroundedByWater(&currentPosition, objectMap)) { pathAllowed = false; waterOnlyToLand = true; } // Blue flag const char* imageName = "MOVENORMAL"; if (!v61) { // Red flag imageName = "MOVEOUT"; if (!pathLeadsToAction) { // White flag imageName = "MOVEACTION"; } } const bool endOfPath{currentPosition == *positionPtr}; if (endOfPath) { v61 = false; if (pathLeadsToAction) { // Red flag with a scroll, noble actions imageName = "MOVENEGO"; if (!noble) { // Red flag with a sword, battle imageName = "MOVEBATTLE"; } } } if (!pathAllowed) { // Crossed out white flag, when path of water only stack leads to the land imageName = "MOVEINCMP"; } auto flagImage = imagesApi.getImage(images->isoCmon, imageName, 0, true, images->log); if (!flagImage) { continue; } const auto imagesCount{flagImage->vftable->getImagesCount(flagImage)}; flagImage->vftable->setImageIndex(flagImage, index % imagesCount); CImage2Text* turnNumberImage{}; if (displayPathTurn && !firstNode) { bool drawTurnNumber{}; turnNumber = 0; const auto prev = node->prev; const auto prevTurnsToReach{prev->data.turnsToReach}; const auto currTurnsToReach{node->data.turnsToReach}; const bool differ{prevTurnsToReach != currTurnsToReach}; // Check previous node, draw turn number only if number of turns to reach is different // and previous one is not 0 if (differ) { manyTurnsToTravel = true; if (prevTurnsToReach != 0) { drawTurnNumber = true; turnNumber = prevTurnsToReach; } } const bool lastNode{node->next == pathInfo.head}; if (lastNode && manyTurnsToTravel) { // Always draw turn number on the last path node, // but only when path is longer than single turn drawTurnNumber = true; // Special case: end of the path is the first node of a new travel turn // (previous node has different turns to reach), we draw _previous_ day turn number. // Exception: do not draw 0 as turn number if (!differ || prev->data.turnsToReach == 0) { turnNumber = currTurnsToReach; } else { turnNumber = prevTurnsToReach; } } if (drawTurnNumber) { turnNumberImage = static_cast<CImage2Text*>(memAlloc(sizeof(CImage2Text))); CImage2TextApi::get().constructor(turnNumberImage, 32, 64); std::string text{turnString}; replace(text, "%TURN%", fmt::format("{:d}", turnNumber)); CImage2TextApi::get().setText(turnNumberImage, text.c_str()); } } CImage2Text* moveCostImage{}; if (pathAllowed && !turnNumberImage) { moveCostImage = static_cast<CImage2Text*>(memAlloc(sizeof(CImage2Text))); CImage2TextApi::get().constructor(moveCostImage, 32, 64); const auto moveCostString{fmt::format( "\\fmedium;\\hC;\\vT;\\c{:03d};{:03d};{:03d};\\o{:03d};{:03d};{:03d};{:d}", (int)moveCostColor.r, (int)moveCostColor.g, (int)moveCostColor.b, (int)moveCostOutline.r, (int)moveCostOutline.g, (int)moveCostOutline.b, node->data.moveCostTotal)}; CImage2TextApi::get().setText(moveCostImage, moveCostString.c_str()); } auto multilayerImg = static_cast<CMultiLayerImg*>(memAlloc(sizeof(CMultiLayerImg))); CMultiLayerImgApi::get().constructor(multilayerImg); CMultiLayerImgApi::get().addImage(multilayerImg, flagImage, -999, -999); if (turnNumberImage) { CMultiLayerImgApi::get().addImage(multilayerImg, turnNumberImage, -999, -999); } if (moveCostImage) { CMultiLayerImgApi::get().addImage(multilayerImg, moveCostImage, -999, -999); } CMqPoint pos; pos.x = currentPosition.x; pos.y = currentPosition.y; MapGraphicsApi::get().showImageOnMap(&pos, isoLayers().symMovePath, multilayerImg, 0, 0); } imagesApi.createOrFreeGameImages(&imagesPtr, nullptr); pathApi.freeNodes(&pathInfo); pathApi.freeNode(&pathInfo, pathInfo.head); } int __stdcall computeMovementCostHooked(const game::CMqPoint* mapPosition, const game::IMidgardObjectMap* objectMap, const game::CMidgardMap* midgardMap, const game::CMidgardPlan* plan, const game::CMidgardID* stackId, const char* a6, const char* a7, bool leaderAlive, bool plainsBonus, bool forestBonus, bool waterBonus, bool waterOnly, bool forbidWaterOnlyOnLand) { using namespace game; constexpr int movementForbidden = 0; const int x = mapPosition->x; const int y = mapPosition->y; if (x < 0 || x >= midgardMap->mapSize || y < 0 || y >= midgardMap->mapSize) { // Outside of map return movementForbidden; } const bool pred1 = !a6 || !((1 << (x & 7)) & a6[18 * y + (x >> 3)]); if (!pred1) { return movementForbidden; } // clang-format off static const std::array<IdType, 6> interactiveObjectTypes{{ IdType::Fortification, IdType::Landmark, IdType::Site, IdType::Ruin, IdType::Rod, IdType::Crystal }}; // clang-format on const auto& planApi = CMidgardPlanApi::get(); if (planApi.isPositionContainsObjects(plan, mapPosition, interactiveObjectTypes.data(), std::size(interactiveObjectTypes))) { // Interactive object is in the way return movementForbidden; } const IdType bagType = IdType::Bag; const CMidgardID* bagId = planApi.getObjectId(plan, mapPosition, &bagType); const bool pred2 = a7 && ((1 << (x & 7)) & a7[18 * y + (x >> 3)]); if (!(!bagId || pred2)) { return movementForbidden; } const IdType stackType = IdType::Stack; const CMidgardID* stackAtPosition = planApi.getObjectId(plan, mapPosition, &stackType); if (!(!stackAtPosition || isIdsEqualOrBothNull(stackAtPosition, stackId) || pred2)) { return movementForbidden; } const IdType roadType = IdType::Road; const bool road = planApi.getObjectId(plan, mapPosition, &roadType) != nullptr; LGroundCategory ground{}; if (!CMidgardMapApi::get().getGround(midgardMap, &ground, mapPosition, objectMap)) { return movementForbidden; } const auto& groundTypes = GroundCategories::get(); if (ground.id == groundTypes.water->id) { const auto& water = userSettings().movementCost.water; if (!waterOnly) { if (leaderAlive) { return waterBonus ? water.withBonus : water.dflt; } return water.deadLeader; } // Check deep waters if (gameFunctions().isWaterTileSurroundedByWater(mapPosition, objectMap)) { return water.waterOnly; } } else if (ground.id == groundTypes.forest->id) { const auto& forest = userSettings().movementCost.forest; if (!waterOnly) { if (leaderAlive) { return forestBonus ? forest.withBonus : forest.dflt; } return forest.deadLeader; } } else if (ground.id == groundTypes.plain->id) { const auto& plain = userSettings().movementCost.plain; if (!waterOnly) { if (!leaderAlive) { return plain.deadLeader; } if (!plainsBonus && road) { return plain.onRoad; } return plain.dflt; } } else { // Mountain ground type return movementForbidden; } // This is the case when water-only stack tries to move on shore or land. // We don't care about ground type here. // Forbid movement so move points will not be wasted in attempt to perform illegal move if (forbidWaterOnlyOnLand) { return movementForbidden; } // Assumption: // Unreachable big value used by the game // to compute and show movement path on land for water-only stacks. // This logic is only to properly show movement path on land // while marking it as forbidden constexpr int moveCostWaterOnlyOnLand = 1000; return moveCostWaterOnlyOnLand; } } // namespace hooks
14,649
C++
.cpp
344
32.287791
100
0.604318
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,870
tileindices.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/tileindices.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tileindices.h" #include "version.h" #include <array> namespace game::TileIndicesApi { // clang-format off std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5ac1d4, (Api::CreateBorderTiles)0x5ac476, (Api::CreateTerrainTiles)0x5ac401, (Api::GetTileDataIndex)0x5ad1e9, }, // Russobit Api{ (Api::Constructor)0x5ac1d4, (Api::CreateBorderTiles)0x5ac476, (Api::CreateTerrainTiles)0x5ac401, (Api::GetTileDataIndex)0x5ad1e9, }, // Gog Api{ (Api::Constructor)0x5ab45c, (Api::CreateBorderTiles)0x5ab6fe, (Api::CreateTerrainTiles)0x5ab689, (Api::GetTileDataIndex)0x5ac471, }, // Scenario Editor Api{ (Api::Constructor)0x55227c, (Api::CreateBorderTiles)0x55251e, (Api::CreateTerrainTiles)0x5524a9, (Api::GetTileDataIndex)0x553221, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::TileIndicesApi
1,879
C++
.cpp
59
27.423729
72
0.699174
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,871
leaderabilitycat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/leaderabilitycat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "leaderabilitycat.h" #include "version.h" #include <array> namespace game::LeaderAbilityCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LLeaderAbility*)0x8395e8, (LLeaderAbility*)0x8395f8, (LLeaderAbility*)0x839608, (LLeaderAbility*)0x839618, (LLeaderAbility*)0x839628, (LLeaderAbility*)0x839638, (LLeaderAbility*)0x839648, (LLeaderAbility*)0x839658, (LLeaderAbility*)0x839668, (LLeaderAbility*)0x839678, (LLeaderAbility*)0x839688, }, // Russobit Categories{ (LLeaderAbility*)0x8395e8, (LLeaderAbility*)0x8395f8, (LLeaderAbility*)0x839608, (LLeaderAbility*)0x839618, (LLeaderAbility*)0x839628, (LLeaderAbility*)0x839638, (LLeaderAbility*)0x839648, (LLeaderAbility*)0x839658, (LLeaderAbility*)0x839668, (LLeaderAbility*)0x839678, (LLeaderAbility*)0x839688, }, // Gog Categories{ (LLeaderAbility*)0x837598, (LLeaderAbility*)0x8375a8, (LLeaderAbility*)0x8375b8, (LLeaderAbility*)0x8375c8, (LLeaderAbility*)0x8375d8, (LLeaderAbility*)0x8375e8, (LLeaderAbility*)0x8375f8, (LLeaderAbility*)0x837608, (LLeaderAbility*)0x837618, (LLeaderAbility*)0x837628, (LLeaderAbility*)0x837638, }, // Scenario Editor Categories{ (LLeaderAbility*)0x665840, (LLeaderAbility*)0x665850, (LLeaderAbility*)0x665860, (LLeaderAbility*)0x665870, (LLeaderAbility*)0x665880, (LLeaderAbility*)0x665890, (LLeaderAbility*)0x6658A0, (LLeaderAbility*)0x6658B0, (LLeaderAbility*)0x6658C0, (LLeaderAbility*)0x6658D0, (LLeaderAbility*)0x6658E0, } }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } } // namespace game::LeaderAbilityCategories
2,844
C++
.cpp
87
26.793103
72
0.68532
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,872
usstackleader.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/usstackleader.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "usstackleader.h" #include "version.h" #include <array> namespace game::IUsStackLeaderApi { // clang-format off static std::array<IUsStackLeaderVftable*, 4> vftables = {{ // Akella (IUsStackLeaderVftable*)0x6ecd94, // Russobit (IUsStackLeaderVftable*)0x6ecd94, // Gog (IUsStackLeaderVftable*)0x6ead34, // Scenario Editor (IUsStackLeaderVftable*)0x5e0f5c, }}; // clang-format on const IUsStackLeaderVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IUsStackLeaderApi
1,380
C++
.cpp
39
32.897436
72
0.753743
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,873
unitsforhire.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitsforhire.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitsforhire.h" #include "categoryids.h" #include "dbf/dbffile.h" #include "dbfaccess.h" #include "log.h" #include "midgardid.h" #include "utils.h" #include <fmt/format.h> #include <string> #include <type_traits> /** Converts enum value to underlying integral type. */ template <typename T> static constexpr auto toIntegral(T enumValue) { return static_cast<typename std::underlying_type<T>::type>(enumValue); } namespace hooks { static UnitsForHire units; bool loadUnitsForHire() { using namespace utils; const std::string raceDbName{"Grace.dbf"}; DbfFile raceDb; if (!raceDb.open(globalsFolder() / raceDbName)) { logError("mssProxyError.log", fmt::format("Could not read {:s} database.", raceDbName)); return false; } // check how many new soldier_n columns we have, starting from soldier_6 constexpr size_t columnsMax{10}; size_t newColumns{}; for (; newColumns < columnsMax; ++newColumns) { const DbfColumn* column{raceDb.column(fmt::format("SOLDIER_{:d}", newColumns + 6))}; if (!column) { break; } } if (!newColumns) { return true; } UnitsForHire tmpUnits(raceDb.recordsTotal()); for (size_t row = 0; row < raceDb.recordsTotal(); ++row) { const std::string idColumnName{"RACE_ID"}; game::CMidgardID raceId{}; if (!dbRead(raceId, raceDb, row, idColumnName)) { logError("mssProxyError.log", fmt::format("Failed to read row {:d} column {:s} from {:s} database.", row, idColumnName, raceDbName)); return false; } if (raceId == game::invalidId) { logError("mssProxyError.log", fmt::format("Row {:d} has invalid {:s} value in {:s} database.", row, idColumnName, raceDbName)); return false; } const auto& idApi = game::CMidgardIDApi::get(); const int raceIndex = idApi.getTypeIndex(&raceId); if (raceIndex >= (int)tmpUnits.size()) { logError("mssProxyError.log", fmt::format("Row {:d} column {:s} has invalid " "race index {:d} in {:s} database.", row, idColumnName, raceIndex, raceDbName)); return false; } // Neutrals race does not hire units, skip if (raceIndex == toIntegral(game::RaceId::Neutral)) { continue; } for (size_t i = 0; i < newColumns; ++i) { const std::string columnName{fmt::format("SOLDIER_{:d}", i + 6)}; game::CMidgardID soldierId{}; if (!dbRead(soldierId, raceDb, row, columnName) || soldierId == game::invalidId) { logError("mssProxyError.log", fmt::format("Row {:d} column {:s} has invalid id in {:s} database", row, columnName, raceDbName)); return false; } // Allow different races to have different number of units to hire if (soldierId == game::emptyId) { continue; } tmpUnits[raceIndex].push_back(soldierId); } } units.swap(tmpUnits); return true; } const UnitsForHire& unitsForHire() { return units; } } // namespace hooks
4,257
C++
.cpp
109
30.715596
97
0.606736
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,874
netcustomservice.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netcustomservice.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netcustomservice.h" #include "lobbyclient.h" #include "log.h" #include "mempool.h" #include "midgard.h" #include "mqnetservice.h" #include "netcustomsession.h" #include "settings.h" #include "utils.h" #include <MessageIdentifiers.h> #include <fmt/format.h> #include <mutex> namespace hooks { void LobbyPeerCallbacks::onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) { if (!netService->lobbyPeer.peer) { return; } switch (type) { case ID_DISCONNECTION_NOTIFICATION: logDebug("lobby.log", "Disconnected"); break; case ID_ALREADY_CONNECTED: logDebug("lobby.log", "Already connected"); break; case ID_CONNECTION_LOST: logDebug("lobby.log", "Connection lost"); break; case ID_CONNECTION_ATTEMPT_FAILED: logDebug("lobby.log", "Connection attempt failed"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: logDebug("lobby.log", "Server is full"); break; case ID_CONNECTION_REQUEST_ACCEPTED: { logDebug("lobby.log", "Connection request accepted, set server address"); // Make sure plugins know about the server netService->lobbyClient.SetServerAddress(packet->systemAddress); netService->roomsClient.SetServerAddress(packet->systemAddress); break; } case ID_LOBBY2_SERVER_ERROR: logDebug("lobby.log", "Lobby server error"); break; default: logDebug("lobby.log", fmt::format("Packet type {:d}", static_cast<int>(type))); break; } } CNetCustomService::CNetCustomService(NetworkPeer::PeerPtr&& peer) : lobbyPeer(std::move(peer)) , callbacks(this) , session{nullptr} { lobbyPeer.addCallback(&callbacks); logDebug("lobby.log", "Set msg factory"); lobbyClient.SetMessageFactory(&lobbyMsgFactory); logDebug("lobby.log", "Create callbacks"); lobbyClient.SetCallbackInterface(&loggingCallbacks); logDebug("lobby.log", "Attach lobby client as a plugin"); lobbyPeer.peer->AttachPlugin(&lobbyClient); lobbyPeer.peer->AttachPlugin(&roomsClient); roomsClient.SetRoomsCallback(&roomsLogCallback); } static game::IMqNetService* getNetServiceInterface() { auto midgard = game::CMidgardApi::get().instance(); return midgard->data->netService; } CNetCustomService* getNetService() { auto service = getNetServiceInterface(); if (!isNetServiceCustom(service)) { return nullptr; } return static_cast<CNetCustomService*>(service); } void __fastcall netCustomServiceDtor(CNetCustomService* thisptr, int /*%edx*/, char flags) { logDebug("lobby.log", "CNetCustomService d-tor called"); thisptr->~CNetCustomService(); if (flags & 1) { logDebug("lobby.log", "CNetCustomService d-tor frees memory"); game::Memory::get().freeNonZero(thisptr); } } bool __fastcall netCustomServiceHasSessions(CNetCustomService* thisptr, int /*%edx*/) { logDebug("lobby.log", "CNetCustomService hasSessions called"); return false; } void __fastcall netCustomServiceGetSessions(CNetCustomService* thisptr, int /*%edx*/, game::List<game::IMqNetSessEnum*>* sessions, const GUID* appGuid, const char* ipAddress, bool allSessions, bool requirePassword) { // This method used by vanilla interface. // Since we have our custom one, we can ignore it and there is no need to implement. logDebug("lobby.log", "CNetCustomService getSessions called"); } void __fastcall netCustomServiceCreateSession(CNetCustomService* thisptr, int /*%edx*/, game::IMqNetSession** netSession, const GUID* /* appGuid */, const char* sessionName, const char* password) { logDebug("lobby.log", fmt::format("CNetCustomService createSession called. Name '{:s}'", sessionName)); // We already created a session, just return it *netSession = thisptr->session; } void __fastcall netCustomServiceJoinSession(CNetCustomService* thisptr, int /*%edx*/, game::IMqNetSession** netSession, game::IMqNetSessEnum* netSessionEnum, const char* password) { // This method is used by vanilla interface. // Since we are using our custom one, we can join session directly and ignore this method. logDebug("lobby.log", "CNetCustomService joinSession called"); } static game::IMqNetServiceVftable netCustomServiceVftable{ (game::IMqNetServiceVftable::Destructor)netCustomServiceDtor, (game::IMqNetServiceVftable::HasSessions)netCustomServiceHasSessions, (game::IMqNetServiceVftable::GetSessions)netCustomServiceGetSessions, (game::IMqNetServiceVftable::CreateSession)netCustomServiceCreateSession, (game::IMqNetServiceVftable::JoinSession)netCustomServiceJoinSession, }; bool createCustomNetService(game::IMqNetService** service) { using namespace game; *service = nullptr; logDebug("lobby.log", "Get peer instance"); auto lobbyPeer = NetworkPeer::PeerPtr(SLNet::RakPeerInterface::GetInstance()); const auto& lobbySettings = userSettings().lobby; const auto& clientPort = lobbySettings.client.port; SLNet::SocketDescriptor socket{clientPort, nullptr}; logDebug("lobby.log", fmt::format("Start lobby peer on port {:d}", clientPort)); if (lobbyPeer->Startup(1, &socket, 1) != SLNet::RAKNET_STARTED) { logError("lobby.log", "Failed to start lobby client"); return false; } const auto& serverIp = lobbySettings.server.ip; const auto& serverPort = lobbySettings.server.port; logDebug("lobby.log", fmt::format("Connecting to lobby server with ip '{:s}', port {:d}", serverIp, serverPort)); if (lobbyPeer->Connect(serverIp.c_str(), serverPort, nullptr, 0) != SLNet::CONNECTION_ATTEMPT_STARTED) { logError("lobby.log", "Failed to connect to lobby server"); return false; } logDebug("lobby.log", "Allocate CNetCustomService"); auto netService = (CNetCustomService*)game::Memory::get().allocate(sizeof(CNetCustomService)); logDebug("lobby.log", "Call placement new"); new (netService) CNetCustomService(std::move(lobbyPeer)); logDebug("lobby.log", "Assign vftable"); netService->vftable = &netCustomServiceVftable; logDebug("lobby.log", "CNetCustomService created"); *service = netService; return true; } void addLobbyCallbacks(SLNet::Lobby2Callbacks* callbacks) { auto netService{getNetService()}; if (!netService) { return; } netService->lobbyClient.AddCallbackInterface(callbacks); } void removeLobbyCallbacks(SLNet::Lobby2Callbacks* callbacks) { auto netService{getNetService()}; if (!netService) { return; } netService->lobbyClient.RemoveCallbackInterface(callbacks); } void addRoomsCallback(SLNet::RoomsCallback* callback) { auto netService{getNetService()}; if (!netService) { return; } logDebug("lobby.log", fmt::format("Adding room callback {:p}", (void*)callback)); netService->roomsClient.AddRoomsCallback(callback); } void removeRoomsCallback(SLNet::RoomsCallback* callback) { auto netService{getNetService()}; if (!netService) { return; } logDebug("lobby.log", fmt::format("Removing room callback {:p}", (void*)callback)); netService->roomsClient.RemoveRoomsCallback(callback); } bool isNetServiceCustom() { return isNetServiceCustom(getNetServiceInterface()); } bool isNetServiceCustom(const game::IMqNetService* service) { return service && (service->vftable == &netCustomServiceVftable); } } // namespace hooks
9,165
C++
.cpp
228
32.609649
98
0.664568
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,875
menuphase.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menuphase.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menuphase.h" #include "version.h" #include <array> namespace game::CMenuPhaseApi { // clang-format off std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x4ea926, (Api::SetTransition)0x4eb20c, (Api::DoTransition)0x4eae89, (Api::ShowFullScreenAnimation)0x4ead7e, (Api::SwitchToMenu)0x4eae4d, (Api::ShowTransition)0x4ebcd3, (Api::SwitchToMenu)0x4eb16c, (Api::ShowTransition)0x4ebd9d, (Api::ShowTransition)0x4ebe47, (Api::ShowTransition)0x4ebf3a, (Api::SwitchToMenu)0x4ec23e, (Api::ShowTransition)0x4ec340, (Api::SwitchToMenu)0x4ec398, (Api::ShowTransition)0x4ec3fe, (Api::SwitchToMenu)0x4ec079, (Api::SwitchToMenu)0x4ec0f2, (Api::SwitchToMenu)0x4ec124, (Api::SwitchToMenu)0x4ec1b9, (Api::SwitchToMenu)0x4ec1e7, (Api::SwitchToMenu)0x4ec36a, (Api::SwitchToMenu)0x4ec41b, (Api::SwitchToMenu)0x4ec449, (Api::ShowTransition)0x4ec46f, (Api::SwitchToMenu)0x4ebe19, (Api::SwitchToMenu)0x4ebe76, (Api::ShowTransition)0x4ebea4, (Api::SwitchToMenu)0x4ebf0c, (Api::SwitchToMenu)0x4ebf90, (Api::SwitchToMenu)0x4ebfbe, (Api::SwitchToMenu)0x4ebfec, (Api::SwitchToMenu)0x4ec009, (Api::SwitchToMenu)0x4ec037, (Api::SwitchToMenu)0x4ec4e0, (Api::SwitchToMenu)0x4ebbf4, (Api::SetString)0x4eba33, (Api::SetCampaignId)0x4ebb97, (Api::SetString)0x4ebbac, (Api::SetString)0x4ebbd0, }, // Russobit Api{ (Api::Constructor)0x4ea926, (Api::SetTransition)0x4eb20c, (Api::DoTransition)0x4eae89, (Api::ShowFullScreenAnimation)0x4ead7e, (Api::SwitchToMenu)0x4eae4d, (Api::ShowTransition)0x4ebcd3, (Api::SwitchToMenu)0x4eb16c, (Api::ShowTransition)0x4ebd9d, (Api::ShowTransition)0x4ebe47, (Api::ShowTransition)0x4ebf3a, (Api::SwitchToMenu)0x4ec23e, (Api::ShowTransition)0x4ec340, (Api::SwitchToMenu)0x4ec398, (Api::ShowTransition)0x4ec3fe, (Api::SwitchToMenu)0x4ec079, (Api::SwitchToMenu)0x4ec0f2, (Api::SwitchToMenu)0x4ec124, (Api::SwitchToMenu)0x4ec1b9, (Api::SwitchToMenu)0x4ec1e7, (Api::SwitchToMenu)0x4ec36a, (Api::SwitchToMenu)0x4ec41b, (Api::SwitchToMenu)0x4ec449, (Api::ShowTransition)0x4ec46f, (Api::SwitchToMenu)0x4ebe19, (Api::SwitchToMenu)0x4ebe76, (Api::ShowTransition)0x4ebea4, (Api::SwitchToMenu)0x4ebf0c, (Api::SwitchToMenu)0x4ebf90, (Api::SwitchToMenu)0x4ebfbe, (Api::SwitchToMenu)0x4ebfec, (Api::SwitchToMenu)0x4ec009, (Api::SwitchToMenu)0x4ec037, (Api::SwitchToMenu)0x4ec4e0, (Api::SwitchToMenu)0x4ebbf4, (Api::SetString)0x4eba33, (Api::SetCampaignId)0x4ebb97, (Api::SetString)0x4ebbac, (Api::SetString)0x4ebbd0, }, // Gog Api{ (Api::Constructor)0x4e9dd8, (Api::SetTransition)0x4ea6be, (Api::DoTransition)0x4ea33b, (Api::ShowFullScreenAnimation)0x4ea230, (Api::SwitchToMenu)0x4ea2ff, (Api::ShowTransition)0x4eb193, (Api::SwitchToMenu)0x4ea61e, (Api::ShowTransition)0x4eb25d, (Api::ShowTransition)0x4eb307, (Api::ShowTransition)0x4eb3fa, (Api::SwitchToMenu)0x4eb6fe, (Api::ShowTransition)0x4eb800, (Api::SwitchToMenu)0x4eb858, (Api::ShowTransition)0x4eb8be, (Api::SwitchToMenu)0x4eb539, (Api::SwitchToMenu)0x4eb5b2, (Api::SwitchToMenu)0x4eb5e4, (Api::SwitchToMenu)0x4eb679, (Api::SwitchToMenu)0x4eb6a7, (Api::SwitchToMenu)0x4eb82a, (Api::SwitchToMenu)0x4eb8db, (Api::SwitchToMenu)0x4eb909, (Api::ShowTransition)0x4eb92f, (Api::SwitchToMenu)0x4eb2d9, (Api::SwitchToMenu)0x4eb336, (Api::ShowTransition)0x4eb364, (Api::SwitchToMenu)0x4eb3cc, (Api::SwitchToMenu)0x4eb450, (Api::SwitchToMenu)0x4eb47e, (Api::SwitchToMenu)0x4eb4ac, (Api::SwitchToMenu)0x4eb4c9, (Api::SwitchToMenu)0x4eb4f7, (Api::SwitchToMenu)0x4eb9a0, (Api::SwitchToMenu)0x4eb0b4, (Api::SetString)0x4eaeec, (Api::SetCampaignId)0x4eb050, (Api::SetString)0x4eb06c, (Api::SetString)0x4eb090, }, }}; static std::array<IMqNetSystemVftable*, 3> vftables = {{ // Akella (IMqNetSystemVftable*)0x6df0a4, // Russobit (IMqNetSystemVftable*)0x6df0a4, // Gog (IMqNetSystemVftable*)0x6dd04c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } IMqNetSystemVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMenuPhaseApi
5,771
C++
.cpp
166
27.716867
72
0.663094
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,876
battlemsgdata.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/battlemsgdata.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "battlemsgdata.h" #include "version.h" #include <array> namespace game::BattleMsgDataApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::GetUnitStatus)0x623b8c, (Api::SetUnitStatus)0x623c11, (Api::GetUnitIntValue)0x62332c, (Api::GetUnitIntValue)0x623391, (Api::SetUnitIntValue)0x6232d7, (Api::SetUnitInt16Value)0x62423b, (Api::CheckUnitDeath)0x65cf69, (Api::SetInt8Value)0x6247d9, (Api::AddSummonedUnit)0x6235c0, (Api::SetSummonOwner)0x6249ec, (Api::CannotUseDoppelgangerAttack)0x662e69, (Api::RemoveTransformStatuses)0x661f7b, (Api::IsUnitAttacker)0x623b58, (Api::GetUnitIntValue)0x6233f6, (Api::SetUnitIntValue)0x6233c3, (Api::SetUnitBoolValue)0x62371c, (Api::UnitHasModifier)0x65e9c8, (Api::GetUnitInfoById)0x622ef5, (Api::CanPerformAttackOnUnitWithStatusCheck)0x64734d, (Api::IsUnitAttackSourceWardRemoved)0x623d76, (Api::RemoveUnitAttackSourceWard)0x6240e9, (Api::IsUnitAttackClassWardRemoved)0x623dc7, (Api::RemoveUnitAttackClassWard)0x624130, (Api::UnitCanBeHealed)0x65e938, (Api::UnitCanBeCured)0x65d890, (Api::UnitCanBeRevived)0x65d927, (Api::AfterBattleTurn)0x627ac9, (Api::BeforeBattleTurn)0x627bff, (Api::ResetModifiedUnitsInfo)0x62326e, (Api::ResetUnitModifierInfo)0x6231d4, (Api::FindAttackTarget)0x5d163a, (Api::FindAttackTargetWithAllReach)0x5d0ee1, (Api::FindSpecificAttackTarget)0x5d19e9, (Api::FindSpecificAttackTarget)0x5d3079, (Api::FindDoppelgangerAttackTarget)0x5d2409, (Api::FindDamageAttackTargetWithNonAllReach)0x5d0a1b, (Api::FindDamageAttackTargetWithAnyReach)0x5d0cf1, (Api::FindDamageAttackTargetWithAdjacentReach)0x5d0b00, (Api::AddUnitToBattleMsgData)0x62282a, (Api::Constructor)0x62dee0, (Api::CopyConstructor)0x622656, (Api::CopyConstructor)0x6229ed, (Api::CopyAssignment)0x622a21, (Api::Copy)0x62e200, (Api::Destructor)0x622a16, (Api::RemoveUnitInfo)0x623652, (Api::DecreaseUnitAttacks)0x6239b6, (Api::GetTargetsToAttack)0x62884b, (Api::GetLeaderEquippedBattleItemIds)0x64aff9, (Api::GetLeaderEquippedBattleItemIndex)0x634f1e, (Api::GetUnitInfos)0x623531, (Api::FillTargetsList)0x65b725, (Api::FillTargetsListForAllAnyAttackReach)0x65bbc6, (Api::FillTargetsListForAllAnyAttackReach)0x65bcf7, (Api::FillTargetsListForAdjacentAttackReach)0x65be28, (Api::FillEmptyTargetsList)0x66411a, (Api::FillEmptyTargetsListForAllAnyAttackReach)0x664226, (Api::FillEmptyTargetsListForAllAnyAttackReach)0x66429c, (Api::FillTargetsListForAdjacentAttackReach)0x664312, (Api::IsAutoBattle)0x6243c8, (Api::AlliesNotPreventingAdjacentAttack)0x65c19c, (Api::GiveAttack)0x623ade, (Api::RemoveFiniteBoostLowerDamage)0x627b07, (Api::GenerateBigFaceDescription)0x650ea8, (Api::UpdateBattleActions)0x625253, (Api::GetItemAttackTargets)0x62571b, (Api::BeforeBattleRound)0x623440, }, // Russobit Api{ (Api::GetUnitStatus)0x623b8c, (Api::SetUnitStatus)0x623c11, (Api::GetUnitIntValue)0x62332c, (Api::GetUnitIntValue)0x623391, (Api::SetUnitIntValue)0x6232d7, (Api::SetUnitInt16Value)0x62423b, (Api::CheckUnitDeath)0x65cf69, (Api::SetInt8Value)0x6247d9, (Api::AddSummonedUnit)0x6235c0, (Api::SetSummonOwner)0x6249ec, (Api::CannotUseDoppelgangerAttack)0x662e69, (Api::RemoveTransformStatuses)0x661f7b, (Api::IsUnitAttacker)0x623b58, (Api::GetUnitIntValue)0x6233f6, (Api::SetUnitIntValue)0x6233c3, (Api::SetUnitBoolValue)0x62371c, (Api::UnitHasModifier)0x65e9c8, (Api::GetUnitInfoById)0x622ef5, (Api::CanPerformAttackOnUnitWithStatusCheck)0x64734d, (Api::IsUnitAttackSourceWardRemoved)0x623d76, (Api::RemoveUnitAttackSourceWard)0x6240e9, (Api::IsUnitAttackClassWardRemoved)0x623dc7, (Api::RemoveUnitAttackClassWard)0x624130, (Api::UnitCanBeHealed)0x65e938, (Api::UnitCanBeCured)0x65d890, (Api::UnitCanBeRevived)0x65d927, (Api::AfterBattleTurn)0x627ac9, (Api::BeforeBattleTurn)0x627bff, (Api::ResetModifiedUnitsInfo)0x62326e, (Api::ResetUnitModifierInfo)0x6231d4, (Api::FindAttackTarget)0x5d163a, (Api::FindAttackTargetWithAllReach)0x5d0ee1, (Api::FindSpecificAttackTarget)0x5d19e9, (Api::FindSpecificAttackTarget)0x5d3079, (Api::FindDoppelgangerAttackTarget)0x5d2409, (Api::FindDamageAttackTargetWithNonAllReach)0x5d0a1b, (Api::FindDamageAttackTargetWithAnyReach)0x5d0cf1, (Api::FindDamageAttackTargetWithAdjacentReach)0x5d0b00, (Api::AddUnitToBattleMsgData)0x62282a, (Api::Constructor)0x62dee0, (Api::CopyConstructor)0x622656, (Api::CopyConstructor)0x6229ed, (Api::CopyAssignment)0x622a21, (Api::Copy)0x62e200, (Api::Destructor)0x622a16, (Api::RemoveUnitInfo)0x623652, (Api::DecreaseUnitAttacks)0x6239b6, (Api::GetTargetsToAttack)0x62884b, (Api::GetLeaderEquippedBattleItemIds)0x64aff9, (Api::GetLeaderEquippedBattleItemIndex)0x634f1e, (Api::GetUnitInfos)0x623531, (Api::FillTargetsList)0x65b725, (Api::FillTargetsListForAllAnyAttackReach)0x65bbc6, (Api::FillTargetsListForAllAnyAttackReach)0x65bcf7, (Api::FillTargetsListForAdjacentAttackReach)0x65be28, (Api::FillEmptyTargetsList)0x66411a, (Api::FillEmptyTargetsListForAllAnyAttackReach)0x664226, (Api::FillEmptyTargetsListForAllAnyAttackReach)0x66429c, (Api::FillTargetsListForAdjacentAttackReach)0x664312, (Api::IsAutoBattle)0x6243c8, (Api::AlliesNotPreventingAdjacentAttack)0x65c19c, (Api::GiveAttack)0x623ade, (Api::RemoveFiniteBoostLowerDamage)0x627b07, (Api::GenerateBigFaceDescription)0x650ea8, (Api::UpdateBattleActions)0x625253, (Api::GetItemAttackTargets)0x62571b, (Api::BeforeBattleRound)0x623440, }, // Gog Api{ (Api::GetUnitStatus)0x62271c, (Api::SetUnitStatus)0x6227a1, (Api::GetUnitIntValue)0x621ebc, (Api::GetUnitIntValue)0x621f21, (Api::SetUnitIntValue)0x621e67, (Api::SetUnitInt16Value)0x622dcb, (Api::CheckUnitDeath)0x65b9e9, (Api::SetInt8Value)0x623369, (Api::AddSummonedUnit)0x622150, (Api::SetSummonOwner)0x62357c, (Api::CannotUseDoppelgangerAttack)0x6618e9, (Api::RemoveTransformStatuses)0x6609fb, (Api::IsUnitAttacker)0x6226e8, (Api::GetUnitIntValue)0x621f86, (Api::SetUnitIntValue)0x621f53, (Api::SetUnitBoolValue)0x6222ac, (Api::UnitHasModifier)0x65d448, (Api::GetUnitInfoById)0x621a85, (Api::CanPerformAttackOnUnitWithStatusCheck)0x645b7d, (Api::IsUnitAttackSourceWardRemoved)0x622906, (Api::RemoveUnitAttackSourceWard)0x622c79, (Api::IsUnitAttackClassWardRemoved)0x622957, (Api::RemoveUnitAttackClassWard)0x622cc0, (Api::UnitCanBeHealed)0x65d3b8, (Api::UnitCanBeCured)0x65c310, (Api::UnitCanBeRevived)0x65c3a7, (Api::AfterBattleTurn)0x626609, (Api::BeforeBattleTurn)0x62673f, (Api::ResetModifiedUnitsInfo)0x621dfe, (Api::ResetUnitModifierInfo)0x621d64, (Api::FindAttackTarget)0x5d056b, (Api::FindAttackTargetWithAllReach)0x5cfe12, (Api::FindSpecificAttackTarget)0x5d091a, (Api::FindSpecificAttackTarget)0x5d1faa, (Api::FindDoppelgangerAttackTarget)0x5d133a, (Api::FindDamageAttackTargetWithNonAllReach)0x5cf94c, (Api::FindDamageAttackTargetWithAnyReach)0x5cfc22, (Api::FindDamageAttackTargetWithAdjacentReach)0x5cfa31, (Api::AddUnitToBattleMsgData)0x6213ba, (Api::Constructor)0x62c920, (Api::CopyConstructor)0x6211e6, (Api::CopyConstructor)0x62157d, (Api::CopyAssignment)0x6215b1, (Api::Copy)0x62cc40, (Api::Destructor)0x6215a6, (Api::RemoveUnitInfo)0x6221e2, (Api::DecreaseUnitAttacks)0x622546, (Api::GetTargetsToAttack)0x62738b, (Api::GetLeaderEquippedBattleItemIds)0x649939, (Api::GetLeaderEquippedBattleItemIndex)0x63395e, (Api::GetUnitInfos)0x6220c1, (Api::FillTargetsList)0x65a1a5, (Api::FillTargetsListForAllAnyAttackReach)0x65a646, (Api::FillTargetsListForAllAnyAttackReach)0x65a777, (Api::FillTargetsListForAdjacentAttackReach)0x65a8a8, (Api::FillEmptyTargetsList)0x662b9a, (Api::FillEmptyTargetsListForAllAnyAttackReach)0x662ca6, (Api::FillEmptyTargetsListForAllAnyAttackReach)0x662d1c, (Api::FillTargetsListForAdjacentAttackReach)0x662d92, (Api::IsAutoBattle)0x622f58, (Api::AlliesNotPreventingAdjacentAttack)0x65ac1c, (Api::GiveAttack)0x62266e, (Api::RemoveFiniteBoostLowerDamage)0x626647, (Api::GenerateBigFaceDescription)0x64f7e8, (Api::UpdateBattleActions)0x623d93, (Api::GetItemAttackTargets)0x62425b, (Api::BeforeBattleRound)0x621fd0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BattleMsgDataApi
10,481
C++
.cpp
241
35.560166
72
0.713434
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,877
batviewer2dengine.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batviewer2dengine.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batviewer2dengine.h" #include "version.h" #include <array> namespace game::BatViewer2DEngineApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::ClearTargetMarks)0x6483e9, (Api::DrawTargetMark)0x648394, }, // Russobit Api{ (Api::ClearTargetMarks)0x6483e9, (Api::DrawTargetMark)0x648394, }, // Gog Api{ (Api::ClearTargetMarks)0x646c69, (Api::DrawTargetMark)0x646c14, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BatViewer2DEngineApi
1,458
C++
.cpp
46
28.304348
72
0.717129
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,878
image2fill.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/image2fill.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "image2fill.h" #include "version.h" #include <array> namespace game::CImage2FillApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x53576e, (Api::SetColor)0x5357ff, }, // Russobit Api{ (Api::Constructor)0x53576e, (Api::SetColor)0x5357ff, }, // Gog Api{ (Api::Constructor)0x534d85, (Api::SetColor)0x534E16, }, // Scenario Editor Api{ (Api::Constructor)0, (Api::SetColor)0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CImage2FillApi
1,499
C++
.cpp
51
25.686275
72
0.693001
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,879
midevcondition.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midevcondition.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midevcondition.h" #include "version.h" #include <array> namespace game::CMidEvConditionApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::CreateFromCategory)0x5f2359, }, // Russobit Api{ (Api::CreateFromCategory)0x5f2359, }, // Gog Api{ (Api::CreateFromCategory)0x5f1068, }, // Scenario Editor Api{ (Api::CreateFromCategory)0x4f81f7, (Api::GetInfoString)0x41acba, (Api::GetDescription)0x41a9ea, (Api::GetDescription)0x41cad0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidEvConditionApi
1,537
C++
.cpp
50
27.14
72
0.709852
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,880
midcondownresource.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midcondownresource.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midcondownresource.h" #include "button.h" #include "condinterf.h" #include "condinterfhandler.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "eventconditioncathooks.h" #include "game.h" #include "interfmanager.h" #include "log.h" #include "mempool.h" #include "midevcondition.h" #include "midevent.h" #include "mideventhooks.h" #include "midgard.h" #include "midgardobjectmap.h" #include "midgardstream.h" #include "midplayer.h" #include "testcondition.h" #include "textboxinterf.h" #include "textids.h" #include "togglebutton.h" #include "utils.h" #include <fmt/format.h> namespace hooks { /** * Custom event condition that checks if player have * less or equal / greater or equal amount of resources. */ struct CMidCondOwnResource : public game::CMidEvCondition { game::Bank resource; /** If true, player must have more than specified amount to met the condition. */ bool greaterOrEqual; }; void __fastcall condOwnResourceDestructor(CMidCondOwnResource* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall condOwnResourceIsIdsEqual(const CMidCondOwnResource*, int /*%edx*/, const game::CMidgardID*) { return false; } void __fastcall condOwnResourceAddToList(const CMidCondOwnResource*, int /*%edx*/, game::Set<game::CMidgardID>*) { } bool __fastcall condOwnResourceIsValid(const CMidCondOwnResource* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap) { return game::BankApi::get().isValid(&thisptr->resource); } bool __fastcall condOwnResourceMethod4(const CMidCondOwnResource*, int /*%edx*/, int) { return false; } void __fastcall condOwnResourceStream(CMidCondOwnResource* thisptr, int /*%edx*/, game::IMidgardStream** stream) { auto streamPtr = *stream; auto vftable = streamPtr->vftable; vftable->streamCurrency(streamPtr, "BANK", &thisptr->resource); vftable->streamBool(streamPtr, "GRE", &thisptr->greaterOrEqual); } // clang-format off static game::CMidEvConditionVftable condOwnResourceVftable{ (game::CMidEvConditionVftable::Destructor)condOwnResourceDestructor, (game::CMidEvConditionVftable::IsIdsEqual)condOwnResourceIsIdsEqual, (game::CMidEvConditionVftable::AddToList)condOwnResourceAddToList, (game::CMidEvConditionVftable::IsValid)condOwnResourceIsValid, (game::CMidEvConditionVftable::Method4)condOwnResourceMethod4, (game::CMidEvConditionVftable::Stream)condOwnResourceStream, }; // clang-format on game::CMidEvCondition* createMidCondOwnResource() { using namespace game; auto ownResource = (CMidCondOwnResource*)Memory::get().allocate(sizeof(CMidCondOwnResource)); ownResource->category.vftable = EventCondCategories::vftable(); ownResource->category.id = customEventConditions().ownResource.category.id; ownResource->category.table = customEventConditions().ownResource.category.table; ownResource->greaterOrEqual = true; ownResource->resource = Bank{}; ownResource->vftable = &condOwnResourceVftable; return ownResource; } void __stdcall midCondOwnResourceGetInfoString(game::String* info, const game::IMidgardObjectMap* objectMap, const game::CMidEvCondition* eventCondition) { const auto ownResource = static_cast<const CMidCondOwnResource*>(eventCondition); const auto& res = ownResource->resource; const auto textInfoId = &customEventConditions().ownResource.infoText; std::string str{game::gameFunctions().getInterfaceText(textInfoId)}; replace(str, "%COND%", (ownResource->greaterOrEqual ? ">=" : "<=")); replace(str, "%GOLD%", fmt::format("{:d}", res.gold)); replace(str, "%INFERNAL%", fmt::format("{:d}", res.infernalMana)); replace(str, "%LIFE%", fmt::format("{:d}", res.lifeMana)); replace(str, "%DEATH%", fmt::format("{:d}", res.deathMana)); replace(str, "%RUNIC%", fmt::format("{:d}", res.runicMana)); replace(str, "%GROVE%", fmt::format("{:d}", res.groveMana)); game::StringApi::get().initFromStringN(info, str.c_str(), str.length()); } struct CCondOwnResourceInterf : public game::editor::CCondInterf { void* unknown; CMidCondOwnResource* ownResourceCondition; game::CMidgardID eventId; }; void __fastcall condOwnResourceInterfDestructor(CCondOwnResourceInterf* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } static game::CInterfaceVftable::OnVisibilityChanged onVisibilityChanged{}; void __fastcall condOwnResourceInterfOnVisibilityChanged(CCondOwnResourceInterf* thisptr, int /*%edx*/, int a2, int a3) { using namespace game; if (onVisibilityChanged) { onVisibilityChanged(thisptr, a2, a3); } if (!a2) { return; } auto ownResource = thisptr->ownResourceCondition; if (!ownResource) { return; } auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); const auto& setString = CEditBoxInterfApi::get().setString; const auto& resources = ownResource->resource; auto goldEdit = dialogApi.findEditBox(dialog, "EDIT_GOLD"); if (goldEdit) { setString(goldEdit, fmt::format("{:d}", resources.gold).c_str()); } auto infernalEdit = dialogApi.findEditBox(dialog, "EDIT_INFERNAL"); if (infernalEdit) { setString(infernalEdit, fmt::format("{:d}", resources.infernalMana).c_str()); } auto lifeEdit = dialogApi.findEditBox(dialog, "EDIT_LIFE"); if (lifeEdit) { setString(lifeEdit, fmt::format("{:d}", resources.lifeMana).c_str()); } auto deathEdit = dialogApi.findEditBox(dialog, "EDIT_DEATH"); if (deathEdit) { setString(deathEdit, fmt::format("{:d}", resources.deathMana).c_str()); } auto runicEdit = dialogApi.findEditBox(dialog, "EDIT_RUNIC"); if (runicEdit) { setString(runicEdit, fmt::format("{:d}", resources.runicMana).c_str()); } auto groveEdit = dialogApi.findEditBox(dialog, "EDIT_GROVE"); if (groveEdit) { setString(groveEdit, fmt::format("{:d}", resources.groveMana).c_str()); } auto toggle = dialogApi.findToggleButton(dialog, "TOG_GRE"); if (toggle) { CToggleButtonApi::get().setChecked(toggle, ownResource->greaterOrEqual); } thisptr->ownResourceCondition = nullptr; } bool __fastcall condOwnResourceInterfSetEventCondition(CCondOwnResourceInterf* thisptr, int /*%edx*/, game::CMidEvCondition* eventCondition) { if (eventCondition->category.id == customEventConditions().ownResource.category.id) { thisptr->ownResourceCondition = reinterpret_cast<CMidCondOwnResource*>(eventCondition); return true; } return false; } void __fastcall condOwnResourcesInterfCancelButtonHandler(CCondOwnResourceInterf* thisptr, int /*%edx*/) { using namespace game; using namespace editor; auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, false); } InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } void __fastcall condOwnResourcesInterfOkButtonHandler(CCondOwnResourceInterf* thisptr, int /*%edx*/) { using namespace game; using namespace editor; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); Bank resources{}; auto goldEdit = dialogApi.findEditBox(dialog, "EDIT_GOLD"); if (goldEdit) { resources.gold = std::atoi(goldEdit->data->editBoxData.inputString.string); } auto infernalEdit = dialogApi.findEditBox(dialog, "EDIT_INFERNAL"); if (infernalEdit) { resources.infernalMana = std::atoi(infernalEdit->data->editBoxData.inputString.string); } auto lifeEdit = dialogApi.findEditBox(dialog, "EDIT_LIFE"); if (lifeEdit) { resources.lifeMana = std::atoi(lifeEdit->data->editBoxData.inputString.string); } auto deathEdit = dialogApi.findEditBox(dialog, "EDIT_DEATH"); if (deathEdit) { resources.deathMana = std::atoi(deathEdit->data->editBoxData.inputString.string); } auto runicEdit = dialogApi.findEditBox(dialog, "EDIT_RUNIC"); if (runicEdit) { resources.runicMana = std::atoi(runicEdit->data->editBoxData.inputString.string); } auto groveEdit = dialogApi.findEditBox(dialog, "EDIT_GROVE"); if (groveEdit) { resources.groveMana = std::atoi(groveEdit->data->editBoxData.inputString.string); } // This should never happen since we don't allow to enter resource values outside [0 : 9999]. if (!BankApi::get().isValid(&resources)) { // Could not create new condition showMessageBox(getInterfaceText("X100TA0631")); return; } auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, true); } auto objectMap = CCondInterfApi::get().getObjectMap(thisptr->unknown); { auto midEvent = (const CMidEvent*)objectMap->vftable ->findScenarioObjectById(objectMap, &thisptr->eventId); const int conditionsTotal = midEvent->conditions.end - midEvent->conditions.bgn; if (conditionsTotal >= 10) { // Could not create new condition showMessageBox(getInterfaceText("X100TA0631")); return; } } auto midEvent = (CMidEvent*)objectMap->vftable ->findScenarioObjectByIdForChange(objectMap, &thisptr->eventId); auto ownResource = static_cast<CMidCondOwnResource*>(createMidCondOwnResource()); BankApi::get().copy(&ownResource->resource, &resources); auto greToggle = dialogApi.findToggleButton(dialog, "TOG_GRE"); if (greToggle) { ownResource->greaterOrEqual = greToggle->data->checked; } CMidEventApi::get().addCondition(midEvent, nullptr, ownResource); InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } static game::editor::CCondInterfVftable condOwnResourceInterfVftable{}; game::editor::CCondInterf* createCondOwnResourceInterf(game::ITask* task, void* a2, const game::CMidgardID* eventId) { using namespace game; using namespace editor; auto thisptr = (CCondOwnResourceInterf*)Memory::get().allocate(sizeof(CCondOwnResourceInterf)); static const char dialogName[]{"DLG_COND_OWN_RESOURCE"}; CCondInterfApi::get().constructor(thisptr, dialogName, task); // After CCondInterf c-tor we have its vftable. // Use its address to populate our handmade vftable // since its easier than defining all these methods by hand in code. static bool initialized{false}; if (!initialized) { // Remember parent's OnVisibilityChanged address so we can use it later onVisibilityChanged = thisptr->CInterface::vftable->onVisibilityChanged; initialized = true; std::memcpy(&condOwnResourceInterfVftable, thisptr->CInterface::vftable, sizeof(CInterfaceVftable)); // Change methods that are specific for our custom class condOwnResourceInterfVftable .destructor = (CInterfaceVftable::Destructor)&condOwnResourceInterfDestructor; condOwnResourceInterfVftable.onVisibilityChanged = (CInterfaceVftable::OnVisibilityChanged)&condOwnResourceInterfOnVisibilityChanged; condOwnResourceInterfVftable .setEventCondition = (CCondInterfVftable:: SetEventCondition)&condOwnResourceInterfSetEventCondition; } thisptr->CInterface::vftable = &condOwnResourceInterfVftable; thisptr->eventId = *eventId; thisptr->unknown = a2; thisptr->ownResourceCondition = nullptr; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); if (dialogApi.findButton(dialog, "BTN_OK")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condOwnResourcesInterfOkButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } if (dialogApi.findButton(dialog, "BTN_CANCEL")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condOwnResourcesInterfCancelButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } const auto& setFilterAndLength = CEditBoxInterfApi::get().setFilterAndLength; setFilterAndLength(dialog, "EDIT_GOLD", dialogName, EditFilter::DigitsOnly, 4); setFilterAndLength(dialog, "EDIT_INFERNAL", dialogName, EditFilter::DigitsOnly, 4); setFilterAndLength(dialog, "EDIT_LIFE", dialogName, EditFilter::DigitsOnly, 4); setFilterAndLength(dialog, "EDIT_DEATH", dialogName, EditFilter::DigitsOnly, 4); setFilterAndLength(dialog, "EDIT_RUNIC", dialogName, EditFilter::DigitsOnly, 4); setFilterAndLength(dialog, "EDIT_GROVE", dialogName, EditFilter::DigitsOnly, 4); return thisptr; } struct CTestOwnResource : public game::ITestCondition { CMidCondOwnResource* ownResource; }; void __fastcall testOwnResourceDestructor(CTestOwnResource* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall testOwnResourceDoTest(const CTestOwnResource* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* eventId) { using namespace game; if (!CMidEventApi::get().affectsPlayer(objectMap, playerId, eventId)) { return false; } auto obj = objectMap->vftable->findScenarioObjectById(objectMap, playerId); auto player = reinterpret_cast<const CMidPlayer*>(obj); const auto& playerBank = player->bank; const auto condition = thisptr->ownResource; const auto& resource = condition->resource; return condition->greaterOrEqual ? playerBank >= resource : playerBank <= resource; } game::ITestConditionVftable testOwnResourceVftable{ (game::ITestConditionVftable::Destructor)testOwnResourceDestructor, (game::ITestConditionVftable::Test)testOwnResourceDoTest, }; game::ITestCondition* createTestOwnResource(game::CMidEvCondition* eventCondition) { auto thisptr = (CTestOwnResource*)game::Memory::get().allocate(sizeof(CTestOwnResource)); thisptr->ownResource = reinterpret_cast<CMidCondOwnResource*>(eventCondition); thisptr->vftable = &testOwnResourceVftable; return thisptr; } bool checkOwnResourceConditionsValid(game::CDialogInterf*, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* eventId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, eventId); if (!obj) { return false; } const auto& category = customEventConditions().ownResource.category; auto event = static_cast<const CMidEvent*>(obj); std::vector<const CMidEvCondition*> conditions{}; getConditionsOfType(event, &category, conditions); const auto& ownResourceTextIds = textIds().events.conditions.ownResource; // At most 2 own resource conditions allowed if (conditions.size() > 2) { auto message = getInterfaceText(ownResourceTextIds.tooMany.c_str()); if (message.empty()) { message = "At most two conditions of type \"Own resource\" is allowed per event."; } showMessageBox(message); return false; } // Single condition is always valid if (conditions.size() != 2) { return true; } auto first = static_cast<const CMidCondOwnResource*>(conditions[0]); auto second = static_cast<const CMidCondOwnResource*>(conditions[1]); // Allow meaningless conditions if (first->greaterOrEqual == second->greaterOrEqual) { return true; } bool mutuallyExclusive{false}; // Valid range should be [first : second] if (first->greaterOrEqual) { mutuallyExclusive = !(first->resource <= second->resource); } // Valid range should be [second : first] if (second->greaterOrEqual) { mutuallyExclusive = !(second->resource <= first->resource); } if (mutuallyExclusive) { auto message = getInterfaceText(ownResourceTextIds.mutuallyExclusive.c_str()); if (message.empty()) { message = "Conditions of type \"Own resource\" are mutually exclusive."; } showMessageBox(message); } return !mutuallyExclusive; } } // namespace hooks
19,617
C++
.cpp
442
36.708145
100
0.677208
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,881
menunewskirmishsingle.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menunewskirmishsingle.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menunewskirmishsingle.h" #include "version.h" #include <array> namespace game::CMenuNewSkirmishSingleApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x4ea0b8 }, // Russobit Api{ (Api::Constructor)0x4ea0b8 }, // Gog Api{ (Api::Constructor)0x4e9553 } }}; static std::array<Vftable*, 3> vftables = {{ // Akella (Vftable*)0x6ded5c, // Russobit (Vftable*)0x6ded5c, // Gog (Vftable*)0x6dcd04 }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } Vftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMenuNewSkirmishSingleApi
1,582
C++
.cpp
55
25.654545
72
0.711184
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,882
enclayoutstack.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutstack.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutstack.h" #include "version.h" #include <array> namespace game::CEncLayoutStackApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Update)0x57c814, }, // Russobit Api{ (Api::Update)0x57c814, }, // Gog Api{ (Api::Update)0x57becf, }, // Scenario Editor Api{ (Api::Update)0x4cdc32, }, }}; static std::array<IEncLayoutVftable*, 4> vftables = {{ // Akella (IEncLayoutVftable*)0x6e8dec, // Russobit (IEncLayoutVftable*)0x6e8dec, // Gog (IEncLayoutVftable*)0x6e6d8c, // Scenario Editor (IEncLayoutVftable*)0x5d81a4, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } IEncLayoutVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CEncLayoutStackApi
1,729
C++
.cpp
61
24.983607
72
0.703793
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,883
midcondvarcmp.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midcondvarcmp.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midcondvarcmp.h" #include "button.h" #include "condinterf.h" #include "condinterfhandler.h" #include "d2string.h" #include "dialoginterf.h" #include "eventconditioncathooks.h" #include "game.h" #include "gameutils.h" #include "interfmanager.h" #include "listbox.h" #include "mempool.h" #include "midevcondition.h" #include "midevent.h" #include "mideventhooks.h" #include "midgardobjectmap.h" #include "midgardstream.h" #include "midscenvariables.h" #include "radiobuttoninterf.h" #include "testcondition.h" #include "textids.h" #include "utils.h" #include <fmt/format.h> #include <functional> #include <vector> namespace hooks { /** Same as RAD_OPERATOR button indices in DLG_COND_VAR_CMP from ScenEdit.dlg */ enum class CompareType : int { Equal, NotEqual, Greater, GreaterEqual, Less, LessEqual, }; /** Custom event condition that compares two scenario variables. */ struct CMidCondVarCmp : game::CMidEvCondition { int variableId1; int variableId2; CompareType compareType; }; void __fastcall condVarCmpDestructor(CMidCondVarCmp* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall condVarCmpIsIdsEqual(const CMidCondVarCmp*, int /*%edx*/, const game::CMidgardID*) { return false; } void __fastcall condVarCmpAddToList(const CMidCondVarCmp*, int /*%edx*/, game::Set<game::CMidgardID>*) { } bool __fastcall condVarCmpIsValid(const CMidCondVarCmp* thisptr, int /*%edx*/, const game::IMidgardObjectMap*) { return true; } bool __fastcall condVarCmpMethod4(const CMidCondVarCmp*, int /*%edx*/, int) { return false; } void __fastcall condVarCmpStream(CMidCondVarCmp* thisptr, int /*%edx*/, game::IMidgardStream** stream) { auto streamPtr = *stream; auto vftable = streamPtr->vftable; vftable->streamInt(streamPtr, "VAR1", &thisptr->variableId1); vftable->streamInt(streamPtr, "VAR2", &thisptr->variableId2); vftable->streamInt(streamPtr, "CMP", (int*)&thisptr->compareType); } // clang-format off static game::CMidEvConditionVftable condVarCmpVftable{ (game::CMidEvConditionVftable::Destructor)condVarCmpDestructor, (game::CMidEvConditionVftable::IsIdsEqual)condVarCmpIsIdsEqual, (game::CMidEvConditionVftable::AddToList)condVarCmpAddToList, (game::CMidEvConditionVftable::IsValid)condVarCmpIsValid, (game::CMidEvConditionVftable::Method4)condVarCmpMethod4, (game::CMidEvConditionVftable::Stream)condVarCmpStream, }; // clang-format on game::CMidEvCondition* createMidCondVarCmp() { using namespace game; auto varCmp = (CMidCondVarCmp*)Memory::get().allocate(sizeof(CMidCondVarCmp)); varCmp->category.vftable = EventCondCategories::vftable(); varCmp->category.id = customEventConditions().variableCmp.category.id; varCmp->category.table = customEventConditions().variableCmp.category.table; varCmp->compareType = CompareType::Equal; varCmp->vftable = &condVarCmpVftable; return varCmp; } void __stdcall midCondVarCmpGetInfoString(game::String* info, const game::IMidgardObjectMap* objectMap, const game::CMidEvCondition* eventCondition) { auto variables = getScenarioVariables(objectMap); if (!variables) { // Sanity check, this should never happen return; } auto* condition = static_cast<const CMidCondVarCmp*>(eventCondition); auto& findById = game::CMidScenVariablesApi::get().findById; auto data1 = findById(variables, condition->variableId1); auto data2 = findById(variables, condition->variableId2); std::string comparison; const auto& varCmpTextIds = textIds().events.conditions.variableCmp; switch (condition->compareType) { case CompareType::Equal: comparison = getInterfaceText(varCmpTextIds.equal.c_str()); if (comparison.empty()) { comparison = "is equal to"; } break; case CompareType::NotEqual: comparison = getInterfaceText(varCmpTextIds.notEqual.c_str()); if (comparison.empty()) { comparison = "is not equal to"; } break; case CompareType::Greater: comparison = getInterfaceText(varCmpTextIds.greater.c_str()); if (comparison.empty()) { comparison = "is greater than"; } break; case CompareType::GreaterEqual: comparison = getInterfaceText(varCmpTextIds.greaterEqual.c_str()); if (comparison.empty()) { comparison = "is greater or equal to"; } break; case CompareType::Less: comparison = getInterfaceText(varCmpTextIds.less.c_str()); if (comparison.empty()) { comparison = "is less than"; } break; case CompareType::LessEqual: comparison = getInterfaceText(varCmpTextIds.lessEqual.c_str()); if (comparison.empty()) { comparison = "is less or equal to"; } break; } const auto str{fmt::format("{:s} {:s} {:s}", data1->name, comparison, data2->name)}; game::StringApi::get().initFromStringN(info, str.c_str(), str.length()); } using Variables = std::vector<const game::ScenarioVariable*>; struct CCondVarCmpInterf : public game::editor::CCondInterf { void* unknown; CMidCondVarCmp* condition; game::CMidgardID eventId; Variables variables; }; void __fastcall condVarCmpInterfDestructor(CCondVarCmpInterf* thisptr, int /*%edx*/, char flags) { Variables().swap(thisptr->variables); if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } static game::CInterfaceVftable::OnVisibilityChanged onVisibilityChanged{}; void __fastcall condVarCmpInterfOnVisibilityChanged(CCondVarCmpInterf* thisptr, int /*%edx*/, int a2, int a3) { using namespace game; if (onVisibilityChanged) { onVisibilityChanged(thisptr, a2, a3); } if (!a2) { return; } if (!thisptr->condition) { return; } auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); auto radioButton = dialogApi.findRadioButton(dialog, "RAD_OPERATOR"); if (radioButton) { CRadioButtonInterfApi::get().setCheckedButton(radioButton, (int)thisptr->condition->compareType); } const auto variableId1 = thisptr->condition->variableId1; const auto variableId2 = thisptr->condition->variableId2; const auto& variables = thisptr->variables; for (size_t i = 0; i < variables.size(); ++i) { const auto id = variables[i]->first; if (variableId1 == id) { auto listBox = dialogApi.findListBox(dialog, "TLBOX_VARIABLES1"); if (listBox) { CListBoxInterfApi::get().setSelectedIndex(listBox, i); } } if (variableId2 == id) { auto listBox = dialogApi.findListBox(dialog, "TLBOX_VARIABLES2"); if (listBox) { CListBoxInterfApi::get().setSelectedIndex(listBox, i); } } } } bool __fastcall condVarCmpInterfSetEventCondition(CCondVarCmpInterf* thisptr, int /*%edx*/, game::CMidEvCondition* eventCondition) { if (eventCondition->category.id == customEventConditions().variableCmp.category.id) { thisptr->condition = static_cast<CMidCondVarCmp*>(eventCondition); return true; } return false; } static game::editor::CCondInterfVftable condVarCmpInterfVftable{}; void __fastcall condVarCmpInterfCancelButtonHandler(CCondVarCmpInterf* thisptr, int /*%edx*/) { using namespace game; auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, false); } InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } void __fastcall condVarCmpInterfOkButtonHandler(CCondVarCmpInterf* thisptr, int /*%edx*/) { using namespace game; using namespace editor; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); auto listBox1 = dialogApi.findListBox(dialog, "TLBOX_VARIABLES1"); auto listBox2 = dialogApi.findListBox(dialog, "TLBOX_VARIABLES2"); if (!listBox1 || !listBox2) { return; } const int total = static_cast<int>(thisptr->variables.size()); const int index1 = CListBoxInterfApi::get().selectedIndex(listBox1); if (index1 < 0 || index1 >= total) { return; } const int index2 = CListBoxInterfApi::get().selectedIndex(listBox2); if (index2 < 0 || index2 >= total) { return; } auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, true); } auto objectMap = CCondInterfApi::get().getObjectMap(thisptr->unknown); { auto midEvent = (const CMidEvent*)objectMap->vftable ->findScenarioObjectById(objectMap, &thisptr->eventId); const int conditionsTotal = midEvent->conditions.end - midEvent->conditions.bgn; if (conditionsTotal >= 10) { // Could not create new condition showMessageBox(getInterfaceText("X100TA0631")); return; } } auto condition = static_cast<CMidCondVarCmp*>(createMidCondVarCmp()); auto radioButton = dialogApi.findRadioButton(dialog, "RAD_OPERATOR"); if (radioButton) { condition->compareType = static_cast<CompareType>(radioButton->data->selectedButton); } condition->variableId1 = thisptr->variables[index1]->first; condition->variableId2 = thisptr->variables[index2]->first; auto midEvent = (CMidEvent*)objectMap->vftable ->findScenarioObjectByIdForChange(objectMap, &thisptr->eventId); CMidEventApi::get().addCondition(midEvent, nullptr, condition); InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } void __fastcall condVarCmpInterfListBoxDisplayHandler(CCondVarCmpInterf* thisptr, int /*%edx*/, game::String* string, bool a3, int selectedIndex) { const auto total = static_cast<int>(thisptr->variables.size()); if (selectedIndex < 0 || selectedIndex >= total) { return; } const auto variable = thisptr->variables[selectedIndex]; game::StringApi::get().initFromStringN(string, variable->second.name, std::strlen(variable->second.name)); } game::editor::CCondInterf* createCondVarCmpInterf(game::ITask* task, void* a2, const game::CMidgardID* eventId) { using namespace game; using namespace editor; auto thisptr = (CCondVarCmpInterf*)Memory::get().allocate(sizeof(CCondVarCmpInterf)); // Set all values to zero, so std::vector variables in CCondVarCmpInterf can work properly std::memset(thisptr, 0, sizeof(CCondVarCmpInterf)); static const char dialogName[]{"DLG_COND_VAR_CMP"}; CCondInterfApi::get().constructor(thisptr, dialogName, task); static bool initialized{false}; if (!initialized) { initialized = true; onVisibilityChanged = thisptr->CInterface::vftable->onVisibilityChanged; std::memcpy(&condVarCmpInterfVftable, thisptr->CInterface::vftable, sizeof(CInterfaceVftable)); // Change methods that are specific for our custom class condVarCmpInterfVftable .destructor = (CInterfaceVftable::Destructor)&condVarCmpInterfDestructor; condVarCmpInterfVftable .onVisibilityChanged = (CInterfaceVftable:: OnVisibilityChanged)&condVarCmpInterfOnVisibilityChanged; condVarCmpInterfVftable .setEventCondition = (CCondInterfVftable:: SetEventCondition)&condVarCmpInterfSetEventCondition; } thisptr->CInterface::vftable = &condVarCmpInterfVftable; thisptr->eventId = *eventId; thisptr->unknown = a2; thisptr->condition = nullptr; { // Cache scenario variables auto objectMap = CCondInterfApi::get().getObjectMap(thisptr->unknown); Variables variables; auto scenVariables = getScenarioVariables(objectMap); if (scenVariables) { for (const auto& variable : scenVariables->variables) { variables.push_back(&variable); } } variables.swap(thisptr->variables); } auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); if (dialogApi.findButton(dialog, "BTN_OK")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condVarCmpInterfOkButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } if (dialogApi.findButton(dialog, "BTN_CANCEL")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condVarCmpInterfCancelButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } const auto& listApi = CListBoxInterfApi::get(); auto variablesList1 = dialogApi.findListBox(dialog, "TLBOX_VARIABLES1"); if (variablesList1) { using ListBoxCallback = CCondInterfApi::Api::ListBoxDisplayCallback; ListBoxCallback callback{}; SmartPointer functor{}; callback.callback = (ListBoxCallback::Callback)condVarCmpInterfListBoxDisplayHandler; CCondInterfApi::get().createListBoxDisplayFunctor(&functor, 0, thisptr, &callback); listApi.assignDisplayTextFunctor(dialog, "TLBOX_VARIABLES1", dialogName, &functor, false); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); listApi.setElementsTotal(variablesList1, thisptr->variables.size()); } auto variablesList2 = dialogApi.findListBox(dialog, "TLBOX_VARIABLES2"); if (variablesList2) { using ListBoxCallback = CCondInterfApi::Api::ListBoxDisplayCallback; ListBoxCallback callback{}; SmartPointer functor{}; callback.callback = (ListBoxCallback::Callback)condVarCmpInterfListBoxDisplayHandler; CCondInterfApi::get().createListBoxDisplayFunctor(&functor, 0, thisptr, &callback); listApi.assignDisplayTextFunctor(dialog, "TLBOX_VARIABLES2", dialogName, &functor, false); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); listApi.setElementsTotal(variablesList2, thisptr->variables.size()); } return thisptr; } struct CTestVarCmp : public game::ITestCondition { CMidCondVarCmp* condition; }; void __fastcall testVarCmpDestructor(CTestVarCmp* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall testVarCmpDoTest(const CTestVarCmp* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* eventId) { auto variables = getScenarioVariables(objectMap); if (!variables) { // Sanity check, this should never happen return false; } const auto& findById = game::CMidScenVariablesApi::get().findById; const auto* condition = thisptr->condition; const auto value1 = findById(variables, condition->variableId1)->value; const auto value2 = findById(variables, condition->variableId2)->value; switch (condition->compareType) { case CompareType::Equal: return value1 == value2; case CompareType::NotEqual: return value1 != value2; case CompareType::Greater: return value1 > value2; case CompareType::GreaterEqual: return value1 >= value2; case CompareType::Less: return value1 < value2; case CompareType::LessEqual: return value1 <= value2; } return false; } static game::ITestConditionVftable testVarCmpVftable{ (game::ITestConditionVftable::Destructor)testVarCmpDestructor, (game::ITestConditionVftable::Test)testVarCmpDoTest, }; game::ITestCondition* createTestVarCmp(game::CMidEvCondition* eventCondition) { auto thisptr = (CTestVarCmp*)game::Memory::get().allocate(sizeof(CTestVarCmp)); thisptr->condition = static_cast<CMidCondVarCmp*>(eventCondition); thisptr->vftable = &testVarCmpVftable; return thisptr; } } // namespace hooks
19,262
C++
.cpp
465
33.445161
98
0.664901
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,884
exchangeinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/exchangeinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "exchangeinterf.h" #include "version.h" #include <array> namespace game::CExchangeInterfApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x493296, (Api::CreateButtonFunctor)0x495468 }, // Russobit Api{ (Api::Constructor)0x493296, (Api::CreateButtonFunctor)0x495468 }, // Gog Api{ (Api::Constructor)0x492cee, (Api::CreateButtonFunctor)0x494ebb } }}; static std::array<Vftable, 4> vftables = {{ // Akella Vftable{ (CMidDataCache2::INotifyVftable*)0x6d70cc, (CInterfaceVftable*)0x6d703c, (ITaskManagerHolderVftable*)0x6d702c, (IMidDropManagerVftable*)0x6d6fec, }, // Russobit Vftable{ (CMidDataCache2::INotifyVftable*)0x6d70cc, (CInterfaceVftable*)0x6d703c, (ITaskManagerHolderVftable*)0x6d702c, (IMidDropManagerVftable*)0x6d6fec, }, // Gog Vftable{ (CMidDataCache2::INotifyVftable*)0x6d506c, (CInterfaceVftable*)0x6d4fdc, (ITaskManagerHolderVftable*)0x6d4fcc, (IMidDropManagerVftable*)0x6d4f8c, }, // Scenario Editor Vftable{}, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } Vftable& vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CExchangeInterfApi
2,253
C++
.cpp
75
25.626667
72
0.699678
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,885
batattacktransformself.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batattacktransformself.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batattacktransformself.h" #include "version.h" #include <array> namespace game::CBatAttackTransformSelfApi { // clang-format off static std::array<IBatAttackVftable*, 4> vftables = {{ // Akella (IBatAttackVftable*)0x6f54ac, // Russobit (IBatAttackVftable*)0x6f54ac, // Gog (IBatAttackVftable*)0x6f345c, // Scenario Editor (IBatAttackVftable*)nullptr, }}; // clang-format on IBatAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CBatAttackTransformSelfApi
1,375
C++
.cpp
39
32.769231
72
0.753569
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,886
autodialog.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/autodialog.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "autodialog.h" #include "version.h" #include <array> namespace game::AutoDialogApi { // clang-format off std::array<Api, 3> functions = {{ // Akella Api{ (Api::LoadScriptFile)0x50e227, (Api::LoadImage)0x5c9d20, }, // Russobit Api{ (Api::LoadScriptFile)0x50e227, (Api::LoadImage)0x5c9d20, }, // Gog Api{ (Api::LoadScriptFile)0x50d6eb, (Api::LoadImage)0x5c8cee, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::AutoDialogApi
1,407
C++
.cpp
46
27.195652
72
0.707965
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,887
citystackinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/citystackinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "citystackinterf.h" #include "version.h" #include <array> namespace game::CCityStackInterfApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x4b14cd, (Api::CreateButtonFunctor)0x4b4bca }, // Russobit Api{ (Api::Constructor)0x4b14cd, (Api::CreateButtonFunctor)0x4b4bca }, // Gog Api{ (Api::Constructor)0x4b0bcf, (Api::CreateButtonFunctor)0x4b4263 } }}; static std::array<Vftable, 4> vftables = {{ // Akella Vftable{ (CMidDataCache2::INotifyVftable*)0x6d96e4, (CMidCommandQueue2::INotifyCQVftable*)0x6d96d4, (IResetStackExtVftable*)0x6d96b4, (CInterfaceVftable*)0x6d9624, (ITaskManagerHolderVftable*)0x6d9614, (IMidDropManagerVftable*)0x6d95d4, }, // Russobit Vftable{ (CMidDataCache2::INotifyVftable*)0x6d96e4, (CMidCommandQueue2::INotifyCQVftable*)0x6d96d4, (IResetStackExtVftable*)0x6d96b4, (CInterfaceVftable*)0x6d9624, (ITaskManagerHolderVftable*)0x6d9614, (IMidDropManagerVftable*)0x6d95d4, }, // Gog Vftable{ (CMidDataCache2::INotifyVftable*)0x6d7684, (CMidCommandQueue2::INotifyCQVftable*)0x6d7674, (IResetStackExtVftable*)0x6d7654, (CInterfaceVftable*)0x6d75c4, (ITaskManagerHolderVftable*)0x6d75b4, (IMidDropManagerVftable*)0x6d7574, }, // Scenario Editor Vftable{}, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } Vftable& vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CCityStackInterfApi
2,550
C++
.cpp
81
26.728395
72
0.703493
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,888
fontshooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/fontshooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "fontshooks.h" #include "fonts.h" #include "mempool.h" #include <array> #include <filesystem> #include <memory> #include <string> #include <vector> namespace hooks { /** Wrapper is needed to safely use std::vector<FontListPtrPairWrapper> */ struct FontListPtrPairWrapper { FontListPtrPairWrapper() { game::FontListPtrPairApi::get().defaultCtor(&pair); } FontListPtrPairWrapper(const game::FontListPtrPair& listPtrPair) { game::FontListPtrPairApi::get().copyConstructor(&pair, &listPtrPair); } FontListPtrPairWrapper(const FontListPtrPairWrapper& other) { game::FontListPtrPairApi::get().copyConstructor(&pair, &other.pair); } FontListPtrPairWrapper& operator=(const FontListPtrPairWrapper& other) = delete; FontListPtrPairWrapper(FontListPtrPairWrapper&& other) noexcept { // Emulate move semantics by copying and deleting game::FontListPtrPairApi::get().copyConstructor(&pair, &other.pair); game::FontListPtrPairApi::get().destructor(&other.pair); } ~FontListPtrPairWrapper() { game::FontListPtrPairApi::get().destructor(&pair); } game::FontListPtrPair pair{}; }; struct CustomFontCacheData : public game::FontCacheData { CustomFontCacheData() { game::FontCacheApi::get().dataConstructor(this); } std::vector<FontListPtrPairWrapper> customFonts; }; bool __stdcall loadFontFilesHooked(const char* interfFolder) { using namespace game; const auto& cacheApi = FontCacheApi::get(); if (cacheApi.fontCache->data != nullptr) { // Font cache exists, fonts are already loaded return false; } const auto& fontApi = FontListPtrPairApi::get(); // Load default fonts FontListPtrPair small; fontApi.loadFromFile(&small, interfFolder, "small"); FontListPtrPair normal; fontApi.loadFromFile(&normal, interfFolder, "normal"); FontListPtrPair medium; fontApi.loadFromFile(&medium, interfFolder, "medium"); FontListPtrPair large; fontApi.loadFromFile(&large, interfFolder, "large"); FontListPtrPair vLarge; fontApi.loadFromFile(&vLarge, interfFolder, "vlarge"); FontListPtrPair medbold; fontApi.loadFromFile(&medbold, interfFolder, "medbold"); FontListPtrPair menu; fontApi.loadFromFile(&menu, interfFolder, "menu"); if (!fontApi.isLoaded(&small) || !fontApi.isLoaded(&normal) || !fontApi.isLoaded(&medium) || !fontApi.isLoaded(&large) || !fontApi.isLoaded(&vLarge) || !fontApi.isLoaded(&medbold) || !fontApi.isLoaded(&menu)) { fontApi.destructor(&menu); fontApi.destructor(&medbold); fontApi.destructor(&vLarge); fontApi.destructor(&large); fontApi.destructor(&medium); fontApi.destructor(&normal); fontApi.destructor(&small); return false; } FontCache* cache = (FontCache*)Memory::get().allocate(sizeof(FontCache)); auto* cacheData = (CustomFontCacheData*)Memory::get().allocate(sizeof(CustomFontCacheData)); new (cacheData) CustomFontCacheData(); cache->data = cacheData; // Set global pointer cacheApi.smartPtrSetData(cacheApi.fontCache, cache); // Setup default fonts fontApi.copyConstructor(&cache->data->small, &small); fontApi.copyConstructor(&cache->data->normal, &normal); fontApi.copyConstructor(&cache->data->medium, &medium); fontApi.copyConstructor(&cache->data->large, &large); fontApi.copyConstructor(&cache->data->veryLarge, &vLarge); fontApi.copyConstructor(&cache->data->mediumBold, &medbold); fontApi.copyConstructor(&cache->data->menu, &menu); // clang-format off static const std::array<const char*, 7u> defaultFonts{{ "small", "normal", "medium", "large", "vlarge", "medbold", "menu" }}; // clang-format on // Load custom fonts const std::filesystem::path directory{interfFolder}; for (const auto& entry : std::filesystem::directory_iterator(directory)) { if (!entry.is_regular_file()) { continue; } const std::filesystem::path& path = entry.path(); if (path.extension().string() != ".mft") { continue; } const std::string name = path.stem().string(); if (std::find(defaultFonts.cbegin(), defaultFonts.cend(), name) != defaultFonts.cend()) { // Do not load default fonts twice continue; } FontListPtrPairWrapper font; fontApi.loadFromFile(&font.pair, interfFolder, name.c_str()); if (fontApi.isLoaded(&font.pair)) { cacheData->customFonts.emplace_back(font); } } fontApi.destructor(&menu); fontApi.destructor(&medbold); fontApi.destructor(&vLarge); fontApi.destructor(&large); fontApi.destructor(&medium); fontApi.destructor(&normal); fontApi.destructor(&small); return true; } void __fastcall fontCacheDataDtorHooked(game::FontCacheData* thisptr, int /*%edx*/) { using namespace game; const auto& destructor = FontListPtrPairApi::get().destructor; CustomFontCacheData* data = static_cast<CustomFontCacheData*>(thisptr); data->customFonts.~vector(); destructor(&data->menu); destructor(&data->mediumBold); destructor(&data->veryLarge); destructor(&data->large); destructor(&data->medium); destructor(&data->normal); destructor(&data->small); } } // namespace hooks
6,340
C++
.cpp
169
31.994083
97
0.693085
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,889
itemtransferhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/itemtransferhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "itemtransferhooks.h" #include "button.h" #include "citystackinterf.h" #include "dialoginterf.h" #include "dynamiccast.h" #include "exchangeinterf.h" #include "fortification.h" #include "globaldata.h" #include "interfmanager.h" #include "itembase.h" #include "itemcategory.h" #include "itemutils.h" #include "log.h" #include "mempool.h" #include "midbag.h" #include "midgardmsgbox.h" #include "midgardobjectmap.h" #include "miditem.h" #include "midmsgboxbuttonhandlerstd.h" #include "midstack.h" #include "netmessages.h" #include "originalfunctions.h" #include "phasegame.h" #include "pickupdropinterf.h" #include "sitemerchantinterf.h" #include "textids.h" #include "utils.h" #include "visitors.h" #include <fmt/format.h> #include <optional> #include <vector> namespace hooks { using ItemFilter = std::function<bool(game::IMidgardObjectMap* objectMap, const game::CMidgardID* itemId)>; static const game::LItemCategory* getItemCategoryById(game::IMidgardObjectMap* objectMap, const game::CMidgardID* itemId) { auto globalItem = getGlobalItemById(objectMap, itemId); return globalItem ? globalItem->vftable->getCategory(globalItem) : nullptr; } static bool isPotion(game::IMidgardObjectMap* objectMap, const game::CMidgardID* itemId) { using namespace game; auto category = getItemCategoryById(objectMap, itemId); if (!category) { return false; } const auto& categories = ItemCategories::get(); const auto id = category->id; return categories.potionBoost->id == id || categories.potionHeal->id == id || categories.potionPermanent->id == id || categories.potionRevive->id == id; } static bool isSpell(game::IMidgardObjectMap* objectMap, const game::CMidgardID* itemId) { using namespace game; auto category = getItemCategoryById(objectMap, itemId); if (!category) { return false; } const auto& categories = ItemCategories::get(); const auto id = category->id; return categories.scroll->id == id || categories.wand->id == id; } static bool isValuable(game::IMidgardObjectMap* objectMap, const game::CMidgardID* itemId) { using namespace game; auto category = getItemCategoryById(objectMap, itemId); if (!category) { return false; } const auto& categories = ItemCategories::get(); return categories.valuable->id == category->id; } /** Transfers items from src object to dst. */ static void transferItems(const std::vector<game::CMidgardID>& items, game::CPhaseGame* phaseGame, const game::CMidgardID* dstObjectId, const char* dstObjectName, const game::CMidgardID* srcObjectId, const char* srcObjectName) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); const auto& exchangeItem = VisitorApi::get().exchangeItem; const auto& sendExchangeItemMsg = NetMessagesApi::get().sendStackExchangeItemMsg; for (const auto& item : items) { sendExchangeItemMsg(phaseGame, srcObjectId, dstObjectId, &item, 1); if (!exchangeItem(srcObjectId, dstObjectId, &item, objectMap, 1)) { logError("mssProxyError.log", fmt::format("Failed to transfer item {:s} from {:s} {:s} to {:s} {:s}", idToString(&item), srcObjectName, idToString(srcObjectId), dstObjectName, idToString(dstObjectId))); } } } /** Transfers city items to visiting stack. */ static void transferCityToStack(game::CPhaseGame* phaseGame, const game::CMidgardID* cityId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto obj = objectMap->vftable->findScenarioObjectById(objectMap, cityId); if (!obj) { logError("mssProxyError.log", fmt::format("Could not find city {:s}", idToString(cityId))); return; } auto fortification = static_cast<CFortification*>(obj); if (fortification->stackId == emptyId) { return; } auto& inventory = fortification->inventory; std::vector<CMidgardID> items; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); for (int i = 0; i < itemsTotal; ++i) { auto item = inventory.vftable->getItem(&inventory, i); if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { items.push_back(*item); } } transferItems(items, phaseGame, &fortification->stackId, "stack", cityId, "city"); } void __fastcall cityInterfTransferAllToStack(game::CCityStackInterf* thisptr, int /*%edx*/) { transferCityToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId); } void __fastcall cityInterfTransferPotionsToStack(game::CCityStackInterf* thisptr, int /*%edx*/) { transferCityToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId, isPotion); } void __fastcall cityInterfTransferSpellsToStack(game::CCityStackInterf* thisptr, int /*%edx*/) { transferCityToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId, isSpell); } void __fastcall cityInterfTransferValuablesToStack(game::CCityStackInterf* thisptr, int /*%edx*/) { transferCityToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId, isValuable); } static bool isItemEquipped(const game::IdVector& equippedItems, const game::CMidgardID* itemId) { for (const game::CMidgardID* item = equippedItems.bgn; item != equippedItems.end; item++) { if (*item == *itemId) { return true; } } return false; } /** Transfers visiting stack items to city. */ static void transferStackToCity(game::CPhaseGame* phaseGame, const game::CMidgardID* cityId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto obj = objectMap->vftable->findScenarioObjectById(objectMap, cityId); if (!obj) { logError("mssProxyError.log", fmt::format("Could not find city {:s}", idToString(cityId))); return; } auto fortification = static_cast<CFortification*>(obj); if (fortification->stackId == emptyId) { return; } auto stackObj = objectMap->vftable->findScenarioObjectById(objectMap, &fortification->stackId); if (!stackObj) { logError("mssProxyError.log", fmt::format("Could not find stack {:s}", idToString(&fortification->stackId))); return; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto stack = (CMidStack*)dynamicCast(stackObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); if (!stack) { logError("mssProxyError.log", fmt::format("Failed to cast scenario oject {:s} to stack", idToString(&fortification->stackId))); return; } auto& inventory = stack->inventory; std::vector<CMidgardID> items; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); for (int i = 0; i < itemsTotal; i++) { auto item = inventory.vftable->getItem(&inventory, i); if (isItemEquipped(stack->leaderEquippedItems, item)) { continue; } if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { items.push_back(*item); } } transferItems(items, phaseGame, cityId, "city", &fortification->stackId, "stack"); } void __fastcall cityInterfTransferAllToCity(game::CCityStackInterf* thisptr, int /*%edx*/) { transferStackToCity(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId); } void __fastcall cityInterfTransferPotionsToCity(game::CCityStackInterf* thisptr, int /*%edx*/) { transferStackToCity(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId, isPotion); } void __fastcall cityInterfTransferSpellsToCity(game::CCityStackInterf* thisptr, int /*%edx*/) { transferStackToCity(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId, isSpell); } void __fastcall cityInterfTransferValuablesToCity(game::CCityStackInterf* thisptr, int /*%edx*/) { transferStackToCity(thisptr->dragDropInterf.phaseGame, &thisptr->data->fortificationId, isValuable); } game::CCityStackInterf* __fastcall cityStackInterfCtorHooked(game::CCityStackInterf* thisptr, int /*%edx*/, void* taskOpenInterf, game::CPhaseGame* phaseGame, game::CMidgardID* cityId) { using namespace game; getOriginalFunctions().cityStackInterfCtor(thisptr, taskOpenInterf, phaseGame, cityId); const auto& button = CButtonInterfApi::get(); const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; const char dialogName[] = "DLG_CITY_STACK"; auto dialog = CDragAndDropInterfApi::get().getDialog(&thisptr->dragDropInterf); using ButtonCallback = CCityStackInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor; const auto& dialogApi = CDialogInterfApi::get(); const auto& cityStackInterf = CCityStackInterfApi::get(); if (dialogApi.findControl(dialog, "BTN_TRANSF_L_ALL")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferAllToStack; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_ALL")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferAllToCity; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_POTIONS")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferPotionsToStack; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_POTIONS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_POTIONS")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferPotionsToCity; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_POTIONS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_SPELLS")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferSpellsToStack; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_SPELLS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_SPELLS")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferSpellsToCity; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_SPELLS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_VALUABLES")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferValuablesToStack; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_VALUABLES")) { callback.callback = (ButtonCallback::Callback)cityInterfTransferValuablesToCity; cityStackInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } return thisptr; } /** Transfers items from stack with srcStackId to stack with dstStackId. */ static void transferStackToStack(game::CPhaseGame* phaseGame, const game::CMidgardID* dstStackId, const game::CMidgardID* srcStackId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto srcObj = objectMap->vftable->findScenarioObjectById(objectMap, srcStackId); if (!srcObj) { logError("mssProxyError.log", fmt::format("Could not find stack {:s}", idToString(srcStackId))); return; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto srcStack = (CMidStack*)dynamicCast(srcObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); if (!srcStack) { logError("mssProxyError.log", fmt::format("Failed to cast scenario oject {:s} to stack", idToString(srcStackId))); return; } auto& inventory = srcStack->inventory; std::vector<CMidgardID> items; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); for (int i = 0; i < itemsTotal; i++) { auto item = inventory.vftable->getItem(&inventory, i); if (isItemEquipped(srcStack->leaderEquippedItems, item)) { continue; } if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { items.push_back(*item); } } transferItems(items, phaseGame, dstStackId, "stack", srcStackId, "stack"); } void __fastcall exchangeTransferAllToLeftStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackLeftSideId, &thisptr->data->stackRightSideId); } void __fastcall exchangeTransferPotionsToLeftStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackLeftSideId, &thisptr->data->stackRightSideId, isPotion); } void __fastcall exchangeTransferSpellsToLeftStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackLeftSideId, &thisptr->data->stackRightSideId, isSpell); } void __fastcall exchangeTransferValuablesToLeftStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackLeftSideId, &thisptr->data->stackRightSideId, isValuable); } void __fastcall exchangeTransferAllToRightStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackRightSideId, &thisptr->data->stackLeftSideId); } void __fastcall exchangeTransferPotionsToRightStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackRightSideId, &thisptr->data->stackLeftSideId, isPotion); } void __fastcall exchangeTransferSpellsToRightStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackRightSideId, &thisptr->data->stackLeftSideId, isSpell); } void __fastcall exchangeTransferValuablesToRightStack(game::CExchangeInterf* thisptr, int /*%edx*/) { transferStackToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackRightSideId, &thisptr->data->stackLeftSideId, isValuable); } game::CExchangeInterf* __fastcall exchangeInterfCtorHooked(game::CExchangeInterf* thisptr, int /*%edx*/, void* taskOpenInterf, game::CPhaseGame* phaseGame, game::CMidgardID* stackLeftSide, game::CMidgardID* stackRightSide) { using namespace game; getOriginalFunctions().exchangeInterfCtor(thisptr, taskOpenInterf, phaseGame, stackLeftSide, stackRightSide); const auto& button = CButtonInterfApi::get(); const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; const char dialogName[] = "DLG_EXCHANGE"; auto dialog = CDragAndDropInterfApi::get().getDialog(&thisptr->dragDropInterf); using ButtonCallback = CExchangeInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor; const auto& dialogApi = CDialogInterfApi::get(); const auto& exchangeInterf = CExchangeInterfApi::get(); if (dialogApi.findControl(dialog, "BTN_TRANSF_L_ALL")) { callback.callback = (ButtonCallback::Callback)exchangeTransferAllToLeftStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_ALL")) { callback.callback = (ButtonCallback::Callback)exchangeTransferAllToRightStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_POTIONS")) { callback.callback = (ButtonCallback::Callback)exchangeTransferPotionsToLeftStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_POTIONS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_POTIONS")) { callback.callback = (ButtonCallback::Callback)exchangeTransferPotionsToRightStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_POTIONS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_SPELLS")) { callback.callback = (ButtonCallback::Callback)exchangeTransferSpellsToLeftStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_SPELLS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_SPELLS")) { callback.callback = (ButtonCallback::Callback)exchangeTransferSpellsToRightStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_SPELLS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_VALUABLES")) { callback.callback = (ButtonCallback::Callback)exchangeTransferValuablesToLeftStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_VALUABLES")) { callback.callback = (ButtonCallback::Callback)exchangeTransferValuablesToRightStack; exchangeInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } return thisptr; } /** Transfers bag items to stack. */ static void transferBagToStack(game::CPhaseGame* phaseGame, const game::CMidgardID* stackId, const game::CMidgardID* bagId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto bagObj = objectMap->vftable->findScenarioObjectById(objectMap, bagId); if (!bagObj) { logError("mssProxyError.log", fmt::format("Could not find bag {:s}", idToString(bagId))); return; } auto bag = static_cast<CMidBag*>(bagObj); auto& inventory = bag->inventory; std::vector<CMidgardID> items; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); for (int i = 0; i < itemsTotal; i++) { auto item = inventory.vftable->getItem(&inventory, i); if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { items.push_back(*item); } } transferItems(items, phaseGame, stackId, "stack", bagId, "bag"); } void __fastcall pickupTransferAllToStack(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferBagToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId); } void __fastcall pickupTransferPotionsToStack(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferBagToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId, isPotion); } void __fastcall pickupTransferSpellsToStack(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferBagToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId, isSpell); } void __fastcall pickupTransferValuablesToStack(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferBagToStack(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId, isValuable); } /** Transfers stack items to bag. */ static void transferStackToBag(game::CPhaseGame* phaseGame, const game::CMidgardID* stackId, const game::CMidgardID* bagId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto stackObj = objectMap->vftable->findScenarioObjectById(objectMap, stackId); if (!stackObj) { logError("mssProxyError.log", fmt::format("Could not find stack {:s}", idToString(stackId))); return; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto stack = (CMidStack*)dynamicCast(stackObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); if (!stack) { logError("mssProxyError.log", fmt::format("Failed to cast scenario oject {:s} to stack", idToString(stackId))); return; } auto& inventory = stack->inventory; std::vector<CMidgardID> items; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); for (int i = 0; i < itemsTotal; i++) { auto item = inventory.vftable->getItem(&inventory, i); if (isItemEquipped(stack->leaderEquippedItems, item)) { continue; } if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { items.push_back(*item); } } transferItems(items, phaseGame, bagId, "bag", stackId, "stack"); } void __fastcall pickupTransferAllToBag(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferStackToBag(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId); } void __fastcall pickupTransferPotionsToBag(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferStackToBag(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId, isPotion); } void __fastcall pickupTransferSpellsToBag(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferStackToBag(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId, isSpell); } void __fastcall pickupTransferValuablesToBag(game::CPickUpDropInterf* thisptr, int /*%edx*/) { transferStackToBag(thisptr->dragDropInterf.phaseGame, &thisptr->data->stackId, &thisptr->data->bagId, isValuable); } game::CPickUpDropInterf* __fastcall pickupDropInterfCtorHooked(game::CPickUpDropInterf* thisptr, int /*%edx*/, void* taskOpenInterf, game::CPhaseGame* phaseGame, game::CMidgardID* stackId, game::CMidgardID* bagId) { using namespace game; getOriginalFunctions().pickupDropInterfCtor(thisptr, taskOpenInterf, phaseGame, stackId, bagId); const auto& button = CButtonInterfApi::get(); const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; const char dialogName[] = "DLG_PICKUP_DROP"; auto dialog = CDragAndDropInterfApi::get().getDialog(&thisptr->dragDropInterf); using ButtonCallback = CPickUpDropInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor; const auto& dialogApi = CDialogInterfApi::get(); const auto& pickupInterf = CPickUpDropInterfApi::get(); if (dialogApi.findControl(dialog, "BTN_TRANSF_L_ALL")) { callback.callback = (ButtonCallback::Callback)pickupTransferAllToStack; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_ALL")) { callback.callback = (ButtonCallback::Callback)pickupTransferAllToBag; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_POTIONS")) { callback.callback = (ButtonCallback::Callback)pickupTransferPotionsToStack; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_POTIONS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_POTIONS")) { callback.callback = (ButtonCallback::Callback)pickupTransferPotionsToBag; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_POTIONS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_SPELLS")) { callback.callback = (ButtonCallback::Callback)pickupTransferSpellsToStack; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_SPELLS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_SPELLS")) { callback.callback = (ButtonCallback::Callback)pickupTransferSpellsToBag; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_SPELLS", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_L_VALUABLES")) { callback.callback = (ButtonCallback::Callback)pickupTransferValuablesToStack; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_L_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_TRANSF_R_VALUABLES")) { callback.callback = (ButtonCallback::Callback)pickupTransferValuablesToBag; pickupInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_TRANSF_R_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } return thisptr; } struct SellItemsMsgBoxHandler : public game::CMidMsgBoxButtonHandler { game::CSiteMerchantInterf* merchantInterf; }; void __fastcall sellItemsMsgBoxHandlerDtor(SellItemsMsgBoxHandler* thisptr, int /*%edx*/, char flags) { if (flags & 1) { // We can skip a call to CMidMsgBoxButtonHandler destructor // since we know it does not have any members and does not free anything except its memory. // Free our memory here game::Memory::get().freeNonZero(thisptr); } } static void sellItemsToMerchant(game::CPhaseGame* phaseGame, const game::CMidgardID* merchantId, const game::CMidgardID* stackId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto stackObj = objectMap->vftable->findScenarioObjectById(objectMap, stackId); if (!stackObj) { logError("mssProxyError.log", fmt::format("Could not find stack {:s}", idToString(stackId))); return; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto stack = (CMidStack*)dynamicCast(stackObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); if (!stack) { logError("mssProxyError.log", fmt::format("Failed to cast scenario oject {:s} to stack", idToString(stackId))); return; } auto& inventory = stack->inventory; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); std::vector<CMidgardID> itemsToSell; for (int i = 0; i < itemsTotal; ++i) { auto item = inventory.vftable->getItem(&inventory, i); if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { itemsToSell.push_back(*item); } } const auto& sendSellItemMsg = NetMessagesApi::get().sendSiteSellItemMsg; for (const auto& item : itemsToSell) { sendSellItemMsg(phaseGame, merchantId, stackId, &item); } } void __fastcall sellValuablesMsgBoxHandlerFunction(SellItemsMsgBoxHandler* thisptr, int /*%edx*/, game::CMidgardMsgBox* msgBox, bool okPressed) { using namespace game; auto merchant = thisptr->merchantInterf; auto phaseGame = merchant->dragDropInterf.phaseGame; if (okPressed) { auto data = merchant->data; sellItemsToMerchant(phaseGame, &data->merchantId, &data->stackId, isValuable); } auto manager = phaseGame->data->interfManager.data; auto vftable = manager->CInterfManagerImpl::CInterfManager::vftable; vftable->hideInterface(manager, msgBox); if (msgBox) { msgBox->vftable->destructor(msgBox, 1); } } game::CMidMsgBoxButtonHandlerVftable sellValuablesMsgBoxHandlerVftable{ (game::CMidMsgBoxButtonHandlerVftable::Destructor)sellItemsMsgBoxHandlerDtor, (game::CMidMsgBoxButtonHandlerVftable::Handler)sellValuablesMsgBoxHandlerFunction}; void __fastcall sellAllItemsMsgBoxHandlerFunction(SellItemsMsgBoxHandler* thisptr, int /*%edx*/, game::CMidgardMsgBox* msgBox, bool okPressed) { using namespace game; auto merchant = thisptr->merchantInterf; auto phaseGame = merchant->dragDropInterf.phaseGame; if (okPressed) { auto data = merchant->data; sellItemsToMerchant(phaseGame, &data->merchantId, &data->stackId); } auto manager = phaseGame->data->interfManager.data; auto vftable = manager->CInterfManagerImpl::CInterfManager::vftable; vftable->hideInterface(manager, msgBox); if (msgBox) { msgBox->vftable->destructor(msgBox, 1); } } game::CMidMsgBoxButtonHandlerVftable sellAllItemsMsgBoxHandlerVftable{ (game::CMidMsgBoxButtonHandlerVftable::Destructor)sellItemsMsgBoxHandlerDtor, (game::CMidMsgBoxButtonHandlerVftable::Handler)sellAllItemsMsgBoxHandlerFunction}; static std::string bankToPriceMessage(const game::Bank& bank) { using namespace game; std::string priceText; if (bank.gold) { auto text = getInterfaceText("X005TA0055"); replace(text, "%QTY%", fmt::format("{:d}", bank.gold)); priceText.append(text + '\n'); } if (bank.runicMana) { auto text = getInterfaceText("X005TA0056"); replace(text, "%QTY%", fmt::format("{:d}", bank.runicMana)); priceText.append(text + '\n'); } if (bank.deathMana) { auto text = getInterfaceText("X005TA0057"); replace(text, "%QTY%", fmt::format("{:d}", bank.deathMana)); priceText.append(text + '\n'); } if (bank.lifeMana) { auto text = getInterfaceText("X005TA0058"); replace(text, "%QTY%", fmt::format("{:d}", bank.lifeMana)); priceText.append(text + '\n'); } if (bank.infernalMana) { auto text = getInterfaceText("X005TA0059"); replace(text, "%QTY%", fmt::format("{:d}", bank.infernalMana)); priceText.append(text + '\n'); } if (bank.groveMana) { auto text = getInterfaceText("X160TA0001"); replace(text, "%QTY%", fmt::format("{:d}", bank.groveMana)); priceText.append(text + '\n'); } return priceText; } static game::Bank computeItemsSellPrice(game::IMidgardObjectMap* objectMap, const game::CMidgardID* stackId, std::optional<ItemFilter> itemFilter = std::nullopt) { using namespace game; auto stackObj = objectMap->vftable->findScenarioObjectById(objectMap, stackId); if (!stackObj) { logError("mssProxyError.log", fmt::format("Could not find stack {:s}", idToString(stackId))); return {}; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto stack = (CMidStack*)dynamicCast(stackObj, 0, rtti.IMidScenarioObjectType, rtti.CMidStackType, 0); if (!stack) { logError("mssProxyError.log", fmt::format("Failed to cast scenario oject {:s} to stack", idToString(stackId))); return {}; } auto& inventory = stack->inventory; const int itemsTotal = inventory.vftable->getItemsCount(&inventory); auto getSellingPrice = CMidItemApi::get().getSellingPrice; auto bankAdd = BankApi::get().add; Bank sellPrice{}; for (int i = 0; i < itemsTotal; ++i) { auto item = inventory.vftable->getItem(&inventory, i); if (!itemFilter || (itemFilter && (*itemFilter)(objectMap, item))) { Bank price{}; getSellingPrice(&price, objectMap, item); bankAdd(&sellPrice, &price); } } return sellPrice; } void __fastcall merchantSellValuables(game::CSiteMerchantInterf* thisptr, int /*%edx*/) { using namespace game; auto phaseGame = thisptr->dragDropInterf.phaseGame; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto stackId = &thisptr->data->stackId; const auto sellPrice = computeItemsSellPrice(objectMap, stackId, isValuable); if (BankApi::get().isZero(&sellPrice)) { // No items to sell return; } const auto priceText = bankToPriceMessage(sellPrice); auto message = getInterfaceText(textIds().interf.sellAllValuables.c_str()); if (!message.empty()) { replace(message, "%PRICE%", priceText); } else { // Fallback in case of interface text could not be found message = fmt::format("Do you want to sell all valuables? Revenue will be:\n{:s}", priceText); } auto memAlloc = Memory::get().allocate; auto handler = (SellItemsMsgBoxHandler*)memAlloc(sizeof(SellItemsMsgBoxHandler)); handler->vftable = &sellValuablesMsgBoxHandlerVftable; handler->merchantInterf = thisptr; hooks::showMessageBox(message, handler, true); } void __fastcall merchantSellAll(game::CSiteMerchantInterf* thisptr, int /*%edx*/) { using namespace game; auto phaseGame = thisptr->dragDropInterf.phaseGame; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto stackId = &thisptr->data->stackId; const auto sellPrice = computeItemsSellPrice(objectMap, stackId); if (BankApi::get().isZero(&sellPrice)) { // No items to sell return; } const auto priceText = bankToPriceMessage(sellPrice); auto message = getInterfaceText(textIds().interf.sellAllItems.c_str()); if (!message.empty()) { replace(message, "%PRICE%", priceText); } else { // Fallback in case of interface text could not be found message = fmt::format("Do you want to sell all items? Revenue will be:\n{:s}", priceText); } auto memAlloc = Memory::get().allocate; auto handler = (SellItemsMsgBoxHandler*)memAlloc(sizeof(SellItemsMsgBoxHandler)); handler->vftable = &sellAllItemsMsgBoxHandlerVftable; handler->merchantInterf = thisptr; hooks::showMessageBox(message, handler, true); } game::CSiteMerchantInterf* __fastcall siteMerchantInterfCtorHooked( game::CSiteMerchantInterf* thisptr, int /*%edx*/, void* taskOpenInterf, game::CPhaseGame* phaseGame, game::CMidgardID* stackId, game::CMidgardID* merchantId) { using namespace game; getOriginalFunctions().siteMerchantInterfCtor(thisptr, taskOpenInterf, phaseGame, stackId, merchantId); const auto& button = CButtonInterfApi::get(); const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; const char dialogName[] = "DLG_MERCHANT"; auto dialog = CDragAndDropInterfApi::get().getDialog(&thisptr->dragDropInterf); using ButtonCallback = CSiteMerchantInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor; const auto& dialogApi = CDialogInterfApi::get(); const auto& merchantInterf = CSiteMerchantInterfApi::get(); if (dialogApi.findControl(dialog, "BTN_SELL_ALL_VALUABLES")) { callback.callback = (ButtonCallback::Callback)merchantSellValuables; merchantInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_SELL_ALL_VALUABLES", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } if (dialogApi.findControl(dialog, "BTN_SELL_ALL")) { callback.callback = (ButtonCallback::Callback)merchantSellAll; merchantInterf.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, "BTN_SELL_ALL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); } return thisptr; } } // namespace hooks
41,459
C++
.cpp
867
39.130334
100
0.664126
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,890
unitcat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitcat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitcat.h" #include "version.h" #include <array> namespace game::UnitCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LUnitCategory*)0x83a1a0, (LUnitCategory*)0x83a1e0, (LUnitCategory*)0x83a1d0, (LUnitCategory*)0x83a1b0, (LUnitCategory*)0x83a1c0, (LUnitCategory*)0x83a1f0, }, // Russobit Categories{ (LUnitCategory*)0x83a1a0, (LUnitCategory*)0x83a1e0, (LUnitCategory*)0x83a1d0, (LUnitCategory*)0x83a1b0, (LUnitCategory*)0x83a1c0, (LUnitCategory*)0x83a1f0, }, // Gog Categories{ (LUnitCategory*)0x838150, (LUnitCategory*)0x838190, (LUnitCategory*)0x838180, (LUnitCategory*)0x838160, (LUnitCategory*)0x838170, (LUnitCategory*)0x8381a0, }, // Scenario Editor Categories{ (LUnitCategory*)0x666070, (LUnitCategory*)0x6660b0, (LUnitCategory*)0x6660a0, (LUnitCategory*)0x666080, (LUnitCategory*)0x666090, (LUnitCategory*)0x6660c0, } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6ea5cc, // Russobit (const void*)0x6ea5cc, // Gog (const void*)0x6e856c, // Scenario Editor (const void*)0x5ddfac, }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::UnitCategories
2,406
C++
.cpp
81
24.950617
72
0.683779
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,891
editor.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/editor.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "editor.h" namespace game { // clang-format off EditorFunctions editorFunctions{ (RadioButtonIndexToPlayerId)0x429f1b, (FindPlayerByRaceCategory)0x4e1bf5, (CanPlace)0x511142, (CanPlace)0x512376, (CountStacksOnMap)0x40b631, (GetSubRaceByRace)0x50b1a6, (IsRaceCategoryPlayable)0x419193, (ChangeCapitalTerrain)0x50afb4, (GetObjectNamePos)0x45797c, }; // clang-format on } // namespace game
1,248
C++
.cpp
34
34.029412
72
0.767769
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,892
midgard.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midgard.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midgard.h" #include "version.h" #include <array> namespace game::CMidgardApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Instance)0x401d35, (Api::SetClientsNetProxy)0x4030c5, (Api::SetNetService)0x403089, (Api::CreateNetClient)0x403200, (Api::SendNetMsgToServer)0x403b71, }, // Russobit Api{ (Api::Instance)0x401d35, (Api::SetClientsNetProxy)0x4030c5, (Api::SetNetService)0x403089, (Api::CreateNetClient)0x403200, (Api::SendNetMsgToServer)0x403b71, }, // Gog Api{ (Api::Instance)0x401a7b, (Api::SetClientsNetProxy)0x402e0b, (Api::SetNetService)0x402dcf, (Api::CreateNetClient)0x402f46, (Api::SendNetMsgToServer)0x4038b7, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidgardApi
1,780
C++
.cpp
55
28.054545
72
0.700581
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,893
unitpositionmap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitpositionmap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitpositionmap.h" #include "version.h" #include <array> namespace game::UnitPositionMapApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x640100, (Api::Destructor)0x6401a0, (Api::CopyConstructor)0x640180, (Api::CopyAssignment)0x6401c0, (Api::FindByPosition)0x634eaf, (Api::HasNegativePosition)0x631bfb, }, // Russobit Api{ (Api::Constructor)0x640100, (Api::Destructor)0x6401a0, (Api::CopyConstructor)0x640180, (Api::CopyAssignment)0x6401c0, (Api::FindByPosition)0x634eaf, (Api::HasNegativePosition)0x631bfb, }, // Gog Api{ (Api::Constructor)0x63eb00, (Api::Destructor)0x63eba0, (Api::CopyConstructor)0x63eb80, (Api::CopyAssignment)0x63ebc0, (Api::FindByPosition)0x6338ef, (Api::HasNegativePosition)0x63063b, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::UnitPositionMapApi
1,911
C++
.cpp
58
28.396552
72
0.700216
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,894
spinbuttoninterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/spinbuttoninterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "spinbuttoninterf.h" #include "version.h" #include <array> namespace game::CSpinButtonInterfApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetValues)0x53a661, (Api::SetOptions)0x53a5c1, (Api::SetSelectedOption)0x53a59c, (Api::AssignFunctor)0x5c9bf6, }, // Russobit Api{ (Api::SetValues)0x53a661, (Api::SetOptions)0x53a5c1, (Api::SetSelectedOption)0x53a59c, (Api::AssignFunctor)0x5c9bf6, }, // Gog Api{ (Api::SetValues)0x539d02, (Api::SetOptions)0x539c62, (Api::SetSelectedOption)0x539c3d, (Api::AssignFunctor)0x5c8bc4, }, // Scenario Editor Api{ (Api::SetValues)0, (Api::SetOptions)0, (Api::SetSelectedOption)0, (Api::AssignFunctor)0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CSpinButtonInterfApi
1,823
C++
.cpp
59
26.474576
72
0.689028
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,895
midmsgboxbuttonhandlerstd.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midmsgboxbuttonhandlerstd.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midmsgboxbuttonhandlerstd.h" #include "version.h" #include <array> namespace game::CMidMsgBoxButtonHandlerStdApi { // clang-format off static std::array<CMidMsgBoxButtonHandlerVftable*, 4> vftables = {{ // Akella (CMidMsgBoxButtonHandlerVftable*)0x6db61c, // Russobit (CMidMsgBoxButtonHandlerVftable*)0x6db61c, // Gog (CMidMsgBoxButtonHandlerVftable*)0x6d95bc, // Scenario Editor (CMidMsgBoxButtonHandlerVftable*)0x5ca7cc, }}; // clang-format on CMidMsgBoxButtonHandlerVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidMsgBoxButtonHandlerStdApi
1,463
C++
.cpp
39
35.025641
72
0.768851
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,896
pointset.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/pointset.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pointset.h" #include "version.h" #include <array> namespace game::PointSetApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)nullptr, (Api::Destructor)nullptr, (Api::Add)nullptr, }, // Russobit Api{ (Api::Constructor)nullptr, (Api::Destructor)nullptr, (Api::Add)nullptr, }, // Gog Api{ (Api::Constructor)nullptr, (Api::Destructor)nullptr, (Api::Add)nullptr, }, // Scenario Editor Api{ (Api::Constructor)0x405ed2, (Api::Destructor)0x405f31, (Api::Add)0x405e6f, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::PointSetApi
1,616
C++
.cpp
55
25.290909
72
0.681877
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,897
surfacedecompressdata.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/surfacedecompressdata.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "surfacedecompressdata.h" #include "version.h" #include <array> namespace game::SurfaceDecompressDataApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::ConvertColor)0x5619e2, (Api::FillArea)0x5616be, (Api::SetColor)0x561694, (Api::DrawTextString)0x534d0b, }, // Russobit Api{ (Api::ConvertColor)0x5619e2, (Api::FillArea)0x5616be, (Api::SetColor)0x561694, (Api::DrawTextString)0x534d0b, }, // Gog Api{ (Api::ConvertColor)0x56117f, (Api::FillArea)0x560e5b, (Api::SetColor)0x560e31, (Api::DrawTextString)0x5342e9, }, // Scenario Editor Api{ (Api::ConvertColor)0x584553, (Api::FillArea)0x58422f, (Api::SetColor)0x584205, (Api::DrawTextString)0x48ea22, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::SurfaceDecompressDataApi
1,836
C++
.cpp
59
26.694915
72
0.691309
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,898
netsingleplayer.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netsingleplayer.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netsingleplayer.h" #include "version.h" #include <array> namespace game::CNetSinglePlayerApi { // clang-format off static std::array<IMqNetPlayerVftable*, 4> vftables = {{ // Akella (IMqNetPlayerVftable*)0x6e6bf4, // Russobit (IMqNetPlayerVftable*)0x6e6bf4, // Gog (IMqNetPlayerVftable*)0x6e4b94, // Scenario Editor (IMqNetPlayerVftable*)nullptr, }}; // clang-format on IMqNetPlayerVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CNetSinglePlayerApi
1,367
C++
.cpp
39
32.564103
72
0.752079
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,899
hooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/hooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "hooks.h" #include "aigiveitemsaction.h" #include "aigiveitemsactionhooks.h" #include "attackimpl.h" #include "attackreachcat.h" #include "attackutils.h" #include "autodialog.h" #include "batattackbestowwards.h" #include "batattackdoppelganger.h" #include "batattackdrain.h" #include "batattackdrainlevel.h" #include "batattackdrainoverflow.h" #include "batattackgiveattack.h" #include "batattackgroupupgrade.h" #include "batattackshatter.h" #include "batattacksummon.h" #include "batattacktransformother.h" #include "batattacktransformself.h" #include "batattackuntransformeffect.h" #include "batbigface.h" #include "battleattackinfo.h" #include "battlemsgdatahooks.h" #include "battleviewerinterf.h" #include "battleviewerinterfhooks.h" #include "bestowwardshooks.h" #include "buildingbranch.h" #include "buildingtype.h" #include "button.h" #include "citystackinterf.h" #include "citystackinterfhooks.h" #include "cmdbattlechooseactionmsg.h" #include "cmdbattleendmsg.h" #include "cmdbattleresultmsg.h" #include "cmdbattlestartmsg.h" #include "commandmsghooks.h" #include "condinterf.h" #include "condinterfhooks.h" #include "customattackhooks.h" #include "customattacks.h" #include "customattackutils.h" #include "custombuildingcategories.h" #include "d2string.h" #include "dbfaccess.h" #include "dbtable.h" #include "dialoginterf.h" #include "difficultylevel.h" #include "displayhandlershooks.h" #include "doppelgangerhooks.h" #include "drainattackhooks.h" #include "drainlevelhooks.h" #include "dynamiccast.h" #include "dynupgrade.h" #include "editboxinterf.h" #include "editor.h" #include "effectinterfhooks.h" #include "effectresulthooks.h" #include "enclayoutcityhooks.h" #include "enclayoutruinhooks.h" #include "enclayoutstack.h" #include "enclayoutstackhooks.h" #include "enclayoutunithooks.h" #include "encparambase.h" #include "encparambasehooks.h" #include "eventconditioncathooks.h" #include "eventeffectcathooks.h" #include "exchangeinterf.h" #include "exchangeinterfhooks.h" #include "fonts.h" #include "fontshooks.h" #include "fortcategory.h" #include "fortification.h" #include "gameutils.h" #include "globaldata.h" #include "groupupgradehooks.h" #include "idlist.h" #include "interfmanager.h" #include "interftexthooks.h" #include "intvector.h" #include "isoenginegroundhooks.h" #include "itembase.h" #include "itemcategory.h" #include "itemexpotionboost.h" #include "itemtransferhooks.h" #include "itemutils.h" #include "leaderabilitycat.h" #include "listbox.h" #include "log.h" #include "lordtype.h" #include "mainview2.h" #include "mainview2hooks.h" #include "managestkinterf.h" #include "managestkinterfhooks.h" #include "mempool.h" #include "menuloadskirmishmultihooks.h" #include "menunewskirmishhooks.h" #include "menunewskirmishhotseathooks.h" #include "menunewskirmishmultihooks.h" #include "menunewskirmishsingle.h" #include "menunewskirmishsinglehooks.h" #include "menuphasehooks.h" #include "menuprotocolhooks.h" #include "middatacache.h" #include "midevconditionhooks.h" #include "mideveffecthooks.h" #include "mideventhooks.h" #include "midgardid.h" #include "midgardmsgbox.h" #include "midgardscenariomap.h" #include "midgardstreamenv.h" #include "midmsgboxbuttonhandlerstd.h" #include "midmusic.h" #include "midplayer.h" #include "midscenvariables.h" #include "midserverlogic.h" #include "midserverlogichooks.h" #include "midstack.h" #include "midunitdescriptor.h" #include "midunitdescriptorhooks.h" #include "midunithooks.h" #include "midvillage.h" #include "modifgroup.h" #include "modifgrouphooks.h" #include "modifierutils.h" #include "movepathhooks.h" #include "musichooks.h" #include "netmsghooks.h" #include "netplayerinfo.h" #include "netsingleplayer.h" #include "netsingleplayerhooks.h" #include "originalfunctions.h" #include "phasegame.h" #include "playerbuildings.h" #include "playerincomehooks.h" #include "racecategory.h" #include "racetype.h" #include "restrictions.h" #include "scenariodata.h" #include "scenariodataarray.h" #include "scenarioinfo.h" #include "settings.h" #include "sitemerchantinterf.h" #include "sitemerchantinterfhooks.h" #include "smartptr.h" #include "stackbattleactionmsg.h" #include "summonhooks.h" #include "testconditionhooks.h" #include "transformotherhooks.h" #include "transformselfhooks.h" #include "umattack.h" #include "umattackhooks.h" #include "umunit.h" #include "umunithooks.h" #include "unitbranchcat.h" #include "unitgenerator.h" #include "unitmodifier.h" #include "unitmodifierhooks.h" #include "unitsforhire.h" #include "unitstovalidate.h" #include "unitutils.h" #include "untransformeffecthooks.h" #include "usracialsoldier.h" #include "ussoldier.h" #include "usstackleader.h" #include "usunitimpl.h" #include "utils.h" #include "version.h" #include "visitors.h" #include <algorithm> #include <cstring> #include <fmt/format.h> #include <fstream> #include <iterator> #include <string> namespace hooks { /** Hooks that used only in game. */ static Hooks getGameHooks() { using namespace game; auto& fn = gameFunctions(); auto& battle = BattleMsgDataApi::get(); auto& orig = getOriginalFunctions(); // clang-format off Hooks hooks{ // Fix game crash in battles with summoners {CMidUnitApi::get().removeModifier, removeModifierHooked}, // Fix unit transformation to include hp mods into current hp recalculation {CMidUnitApi::get().transform, transformHooked}, // Show buildings with custom branch category on the 'other buildings' tab {CBuildingBranchApi::get().constructor, buildingBranchCtorHooked}, // Allow alchemists to buff retreating units {CBatAttackGiveAttackApi::vftable()->canPerform, giveAttackCanPerformHooked}, // Random scenario generator {CMenuNewSkirmishSingleApi::get().constructor, menuNewSkirmishSingleCtorHooked, (void**)&orig.menuNewSkirmishSingleCtor}, {CMenuNewSkirmishHotseatApi::get().constructor, menuNewSkirmishHotseatCtorHooked, (void**)&orig.menuNewSkirmishHotseatCtor}, {CMenuNewSkirmishMultiApi::get().constructor, menuNewSkirmishMultiCtorHooked, (void**)&orig.menuNewSkirmishMultiCtor}, // Random scenario generator templates {CMenuPhaseApi::get().constructor, menuPhaseCtorHooked, (void**)&orig.menuPhaseCtor}, {CMenuPhaseApi::vftable()->destructor, menuPhaseDtorHooked, (void**)&orig.menuPhaseDtor}, // Support custom battle attack objects {fn.createBatAttack, createBatAttackHooked, (void**)&orig.createBatAttack}, // Support immunity bitmask in BattleMsgData {fn.getAttackClassWardFlagPosition, getAttackClassWardFlagPositionHooked, (void**)&orig.getAttackClassWardFlagPosition}, // Support custom attack animations? {fn.attackClassToString, attackClassToStringHooked, (void**)&orig.attackClassToString}, // Add items transfer buttons to city interface {CCityStackInterfApi::get().constructor, cityStackInterfCtorHooked, (void**)&orig.cityStackInterfCtor}, // Add items transfer buttons to stack exchange interface {CExchangeInterfApi::get().constructor, exchangeInterfCtorHooked, (void**)&orig.exchangeInterfCtor}, // Add items transfer buttons to pickup drop interface {CPickUpDropInterfApi::get().constructor, pickupDropInterfCtorHooked, (void**)&orig.pickupDropInterfCtor}, // Add sell all valuables button to merchant interface {CSiteMerchantInterfApi::get().constructor, siteMerchantInterfCtorHooked, (void**)&orig.siteMerchantInterfCtor}, // Cities can generate daily income depending on scenario variable settings {fn.computePlayerDailyIncome, computePlayerDailyIncomeHooked, (void**)&orig.computePlayerDailyIncome}, // Vampiric attacks can deal critical damage {CBatAttackDrainApi::vftable()->onHit, drainAttackOnHitHooked}, {CBatAttackDrainOverflowApi::vftable()->onHit, drainOverflowAttackOnHitHooked}, // Support additional music tracks for battle and capital cities {CMidMusicApi::get().playBattleTrack, playBattleTrackHooked}, {CMidMusicApi::get().playCapitalTrack, playCapitalTrackHooked}, // Fix game crash with pathfinding on 144x144 maps {fn.markMapPosition, markMapPositionHooked, (void**)&orig.markMapPosition}, // Allow user to tweak power computations {fn.getAttackPower, getAttackPowerHooked}, // Fix game crash when AI controlled unit with transform self attack // uses alternative attack with 'adjacent' attack range // Fix incorrect calculation of effective HP used by AI for target prioritization {fn.computeUnitEffectiveHpForAi, computeUnitEffectiveHpForAiHooked}, // Allow transform-self attack to not consume a unit turn for transformation // Fixes modifiers becoming permanent after modified unit is transformed // Support custom attack damage ratios {battle.beforeBattleTurn, beforeBattleTurnHooked}, // Fix free transform-self to properly reset if the same unit has consequent turns in consequent battles {battle.beforeBattleRound, beforeBattleRoundHooked, (void**)&orig.beforeBattleRound}, /** * Allows bestow wards to: * 1) Grant modifiers even if there are no source wards among them * 2) Heal its targets to the ammount specified in QTY_HEAL * 3) Heal retreating units * 4) Use Revive as a secondary attack * 5) Target a unit with a secondary attack even if there are no modifiers that can be * applied to this unit * 6) Treat modifiers with complete immunity correctly */ {CBatAttackBestowWardsApi::vftable()->canPerform, bestowWardsAttackCanPerformHooked}, /** * Fix bestow wards: * 1) Becoming permanent when more than 8 modifiers are applied at once * 2) Not resetting attack class wards (when reapplied) * 3) Incorrectly resetting attack source ward if its modifier also contains hp, regen or armor element */ // Fixes modifiers getting lost after modified unit is untransformed {CBatAttackBestowWardsApi::vftable()->onHit, bestowWardsAttackOnHitHooked}, // Fix bestow wards with double attack where modifiers granted by first attack are removed {battle.afterBattleTurn, afterBattleTurnHooked}, // Allow any attack with QTY_HEAL > 0 to heal units when battle ends (just like ordinary heal does) {fn.getUnitHealAttackNumber, getUnitHealAttackNumberHooked}, // Fix AI not being able to find target for lower damage/ini attack // Fix incorrect AI prioritization of shatter attack targets {battle.findAttackTarget, findAttackTargetHooked, (void**)&orig.findAttackTarget}, // Support custom attack sources {fn.getUnitAttackSourceImmunities, getUnitAttackSourceImmunitiesHooked}, {battle.isUnitAttackSourceWardRemoved, isUnitAttackSourceWardRemovedHooked}, {battle.removeUnitAttackSourceWard, removeUnitAttackSourceWardHooked}, {battle.addUnitToBattleMsgData, addUnitToBattleMsgDataHooked, (void**)&orig.addUnitToBattleMsgData}, // Support custom attack reaches {battle.fillTargetsList, fillTargetsListHooked}, {battle.fillEmptyTargetsList, fillEmptyTargetsListHooked}, {battle.getTargetsToAttack, getTargetsToAttackHooked}, {battle.findDoppelgangerAttackTarget, findDoppelgangerAttackTargetHooked}, {battle.findDamageAttackTargetWithNonAllReach, findDamageAttackTargetWithNonAllReachHooked}, {BattleViewerInterfApi::get().markAttackTargets, markAttackTargetsHooked}, {fn.isGroupSuitableForAiNobleMisfit, isGroupSuitableForAiNobleMisfitHooked}, {fn.isUnitSuitableForAiNobleDuel, isUnitSuitableForAiNobleDuelHooked}, {fn.isAttackBetterThanItemUsage, isAttackBetterThanItemUsageHooked}, {fn.getSummonUnitImplIdByAttack, getSummonUnitImplIdByAttackHooked}, {fn.isSmallMeleeFighter, isSmallMeleeFighterHooked}, {fn.cAiHireUnitEval, cAiHireUnitEvalHooked}, {fn.getMeleeUnitToHireAiRating, getMeleeUnitToHireAiRatingHooked}, {fn.computeTargetUnitAiPriority, computeTargetUnitAiPriorityHooked}, // Allow users to specify critical hit chance // Support custom attack damage ratios {fn.computeDamage, computeDamageHooked}, // Fix occasional crash with incorrect removal of summoned unit info // Fix persistent crash with summons when unrestrictedBestowWards is enabled {battle.removeUnitInfo, removeUnitInfoHooked}, // Fix bug where transform-self attack is unable to target self if alt attack is targeting allies {CBatAttackTransformSelfApi::vftable()->fillTargetsList, transformSelfAttackFillTargetsListHooked}, // Allow transform self into leveled units using script logic // Allow transform-self attack to not consume a unit turn for transformation // Fix bug where transform-self attack is unable to target self if alt attack is targeting allies // Fix possible attack count mismatch (once vs twice) on unit transformation {CBatAttackTransformSelfApi::vftable()->onHit, transformSelfAttackOnHitHooked}, // Allow transform other into leveled units using script logic // Fix bug where transform-other attack selects melee vs ranged transform based on attacker position rather than target position // Fix possible attack count mismatch (once vs twice) on unit transformation {CBatAttackTransformOtherApi::vftable()->onHit, transformOtherAttackOnHitHooked}, // Allow to drain different number of levels using script logic // Fix possible attack count mismatch (once vs twice) on unit transformation {CBatAttackDrainLevelApi::vftable()->onHit, drainLevelAttackOnHitHooked}, // Fix possible attack count mismatch (once vs twice) on unit transformation {CBatAttackUntransformEffectApi::vftable()->onHit, untransformEffectAttackOnHitHooked}, // Fix inability to target self for transformation in case of transform-self + summon attack // Remove persistent marking of all target units in case of transform-self attack {BattleViewerInterfApi::vftable()->update, battleViewerInterfUpdateHooked}, // Fix missing modifiers of alternative attacks {fn.getUnitAttacks, getUnitAttacksHooked}, // Support custom event conditions {ITestConditionApi::get().create, createTestConditionHooked, (void**)&orig.createTestCondition}, // Support custom event effects //{IEffectResultApi::get().create, createEffectResultHooked, (void**)&orig.createEffectResult}, // Support additional as well as high tier units in hire list {fn.addPlayerUnitsToHireList, addPlayerUnitsToHireListHooked}, {fn.shouldAddUnitToHire, shouldAddUnitToHireHooked}, {fn.enableUnitInHireListUi, enableUnitInHireListUiHooked}, // Allow scenarios with prebuilt buildings in capitals // Start with prebuilt temple in capital for warrior lord depending on user setting {fn.buildLordSpecificBuildings, buildLordSpecificBuildingsHooked}, // Allows transformed leaders (doppelganger, drain-level, transform-self/other attacks) to use battle items (potions, orbs and talismans) {BattleViewerInterfApi::get().updateBattleItems, battleViewerInterfUpdateBattleItemsHooked}, {BatBigFaceApi::get().update, batBigFaceUpdateHooked}, {battle.updateBattleActions, updateBattleActionsHooked}, // Support race-specific village graphics {GameImagesApi::get().getCityPreviewLargeImageNames, getCityPreviewLargeImageNamesHooked, (void**)&orig.getCityPreviewLargeImageNames}, {GameImagesApi::get().getCityIconImageNames, getCityIconImageNamesHooked, (void**)&orig.getCityIconImageNames}, // Support grid toggle button {CMainView2Api::get().showIsoDialog, mainView2ShowIsoDialogHooked}, // Reference ground rendering implementation // TODO: fix occasional magenta 'triangles' showing up after closing capital window //{CGroundTextureApi::vftable()->draw, groundTextureDrawHooked}, //{CGroundTextureApi::isoEngineVftable()->render, isoEngineGroundRenderHooked}, // Support native modifiers {CMidUnitApi::get().upgrade, upgradeHooked}, // Fix doppelganger attack using alternative attack when attacker is transformed (by doppelganger, drain-level, transform-self/other attacks) {battle.cannotUseDoppelgangerAttack, cannotUseDoppelgangerAttackHooked}, // Support new menu windows {CMenuPhaseApi::get().setTransition, menuPhaseSetTransitionHooked, (void**)&orig.menuPhaseSetTransition}, // Support custom modifiers {fn.loadScenarioMap, loadScenarioMapHooked, (void**)&orig.loadScenarioMap}, // Show broken (removed) wards in unit encyclopedia {CEncParamBaseApi::get().addUnitBattleInfo, encParamBaseAddUnitBattleInfoHooked}, // Fix crash on drag&drop when INotify::OnObjectChanged is processed between mouse down and up {CManageStkInterfApi::vftable().notify->onObjectChanged, manageStkInterfOnObjectChangedHooked, (void**)&orig.manageStkInterfOnObjectChanged}, {CExchangeInterfApi::vftable().notify->onObjectChanged, exchangeInterfOnObjectChangedHooked, (void**)&orig.exchangeInterfOnObjectChanged}, {CCityStackInterfApi::vftable().notify->onObjectChanged, cityStackInterfOnObjectChangedHooked, (void**)&orig.cityStackInterfOnObjectChanged}, {CSiteMerchantInterfApi::vftable().notify->onObjectChanged, siteMerchantInterfOnObjectChangedHooked, (void**)&orig.siteMerchantInterfOnObjectChanged}, // Fix inability to use heal potion on transformed unit if its current hp is greater than maximum hp of unit it is transformed to // (most common case is a unit transformed to Imp by a Witch while retaining his original hp) {fn.canApplyPotionToUnit, canApplyPotionToUnitHooked}, // Fix crash on AI turn when it tries to exchange items and a source stack is destroyed in battle/event while moving to destination {CAiGiveItemsActionApi::vftable().action->execute, aiGiveItemsActionExecuteHooked}, // Allow foreign race units to upgrade even if its race capital is present in scenario (functions as if the unit type is locked) // Allow foreign race units (including neutral) to be upgraded using capital buildings // Fix errornous logic that allowed retreated units to upgrade under certain conditions (introduce setting battle.allowRetreatedUnitsToUpgrade) {CBatAttackGroupUpgradeApi::get().upgradeGroup, upgradeGroupHooked}, {fn.getUpgradeUnitImplCheckXp, getUpgradeUnitImplCheckXpHooked}, {fn.changeUnitXpCheckUpgrade, changeUnitXpCheckUpgradeHooked}, // Allow player to customize movement cost {fn.computeMovementCost, computeMovementCostHooked}, }; // clang-format on if (userSettings().engine.sendRefreshInfoObjectCountLimit) { // Fix incomplete scenario loading when its object size exceed network message buffer size // of 512 KB hooks.emplace_back(HookInfo{CMidServerLogicApi::get().sendRefreshInfo, midServerLogicSendRefreshInfoHooked}); } if (userSettings().shatteredArmorMax != baseSettings().shatteredArmorMax) { // Allow users to customize total armor shatter damage hooks.emplace_back( HookInfo{CBatAttackShatterApi::vftable()->canPerform, shatterCanPerformHooked}); hooks.emplace_back(HookInfo{battle.setUnitShatteredArmor, setUnitShatteredArmorHooked}); } if (userSettings().shatterDamageMax != baseSettings().shatterDamageMax) { // Allow users to customize maximum armor shatter damage per attack hooks.emplace_back(HookInfo{CBatAttackShatterApi::vftable()->onHit, shatterOnHitHooked}); } if (userSettings().showBanners != baseSettings().showBanners) { // Allow users to show banners by default hooks.emplace_back(HookInfo{fn.toggleShowBannersInit, toggleShowBannersInitHooked}); } if (userSettings().showResources != baseSettings().showResources || userSettings().showLandConverted != baseSettings().showLandConverted) { // Allow users to show resources panel by default hooks.emplace_back(HookInfo{fn.respopupInit, respopupInitHooked}); } if (userSettings().carryOverItemsMax != baseSettings().carryOverItemsMax) { // Change maximum number of items that player can carry between campaign scenarios hooks.emplace_back(HookInfo{CDDCarryOverItemsApi::get().constructor, carryOverItemsCtorHooked, (void**)&orig.carryOverItemsCtor}); } if (userSettings().doppelgangerRespectsEnemyImmunity != baseSettings().doppelgangerRespectsEnemyImmunity || userSettings().doppelgangerRespectsAllyImmunity != baseSettings().doppelgangerRespectsAllyImmunity) { // Make Doppelganger attack respect target source/class wards and immunities hooks.emplace_back(HookInfo{CBatAttackDoppelgangerApi::vftable()->canPerform, doppelgangerAttackCanPerformHooked}); hooks.emplace_back(HookInfo{CBatAttackDoppelgangerApi::vftable()->isImmune, doppelgangerAttackIsImmuneHooked}); } if (userSettings().leveledDoppelgangerAttack != baseSettings().leveledDoppelgangerAttack) { // Allow doppelganger to transform into leveled units using script logic hooks.emplace_back( HookInfo{CBatAttackDoppelgangerApi::vftable()->onHit, doppelgangerAttackOnHitHooked}); } if (userSettings().leveledSummonAttack != baseSettings().leveledSummonAttack) { // Allow summon leveled units using script logic hooks.emplace_back( HookInfo{CBatAttackSummonApi::vftable()->onHit, summonAttackOnHitHooked}); } if (userSettings().missChanceSingleRoll != baseSettings().missChanceSingleRoll) { // Compute attack miss chance using single random value, instead of two hooks.emplace_back(HookInfo{fn.attackShouldMiss, attackShouldMissHooked}); } if (userSettings().unrestrictedBestowWards != baseSettings().unrestrictedBestowWards) { // Increases total ward limit for bestow-wards attack from 8 to 48 // clang-format off hooks.emplace_back(HookInfo{battle.constructor, battleMsgDataCtorHooked, (void**)&orig.battleMsgDataCtor}); hooks.emplace_back(HookInfo{battle.copyConstructor, battleMsgDataCopyCtorHooked}); hooks.emplace_back(HookInfo{battle.copyConstructor2, battleMsgDataCopyCtorHooked}); hooks.emplace_back(HookInfo{battle.copyAssignment, battleMsgDataCopyAssignHooked}); hooks.emplace_back(HookInfo{battle.copy, battleMsgDataCopyHooked}); hooks.emplace_back(HookInfo{battle.destructor, battleMsgDataDtorHooked}); hooks.emplace_back(HookInfo{CStackBattleActionMsgApi::vftable()->serialize, stackBattleActionMsgSerializeHooked, (void**)&orig.stackBattleActionMsgSerialize}); hooks.emplace_back(HookInfo{CCmdBattleStartMsgApi::vftable()->serialize, cmdBattleStartMsgSerializeHooked, (void**)&orig.cmdBattleStartMsgSerialize}); hooks.emplace_back(HookInfo{CCmdBattleChooseActionMsgApi::vftable()->serialize, cmdBattleChooseActionMsgSerializeHooked, (void**)&orig.cmdBattleChooseActionMsgSerialize}); hooks.emplace_back(HookInfo{CCmdBattleResultMsgApi::vftable()->serialize, cmdBattleResultMsgSerializeHooked, (void**)&orig.cmdBattleResultMsgSerialize}); hooks.emplace_back(HookInfo{CCmdBattleEndMsgApi::vftable()->serialize, cmdBattleEndMsgSerializeHooked, (void**)&orig.cmdBattleEndMsgSerialize}); hooks.emplace_back(HookInfo{CCommandMsgApi::get().destructor, commandMsgDtorHooked, (void**)&orig.commandMsgDtor}); hooks.emplace_back(HookInfo{CNetMsgApi::get().destructor, netMsgDtorHooked, (void**)&orig.netMsgDtor}); // clang-format on } if (userSettings().movementCost.show) { // Show movement cost hooks.emplace_back(HookInfo{fn.showMovementPath, showMovementPathHooked}); } if (isLobbySupported()) { // clang-format off // Support custom lobby server hooks.emplace_back(HookInfo{CMenuProtocolApi::get().createMenu, menuProtocolCreateMenuHooked}); hooks.emplace_back(HookInfo{CMenuProtocolApi::get().continueHandler, menuProtocolContinueHandlerHooked, (void**)&orig.menuProtocolContinueHandler}); hooks.emplace_back(HookInfo{CMenuProtocolApi::get().displayCallback, menuProtocolDisplayCallbackHooked, (void**)&orig.menuProtocolDisplayCallback}); hooks.emplace_back(HookInfo{CMenuNewSkirmishApi::get().loadScenarioCallback, menuNewSkirmishLoadScenarioCallbackHooked, (void**)&orig.menuNewSkirmishLoadScenario}); hooks.emplace_back(HookInfo{CMenuNewSkirmishMultiApi::get().createServer, menuNewSkirmishMultiCreateServerHooked, (void**)&orig.menuNewSkirmishMultiCreateServer}); hooks.emplace_back(HookInfo{CMenuLoadApi::get().buttonLoadCallback, menuLoadSkirmishMultiLoadScenarioHooked, (void**)&orig.menuLoadSkirmishMultiLoadScenario}); hooks.emplace_back(HookInfo{CMenuLoadApi::get().createHostPlayer, menuLoadSkirmishMultiCreateHostPlayerHooked, (void**)&orig.menuLoadSkirmishMultiCreateHostPlayer}); // clang-format on } bool hookSendObjectsChanges = false; if (userSettings().debugMode) { // clang-format off // Log all net messages being sent by single player (both client and server) to netMessages<PID>.log if (userSettings().debug.logSinglePlayerMessages) { hooks.emplace_back(HookInfo{CNetSinglePlayerApi::vftable()->sendMessage, netSinglePlayerSendMessageHooked, (void**)&orig.netSinglePlayerSendMessage}); } // Log added/changed/erased objects ids being sent by server to netMessages<PID>.log if (userSettings().debug.sendObjectsChangesTreshold) { hookSendObjectsChanges = true; } // clang-format on } if (userSettings().modifiers.validateUnitsOnGroupChanged) { // Validate current HP / XP of units when their group changes (units added, removed, // rearranged, etc.) to resolve issues with custom HP / XP modifiers, that depend on other // units (like auras in MNS mod). hooks.emplace_back( HookInfo{fn.getStackFortRuinGroupForChange, getStackFortRuinGroupForChangeHooked}); hookSendObjectsChanges = true; } if (hookSendObjectsChanges) { hooks.emplace_back(HookInfo{CMidServerLogicApi::vftable().midMsgSender->sendObjectsChanges, midServerLogicSendObjectsChangesHooked, (void**)&orig.midServerLogicSendObjectsChanges}); } return hooks; } /** Hooks that used only in Scenario Editor. */ static Hooks getScenarioEditorHooks() { using namespace game; auto& orig = getOriginalFunctions(); // clang-format off Hooks hooks{ // Check sites placement the same way as ruins, allowing them to be placed on water {editorFunctions.canPlaceSite, editorFunctions.canPlaceRuin}, // Allow editor to set elves race as caster in 'cast spell on location' event effect {editorFunctions.radioButtonIndexToPlayerId, radioButtonIndexToPlayerIdHooked}, // Fix DLG_R_C_SPELL so it shows actual spell info {CEncLayoutSpellApi::get().constructor, encLayoutSpellCtorHooked, (void**)&orig.encLayoutSpellCtor}, // Allow editor to place more than 200 stacks on a map {editorFunctions.countStacksOnMap, countStacksOnMapHooked}, // Support custom event conditions {CMidEvConditionApi::get().getInfoString, eventConditionGetInfoStringHooked, (void**)&orig.eventConditionGetInfoString}, {CMidEvConditionApi::get().getDescription, eventConditionGetDescriptionHooked, (void**)&orig.eventConditionGetDescription}, {CMidEvConditionApi::get().getBrief, eventConditionGetBriefHooked, (void**)&orig.eventConditionGetBrief}, {editor::CCondInterfApi::get().createFromCategory, createCondInterfFromCategoryHooked, (void**)&orig.createCondInterfFromCategory}, {CMidEventApi::get().checkValid, checkEventValidHooked, (void**)&orig.checkEventValid}, // Support custom event effects //{CMidEvEffectApi::get().getInfoString, eventEffectGetInfoStringHooked, (void**)&orig.eventEffectGetInfoString}, //{CMidEvEffectApi::get().getDescription, eventEffectGetDescriptionHooked, (void**)&orig.eventEffectGetDescription}, //{CMidEvEffectApi::get().getBrief, eventEffectGetBriefHooked, (void**)&orig.eventEffectGetBrief}, //{editor::CEffectInterfApi::get().createFromCategory, createEffectInterfFromCategoryHooked, (void**)&orig.createEffectInterfFromCategory}, {CMidgardScenarioMapApi::get().checkObjects, checkMapObjectsHooked}, // Support custom modifiers {CMidgardScenarioMapApi::get().stream, scenarioMapStreamHooked, (void**)&orig.scenarioMapStream}, }; // clang-format on return hooks; } Hooks getHooks() { using namespace game; Hooks hooks{executableIsGame() ? getGameHooks() : getScenarioEditorHooks()}; auto& fn = gameFunctions(); auto& orig = getOriginalFunctions(); // Register buildings with custom branch category as unit buildings hooks.emplace_back(HookInfo{fn.createBuildingType, createBuildingTypeHooked}); // Support custom building branch category hooks.emplace_back( HookInfo{LBuildingCategoryTableApi::get().constructor, buildingCategoryTableCtorHooked}); // Increase maximum allowed game turn hooks.emplace_back(HookInfo{fn.isTurnValid, isTurnValidHooked}); // Support custom attack class category hooks.emplace_back( HookInfo{LAttackClassTableApi::get().constructor, attackClassTableCtorHooked}); // Support custom attack class in CAttackImpl constructor // Support custom attack damage ratios // Support per-attack crit settings hooks.emplace_back(HookInfo{CAttackImplApi::get().constructor, attackImplCtorHooked}); hooks.emplace_back(HookInfo{CAttackImplApi::get().constructor2, attackImplCtor2Hooked, (void**)&orig.attackImplCtor2}); hooks.emplace_back(HookInfo{CAttackImplApi::vftable()->getData, attackImplGetDataHooked, (void**)&orig.attackImplGetData}); /** * Display heal/damage value for any attack with qtyHeal/qtyDamage > 0 regardless of its class. * This hook is required for detailedAttackDescription. */ hooks.emplace_back(HookInfo{fn.getAttackQtyDamageOrHeal, getAttackQtyDamageOrHealHooked}); // Support custom attack sources hooks.emplace_back( HookInfo{LAttackSourceTableApi::get().constructor, attackSourceTableCtorHooked}); hooks.emplace_back( HookInfo{fn.getSoldierAttackSourceImmunities, getSoldierAttackSourceImmunitiesHooked}); hooks.emplace_back(HookInfo{fn.getSoldierImmunityAiRating, getSoldierImmunityAiRatingHooked, (void**)&orig.getSoldierImmunityAiRating}); hooks.emplace_back(HookInfo{fn.getAttackSourceText, getAttackSourceTextHooked}); hooks.emplace_back(HookInfo{fn.appendAttackSourceText, appendAttackSourceTextHooked}); hooks.emplace_back(HookInfo{fn.getAttackSourceWardFlagPosition, getAttackSourceWardFlagPositionHooked, (void**)&orig.getAttackSourceWardFlagPosition}); // Support custom attack reaches hooks.emplace_back( HookInfo{LAttackReachTableApi::get().constructor, attackReachTableCtorHooked}); hooks.emplace_back(HookInfo{fn.getAttackClassAiRating, getAttackClassAiRatingHooked}); hooks.emplace_back(HookInfo{fn.getAttackReachAiRating, getAttackReachAiRatingHooked}); hooks.emplace_back(HookInfo{CMidStackApi::vftable()->initialize, midStackInitializeHooked}); // Always place melee units at the front lane in groups controlled by non-neutrals AI // Support custom attack reaches hooks.emplace_back(HookInfo{fn.chooseUnitLane, chooseUnitLaneHooked}); // Fix missing modifiers of alternative attacks hooks.emplace_back(HookInfo{CUmAttackApi::get().constructor, umAttackCtorHooked}); hooks.emplace_back(HookInfo{CUmAttackApi::get().copyConstructor, umAttackCopyCtorHooked}); // Fix incorrect representation of alternative attack modifiers in unit encyclopedia hooks.emplace_back( HookInfo{CMidUnitDescriptorApi::get().getAttack, midUnitDescriptorGetAttackHooked}); hooks.emplace_back(HookInfo{CMidUnitDescriptorApi::vftable()->getAttackInitiative, midUnitDescriptorGetAttackInitiativeHooked}); // Fix crash in encyclopedia showing info // about dyn leveled (stopped) doppleganger that transformed to stack leader hooks.emplace_back(HookInfo{CMidUnitDescriptorApi ::vftable()->isUnitLeader, midUnitDescriptorIsUnitLeaderHooked}); if (userSettings().debugMode) { // Show and log game exceptions information hooks.emplace_back(HookInfo{os_exceptionApi::get().throwException, throwExceptionHooked, (void**)&orig.throwException}); } if (userSettings().shatterDamageUpgradeRatio != baseSettings().shatterDamageUpgradeRatio) { // Allow users to customize shatter damage upgrade ratio hooks.emplace_back( HookInfo{fn.applyDynUpgradeToAttackData, applyDynUpgradeToAttackDataHooked}); } if (userSettings().unitEncyclopedia.detailedAttackDescription != baseSettings().unitEncyclopedia.detailedAttackDescription) { // Additional display of some stats bonuses, drain, critical hit, custom attack ratios, etc. hooks.emplace_back(HookInfo{fn.generateAttackDescription, generateAttackDescriptionHooked}); } // Support custom event conditions hooks.emplace_back( HookInfo{LEventCondCategoryTableApi::get().constructor, eventCondCategoryTableCtorHooked}); hooks.emplace_back(HookInfo{CMidEvConditionApi::get().createFromCategory, createEventConditionFromCategoryHooked, (void**)&orig.createEventConditionFromCategory}); // Support custom event effects // hooks.emplace_back(HookInfo{LEventEffectCategoryTableApi::get().constructor, // eventEffectCategoryTableCtorHooked}); // hooks.emplace_back(HookInfo{CMidEvEffectApi::get().createFromCategory, // createEventEffectFromCategoryHooked, // (void**)&orig.createEventEffectFromCategory}); // Allow every leader use additional animations on strategic map hooks.emplace_back( HookInfo{fn.isUnitUseAdditionalAnimation, isUnitUseAdditionalAnimationHooked}); // Support race-specific village graphics hooks.emplace_back( HookInfo{DisplayHandlersApi::get().villageHandler, displayHandlerVillageHooked}); if (userSettings().modifiers.cumulativeUnitRegeneration) { // Allow unit regeneration modifiers to stack hooks.emplace_back(HookInfo{CUmUnitApi::get().constructor, umUnitCtorHooked}); hooks.emplace_back(HookInfo{CUmUnitApi::get().copyConstructor, umUnitCopyCtorHooked}); hooks.emplace_back( HookInfo{CUmUnitApi::vftable().usSoldier->getRegen, umUnitGetRegenHooked}); } // Support custom modifiers hooks.emplace_back(HookInfo{LModifGroupTableApi::get().constructor, modifGroupTableCtorHooked}); hooks.emplace_back(HookInfo{TUnitModifierApi::get().constructor, unitModifierCtorHooked}); hooks.emplace_back(HookInfo{TUnitModifierApi::vftable()->destructor, unitModifierDtorHooked}); hooks.emplace_back(HookInfo{CMidUnitApi::get().addModifier, addModifierHooked}); hooks.emplace_back(HookInfo{CMidUnitApi::vftable()->stream, midUnitStreamHooked}); // Support custom modifiers display for unit encyclopedia hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().constructor, encLayoutUnitCtorHooked}); hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().constructor2, encLayoutUnitCtor2Hooked}); hooks.emplace_back( HookInfo{CEncLayoutUnitApi::get().dataConstructor, encLayoutUnitDataCtorHooked}); hooks.emplace_back( HookInfo{CEncLayoutUnitApi::get().dataDestructor, encLayoutUnitDataDtorHooked}); hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().initialize, encLayoutUnitInitializeHooked, (void**)&orig.encLayoutUnitInitialize}); // Show effective HP in unit encyclopedia hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().update, encLayoutUnitUpdateHooked, (void**)&orig.encLayoutUnitUpdate}); // Show total xp-killed in stack/city/ruin encyclopedia hooks.emplace_back(HookInfo{CEncLayoutStackApi::get().update, encLayoutStackUpdateHooked, (void**)&orig.encLayoutStackUpdate}); hooks.emplace_back(HookInfo{CEncLayoutCityApi::get().update, encLayoutCityUpdateHooked, (void**)&orig.encLayoutCityUpdate}); hooks.emplace_back(HookInfo{CEncLayoutRuinApi::get().update, encLayoutRuinUpdateHooked, (void**)&orig.encLayoutRuinUpdate}); // Support native modifiers hooks.emplace_back(HookInfo{CMidUnitApi::get().getModifiers, getModifiersHooked}); hooks.emplace_back(HookInfo{CMidUnitApi::get().addModifiers, addModifiersHooked}); hooks.emplace_back(HookInfo{CMidUnitApi::get().removeModifiers, removeModifiersHooked}); hooks.emplace_back(HookInfo{CMidUnitApi::vftable()->initWithSoldierImpl, initWithSoldierImplHooked, (void**)&orig.initWithSoldierImpl}); // Update city encyclopedia on visiting stack changes hooks.emplace_back(HookInfo{CEncLayoutCityApi::vftable()->onObjectChanged, encLayoutCityOnObjectChangedHooked}); // Fix infamous crash in multiplayer with city encyclopedia when observing other player's cities hooks.emplace_back( HookInfo{CEncLayoutCityApi::get().updateGroupUi, encLayoutCityUpdateGroupUiHooked}); // Fix display of required buildings when multiple units have the same upgrade building hooks.emplace_back(HookInfo{fn.getUnitRequiredBuildings, getUnitRequiredBuildingsHooked}); // Allow foreign race units to upgrade even if its race capital is present in scenario // (functions as if the unit type is locked) Allow foreign race units (including neutral) to be // upgraded using capital buildings hooks.emplace_back(HookInfo{fn.isUnitTierMax, isUnitTierMaxHooked}); hooks.emplace_back(HookInfo{fn.isUnitLevelNotMax, isUnitLevelNotMaxHooked}); hooks.emplace_back(HookInfo{fn.isUnitUpgradePending, isUnitUpgradePendingHooked}); // Fixes crash on scenario loading when level of any unit is below its template from // `GUnits.dbf`, or above maximum level for generated units (restricted by total count of unit // templates) hooks.emplace_back( HookInfo{CMidUnitApi::get().streamImplIdAndLevel, midUnitStreamImplIdAndLevelHooked}); // Support custom fonts hooks.emplace_back(HookInfo{FontCacheApi::get().loadFontFiles, loadFontFilesHooked}); hooks.emplace_back(HookInfo{FontCacheApi::get().dataDestructor, fontCacheDataDtorHooked}); // Fixes incorrect order of building status checks along with missing lordHasBuilding condition hooks.emplace_back(HookInfo{fn.getBuildingStatus, getBuildingStatusHooked}); // Fix input of 'io' (U+0451) and 'IO' (U+0401) hooks.emplace_back(HookInfo{CEditBoxInterfApi::get().isCharValid, editBoxIsCharValidHooked}); return hooks; } Hooks getVftableHooks() { using namespace game; Hooks hooks; if (CBatAttackBestowWardsApi::vftable()) // Allow bestow wards to target dead units, so it can be coupled with Revive as a secondary // attack hooks.emplace_back( HookInfo{&CBatAttackBestowWardsApi::vftable()->method15, bestowWardsMethod15Hooked}); if (userSettings().allowShatterAttackToMiss != baseSettings().allowShatterAttackToMiss) { if (CBatAttackShatterApi::vftable()) // Fix an issue where shatter attack always hits regardless of its power value hooks.emplace_back( HookInfo{&CBatAttackShatterApi::vftable()->canMiss, shatterCanMissHooked}); } return hooks; } void respopupInitHooked(void) { logDebug("mss32Proxy.log", "Resource popup hook start"); auto& variables = game::gameVariables(); *variables.minimapMode = userSettings().showLandConverted; *variables.respopup = userSettings().showResources; logDebug("mss32Proxy.log", "Resource popup hook finished"); } void* __fastcall toggleShowBannersInitHooked(void* thisptr, int /*%edx*/) { logDebug("mss32Proxy.log", "Show banners hook start"); char* ptr = (char*)thisptr; *ptr = userSettings().showBanners; // meaning unknown ptr[1] = 0; logDebug("mss32Proxy.log", "Show banners hook finished"); return thisptr; } bool __stdcall addPlayerUnitsToHireListHooked(game::CMidDataCache2* dataCache, const game::CMidgardID* playerId, const game::CMidgardID* a3, game::IdList* hireList) { using namespace game; const auto& list = IdListApi::get(); list.clear(hireList); const auto& id = CMidgardIDApi::get(); if (id.getType(a3) != IdType::Fortification) { return false; } auto findScenarioObjectById = dataCache->vftable->findScenarioObjectById; auto playerObject = findScenarioObjectById(dataCache, playerId); if (!playerObject) { logError("mssProxyError.log", fmt::format("Could not find player object with id {:x}", playerId->value)); return false; } const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); CMidPlayer* player = (CMidPlayer*)dynamicCast(playerObject, 0, rtti.IMidScenarioObjectType, rtti.CMidPlayerType, 0); if (!player) { logError("mssProxyError.log", fmt::format("Object with id {:x} is not player", playerId->value)); return false; } auto buildingsObject = findScenarioObjectById(dataCache, &player->buildingsId); if (!buildingsObject) { logError("mssProxyError.log", fmt::format("Could not find player buildings with id {:x}", player->buildingsId.value)); return false; } auto playerBuildings = (CPlayerBuildings*)dynamicCast(buildingsObject, 0, rtti.IMidScenarioObjectType, rtti.CPlayerBuildingsType, 0); if (!playerBuildings) { logError("mssProxyError.log", fmt::format("Object with id {:x} is not player buildings", player->buildingsId.value)); return false; } const auto& global = GlobalDataApi::get(); const auto globalData = *global.getGlobalData(); auto races = globalData->races; TRaceType* race = (TRaceType*)global.findById(races, &player->raceId); const auto& fn = gameFunctions(); const auto& addUnitToHireList = fn.addUnitToHireList; const auto& unitBranch = UnitBranchCategories::get(); addUnitToHireList(race, playerBuildings, unitBranch.fighter, hireList); addUnitToHireList(race, playerBuildings, unitBranch.archer, hireList); addUnitToHireList(race, playerBuildings, unitBranch.mage, hireList); addUnitToHireList(race, playerBuildings, unitBranch.special, hireList); fn.addSideshowUnitToHireList(race, playerBuildings, hireList); if (!unitsForHire().empty()) { const int raceIndex = id.getTypeIndex(&player->raceId); const auto& units = unitsForHire()[raceIndex]; for (const auto& unit : units) { list.pushBack(hireList, &unit); } } const auto& buildList = playerBuildings->buildings; if (buildList.length == 0) { // Player has no buildings in capital, skip return true; } auto variables{getScenarioVariables(dataCache)}; if (!variables || !variables->variables.length) { return true; } int hireTierMax{0}; for (const auto& variable : variables->variables) { static const char varName[]{"UNIT_HIRE_TIER_MAX"}; if (!strncmp(variable.second.name, varName, sizeof(varName))) { hireTierMax = variable.second.value; break; } } if (hireTierMax <= 1) { // No variable defined or high tier hire is disabled, skip. return true; } const auto units = globalData->units; for (auto current = units->map->data.bgn, end = units->map->data.end; current != end; ++current) { const auto unitImpl = current->second; auto soldier = fn.castUnitImplToSoldier(unitImpl); if (!soldier) { continue; } if (race->id != *soldier->vftable->getRaceId(soldier)) { continue; } auto racialSoldier = fn.castUnitImplToRacialSoldier(unitImpl); if (!racialSoldier) { continue; } auto upgradeBuildingId = racialSoldier->vftable->getUpgradeBuildingId(racialSoldier); if (*upgradeBuildingId == emptyId) { continue; } bool hasBulding{false}; for (auto node = buildList.head->next; node != buildList.head; node = node->next) { if (node->data == *upgradeBuildingId) { hasBulding = true; break; } } if (!hasBulding) { // No building for this unit was built in capital, skip continue; } if (getBuildingLevel(upgradeBuildingId) <= hireTierMax) { list.pushBack(hireList, &current->first); } } return true; } void __stdcall createBuildingTypeHooked(const game::CDBTable* dbTable, void* a2, const game::GlobalData** globalData) { using namespace game; auto* buildings = (*globalData)->buildingCategories; LBuildingCategory category; category.vftable = BuildingCategories::vftable(); auto& db = CDBTableApi::get(); db.findBuildingCategory(&category, dbTable, "CATEGORY", buildings); auto memAlloc = Memory::get().allocate; auto constructor = TBuildingTypeApi::get().constructor; TBuildingType* buildingType = nullptr; auto& buildingCategories = BuildingCategories::get(); if (category.id == buildingCategories.unit->id || isCustomBuildingCategory(&category)) { // This is TBuildingUnitUpgType constructor // without TBuildingTypeData::category validity check TBuildingUnitUpgType* unitBuilding = (TBuildingUnitUpgType*)memAlloc( sizeof(TBuildingUnitUpgType)); constructor(unitBuilding, dbTable, globalData); unitBuilding->branch.vftable = UnitBranchCategories::vftable(); unitBuilding->vftable = (IMidObjectVftable*)TBuildingUnitUpgTypeApi::vftable(); auto* branches = (*globalData)->unitBranches; db.findUnitBranchCategory(&unitBuilding->branch, dbTable, "BRANCH", branches); db.readUnitLevel(&unitBuilding->level, dbTable, "LEVEL"); buildingType = unitBuilding; } else { buildingType = constructor((TBuildingType*)memAlloc(sizeof(TBuildingType)), dbTable, globalData); } if (!gameFunctions().addObjectAndCheckDuplicates(a2, buildingType)) { db.duplicateRecordException(dbTable, &buildingType->id); } } game::LBuildingCategoryTable* __fastcall buildingCategoryTableCtorHooked( game::LBuildingCategoryTable* thisptr, int /*%edx*/, const char* globalsFolderPath, void* codeBaseEnvProxy) { using namespace game; static const char dbfFileName[] = "LBuild.dbf"; logDebug("newBuildingType.log", "Hook started"); const auto dbfFilePath{std::filesystem::path(globalsFolderPath) / dbfFileName}; addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Fighter, "L_FIGHTER"); addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Mage, "L_MAGE"); addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Archer, "L_ARCHER"); addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Other, "L_CUSTOM"); addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Special, "L_SPECIAL"); auto& table = LBuildingCategoryTableApi::get(); auto& categories = BuildingCategories::get(); thisptr->bgn = nullptr; thisptr->end = nullptr; thisptr->allocatedMemEnd = nullptr; thisptr->allocator = nullptr; thisptr->vftable = LBuildingCategoryTableApi::vftable(); table.init(thisptr, codeBaseEnvProxy, globalsFolderPath, dbfFileName); table.readCategory(categories.guild, thisptr, "L_GUILD", dbfFileName); table.readCategory(categories.heal, thisptr, "L_HEAL", dbfFileName); table.readCategory(categories.magic, thisptr, "L_MAGIC", dbfFileName); table.readCategory(categories.unit, thisptr, "L_UNIT", dbfFileName); for (auto& custom : getCustomBuildingCategories()) { table.readCategory(&custom.second, thisptr, custom.second.text.c_str(), dbfFileName); } table.initDone(thisptr); logDebug("newBuildingType.log", "Hook finished"); return thisptr; } static void addUnitBuilding(game::BuildingBranchMap* branchMap, const game::TBuildingType* buildingType, game::BuildingBranchNumber branchNumber, game::CPhaseGame* phaseGame) { using namespace game; const auto& buildingBranch = CBuildingBranchApi::get(); const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); const auto& branches = UnitBranchCategories::get(); const TBuildingUnitUpgType* unitUpg = (const TBuildingUnitUpgType*) dynamicCast(buildingType, 0, rtti.TBuildingTypeType, rtti.TBuildingUnitUpgTypeType, 0); auto branchId = unitUpg->branch.id; if (branchId == branches.sideshow->id) { buildingBranch.addSideshowUnitBuilding(branchMap, unitUpg); return; } if (branchId == branches.fighter->id && branchNumber == BuildingBranchNumber::Fighter || branchId == branches.mage->id && branchNumber == BuildingBranchNumber::Mage || branchId == branches.archer->id && branchNumber == BuildingBranchNumber::Archer || branchId == branches.special->id && branchNumber == BuildingBranchNumber::Special) { buildingBranch.addUnitBuilding(phaseGame, branchMap, unitUpg); } } static void addBuilding(game::BuildingBranchMap* branchMap, const game::TBuildingType* buildingType, game::BuildingBranchNumber branchNumber, game::CPhaseGame* phaseGame) { using namespace game; const auto& buildingBranch = CBuildingBranchApi::get(); const auto& categories = BuildingCategories::get(); const LBuildingCategory* category = &buildingType->data->category; if (category->id == categories.unit->id) { addUnitBuilding(branchMap, buildingType, branchNumber, phaseGame); } else if ((category->id == categories.guild->id || category->id == categories.heal->id || category->id == categories.magic->id) && branchNumber == BuildingBranchNumber::Other) { buildingBranch.addBuilding(phaseGame, branchMap, buildingType); } else if (category->id == getCustomBuildingCategoryId(branchNumber)) { buildingBranch.addBuilding(phaseGame, branchMap, buildingType); } } game::CBuildingBranch* __fastcall buildingBranchCtorHooked(game::CBuildingBranch* thisptr, int /*%edx*/, game::CPhaseGame* phaseGame, game::BuildingBranchNumber* branchNumber) { using namespace game; logDebug("newBuildingType.log", "CBuildingBranchCtor hook started"); auto memAlloc = Memory::get().allocate; CBuildingBranchData* data = (CBuildingBranchData*)memAlloc(sizeof(CBuildingBranchData)); const auto& buildingBranch = CBuildingBranchApi::get(); buildingBranch.initData(data); thisptr->data = data; thisptr->vftable = CBuildingBranchApi::vftable(); buildingBranch.initBranchMap(&thisptr->data->map); thisptr->data->branchNumber = *branchNumber; auto* dialogName = &thisptr->data->branchDialogName; StringApi::get().free(dialogName); dialogName->string = nullptr; dialogName->length = 0; dialogName->lengthAllocated = 0; const auto& phase = CPhaseApi::get(); auto playerId = phase.getCurrentPlayerId(&phaseGame->phase); auto objectMap = phase.getObjectMap(&phaseGame->phase); auto findScenarioObjectById = objectMap->vftable->findScenarioObjectById; auto playerObject = findScenarioObjectById(objectMap, playerId); const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); const CMidPlayer* player = (const CMidPlayer*)dynamicCast(playerObject, 0, rtti.IMidScenarioObjectType, rtti.CMidPlayerType, 0); const LRaceCategory* playerRace = &player->raceType->data->raceType; thisptr->data->raceCategory.table = playerRace->table; thisptr->data->raceCategory.id = playerRace->id; const auto& fn = gameFunctions(); auto lord = fn.getLordByPlayer(player); auto buildList = lord->data->buildList; const auto& globalApi = GlobalDataApi::get(); auto buildings = (*globalApi.getGlobalData())->buildings; for (const auto& id : buildList->data) { auto buildingType = (const TBuildingType*)globalApi.findById(buildings, &id); addBuilding(&thisptr->data->map, buildingType, *branchNumber, phaseGame); } logDebug("newBuildingType.log", "Ctor finished"); return thisptr; } int __stdcall chooseUnitLaneHooked(const game::IUsSoldier* soldier) { using namespace game; // Place units with adjacent attack reach at the front lane, despite of their attack class IAttack* attack = soldier->vftable->getAttackById(soldier); return isMeleeAttack(attack) ? 1 : 0; } bool __stdcall isTurnValidHooked(int turn) { return turn >= 0 && turn <= 9999 || turn == -1; } game::CMidgardID* __stdcall radioButtonIndexToPlayerIdHooked(game::CMidgardID* playerId, game::IMidgardObjectMap* objectMap, int index) { using namespace game; const auto& races = RaceCategories::get(); const auto& fn = editorFunctions; const CMidPlayer* player{nullptr}; switch (index) { case 0: player = fn.findPlayerByRaceCategory(races.human, objectMap); break; case 1: player = fn.findPlayerByRaceCategory(races.heretic, objectMap); break; case 2: player = fn.findPlayerByRaceCategory(races.undead, objectMap); break; case 3: player = fn.findPlayerByRaceCategory(races.dwarf, objectMap); break; case 4: player = fn.findPlayerByRaceCategory(races.elf, objectMap); break; } *playerId = player ? player->id : emptyId; return playerId; } bool __fastcall giveAttackCanPerformHooked(game::CBatAttackGiveAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId) { using namespace game; CMidgardID targetGroupId{}; thisptr->vftable->getTargetGroupId(thisptr, &targetGroupId, battleMsgData); auto& fn = gameFunctions(); CMidgardID unitGroupId{}; fn.getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, unitId, true); if (targetGroupId != unitGroupId) { // Do not allow to give additional attacks to enemies return false; } if (*unitId == thisptr->unitId1) { // Do not allow to give additional attacks to self return false; } CMidUnit* unit = fn.findUnitById(objectMap, unitId); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); auto attack = soldier->vftable->getAttackById(soldier); const auto attackClass = attack->vftable->getAttackClass(attack); const auto& attackCategories = AttackClassCategories::get(); if (attackClass->id == attackCategories.giveAttack->id) { // Do not allow to buff other units with this attack type return false; } auto secondAttack = soldier->vftable->getSecondAttackById(soldier); if (!secondAttack) { return true; } const auto secondAttackClass = secondAttack->vftable->getAttackClass(secondAttack); // Do not allow to buff other units with this attack type as their second attack return secondAttackClass->id != attackCategories.giveAttack->id; } bool __fastcall shatterCanPerformHooked(game::CBatAttackShatter* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId) { using namespace game; CMidgardID targetGroupId{}; thisptr->vftable->getTargetGroupId(thisptr, &targetGroupId, battleMsgData); auto& fn = gameFunctions(); CMidgardID unitGroupId{}; fn.getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, unitId, true); if (targetGroupId != unitGroupId) { // Can't target allies return false; } auto& battle = BattleMsgDataApi::get(); if (battle.getUnitStatus(battleMsgData, unitId, BattleStatus::Retreat)) { // Can't target retreating units return false; } const int shatteredArmor = battle.getUnitShatteredArmor(battleMsgData, unitId); if (shatteredArmor >= userSettings().shatteredArmorMax) { return false; } CMidUnit* unit = fn.findUnitById(objectMap, unitId); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); int unitArmor{}; soldier->vftable->getArmor(soldier, &unitArmor); const int fortArmor = battle.getUnitFortificationArmor(battleMsgData, unitId); const int reducedArmor = unitArmor - shatteredArmor; if (reducedArmor > fortArmor) { return reducedArmor > 0; } return false; } void __fastcall setUnitShatteredArmorHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::CMidgardID* unitId, int armor) { using namespace game; auto info = BattleMsgDataApi::get().getUnitInfoById(thisptr, unitId); if (!info) { return; } info->shatteredArmor = std::clamp(info->shatteredArmor + armor, 0, userSettings().shatteredArmorMax); } void __fastcall shatterOnHitHooked(game::CBatAttackShatter* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId, game::BattleAttackInfo** attackInfo) { using namespace game; auto attackVftable = (const IAttackVftable*)thisptr->attack->vftable; const auto damageMax{userSettings().shatterDamageMax}; int shatterDamage = attackVftable->getQtyDamage(thisptr->attack); if (shatterDamage > damageMax) { shatterDamage = damageMax; } setUnitShatteredArmorHooked(battleMsgData, 0, unitId, shatterDamage); const auto unit = gameFunctions().findUnitById(objectMap, unitId); BattleAttackUnitInfo info{}; info.unitId = *unitId; info.unitImplId = unit->unitImpl->id; info.attackMissed = false; info.damage = 0; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); } bool __fastcall shatterCanMissHooked(game::CBatAttackShatter* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData, game::CMidgardID* id) { return true; } bool __stdcall buildLordSpecificBuildingsHooked(game::IMidgardObjectMap* objectMap, const game::NetPlayerInfo* playerInfo, int) { using namespace game; auto playerObj = objectMap->vftable->findScenarioObjectById(objectMap, &playerInfo->playerId); const auto dynamicCast = RttiApi::get().dynamicCast; const auto& rtti = RttiApi::rtti(); auto player = (const CMidPlayer*)dynamicCast(playerObj, 0, rtti.IMidScenarioObjectType, rtti.CMidPlayerType, 0); auto& fn = gameFunctions(); if (!userSettings().preserveCapitalBuildings) { fn.deletePlayerBuildings(objectMap, player); } auto lordType = fn.getLordByPlayer(player); const auto lordCategoryId{lordType->data->lordCategory.id}; const auto& lordCategories = LordCategories::get(); const auto& buildingCategories = BuildingCategories::get(); if (lordCategoryId == lordCategories.diplomat->id) { return fn.addCapitalBuilding(objectMap, player, buildingCategories.guild); } if (lordCategoryId == lordCategories.mage->id) { return fn.addCapitalBuilding(objectMap, player, buildingCategories.magic); } if (userSettings().buildTempleForWarriorLord && lordCategoryId == lordCategories.warrior->id) { return fn.addCapitalBuilding(objectMap, player, buildingCategories.heal); } return true; } game::CEncLayoutSpell* __fastcall encLayoutSpellCtorHooked(game::CEncLayoutSpell* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::CInterface* interf, void* a2, game::CMidgardID* spellId, game::CEncParamBase* encParam, const game::CMidgardID* playerId) { using namespace game; if (!playerId) { forEachScenarioObject(objectMap, IdType::Player, [&playerId](const IMidScenarioObject* obj) { // Use id of the first found player to show spell info if (!playerId) { playerId = &obj->id; } }); } // Show spell price and casting cost encParam->data->statuses = 4; return getOriginalFunctions().encLayoutSpellCtor(thisptr, objectMap, interf, a2, spellId, encParam, playerId); } int __stdcall countStacksOnMapHooked(game::IMidgardObjectMap*) { return 0; } game::CDDCarryOverItems* __fastcall carryOverItemsCtorHooked(game::CDDCarryOverItems* thisptr, int /*%edx*/, game::IMidDropManager* dropManager, game::CListBoxInterf* listBox, game::CPhaseGame* phaseGame, int carryOverItemsMax) { return getOriginalFunctions().carryOverItemsCtor(thisptr, dropManager, listBox, phaseGame, userSettings().carryOverItemsMax); } void __fastcall markMapPositionHooked(void* thisptr, int /*%edx*/, game::CMqPoint* position) { if (position->x < 0 || position->x >= 144 || position->y < 0 || position->y >= 144) return; return getOriginalFunctions().markMapPosition(thisptr, position); } int __stdcall computeDamageHooked(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::IAttack* attack, const game::CMidgardID* attackerUnitId, const game::CMidgardID* targetUnitId, bool computeCriticalHit, int* attackDamage, int* criticalHitDamage) { using namespace game; int armor; const auto& fn = gameFunctions(); fn.computeArmor(&armor, objectMap, battleMsgData, targetUnitId); bool isEasyDifficulty = false; auto player = getPlayer(objectMap, battleMsgData, attackerUnitId); if (player && player->isHuman) { const auto& difficulties = DifficultyLevelCategories::get(); isEasyDifficulty = getScenarioInfo(objectMap)->gameDifficulty.id == difficulties.easy->id; } int damageMax = fn.computeDamageMax(objectMap, attackerUnitId); int damageWithBuffs = fn.computeDamageWithBuffs(attack, damageMax, battleMsgData, attackerUnitId, true, isEasyDifficulty); int damage = damageWithBuffs * (100 - armor) / 100; int critDamage = 0; if (computeCriticalHit) { bool critHit = attack->vftable->getCritHit(attack); if (!critHit) { auto unit = fn.findUnitById(objectMap, attackerUnitId); critHit = hasCriticalHitLeaderAbility(unit->unitImpl); } if (critHit) { auto customData = getCustomAttackData(attack); int critPower = customData.critPower; if (!fn.attackShouldMiss(&critPower)) { critDamage = damageWithBuffs * customData.critDamage / 100; } } } if (getCustomAttacks().damageRatiosEnabled) { auto& damageRatios = getCustomDamageRatios(attack); auto ratio = damageRatios.find(*targetUnitId); if (ratio != damageRatios.end()) { damage = applyAttackDamageRatio(damage, ratio->second); critDamage = applyAttackDamageRatio(critDamage, ratio->second); } } if (attackDamage) *attackDamage = damage; if (criticalHitDamage) *criticalHitDamage = critDamage; return damage + critDamage; } void __stdcall getAttackPowerHooked(int* power, const game::IAttack* attack, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId, const game::BattleMsgData* battleMsgData) { if (!attack) { *power = 100; return; } using namespace game; const auto& restrictions = game::gameRestrictions(); const auto attackClass = attack->vftable->getAttackClass(attack); if (!attackHasPower(attackClass->id)) { *power = 100; return; } int tmpPower{}; attack->vftable->getPower(attack, &tmpPower); const auto& battle = BattleMsgDataApi::get(); auto groupId = battle.isUnitAttacker(battleMsgData, unitId) ? &battleMsgData->attackerGroupId : &battleMsgData->defenderGroupId; const auto& fn = gameFunctions(); if (!fn.isGroupOwnerPlayerHuman(objectMap, groupId)) { const auto& difficulties = DifficultyLevelCategories::get(); const auto difficultyId = getScenarioInfo(objectMap)->gameDifficulty.id; const auto& aiAttackPower = userSettings().aiAttackPowerBonus; const std::int8_t* bonus = &aiAttackPower.easy; if (difficultyId == difficulties.easy->id) { bonus = &aiAttackPower.easy; } else if (difficultyId == difficulties.average->id) { bonus = &aiAttackPower.average; } else if (difficultyId == difficulties.hard->id) { bonus = &aiAttackPower.hard; } else if (difficultyId == difficulties.veryHard->id) { bonus = &aiAttackPower.veryHard; } if (aiAttackPower.absolute) { tmpPower += *bonus; } else { tmpPower += tmpPower * *bonus / 100; } tmpPower = std::clamp(tmpPower, restrictions.attackPower->min, restrictions.attackPower->max); } const auto& attacks = AttackClassCategories::get(); if (battleMsgData->currentRound > userSettings().disableAllowedRoundMax && (attackClass->id == attacks.paralyze->id || attackClass->id == attacks.petrify->id)) { tmpPower = 0; } tmpPower -= battle.getAttackPowerReduction(battleMsgData, unitId); *power = std::clamp(tmpPower, restrictions.attackPower->min, restrictions.attackPower->max); } bool __stdcall attackShouldMissHooked(const int* power) { return game::gameFunctions().generateRandomNumber(100) > *power; } int __stdcall getUnitHealAttackNumberHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; const auto& fn = gameFunctions(); auto unit = fn.findUnitById(objectMap, unitId); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); auto attack = soldier->vftable->getAttackById(soldier); int qtyHeal = attack->vftable->getQtyHeal(attack); if (qtyHeal > 0) return 1; auto attack2 = soldier->vftable->getSecondAttackById(soldier); if (attack2) { qtyHeal = attack2->vftable->getQtyHeal(attack2); if (qtyHeal > 0) return 2; } return 0; } int __stdcall getAttackQtyDamageOrHealHooked(const game::IAttack* attack, int damageMax) { int qtyHeal = attack->vftable->getQtyHeal(attack); if (qtyHeal) return qtyHeal; int qtyDamage = attack->vftable->getQtyDamage(attack); if (qtyDamage > damageMax) qtyDamage = damageMax; return qtyDamage; } static game::CMidgardID currUnitId = game::emptyId; void __stdcall afterBattleTurnHooked(game::BattleMsgData* battleMsgData, const game::CMidgardID* unitId, const game::CMidgardID* nextUnitId) { using namespace game; if (*unitId != *nextUnitId) { battleMsgData->battleStateFlags2.parts.shouldUpdateUnitEffects = true; BattleMsgDataApi::get().removeFiniteBoostLowerDamage(battleMsgData, unitId); } currUnitId = *unitId; } void __stdcall beforeBattleTurnHooked(game::BattleMsgData* battleMsgData, game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); battle.setUnitStatus(battleMsgData, unitId, BattleStatus::Defend, false); // Fix bestow wards with double attack where modifiers granted by first attack are removed if (*unitId != currUnitId) { auto unitInfo = battle.getUnitInfoById(battleMsgData, unitId); auto modifiedUnitIds = getModifiedUnitIds(unitInfo); for (auto it = modifiedUnitIds.begin(); it != modifiedUnitIds.end(); it++) removeModifiers(battleMsgData, objectMap, unitInfo, &(*it)); resetModifiedUnitsInfo(unitInfo); } battle.setAttackPowerReduction(battleMsgData, unitId, 0); getCustomAttacks().targets.clear(); getCustomAttacks().damageRatios.clear(); auto& freeTransformSelf = getCustomAttacks().freeTransformSelf; if (freeTransformSelf.unitId != *unitId) { freeTransformSelf.unitId = *unitId; freeTransformSelf.turnCount = 0; freeTransformSelf.used = false; } else if (freeTransformSelf.used) { // Fix free transform-self to disable Wait/Defend/Retreat auto unitInfo = battle.getUnitInfoById(battleMsgData, unitId); if (unitInfo) unitInfo->unitFlags.parts.attackedOnceOfTwice = 1; } freeTransformSelf.turnCount++; } void __stdcall throwExceptionHooked(const game::os_exception* thisptr, const void* throwInfo) { if (thisptr && thisptr->message) { showErrorMessageBox(fmt::format("Caught exception '{:s}'.\n" "The {:s} will probably crash now.", thisptr->message, executableIsGame() ? "game" : "editor")); } getOriginalFunctions().throwException(thisptr, throwInfo); } int __stdcall computeUnitEffectiveHpForAiHooked(const game::IMidgardObjectMap* objectMap, const game::CMidUnit* unit, const game::BattleMsgData* battleMsgData) { using namespace game; const auto& fn = gameFunctions(); if (!unit) return 0; int armor; fn.computeArmor(&armor, objectMap, battleMsgData, &unit->id); return computeUnitEffectiveHpForAi(unit->currentHp, armor); } void __stdcall applyDynUpgradeToAttackDataHooked(const game::CMidgardID* unitImplId, game::CUnitGenerator* unitGenerator, int unitLevel, game::IdType dynUpgradeType, const game::CMidgardID* altAttackId, game::CAttackData* attackData) { using namespace game; CMidgardID leveledUnitImplId{}; unitGenerator->vftable->generateUnitImplId(unitGenerator, &leveledUnitImplId, unitImplId, unitLevel); CMidgardID globalUnitImplId{}; unitGenerator->vftable->getGlobalUnitImplId(unitGenerator, &globalUnitImplId, &leveledUnitImplId); CMidgardID leveledAttackId{}; CMidgardIDApi::get().changeType(&leveledAttackId, &leveledUnitImplId, dynUpgradeType); CDynUpgrade* upgrade1 = nullptr; CDynUpgrade* upgrade2 = nullptr; int upgrade1Count; int upgrade2Count; gameFunctions().computeUnitDynUpgrade(&globalUnitImplId, unitLevel, &upgrade1, &upgrade2, &upgrade1Count, &upgrade2Count); attackData->attackId = leveledAttackId; attackData->altAttack = *altAttackId; if (upgrade1) attackData->initiative += upgrade1->initiative * upgrade1Count; if (upgrade2) attackData->initiative += upgrade2->initiative * upgrade2Count; if (attackData->power > 0) { if (upgrade1) attackData->power += upgrade1->power * upgrade1Count; if (upgrade2) attackData->power += upgrade2->power * upgrade2Count; } if (attackData->qtyDamage > 0) { float ratio = 1.0; if (attackData->attackClass->id == AttackClassCategories::get().shatter->id) ratio = (float)userSettings().shatterDamageUpgradeRatio / 100; if (upgrade1) attackData->qtyDamage += lround(upgrade1->damage * upgrade1Count * ratio); if (upgrade2) attackData->qtyDamage += lround(upgrade2->damage * upgrade2Count * ratio); } if (attackData->qtyHeal > 0) { if (upgrade1) attackData->qtyHeal += upgrade1->heal * upgrade1Count; if (upgrade2) attackData->qtyHeal += upgrade2->heal * upgrade2Count; } } void __stdcall getUnitAttacksHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId, game::AttackTypePairVector* value, bool checkAltAttack) { using namespace game; const auto& fn = gameFunctions(); const auto& vectorApi = AttackTypePairVectorApi::get(); auto unit = fn.findUnitById(objectMap, unitId); auto attack = getAttack(unit->unitImpl, true, checkAltAttack); AttackTypePair pair{attack, AttackType::Primary}; vectorApi.pushBack(value, &pair); auto attack2 = getAttack(unit->unitImpl, false, checkAltAttack); if (attack2) { AttackTypePair pair{attack2, AttackType::Secondary}; vectorApi.pushBack(value, &pair); } auto item1Attack = fn.getItemAttack(objectMap, unitId, 1); if (item1Attack) { AttackTypePair pair{item1Attack, AttackType::Item}; vectorApi.pushBack(value, &pair); } auto item2Attack = fn.getItemAttack(objectMap, unitId, 2); if (item2Attack) { AttackTypePair pair{item2Attack, AttackType::Item}; vectorApi.pushBack(value, &pair); } } bool __stdcall isUnitUseAdditionalAnimationHooked(const game::CMidgardID*) { return true; } bool __stdcall shouldAddUnitToHireHooked(const game::CMidPlayer* player, game::CPhaseGame* phaseGame, const game::CMidgardID* unitImplId) { return true; } bool __stdcall enableUnitInHireListUiHooked(const game::CMidPlayer* player, game::CPhaseGame* phaseGame, const game::CMidgardID* unitImplId) { using namespace game; auto objectMap = CPhaseApi::get().getObjectMap(&phaseGame->phase); auto playerBuildings = getPlayerBuildings(objectMap, player); if (!playerBuildings) { return false; } const auto& global = GlobalDataApi::get(); const auto globalData = *global.getGlobalData(); auto unitImpl = (const TUsUnitImpl*)global.findById(globalData->units, unitImplId); if (!unitImpl) { return false; } auto racialSoldier = gameFunctions().castUnitImplToRacialSoldier(unitImpl); if (!racialSoldier) { return false; } auto soldier = gameFunctions().castUnitImplToSoldier(unitImpl); if (!soldier) { return false; } auto enrollBuildingId = racialSoldier->vftable->getEnrollBuildingId(racialSoldier); // Starting units are always allowed if (soldier->vftable->getLevel(soldier) == 1 && *enrollBuildingId == emptyId) { return true; } // If unit has enroll bulding requirement, check it if (*enrollBuildingId != emptyId) { const auto& buildList = playerBuildings->buildings; for (auto node = buildList.head->next; node != buildList.head; node = node->next) { if (node->data == *enrollBuildingId) { return true; } } return false; } // High tier units have only upgrade building requirement: // upgrade building is required for units from previous tier to promote auto upgradeBuildingId = racialSoldier->vftable->getUpgradeBuildingId(racialSoldier); if (*upgradeBuildingId != emptyId) { const auto& buildList = playerBuildings->buildings; for (auto node = buildList.head->next; node != buildList.head; node = node->next) { if (node->data == *upgradeBuildingId) { return true; } } } return false; } void __stdcall getCityPreviewLargeImageNamesHooked(game::List<game::String>* imageNames, const void* cityFF, const game::LRaceCategory* race, int cityTier) { using namespace game; const auto& races{RaceCategories::get()}; const auto raceId{race->id}; if (cityTier == 0 || raceId == races.neutral->id) { getOriginalFunctions().getCityPreviewLargeImageNames(imageNames, cityFF, race, cityTier); return; } char raceSuffix{'?'}; if (raceId == races.human->id) { raceSuffix = 'H'; } else if (raceId == races.undead->id) { raceSuffix = 'U'; } else if (raceId == races.heretic->id) { raceSuffix = 'E'; } else if (raceId == races.dwarf->id) { raceSuffix = 'D'; } else if (raceId == races.elf->id) { raceSuffix = 'F'; } const auto name{fmt::format("ALN{:c}{:d}", raceSuffix, cityTier)}; const auto length{name.length()}; GameImagesApi::get().getImageNames(imageNames, cityFF, name.c_str(), length, length); if (!imageNames->length) { // Fallback to default city image names getOriginalFunctions().getCityPreviewLargeImageNames(imageNames, cityFF, race, cityTier); } } void __stdcall getCityIconImageNamesHooked(game::List<game::String>* imageNames, const void* iconsFF, const game::CMidgardID* fortificationId, const game::IMidgardObjectMap* objectMap) { using namespace game; auto obj{objectMap->vftable->findScenarioObjectById(objectMap, fortificationId)}; if (!obj) { return; } auto fortification{static_cast<const CFortification*>(obj)}; auto vftable{static_cast<const CFortificationVftable*>(fortification->vftable)}; auto category{vftable->getCategory(fortification)}; if (category->id != FortCategories::get().village->id) { getOriginalFunctions().getCityIconImageNames(imageNames, iconsFF, fortificationId, objectMap); return; } auto village{static_cast<const CMidVillage*>(fortification)}; const auto& races{RaceCategories::get()}; const auto neutralRace{races.neutral}; const LRaceCategory* ownerRace{neutralRace}; if (village->ownerId != emptyId) { auto player{getPlayer(objectMap, &village->ownerId)}; if (player) { ownerRace = &player->raceType->data->raceType; } } const auto ownerRaceId{ownerRace->id}; if (ownerRaceId == neutralRace->id) { getOriginalFunctions().getCityIconImageNames(imageNames, iconsFF, fortificationId, objectMap); return; } const char* raceSuffix{"HU"}; if (ownerRaceId == races.human->id) { raceSuffix = "HU"; } else if (ownerRaceId == races.heretic->id) { raceSuffix = "HE"; } else if (ownerRaceId == races.undead->id) { raceSuffix = "UN"; } else if (ownerRaceId == races.dwarf->id) { raceSuffix = "DW"; } else if (ownerRaceId == races.elf->id) { raceSuffix = "EL"; } const char tierLetter{'0' + static_cast<char>(village->tierLevel)}; const auto name{fmt::format("CITY{:s}{:c}", raceSuffix, tierLetter)}; const auto length{name.length()}; GameImagesApi::get().getImageNames(imageNames, iconsFF, name.c_str(), length, length); if (!imageNames->length) { // Fallback to default city icon image names getOriginalFunctions().getCityIconImageNames(imageNames, iconsFF, fortificationId, objectMap); } } bool __fastcall checkMapObjectsHooked(game::CMidgardScenarioMap* scenarioMap, int /*%edx*/) { using namespace game; std::memset(scenarioMap->freeIdTypeIndices, 0, sizeof(scenarioMap->freeIdTypeIndices)); const auto& api{CMidgardScenarioMapApi::get()}; ScenarioMapDataIterator current{}; api.begin(scenarioMap, &current); ScenarioMapDataIterator end{}; api.end(scenarioMap, &end); const auto& idApi{CMidgardIDApi::get()}; while (current.foundRecord != end.foundRecord) { const auto* objectId{&current.foundRecord->key}; const auto type{static_cast<int>(idApi.getType(objectId))}; const auto typeIndex{idApi.getTypeIndex(objectId)}; if (scenarioMap->freeIdTypeIndices[type] <= typeIndex) { scenarioMap->freeIdTypeIndices[type] = typeIndex + 1; } const auto* object{current.foundRecord->value.data}; if (!object->vftable->isValid(object, scenarioMap)) { logError("mssProxyError.log", fmt::format("Scenario object {:s} is invalid", idToString(objectId))); return false; } api.advance(&current); } return true; } void validateUnits(game::CMidgardScenarioMap* scenarioMap) { using namespace game; forEachScenarioObject(scenarioMap, IdType::Unit, [](const IMidScenarioObject* obj) { validateUnit((CMidUnit*)obj); }); } int __stdcall loadScenarioMapHooked(int a1, game::CMidStreamEnvFile* streamEnv, game::CMidgardScenarioMap* scenarioMap) { int result = getOriginalFunctions().loadScenarioMap(a1, streamEnv, scenarioMap); // Write-mode validation is done in midUnitStreamHooked validateUnits(scenarioMap); return result; } bool __fastcall scenarioMapStreamHooked(game::CMidgardScenarioMap* scenarioMap, int /*%edx*/, game::IMidgardStreamEnv* streamEnv) { bool result = getOriginalFunctions().scenarioMapStream(scenarioMap, streamEnv); if (result && streamEnv->vftable->readMode(streamEnv)) { // Write-mode validation is done in midUnitStreamHooked validateUnits(scenarioMap); } return result; } void __stdcall getStackFortRuinGroupForChangeHooked(game::IMidgardObjectMap* objectMap, const game::CMidgardID* objectId, game::CMidUnitGroup** result) { using namespace game; auto group = getGroup(objectMap, objectId, true); if (group) { // The validation itself will be performed in midServerLogicSendObjectsChangesHooked auto& unitsToValidate = getUnitsToValidate(); const auto& units = group->units; for (auto it = units.bgn; it != units.end; it++) { unitsToValidate.insert(*it); } } *result = group; } game::CanApplyPotionResult __stdcall canApplyPotionToUnitHooked( const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId, const game::CMidgardID* groupId, const game::CMidgardID* itemId) { using namespace game; const auto& itemCategories = ItemCategories::get(); auto inventory = getInventory(objectMap, groupId); if (inventory->vftable->getItemIndex(inventory, itemId) == -1) { return CanApplyPotionResult::NoItemInInventory; } auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); auto itemBase = getGlobalItemById(objectMap, itemId); auto itemCategory = itemBase->vftable->getCategory(itemBase); if (itemCategory->id == itemCategories.potionBoost->id || itemCategory->id == itemCategories.potionPermanent->id) { if (unit->currentHp <= 0) { return CanApplyPotionResult::CannotBoostDead; } auto potionBoost = castItemToPotionBoost(itemBase); if (hasModifier(unit->unitImpl, potionBoost->vftable->getModifierId(potionBoost))) { return CanApplyPotionResult::AlreadyApplied; } } else if (itemCategory->id == itemCategories.potionHeal->id) { if (unit->currentHp <= 0) { return CanApplyPotionResult::CannotHealDead; } else if (unit->currentHp >= getUnitHpMax(unit)) { return CanApplyPotionResult::AlreadyAtFullHp; } } else if (itemCategory->id == itemCategories.potionRevive->id) { if (unit->currentHp > 0) { return CanApplyPotionResult::AlreadyAlive; } } else { return CanApplyPotionResult::NotAPotion; } return CanApplyPotionResult::Ok; } void __stdcall getUnitRequiredBuildingsHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::IUsUnit* unitImpl, game::Vector<game::TBuildingType*>* result) { using namespace game; const auto& fn = gameFunctions(); const auto& globalDataApi = GlobalDataApi::get(); const auto& intVectorApi = IntVectorApi::get(); const GlobalData* globalData = *globalDataApi.getGlobalData(); auto player = getPlayer(objectMap, playerId); const auto& units = globalData->units->map->data; const auto& buildings = (*globalData->buildings)->data; for (auto building = buildings.bgn; building != buildings.end; ++building) { for (auto unit = units.bgn; unit != units.end; ++unit) { auto racialSoldier = fn.castUnitImplToRacialSoldier(unit->second); if (racialSoldier) { auto upgradeBuildingId = racialSoldier->vftable->getUpgradeBuildingId( racialSoldier); if (*upgradeBuildingId == building->first) { auto prevUnitImplId = racialSoldier->vftable->getPrevUnitImplId(racialSoldier); if (*prevUnitImplId == unitImpl->id) { if (!player || lordHasBuilding(&player->lordId, &building->first)) { intVectorApi.pushBack((IntVector*)result, (int*)&building->second); } } } } } } } const game::TUsUnitImpl* __stdcall getUpgradeUnitImplCheckXpHooked( const game::IMidgardObjectMap* objectMap, const game::CMidUnit* unit) { using namespace game; const auto& fn = gameFunctions(); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); if (unit->currentXp < soldier->vftable->getXpNext(soldier)) { return nullptr; } return getUpgradeUnitImpl(objectMap, getPlayerByUnitId(objectMap, &unit->id), unit); } bool __stdcall changeUnitXpCheckUpgradeHooked(game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* unitId, int amount) { using namespace game; const auto& fn = gameFunctions(); const auto& visitors = VisitorApi::get(); auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); int xpNext = soldier->vftable->getXpNext(soldier); int xpAmount = amount; if (unit->currentXp + xpAmount >= xpNext) { if (!getUpgradeUnitImpl(objectMap, getPlayer(objectMap, playerId), unit)) { xpAmount = xpNext - unit->currentXp - 1; } } return visitors.changeUnitXp(unitId, xpAmount, objectMap, 1); } bool __stdcall isUnitTierMaxHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* unitId) { using namespace game; const auto& fn = gameFunctions(); if (fn.isPlayerRaceUnplayable(playerId, objectMap)) { return true; } auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); if (unit->dynLevel) { return true; } if (!canUnitGainXp(unit->unitImpl)) { return true; } if (hasMaxTierUpgradeBuilding(objectMap, unit->unitImpl)) { return true; } return hasNextTierUnitImpl(unit->unitImpl) == false; } bool __stdcall isUnitLevelNotMaxHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* unitId) { // Originally calls isUnitTierMax, but it is already getting called before this function // everywhere in the game code, so the excessive call is removed from here. using namespace game; const auto& fn = gameFunctions(); auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); if (!canUnitGainXp(unit->unitImpl)) { return false; } auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); auto soldierLevel = soldier->vftable->getLevel(soldier); if (soldierLevel == getGeneratedUnitImplLevelMax()) { return false; } auto stackLeader = fn.castUnitImplToStackLeader(unit->unitImpl); if (stackLeader) { auto scenarioInfo = getScenarioInfo(objectMap); if (!scenarioInfo) { return false; } return soldierLevel < scenarioInfo->leaderMaxLevel; } return soldierLevel < *gameRestrictions().unitMaxLevel; } bool __stdcall isUnitUpgradePendingHooked(const game::CMidgardID* unitId, const game::IMidgardObjectMap* objectMap) { using namespace game; const auto& fn = gameFunctions(); auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); if (unit->currentXp == soldier->vftable->getXpNext(soldier) - 1) { auto playerId = getPlayerIdByUnitId(objectMap, unitId); if (fn.isUnitLevelNotMax(objectMap, &playerId, unitId)) { return getUpgradeUnitImpl(objectMap, getPlayer(objectMap, &playerId), unit) == nullptr; } } return false; } bool __fastcall editBoxIsCharValidHooked(const game::EditBoxData* thisptr, int /*%edx*/, char character) { using namespace game; // Cast to int using unsigned char // so extended symbols (>= 127) are handled correctly by isalpha() const int ch = static_cast<unsigned char>(character); if (!(ch && ch != VK_ESCAPE && (thisptr->allowEnter || ch != '\n' && ch != '\r'))) { return false; } // clang-format off // These characters are language specific and depend on actual code page being used. // For example, in cp-1251 they will represent Russian alphabet. // They are hardcoded in game and should work fine on different code pages // such as cp-1250, cp-1251 static const unsigned char languageSpecific[] = { 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xA8, 0xB8, // This allows players to enter 'io' (U+0451) and 'IO' (U+0401) in cp-1251 0 }; // clang-format on if (thisptr->filter == EditFilter::TextOnly) { if (isalpha(ch) || isspace(ch)) { return true; } // Check if ch is language specific character if (strchr(reinterpret_cast<const char*>(languageSpecific), ch)) { return true; } return false; } if (thisptr->filter >= EditFilter::AlphaNum) { if (thisptr->filter == EditFilter::DigitsOnly) { return isdigit(ch) != 0; } if (thisptr->filter >= EditFilter::AlphaNumNoSlash) { if (thisptr->filter >= EditFilter::NamesDot) { if (thisptr->filter == EditFilter::NamesDot) { return true; } if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') && ch != ' ' && ch != '\\' && ch != '_' && ch != '-') { return false; } return true; } if (iscntrl(ch)) { return false; } if (!strchr("/?*\"<>|+':\\", ch)) { return true; } return false; } if (iscntrl(ch)) { return false; } if (!strchr("/?*\"<>|+'", ch)) { return true; } return false; } // Remove two symbols from forbidden list. // This allows players to enter 'io' (U+0451) and 'IO' (U+0401) in cp-1251 static const char forbiddenSymbols[] = {'`', '^', '~', /* 0xA8, 0xB8, */ 0}; if (!strchr(forbiddenSymbols, ch)) { if (isalpha(ch) || isdigit(ch) || isspace(ch) || ispunct(ch)) { return true; } if (strchr(reinterpret_cast<const char*>(languageSpecific), ch)) { return true; } return false; } return false; } // Conditions should be checked from most critical to less critical to provide correct flow of unit // upgrades, AI building decisions and UI messages game::BuildingStatus __stdcall getBuildingStatusHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* buildingId, bool ignoreBuildTurnAndCost) { using namespace game; auto player = getPlayer(objectMap, playerId); if (playerHasBuilding(objectMap, player, buildingId)) { return BuildingStatus::AlreadyBuilt; } auto building = getBuilding(buildingId); auto scenarioInfo = getScenarioInfo(objectMap); if (getBuildingLevel(building) > scenarioInfo->unitMaxTier) { return BuildingStatus::ExceedsMaxLevel; } if (!lordHasBuilding(&player->lordId, buildingId)) { return BuildingStatus::LordHasNoBuilding; } if (playerHasSiblingUnitBuilding(objectMap, player, building)) { return BuildingStatus::PlayerHasSiblingUnitBuilding; } auto requiredId = building->data->requiredId; if (requiredId != emptyId && !playerHasBuilding(objectMap, player, &requiredId)) { return BuildingStatus::PlayerHasNoRequiredBuilding; } if (!ignoreBuildTurnAndCost) { if (player->bank < building->data->cost) { return BuildingStatus::InsufficientBank; } if (player->constructionTurn == scenarioInfo->currentTurn) { return BuildingStatus::PlayerAlreadyBuiltThisDay; } } return BuildingStatus::CanBeBuilt; } } // namespace hooks
101,118
C++
.cpp
2,016
40.889385
179
0.674865
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,900
attackmodified.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/attackmodified.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "attackmodified.h" #include "version.h" #include <array> namespace game::CAttackModifiedApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5aa0ca, (Api::CopyConstructor)0x5aa1cb, (Api::Wrap)0x5aa317, }, // Russobit Api{ (Api::Constructor)0x5aa0ca, (Api::CopyConstructor)0x5aa1cb, (Api::Wrap)0x5aa317, }, // Gog Api{ (Api::Constructor)0x5a9352, (Api::CopyConstructor)0x5a9453, (Api::Wrap)0x5a959f, }, // Scenario Editor Api{ (Api::Constructor)0x55142b, (Api::CopyConstructor)0x55152c, (Api::Wrap)0x551678, }, }}; static std::array<IAttackVftable*, 4> vftables = {{ // Akella (IAttackVftable*)0x6ed69c, // Russobit (IAttackVftable*)0x6ed69c, // Gog (IAttackVftable*)0x6eb63c, // Scenario Editor (IAttackVftable*)0x5e17e4, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const IAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CAttackModifiedApi
2,013
C++
.cpp
69
25.15942
72
0.691791
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,901
netmsg.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netmsg.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netmsg.h" #include "version.h" #include <array> namespace game::CNetMsgApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Destructor)0x55cc83, }, // Russobit Api{ (Api::Destructor)0x55cc83, }, // Gog Api{ (Api::Destructor)0x55c470, }, // Scenario Editor Api{ (Api::Destructor)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } // clang-format off static std::array<CNetMsgVftable*, 4> vftables = {{ // Akella (CNetMsgVftable*)0x6e67c4, // Russobit (CNetMsgVftable*)0x6e67c4, // Gog (CNetMsgVftable*)0x6e4764, // Scenario Editor (CNetMsgVftable*)nullptr, }}; // clang-format on CNetMsgVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CNetMsgApi
1,740
C++
.cpp
63
24.333333
72
0.699401
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,902
generationresultinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/generationresultinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "generationresultinterf.h" #include "autodialog.h" #include "button.h" #include "dialoginterf.h" #include "image2memory.h" #include "mempool.h" #include "menubase.h" #include "menurandomscenario.h" #include "multilayerimg.h" #include "pictureinterf.h" namespace hooks { static void __fastcall acceptButtonHandler(CGenerationResultInterf* thisptr, int /* %edx */) { thisptr->onAccept(thisptr->menu); } static void __fastcall rejectButtonHandler(CGenerationResultInterf* thisptr, int /* %edx */) { thisptr->onReject(thisptr->menu); } static void __fastcall cancelButtonHandler(CGenerationResultInterf* thisptr, int /* %edx */) { thisptr->onCancel(thisptr->menu); } static int pixelIndex(int x, int y, int size, float scaleFactor = 1.0f) { const int i = static_cast<int>(x / scaleFactor); const int j = static_cast<int>(y / scaleFactor); return i + size * j; } static CImage2Memory* createPreviewImage(CMenuRandomScenario* menu) { using namespace game; const int size = menu->scenario->size; const int width = size; const int height = size; const int previewSize = 144; const float scaleFactor = static_cast<float>(previewSize) / static_cast<float>(size); CImage2Memory* preview = createImage2Memory(previewSize, previewSize); rsg::MapGenerator* generator{menu->generator.get()}; // Each pixel represents map tile that is colored according to its zone std::vector<Color> tileColoring(width * height); for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { rsg::Position pos{i, j}; static const Color colors[] = { Color{255, 0, 0, 255}, // Zone id 0: red Color{0, 255, 0, 255}, // 1: green Color{0, 0, 255, 255}, // 2: blue Color{255, 255, 255, 255}, // 3: white Color{0, 0, 0, 255}, // 4: black Color{127, 127, 127, 255}, // 5: gray Color{255, 255, 0, 255}, // 6: yellow Color{0, 255, 255, 255}, // 7: cyan Color{255, 0, 255, 255}, // 8: magenta Color{255, 153, 0, 255}, // 9: orange Color{0, 158, 10, 255}, // 10: dark green Color{0, 57, 158, 255}, // 11: dark blue Color{158, 57, 0, 255}, // 12: dark red }; const int index{pixelIndex(i, j, width)}; const auto zoneId{generator->zoneColoring[generator->posToIndex(pos)]}; const int colorsTotal{static_cast<int>(std::size(colors))}; if (zoneId < colorsTotal) { tileColoring[index] = colors[zoneId]; } else { const std::uint8_t c = 32 + 10 * (zoneId - colorsTotal); tileColoring[index] = Color(c, c, c, 255); } } } // Scale tile coloring up to 144 x 144 pixels. // It is better to show preview images of the same size regardless of scenario size for (int i = 0; i < previewSize; ++i) { for (int j = 0; j < previewSize; ++j) { const int sourceIndex{pixelIndex(i, j, size, scaleFactor)}; const int destIndex{pixelIndex(i, j, previewSize)}; preview->pixels[destIndex] = tileColoring[sourceIndex]; } } return preview; } CGenerationResultInterf* createGenerationResultInterf(CMenuRandomScenario* menu, OnGenerationResultAccepted onAccept, OnGenerationResultRejected onReject, OnGenerationResultCanceled onCancel) { using namespace game; static const char dialogName[] = "DLG_GENERATION_RESULT"; const auto& allocateMemory = Memory::get().allocate; auto popup = (CGenerationResultInterf*)allocateMemory(sizeof(CGenerationResultInterf)); CPopupDialogInterfApi::get().constructor(popup, dialogName, nullptr); popup->onAccept = onAccept; popup->onReject = onReject; popup->onCancel = onCancel; popup->menu = menu; CDialogInterf* dialog{*popup->dialog}; using ButtonCallback = CMenuBaseApi::Api::ButtonCallback; const auto& createButtonFunctor = CMenuBaseApi::get().createButtonFunctor; const auto& assignFunctor = CButtonInterfApi::get().assignFunctor; const auto& smartPtrFree = SmartPointerApi::get().createOrFreeNoDtor; SmartPointer functor; { auto callback = (ButtonCallback)acceptButtonHandler; createButtonFunctor(&functor, 0, (CMenuBase*)popup, &callback); assignFunctor(dialog, "BTN_ACCEPT", dialogName, &functor, 0); smartPtrFree(&functor, nullptr); } { auto callback = (ButtonCallback)rejectButtonHandler; createButtonFunctor(&functor, 0, (CMenuBase*)popup, &callback); assignFunctor(dialog, "BTN_REJECT", dialogName, &functor, 0); smartPtrFree(&functor, nullptr); } { auto callback = (ButtonCallback)cancelButtonHandler; createButtonFunctor(&functor, 0, (CMenuBase*)popup, &callback); assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); smartPtrFree(&functor, nullptr); } { IMqImage2* border = AutoDialogApi::get().loadImage("ZONES_BORDER"); CImage2Memory* preview = createPreviewImage(menu); CMultiLayerImg* image{(CMultiLayerImg*)allocateMemory(sizeof(CMultiLayerImg))}; const auto& multilayerApi{CMultiLayerImgApi::get()}; multilayerApi.constructor(image); // Make sure preview is inside border image const int borderOffset = 7; multilayerApi.addImage(image, border, -999, -999); multilayerApi.addImage(image, preview, borderOffset, borderOffset); CPictureInterf* zonesImage = CDialogInterfApi::get().findPicture(dialog, "IMG_ZONES"); CMqPoint offset{}; CPictureInterfApi::get().setImage(zonesImage, image, &offset); } return popup; } } // namespace hooks
6,901
C++
.cpp
154
37.123377
94
0.648181
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,903
interfaceutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/interfaceutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "interfaceutils.h" #include "attackclasscat.h" #include "attacksourcecat.h" #include "borderedimg.h" #include "categorylist.h" #include "customattacks.h" #include "encunitdescriptor.h" #include "leaderunitdescriptor.h" #include "mempool.h" #include "midunit.h" #include "midunitdescriptor.h" #include "mqimage2.h" #include "pictureinterf.h" #include "settings.h" #include "textids.h" #include "unittypedescriptor.h" #include "unitutils.h" #include "usunitimpl.h" #include "utils.h" #include <editor.h> #include <fmt/format.h> namespace hooks { const game::CMidUnitDescriptor* castToMidUnitDescriptor(const game::IEncUnitDescriptor* descriptor) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (const game::CMidUnitDescriptor*)dynamicCast(descriptor, 0, rtti.IEncUnitDescriptorType, rtti.CMidUnitDescriptorType, 0); } const game::CUnitTypeDescriptor* castToUnitTypeDescriptor( const game::IEncUnitDescriptor* descriptor) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (const game::CUnitTypeDescriptor*)dynamicCast(descriptor, 0, rtti.IEncUnitDescriptorType, rtti.CUnitTypeDescriptorType, 0); } const game::CLeaderUnitDescriptor* castToLeaderUnitDescriptor( const game::IEncUnitDescriptor* descriptor) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; return (const game::CLeaderUnitDescriptor*)dynamicCast(descriptor, 0, rtti.IEncUnitDescriptorType, rtti.CLeaderUnitDescriptorType, 0); } const game::TUsUnitImpl* getUnitImpl(const game::IEncUnitDescriptor* descriptor) { auto midUnitDescriptor = castToMidUnitDescriptor(descriptor); if (midUnitDescriptor) { return getUnitImpl(midUnitDescriptor->unit->unitImpl); } auto unitTypeDescriptor = castToUnitTypeDescriptor(descriptor); if (unitTypeDescriptor) { return getUnitImpl(&unitTypeDescriptor->unitImplId); } auto leaderUnitDescriptor = castToLeaderUnitDescriptor(descriptor); if (leaderUnitDescriptor) { const auto& data = leaderUnitDescriptor->data; return generateUnitImpl(&data.globalUnitImplId, data.level); } // Should not happen as base game only have 3 descendants of IEncUnitDescriptor return nullptr; } bool hasCriticalHitLeaderAbility(const game::IEncUnitDescriptor* descriptor) { using namespace game; const auto& categoryListApi = CategoryListApi::get(); if (!descriptor->vftable->isUnitLeader(descriptor)) { return false; } List<LLeaderAbility> abilities{}; categoryListApi.constructor((CategoryList*)&abilities); descriptor->vftable->getLeaderAbilities(descriptor, &abilities); bool result = false; for (const auto& ability : abilities) { if (ability.id == LeaderAbilityCategories::get().criticalHit->id) { result = true; break; } } categoryListApi.clear((CategoryList*)&abilities); categoryListApi.freeNode((CategoryList*)&abilities, (CategoryListNode*)abilities.head); return result; } std::string getNumberText(int value, bool percent) { return fmt::format(percent ? "{:d}%" : "{:d}", value); } std::string getBonusNumberText(int bonus, bool percent, bool reverse) { if (!bonus) { return ""; } bool positive = reverse ? bonus < 0 : bonus > 0; std::string result; if (positive) { result = getInterfaceText(textIds().interf.positiveBonusNumber.c_str()); if (result.empty()) result = "\\c025;090;000;%SIGN% %NUMBER%\\c000;000;000;"; } else { result = getInterfaceText(textIds().interf.negativeBonusNumber.c_str()); if (result.empty()) result = "\\c100;000;000;%SIGN% %NUMBER%\\c000;000;000;"; } replace(result, "%SIGN%", bonus > 0 ? "+" : "-"); replace(result, "%NUMBER%", getNumberText(abs(bonus), percent)); return result; } std::string addBonusNumberText(const std::string& base, int bonus, bool percent, bool reverse) { auto result = getInterfaceText(textIds().interf.modifiedNumber.c_str()); if (result.empty()) result = "%NUMBER% %BONUS%"; replace(result, "%NUMBER%", base); replace(result, "%BONUS%", getBonusNumberText(bonus, percent, reverse)); return result; } static std::string getModifiedNumberText(int value, int base, bool percent, bool reverse, bool full) { int bonus = value - base; if (!bonus) { return getNumberText(base, percent); } if (!base && !full) { return getBonusNumberText(bonus, percent, reverse); } auto result = getNumberText(base, percent); return addBonusNumberText(result, bonus, percent, reverse); } std::string getModifiedNumberText(int value, int base, bool percent) { return getModifiedNumberText(value, base, percent, false, false); } std::string getModifiedNumberTextFull(int value, int base, bool percent) { return getModifiedNumberText(value, base, percent, false, true); } std::string getModifiedNumberTextReverseBonus(int value, int base, bool percent) { return getModifiedNumberText(value, base, percent, true, false); } static std::string getModifiedNumberTextTotal(int value, int base, bool percent, bool reverse) { int bonus = value - base; if (!bonus) { return getNumberText(base, percent); } auto result = getInterfaceText(textIds().interf.modifiedNumberTotal.c_str()); if (result.empty()) result = "%TOTAL% (%BONUS%)"; replace(result, "%TOTAL%", getNumberText(value, percent)); replace(result, "%BONUS%", getBonusNumberText(bonus, percent, reverse)); return result; } std::string getModifiedNumberTextTotal(int value, int base, bool percent) { return getModifiedNumberTextTotal(value, base, percent, false); } std::string getModifiedNumberTextTotalReverseBonus(int value, int base, bool percent) { return getModifiedNumberTextTotal(value, base, percent, true); } std::string getModifiedStringText(const std::string& value, bool modified) { if (!modified) return value; auto result = getInterfaceText(textIds().interf.modifiedValue.c_str()); if (result.empty()) result = "\\c025;090;000;%VALUE%\\c000;000;000;"; replace(result, "%VALUE%", value); return result; } std::string getRemovedAttackWardText(const std::string& value) { auto result = getInterfaceText(textIds().interf.removedAttackWard.c_str(), "\\fMedBold;\\c100;000;000;%WARD%\\c000;000;000;\\fNormal;"); replace(result, "%WARD%", value); return result; } std::string getAttackSourceText(const game::LAttackSource* source) { // Spell can have no source if (!source) return getInterfaceText("X005TA0473"); // "None" return getAttackSourceText(source->id); } std::string getAttackSourceText(game::AttackSourceId id) { using namespace game; const auto& sources = AttackSourceCategories::get(); if (id == sources.weapon->id) return getInterfaceText("X005TA0145"); // "Weapon" else if (id == sources.mind->id) return getInterfaceText("X005TA0146"); // "Mind" else if (id == sources.life->id) return getInterfaceText("X005TA0147"); // "Life" else if (id == sources.death->id) return getInterfaceText("X005TA0148"); // "Death" else if (id == sources.fire->id) return getInterfaceText("X005TA0149"); // "Fire" else if (id == sources.water->id) return getInterfaceText("X005TA0150"); // "Water" else if (id == sources.air->id) return getInterfaceText("X005TA0151"); // "Air" else if (id == sources.earth->id) return getInterfaceText("X005TA0152"); // "Earth" else { for (const auto& custom : getCustomAttacks().sources) { if (id == custom.source.id) return getInterfaceText(custom.nameId.c_str()); } } return ""; } std::string getAttackClassText(game::AttackClassId id) { using namespace game; const auto& classes = AttackClassCategories::get(); if (id == classes.paralyze->id) return getInterfaceText("X005TA0789"); else if (id == classes.petrify->id) return getInterfaceText("X005TA0790"); else if (id == classes.damage->id) return getInterfaceText("X005TA0791"); else if (id == classes.drain->id) return getInterfaceText("X005TA0792"); else if (id == classes.heal->id) return getInterfaceText("X005TA0793"); else if (id == classes.fear->id) return getInterfaceText("X005TA0794"); else if (id == classes.boostDamage->id) return getInterfaceText("X005TA0795"); else if (id == classes.lowerDamage->id) return getInterfaceText("X005TA0796"); else if (id == classes.lowerInitiative->id) return getInterfaceText("X005TA0797"); else if (id == classes.poison->id) return getInterfaceText("X005TA0798"); else if (id == classes.frostbite->id) return getInterfaceText("X005TA0799"); else if (id == classes.blister->id) return getInterfaceText("X160TA0012"); else if (id == classes.bestowWards->id) return getInterfaceText("X160TA0014"); else if (id == classes.shatter->id) return getInterfaceText("X160TA0020"); else if (id == classes.revive->id) return getInterfaceText("X005TA0800"); else if (id == classes.drainOverflow->id) return getInterfaceText("X005TA0801"); else if (id == classes.cure->id) return getInterfaceText("X005TA0802"); else if (id == classes.summon->id) return getInterfaceText("X005TA0803"); else if (id == classes.drainLevel->id) return getInterfaceText("X005TA0804"); else if (id == classes.giveAttack->id) return getInterfaceText("X005TA0805"); else if (id == classes.doppelganger->id) return getInterfaceText("X005TA0806"); else if (id == classes.transformSelf->id) return getInterfaceText("X005TA0807"); else if (id == classes.transformOther->id) return getInterfaceText("X005TA0808"); return ""; } bool getDynUpgradesToDisplay(game::IEncUnitDescriptor* descriptor, const game::CDynUpgrade** upgrade1, const game::CDynUpgrade** upgrade2) { using namespace game; if (!userSettings().unitEncyclopedia.displayDynamicUpgradeValues) { return false; } if (!descriptor->vftable->isUnitType(descriptor)) { return false; } CMidgardID globalUnitImplId; descriptor->vftable->getGlobalUnitImplId(descriptor, &globalUnitImplId); auto globalUnitImpl = getUnitImpl(&globalUnitImplId); *upgrade1 = getDynUpgrade(globalUnitImpl, 1); *upgrade2 = getDynUpgrade(globalUnitImpl, 2); return *upgrade1 && *upgrade2; } void addDynUpgradeLevelToField(std::string& text, const char* field, int level) { auto result = getInterfaceText(textIds().interf.dynamicUpgradeLevel.c_str()); if (result.empty()) { result = "%STAT% (level-ups weaken at %UPGLV%)"; } replace(result, "%STAT%", field); replace(result, "%UPGLV%", fmt::format("{:d}", level)); replace(text, field, result); } void addDynUpgradeTextToField(std::string& text, const char* field, int upgrade1, int upgrade2) { if (!upgrade1 && !upgrade2) { return; } auto result = getInterfaceText(textIds().interf.dynamicUpgradeValues.c_str()); if (result.empty()) { result = "%STAT% (%UPG1% | %UPG2% per level)"; } replace(result, "%STAT%", field); replace(result, "%UPG1%", fmt::format("{:+d}", upgrade1)); replace(result, "%UPG2%", fmt::format("{:+d}", upgrade2)); replace(text, field, result); } void setCenteredImage(game::CPictureInterf* picture, game::IMqImage2* image) { using namespace game; const auto& pictureApi = CPictureInterfApi::get(); auto pictureArea = picture->vftable->getArea(picture); CMqPoint pictureSize{pictureArea->right - pictureArea->left, pictureArea->bottom - pictureArea->top}; CMqPoint imageSize{}; image->vftable->getSize(image, &imageSize); CMqPoint offset{(pictureSize.x - imageSize.x) / 2, (pictureSize.y - imageSize.y) / 2}; pictureApi.setImage(picture, image, &offset); } game::CBorderedImg* createBorderedImage(game::IMqImage2* image, game::BorderType borderType) { using namespace game; const auto& borderedImgApi = CBorderedImgApi::get(); auto memAlloc = Memory::get().allocate; auto result = (CBorderedImg*)memAlloc(sizeof(CBorderedImg)); borderedImgApi.constructor(result, borderType); borderedImgApi.addImage(result, image); return result; } } // namespace hooks
13,968
C++
.cpp
353
33.917847
100
0.687865
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,904
roompasswordinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/roompasswordinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "roompasswordinterf.h" #include "button.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "log.h" #include "mempool.h" #include "menubase.h" #include "menucustomlobby.h" #include "popupdialoginterf.h" #include "textids.h" #include "utils.h" namespace hooks { struct CRoomPasswordInterf : public game::CPopupDialogInterf { RoomPasswordHandler onSuccess; RoomPasswordHandler onCancel; CMenuCustomLobby* menuLobby; }; static void closeRoomPasswordInterf(CRoomPasswordInterf* interf) { hideInterface(interf); interf->vftable->destructor(interf, 1); } static void cancelRoomPasswordInput(CRoomPasswordInterf* interf) { interf->onCancel(interf->menuLobby); closeRoomPasswordInterf(interf); } static void __fastcall onOkPressed(CRoomPasswordInterf* thisptr, int /*%edx*/) { logDebug("lobby.log", "User tries to enter room password"); using namespace game; auto& dialogApi = CDialogInterfApi::get(); auto dialog = *thisptr->dialog; auto pwdEdit = dialogApi.findEditBox(dialog, "EDIT_PASSWORD"); if (!pwdEdit) { logDebug("lobby.log", "Edit password ui element not found"); cancelRoomPasswordInput(thisptr); return; } const auto& pwdString = pwdEdit->data->editBoxData.inputString; const char* password = pwdString.string ? pwdString.string : ""; auto menuLobby = thisptr->menuLobby; if (customLobbyCheckRoomPassword(menuLobby, password)) { auto onSuccess = thisptr->onSuccess; // Close menu and _then_ run success logic closeRoomPasswordInterf(thisptr); onSuccess(menuLobby); } else { auto message{getInterfaceText(textIds().lobby.wrongRoomPassword.c_str())}; if (message.empty()) { message = "Wrong room password"; } showMessageBox(message); } } static void __fastcall onCancelPressed(CRoomPasswordInterf* thisptr, int /*%edx*/) { logDebug("lobby.log", "User canceled room password input"); cancelRoomPasswordInput(thisptr); } static CRoomPasswordInterf* createRoomPasswordInterf(CMenuCustomLobby* menuLobby, RoomPasswordHandler onSuccess, RoomPasswordHandler onCancel) { using namespace game; static const char dialogName[]{"DLG_ROOM_PASSWORD"}; auto interf = (CRoomPasswordInterf*)Memory::get().allocate(sizeof(CRoomPasswordInterf)); CPopupDialogInterfApi::get().constructor(interf, dialogName, nullptr); interf->onSuccess = onSuccess; interf->onCancel = onCancel; interf->menuLobby = menuLobby; const auto createFunctor = CMenuBaseApi::get().createButtonFunctor; const auto assignFunctor = CButtonInterfApi::get().assignFunctor; const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; auto& dialogApi = CDialogInterfApi::get(); auto dialog = *interf->dialog; SmartPointer functor; auto callback = (CMenuBaseApi::Api::ButtonCallback)onCancelPressed; createFunctor(&functor, 0, (CMenuBase*)interf, &callback); assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)onOkPressed; createFunctor(&functor, 0, (CMenuBase*)interf, &callback); assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); freeFunctor(&functor, nullptr); return interf; } void showRoomPasswordDialog(CMenuCustomLobby* menuLobby, RoomPasswordHandler onSuccess, RoomPasswordHandler onCancel) { showInterface(createRoomPasswordInterf(menuLobby, onSuccess, onCancel)); } } // namespace hooks
4,551
C++
.cpp
113
35.00885
92
0.721404
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,905
main.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/main.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma comment(lib, "detours.lib") #include "customattacks.h" #include "custommodifiers.h" #include "hooks.h" #include "log.h" #include "restrictions.h" #include "settings.h" #include "unitsforhire.h" #include "utils.h" #include "version.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <detours.h> #include <fmt/format.h> #include <string> #include <thread> static HMODULE library{}; static void* registerInterface{}; static void* unregisterInterface{}; std::thread::id mainThreadId; extern "C" __declspec(naked) void __stdcall RIB_register_interface(void) { __asm { jmp registerInterface; } } extern "C" __declspec(naked) void __stdcall RIB_unregister_interface(void) { __asm { jmp unregisterInterface; } } template <typename T> static void writeProtectedMemory(T* address, T value) { DWORD oldProtection{}; if (VirtualProtect(address, sizeof(T), PAGE_EXECUTE_READWRITE, &oldProtection)) { *address = value; VirtualProtect(address, sizeof(T), oldProtection, &oldProtection); return; } hooks::logError("mssProxyError.log", fmt::format("Failed to change memory protection for {:p}", (void*)address)); } template <typename T> static void adjustRestrictionMax(game::Restriction<T>* restriction, const T& value, const char* name) { if (value >= restriction->min) { hooks::logDebug("restrictions.log", fmt::format("Set '{:s}' to {:d}", name, value)); writeProtectedMemory(&restriction->max, value); return; } hooks::logError( "mssProxyError.log", fmt::format( "User specified '{:s}' value of {:d} is less than minimum value allowed in game ({:d}). " "Change rejected.", name, value, restriction->min)); } static void adjustGameRestrictions() { using namespace hooks; auto& restrictions = game::gameRestrictions(); // Allow game to load and scenario editor to create scenarios with maximum allowed spells level // set to zero, disabling usage of magic in scenario writeProtectedMemory(&restrictions.spellLevel->min, 0); // Allow using units with tier higher than 5 writeProtectedMemory(&restrictions.unitTier->max, 10); if (userSettings().unitMaxDamage != baseSettings().unitMaxDamage) { adjustRestrictionMax(restrictions.attackDamage, userSettings().unitMaxDamage, "UnitMaxDamage"); } if (userSettings().unitMaxArmor != baseSettings().unitMaxArmor) { adjustRestrictionMax(restrictions.unitArmor, userSettings().unitMaxArmor, "UnitMaxArmor"); } if (userSettings().stackScoutRangeMax != baseSettings().stackScoutRangeMax) { adjustRestrictionMax(restrictions.stackScoutRange, userSettings().stackScoutRangeMax, "StackMaxScoutRange"); } if (executableIsGame()) { if (userSettings().criticalHitDamage != baseSettings().criticalHitDamage) { logDebug("restrictions.log", fmt::format("Set 'criticalHitDamage' to {:d}", (int)userSettings().criticalHitDamage)); writeProtectedMemory(restrictions.criticalHitDamage, userSettings().criticalHitDamage); } if (userSettings().mageLeaderAttackPowerReduction != baseSettings().mageLeaderAttackPowerReduction) { logDebug("restrictions.log", fmt::format("Set 'mageLeaderPowerReduction' to {:d}", (int)userSettings().mageLeaderAttackPowerReduction)); writeProtectedMemory(restrictions.mageLeaderAttackPowerReduction, userSettings().mageLeaderAttackPowerReduction); } } } static bool setupHook(hooks::HookInfo& hook) { hooks::logDebug("mss32Proxy.log", fmt::format("Try to attach hook. Function {:p}, hook {:p}.", hook.target, hook.hook)); // hook.original is an optional field that can point to where the new address of the original // function should be placed. void** pointer = hook.original ? hook.original : (void**)&hook.original; *pointer = hook.target; auto result = DetourAttach(pointer, hook.hook); if (result != NO_ERROR) { const std::string msg{ fmt::format("Failed to attach hook. Function {:p}, hook {:p}. Error code: {:d}.", hook.target, hook.hook, result)}; hooks::logError("mssProxyError.log", msg); MessageBox(NULL, msg.c_str(), "mss32.dll proxy", MB_OK); return false; } return true; } static bool setupHooks() { auto hooks{hooks::getHooks()}; DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); for (auto& hook : hooks) { if (!setupHook(hook)) { return false; } } const auto result = DetourTransactionCommit(); if (result != NO_ERROR) { const std::string msg{ fmt::format("Failed to commit detour transaction. Error code: {:d}.", result)}; hooks::logError("mssProxyError.log", msg); MessageBox(NULL, msg.c_str(), "mss32.dll proxy", MB_OK); return false; } hooks::logDebug("mss32Proxy.log", "All hooks are set"); return true; } static void setupVftableHooks() { for (const auto& hook : hooks::getVftableHooks()) { void** target = (void**)hook.target; if (hook.original) *hook.original = *target; writeProtectedMemory(target, hook.hook); } hooks::logDebug("mss32Proxy.log", "All vftable hooks are set"); } BOOL APIENTRY DllMain(HMODULE hDll, DWORD reason, LPVOID reserved) { if (reason == DLL_PROCESS_DETACH) { FreeLibrary(library); return TRUE; } if (reason != DLL_PROCESS_ATTACH) { return TRUE; } mainThreadId = std::this_thread::get_id(); library = LoadLibrary("Mss23.dll"); if (!library) { MessageBox(NULL, "Failed to load Mss23.dll", "mss32.dll proxy", MB_OK); return FALSE; } registerInterface = GetProcAddress(library, "RIB_register_interface"); unregisterInterface = GetProcAddress(library, "RIB_unregister_interface"); if (!registerInterface || !unregisterInterface) { MessageBox(NULL, "Could not load Mss23.dll addresses", "mss32.dll proxy", MB_OK); return FALSE; } DisableThreadLibraryCalls(hDll); const auto error = hooks::determineGameVersion(hooks::exePath()); if (error || hooks::gameVersion() == hooks::GameVersion::Unknown) { const std::string msg{ fmt::format("Failed to determine target exe type.\nReason: {:s}.", error.message())}; hooks::logError("mssProxyError.log", msg); MessageBox(NULL, msg.c_str(), "mss32.dll proxy", MB_OK); return FALSE; } if (hooks::executableIsGame() && !hooks::loadUnitsForHire()) { MessageBox(NULL, "Failed to load new units. Check error log for details.", "mss32.dll proxy", MB_OK); return FALSE; } adjustGameRestrictions(); setupVftableHooks(); if (!setupHooks()) { return FALSE; } // Lazy initialization is not optimal as the data can be accessed in parallel threads. // Thread sync is excessive because the data is read-only or thread-exclusive once initialized. hooks::initializeCustomAttacks(); hooks::initializeCustomModifiers(); return TRUE; }
8,412
C++
.cpp
211
32.962085
101
0.65833
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,906
nativegameinfo.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/nativegameinfo.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "nativegameinfo.h" #include "attack.h" #include "customattacks.h" #include "dbfaccess.h" #include "dbffile.h" #include "game.h" #include "generatorsettings.h" #include "globaldata.h" #include "itembase.h" #include "itemcategory.h" #include "itemtypelist.h" #include "landmark.h" #include "log.h" #include "nativeiteminfo.h" #include "nativelandmarkinfo.h" #include "nativeraceinfo.h" #include "nativespellinfo.h" #include "nativeunitinfo.h" #include "racetype.h" #include "strategicspell.h" #include "ussoldierimpl.h" #include "usstackleader.h" #include "usunitimpl.h" #include "utils.h" #include <cassert> #include <fmt/format.h> namespace hooks { /** Converts game id to scenario generator id. */ static const rsg::CMidgardID& idToRsgId(const game::CMidgardID& id) { // We can do this because their internal representations match return reinterpret_cast<const rsg::CMidgardID&>(id); } /** Converts scenario generator id to game id. */ static const game::CMidgardID& rsgIdToId(const rsg::CMidgardID& id) { // We can do this because their internal representations match return reinterpret_cast<const game::CMidgardID&>(id); } static bool isVanillaReachId(game::AttackReachId id) { return id == game::AttackReachId::All || id == game::AttackReachId::Any || id == game::AttackReachId::Adjacent; } /** Represents sum of currencies in a bank as scenario generator value */ static int bankToValue(const game::Bank& bank) { return bank.gold + bank.deathMana + bank.lifeMana + bank.infernalMana + bank.runicMana + bank.groveMana; } /** * Translates specified string according to current game locale settings. * Only 'length' characters of a specified string will be translated. */ static std::string translate(const std::string_view& string, std::uint8_t length) { // Translated string can be no longer than 'length' characters, add 1 for null terminator char buffer[std::numeric_limits<decltype(length)>::max() + 1] = {0}; std::memcpy(buffer, string.data(), std::min(string.length(), std::size_t{length})); buffer[sizeof(buffer) - 1] = '\0'; auto& oemToCharA{*game::gameFunctions().oemToCharA}; oemToCharA(buffer, buffer); return trimSpaces(buffer); } static bool readSiteText(rsg::SiteTexts& texts, const std::filesystem::path& dbFilename, bool readDescriptions = true) { texts.clear(); utils::DbfFile db; if (!db.open(dbFilename)) { logError("mssProxyError.log", fmt::format("Could not open {:s}", dbFilename.filename().string())); return false; } const utils::DbfColumn* nameColumn{db.column("NAME")}; if (!nameColumn) { return false; } const utils::DbfColumn* descColumn{db.column("DESC")}; if (!descColumn) { return false; } const std::uint8_t nameLength{nameColumn->length}; const std::uint8_t descriptionLength{descColumn->length}; const std::uint32_t recordsTotal{db.recordsTotal()}; for (std::uint32_t i = 0; i < recordsTotal; ++i) { utils::DbfRecord record; if (!db.record(record, i)) { logError("mssProxyError.log", fmt::format("Could not read record {:d} from {:s}", i, dbFilename.filename().string())); continue; } if (record.isDeleted()) { continue; } std::string name; if (!record.value(name, "NAME")) { continue; } rsg::SiteText text; text.name = translate(name, nameLength); if (readDescriptions) { std::string description; if (record.value(description, "DESC")) { text.description = translate(description, descriptionLength); } } texts.emplace_back(std::move(text)); } return true; } NativeGameInfo::NativeGameInfo(const std::filesystem::path& gameFolderPath) { if (!readGameInfo(gameFolderPath)) { throw std::runtime_error("Could not read game info"); } } const rsg::UnitsInfo& NativeGameInfo::getUnits() const { return unitsInfo; } const rsg::UnitInfoArray& NativeGameInfo::getLeaders() const { return leaders; } const rsg::UnitInfoArray& NativeGameInfo::getSoldiers() const { return soldiers; } int NativeGameInfo::getMinLeaderValue() const { return minLeaderValue; } int NativeGameInfo::getMaxLeaderValue() const { return maxLeaderValue; } int NativeGameInfo::getMinSoldierValue() const { return minSoldierValue; } int NativeGameInfo::getMaxSoldierValue() const { return maxSoldierValue; } const rsg::ItemsInfo& NativeGameInfo::getItemsInfo() const { return itemsInfo; } const rsg::ItemInfoArray& NativeGameInfo::getItems() const { return allItems; } const rsg::ItemInfoArray& NativeGameInfo::getItems(rsg::ItemType itemType) const { const auto it{itemsByType.find(itemType)}; if (it == itemsByType.end()) { throw std::runtime_error("Could not find items by type"); } return it->second; } const rsg::SpellsInfo& NativeGameInfo::getSpellsInfo() const { return spellsInfo; } const rsg::SpellInfoArray& NativeGameInfo::getSpells() const { return allSpells; } const rsg::SpellInfoArray& NativeGameInfo::getSpells(rsg::SpellType spellType) const { const auto it{spellsByType.find(spellType)}; if (it == spellsByType.end()) { throw std::runtime_error("Could not find spells by type"); } return it->second; } const rsg::LandmarksInfo& NativeGameInfo::getLandmarksInfo() const { return landmarksInfo; } const rsg::LandmarkInfoArray& NativeGameInfo::getLandmarks(rsg::LandmarkType landmarkType) const { const auto it{landmarksByType.find(landmarkType)}; if (it == landmarksByType.end()) { throw std::runtime_error("Could not find landmarks by type"); } return it->second; } const rsg::LandmarkInfoArray& NativeGameInfo::getLandmarks(rsg::RaceType raceType) const { const auto it{landmarksByRace.find(raceType)}; if (it == landmarksByRace.end()) { throw std::runtime_error("Could not find landmarks by race"); } return it->second; } const rsg::LandmarkInfoArray& NativeGameInfo::getMountainLandmarks() const { return mountainLandmarks; } const rsg::RacesInfo& NativeGameInfo::getRacesInfo() const { return racesInfo; } const rsg::RaceInfo& NativeGameInfo::getRaceInfo(rsg::RaceType raceType) const { for (const auto& pair : racesInfo) { if (pair.second->getRaceType() == raceType) { return *pair.second.get(); } } assert(false); throw std::runtime_error("Could not find race by type"); } const char* NativeGameInfo::getGlobalText(const rsg::CMidgardID& textId) const { return hooks::getGlobalText(rsgIdToId(textId)); } const char* NativeGameInfo::getEditorInterfaceText(const rsg::CMidgardID& textId) const { const auto it{editorInterfaceTexts.find(textId)}; if (it == editorInterfaceTexts.end()) { // Return a string that is easy to spot in the game/editor. // This should help tracking potential problem return "NOT FOUND"; } // This is fine because we don't change texts after loading // and GameInfo lives longer than scenario generator return it->second.c_str(); } const rsg::CityNames& NativeGameInfo::getCityNames() const { return cityNames; } const rsg::SiteTexts& NativeGameInfo::getMercenaryTexts() const { return mercenaryTexts; } const rsg::SiteTexts& NativeGameInfo::getMageTexts() const { return mageTexts; } const rsg::SiteTexts& NativeGameInfo::getMerchantTexts() const { return merchantTexts; } const rsg::SiteTexts& NativeGameInfo::getRuinTexts() const { return ruinTexts; } const rsg::SiteTexts& NativeGameInfo::getTrainerTexts() const { return trainerTexts; } bool NativeGameInfo::readGameInfo(const std::filesystem::path& gameFolderPath) { // Some parts of the data nedded by scenario generator is not loaded by game // Load and process it manually const std::filesystem::path scenDataFolder{gameFolderPath / "ScenData"}; const std::filesystem::path interfDataFolder{gameFolderPath / "Interf"}; return rsg::readGeneratorSettings(gameFolderPath) && readRacesInfo() && readUnitsInfo() && readItemsInfo() && readSpellsInfo() && readLandmarksInfo() && readEditorInterfaceTexts(interfDataFolder) && readCityNames(scenDataFolder) && readSiteTexts(scenDataFolder); } bool NativeGameInfo::readUnitsInfo() { unitsInfo.clear(); leaders.clear(); soldiers.clear(); minLeaderValue = std::numeric_limits<int>::max(); maxLeaderValue = std::numeric_limits<int>::min(); minSoldierValue = std::numeric_limits<int>::max(); maxSoldierValue = std::numeric_limits<int>::min(); using namespace game; const auto& fn{gameFunctions()}; const auto& idApi{CMidgardIDApi::get()}; const auto& globalApi{GlobalDataApi::get()}; const GlobalData* global{*globalApi.getGlobalData()}; const auto& units{global->units->map->data}; for (const auto* i = units.bgn; i != units.end; ++i) { const TUsUnitImpl* unitImpl{i->second}; // Ignore generated units if (idApi.getType(&unitImpl->id) == IdType::UnitGenerated) { continue; } // Check unit is a soldier const TUsSoldierImpl* soldier{(const TUsSoldierImpl*)fn.castUnitImplToSoldier(unitImpl)}; if (!soldier) { continue; } // Skip water-only units until generator supports water zones if (soldier->vftable->getWaterOnly(soldier)) { continue; } auto& unitId{idToRsgId(unitImpl->id)}; auto& raceId{idToRsgId(*soldier->vftable->getRaceId(soldier))}; auto& nameId{idToRsgId(soldier->data->name.id)}; int level{soldier->vftable->getLevel(soldier)}; int value{soldier->vftable->getXpKilled(soldier)}; rsg::SubRaceType subrace{(rsg::SubRaceType)soldier->vftable->getSubrace(soldier)->id}; const IAttack* attack{soldier->vftable->getAttackById(soldier)}; const AttackReachId reachId{attack->vftable->getAttackReach(attack)->id}; rsg::ReachType reach; if (isVanillaReachId(reachId)) { reach = (rsg::ReachType)reachId; } else { // Map custom reaches to vanilla ones (Any, All or Adjacent) // depending on 'melee' hint and max targets count. // We don't care about their actual logic const auto& customReaches{getCustomAttacks().reaches}; auto it{std::find_if(customReaches.begin(), customReaches.end(), [reachId](const CustomAttackReach& customReach) { return customReach.reach.id == reachId; })}; if (it == customReaches.end()) { // This should never happen continue; } if (it->melee) { // Melle custom reaches become 'Adjacent' reach = rsg::ReachType::Adjacent; } else { // Non-melee custom reaches with 6 max targets becomes 'All', // others are 'Any' reach = it->maxTargets == 6 ? rsg::ReachType::All : rsg::ReachType::Any; } } rsg::AttackType attackType{(rsg::AttackType)attack->vftable->getAttackClass(attack)->id}; int hp{soldier->vftable->getHitPoints(soldier)}; rsg::UnitType unitType{(rsg::UnitType)unitImpl->category.id}; int move{0}; int leadership{0}; // Get leader specifics if (unitType == rsg::UnitType::Leader) { const IUsStackLeader* stackLeader{fn.castUnitImplToStackLeader(unitImpl)}; move = stackLeader->vftable->getMovement(stackLeader); leadership = stackLeader->vftable->getLeadership(stackLeader); } bool big{!soldier->vftable->getSizeSmall(soldier)}; bool male{soldier->vftable->getSexM(soldier)}; auto unitInfo{std::make_unique<NativeUnitInfo>(unitId, raceId, nameId, level, value, unitType, subrace, reach, attackType, hp, move, leadership, big, male)}; if (unitType == rsg::UnitType::Leader) { leaders.push_back(unitInfo.get()); if (value < minLeaderValue) { minLeaderValue = value; } if (value > maxLeaderValue) { maxLeaderValue = value; } } else if (unitType == rsg::UnitType::Soldier) { soldiers.push_back(unitInfo.get()); if (value < minSoldierValue) { minSoldierValue = value; } if (value > maxSoldierValue) { maxSoldierValue = value; } } unitsInfo[unitId] = std::move(unitInfo); } return true; } bool NativeGameInfo::readItemsInfo() { itemsInfo.clear(); allItems.clear(); itemsByType.clear(); using namespace game; const GlobalData* global{*GlobalDataApi::get().getGlobalData()}; const auto& items{global->itemTypes->data->data}; for (const auto* i = items.bgn; i != items.end; ++i) { const CItemBase* item{i->second}; auto& itemId{idToRsgId(item->itemId)}; rsg::ItemType itemType{(rsg::ItemType)item->vftable->getCategory(item)->id}; const Bank* bank{item->vftable->getValue(item)}; int value{bankToValue(*bank)}; if (itemType == rsg::ItemType::Talisman) { // Talisman value is specified for a single charge, adjust it value *= 5; } auto itemInfo{std::make_unique<NativeItemInfo>(itemId, value, itemType)}; allItems.push_back(itemInfo.get()); itemsByType[itemType].push_back(itemInfo.get()); itemsInfo[itemId] = std::move(itemInfo); } return true; } bool NativeGameInfo::readSpellsInfo() { spellsInfo.clear(); allSpells.clear(); spellsByType.clear(); using namespace game; const GlobalData* global{*GlobalDataApi::get().getGlobalData()}; const auto& spells{(*global->spells)->data}; for (const auto* i = spells.bgn; i != spells.end; ++i) { const TStrategicSpell* spell{i->second}; auto& spellId{idToRsgId(spell->id)}; // Use buy cost as a spell value int value{bankToValue(spell->data->buyCost)}; int level{spell->data->level}; rsg::SpellType spellType{(rsg::SpellType)spell->data->spellCategory.id}; auto spellInfo{std::make_unique<NativeSpellInfo>(spellId, value, level, spellType)}; allSpells.push_back(spellInfo.get()); spellsByType[spellType].push_back(spellInfo.get()); spellsInfo[spellId] = std::move(spellInfo); } return true; } bool NativeGameInfo::readLandmarksInfo() { landmarksInfo.clear(); landmarksByType.clear(); landmarksByRace.clear(); mountainLandmarks.clear(); using namespace game; const GlobalData* global{*GlobalDataApi::get().getGlobalData()}; const auto& landmarks{(*global->landmarks)->data}; for (const auto* i = landmarks.bgn; i != landmarks.end; ++i) { const TLandmark* landmark{i->second}; auto& landmarkId{idToRsgId(landmark->id)}; rsg::Position size{landmark->data->size.x, landmark->data->size.y}; rsg::LandmarkType landmarkType{(rsg::LandmarkType)landmark->data->category.id}; bool mountain{landmark->data->mountain}; auto info{std::make_unique<NativeLandmarkInfo>(landmarkId, size, landmarkType, mountain)}; if (isEmpireLandmark(landmarkId)) { landmarksByRace[rsg::RaceType::Human].push_back(info.get()); } if (isClansLandmark(landmarkId)) { landmarksByRace[rsg::RaceType::Dwarf].push_back(info.get()); } if (isUndeadLandmark(landmarkId)) { landmarksByRace[rsg::RaceType::Undead].push_back(info.get()); } if (isLegionsLandmark(landmarkId)) { landmarksByRace[rsg::RaceType::Heretic].push_back(info.get()); } if (isElvesLandmark(landmarkId)) { landmarksByRace[rsg::RaceType::Elf].push_back(info.get()); } if (isNeutralLandmark(landmarkId)) { landmarksByRace[rsg::RaceType::Neutral].push_back(info.get()); } if (isMountainLandmark(landmarkId)) { mountainLandmarks.push_back(info.get()); } landmarksByType[landmarkType].push_back(info.get()); landmarksInfo[landmarkId] = std::move(info); } return true; } bool NativeGameInfo::readRacesInfo() { racesInfo.clear(); using namespace game; const GlobalData* global{*GlobalDataApi::get().getGlobalData()}; const auto& races{(*global->races)->data}; for (decltype(races.bgn) i = races.bgn; i != races.end; ++i) { const TRaceType* race{i->second}; const auto data{race->data}; auto& raceId{idToRsgId(race->id)}; auto& guardianId{idToRsgId(data->guardianUnitId)}; auto& nobleId{idToRsgId(data->nobleUnitId)}; auto raceType{static_cast<rsg::RaceType>(data->raceType.id)}; const auto& leaderNames{data->leaderNames->names}; rsg::LeaderNames names; for (const LeaderName* j = leaderNames.bgn; j != leaderNames.end; ++j) { if (j->male) { names.maleNames.emplace_back(std::string(j->name)); } else { names.femaleNames.emplace_back(std::string(j->name)); } } std::vector<rsg::CMidgardID> leaderIds; for (const CMidgardID* id = data->leaders.bgn; id != data->leaders.end; ++id) { leaderIds.emplace_back(idToRsgId(*id)); } racesInfo[raceId] = std::make_unique<NativeRaceInfo>(raceId, guardianId, nobleId, raceType, std::move(names), std::move(leaderIds)); } return true; } bool NativeGameInfo::readEditorInterfaceTexts(const std::filesystem::path& interfFolderPath) { editorInterfaceTexts.clear(); const auto dbFilePath{interfFolderPath / "TAppEdit.dbf"}; utils::DbfFile db; if (!db.open(dbFilePath)) { logError("mssProxyError.log", fmt::format("Could not open {:s}", dbFilePath.filename().string())); return false; } const utils::DbfColumn* textColumn{db.column("TEXT")}; if (!textColumn) { logError("mssProxyError.log", fmt::format("Missing 'TEXT' column in {:s}", dbFilePath.filename().string())); return false; } const std::uint8_t textLength{textColumn->length}; const std::uint32_t recordsTotal{db.recordsTotal()}; for (std::uint32_t i = 0; i < recordsTotal; ++i) { utils::DbfRecord record; if (!db.record(record, i)) { logError("mssProxyError.log", fmt::format("Could not read record {:d} from {:s}", i, dbFilePath.filename().string())); continue; } if (record.isDeleted()) { continue; } game::CMidgardID textId; if (!utils::dbRead(textId, db, i, "TXT_ID")) { continue; } std::string text; if (!record.value(text, "TEXT")) { continue; } editorInterfaceTexts[idToRsgId(textId)] = translate(text, textLength); } return true; } bool NativeGameInfo::readCityNames(const std::filesystem::path& scenDataFolderPath) { cityNames.clear(); const auto dbFilePath{scenDataFolderPath / "Cityname.dbf"}; utils::DbfFile db; if (!db.open(dbFilePath)) { logError("mssProxyError.log", fmt::format("Could not open {:s}", dbFilePath.filename().string())); return false; } const utils::DbfColumn* nameColumn{db.column("NAME")}; if (!nameColumn) { logError("mssProxyError.log", fmt::format("Missing 'NAME' column in {:s}", dbFilePath.filename().string())); return false; } const std::uint8_t textLength{nameColumn->length}; const std::uint32_t recordsTotal{db.recordsTotal()}; for (std::uint32_t i = 0; i < recordsTotal; ++i) { utils::DbfRecord record; if (!db.record(record, i)) { logError("mssProxyError.log", fmt::format("Could not read record {:d} from {:s}", i, dbFilePath.filename().string())); continue; } if (record.isDeleted()) { continue; } std::string name{}; if (!record.value(name, "NAME")) { continue; } cityNames.push_back(translate(name, textLength)); } return true; } bool NativeGameInfo::readSiteTexts(const std::filesystem::path& scenDataFolderPath) { return readSiteText(mercenaryTexts, scenDataFolderPath / "Campname.dbf") && readSiteText(mageTexts, scenDataFolderPath / "Magename.dbf") && readSiteText(merchantTexts, scenDataFolderPath / "Mercname.dbf") && readSiteText(ruinTexts, scenDataFolderPath / "Ruinname.dbf", false) && readSiteText(trainerTexts, scenDataFolderPath / "Trainame.dbf"); } } // namespace hooks
22,524
C++
.cpp
591
30.901861
99
0.647056
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,907
currency.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/currency.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "currency.h" #include "version.h" #include <array> namespace game::BankApi { // clang-format off static std::array<Api, 5> functions = {{ // Akella Api{ (Api::Add)0x58748f, (Api::Subtract)0x5873c5, (Api::Multiply)0x587559, (Api::Divide)0x58763d, (Api::Less)0x587833, (Api::Copy)0x5870dd, (Api::SetInvalid)0x5870ac, (Api::SetZero)0x5879a7, (Api::SetCurrency)0x5878bc, (Api::IsZero)0x58797e, (Api::IsValid)0x58790f, (Api::ToString)0x5872d9, (Api::FromString)0x5873ab, }, // Russobit Api{ (Api::Add)0x58748f, (Api::Subtract)0x5873c5, (Api::Multiply)0x587559, (Api::Divide)0x58763d, (Api::Less)0x587833, (Api::Copy)0x5870dd, (Api::SetInvalid)0x5870ac, (Api::SetZero)0x5879a7, (Api::SetCurrency)0x5878bc, (Api::IsZero)0x58797e, (Api::IsValid)0x58790f, (Api::ToString)0x5872d9, (Api::FromString)0x5873ab, }, // Gog Api{ (Api::Add)0x586642, (Api::Subtract)0x586578, (Api::Multiply)0x58670c, (Api::Divide)0x5867f0, (Api::Less)0x5869e6, (Api::Copy)0x586290, (Api::SetInvalid)0x58625f, (Api::SetZero)0x586b5a, (Api::SetCurrency)0x586a6f, (Api::IsZero)0x586b31, (Api::IsValid)0x586ac2, (Api::ToString)0x58648c, (Api::FromString)0x58655e, }, // Scenario Editor Api{ (Api::Add)0x52de01, (Api::Subtract)0, (Api::Multiply)0x52decb, (Api::Divide)0, (Api::Less)0x52e0bf, (Api::Copy)0x52db19, (Api::SetInvalid)0x52dae8, (Api::SetZero)0x52e233, (Api::SetCurrency)0x52e148, (Api::IsZero)0x52e20a, (Api::IsValid)0x52e19b, (Api::ToString)0x52dd15, (Api::FromString)0x52dde7, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BankApi
2,875
C++
.cpp
95
24.105263
72
0.634234
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,908
midgardplan.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midgardplan.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midgardplan.h" #include "version.h" #include <array> namespace game::CMidgardPlanApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetObjectId)0x5f685f, (Api::IsPositionContainsObjects)0x5f69ae, }, // Russobit Api{ (Api::GetObjectId)0x5f685f, (Api::IsPositionContainsObjects)0x5f69ae, }, // Gog Api{ (Api::GetObjectId)0x5f54e2, (Api::IsPositionContainsObjects)0x5f5631, }, // Scenario Editor Api{ (Api::GetObjectId)0x4e4a42, (Api::IsPositionContainsObjects)0x4e4b91, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidgardPlanApi
1,584
C++
.cpp
51
27.352941
72
0.710079
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,909
midgardmap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midgardmap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midgardmap.h" #include "version.h" #include <array> namespace game::CMidgardMapApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::ChangeTerrain)nullptr, (Api::GetGround)0x5e6f63, }, // Russobit Api{ (Api::ChangeTerrain)nullptr, (Api::GetGround)0x5e6f63, }, // Gog Api{ (Api::ChangeTerrain)nullptr, (Api::GetGround)0x5e5c78, }, // Scenario Editor Api{ (Api::ChangeTerrain)0x4e3d8d, (Api::GetGround)0x4e39f4, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidgardMapApi
1,522
C++
.cpp
51
26.137255
72
0.697817
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,910
netcustomplayerclient.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netcustomplayerclient.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netcustomplayerclient.h" #include "log.h" #include "mempool.h" #include "mqnetreception.h" #include "mqnetsystem.h" #include "netcustomplayer.h" #include "netcustomservice.h" #include "netcustomsession.h" #include "netmessages.h" #include "netmsg.h" #include "settings.h" #include "utils.h" #include <BitStream.h> #include <MessageIdentifiers.h> #include <chrono> #include <fmt/format.h> #include <mutex> #include <thread> namespace hooks { static std::mutex netMessagesMutex; void PlayerClientCallbacks::onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) { auto netSystem{playerClient->player.netSystem}; switch (type) { case ID_REMOTE_DISCONNECTION_NOTIFICATION: logDebug("playerClient.log", "Client disconnected"); break; case ID_REMOTE_CONNECTION_LOST: logDebug("playerClient.log", "Client lost connection"); break; case ID_REMOTE_NEW_INCOMING_CONNECTION: logDebug("playerClient.log", "Client connected"); break; case ID_CONNECTION_REQUEST_ACCEPTED: { logDebug("playerClient.log", "Connection request to the server was accepted"); if (netSystem) { auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); netSystem->vftable->onPlayerConnected(netSystem, (int)guidInt); } break; } case ID_NEW_INCOMING_CONNECTION: logDebug("playerClient.log", "Incoming connection"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: logDebug("playerClient.log", "Server is full"); break; case ID_DISCONNECTION_NOTIFICATION: { logDebug("playerClient.log", "Server was shut down"); if (netSystem) { netSystem->vftable->onPlayerDisconnected(netSystem, 1); } break; } case ID_CONNECTION_LOST: { logDebug("playerClient.log", "Connection with server is lost"); if (netSystem) { netSystem->vftable->onPlayerDisconnected(netSystem, 1); } break; } case 0xff: { // Game message received auto message = reinterpret_cast<const game::NetMessageHeader*>(packet->data); auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); logDebug("playerClient.log", fmt::format("Game message '{:s}' from {:x}", message->messageClassName, guidInt)); auto msg = std::make_unique<unsigned char[]>(message->length); std::memcpy(msg.get(), message, message->length); { std::lock_guard<std::mutex> messageGuard(netMessagesMutex); playerClient->messages.push_back( CNetCustomPlayerClient::IdMessagePair{std::uint32_t{guidInt}, std::move(msg)}); } auto reception = playerClient->player.netReception; if (reception) { reception->vftable->notify(reception); } break; } default: logDebug("playerClient.log", fmt::format("Packet type {:d}", static_cast<int>(type))); break; } } void __fastcall playerClientDtor(CNetCustomPlayerClient* thisptr, int /*%edx*/, char flags) { playerLog("CNetCustomPlayerClient d-tor"); thisptr->~CNetCustomPlayerClient(); if (flags & 1) { playerLog("CNetCustomPlayerClient d-tor frees memory"); game::Memory::get().freeNonZero(thisptr); } } game::String* __fastcall playerClientGetName(CNetCustomPlayerClient* thisptr, int /*%edx*/, game::String* string) { playerLog("CNetCustomPlayerClient getName"); thisptr->player.vftable->getName(&thisptr->player, string); return string; } int __fastcall playerClientGetNetId(CNetCustomPlayerClient* thisptr, int /*%edx*/) { playerLog("CNetCustomPlayerClient getNetId"); return thisptr->player.vftable->getNetId(&thisptr->player); } game::IMqNetSession* __fastcall playerClientGetSession(CNetCustomPlayerClient* thisptr, int /*%edx*/) { playerLog("CNetCustomPlayerClient getSession"); return thisptr->player.vftable->getSession(&thisptr->player); } int __fastcall playerClientGetMessageCount(CNetCustomPlayerClient* thisptr, int /*%edx*/) { playerLog("CNetCustomPlayerClient getMessageCount"); std::lock_guard<std::mutex> messageGuard(netMessagesMutex); return static_cast<int>(thisptr->messages.size()); } bool __fastcall playerClientSendMessage(CNetCustomPlayerClient* thisptr, int /*%edx*/, int idTo, const game::NetMessageHeader* message) { auto peer = thisptr->getPeer(); if (!peer) { playerLog("CNetCustomPlayerClient could not send message, peer is nullptr"); return false; } auto serverGuid = peer->GetGuidFromSystemAddress(thisptr->serverAddress); auto serverId = SLNet::RakNetGUID::ToUint32(serverGuid); playerLog( fmt::format("CNetCustomPlayerClient {:s} sendMessage '{:s}' to {:x}, server guid 0x{:x}", thisptr->player.name, message->messageClassName, std::uint32_t(idTo), serverId)); if (idTo != game::serverNetPlayerId) { playerLog("CNetCustomPlayerClient should send messages only to server ???"); // Only send messages to server return false; } SLNet::BitStream stream((unsigned char*)message, message->length, false); if (peer->Send(&stream, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED, 0, thisptr->serverAddress, false) == 0) { playerLog(fmt::format("CNetCustomPlayerClient {:s} Send returned bad input", thisptr->player.name)); } return true; } int __fastcall playerClientReceiveMessage(CNetCustomPlayerClient* thisptr, int /*%edx*/, int* idFrom, game::NetMessageHeader* buffer) { if (!idFrom || !buffer) { // This should never happen return 3; } playerLog("CNetCustomPlayerClient receiveMessage"); std::lock_guard<std::mutex> messageGuard(netMessagesMutex); if (thisptr->messages.empty()) { return 0; } const auto& pair = thisptr->messages.front(); const auto& id{pair.first}; if (id != thisptr->serverId) { playerLog( fmt::format("CNetCustomPlayerClient received message from {:x}, its not a server!", id)); return 0; } auto message = reinterpret_cast<const game::NetMessageHeader*>(pair.second.get()); if (message->messageType != game::netMessageNormalType) { playerLog("CNetCustomPlayerClient received message with invalid type"); return 3; } if (message->length >= game::netMessageMaxLength) { playerLog("CNetCustomPlayerClient received message with invalid length"); return 3; } playerLog(fmt::format("CNetCustomPlayerClient receiveMessage '{:s}' length {:d} from 0x{:x}", message->messageClassName, message->length, pair.first)); *idFrom = static_cast<int>(id); std::memcpy(buffer, message, message->length); thisptr->messages.pop_front(); return 2; } void __fastcall playerClientSetNetSystem(CNetCustomPlayerClient* thisptr, int /*%edx*/, game::IMqNetSystem* netSystem) { playerLog("CNetCustomPlayerClient setNetSystem"); thisptr->player.vftable->setNetSystem(&thisptr->player, netSystem); } int __fastcall playerClientMethod8(CNetCustomPlayerClient* thisptr, int /*%edx*/, int a2) { playerLog("CNetCustomPlayerClient method8"); return thisptr->player.vftable->method8(&thisptr->player, a2); } static bool __fastcall playerClientSetName(CNetCustomPlayerClient* thisptr, int /*%edx*/, const char* name) { playerLog("CNetCustomPlayerClient setName"); thisptr->player.name = name; return true; } static bool __fastcall playerClientIsHost(CNetCustomPlayerClient* thisptr, int /*%edx*/) { const auto host{thisptr->player.session->host}; playerLog(fmt::format("CNetCustomPlayerClient isHost {:d}", host)); return host; } static game::IMqNetPlayerClientVftable playerClientVftable{ (game::IMqNetPlayerClientVftable::Destructor)playerClientDtor, (game::IMqNetPlayerClientVftable::GetName)playerClientGetName, (game::IMqNetPlayerClientVftable::GetNetId)playerClientGetNetId, (game::IMqNetPlayerClientVftable::GetSession)playerClientGetSession, (game::IMqNetPlayerClientVftable::GetMessageCount)playerClientGetMessageCount, (game::IMqNetPlayerClientVftable::SendNetMessage)playerClientSendMessage, (game::IMqNetPlayerClientVftable::ReceiveMessage)playerClientReceiveMessage, (game::IMqNetPlayerClientVftable::SetNetSystem)playerClientSetNetSystem, (game::IMqNetPlayerClientVftable::Method8)playerClientMethod8, (game::IMqNetPlayerClientVftable::SetName)playerClientSetName, (game::IMqNetPlayerClientVftable::IsHost)playerClientIsHost, }; CNetCustomPlayerClient::CNetCustomPlayerClient(CNetCustomSession* session, game::IMqNetSystem* netSystem, game::IMqNetReception* netReception, const char* name, NetworkPeer::PeerPtr&& peer, std::uint32_t netId, const SLNet::SystemAddress& serverAddress, std::uint32_t serverId) : player{session, netSystem, netReception, name, std::move(peer), netId} , callbacks(this) , serverAddress{serverAddress} , serverId{serverId} { vftable = &playerClientVftable; } void CNetCustomPlayerClient::setupPacketCallbacks() { playerLog("Setup player client packet callbacks"); player.netPeer.addCallback(&callbacks); } SLNet::SystemAddress lobbyAddressToServerPlayer(const SLNet::SystemAddress& lobbyAddress); CNetCustomPlayerClient* createCustomPlayerClient(CNetCustomSession* session, const char* name) { // Create peer using namespace game; const std::uint16_t clientPort = CNetCustomPlayer::clientPort + userSettings().lobby.client.port; SLNet::SocketDescriptor descriptor{clientPort, nullptr}; auto peer{NetworkPeer::PeerPtr(SLNet::RakPeerInterface::GetInstance())}; // Non-host client players have two connections: // with lobby server for NAT traversal and with player server const auto result{peer->Startup(2, &descriptor, 1)}; if (result != SLNet::StartupResult::RAKNET_STARTED) { playerLog("Failed to start peer for CNetCustomPlayerClient"); return nullptr; } playerLog("Creating CNetCustomPlayerClient"); auto client = (CNetCustomPlayerClient*)Memory::get().allocate(sizeof(CNetCustomPlayerClient)); // Empty fields will be initialized later new (client) CNetCustomPlayerClient(session, nullptr, nullptr, name, std::move(peer), 0, SLNet::UNASSIGNED_SYSTEM_ADDRESS, 0); playerLog("Player client created"); return client; } game::IMqNetPlayerClient* createCustomPlayerClient(CNetCustomSession* session, game::IMqNetSystem* netSystem, game::IMqNetReception* netReception, const char* name) { using namespace game; const std::uint16_t clientPort = CNetCustomPlayer::clientPort + userSettings().lobby.client.port; SLNet::SocketDescriptor descriptor{clientPort, nullptr}; auto peer{NetworkPeer::PeerPtr(SLNet::RakPeerInterface::GetInstance())}; const auto result{peer->Startup(1, &descriptor, 1)}; if (result != SLNet::StartupResult::RAKNET_STARTED) { playerLog("Failed to start peer for CNetCustomPlayerClient"); return nullptr; } auto service = session->service; auto serverAddress{lobbyAddressToServerPlayer(service->lobbyPeer.peer->GetMyBoundAddress())}; auto serverIp{serverAddress.ToString(false)}; playerLog(fmt::format("Client tries to connect to server at '{:s}'", serverIp)); // connect to server const auto connectResult{peer->Connect(serverIp, CNetCustomPlayer::serverPort, nullptr, 0)}; if (connectResult != SLNet::ConnectionAttemptResult::CONNECTION_ATTEMPT_STARTED) { playerLog(fmt::format("Failed to start CNetCustomPlayerClient connection. Error: {:d}", (int)connectResult)); return nullptr; } { playerLog("Wait for fucks sake"); using namespace std::chrono_literals; // This delay is needed for SLNet peer to connect to server // so the peer->GetGuidFromSystemAddress() call will work and give us server netId. // This is ugly and unreliable at all. // We can just store server SystemAddress and convert it go guid // or compare with packet->systemAddress to filter messages from server. // Or we just assume that players in game never send messages between each other // only to and from the server? std::this_thread::sleep_for(100ms); } auto netId = SLNet::RakNetGUID::ToUint32(peer->GetMyGUID()); playerLog(fmt::format("Creating player client on port {:d}", clientPort)); auto serverGuid = peer->GetGuidFromSystemAddress( SLNet::SystemAddress(serverIp, CNetCustomPlayer::serverPort)); auto serverId = SLNet::RakNetGUID::ToUint32(serverGuid); playerLog("Creating CNetCustomPlayerClient"); auto client = (CNetCustomPlayerClient*)Memory::get().allocate(sizeof(CNetCustomPlayerClient)); new (client) CNetCustomPlayerClient(session, netSystem, netReception, name, std::move(peer), netId, serverAddress, serverId); playerLog("Player client created"); playerLog(fmt::format("CNetCustomPlayerClient has netId 0x{:x}, " "expects server with netId 0x{:x}", netId, serverId)); return client; } CNetCustomPlayerClient* createCustomHostPlayerClient(CNetCustomSession* session, const char* name) { using namespace game; const std::uint16_t clientPort = CNetCustomPlayer::clientPort + userSettings().lobby.client.port; SLNet::SocketDescriptor descriptor{clientPort, nullptr}; auto peer{NetworkPeer::PeerPtr(SLNet::RakPeerInterface::GetInstance())}; const auto result{peer->Startup(1, &descriptor, 1)}; if (result != SLNet::StartupResult::RAKNET_STARTED) { playerLog("Failed to start peer for CNetCustomPlayerClient (host)"); return nullptr; } auto service = session->service; // Create player server address from our local address // since host player client is on the same machine as player server auto serverAddress{lobbyAddressToServerPlayer(service->lobbyPeer.peer->GetMyBoundAddress())}; auto serverIp{serverAddress.ToString(false)}; playerLog(fmt::format("Host client tries to connect to server at '{:s}', port {:d}", serverIp, CNetCustomPlayer::serverPort)); // Connect to server const auto connectResult{peer->Connect(serverIp, CNetCustomPlayer::serverPort, nullptr, 0)}; if (connectResult != SLNet::ConnectionAttemptResult::CONNECTION_ATTEMPT_STARTED) { playerLog(fmt::format("Failed to start CNetCustomPlayerClient connection. Error: {:d}", (int)connectResult)); return nullptr; } playerLog("Creating CNetCustomPlayerClient (host)"); auto client = (CNetCustomPlayerClient*)Memory::get().allocate(sizeof(CNetCustomPlayerClient)); // Empty fields will be initialized later new (client) CNetCustomPlayerClient(session, nullptr, nullptr, name, std::move(peer), 0, serverAddress, 0); playerLog("Host player client created"); return client; } } // namespace hooks
17,658
C++
.cpp
380
37.247368
99
0.659727
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,911
menuprotocolhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menuprotocolhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menuprotocolhooks.h" #include "dialoginterf.h" #include "listbox.h" #include "lobbyclient.h" #include "mempool.h" #include "menuflashwait.h" #include "menuphase.h" #include "menuphasehooks.h" #include "midgard.h" #include "netcustomservice.h" #include "networkpeer.h" #include "originalfunctions.h" #include "textids.h" #include "uievent.h" #include "utils.h" namespace hooks { struct CMenuCustomProtocol; class LobbyServerConnectionCallback : public NetworkPeerCallbacks { public: LobbyServerConnectionCallback(CMenuCustomProtocol* menu) : menuProtocol{menu} { } ~LobbyServerConnectionCallback() override = default; void onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) override; private: CMenuCustomProtocol* menuProtocol; }; struct CMenuCustomProtocol : public game::CMenuProtocol { CMenuCustomProtocol(game::CMenuPhase* menuPhase) : menuWait{nullptr} , callback{this} { using namespace game; CMenuProtocolApi::get().constructor(this, menuPhase); auto dialog = CMenuBaseApi::get().getDialogInterface(this); auto listBox = CDialogInterfApi::get().findListBox(dialog, "TLBOX_PROTOCOL"); if (listBox) { // One more entry for our custom protocol CListBoxInterfApi::get().setElementsTotal(listBox, listBox->listBoxData->elementsTotal + 1); } } game::UiEvent timeoutEvent{}; game::CMenuFlashWait* menuWait; LobbyServerConnectionCallback callback; }; static void stopWaitingConnection(CMenuCustomProtocol* menu) { using namespace game; UiEventApi::get().destructor(&menu->timeoutEvent); auto menuWait{menu->menuWait}; if (menuWait) { hideInterface(menuWait); menuWait->vftable->destructor(menuWait, 1); menu->menuWait = nullptr; } auto netService{getNetService()}; if (!netService) { return; } netService->lobbyPeer.removeCallback(&menu->callback); } static void showConnectionError(CMenuCustomProtocol* menu, const char* errorMessage) { stopWaitingConnection(menu); showMessageBox(errorMessage); } void LobbyServerConnectionCallback::onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) { switch (type) { case ID_CONNECTION_ATTEMPT_FAILED: { auto message{getInterfaceText(textIds().lobby.connectAttemptFailed.c_str())}; if (message.empty()) { message = "Connection attempt failed"; } showConnectionError(menuProtocol, message.c_str()); return; } case ID_NO_FREE_INCOMING_CONNECTIONS: { auto message{getInterfaceText(textIds().lobby.serverIsFull.c_str())}; if (message.empty()) { message = "Lobby server is full"; } showConnectionError(menuProtocol, message.c_str()); return; } case ID_ALREADY_CONNECTED: showConnectionError(menuProtocol, "Already connected.\nThis should never happen"); return; case ID_CONNECTION_REQUEST_ACCEPTED: { std::string hash; if (!computeHash(globalsFolder(), hash)) { auto message{getInterfaceText(textIds().lobby.computeHashFailed.c_str())}; if (message.empty()) { message = "Could not compute hash"; } showConnectionError(menuProtocol, message.c_str()); return; } if (!tryCheckFilesIntegrity(hash.c_str())) { auto message{getInterfaceText(textIds().lobby.requestHashCheckFailed.c_str())}; if (message.empty()) { message = "Could not request game integrity check"; } showConnectionError(menuProtocol, message.c_str()); return; } return; } case ID_FILES_INTEGRITY_RESULT: { stopWaitingConnection(menuProtocol); SLNet::BitStream input{packet->data, packet->length, false}; input.IgnoreBytes(sizeof(SLNet::MessageID)); bool checkPassed{false}; input.Read(checkPassed); if (checkPassed) { // Switch to custom lobby window menuPhaseSetTransitionHooked(menuProtocol->menuBaseData->menuPhase, 0, 2); return; } auto message{getInterfaceText(textIds().lobby.wrongHash.c_str())}; if (message.empty()) { message = "Game integrity check failed"; } showConnectionError(menuProtocol, message.c_str()); return; } default: return; } } static void __fastcall menuProtocolTimeoutHandler(CMenuCustomProtocol* menu, int /*%edx*/) { auto message{getInterfaceText(textIds().lobby.serverNotResponding.c_str())}; if (message.empty()) { message = "Failed to connect.\nLobby server not responding"; } showConnectionError(menu, message.c_str()); } void __fastcall menuProtocolDisplayCallbackHooked(game::CMenuProtocol* thisptr, int /*%edx*/, game::String* string, bool a3, int selectedIndex) { using namespace game; auto dialog = CMenuBaseApi::get().getDialogInterface(thisptr); auto listBox = CDialogInterfApi::get().findListBox(dialog, "TLBOX_PROTOCOL"); int lastIndex = -1; if (listBox) { lastIndex = listBox->listBoxData->elementsTotal - 1; } if (selectedIndex == lastIndex) { auto serverName{getInterfaceText(textIds().lobby.serverName.c_str())}; if (serverName.empty()) { serverName = "Lobby server"; } StringApi::get().initFromString(string, serverName.c_str()); return; } getOriginalFunctions().menuProtocolDisplayCallback(thisptr, string, a3, selectedIndex); } void __fastcall menuProtocolContinueHandlerHooked(CMenuCustomProtocol* thisptr, int /*%edx*/) { using namespace game; auto dialog = CMenuBaseApi::get().getDialogInterface(thisptr); auto listBox = CDialogInterfApi::get().findListBox(dialog, "TLBOX_PROTOCOL"); if (!listBox) { return; } auto data = listBox->listBoxData; if (data->selectedElement != data->elementsTotal - 1) { getOriginalFunctions().menuProtocolContinueHandler(thisptr); return; } auto& midgardApi = CMidgardApi::get(); auto midgard = midgardApi.instance(); // Delete old net service midgardApi.setNetService(midgard, nullptr, true, false); IMqNetService* service{nullptr}; if (!createCustomNetService(&service)) { return; } midgardApi.setNetService(midgard, service, true, false); auto menuWait = (CMenuFlashWait*)Memory::get().allocate(sizeof(CMenuFlashWait)); CMenuFlashWaitApi::get().constructor(menuWait); thisptr->menuWait = menuWait; showInterface(menuWait); auto netService{static_cast<CNetCustomService*>(service)}; netService->lobbyPeer.addCallback(&thisptr->callback); // Stop attempting to connect after 10 seconds createTimerEvent(&thisptr->timeoutEvent, thisptr, menuProtocolTimeoutHandler, 10000); } game::CMenuProtocol* __stdcall menuProtocolCreateMenuHooked(game::CMenuPhase* menuPhase) { using namespace game; auto menu = (CMenuCustomProtocol*)Memory::get().allocate(sizeof(CMenuCustomProtocol)); new (menu) CMenuCustomProtocol(menuPhase); return menu; } } // namespace hooks
8,623
C++
.cpp
225
30.733333
95
0.66419
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,912
interftexthooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/interftexthooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "interftexthooks.h" #include "attackdescriptor.h" #include "attackimpl.h" #include "attackutils.h" #include "customattackutils.h" #include "d2string.h" #include "dialoginterf.h" #include "dynupgrade.h" #include "encunitdescriptor.h" #include "interfaceutils.h" #include "midunit.h" #include "midunitdescriptor.h" #include "settings.h" #include "textboxinterf.h" #include "textids.h" #include "unitutils.h" #include "ussoldierimpl.h" #include "utils.h" #include <fmt/format.h> namespace hooks { std::string getMaxDamageText(const std::string& value) { // "%DMG% \c000;000;000;(\c128;000;000;Max\c000;000;000;)" auto result = getInterfaceText("X005TA0811"); replace(result, "%DMG%", value); return result; } std::string getDamageText(int value, int base, int max) { auto result = getModifiedNumberText(value, base, false); return value >= max ? getMaxDamageText(result) : result; } std::string addAltAttackText(const std::string& base, const std::string& value) { auto result = getInterfaceText("X005TA0829"); // "%ATTACK% or %BLANK%" replace(result, "%ATTACK%", value); replace(result, "%BLANK%", base); return result; } std::string addAttack2Text(const std::string& base, const std::string& value) { auto result = getInterfaceText("X005TA0785"); // " / %ATTACK%" replace(result, "%ATTACK%", value); result.insert(0, base); return result; } std::string getCritHitText() { auto text = getInterfaceText(textIds().interf.critHitAttack.c_str()); if (text.length()) return text; return getInterfaceText("X160TA0017"); // "Critical hit" } std::string getDrainEffectText() { auto text = getInterfaceText(textIds().interf.drainEffect.c_str()); if (text.length()) return text; return getInterfaceText("X005TA0792"); // "Drain" } std::string addCritHitText(const std::string& base, const std::string& value, bool full) { auto text = getInterfaceText(textIds().interf.critHitDamage.c_str()); if (text.empty()) text = "%DMG% (%CRIT%)"; replace(text, "%DMG%", base); replace(text, "%CRIT%", full ? fmt::format("{:s} {:s}", getCritHitText(), value) : value); return text; } std::string getDurationText() { auto text = getInterfaceText(textIds().interf.durationText.c_str()); if (text.length()) return text; return "Duration"; } std::string getInstantDurationText() { auto text = getInterfaceText(textIds().interf.instantDurationText.c_str()); if (text.length()) return text; return "Instant"; } std::string getRandomDurationText() { auto text = getInterfaceText(textIds().interf.randomDurationText.c_str()); if (text.length()) return text; return "Random"; } std::string getSingleTurnDurationText() { auto text = getInterfaceText(textIds().interf.singleTurnDurationText.c_str()); if (text.length()) return text; return "Single turn"; } std::string getWholeBattleDurationText() { auto text = getInterfaceText(textIds().interf.wholeBattleDurationText.c_str()); if (text.length()) return text; return "Whole battle"; } std::string getOverflowText() { auto text = getInterfaceText(textIds().interf.overflowAttack.c_str()); if (text.length()) return text; return "Overflow"; } std::string getInfiniteText() { auto text = getInterfaceText(textIds().interf.infiniteAttack.c_str()); if (text.length()) return text; return "Lasting"; } std::string getAttackDurationText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { using namespace game; const auto& classes = AttackClassCategories::get(); if (actual.classId() == classes.paralyze->id || actual.classId() == classes.petrify->id || actual.classId() == classes.poison->id || actual.classId() == classes.frostbite->id || actual.classId() == classes.blister->id) { return getModifiedStringText(actual.infinite() ? getRandomDurationText() : getSingleTurnDurationText(), actual.infinite() != global.infinite()); } else if (actual.classId() == classes.boostDamage->id || actual.classId() == classes.lowerDamage->id || actual.classId() == classes.lowerInitiative->id) { return getModifiedStringText(actual.infinite() ? getWholeBattleDurationText() : getSingleTurnDurationText(), actual.infinite() != global.infinite()); } else if (actual.classId() == classes.transformOther->id) { return getModifiedStringText(actual.infinite() ? getRandomDurationText() : getWholeBattleDurationText(), actual.infinite() != global.infinite()); } else { return getInstantDurationText(); } } std::string addOverflowText(const std::string& base, const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { using namespace game; const auto& classes = AttackClassCategories::get(); if (actual.classId() != classes.drainOverflow->id) return base; auto text = getInterfaceText(textIds().interf.overflowText.c_str()); if (text.empty()) text = "%ATTACK% (%OVERFLOW%)"; replace(text, "%ATTACK%", base); replace(text, "%OVERFLOW%", getModifiedStringText(getOverflowText(), global.classId() != classes.drainOverflow->id)); return text; } std::string addInfiniteText(const std::string& base, const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { if (!actual.infinite()) { return base; } auto result = getInterfaceText(textIds().interf.infiniteText.c_str()); if (result.empty()) result = "%ATTACK% (%INFINITE%)"; replace(result, "%ATTACK%", base); replace(result, "%INFINITE%", getModifiedStringText(getInfiniteText(), !global.infinite())); return result; } std::string getRatedAttackDamageText(int damage, int critDamage, double ratio) { auto result = getNumberText(applyAttackDamageRatio(damage, ratio), false); if (critDamage) { result = addCritHitText(result, getNumberText(applyAttackDamageRatio(critDamage, ratio), false), false); } return result; } std::string getRatedAttackDamageText(const std::string& base, const utils::AttackDescriptor& actual, int maxTargets) { auto ratios = computeAttackDamageRatio(actual.custom(), maxTargets); if (ratios.size() < 2) return base; auto critDamage = actual.damage() * actual.critDamage() / 100; if (!actual.damageRatioPerTarget() && ratios.size() > 2) { auto result = getInterfaceText(textIds().interf.ratedDamageEqual.c_str()); if (result.empty()) result = "%DMG%, (%TARGETS%x) %RATED%"; replace(result, "%DMG%", base); replace(result, "%TARGETS%", fmt::format("{:d}", ratios.size() - 1)); replace(result, "%RATED%", getRatedAttackDamageText(actual.damage(), critDamage, ratios[1])); return result; } else { auto result = getInterfaceText(textIds().interf.ratedDamage.c_str()); if (result.empty()) result = "%DMG%, %RATED%"; auto separator = getInterfaceText(textIds().interf.ratedDamageSeparator.c_str()); if (separator.empty()) separator = ", "; std::string rated; for (auto it = ratios.begin() + 1; it < ratios.end(); ++it) { if (!rated.empty()) rated += separator; rated += getRatedAttackDamageText(actual.damage(), critDamage, *it); } replace(result, "%DMG%", base); replace(result, "%RATED%", rated); return result; } } std::string getSplitAttackDamageText(const std::string& base) { auto result = getInterfaceText(textIds().interf.splitDamage.c_str()); if (result.empty()) result = "%DMG%, split between targets"; replace(result, "%DMG%", base); return result; } std::string getAttackPowerText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { std::string result; if (actual.hasPower() && global.hasPower()) { result = getModifiedNumberText(actual.power(), global.power(), true); } else { result = getNumberText(actual.power(), true); } if (actual.critHit()) { bool full = !userSettings().unitEncyclopedia.displayCriticalHitTextInAttackName; result = addCritHitText(result, getModifiedNumberText(actual.critPower(), global.critPower(), true), full); } return result; } std::string getDamageDrainAttackDamageText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global, int maxTargets, int damageMax) { int multiplier = actual.damageSplit() ? userSettings().splitDamageMultiplier : 1; auto result = getDamageText(actual.damage(), global.damage(), damageMax * multiplier); if (actual.critHit()) { bool full = !userSettings().unitEncyclopedia.displayCriticalHitTextInAttackName; result = addCritHitText(result, getModifiedNumberText(actual.damage() * actual.critDamage() / 100, actual.damage() * global.critDamage() / 100, false), full); } if (maxTargets < 2) return result; else if (actual.damageSplit()) { return getSplitAttackDamageText(result); } else { return getRatedAttackDamageText(result, actual, maxTargets); } } std::string getBoostDamageAttackDamageText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { int boost = global.boost() ? global.boost() : actual.boost(); auto result = getInterfaceText("X005TA0535"); // "+%BOOST%%" replace(result, "%BOOST%", getNumberText(boost, false)); return addBonusNumberText(result, actual.boost() - boost, true, false); } std::string getLowerDamageAttackDamageText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { int lower = global.lower() ? global.lower() : actual.lower(); auto result = getInterfaceText("X005TA0550"); // "-%LOWER%%" replace(result, "%LOWER%", getNumberText(lower, false)); return addBonusNumberText(result, lower - actual.lower(), true, true); } std::string getLowerInitiativeAttackDamageText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { int lower = global.lowerIni() ? global.lowerIni() : actual.lowerIni(); auto result = getInterfaceText("X005TA0550"); // "-%LOWER%%" replace(result, "%LOWER%", getNumberText(lower, false)); return addBonusNumberText(result, lower - actual.lowerIni(), true, true); } std::string getAttackDamageText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global, int maxTargets, int damageMax) { using namespace game; const auto& classes = AttackClassCategories::get(); if (actual.classId() == classes.boostDamage->id) { return getBoostDamageAttackDamageText(actual, global); } else if (actual.classId() == classes.lowerDamage->id) { return getLowerDamageAttackDamageText(actual, global); } else if (actual.classId() == classes.lowerInitiative->id) { return getLowerInitiativeAttackDamageText(actual, global); } else if (actual.classId() == classes.damage->id || actual.classId() == classes.drain->id || actual.classId() == classes.drainOverflow->id) { return getDamageDrainAttackDamageText(actual, global, maxTargets, damageMax); } else if (actual.classId() == classes.heal->id || actual.classId() == classes.bestowWards->id) { return getModifiedNumberText(actual.heal(), global.heal(), false); } else if (actual.classId() == classes.poison->id || actual.classId() == classes.frostbite->id || actual.classId() == classes.blister->id) { return getNumberText(global.damage(), false); } else { return getDamageText(actual.damage(), global.damage(), damageMax); } } std::string getAttackDrainText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { auto result = getModifiedNumberText(actual.drain(), global.drain(), false); return addOverflowText(result, actual, global); } std::string getAttackSourceText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { std::string result = getAttackSourceText(actual.sourceId()); return getModifiedStringText(result, actual.sourceId() != global.sourceId()); } std::string getAttackReachText(game::AttackReachId id) { using namespace game; const auto& reaches = AttackReachCategories::get(); if (id == reaches.adjacent->id) return getInterfaceText("X005TA0201"); // "Adjacent units" else if (id == reaches.all->id || id == reaches.any->id) return getInterfaceText("X005TA0200"); // "Any unit" else { for (const auto& custom : getCustomAttacks().reaches) { if (id == custom.reach.id) { return getInterfaceText(custom.reachTxt.c_str()); } } } return ""; } std::string getAttackTargetsText(game::AttackReachId id) { using namespace game; const auto& reaches = AttackReachCategories::get(); if (id == reaches.all->id) return getInterfaceText("X005TA0674"); // "6" else if (id == reaches.any->id || id == reaches.adjacent->id) return getInterfaceText("X005TA0675"); // "1" else { for (const auto& custom : getCustomAttacks().reaches) { if (id == custom.reach.id) { return getInterfaceText(custom.targetsTxt.c_str()); } } } return ""; } std::string getAttackNameText(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { auto result = getModifiedStringText(actual.name(), actual.name() != global.name()); if (actual.infinite() && userSettings().unitEncyclopedia.displayInfiniteAttackIndicator) { result = addInfiniteText(result, actual, global); } if (actual.critHit() && userSettings().unitEncyclopedia.displayCriticalHitTextInAttackName) { result = addCritHitText(result, getModifiedStringText(getCritHitText(), !global.critHit()), false); } return result; } void addDynUpgradeText(std::string& description, game::IEncUnitDescriptor* descriptor, const utils::AttackDescriptor& actual, const utils::AttackDescriptor& actual2) { using namespace game; const CDynUpgrade* upgrade1 = nullptr; const CDynUpgrade* upgrade2 = nullptr; if (!getDynUpgradesToDisplay(descriptor, &upgrade1, &upgrade2)) { return; } if (actual.damage() || actual2.damage()) { addDynUpgradeTextToField(description, "%DAMAGE%", upgrade1->damage, upgrade2->damage); } else if (actual.heal() || actual2.heal()) { addDynUpgradeTextToField(description, "%DAMAGE%", upgrade1->heal, upgrade2->heal); } if (actual.hasPower() || actual2.hasPower()) { addDynUpgradeTextToField(description, "%HIT2%", upgrade1->power, upgrade2->power); } addDynUpgradeTextToField(description, "%INIT%", upgrade1->initiative, upgrade2->initiative); } std::string getTwiceField(game::IEncUnitDescriptor* descriptor) { using namespace game; if (!descriptor->vftable->attacksTwice(descriptor)) return ""; auto result = getInterfaceText("X005TA0786"); // "(2x) %BLANK%" replace(result, "%BLANK%", ""); bool modified = false; auto midUnitDescriptor = castToMidUnitDescriptor(descriptor); if (midUnitDescriptor) { const auto unitImpl = midUnitDescriptor->unit->unitImpl; const auto soldierImpl = getSoldierImpl(unitImpl); modified = soldierImpl && !soldierImpl->vftable->getAttackTwice(soldierImpl); } return getModifiedStringText(result, modified); } std::string getAltAttackField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { if (actual.empty()) return ""; return addAltAttackText("", getAttackNameText(actual, global)); } std::string getAttackField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { return getAttackNameText(actual, global); } std::string getSecondField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { if (actual.empty()) return ""; return addAttack2Text("", getAttackNameText(actual, global)); } std::string getHitField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { return getAttackPowerText(actual, global); } std::string getHit2Field(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { if (actual.empty()) return ""; auto result = getInterfaceText("X005TA0881"); // " / %POWER%" replace(result, "%POWER%", getAttackPowerText(actual, global)); return result; } std::string getEffectField(const utils::AttackDescriptor& actual) { using namespace game; const auto& classes = AttackClassCategories::get(); if (actual.classId() == classes.heal->id || actual.classId() == classes.bestowWards->id) return getInterfaceText("X005TA0504"); // "Heal" else if (actual.classId() == classes.boostDamage->id) return getInterfaceText("X005TA0534"); // "Boost" else if (actual.classId() == classes.lowerDamage->id) return getInterfaceText("X005TA0547"); // "Lower" else if (actual.classId() == classes.lowerInitiative->id) return getInterfaceText("X005TA0551"); // "Lower initiative" else return getInterfaceText("X005TA0503"); // "Damage" } std::string getDamageField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global, const utils::AttackDescriptor& actual2, const utils::AttackDescriptor& global2, int damageMax) { auto maxTargets = getAttackMaxTargets(actual.reachId()); auto result = getAttackDamageText(actual, global, maxTargets, damageMax); if (!actual2.empty()) { auto damage2 = getAttackDamageText(actual2, global2, maxTargets, damageMax); if (result == "0") result = damage2; else if (damage2 != "0") result = addAttack2Text(result, damage2); } return result; } std::string getDrainField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global, const utils::AttackDescriptor& actual2, const utils::AttackDescriptor& global2) { if (!actual.drain() && !actual2.drain()) return ""; auto result = getInterfaceText(textIds().interf.drainDescription.c_str()); if (result.empty()) result = "\\fMedBold;%DRAINEFFECT%:\\t\\fNormal;%DRAIN%\\n"; auto drain = getAttackDrainText(actual, global); if (!actual2.empty()) { auto drain2 = getAttackDrainText(actual2, global2); if (drain == "0") drain = drain2; else if (drain2 != "0") drain = addAttack2Text(drain, drain2); } replace(result, "%DRAINEFFECT%", getDrainEffectText()); replace(result, "%DRAIN%", drain); return result; } std::string getDurationField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global, const utils::AttackDescriptor& actual2, const utils::AttackDescriptor& global2) { using namespace game; const auto& classes = AttackClassCategories::get(); if (!actual.hasInfinite() && !actual2.hasInfinite()) { return ""; } auto result = getInterfaceText(textIds().interf.durationDescription.c_str()); if (result.empty()) { result = "\\fMedBold;%DURATION%:\\t\\fNormal;%DURATIONVALUE%\\n"; } auto duration = getAttackDurationText(actual, global); if (!actual2.empty()) { duration = addAttack2Text(duration, getAttackDurationText(actual2, global2)); } replace(result, "%DURATION%", getDurationText()); replace(result, "%DURATIONVALUE%", duration); return result; } std::string getSourceField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global, const utils::AttackDescriptor& actualAlt, const utils::AttackDescriptor& globalAlt) { std::string result = getAttackSourceText(actual, global); const auto& classes = game::AttackClassCategories::get(); if (actualAlt.classId() == classes.doppelganger->id) { if (userSettings().doppelgangerRespectsEnemyImmunity || userSettings().doppelgangerRespectsAllyImmunity) { result = addAltAttackText(result, getAttackSourceText(actualAlt, globalAlt)); } } return result; } std::string getSource2Field(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { if (actual.empty()) return ""; auto result = getInterfaceText("X005TA0816"); // " / %SOURCE%" replace(result, "%SOURCE%", getAttackSourceText(actual, global)); return result; } std::string getInitField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { return getModifiedNumberText(actual.initiative(), global.initiative(), false); } std::string getReachField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { std::string result = getAttackReachText(actual.reachId()); return getModifiedStringText(result, actual.reachId() != global.reachId()); } std::string getTargetsField(const utils::AttackDescriptor& actual, const utils::AttackDescriptor& global) { std::string result = getAttackTargetsText(actual.reachId()); return getModifiedStringText(result, actual.reachId() != global.reachId()); } void __stdcall generateAttackDescriptionHooked(game::IEncUnitDescriptor* descriptor, game::CDialogInterf* dialog, int boostDamageLevel, int lowerDamageLevel, int lowerInitiativeLevel, const game::IdList* editorModifiers, int damageMax) { using namespace utils; AttackDescriptor actual(descriptor, AttackType::Primary, false, boostDamageLevel, lowerDamageLevel, lowerInitiativeLevel, nullptr, damageMax); AttackDescriptor global(descriptor, AttackType::Primary, true, 0, 0, 0, editorModifiers, damageMax); AttackDescriptor actual2(descriptor, AttackType::Secondary, false, boostDamageLevel, lowerDamageLevel, 0, nullptr, damageMax); AttackDescriptor global2(descriptor, AttackType::Secondary, true); AttackDescriptor actualAlt(descriptor, AttackType::Alternative, false); AttackDescriptor globalAlt(descriptor, AttackType::Alternative, true); auto description = getInterfaceText("X005TA0424"); // "%PART1%%PART2%" // \s110; // \fMedBold;Attack:\t\p110;\fNormal;%TWICE%%ALTATTACK%%ATTACK%%SECOND%\p0;\n // \fMedBold;Chances to hit:\t\fNormal;%HIT%%HIT2%\n replace(description, "%PART1%", getInterfaceText("X005TA0787")); // \fMedBold;%EFFECT%:\t\fNormal;%DAMAGE%\n // \fMedBold;Source:\t\fNormal;%SOURCE%%SOURCE2%\n // \fMedBold;Initiative:\t\fNormal;%INIT%\n // \fMedBold;Reach:\t\fNormal;%REACH%\n // \fMedBold;Targets:\t\fNormal;%TARGETS% replace(description, "%PART2%", getInterfaceText("X005TA0788")); addDynUpgradeText(description, descriptor, actual, actual2); replace(description, "%TWICE%", getTwiceField(descriptor)); replace(description, "%ALTATTACK%", getAltAttackField(actualAlt, globalAlt)); replace(description, "%ATTACK%", getAttackField(actual, global)); replace(description, "%SECOND%", getSecondField(actual2, global2)); replace(description, "%HIT%", getHitField(actual, global)); replace(description, "%HIT2%", getHit2Field(actual2, global2)); replace(description, "%EFFECT%", getEffectField(actual)); replace(description, "%DURATION%", getDurationField(actual, global, actual2, global2)); replace(description, "%DAMAGE%", getDamageField(actual, global, actual2, global2, damageMax)); replace(description, "%DRAIN%", getDrainField(actual, global, actual2, global2)); replace(description, "%SOURCE%", getSourceField(actual, global, actualAlt, globalAlt)); replace(description, "%SOURCE2%", getSource2Field(actual2, global2)); replace(description, "%INIT%", getInitField(actual, global)); replace(description, "%REACH%", getReachField(actual, global)); replace(description, "%TARGETS%", getTargetsField(actual, global)); auto textBox = game::CDialogInterfApi::get().findTextBox(dialog, "TXT_ATTACK_INFO"); game::CTextBoxInterfApi::get().setString(textBox, description.c_str()); } game::String* __stdcall getAttackSourceTextHooked(game::String* value, const game::LAttackSource* attackSource) { const auto& stringApi = game::StringApi::get(); stringApi.initFromString(value, getAttackSourceText(attackSource).c_str()); return value; } void __stdcall appendAttackSourceTextHooked(const game::LAttackSource* attackSource, game::String* value, bool* valueIsNotEmpty) { const auto& stringApi = game::StringApi::get(); auto text = getAttackSourceText(attackSource); if (*valueIsNotEmpty) stringApi.append(value, ", ", strlen(", ")); stringApi.append(value, text.c_str(), text.length()); *valueIsNotEmpty = true; } } // namespace hooks
28,394
C++
.cpp
648
35.376543
100
0.643162
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,913
menunewskirmishsinglehooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menunewskirmishsinglehooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menunewskirmishsinglehooks.h" #include "button.h" #include "dialoginterf.h" #include "log.h" #include "menunewskirmishsingle.h" #include "originalfunctions.h" namespace hooks { static void __fastcall showMenuRandomScenarioSingle(game::CMenuNewSkirmishSingle* thisptr, int /*%edx*/) { using namespace game; // Transfer to a new single player random scenario generation menu, from state 6 to 37 CMenuPhase* menuPhase{thisptr->menuBaseData->menuPhase}; CMenuPhaseApi::get().setTransition(menuPhase, 1); } game::CMenuNewSkirmishSingle* __fastcall menuNewSkirmishSingleCtorHooked( game::CMenuNewSkirmishSingle* thisptr, int /* %edx */, game::CMenuPhase* menuPhase) { getOriginalFunctions().menuNewSkirmishSingleCtor(thisptr, menuPhase); using namespace game; static const char buttonName[] = "BTN_RANDOM_MAP"; const auto& menuBase{CMenuBaseApi::get()}; const auto& dialogApi{CDialogInterfApi::get()}; CDialogInterf* dialog{menuBase.getDialogInterface(thisptr)}; // Check if we have new button for random scenario generator menu and setup its callback if (dialogApi.findControl(dialog, buttonName)) { const auto& button{CButtonInterfApi::get()}; SmartPointer functor; auto callback = (CMenuBaseApi::Api::ButtonCallback)showMenuRandomScenarioSingle; menuBase.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, buttonName, "DLG_CHOOSE_SKIRMISH", &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } return thisptr; } } // namespace hooks
2,490
C++
.cpp
56
39.928571
92
0.739364
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false