From 01322aa4c5ba17b6cf14cc74dfd397e7db618f00 Mon Sep 17 00:00:00 2001 From: Ivan Savenko Date: Fri, 6 Jan 2023 21:28:48 +0200 Subject: [PATCH 01/10] Do not allow selecting resolution no supported by display --- Mods/vcmi/config/vcmi/english.json | 1 + client/renderSDL/SDL_Extensions.cpp | 8 -- client/renderSDL/SDL_Extensions.h | 3 - client/windows/GUIClasses.cpp | 126 +++++++++++++++++++++++----- client/windows/GUIClasses.h | 9 ++ 5 files changed, 115 insertions(+), 32 deletions(-) diff --git a/Mods/vcmi/config/vcmi/english.json b/Mods/vcmi/config/vcmi/english.json index 6071cc952..a703ff01f 100644 --- a/Mods/vcmi/config/vcmi/english.json +++ b/Mods/vcmi/config/vcmi/english.json @@ -31,6 +31,7 @@ "vcmi.systemOptions.resolutionButton.help" : "{Select resolution}\n\n Change in-game screen resolution. Game restart required to apply new resolution.", "vcmi.systemOptions.resolutionMenu.hover" : "Select resolution", "vcmi.systemOptions.resolutionMenu.help" : "Change in-game screen resolution.", + "vcmi.systemOptions.fullscreenFailed" : "{Fullscreen}\n\n Failed to switch to fullscreen mode! Current resolution is not supported by display!", "vcmi.townHall.missingBase" : "Base building %s must be built first", "vcmi.townHall.noCreaturesToRecruit" : "There are no creatures to recruit!", diff --git a/client/renderSDL/SDL_Extensions.cpp b/client/renderSDL/SDL_Extensions.cpp index b5b39ab8e..cad39d812 100644 --- a/client/renderSDL/SDL_Extensions.cpp +++ b/client/renderSDL/SDL_Extensions.cpp @@ -66,14 +66,6 @@ SDL_Color CSDL_Ext::toSDL(const ColorRGBA & color) return result; } -Rect CSDL_Ext::getDisplayBounds() -{ - SDL_Rect displayBounds; - SDL_GetDisplayBounds(std::max(0, SDL_GetWindowDisplayIndex(mainWindow)), &displayBounds); - - return fromSDL(displayBounds); -} - void CSDL_Ext::setColors(SDL_Surface *surface, SDL_Color *colors, int firstcolor, int ncolors) { SDL_SetPaletteColors(surface->format->palette,colors,firstcolor,ncolors); diff --git a/client/renderSDL/SDL_Extensions.h b/client/renderSDL/SDL_Extensions.h index 5df8f96af..483531289 100644 --- a/client/renderSDL/SDL_Extensions.h +++ b/client/renderSDL/SDL_Extensions.h @@ -108,9 +108,6 @@ typedef void (*TColorPutterAlpha)(uint8_t *&ptr, const uint8_t & R, const uint8_ uint32_t colorTouint32_t(const SDL_Color * color); //little endian only SDL_Color makeColor(ui8 r, ui8 g, ui8 b, ui8 a); - /// returns dimensions of display on which VCMI window is located - Rect getDisplayBounds(); - void drawLine(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color1, const SDL_Color & color2); void drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const SDL_Color &color, int depth = 1); void drawBorder(SDL_Surface * sur, const Rect &r, const SDL_Color &color, int depth = 1); diff --git a/client/windows/GUIClasses.cpp b/client/windows/GUIClasses.cpp index a78359e6c..63cee346b 100644 --- a/client/windows/GUIClasses.cpp +++ b/client/windows/GUIClasses.cpp @@ -540,7 +540,7 @@ CSystemOptionsWindow::CSystemOptionsWindow() fullscreen = std::make_shared(Point(246, 215), "sysopchk.def", CButton::tooltipLocalized("vcmi.systemOptions.fullscreenButton"), [&](bool value) { - setBoolSetting("video", "fullscreen", value); + setFullscreenMode(value); }); fullscreen->setSelected(settings["video"]["fullscreen"].Bool()); @@ -552,27 +552,110 @@ CSystemOptionsWindow::CSystemOptionsWindow() gameResLabel = std::make_shared(170, 292, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, resolutionToString(screenRes["width"].Integer(), screenRes["height"].Integer())); } -void CSystemOptionsWindow::selectGameRes() +void CSystemOptionsWindow::setFullscreenMode( bool on) { - std::vector items; + fillSelectableResolutions(); -#ifndef VCMI_IOS - Rect displayBounds = CSDL_Ext::getDisplayBounds(); -#endif + const auto & screenRes = settings["video"]["screenRes"]; + const Point desiredResolution(screenRes["width"].Integer(), screenRes["height"].Integer()); + const Point currentResolution(screen->w, screen->h); + + if (!isResolutionSupported(currentResolution, on)) + { + fullscreen->setSelected(!on); + LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.systemOptions.fullscreenFailed")); + return; + } + + setBoolSetting("video", "fullscreen", on); + + if (!isResolutionSupported(desiredResolution, on)) + { + // user changed his desired resolution and switched to fullscreen + // however resolution he selected before is not available in fullscreen + // so reset it back to currect resolution which is confirmed to be supported earlier + Settings gameRes = settings.write["video"]["screenRes"]; + gameRes["width"].Float() = currentResolution.x; + gameRes["height"].Float() = currentResolution.y; + + gameResLabel->setText(resolutionToString(currentResolution.x, currentResolution.y)); + } +} + +void CSystemOptionsWindow::fillSupportedResolutions() +{ + supportedResolutions.clear(); + + // in game we can only change resolution, display is fixed + int displayID = SDL_GetWindowDisplayIndex(mainWindow); + + int modesCount = SDL_GetNumDisplayModes(displayID); + + for (int i =0; i < modesCount; ++i) + { + SDL_DisplayMode mode; + if (SDL_GetDisplayMode(displayID, i, &mode) != 0) + continue; + + Point resolution(mode.w, mode.h); + + supportedResolutions.push_back(resolution); + } +} + +void CSystemOptionsWindow::fillSelectableResolutions() +{ + fillSupportedResolutions(); + selectableResolutions.clear(); - size_t currentResolutionIndex = 0; - size_t i = 0; for(const auto & it : conf.guiOptions) { - const auto & resolution = it.first; -#ifndef VCMI_IOS - if(displayBounds.w < resolution.first || displayBounds.h < resolution.second) - continue; + const Point dimensions(it.first.first, it.first.second); + + if(isResolutionSupported(dimensions)) + selectableResolutions.push_back(dimensions); + } + + boost::range::sort(selectableResolutions, [](const auto & left, const auto & right) + { + return left.x * left.y < right.x * right.y; + }); +} + +bool CSystemOptionsWindow::isResolutionSupported(const Point & resolution) +{ + return isResolutionSupported( resolution, settings["video"]["fullscreen"].Bool()); +} + +bool CSystemOptionsWindow::isResolutionSupported(const Point & resolution, bool fullscreen) +{ +#ifdef VCMI_IOS + // ios can use any resolution + bool canUseAllResolutions = true; +#else + // in fullscreen only resolutions supported by monitor can be used + bool canUseAllResolutions = (fullscreen == false); #endif - auto resolutionStr = resolutionToString(resolution.first, resolution.second); + if (canUseAllResolutions) + return true; + + return vstd::contains(supportedResolutions, resolution); +} + +void CSystemOptionsWindow::selectGameRes() +{ + fillSelectableResolutions(); + + std::vector items; + size_t currentResolutionIndex = 0; + size_t i = 0; + for(const auto & it : selectableResolutions) + { + auto resolutionStr = resolutionToString(it.x, it.y); if(gameResLabel->getText() == resolutionStr) currentResolutionIndex = i; + items.push_back(std::move(resolutionStr)); ++i; } @@ -586,20 +669,21 @@ void CSystemOptionsWindow::selectGameRes() void CSystemOptionsWindow::setGameRes(int index) { - auto iter = conf.guiOptions.begin(); - std::advance(iter, index); + assert(index >= 0 && index < selectableResolutions.size()); - //do not set resolution to illegal one (0x0) - assert(iter!=conf.guiOptions.end() && iter->first.first > 0 && iter->first.second > 0); + if ( index < 0 || index >= selectableResolutions.size() ) + return; + + Point resolution = selectableResolutions[index]; Settings gameRes = settings.write["video"]["screenRes"]; - gameRes["width"].Float() = iter->first.first; - gameRes["height"].Float() = iter->first.second; + gameRes["width"].Float() = resolution.x; + gameRes["height"].Float() = resolution.y; std::string resText; - resText += boost::lexical_cast(iter->first.first); + resText += std::to_string(resolution.x); resText += "x"; - resText += boost::lexical_cast(iter->first.second); + resText += std::to_string(resolution.y); gameResLabel->setText(resText); } diff --git a/client/windows/GUIClasses.h b/client/windows/GUIClasses.h index 9e46652c0..fa71e36eb 100644 --- a/client/windows/GUIClasses.h +++ b/client/windows/GUIClasses.h @@ -226,6 +226,9 @@ private: SettingsListener onFullscreenChanged; + std::vector supportedResolutions; + std::vector selectableResolutions; + //functions bound to buttons void bloadf(); //load game void bsavef(); //save game @@ -234,6 +237,12 @@ private: void brestartf(); //restart game void bmainmenuf(); //return to main menu + void setFullscreenMode( bool on); + void fillSupportedResolutions(); + void fillSelectableResolutions(); + bool isResolutionSupported(const Point & resolution); + bool isResolutionSupported(const Point & resolution, bool fullscreen); + void selectGameRes(); void setGameRes(int index); void closeAndPushEvent(EUserEvent code); From 70c0937972e02caecd4e2f4e367559f51f7c7978 Mon Sep 17 00:00:00 2001 From: Ivan Savenko Date: Thu, 2 Feb 2023 22:42:15 +0200 Subject: [PATCH 02/10] Moved SDL-specific code to SDL_Extensions --- client/renderSDL/SDL_Extensions.cpp | 35 ++++++++++++++++++++++++++ client/renderSDL/SDL_Extensions.h | 5 ++++ client/windows/GUIClasses.cpp | 38 +++++------------------------ client/windows/GUIClasses.h | 1 - 4 files changed, 46 insertions(+), 33 deletions(-) diff --git a/client/renderSDL/SDL_Extensions.cpp b/client/renderSDL/SDL_Extensions.cpp index cad39d812..f7c7a1d59 100644 --- a/client/renderSDL/SDL_Extensions.cpp +++ b/client/renderSDL/SDL_Extensions.cpp @@ -891,7 +891,42 @@ void CSDL_Ext::getClipRect(SDL_Surface * src, Rect & other) other = CSDL_Ext::fromSDL(rect); } +bool CSDL_Ext::isResolutionSupported(const std::vector & resolutions, const Point toTest ) +{ +#if defined(VCMI_ANDROID) || defined(VCMI_IOS) + // ios can use any resolution + // presumably, same goes for Android + return true; +#else + // in fullscreen only resolutions supported by monitor can be used + return vstd::contains(resolutions, toTest); +#endif +} +std::vector CSDL_Ext::getSupportedResolutions() +{ + int displayID = SDL_GetWindowDisplayIndex(mainWindow); + return getSupportedResolutions(displayID); +} + +std::vector CSDL_Ext::getSupportedResolutions( int displayIndex) +{ + std::vector result; + + int modesCount = SDL_GetNumDisplayModes(displayIndex); + + for (int i =0; i < modesCount; ++i) + { + SDL_DisplayMode mode; + if (SDL_GetDisplayMode(displayIndex, i, &mode) != 0) + continue; + + Point resolution(mode.w, mode.h); + + result.push_back(resolution); + } + return result; +} template SDL_Surface * CSDL_Ext::createSurfaceWithBpp<2>(int, int); template SDL_Surface * CSDL_Ext::createSurfaceWithBpp<3>(int, int); diff --git a/client/renderSDL/SDL_Extensions.h b/client/renderSDL/SDL_Extensions.h index 483531289..c369205b5 100644 --- a/client/renderSDL/SDL_Extensions.h +++ b/client/renderSDL/SDL_Extensions.h @@ -130,6 +130,11 @@ typedef void (*TColorPutterAlpha)(uint8_t *&ptr, const uint8_t & R, const uint8_ void applyEffectBpp( SDL_Surface * surf, const Rect & rect, int mode ); void applyEffect(SDL_Surface * surf, const Rect & rect, int mode); //mode: 0 - sepia, 1 - grayscale + bool isResolutionSupported(const std::vector & resolutions, const Point toTest ); + + std::vector getSupportedResolutions(); + std::vector getSupportedResolutions( int displayIndex); + void setColorKey(SDL_Surface * surface, SDL_Color color); ///set key-color to 0,255,255 diff --git a/client/windows/GUIClasses.cpp b/client/windows/GUIClasses.cpp index 63cee346b..e1bc4b1c9 100644 --- a/client/windows/GUIClasses.cpp +++ b/client/windows/GUIClasses.cpp @@ -63,6 +63,8 @@ #include "../lib/NetPacksBase.h" #include "../lib/StartInfo.h" +#include + CRecruitmentWindow::CCreatureCard::CCreatureCard(CRecruitmentWindow * window, const CCreature * crea, int totalAmount) : CIntObject(LCLICK | RCLICK), parent(window), @@ -582,30 +584,8 @@ void CSystemOptionsWindow::setFullscreenMode( bool on) } } -void CSystemOptionsWindow::fillSupportedResolutions() -{ - supportedResolutions.clear(); - - // in game we can only change resolution, display is fixed - int displayID = SDL_GetWindowDisplayIndex(mainWindow); - - int modesCount = SDL_GetNumDisplayModes(displayID); - - for (int i =0; i < modesCount; ++i) - { - SDL_DisplayMode mode; - if (SDL_GetDisplayMode(displayID, i, &mode) != 0) - continue; - - Point resolution(mode.w, mode.h); - - supportedResolutions.push_back(resolution); - } -} - void CSystemOptionsWindow::fillSelectableResolutions() { - fillSupportedResolutions(); selectableResolutions.clear(); for(const auto & it : conf.guiOptions) @@ -629,18 +609,12 @@ bool CSystemOptionsWindow::isResolutionSupported(const Point & resolution) bool CSystemOptionsWindow::isResolutionSupported(const Point & resolution, bool fullscreen) { -#ifdef VCMI_IOS - // ios can use any resolution - bool canUseAllResolutions = true; -#else - // in fullscreen only resolutions supported by monitor can be used - bool canUseAllResolutions = (fullscreen == false); -#endif - - if (canUseAllResolutions) + if (!fullscreen) return true; - return vstd::contains(supportedResolutions, resolution); + auto supportedList = CSDL_Ext::getSupportedResolutions(); + + return CSDL_Ext::isResolutionSupported(supportedList, resolution); } void CSystemOptionsWindow::selectGameRes() diff --git a/client/windows/GUIClasses.h b/client/windows/GUIClasses.h index fa71e36eb..fc3f9df6f 100644 --- a/client/windows/GUIClasses.h +++ b/client/windows/GUIClasses.h @@ -238,7 +238,6 @@ private: void bmainmenuf(); //return to main menu void setFullscreenMode( bool on); - void fillSupportedResolutions(); void fillSelectableResolutions(); bool isResolutionSupported(const Point & resolution); bool isResolutionSupported(const Point & resolution, bool fullscreen); From 286c1e522efd26e437ee4fb728c42fb9c67af7d0 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 9 Feb 2023 19:06:02 +0300 Subject: [PATCH 03/10] vcmi: modernize netpacks --- lib/CGameState.cpp | 2 +- lib/NetPacks.h | 747 ++++++++++++++++++++------------------------ lib/NetPacksBase.h | 103 ++---- lib/NetPacksLib.cpp | 233 +++++++------- lib/NetPacksLobby.h | 57 ++-- 5 files changed, 505 insertions(+), 637 deletions(-) diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index f3b181161..c6a18fd63 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -274,7 +274,7 @@ DLL_LINKAGE std::string MetaString::buildList () const return lista; } -void MetaString::addCreReplacement(CreatureID id, TQuantity count) //adds sing or plural name; +void MetaString::addCreReplacement(const CreatureID & id, TQuantity count) //adds sing or plural name; { if (!count) addReplacement (CRE_PL_NAMES, id); //no creatures - just empty name (eg. defeat Angels) diff --git a/lib/NetPacks.h b/lib/NetPacks.h index 092e76061..bc3b21b3a 100644 --- a/lib/NetPacks.h +++ b/lib/NetPacks.h @@ -39,10 +39,6 @@ class IBattleState; struct Query : public CPackForClient { QueryID queryID; // equals to -1 if it is not an actual query (and should not be answered) - - Query() - { - } }; struct StackLocation @@ -50,11 +46,10 @@ struct StackLocation ConstTransitivePtr army; SlotID slot; - StackLocation() - {} - StackLocation(const CArmedInstance *Army, SlotID Slot): - army(const_cast(Army)), //we are allowed here to const cast -> change will go through one of our packages... do not abuse! - slot(Slot) + StackLocation() = default; + StackLocation(const CArmedInstance * Army, const SlotID & Slot) + : army(const_cast(Army)) //we are allowed here to const cast -> change will go through one of our packages... do not abuse! + , slot(Slot) { } @@ -71,17 +66,16 @@ struct StackLocation struct PackageApplied : public CPackForClient { - PackageApplied() - : result(0), packType(0),requestID(0) - {} + PackageApplied() = default; PackageApplied(ui8 Result) - : result(Result), packType(0), requestID(0) - {} + : result(Result) + { + } void applyCl(CClient *cl); - ui8 result; //0 - something went wrong, request hasn't been realized; 1 - OK - ui32 packType; //type id of applied package - ui32 requestID; //an ID given by client to the request that was applied + ui8 result = 0; //0 - something went wrong, request hasn't been realized; 1 - OK + ui32 packType = 0; //type id of applied package + ui32 requestID = 0; //an ID given by client to the request that was applied PlayerColor player; template void serialize(Handler &h, const int version) @@ -95,8 +89,11 @@ struct PackageApplied : public CPackForClient struct SystemMessage : public CPackForClient { - SystemMessage(const std::string & Text) : text(Text){} - SystemMessage(){} + SystemMessage(std::string Text) + : text(std::move(Text)) + { + } + SystemMessage() = default; void applyCl(CClient *cl); std::string text; @@ -109,14 +106,13 @@ struct SystemMessage : public CPackForClient struct PlayerBlocked : public CPackForClient { - PlayerBlocked() : reason(UPCOMING_BATTLE), startOrEnd(BLOCKADE_STARTED) {} void applyCl(CClient *cl); enum EReason { UPCOMING_BATTLE, ONGOING_MOVEMENT }; enum EMode { BLOCKADE_STARTED, BLOCKADE_ENDED }; - EReason reason; - EMode startOrEnd; + EReason reason = UPCOMING_BATTLE; + EMode startOrEnd = BLOCKADE_STARTED; PlayerColor player; template void serialize(Handler &h, const int version) @@ -129,12 +125,11 @@ struct PlayerBlocked : public CPackForClient struct PlayerCheated : public CPackForClient { - PlayerCheated() : losingCheatCode(false), winningCheatCode(false) {} - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; PlayerColor player; - bool losingCheatCode; - bool winningCheatCode; + bool losingCheatCode = false; + bool winningCheatCode = false; template void serialize(Handler &h, const int version) { @@ -146,9 +141,8 @@ struct PlayerCheated : public CPackForClient struct YourTurn : public CPackForClient { - YourTurn(){} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; PlayerColor player; boost::optional daysWithoutCastle; @@ -164,7 +158,6 @@ struct EntitiesChanged: public CPackForClient { std::vector changes; - EntitiesChanged(){}; void applyCl(CClient * cl); DLL_LINKAGE void applyGs(CGameState * gs); @@ -176,11 +169,10 @@ struct EntitiesChanged: public CPackForClient struct SetResources : public CPackForClient { - SetResources():abs(true){}; void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - bool abs; //false - changes by value; 1 - sets to value + bool abs = true; //false - changes by value; 1 - sets to value PlayerColor player; TResources res; //res[resid] => res amount @@ -194,16 +186,13 @@ struct SetResources : public CPackForClient struct SetPrimSkill : public CPackForClient { - SetPrimSkill() - : abs(0), which(PrimarySkill::ATTACK), val(0) - {} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - ui8 abs; //0 - changes by value; 1 - sets to value + ui8 abs = 0; //0 - changes by value; 1 - sets to value ObjectInstanceID id; - PrimarySkill::PrimarySkill which; - si64 val; + PrimarySkill::PrimarySkill which = PrimarySkill::ATTACK; + si64 val = 0; template void serialize(Handler &h, const int version) { @@ -216,16 +205,13 @@ struct SetPrimSkill : public CPackForClient struct SetSecSkill : public CPackForClient { - SetSecSkill() - : abs(0), val(0) - {} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - ui8 abs; //0 - changes by value; 1 - sets to value + ui8 abs = 0; //0 - changes by value; 1 - sets to value ObjectInstanceID id; SecondarySkill which; - ui16 val; + ui16 val = 0; template void serialize(Handler &h, const int version) { @@ -238,14 +224,13 @@ struct SetSecSkill : public CPackForClient struct HeroVisitCastle : public CPackForClient { - HeroVisitCastle(){flags=0;}; void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - ui8 flags; //1 - start + ui8 flags = 0; //1 - start ObjectInstanceID tid, hid; - bool start() //if hero is entering castle (if false - leaving) + bool start() const //if hero is entering castle (if false - leaving) { return flags & 1; } @@ -260,11 +245,10 @@ struct HeroVisitCastle : public CPackForClient struct ChangeSpells : public CPackForClient { - ChangeSpells():learn(1){} void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); - ui8 learn; //1 - gives spell, 0 - takes + ui8 learn = 1; //1 - gives spell, 0 - takes ObjectInstanceID hid; std::set spells; @@ -278,14 +262,12 @@ struct ChangeSpells : public CPackForClient struct SetMana : public CPackForClient { - SetMana(){val = 0; absolute=true;} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); - + DLL_LINKAGE void applyGs(CGameState * gs) const; ObjectInstanceID hid; - si32 val; - bool absolute; + si32 val = 0; + bool absolute = true; template void serialize(Handler &h, const int version) { @@ -297,13 +279,12 @@ struct SetMana : public CPackForClient struct SetMovePoints : public CPackForClient { - SetMovePoints(){val = 0; absolute=true;} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; ObjectInstanceID hid; - si32 val; - bool absolute; + si32 val = 0; + bool absolute = true; template void serialize(Handler &h, const int version) { @@ -315,14 +296,13 @@ struct SetMovePoints : public CPackForClient struct FoWChange : public CPackForClient { - FoWChange(){mode = 0; waitForDialogs = false;} void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); std::unordered_set tiles; PlayerColor player; - ui8 mode; //mode==0 - hide, mode==1 - reveal - bool waitForDialogs; + ui8 mode = 0; //mode==0 - hide, mode==1 - reveal + bool waitForDialogs = false; template void serialize(Handler &h, const int version) { h & tiles; @@ -336,8 +316,8 @@ struct SetAvailableHeroes : public CPackForClient { SetAvailableHeroes() { - for (int i = 0; i < GameConstants::AVAILABLE_HEROES_PER_PLAYER; i++) - army[i].clear(); + for(auto & i : army) + i.clear(); } void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); @@ -356,17 +336,15 @@ struct SetAvailableHeroes : public CPackForClient struct GiveBonus : public CPackForClient { GiveBonus(ui8 Who = 0) + : who(Who) { - who = Who; - id = 0; } - void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); enum {HERO, PLAYER, TOWN}; - ui8 who; //who receives bonus, uses enum above - si32 id; //hero. town or player id - whoever receives it + ui8 who = 0; //who receives bonus, uses enum above + si32 id = 0; //hero. town or player id - whoever receives it Bonus bonus; MetaString bdescr; @@ -382,17 +360,13 @@ struct GiveBonus : public CPackForClient struct ChangeObjPos : public CPackForClient { - ChangeObjPos() - { - flags = 0; - } void applyFirstCl(CClient *cl); void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); ObjectInstanceID objid; int3 nPos; - ui8 flags; //bit flags: 1 - redraw + ui8 flags = 0; //bit flags: 1 - redraw template void serialize(Handler &h, const int version) { @@ -404,12 +378,8 @@ struct ChangeObjPos : public CPackForClient struct PlayerEndsGame : public CPackForClient { - PlayerEndsGame() - { - } - void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; PlayerColor player; EVictoryLossCheckResult victoryLossCheckResult; @@ -439,11 +409,8 @@ struct PlayerReinitInterface : public CPackForClient struct RemoveBonus : public CPackForClient { RemoveBonus(ui8 Who = 0) + : who(Who) { - who = Who; - whoID = 0; - source = 0; - id = 0; } void applyCl(CClient *cl); @@ -451,11 +418,11 @@ struct RemoveBonus : public CPackForClient enum {HERO, PLAYER, TOWN}; ui8 who; //who receives bonus, uses enum above - ui32 whoID; //hero, town or player id - whoever loses bonus + ui32 whoID = 0; //hero, town or player id - whoever loses bonus //vars to identify bonus: its source - ui8 source; - ui32 id; //source id + ui8 source = 0; + ui32 id = 0; //source id //used locally: copy of removed bonus Bonus bonus; @@ -473,17 +440,14 @@ struct SetCommanderProperty : public CPackForClient { enum ECommanderProperty {ALIVE, BONUS, SECONDARY_SKILL, EXPERIENCE, SPECIAL_SKILL}; - SetCommanderProperty() - :which(ALIVE), amount(0), additionalInfo(0) - {} - void applyCl(CClient *cl){}; + void applyCl(CClient *cl){} DLL_LINKAGE void applyGs(CGameState *gs); ObjectInstanceID heroid; - ECommanderProperty which; - TExpType amount; //0 for dead, >0 for alive - si32 additionalInfo; //for secondary skills choice + ECommanderProperty which = ALIVE; + TExpType amount = 0; //0 for dead, >0 for alive + si32 additionalInfo = 0; //for secondary skills choice Bonus accumulatedBonus; template void serialize(Handler &h, const int version) @@ -498,9 +462,8 @@ struct SetCommanderProperty : public CPackForClient struct AddQuest : public CPackForClient { - AddQuest(){}; - void applyCl(CClient *cl){}; - DLL_LINKAGE void applyGs(CGameState *gs); + void applyCl(CClient *cl){} + DLL_LINKAGE void applyGs(CGameState * gs) const; PlayerColor player; QuestInfo quest; @@ -514,10 +477,9 @@ struct AddQuest : public CPackForClient struct UpdateArtHandlerLists : public CPackForClient { - UpdateArtHandlerLists(){} std::vector treasures, minors, majors, relics; - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; template void serialize(Handler &h, const int version) { h & treasures; @@ -529,10 +491,9 @@ struct UpdateArtHandlerLists : public CPackForClient struct UpdateMapEvents : public CPackForClient { - UpdateMapEvents(){} std::list events; - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; template void serialize(Handler &h, const int version) { h & events; @@ -541,12 +502,11 @@ struct UpdateMapEvents : public CPackForClient struct UpdateCastleEvents : public CPackForClient { - UpdateCastleEvents(){} ObjectInstanceID town; std::list events; - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; template void serialize(Handler &h, const int version) { h & town; @@ -556,12 +516,11 @@ struct UpdateCastleEvents : public CPackForClient struct ChangeFormation : public CPackForClient { - ChangeFormation():formation(0){} ObjectInstanceID hid; - ui8 formation; + ui8 formation = 0; - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; template void serialize(Handler &h, const int version) { h & hid; @@ -571,8 +530,10 @@ struct ChangeFormation : public CPackForClient struct RemoveObject : public CPackForClient { - RemoveObject(){} - RemoveObject(ObjectInstanceID ID){id = ID;}; + RemoveObject() = default; + RemoveObject(const ObjectInstanceID & ID) + : id(ID) + {} void applyFirstCl(CClient *cl); void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); @@ -587,26 +548,29 @@ struct RemoveObject : public CPackForClient struct TryMoveHero : public CPackForClient { - TryMoveHero() - : movePoints(0), result(FAILED), humanKnows(false) - {} void applyFirstCl(CClient *cl); void applyCl(CClient *cl); void applyGs(CGameState *gs); enum EResult { - FAILED, SUCCESS, TELEPORTATION, RESERVED___, BLOCKING_VISIT, EMBARK, DISEMBARK + FAILED, + SUCCESS, + TELEPORTATION, + RESERVED_, + BLOCKING_VISIT, + EMBARK, + DISEMBARK }; ObjectInstanceID id; - ui32 movePoints; - EResult result; //uses EResult + ui32 movePoints = 0; + EResult result = FAILED; //uses EResult int3 start, end; //h3m format std::unordered_set fowRevealed; //revealed tiles boost::optional attackedFrom; // Set when stepping into endangered tile. - bool humanKnows; //used locally during applying to client + bool humanKnows = false; //used locally during applying to client bool stopMovement() const; @@ -624,13 +588,12 @@ struct TryMoveHero : public CPackForClient struct NewStructures : public CPackForClient { - NewStructures():builded(0){} void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); ObjectInstanceID tid; std::set bid; - si16 builded; + si16 builded = 0; template void serialize(Handler &h, const int version) { @@ -642,13 +605,12 @@ struct NewStructures : public CPackForClient struct RazeStructures : public CPackForClient { - RazeStructures():destroyed(0){} void applyCl (CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); ObjectInstanceID tid; std::set bid; - si16 destroyed; + si16 destroyed = 0; template void serialize(Handler &h, const int version) { @@ -660,9 +622,8 @@ struct RazeStructures : public CPackForClient struct SetAvailableCreatures : public CPackForClient { - SetAvailableCreatures(){} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; ObjectInstanceID tid; std::vector > > creatures; @@ -676,9 +637,8 @@ struct SetAvailableCreatures : public CPackForClient struct SetHeroesInTown : public CPackForClient { - SetHeroesInTown(){} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; ObjectInstanceID tid, visiting, garrison; //id of town, visiting hero, hero in garrison @@ -692,11 +652,10 @@ struct SetHeroesInTown : public CPackForClient struct HeroRecruited : public CPackForClient { - HeroRecruited():hid(-1){} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - si32 hid;//subID of hero + si32 hid = -1; //subID of hero ObjectInstanceID tid; int3 tile; PlayerColor player; @@ -712,10 +671,9 @@ struct HeroRecruited : public CPackForClient struct GiveHero : public CPackForClient { - GiveHero(){} void applyFirstCl(CClient *cl); void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; ObjectInstanceID id; //object id PlayerColor player; @@ -729,13 +687,13 @@ struct GiveHero : public CPackForClient struct OpenWindow : public CPackForClient { - OpenWindow():id1(-1),id2(-1){} void applyCl(CClient *cl); enum EWindow {EXCHANGE_WINDOW, RECRUITMENT_FIRST, RECRUITMENT_ALL, SHIPYARD_WINDOW, THIEVES_GUILD, UNIVERSITY_WINDOW, HILL_FORT_WINDOW, MARKET_WINDOW, PUZZLE_MAP, TAVERN_WINDOW}; ui8 window; - si32 id1, id2; + si32 id1 = -1; + si32 id2 = -1; template void serialize(Handler &h, const int version) { @@ -747,12 +705,11 @@ struct OpenWindow : public CPackForClient struct NewObject : public CPackForClient { - NewObject():subID(0){} void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); Obj ID; - ui32 subID; + ui32 subID = 0; int3 pos; ObjectInstanceID id; //used locally, filled during applyGs @@ -767,11 +724,10 @@ struct NewObject : public CPackForClient struct SetAvailableArtifacts : public CPackForClient { - SetAvailableArtifacts():id(0){} void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - si32 id; //two variants: id < 0: set artifact pool for Artifact Merchants in towns; id >= 0: set pool for adv. map Black Market (id is the id of Black Market instance then) + si32 id = 0; //two variants: id < 0: set artifact pool for Artifact Merchants in towns; id >= 0: set pool for adv. map Black Market (id is the id of Black Market instance then) std::vector arts; template void serialize(Handler &h, const int version) @@ -783,8 +739,6 @@ struct SetAvailableArtifacts : public CPackForClient struct NewArtifact : public CPackForClient { - NewArtifact(){} - DLL_LINKAGE void applyGs(CGameState *gs); ConstTransitivePtr art; @@ -874,12 +828,7 @@ struct InsertNewStack : CGarrisonOperationPack ObjectInstanceID army; SlotID slot; CreatureID type; - TQuantity count; - - InsertNewStack() - : count(0) - { - } + TQuantity count = 0; void applyCl(CClient * cl); DLL_LINKAGE void applyGs(CGameState * gs); @@ -994,12 +943,12 @@ struct EraseArtifact : CArtifactOperationPack struct MoveArtifact : CArtifactOperationPack { - MoveArtifact() - : askAssemble(true) {} + MoveArtifact() = default; MoveArtifact(ArtifactLocation * src, ArtifactLocation * dst, bool askAssemble = true) - : src(*src), dst(*dst), askAssemble(askAssemble){} + : src(*src), dst(*dst), askAssemble(askAssemble) + {} ArtifactLocation src, dst; - bool askAssemble; + bool askAssemble = true; void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); @@ -1019,9 +968,12 @@ struct BulkMoveArtifacts : CArtifactOperationPack ArtifactPosition srcPos; ArtifactPosition dstPos; - LinkedSlots() {} - LinkedSlots(ArtifactPosition srcPos, ArtifactPosition dstPos) - : srcPos(srcPos), dstPos(dstPos) {} + LinkedSlots() = default; + LinkedSlots(const ArtifactPosition & srcPos, const ArtifactPosition & dstPos) + : srcPos(srcPos) + , dstPos(dstPos) + { + } template void serialize(Handler & h, const int version) { h & srcPos; @@ -1035,7 +987,11 @@ struct BulkMoveArtifacts : CArtifactOperationPack BulkMoveArtifacts() : swap(false) {} BulkMoveArtifacts(TArtHolder srcArtHolder, TArtHolder dstArtHolder, bool swap) - : srcArtHolder(srcArtHolder), dstArtHolder(dstArtHolder), swap(swap) {} + : srcArtHolder(std::move(std::move(srcArtHolder))) + , dstArtHolder(std::move(std::move(dstArtHolder))) + , swap(swap) + { + } void applyCl(CClient * cl); DLL_LINKAGE void applyGs(CGameState * gs); @@ -1126,11 +1082,11 @@ struct NewTurn : public CPackForClient std::set heroes; //updates movement and mana points std::map res; //player ID => resource value[res_id] std::map cres;//creatures to be placed in towns - ui32 day; - ui8 specialWeek; //weekType + ui32 day = 0; + ui8 specialWeek = 0; //weekType CreatureID creatureid; //for creature weeks - NewTurn():day(0),specialWeek(0){}; + NewTurn() = default; template void serialize(Handler &h, const int version) { @@ -1150,7 +1106,7 @@ struct InfoWindow : public CPackForClient //103 - displays simple info window MetaString text; std::vector components; PlayerColor player; - ui16 soundID; + ui16 soundID = 0; template void serialize(Handler &h, const int version) { @@ -1159,10 +1115,7 @@ struct InfoWindow : public CPackForClient //103 - displays simple info window h & player; h & soundID; } - InfoWindow() - { - soundID = 0; - } + InfoWindow() = default; }; namespace ObjProperty @@ -1184,14 +1137,18 @@ namespace ObjProperty struct SetObjectProperty : public CPackForClient { - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; void applyCl(CClient *cl); ObjectInstanceID id; - ui8 what; // see ObjProperty enum - ui32 val; - SetObjectProperty():what(0),val(0){} - SetObjectProperty(ObjectInstanceID ID, ui8 What, ui32 Val):id(ID),what(What),val(Val){}; + ui8 what = 0; // see ObjProperty enum + ui32 val = 0; + SetObjectProperty() = default; + SetObjectProperty(const ObjectInstanceID & ID, ui8 What, ui32 Val) + : id(ID) + , what(What) + , val(Val) + {} template void serialize(Handler &h, const int version) { @@ -1210,20 +1167,18 @@ struct ChangeObjectVisitors : public CPackForClient VISITOR_REMOVE, // unmark visitor, reversed to ADD VISITOR_CLEAR // clear all visitors from this object (object reset) }; - ui32 mode; // uses VisitMode enum + ui32 mode = VISITOR_CLEAR; // uses VisitMode enum ObjectInstanceID object; ObjectInstanceID hero; // note: hero owner will be also marked as "visited" this object - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - ChangeObjectVisitors() - : mode(VISITOR_CLEAR) - {} + ChangeObjectVisitors() = default; - ChangeObjectVisitors(ui32 mode, ObjectInstanceID object, ObjectInstanceID heroID = ObjectInstanceID(-1)): - mode(mode), - object(object), - hero(heroID) + ChangeObjectVisitors(ui32 mode, const ObjectInstanceID & object, const ObjectInstanceID & heroID = ObjectInstanceID(-1)) + : mode(mode) + , object(object) + , hero(heroID) {} template void serialize(Handler &h, const int version) @@ -1241,8 +1196,6 @@ struct PrepareHeroLevelUp : public CPackForClient /// Do not serialize, used by server only std::vector skills; - PrepareHeroLevelUp(){} - DLL_LINKAGE void applyGs(CGameState * gs); template void serialize(Handler &h, const int version) @@ -1256,13 +1209,11 @@ struct HeroLevelUp : public Query PlayerColor player; ObjectInstanceID heroId; - PrimarySkill::PrimarySkill primskill; + PrimarySkill::PrimarySkill primskill = PrimarySkill::ATTACK; std::vector skills; - HeroLevelUp(): primskill(PrimarySkill::ATTACK){} - void applyCl(CClient * cl); - DLL_LINKAGE void applyGs(CGameState * gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; template void serialize(Handler & h, const int version) { @@ -1281,10 +1232,8 @@ struct CommanderLevelUp : public Query std::vector skills; //0-5 - secondary skills, val-100 - special skill - CommanderLevelUp(){} - void applyCl(CClient * cl); - DLL_LINKAGE void applyGs(CGameState * gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; template void serialize(Handler & h, const int version) { @@ -1307,8 +1256,8 @@ struct BlockingDialog : public Query MetaString text; std::vector components; PlayerColor player; - ui8 flags; - ui16 soundID; + ui8 flags = 0; + ui16 soundID = 0; bool cancel() const { @@ -1321,16 +1270,10 @@ struct BlockingDialog : public Query BlockingDialog(bool yesno, bool Selection) { - flags = 0; - soundID = 0; if(yesno) flags |= ALLOW_CANCEL; if(Selection) flags |= SELECTION; } - BlockingDialog() - { - flags = 0; - soundID = 0; - }; + BlockingDialog() = default; template void serialize(Handler &h, const int version) { @@ -1345,10 +1288,9 @@ struct BlockingDialog : public Query struct GarrisonDialog : public Query { - GarrisonDialog():removableUnits(false){} void applyCl(CClient *cl); ObjectInstanceID objid, hid; - bool removableUnits; + bool removableUnits = false; template void serialize(Handler &h, const int version) { @@ -1361,7 +1303,6 @@ struct GarrisonDialog : public Query struct ExchangeDialog : public Query { - ExchangeDialog() {} void applyCl(CClient *cl); PlayerColor player; @@ -1380,12 +1321,11 @@ struct ExchangeDialog : public Query struct TeleportDialog : public Query { - TeleportDialog() - : impassable(false) - {} + TeleportDialog() = default; - TeleportDialog(PlayerColor Player, TeleportChannelID Channel) - : player(Player), channel(Channel), impassable(false) + TeleportDialog(const PlayerColor & Player, const TeleportChannelID & Channel) + : player(Player) + , channel(Channel) {} void applyCl(CClient *cl); @@ -1393,7 +1333,7 @@ struct TeleportDialog : public Query PlayerColor player; TeleportChannelID channel; TTeleportExitsList exits; - bool impassable; + bool impassable = false; template void serialize(Handler &h, const int version) { @@ -1413,8 +1353,6 @@ struct MapObjectSelectDialog : public Query MetaString description; std::vector objects; - MapObjectSelectDialog(){}; - void applyCl(CClient * cl); template void serialize(Handler & h, const int version) @@ -1431,16 +1369,11 @@ struct MapObjectSelectDialog : public Query class BattleInfo; struct BattleStart : public CPackForClient { - BattleStart() - :info(nullptr) - {} - void applyFirstCl(CClient *cl); void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); - - BattleInfo * info; + DLL_LINKAGE void applyGs(CGameState * gs) const; + BattleInfo * info = nullptr; template void serialize(Handler &h, const int version) { @@ -1450,11 +1383,10 @@ struct BattleStart : public CPackForClient struct BattleNextRound : public CPackForClient { - BattleNextRound():round(0){}; void applyFirstCl(CClient *cl); void applyCl(CClient *cl); - DLL_LINKAGE void applyGs( CGameState *gs ); - si32 round; + DLL_LINKAGE void applyGs(CGameState * gs) const; + si32 round = 0; template void serialize(Handler &h, const int version) { @@ -1464,17 +1396,11 @@ struct BattleNextRound : public CPackForClient struct BattleSetActiveStack : public CPackForClient { - BattleSetActiveStack() - { - stack = 0; - askPlayerInterface = true; - } - void applyCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - ui32 stack; - ui8 askPlayerInterface; + ui32 stack = 0; + ui8 askPlayerInterface = true; template void serialize(Handler &h, const int version) { @@ -1487,19 +1413,13 @@ struct BattleResult : public CPackForClient { enum EResult {NORMAL = 0, ESCAPE = 1, SURRENDER = 2}; - BattleResult() - : result(NORMAL), winner(2) - { - exp[0] = 0; - exp[1] = 0; - }; void applyFirstCl(CClient *cl); void applyGs(CGameState *gs); - EResult result; - ui8 winner; //0 - attacker, 1 - defender, [2 - draw (should be possible?)] + EResult result = NORMAL; + ui8 winner = 2; //0 - attacker, 1 - defender, [2 - draw (should be possible?)] std::map casualties[2]; //first => casualties of attackers - map crid => number - TExpType exp[2]; //exp for attacker and defender + TExpType exp[2] = {0, 0}; //exp for attacker and defender std::set artifacts; //artifacts taken from loser to winner - currently unused template void serialize(Handler &h, const int version) @@ -1517,8 +1437,6 @@ struct BattleLogMessage : public CPackForClient { std::vector lines; - BattleLogMessage(){} - void applyCl(CClient * cl); DLL_LINKAGE void applyGs(CGameState * gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); @@ -1531,15 +1449,10 @@ struct BattleLogMessage : public CPackForClient struct BattleStackMoved : public CPackForClient { - ui32 stack; + ui32 stack = 0; std::vector tilesToMove; - int distance; - bool teleporting; - BattleStackMoved() - : stack(0), - distance(0), - teleporting(false) - {}; + int distance = 0; + bool teleporting = false; void applyFirstCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); @@ -1554,8 +1467,6 @@ struct BattleStackMoved : public CPackForClient struct BattleUnitsChanged : public CPackForClient { - BattleUnitsChanged(){} - DLL_LINKAGE void applyGs(CGameState *gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); void applyCl(CClient *cl); @@ -1570,26 +1481,16 @@ struct BattleUnitsChanged : public CPackForClient struct BattleStackAttacked { - BattleStackAttacked(): - stackAttacked(0), - attackerID(0), - killedAmount(0), - damageAmount(0), - newState(), - flags(0), - spellID(SpellID::NONE) - {}; - DLL_LINKAGE void applyGs(CGameState *gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); - ui32 stackAttacked, attackerID; - ui32 killedAmount; - int64_t damageAmount; + ui32 stackAttacked = 0, attackerID = 0; + ui32 killedAmount = 0; + int64_t damageAmount = 0; UnitChanges newState; enum EFlags {KILLED = 1, SECONDARY = 2, REBIRTH = 4, CLONE_KILLED = 8, SPELL_EFFECT = 16, FIRE_SHIELD = 32, }; - ui32 flags; //uses EFlags (above) - SpellID spellID; //only if flag SPELL_EFFECT is set + ui32 flags = 0; //uses EFlags (above) + SpellID spellID = SpellID::NONE; //only if flag SPELL_EFFECT is set bool killed() const//if target stack was killed { @@ -1634,9 +1535,6 @@ struct BattleStackAttacked struct BattleAttack : public CPackForClient { - BattleAttack() - : stackAttacking(0), flags(0), spellID(SpellID::NONE) - {}; void applyFirstCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); void applyCl(CClient *cl); @@ -1644,12 +1542,12 @@ struct BattleAttack : public CPackForClient BattleUnitsChanged attackerChanges; std::vector bsa; - ui32 stackAttacking; - ui32 flags; //uses Eflags (below) + ui32 stackAttacking = 0; + ui32 flags = 0; //uses Eflags (below) enum EFlags{SHOT = 1, COUNTER = 2, LUCKY = 4, UNLUCKY = 8, BALLISTA_DOUBLE_DMG = 16, DEATH_BLOW = 32, SPELL_LIKE = 64, LIFE_DRAIN = 128}; BattleHex tile; - SpellID spellID; //for SPELL_LIKE + SpellID spellID = SpellID::NONE; //for SPELL_LIKE bool shot() const//distance attack - decrease number of shots { @@ -1696,8 +1594,10 @@ struct BattleAttack : public CPackForClient struct StartAction : public CPackForClient { - StartAction(){}; - StartAction(const BattleAction &act){ba = act; }; + StartAction() = default; + StartAction(BattleAction act) + : ba(std::move(act)) + {} void applyFirstCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); @@ -1710,7 +1610,6 @@ struct StartAction : public CPackForClient struct EndAction : public CPackForClient { - EndAction(){}; void applyCl(CClient *cl); template void serialize(Handler &h, const int version) @@ -1720,27 +1619,19 @@ struct EndAction : public CPackForClient struct BattleSpellCast : public CPackForClient { - BattleSpellCast() - { - side = 0; - manaGained = 0; - casterStack = -1; - castByHero = true; - activeCast = true; - }; - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; void applyCl(CClient *cl); - bool activeCast; - ui8 side; //which hero did cast spell: 0 - attacker, 1 - defender + bool activeCast = true; + ui8 side = 0; //which hero did cast spell: 0 - attacker, 1 - defender SpellID spellID; //id of spell - ui8 manaGained; //mana channeling ability + ui8 manaGained = 0; //mana channeling ability BattleHex tile; //destination tile (may not be set in some global/mass spells std::set affectedCres; //ids of creatures affected by this spell, generally used if spell does not set any effect (like dispel or cure) std::set resistedCres; // creatures that resisted the spell (e.g. Dwarves) std::set reflectedCres; // creatures that reflected the spell (e.g. Magic Mirror spell) - si32 casterStack;// -1 if not cated by creature, >=0 caster stack ID - bool castByHero; //if true - spell has been cast by hero, otherwise by a creature + si32 casterStack = -1; // -1 if not cated by creature, >=0 caster stack ID + bool castByHero = true; //if true - spell has been cast by hero, otherwise by a creature template void serialize(Handler &h, const int version) { @@ -1759,7 +1650,6 @@ struct BattleSpellCast : public CPackForClient struct SetStackEffect : public CPackForClient { - SetStackEffect(){}; DLL_LINKAGE void applyGs(CGameState * gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); void applyCl(CClient * cl); @@ -1778,7 +1668,6 @@ struct SetStackEffect : public CPackForClient struct StacksInjured : public CPackForClient { - StacksInjured(){} DLL_LINKAGE void applyGs(CGameState * gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); @@ -1794,8 +1683,6 @@ struct StacksInjured : public CPackForClient struct BattleResultsApplied : public CPackForClient { - BattleResultsApplied(){} - PlayerColor player1, player2; void applyCl(CClient *cl); @@ -1808,8 +1695,6 @@ struct BattleResultsApplied : public CPackForClient struct BattleObstaclesChanged : public CPackForClient { - BattleObstaclesChanged(){} - DLL_LINKAGE void applyGs(CGameState * gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); void applyCl(CClient * cl); @@ -1839,14 +1724,14 @@ struct ELF_VISIBILITY CatapultAttack : public CPackForClient }; DLL_LINKAGE CatapultAttack(); - DLL_LINKAGE ~CatapultAttack(); + DLL_LINKAGE ~CatapultAttack() override; DLL_LINKAGE void applyGs(CGameState * gs); DLL_LINKAGE void applyBattle(IBattleState * battleState); void applyCl(CClient * cl); std::vector< AttackInfo > attackedParts; - int attacker; //if -1, then a spell caused this + int attacker = -1; //if -1, then a spell caused this template void serialize(Handler &h, const int version) { @@ -1857,18 +1742,14 @@ struct ELF_VISIBILITY CatapultAttack : public CPackForClient struct BattleSetStackProperty : public CPackForClient { - BattleSetStackProperty() - : stackID(0), which(CASTS), val(0), absolute(0) - {}; - enum BattleStackProperty {CASTS, ENCHANTER_COUNTER, UNBIND, CLONED, HAS_CLONE}; - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - int stackID; - BattleStackProperty which; - int val; - int absolute; + int stackID = 0; + BattleStackProperty which = CASTS; + int val = 0; + int absolute = 0; template void serialize(Handler &h, const int version) { @@ -1882,17 +1763,13 @@ struct BattleSetStackProperty : public CPackForClient ///activated at the beginning of turn struct BattleTriggerEffect : public CPackForClient { - BattleTriggerEffect() - : stackID(0), effect(0), val(0), additionalInfo(0) - {}; - - DLL_LINKAGE void applyGs(CGameState *gs); //effect + DLL_LINKAGE void applyGs(CGameState * gs) const; //effect void applyCl(CClient *cl); //play animations & stuff - int stackID; - int effect; //use corresponding Bonus type - int val; - int additionalInfo; + int stackID = 0; + int effect = 0; //use corresponding Bonus type + int val = 0; + int additionalInfo = 0; template void serialize(Handler &h, const int version) { @@ -1905,13 +1782,11 @@ struct BattleTriggerEffect : public CPackForClient struct BattleUpdateGateState : public CPackForClient { - BattleUpdateGateState():state(EGateState::NONE){}; - void applyFirstCl(CClient *cl); - DLL_LINKAGE void applyGs(CGameState *gs); + DLL_LINKAGE void applyGs(CGameState * gs) const; - EGateState state; + EGateState state = EGateState::NONE; template void serialize(Handler &h, const int version) { h & state; @@ -1920,7 +1795,6 @@ struct BattleUpdateGateState : public CPackForClient struct ShowInInfobox : public CPackForClient { - ShowInInfobox(){}; PlayerColor player; Component c; MetaString text; @@ -1936,7 +1810,6 @@ struct ShowInInfobox : public CPackForClient struct AdvmapSpellCast : public CPackForClient { - AdvmapSpellCast():casterID(){} ObjectInstanceID casterID; SpellID spellID; @@ -1954,8 +1827,6 @@ struct ShowWorldViewEx : public CPackForClient std::vector objectPositions; - ShowWorldViewEx(){} - void applyCl(CClient *cl); template void serialize(Handler &h, const int version) @@ -1978,8 +1849,10 @@ struct EndTurn : public CPackForServer struct DismissHero : public CPackForServer { - DismissHero(){}; - DismissHero(ObjectInstanceID HID) : hid(HID) {}; + DismissHero() = default; + DismissHero(const ObjectInstanceID & HID) + : hid(HID) + {} ObjectInstanceID hid; bool applyGh(CGameHandler *gh); @@ -1992,11 +1865,15 @@ struct DismissHero : public CPackForServer struct MoveHero : public CPackForServer { - MoveHero():transit(false){}; - MoveHero(const int3 &Dest, ObjectInstanceID HID, bool Transit) : dest(Dest), hid(HID), transit(Transit) {}; + MoveHero() = default; + MoveHero(const int3 & Dest, const ObjectInstanceID & HID, bool Transit) + : dest(Dest) + , hid(HID) + , transit(Transit) + {} int3 dest; ObjectInstanceID hid; - bool transit; + bool transit = false; bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) @@ -2010,11 +1887,15 @@ struct MoveHero : public CPackForServer struct CastleTeleportHero : public CPackForServer { - CastleTeleportHero():source(0){}; - CastleTeleportHero(const ObjectInstanceID HID, ObjectInstanceID Dest, ui8 Source ) : dest(Dest), hid(HID), source(Source){}; + CastleTeleportHero() = default; + CastleTeleportHero(const ObjectInstanceID & HID, const ObjectInstanceID & Dest, ui8 Source) + : dest(Dest) + , hid(HID) + , source(Source) + {} ObjectInstanceID dest; ObjectInstanceID hid; - si8 source;//who give teleporting, 1=castle gate + si8 source = 0; //who give teleporting, 1=castle gate bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) @@ -2027,14 +1908,20 @@ struct CastleTeleportHero : public CPackForServer struct ArrangeStacks : public CPackForServer { - ArrangeStacks():what(0), val(0){}; - ArrangeStacks(ui8 W, SlotID P1, SlotID P2, ObjectInstanceID ID1, ObjectInstanceID ID2, si32 VAL) - :what(W),p1(P1),p2(P2),id1(ID1),id2(ID2),val(VAL) {}; + ArrangeStacks() = default; + ArrangeStacks(ui8 W, const SlotID & P1, const SlotID & P2, const ObjectInstanceID & ID1, const ObjectInstanceID & ID2, si32 VAL) + : what(W) + , p1(P1) + , p2(P2) + , id1(ID1) + , id2(ID2) + , val(VAL) + {} - ui8 what; //1 - swap; 2 - merge; 3 - split + ui8 what = 0; //1 - swap; 2 - merge; 3 - split SlotID p1, p2; //positions of first and second stack ObjectInstanceID id1, id2; //ids of objects with garrison - si32 val; + si32 val = 0; bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) { @@ -2054,12 +1941,13 @@ struct BulkMoveArmy : public CPackForServer ObjectInstanceID srcArmy; ObjectInstanceID destArmy; - BulkMoveArmy() - {}; + BulkMoveArmy() = default; - BulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot) - : srcArmy(srcArmy), destArmy(destArmy), srcSlot(srcSlot) - {}; + BulkMoveArmy(const ObjectInstanceID & srcArmy, const ObjectInstanceID & destArmy, const SlotID & srcSlot) + : srcArmy(srcArmy) + , destArmy(destArmy) + , srcSlot(srcSlot) + {} bool applyGh(CGameHandler * gh); @@ -2077,14 +1965,15 @@ struct BulkSplitStack : public CPackForServer { SlotID src; ObjectInstanceID srcOwner; - si32 amount; + si32 amount = 0; - BulkSplitStack() : amount(0) - {}; + BulkSplitStack() = default; - BulkSplitStack(ObjectInstanceID srcOwner, SlotID src, si32 howMany) - : src(src), srcOwner(srcOwner), amount(howMany) - {}; + BulkSplitStack(const ObjectInstanceID & srcOwner, const SlotID & src, si32 howMany) + : src(src) + , srcOwner(srcOwner) + , amount(howMany) + {} bool applyGh(CGameHandler * gh); @@ -2103,12 +1992,12 @@ struct BulkMergeStacks : public CPackForServer SlotID src; ObjectInstanceID srcOwner; - BulkMergeStacks() - {}; + BulkMergeStacks() = default; - BulkMergeStacks(ObjectInstanceID srcOwner, SlotID src) - : src(src), srcOwner(srcOwner) - {}; + BulkMergeStacks(const ObjectInstanceID & srcOwner, const SlotID & src) + : src(src) + , srcOwner(srcOwner) + {} bool applyGh(CGameHandler * gh); @@ -2126,12 +2015,12 @@ struct BulkSmartSplitStack : public CPackForServer SlotID src; ObjectInstanceID srcOwner; - BulkSmartSplitStack() - {}; + BulkSmartSplitStack() = default; - BulkSmartSplitStack(ObjectInstanceID srcOwner, SlotID src) - : src(src), srcOwner(srcOwner) - {}; + BulkSmartSplitStack(const ObjectInstanceID & srcOwner, const SlotID & src) + : src(src) + , srcOwner(srcOwner) + {} bool applyGh(CGameHandler * gh); @@ -2146,8 +2035,11 @@ struct BulkSmartSplitStack : public CPackForServer struct DisbandCreature : public CPackForServer { - DisbandCreature(){}; - DisbandCreature(SlotID Pos, ObjectInstanceID ID):pos(Pos),id(ID){}; + DisbandCreature() = default; + DisbandCreature(const SlotID & Pos, const ObjectInstanceID & ID) + : pos(Pos) + , id(ID) + {} SlotID pos; //stack pos ObjectInstanceID id; //object id @@ -2162,8 +2054,11 @@ struct DisbandCreature : public CPackForServer struct BuildStructure : public CPackForServer { - BuildStructure(){}; - BuildStructure(ObjectInstanceID TID, BuildingID BID):tid(TID), bid(BID){}; + BuildStructure() = default; + BuildStructure(const ObjectInstanceID & TID, const BuildingID & BID) + : tid(TID) + , bid(BID) + {} ObjectInstanceID tid; //town id BuildingID bid; //structure id @@ -2178,21 +2073,24 @@ struct BuildStructure : public CPackForServer struct RazeStructure : public BuildStructure { - RazeStructure(){}; - bool applyGh(CGameHandler *gh); }; struct RecruitCreatures : public CPackForServer { - RecruitCreatures():amount(0), level(0){}; - RecruitCreatures(ObjectInstanceID TID, ObjectInstanceID DST, CreatureID CRID, si32 Amount, si32 Level): - tid(TID), dst(DST), crid(CRID), amount(Amount), level(Level){}; + RecruitCreatures() = default; + RecruitCreatures(const ObjectInstanceID & TID, const ObjectInstanceID & DST, const CreatureID & CRID, si32 Amount, si32 Level) + : tid(TID) + , dst(DST) + , crid(CRID) + , amount(Amount) + , level(Level) + {} ObjectInstanceID tid; //dwelling id, or town ObjectInstanceID dst; //destination ID, e.g. hero CreatureID crid; - ui32 amount;//creature amount - si32 level;//dwelling level to buy from, -1 if any + ui32 amount = 0; //creature amount + si32 level = 0; //dwelling level to buy from, -1 if any bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) { @@ -2207,8 +2105,12 @@ struct RecruitCreatures : public CPackForServer struct UpgradeCreature : public CPackForServer { - UpgradeCreature(){}; - UpgradeCreature(SlotID Pos, ObjectInstanceID ID, CreatureID CRID):pos(Pos),id(ID), cid(CRID){}; + UpgradeCreature() = default; + UpgradeCreature(const SlotID & Pos, const ObjectInstanceID & ID, const CreatureID & CRID) + : pos(Pos) + , id(ID) + , cid(CRID) + {} SlotID pos; //stack pos ObjectInstanceID id; //object id CreatureID cid; //id of type to which we want make upgrade @@ -2225,8 +2127,10 @@ struct UpgradeCreature : public CPackForServer struct GarrisonHeroSwap : public CPackForServer { - GarrisonHeroSwap(){}; - GarrisonHeroSwap(ObjectInstanceID TID):tid(TID){}; + GarrisonHeroSwap() = default; + GarrisonHeroSwap(const ObjectInstanceID & TID) + : tid(TID) + {} ObjectInstanceID tid; bool applyGh(CGameHandler *gh); @@ -2240,8 +2144,6 @@ struct GarrisonHeroSwap : public CPackForServer struct ExchangeArtifacts : public CPackForServer { ArtifactLocation src, dst; - ExchangeArtifacts(){}; - bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) { @@ -2255,12 +2157,15 @@ struct BulkExchangeArtifacts : public CPackForServer { ObjectInstanceID srcHero; ObjectInstanceID dstHero; - bool swap; + bool swap = false; - BulkExchangeArtifacts() - : swap(false) {} - BulkExchangeArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap) - : srcHero(srcHero), dstHero(dstHero), swap(swap) {} + BulkExchangeArtifacts() = default; + BulkExchangeArtifacts(const ObjectInstanceID & srcHero, const ObjectInstanceID & dstHero, bool swap) + : srcHero(srcHero) + , dstHero(dstHero) + , swap(swap) + { + } bool applyGh(CGameHandler * gh); template void serialize(Handler & h, const int version) @@ -2274,12 +2179,16 @@ struct BulkExchangeArtifacts : public CPackForServer struct AssembleArtifacts : public CPackForServer { - AssembleArtifacts():assemble(false){}; - AssembleArtifacts(ObjectInstanceID _heroID, ArtifactPosition _artifactSlot, bool _assemble, ArtifactID _assembleTo) - : heroID(_heroID), artifactSlot(_artifactSlot), assemble(_assemble), assembleTo(_assembleTo){}; + AssembleArtifacts() = default; + AssembleArtifacts(const ObjectInstanceID & _heroID, const ArtifactPosition & _artifactSlot, bool _assemble, const ArtifactID & _assembleTo) + : heroID(_heroID) + , artifactSlot(_artifactSlot) + , assemble(_assemble) + , assembleTo(_assembleTo) + {} ObjectInstanceID heroID; ArtifactPosition artifactSlot; - bool assemble; // True to assemble artifact, false to disassemble. + bool assemble = false; // True to assemble artifact, false to disassemble. ArtifactID assembleTo; // Artifact to assemble into. bool applyGh(CGameHandler *gh); @@ -2295,8 +2204,11 @@ struct AssembleArtifacts : public CPackForServer struct BuyArtifact : public CPackForServer { - BuyArtifact(){}; - BuyArtifact(ObjectInstanceID HID, ArtifactID AID):hid(HID),aid(AID){}; + BuyArtifact() = default; + BuyArtifact(const ObjectInstanceID & HID, const ArtifactID & AID) + : hid(HID) + , aid(AID) + {} ObjectInstanceID hid; ArtifactID aid; @@ -2311,14 +2223,10 @@ struct BuyArtifact : public CPackForServer struct TradeOnMarketplace : public CPackForServer { - TradeOnMarketplace() - :marketId(), heroId(), mode(EMarketMode::RESOURCE_RESOURCE) - {}; - ObjectInstanceID marketId; ObjectInstanceID heroId; - EMarketMode::EMarketMode mode; + EMarketMode::EMarketMode mode = EMarketMode::RESOURCE_RESOURCE; std::vector r1, r2; //mode 0: r1 - sold resource, r2 - bought res (exception: when sacrificing art r1 is art id [todo: make r2 preferred slot?] std::vector val; //units of sold resource @@ -2337,10 +2245,14 @@ struct TradeOnMarketplace : public CPackForServer struct SetFormation : public CPackForServer { - SetFormation():formation(0){}; - SetFormation(ObjectInstanceID HID, ui8 Formation):hid(HID),formation(Formation){}; + SetFormation() = default; + ; + SetFormation(const ObjectInstanceID & HID, ui8 Formation) + : hid(HID) + , formation(Formation) + {} ObjectInstanceID hid; - ui8 formation; + ui8 formation = 0; bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) @@ -2353,9 +2265,12 @@ struct SetFormation : public CPackForServer struct HireHero : public CPackForServer { - HireHero():hid(0){}; - HireHero(si32 HID, ObjectInstanceID TID):hid(HID),tid(TID){}; - si32 hid; //available hero serial + HireHero() = default; + HireHero(si32 HID, const ObjectInstanceID & TID) + : hid(HID) + , tid(TID) + {} + si32 hid = 0; //available hero serial ObjectInstanceID tid; //town (tavern) id PlayerColor player; @@ -2371,7 +2286,6 @@ struct HireHero : public CPackForServer struct BuildBoat : public CPackForServer { - BuildBoat(){}; ObjectInstanceID objid; //where player wants to buy a boat bool applyGh(CGameHandler *gh); @@ -2380,13 +2294,15 @@ struct BuildBoat : public CPackForServer h & static_cast(*this); h & objid; } - }; struct QueryReply : public CPackForServer { - QueryReply(){}; - QueryReply(QueryID QID, const JsonNode & Reply):qid(QID), reply(Reply){}; + QueryReply() = default; + QueryReply(const QueryID & QID, const JsonNode & Reply) + : qid(QID) + , reply(Reply) + {} QueryID qid; PlayerColor player; JsonNode reply; @@ -2403,8 +2319,10 @@ struct QueryReply : public CPackForServer struct MakeAction : public CPackForServer { - MakeAction(){}; - MakeAction(const BattleAction &BA):ba(BA){}; + MakeAction() = default; + MakeAction(BattleAction BA) + : ba(std::move(BA)) + {} BattleAction ba; bool applyGh(CGameHandler *gh); @@ -2417,8 +2335,10 @@ struct MakeAction : public CPackForServer struct MakeCustomAction : public CPackForServer { - MakeCustomAction(){}; - MakeCustomAction(const BattleAction &BA):ba(BA){}; + MakeCustomAction() = default; + MakeCustomAction(BattleAction BA) + : ba(std::move(BA)) + {} BattleAction ba; bool applyGh(CGameHandler *gh); @@ -2431,7 +2351,6 @@ struct MakeCustomAction : public CPackForServer struct DigWithHero : public CPackForServer { - DigWithHero(){} ObjectInstanceID id; //digging hero id bool applyGh(CGameHandler *gh); @@ -2444,7 +2363,6 @@ struct DigWithHero : public CPackForServer struct CastAdvSpell : public CPackForServer { - CastAdvSpell(){} ObjectInstanceID hid; //hero id SpellID sid; //spell id int3 pos; //selected tile (not always used) @@ -2463,11 +2381,13 @@ struct CastAdvSpell : public CPackForServer struct SaveGame : public CPackForServer { - SaveGame(){}; - SaveGame(const std::string &Fname) :fname(Fname){}; + SaveGame() = default; + SaveGame(std::string Fname) + : fname(std::move(Fname)) + {} std::string fname; - void applyGs(CGameState *gs){}; + void applyGs(CGameState *gs){} bool applyGh(CGameHandler *gh); template void serialize(Handler &h, const int version) { @@ -2479,8 +2399,10 @@ struct SaveGame : public CPackForServer // TODO: Eventually we should re-merge both SaveGame and PlayerMessage struct SaveGameClient : public CPackForClient { - SaveGameClient(){}; - SaveGameClient(const std::string &Fname) :fname(Fname){}; + SaveGameClient() = default; + SaveGameClient(std::string Fname) + : fname(std::move(Fname)) + {} std::string fname; void applyCl(CClient *cl); @@ -2492,11 +2414,12 @@ struct SaveGameClient : public CPackForClient struct PlayerMessage : public CPackForServer { - PlayerMessage(){}; - PlayerMessage(const std::string &Text, ObjectInstanceID obj) - : text(Text), currObj(obj) - {}; - void applyGs(CGameState *gs){}; + PlayerMessage() = default; + PlayerMessage(std::string Text, const ObjectInstanceID & obj) + : text(std::move(Text)) + , currObj(obj) + {} + void applyGs(CGameState *gs){} bool applyGh(CGameHandler *gh); std::string text; @@ -2512,9 +2435,10 @@ struct PlayerMessage : public CPackForServer struct PlayerMessageClient : public CPackForClient { - PlayerMessageClient(){}; - PlayerMessageClient(PlayerColor Player, const std::string &Text) - : player(Player), text(Text) + PlayerMessageClient() = default; + PlayerMessageClient(const PlayerColor & Player, std::string Text) + : player(Player) + , text(std::move(Text)) {} void applyCl(CClient *cl); @@ -2530,12 +2454,11 @@ struct PlayerMessageClient : public CPackForClient struct CenterView : public CPackForClient { - CenterView():focusTime(0){}; void applyCl(CClient *cl); PlayerColor player; int3 pos; - ui32 focusTime; //ms + ui32 focusTime = 0; //ms template void serialize(Handler &h, const int version) { diff --git a/lib/NetPacksBase.h b/lib/NetPacksBase.h index 88e639337..8159fb6c4 100644 --- a/lib/NetPacksBase.h +++ b/lib/NetPacksBase.h @@ -34,8 +34,8 @@ struct DLL_LINKAGE CPack { std::shared_ptr c; // Pointer to connection that pack received from - CPack() : c(nullptr) {}; - virtual ~CPack() {}; + CPack() = default; + virtual ~CPack() = default; template void serialize(Handler &h, const int version) { @@ -49,8 +49,6 @@ struct DLL_LINKAGE CPack struct CPackForClient : public CPack { - CPackForClient(){}; - CGameState* GS(CClient *cl); void applyFirstCl(CClient *cl)//called before applying to gs {} @@ -60,14 +58,9 @@ struct CPackForClient : public CPack struct CPackForServer : public CPack { - mutable PlayerColor player; + mutable PlayerColor player = PlayerColor::NEUTRAL; mutable si32 requestID; - CGameState* GS(CGameHandler *gh); - CPackForServer(): - player(PlayerColor::NEUTRAL) - { - } - + CGameState * GS(CGameHandler * gh); bool applyGh(CGameHandler *gh) //called after applying to gs { logGlobal->error("Should not happen... applying plain CPackForServer"); @@ -115,7 +108,7 @@ public: void addTxt(ui8 type, ui32 serial) { message.push_back(TLOCAL_STRING); - localStrings.push_back(std::pair(type, serial)); + localStrings.emplace_back(type, serial); } MetaString& operator<<(const std::pair &txt) { @@ -138,7 +131,7 @@ public: void addReplacement(ui8 type, ui32 serial) { message.push_back(TREPLACE_LSTRING); - localStrings.push_back(std::pair(type, serial)); + localStrings.emplace_back(type, serial); } void addReplacement(const std::string &txt) { @@ -155,7 +148,7 @@ public: message.push_back(TREPLACE_PLUSNUMBER); numbers.push_back(txt); } - void addCreReplacement(CreatureID id, TQuantity count); //adds sing or plural name; + void addCreReplacement(const CreatureID & id, TQuantity count); //adds sing or plural name; void addReplacement(const CStackBasicDescriptor &stack); //adds sing or plural name; std::string buildList () const; void clear() @@ -167,17 +160,16 @@ public: } void toString(std::string &dst) const; std::string toString() const; - void getLocalString(const std::pair &txt, std::string &dst) const; + void getLocalString(const std::pair & txt, std::string & dst) const; - MetaString(){} }; struct Component { enum EComponentType {PRIM_SKILL, SEC_SKILL, RESOURCE, CREATURE, ARTIFACT, EXPERIENCE, SPELL, MORALE, LUCK, BUILDING, HERO_PORTRAIT, FLAG}; - ui16 id, subtype; //id uses ^^^ enums, when id==EXPPERIENCE subtype==0 means exp points and subtype==1 levels) - si32 val; // + give; - take - si16 when; // 0 - now; +x - within x days; -x - per x days + ui16 id = 0, subtype = 0; //id uses ^^^ enums, when id==EXPPERIENCE subtype==0 means exp points and subtype==1 levels) + si32 val = 0; // + give; - take + si16 when = 0; // 0 - now; +x - within x days; -x - per x days template void serialize(Handler &h, const int version) { @@ -186,10 +178,7 @@ struct Component h & val; h & when; } - Component() - :id(0), subtype(0), val(0), when(0) - { - } + Component() = default; DLL_LINKAGE explicit Component(const CStackBasicDescriptor &stack); Component(Component::EComponentType Type, ui16 Subtype, si32 Val, si16 When) :id(Type),subtype(Subtype),val(Val),when(When) @@ -197,28 +186,27 @@ struct Component } }; -typedef boost::variant, ConstTransitivePtr > TArtHolder; +using TArtHolder = boost::variant, ConstTransitivePtr>; struct ArtifactLocation { TArtHolder artHolder;//TODO: identify holder by id - ArtifactPosition slot; + ArtifactPosition slot = ArtifactPosition::PRE_FIRST; ArtifactLocation() + : artHolder(ConstTransitivePtr()) { - artHolder = ConstTransitivePtr(); - slot = ArtifactPosition::PRE_FIRST; } - template - ArtifactLocation(const T *ArtHolder, ArtifactPosition Slot) + template + ArtifactLocation(const T * ArtHolder, ArtifactPosition Slot) + : artHolder(const_cast(ArtHolder)) //we are allowed here to const cast -> change will go through one of our packages... do not abuse! + , slot(Slot) { - artHolder = const_cast(ArtHolder); //we are allowed here to const cast -> change will go through one of our packages... do not abuse! - slot = Slot; } - ArtifactLocation(TArtHolder ArtHolder, ArtifactPosition Slot) + ArtifactLocation(TArtHolder ArtHolder, const ArtifactPosition & Slot) + : artHolder(std::move(std::move(ArtHolder))) + , slot(Slot) { - artHolder = ArtHolder; - slot = Slot; } template @@ -253,15 +241,9 @@ struct ArtifactLocation class EntityChanges { public: - Metatype metatype; - int32_t entityIndex; + Metatype metatype = Metatype::UNKNOWN; + int32_t entityIndex = 0; JsonNode data; - EntityChanges() - : metatype(Metatype::UNKNOWN), - entityIndex(0), - data() - { - } template void serialize(Handler & h, const int version) { h & metatype; @@ -284,17 +266,11 @@ public: }; JsonNode data; - EOperation operation; - - BattleChanges() - : operation(EOperation::RESET_STATE), - data() - { - } + EOperation operation = EOperation::RESET_STATE; + BattleChanges() = default; BattleChanges(EOperation operation_) - : operation(operation_), - data() + : operation(operation_) { } }; @@ -302,20 +278,13 @@ public: class UnitChanges : public BattleChanges { public: - uint32_t id; - int64_t healthDelta; - - UnitChanges() - : BattleChanges(EOperation::RESET_STATE), - id(0), - healthDelta(0) - { - } + uint32_t id = 0; + int64_t healthDelta = 0; + UnitChanges() = default; UnitChanges(uint32_t id_, EOperation operation_) - : BattleChanges(operation_), - id(id_), - healthDelta(0) + : BattleChanges(operation_) + , id(id_) { } @@ -331,13 +300,9 @@ public: class ObstacleChanges : public BattleChanges { public: - uint32_t id; + uint32_t id = 0; - ObstacleChanges() - : BattleChanges(EOperation::RESET_STATE), - id(0) - { - } + ObstacleChanges() = default; ObstacleChanges(uint32_t id_, EOperation operation_) : BattleChanges(operation_), diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index 5d5cf5ea9..c29013c4b 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -31,8 +31,7 @@ VCMI_LIB_NAMESPACE_BEGIN - -DLL_LINKAGE void SetResources::applyGs(CGameState *gs) +DLL_LINKAGE void SetResources::applyGs(CGameState * gs) const { assert(player < PlayerColor::PLAYER_LIMIT); if(abs) @@ -46,14 +45,14 @@ DLL_LINKAGE void SetResources::applyGs(CGameState *gs) gs->getPlayerState(player)->resources.positive(); } -DLL_LINKAGE void SetPrimSkill::applyGs(CGameState *gs) +DLL_LINKAGE void SetPrimSkill::applyGs(CGameState * gs) const { CGHeroInstance * hero = gs->getHero(id); assert(hero); hero->setPrimarySkill(which, val, abs); } -DLL_LINKAGE void SetSecSkill::applyGs(CGameState *gs) +DLL_LINKAGE void SetSecSkill::applyGs(CGameState * gs) const { CGHeroInstance *hero = gs->getHero(id); hero->setSecSkillLevel(which, val, abs); @@ -88,17 +87,17 @@ DLL_LINKAGE void SetCommanderProperty::applyGs(CGameState *gs) } } -DLL_LINKAGE void AddQuest::applyGs(CGameState *gs) +DLL_LINKAGE void AddQuest::applyGs(CGameState * gs) const { assert (vstd::contains(gs->players, player)); - auto vec = &gs->players[player].quests; + auto * vec = &gs->players[player].quests; if (!vstd::contains(*vec, quest)) vec->push_back (quest); else logNetwork->warn("Warning! Attempt to add duplicated quest"); } -DLL_LINKAGE void UpdateArtHandlerLists::applyGs(CGameState *gs) +DLL_LINKAGE void UpdateArtHandlerLists::applyGs(CGameState * gs) const { VLC->arth->minors = minors; VLC->arth->majors = majors; @@ -106,24 +105,23 @@ DLL_LINKAGE void UpdateArtHandlerLists::applyGs(CGameState *gs) VLC->arth->relics = relics; } -DLL_LINKAGE void UpdateMapEvents::applyGs(CGameState *gs) +DLL_LINKAGE void UpdateMapEvents::applyGs(CGameState * gs) const { gs->map->events = events; } - -DLL_LINKAGE void UpdateCastleEvents::applyGs(CGameState *gs) +DLL_LINKAGE void UpdateCastleEvents::applyGs(CGameState * gs) const { - auto t = gs->getTown(town); + auto * t = gs->getTown(town); t->events = events; } -DLL_LINKAGE void ChangeFormation::applyGs(CGameState *gs) +DLL_LINKAGE void ChangeFormation::applyGs(CGameState * gs) const { gs->getHero(hid)->setFormation(formation); } -DLL_LINKAGE void HeroVisitCastle::applyGs(CGameState *gs) +DLL_LINKAGE void HeroVisitCastle::applyGs(CGameState * gs) const { CGHeroInstance *h = gs->getHero(hid); CGTownInstance *t = gs->getTown(tid); @@ -142,14 +140,14 @@ DLL_LINKAGE void ChangeSpells::applyGs(CGameState *gs) CGHeroInstance *hero = gs->getHero(hid); if(learn) - for(auto sid : spells) + for(const auto & sid : spells) hero->addSpellToSpellbook(sid); else - for(auto sid : spells) + for(const auto & sid : spells) hero->removeSpellFromSpellbook(sid); } -DLL_LINKAGE void SetMana::applyGs(CGameState *gs) +DLL_LINKAGE void SetMana::applyGs(CGameState * gs) const { CGHeroInstance * hero = gs->getHero(hid); @@ -163,7 +161,7 @@ DLL_LINKAGE void SetMana::applyGs(CGameState *gs) vstd::amax(hero->mana, 0); //not less than 0 } -DLL_LINKAGE void SetMovePoints::applyGs(CGameState *gs) +DLL_LINKAGE void SetMovePoints::applyGs(CGameState * gs) const { CGHeroInstance *hero = gs->getHero(hid); @@ -181,7 +179,7 @@ DLL_LINKAGE void FoWChange::applyGs(CGameState *gs) { TeamState * team = gs->getPlayerTeam(player); auto fogOfWarMap = team->fogOfWarMap; - for(int3 t : tiles) + for(const int3 & t : tiles) (*fogOfWarMap)[t.z][t.x][t.y] = mode; if (mode == 0) //do not hide too much { @@ -203,7 +201,7 @@ DLL_LINKAGE void FoWChange::applyGs(CGameState *gs) } } } - for(int3 t : tilesRevealed) //probably not the most optimal solution ever + for(const int3 & t : tilesRevealed) //probably not the most optimal solution ever (*fogOfWarMap)[t.z][t.x][t.y] = 1; } } @@ -218,7 +216,7 @@ DLL_LINKAGE void SetAvailableHeroes::applyGs(CGameState *gs) CGHeroInstance *h = (hid[i]>=0 ? gs->hpool.heroesPool[hid[i]].get() : nullptr); if(h && army[i]) h->setToArmy(army[i]); - p->availableHeroes.push_back(h); + p->availableHeroes.emplace_back(h); } } @@ -248,8 +246,7 @@ DLL_LINKAGE void GiveBonus::applyGs(CGameState *gs) std::string &descr = b->description; - if(!bdescr.message.size() - && (bonus.type == Bonus::LUCK || bonus.type == Bonus::MORALE)) + if(bdescr.message.empty() && (bonus.type == Bonus::LUCK || bonus.type == Bonus::MORALE)) { if (bonus.source == Bonus::OBJECT) { @@ -270,8 +267,8 @@ DLL_LINKAGE void GiveBonus::applyGs(CGameState *gs) bdescr.toString(descr); } // Some of(?) versions of H3 use %s here instead of %d. Try to replace both of them - boost::replace_first(descr,"%d",boost::lexical_cast(std::abs(bonus.val))); - boost::replace_first(descr,"%s",boost::lexical_cast(std::abs(bonus.val))); + boost::replace_first(descr, "%d", std::to_string(std::abs(bonus.val))); + boost::replace_first(descr, "%s", std::to_string(std::abs(bonus.val))); } DLL_LINKAGE void ChangeObjPos::applyGs(CGameState *gs) @@ -287,7 +284,7 @@ DLL_LINKAGE void ChangeObjPos::applyGs(CGameState *gs) gs->map->addBlockVisTiles(obj); } -DLL_LINKAGE void ChangeObjectVisitors::applyGs(CGameState *gs) +DLL_LINKAGE void ChangeObjectVisitors::applyGs(CGameState * gs) const { switch (mode) { case VISITOR_ADD: @@ -297,7 +294,7 @@ DLL_LINKAGE void ChangeObjectVisitors::applyGs(CGameState *gs) case VISITOR_ADD_TEAM: { TeamState *ts = gs->getPlayerTeam(gs->getHero(hero)->tempOwner); - for (auto & color : ts->players) + for(const auto & color : ts->players) { gs->getPlayerState(color)->visitedObjects.insert(object); } @@ -324,7 +321,7 @@ DLL_LINKAGE void ChangeObjectVisitors::applyGs(CGameState *gs) } } -DLL_LINKAGE void PlayerEndsGame::applyGs(CGameState *gs) +DLL_LINKAGE void PlayerEndsGame::applyGs(CGameState * gs) const { PlayerState *p = gs->getPlayerState(player); if(victoryLossCheckResult.victory()) @@ -374,14 +371,14 @@ DLL_LINKAGE void PlayerReinitInterface::applyGs(CGameState *gs) //TODO: what does mean if more that one player connected? if(playerConnectionId == PlayerSettings::PLAYER_AI) { - for(auto player : players) + for(const auto & player : players) gs->scenarioOps->getIthPlayersSettings(player).connectedPlayerIDs.clear(); } } DLL_LINKAGE void RemoveBonus::applyGs(CGameState *gs) { - CBonusSystemNode *node; + CBonusSystemNode * node = nullptr; if (who == HERO) node = gs->getHero(ObjectInstanceID(whoID)); else @@ -389,9 +386,8 @@ DLL_LINKAGE void RemoveBonus::applyGs(CGameState *gs) BonusList &bonuses = node->getExportedBonusList(); - for (int i = 0; i < bonuses.size(); i++) + for(const auto & b : bonuses) { - auto b = bonuses[i]; if(b->source == source && b->sid == id) { bonus = *b; //backup bonus (to show to interfaces later) @@ -411,7 +407,8 @@ DLL_LINKAGE void RemoveObject::applyGs(CGameState *gs) if(obj->ID == Obj::HERO) //remove beaten hero { - CGHeroInstance * beatenHero = static_cast(obj); + auto * beatenHero = dynamic_cast(obj); + assert(beatenHero); PlayerState * p = gs->getPlayerState(beatenHero->tempOwner); gs->map->heroesOnMap -= beatenHero; p->heroes -= beatenHero; @@ -450,7 +447,7 @@ DLL_LINKAGE void RemoveObject::applyGs(CGameState *gs) return; } - auto quest = dynamic_cast(obj); + const auto * quest = dynamic_cast(obj); if (quest) { gs->map->quests[quest->quest->qid] = nullptr; @@ -492,7 +489,7 @@ DLL_LINKAGE void RemoveObject::applyGs(CGameState *gs) gs->map->calculateGuardingGreaturePositions(); } -static int getDir(int3 src, int3 dst) +static int getDir(const int3 & src, const int3 & dst) { int ret = -1; if(dst.x+1 == src.x && dst.y+1 == src.y) //tl @@ -553,7 +550,8 @@ void TryMoveHero::applyGs(CGameState *gs) { const TerrainTile &tt = gs->map->getTile(h->convertToVisitablePos(end)); assert(tt.visitableObjects.size() >= 1 && tt.visitableObjects.back()->ID == Obj::BOAT); //the only visitable object at destination is Boat - CGBoat *boat = static_cast(tt.visitableObjects.back()); + auto * boat = dynamic_cast(tt.visitableObjects.back()); + assert(boat); gs->map->removeBlockVisTiles(boat); //hero blockvis mask will be used, we don't need to duplicate it with boat h->boat = boat; @@ -561,7 +559,7 @@ void TryMoveHero::applyGs(CGameState *gs) } else if(result == DISEMBARK) //hero leaves boat to destination tile { - CGBoat *b = const_cast(h->boat); + auto * b = const_cast(h->boat); b->direction = h->moveDir; b->pos = start; b->hero = nullptr; @@ -573,13 +571,13 @@ void TryMoveHero::applyGs(CGameState *gs) { gs->map->removeBlockVisTiles(h); h->pos = end; - if(CGBoat *b = const_cast(h->boat)) + if(auto * b = const_cast(h->boat)) b->pos = end; gs->map->addBlockVisTiles(h); } auto fogOfWarMap = gs->getPlayerTeam(h->getOwner())->fogOfWarMap; - for(int3 t : fowRevealed) + for(const int3 & t : fowRevealed) (*fogOfWarMap)[t.z][t.x][t.y] = 1; } @@ -597,7 +595,7 @@ DLL_LINKAGE void NewStructures::applyGs(CGameState *gs) if(currentBuilding->overrideBids.empty()) continue; - for(auto overrideBid : currentBuilding->overrideBids) + for(const auto & overrideBid : currentBuilding->overrideBids) { t->overriddenBuildings.insert(overrideBid); t->deleteTownBonus(overrideBid); @@ -620,19 +618,19 @@ DLL_LINKAGE void RazeStructures::applyGs(CGameState *gs) t->recreateBuildingsBonuses(); } -DLL_LINKAGE void SetAvailableCreatures::applyGs(CGameState *gs) +DLL_LINKAGE void SetAvailableCreatures::applyGs(CGameState * gs) const { - CGDwelling *dw = dynamic_cast(gs->getObjInstance(tid)); + auto * dw = dynamic_cast(gs->getObjInstance(tid)); assert(dw); dw->creatures = creatures; } -DLL_LINKAGE void SetHeroesInTown::applyGs(CGameState *gs) +DLL_LINKAGE void SetHeroesInTown::applyGs(CGameState * gs) const { CGTownInstance *t = gs->getTown(tid); - CGHeroInstance *v = gs->getHero(visiting), - *g = gs->getHero(garrison); + CGHeroInstance * v = gs->getHero(visiting); + CGHeroInstance * g = gs->getHero(garrison); bool newVisitorComesFromGarrison = v && v == t->garrisonHero; bool newGarrisonComesFromVisiting = g && g == t->visitingHero; @@ -656,7 +654,7 @@ DLL_LINKAGE void SetHeroesInTown::applyGs(CGameState *gs) } } -DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs) +DLL_LINKAGE void HeroRecruited::applyGs(CGameState * gs) const { assert(vstd::contains(gs->hpool.heroesPool, hid)); CGHeroInstance *h = gs->hpool.heroesPool[hid]; @@ -676,14 +674,14 @@ DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs) gs->hpool.heroesPool.erase(hid); if(h->id == ObjectInstanceID()) { - h->id = ObjectInstanceID((si32)gs->map->objects.size()); - gs->map->objects.push_back(h); + h->id = ObjectInstanceID(static_cast(gs->map->objects.size())); + gs->map->objects.emplace_back(h); } else gs->map->objects[h->id.getNum()] = h; - gs->map->heroesOnMap.push_back(h); - p->heroes.push_back(h); + gs->map->heroesOnMap.emplace_back(h); + p->heroes.emplace_back(h); h->attachTo(*p); if(fresh) { @@ -697,7 +695,7 @@ DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs) } } -DLL_LINKAGE void GiveHero::applyGs(CGameState *gs) +DLL_LINKAGE void GiveHero::applyGs(CGameState * gs) const { CGHeroInstance *h = gs->getHero(id); @@ -712,8 +710,8 @@ DLL_LINKAGE void GiveHero::applyGs(CGameState *gs) h->setOwner(player); h->movement = h->maxMovePoints(true); h->pos = h->convertFromVisitablePos(oldVisitablePos); - gs->map->heroesOnMap.push_back(h); - gs->getPlayerState(h->getOwner())->heroes.push_back(h); + gs->map->heroesOnMap.emplace_back(h); + gs->getPlayerState(h->getOwner())->heroes.emplace_back(h); gs->map->addBlockVisTiles(h); h->inTownGarrison = false; @@ -750,9 +748,10 @@ DLL_LINKAGE void NewObject::applyGs(CGameState *gs) o = new CGCreature(); { //CStackInstance hlp; - CGCreature *cre = static_cast(o); + auto * cre = dynamic_cast(o); //cre->slots[0] = hlp; - cre->notGrowingTeam = cre->neverFlees = 0; + assert(cre); + cre->notGrowingTeam = cre->neverFlees = false; cre->character = 2; cre->gainedArtifact = ArtifactID::NONE; cre->identifier = -1; @@ -767,9 +766,9 @@ DLL_LINKAGE void NewObject::applyGs(CGameState *gs) o->subID = subID; o->pos = pos; o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front(); - id = o->id = ObjectInstanceID((si32)gs->map->objects.size()); + id = o->id = ObjectInstanceID(static_cast(gs->map->objects.size())); - gs->map->objects.push_back(o); + gs->map->objects.emplace_back(o); gs->map->addBlockVisTiles(o); o->initObj(gs->getRandomGenerator()); gs->map->calculateGuardingGreaturePositions(); @@ -784,7 +783,7 @@ DLL_LINKAGE void NewArtifact::applyGs(CGameState *gs) assert(!art->getParentNodes().size()); art->setType(art->artType); - if (CCombinedArtifactInstance* cart = dynamic_cast(art.get())) + if(auto * cart = dynamic_cast(art.get())) cart->createConstituents(); } @@ -834,7 +833,7 @@ DLL_LINKAGE const CArmedInstance * ArtifactLocation::relatedObj() const DLL_LINKAGE PlayerColor ArtifactLocation::owningPlayer() const { - auto obj = relatedObj(); + const auto * obj = relatedObj(); return obj ? obj->tempOwner : PlayerColor::NEUTRAL; } @@ -850,7 +849,7 @@ DLL_LINKAGE CBonusSystemNode *ArtifactLocation::getHolderNode() DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const { - auto s = getSlot(); + const auto * s = getSlot(); if(s) return s->getArt(); else @@ -859,13 +858,13 @@ DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const DLL_LINKAGE const CArtifactSet * ArtifactLocation::getHolderArtSet() const { - ArtifactLocation *t = const_cast(this); + auto * t = const_cast(this); return t->getHolderArtSet(); } DLL_LINKAGE const CBonusSystemNode * ArtifactLocation::getHolderNode() const { - ArtifactLocation *t = const_cast(this); + auto * t = const_cast(this); return t->getHolderNode(); } @@ -882,7 +881,7 @@ DLL_LINKAGE const ArtSlotInfo *ArtifactLocation::getSlot() const DLL_LINKAGE void ChangeStackCount::applyGs(CGameState * gs) { - auto srcObj = gs->getArmyInstance(army); + auto * srcObj = gs->getArmyInstance(army); if(!srcObj) logNetwork->error("[CRITICAL] ChangeStackCount: invalid army object %d, possible game state corruption.", army.getNum()); @@ -894,7 +893,7 @@ DLL_LINKAGE void ChangeStackCount::applyGs(CGameState * gs) DLL_LINKAGE void SetStackType::applyGs(CGameState * gs) { - auto srcObj = gs->getArmyInstance(army); + auto * srcObj = gs->getArmyInstance(army); if(!srcObj) logNetwork->error("[CRITICAL] SetStackType: invalid army object %d, possible game state corruption.", army.getNum()); @@ -903,7 +902,7 @@ DLL_LINKAGE void SetStackType::applyGs(CGameState * gs) DLL_LINKAGE void EraseStack::applyGs(CGameState * gs) { - auto srcObj = gs->getArmyInstance(army); + auto * srcObj = gs->getArmyInstance(army); if(!srcObj) logNetwork->error("[CRITICAL] EraseStack: invalid army object %d, possible game state corruption.", army.getNum()); @@ -912,11 +911,11 @@ DLL_LINKAGE void EraseStack::applyGs(CGameState * gs) DLL_LINKAGE void SwapStacks::applyGs(CGameState * gs) { - auto srcObj = gs->getArmyInstance(srcArmy); + auto * srcObj = gs->getArmyInstance(srcArmy); if(!srcObj) logNetwork->error("[CRITICAL] SwapStacks: invalid army object %d, possible game state corruption.", srcArmy.getNum()); - auto dstObj = gs->getArmyInstance(dstArmy); + auto * dstObj = gs->getArmyInstance(dstArmy); if(!dstObj) logNetwork->error("[CRITICAL] SwapStacks: invalid army object %d, possible game state corruption.", dstArmy.getNum()); @@ -929,7 +928,7 @@ DLL_LINKAGE void SwapStacks::applyGs(CGameState * gs) DLL_LINKAGE void InsertNewStack::applyGs(CGameState *gs) { - if(auto obj = gs->getArmyInstance(army)) + if(auto * obj = gs->getArmyInstance(army)) obj->putStack(slot, new CStackInstance(type, count)); else logNetwork->error("[CRITICAL] InsertNewStack: invalid army object %d, possible game state corruption.", army.getNum()); @@ -937,11 +936,11 @@ DLL_LINKAGE void InsertNewStack::applyGs(CGameState *gs) DLL_LINKAGE void RebalanceStacks::applyGs(CGameState * gs) { - auto srcObj = gs->getArmyInstance(srcArmy); + auto * srcObj = gs->getArmyInstance(srcArmy); if(!srcObj) logNetwork->error("[CRITICAL] RebalanceStacks: invalid army object %d, possible game state corruption.", srcArmy.getNum()); - auto dstObj = gs->getArmyInstance(dstArmy); + auto * dstObj = gs->getArmyInstance(dstArmy); if(!dstObj) logNetwork->error("[CRITICAL] RebalanceStacks: invalid army object %d, possible game state corruption.", dstArmy.getNum()); @@ -960,13 +959,13 @@ DLL_LINKAGE void RebalanceStacks::applyGs(CGameState * gs) MAYBE_UNUSED(c); auto alHere = ArtifactLocation (src.getStack(), ArtifactPosition::CREATURE_SLOT); auto alDest = ArtifactLocation (dst.getStack(), ArtifactPosition::CREATURE_SLOT); - auto artHere = alHere.getArt(); - auto artDest = alDest.getArt(); + auto * artHere = alHere.getArt(); + auto * artDest = alDest.getArt(); if (artHere) { if (alDest.getArt()) { - auto hero = dynamic_cast (src.army.get()); + auto * hero = dynamic_cast(src.army.get()); if (hero) { artDest->move (alDest, ArtifactLocation (hero, alDest.getArt()->firstBackpackSlot (hero))); @@ -1058,13 +1057,13 @@ DLL_LINKAGE void PutArtifact::applyGs(CGameState *gs) DLL_LINKAGE void EraseArtifact::applyGs(CGameState *gs) { - auto slot = al.getSlot(); + const auto * slot = al.getSlot(); if(slot->locked) { logGlobal->debug("Erasing locked artifact: %s", slot->artifact->artType->getNameTranslated()); DisassembledArtifact dis; dis.al.artHolder = al.artHolder; - auto aset = al.getHolderArtSet(); + auto * aset = al.getHolderArtSet(); #ifndef NDEBUG bool found = false; #endif @@ -1123,9 +1122,9 @@ DLL_LINKAGE void BulkMoveArtifacts::applyGs(CGameState * gs) { srcPos = ArtifactPosition(srcPos.num - numBackpackArtifactsMoved); } - auto slotInfo = artSet->getSlot(srcPos); + const auto * slotInfo = artSet->getSlot(srcPos); assert(slotInfo); - auto art = const_cast(slotInfo->getArt()); + auto * art = const_cast(slotInfo->getArt()); assert(art); switch(operation) { @@ -1153,8 +1152,8 @@ DLL_LINKAGE void BulkMoveArtifacts::applyGs(CGameState * gs) if(swap) { // Swap - auto leftSet = getSrcHolderArtSet(); - auto rightSet = getDstHolderArtSet(); + auto * leftSet = getSrcHolderArtSet(); + auto * rightSet = getDstHolderArtSet(); CArtifactFittingSet artFittingSet(leftSet->bearerType()); artFittingSet.artifactsWorn = rightSet->artifactsWorn; @@ -1182,7 +1181,7 @@ DLL_LINKAGE void AssembledArtifact::applyGs(CGameState *gs) })); MAYBE_UNUSED(transformedArt); - auto combinedArt = new CCombinedArtifactInstance(builtArt); + auto * combinedArt = new CCombinedArtifactInstance(builtArt); gs->map->addNewArtifactInstance(combinedArt); // Retrieve all constituents for(const CArtifact * constituent : *builtArt->constituents) @@ -1213,7 +1212,7 @@ DLL_LINKAGE void AssembledArtifact::applyGs(CGameState *gs) DLL_LINKAGE void DisassembledArtifact::applyGs(CGameState *gs) { - CCombinedArtifactInstance *disassembled = dynamic_cast(al.getArt()); + auto * disassembled = dynamic_cast(al.getArt()); assert(disassembled); std::vector constituents = disassembled->constituentsInfo; @@ -1233,11 +1232,11 @@ DLL_LINKAGE void HeroVisit::applyGs(CGameState *gs) { } -DLL_LINKAGE void SetAvailableArtifacts::applyGs(CGameState *gs) +DLL_LINKAGE void SetAvailableArtifacts::applyGs(CGameState * gs) const { if(id >= 0) { - if(CGBlackMarket *bm = dynamic_cast(gs->map->objects[id].get())) + if(auto * bm = dynamic_cast(gs->map->objects[id].get())) { bm->artifacts = arts; } @@ -1262,7 +1261,7 @@ DLL_LINKAGE void NewTurn::applyGs(CGameState *gs) gs->globalEffects.reduceBonusDurations(Bonus::OneWeek); //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...] - for(NewTurn::Hero h : heroes) //give mana/movement point + for(const NewTurn::Hero & h : heroes) //give mana/movement point { CGHeroInstance *hero = gs->getHero(h.id); if(!hero) @@ -1286,13 +1285,13 @@ DLL_LINKAGE void NewTurn::applyGs(CGameState *gs) hero->mana = h.mana; } - for(auto i = res.cbegin(); i != res.cend(); i++) + for(const auto & re : res) { assert(i->first < PlayerColor::PLAYER_LIMIT); - gs->getPlayerState(i->first)->resources = i->second; + gs->getPlayerState(re.first)->resources = re.second; } - for(auto creatureSet : cres) //set available creatures in towns + for(const auto & creatureSet : cres) //set available creatures in towns creatureSet.second.applyGs(gs); for(CGTownInstance* t : gs->map->towns) @@ -1322,7 +1321,7 @@ DLL_LINKAGE void NewTurn::applyGs(CGameState *gs) } } -DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs) +DLL_LINKAGE void SetObjectProperty::applyGs(CGameState * gs) const { CGObjectInstance *obj = gs->getObjInstance(id); if(!obj) @@ -1331,18 +1330,19 @@ DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs) return; } - CArmedInstance *cai = dynamic_cast(obj); + auto * cai = dynamic_cast(obj); if(what == ObjProperty::OWNER && cai) { if(obj->ID == Obj::TOWN) { - CGTownInstance *t = static_cast(obj); + auto * t = dynamic_cast(obj); + assert(t); if(t->tempOwner < PlayerColor::PLAYER_LIMIT) gs->getPlayerState(t->tempOwner)->towns -= t; if(val < PlayerColor::PLAYER_LIMIT_I) { PlayerState * p = gs->getPlayerState(PlayerColor(val)); - p->towns.push_back(t); + p->towns.emplace_back(t); //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured if(p->daysWithoutCastle) @@ -1363,7 +1363,7 @@ DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs) DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState * gs) { - auto hero = gs->getHero(heroId); + auto * hero = gs->getHero(heroId); assert(hero); auto proposedSkills = hero->getLevelUpProposedSecondarySkills(); @@ -1378,39 +1378,39 @@ DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState * gs) } } -DLL_LINKAGE void HeroLevelUp::applyGs(CGameState * gs) +DLL_LINKAGE void HeroLevelUp::applyGs(CGameState * gs) const { - auto hero = gs->getHero(heroId); + auto * hero = gs->getHero(heroId); assert(hero); hero->levelUp(skills); } -DLL_LINKAGE void CommanderLevelUp::applyGs(CGameState * gs) +DLL_LINKAGE void CommanderLevelUp::applyGs(CGameState * gs) const { - auto hero = gs->getHero(heroId); + auto * hero = gs->getHero(heroId); assert(hero); auto commander = hero->commander; assert(commander); commander->levelUp(); } -DLL_LINKAGE void BattleStart::applyGs(CGameState *gs) +DLL_LINKAGE void BattleStart::applyGs(CGameState * gs) const { gs->curB = info; gs->curB->localInit(); } -DLL_LINKAGE void BattleNextRound::applyGs(CGameState *gs) +DLL_LINKAGE void BattleNextRound::applyGs(CGameState * gs) const { gs->curB->nextRound(round); } -DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState *gs) +DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState * gs) const { gs->curB->nextTurn(stack); } -DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs) +DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState * gs) const { CStack * st = gs->curB->getStack(stackID); assert(st); @@ -1448,7 +1448,7 @@ DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs) } } -DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs) +DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState * gs) const { if(gs->curB) gs->curB->si.gateState = state; @@ -1462,7 +1462,7 @@ void BattleResult::applyGs(CGameState *gs) for(int i = 0; i < 2; ++i) { - if(auto h = gs->curB->battleGetFightingHero(i)) + if(auto * h = gs->curB->battleGetFightingHero(i)) { h->removeBonusesRecursive(Bonus::OneBattle); //remove any "until next battle" bonuses if (h->commander && h->commander->alive) @@ -1556,7 +1556,7 @@ DLL_LINKAGE void StartAction::applyGs(CGameState *gs) } else { - gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.actionSubtype)); + gs->curB->sides[ba.side].usedSpellsHistory.emplace_back(ba.actionSubtype); } switch(ba.actionType) @@ -1581,7 +1581,7 @@ DLL_LINKAGE void StartAction::applyGs(CGameState *gs) } } -DLL_LINKAGE void BattleSpellCast::applyGs(CGameState *gs) +DLL_LINKAGE void BattleSpellCast::applyGs(CGameState * gs) const { assert(gs->curB); @@ -1647,7 +1647,7 @@ DLL_LINKAGE void BattleUnitsChanged::applyBattle(IBattleState * battleState) battleState->updateUnit(elem.id, elem.data); break; default: - logNetwork->error("Unknown unit operation %d", (int)elem.operation); + logNetwork->error("Unknown unit operation %d", static_cast(elem.operation)); break; } } @@ -1676,20 +1676,15 @@ DLL_LINKAGE void BattleObstaclesChanged::applyBattle(IBattleState * battleState) battleState->updateObstacle(change); break; default: - logNetwork->error("Unknown obstacle operation %d", (int)change.operation); + logNetwork->error("Unknown obstacle operation %d", static_cast(change.operation)); break; } } } -DLL_LINKAGE CatapultAttack::CatapultAttack() -{ - attacker = -1; -} +DLL_LINKAGE CatapultAttack::CatapultAttack() = default; -DLL_LINKAGE CatapultAttack::~CatapultAttack() -{ -} +DLL_LINKAGE CatapultAttack::~CatapultAttack() = default; DLL_LINKAGE void CatapultAttack::applyGs(CGameState * gs) { @@ -1699,7 +1694,7 @@ DLL_LINKAGE void CatapultAttack::applyGs(CGameState * gs) DLL_LINKAGE void CatapultAttack::applyBattle(IBattleState * battleState) { - auto town = battleState->getDefendedTown(); + const auto * town = battleState->getDefendedTown(); if(!town) return; @@ -1713,7 +1708,7 @@ DLL_LINKAGE void CatapultAttack::applyBattle(IBattleState * battleState) } } -DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState * gs) +DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState * gs) const { CStack * stack = gs->curB->getStack(stackID); switch(which) @@ -1754,7 +1749,7 @@ DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState * gs) } } -DLL_LINKAGE void PlayerCheated::applyGs(CGameState *gs) +DLL_LINKAGE void PlayerCheated::applyGs(CGameState * gs) const { if(!player.isValidPlayer()) return; @@ -1763,7 +1758,7 @@ DLL_LINKAGE void PlayerCheated::applyGs(CGameState *gs) gs->getPlayerState(player)->enteredWinningCheatCode = winningCheatCode; } -DLL_LINKAGE void YourTurn::applyGs(CGameState *gs) +DLL_LINKAGE void YourTurn::applyGs(CGameState * gs) const { gs->currentPlayer = player; @@ -1771,8 +1766,10 @@ DLL_LINKAGE void YourTurn::applyGs(CGameState *gs) playerState.daysWithoutCastle = daysWithoutCastle; } -DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack) - : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0) +DLL_LINKAGE Component::Component(const CStackBasicDescriptor & stack) + : id(CREATURE) + , subtype(stack.type->idNumber) + , val(stack.count) { } diff --git a/lib/NetPacksLobby.h b/lib/NetPacksLobby.h index b04d92716..b41dfe97a 100644 --- a/lib/NetPacksLobby.h +++ b/lib/NetPacksLobby.h @@ -63,14 +63,10 @@ struct LobbyClientConnected : public CLobbyPackToPropagate // Set by client before sending pack to server std::string uuid; std::vector names; - StartInfo::EMode mode; + StartInfo::EMode mode = StartInfo::INVALID; // Changed by server before announcing pack - int clientId; - int hostClientId; - - LobbyClientConnected() - : mode(StartInfo::INVALID), clientId(-1), hostClientId(-1) - {} + int clientId = -1; + int hostClientId = -1; bool checkClientPermissions(CVCMIServer * srv) const; bool applyOnLobbyHandler(CServerHandler * handler); @@ -92,9 +88,8 @@ struct LobbyClientConnected : public CLobbyPackToPropagate struct LobbyClientDisconnected : public CLobbyPackToPropagate { int clientId; - bool shutdownServer; + bool shutdownServer = false; - LobbyClientDisconnected() : shutdownServer(false) {} bool checkClientPermissions(CVCMIServer * srv) const; bool applyOnServer(CVCMIServer * srv); void applyOnServerAfterAnnounce(CVCMIServer * srv); @@ -126,9 +121,8 @@ struct LobbyGuiAction : public CLobbyPackToPropagate { enum EAction : ui8 { NONE, NO_TAB, OPEN_OPTIONS, OPEN_SCENARIO_LIST, OPEN_RANDOM_MAP_OPTIONS - } action; + } action = NONE; - LobbyGuiAction() : action(NONE) {} bool checkClientPermissions(CVCMIServer * srv) const; void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler); @@ -157,11 +151,10 @@ struct LobbyEndGame : public CLobbyPackToPropagate struct LobbyStartGame : public CLobbyPackToPropagate { // Set by server - std::shared_ptr initializedStartInfo; - CGameState * initializedGameState; - int clientId; //-1 means to all clients + std::shared_ptr initializedStartInfo = nullptr; + CGameState * initializedGameState = nullptr; + int clientId = -1; //-1 means to all clients - LobbyStartGame() : initializedStartInfo(nullptr), initializedGameState(nullptr), clientId(-1) {} bool checkClientPermissions(CVCMIServer * srv) const; bool applyOnServer(CVCMIServer * srv); void applyOnServerAfterAnnounce(CVCMIServer * srv); @@ -181,9 +174,8 @@ struct LobbyStartGame : public CLobbyPackToPropagate struct LobbyChangeHost : public CLobbyPackToPropagate { - int newHostConnectionId; + int newHostConnectionId = -1; - LobbyChangeHost() : newHostConnectionId(-1) {} bool checkClientPermissions(CVCMIServer * srv) const; bool applyOnServer(CVCMIServer * srv); bool applyOnServerAfterAnnounce(CVCMIServer * srv); @@ -197,9 +189,8 @@ struct LobbyChangeHost : public CLobbyPackToPropagate struct LobbyUpdateState : public CLobbyPackToPropagate { LobbyState state; - bool hostChanged; // Used on client-side only + bool hostChanged = false; // Used on client-side only - LobbyUpdateState() : hostChanged(false) {} bool applyOnLobbyHandler(CServerHandler * handler); void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler); @@ -228,7 +219,6 @@ struct LobbySetCampaign : public CLobbyPackToServer { std::shared_ptr ourCampaign; - LobbySetCampaign() {} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler &h, const int version) @@ -239,9 +229,8 @@ struct LobbySetCampaign : public CLobbyPackToServer struct LobbySetCampaignMap : public CLobbyPackToServer { - int mapId; + int mapId = -1; - LobbySetCampaignMap() : mapId(-1) {} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler &h, const int version) @@ -252,9 +241,8 @@ struct LobbySetCampaignMap : public CLobbyPackToServer struct LobbySetCampaignBonus : public CLobbyPackToServer { - int bonusId; + int bonusId = -1; - LobbySetCampaignBonus() : bonusId(-1) {} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler &h, const int version) @@ -266,11 +254,10 @@ struct LobbySetCampaignBonus : public CLobbyPackToServer struct LobbyChangePlayerOption : public CLobbyPackToServer { enum EWhat : ui8 {UNKNOWN, TOWN, HERO, BONUS}; - ui8 what; - si8 direction; //-1 or +1 - PlayerColor color; + ui8 what = UNKNOWN; + si8 direction = 0; //-1 or +1 + PlayerColor color = PlayerColor::CANNOT_DETERMINE; - LobbyChangePlayerOption() : what(UNKNOWN), direction(0), color(PlayerColor::CANNOT_DETERMINE) {} bool checkClientPermissions(CVCMIServer * srv) const; bool applyOnServer(CVCMIServer * srv); @@ -284,9 +271,8 @@ struct LobbyChangePlayerOption : public CLobbyPackToServer struct LobbySetPlayer : public CLobbyPackToServer { - PlayerColor clickedColor; + PlayerColor clickedColor = PlayerColor::CANNOT_DETERMINE; - LobbySetPlayer() : clickedColor(PlayerColor::CANNOT_DETERMINE){} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler &h, const int version) @@ -297,9 +283,8 @@ struct LobbySetPlayer : public CLobbyPackToServer struct LobbySetTurnTime : public CLobbyPackToServer { - ui8 turnTime; + ui8 turnTime = 0; - LobbySetTurnTime() : turnTime(0) {} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler &h, const int version) @@ -310,9 +295,8 @@ struct LobbySetTurnTime : public CLobbyPackToServer struct LobbySetDifficulty : public CLobbyPackToServer { - ui8 difficulty; + ui8 difficulty = 0; - LobbySetDifficulty() : difficulty(0) {} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler &h, const int version) @@ -323,10 +307,9 @@ struct LobbySetDifficulty : public CLobbyPackToServer struct LobbyForceSetPlayer : public CLobbyPackToServer { - ui8 targetConnectedPlayer; - PlayerColor targetPlayerColor; + ui8 targetConnectedPlayer = -1; + PlayerColor targetPlayerColor = PlayerColor::CANNOT_DETERMINE; - LobbyForceSetPlayer() : targetConnectedPlayer(-1), targetPlayerColor(PlayerColor::CANNOT_DETERMINE) {} bool applyOnServer(CVCMIServer * srv); template void serialize(Handler & h, const int version) From 94bc418e34e1259ab9d539c898ce7aeb8a044f17 Mon Sep 17 00:00:00 2001 From: DjWarmonger Date: Sat, 11 Feb 2023 08:28:29 +0100 Subject: [PATCH 04/10] Update CRewardableConstructor.cpp Fixed swapped identifiers in Limiter. --- lib/mapObjects/CRewardableConstructor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/mapObjects/CRewardableConstructor.cpp b/lib/mapObjects/CRewardableConstructor.cpp index f29f17c52..6ef2d2a68 100644 --- a/lib/mapObjects/CRewardableConstructor.cpp +++ b/lib/mapObjects/CRewardableConstructor.cpp @@ -81,8 +81,8 @@ void CRandomRewardObjectInfo::configureLimiter(CRewardableObject * object, CRand limiter.primary = JsonRandom::loadPrimary(source["primary"], rng); limiter.secondary = JsonRandom::loadSecondary(source["secondary"], rng); - limiter.artifacts = JsonRandom::loadArtifacts(source["spells"], rng); - limiter.spells = JsonRandom::loadSpells(source["artifacts"], rng, spells); + limiter.artifacts = JsonRandom::loadArtifacts(source["artifacts"], rng); + limiter.spells = JsonRandom::loadSpells(source["spells"], rng, spells); limiter.creatures = JsonRandom::loadCreatures(source["creatures"], rng); limiter.allOf = configureSublimiters(object, rng, source["allOf"] ); From b30d23d27839a2a360a4edd2d0fe17961e221135 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sun, 12 Feb 2023 00:54:38 +0300 Subject: [PATCH 05/10] vcmi: make ConstTransitivePtr always init self. --- lib/ConstTransitivePtr.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/ConstTransitivePtr.h b/lib/ConstTransitivePtr.h index 3fccbc554..9867bf65e 100644 --- a/lib/ConstTransitivePtr.h +++ b/lib/ConstTransitivePtr.h @@ -16,7 +16,7 @@ VCMI_LIB_NAMESPACE_BEGIN template class ConstTransitivePtr { - T *ptr; + T *ptr = nullptr; ConstTransitivePtr(const T *Ptr) : ptr(const_cast(Ptr)) {} @@ -25,10 +25,7 @@ public: : ptr(Ptr) {} ConstTransitivePtr(std::nullptr_t) - : ptr(nullptr) {} - - const T& operator*() const { return *ptr; From 038db5c71b789727e8ea71a79e8cb5ad3e6cd996 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sun, 12 Feb 2023 04:03:04 +0300 Subject: [PATCH 06/10] vcmi: make int3 as constexpr class This allows us to calculate distances and check const vector validity at compile time --- Global.h | 6 +++++ lib/int3.h | 65 ++++++++++++++++++++++++------------------------------ 2 files changed, 35 insertions(+), 36 deletions(-) diff --git a/Global.h b/Global.h index c1ee6ccb2..66f61d4d4 100644 --- a/Global.h +++ b/Global.h @@ -746,6 +746,12 @@ namespace vstd } return std::to_string(number) + *iter; } + + ///compile-time version of std::abs for ints for int3, in clang++15 std::abs is constexpr + static constexpr int abs(int i) { + if(i < 0) return -i; + return i; + } } using vstd::operator-=; diff --git a/lib/int3.h b/lib/int3.h index 73bda7d76..b665ff2db 100644 --- a/lib/int3.h +++ b/lib/int3.h @@ -18,48 +18,41 @@ public: si32 x, y, z; //c-tor: x, y, z initialized to 0 - int3() : x(0), y(0), z(0) {} // I think that x, y, z should be left uninitialized. + constexpr int3() : x(0), y(0), z(0) {} // I think that x, y, z should be left uninitialized. //c-tor: x, y, z initialized to i - explicit int3(const si32 i) : x(i), y(i), z(i) {} + explicit constexpr int3(const si32 i) : x(i), y(i), z(i) {} //c-tor: x, y, z initialized to X, Y, Z - int3(const si32 X, const si32 Y, const si32 Z) : x(X), y(Y), z(Z) {} - int3(const int3 & c) : x(c.x), y(c.y), z(c.z) {} // Should be set to default (C++11)? + constexpr int3(const si32 X, const si32 Y, const si32 Z) : x(X), y(Y), z(Z) {} + constexpr int3(const int3 & c) = default; - int3 & operator=(const int3 & c) // Should be set to default (C++11)? - { - x = c.x; - y = c.y; - z = c.z; + constexpr int3 & operator=(const int3 & c) = default; + constexpr int3 operator-() const { return int3(-x, -y, -z); } - return *this; - } - int3 operator-() const { return int3(-x, -y, -z); } - - int3 operator+(const int3 & i) const { return int3(x + i.x, y + i.y, z + i.z); } - int3 operator-(const int3 & i) const { return int3(x - i.x, y - i.y, z - i.z); } + constexpr int3 operator+(const int3 & i) const { return int3(x + i.x, y + i.y, z + i.z); } + constexpr int3 operator-(const int3 & i) const { return int3(x - i.x, y - i.y, z - i.z); } //returns int3 with coordinates increased by given number - int3 operator+(const si32 i) const { return int3(x + i, y + i, z + i); } + constexpr int3 operator+(const si32 i) const { return int3(x + i, y + i, z + i); } //returns int3 with coordinates decreased by given number - int3 operator-(const si32 i) const { return int3(x - i, y - i, z - i); } + constexpr int3 operator-(const si32 i) const { return int3(x - i, y - i, z - i); } //returns int3 with coordinates multiplied by given number - int3 operator*(const double i) const { return int3((int)(x * i), (int)(y * i), (int)(z * i)); } + constexpr int3 operator*(const double i) const { return int3((int)(x * i), (int)(y * i), (int)(z * i)); } //returns int3 with coordinates divided by given number - int3 operator/(const double i) const { return int3((int)(x / i), (int)(y / i), (int)(z / i)); } + constexpr int3 operator/(const double i) const { return int3((int)(x / i), (int)(y / i), (int)(z / i)); } //returns int3 with coordinates multiplied by given number - int3 operator*(const si32 i) const { return int3(x * i, y * i, z * i); } + constexpr int3 operator*(const si32 i) const { return int3(x * i, y * i, z * i); } //returns int3 with coordinates divided by given number - int3 operator/(const si32 i) const { return int3(x / i, y / i, z / i); } + constexpr int3 operator/(const si32 i) const { return int3(x / i, y / i, z / i); } - int3 & operator+=(const int3 & i) + constexpr int3 & operator+=(const int3 & i) { x += i.x; y += i.y; z += i.z; return *this; } - int3 & operator-=(const int3 & i) + constexpr int3 & operator-=(const int3 & i) { x -= i.x; y -= i.y; @@ -68,7 +61,7 @@ public: } //increases all coordinates by given number - int3 & operator+=(const si32 i) + constexpr int3 & operator+=(const si32 i) { x += i; y += i; @@ -76,7 +69,7 @@ public: return *this; } //decreases all coordinates by given number - int3 & operator-=(const si32 i) + constexpr int3 & operator-=(const si32 i) { x -= i; y -= i; @@ -84,10 +77,10 @@ public: return *this; } - bool operator==(const int3 & i) const { return (x == i.x && y == i.y && z == i.z); } - bool operator!=(const int3 & i) const { return (x != i.x || y != i.y || z != i.z); } + constexpr bool operator==(const int3 & i) const { return (x == i.x && y == i.y && z == i.z); } + constexpr bool operator!=(const int3 & i) const { return (x != i.x || y != i.y || z != i.z); } - bool operator<(const int3 & i) const + constexpr bool operator<(const int3 & i) const { if (z < i.z) return true; @@ -130,7 +123,7 @@ public: } //returns squared distance on Oxy plane (z coord is not used) - ui32 dist2dSQ(const int3 & o) const + constexpr ui32 dist2dSQ(const int3 & o) const { const si32 dx = (x - o.x); const si32 dy = (y - o.y); @@ -142,17 +135,17 @@ public: return std::sqrt((double)dist2dSQ(o)); } //manhattan distance used for patrol radius (z coord is not used) - double mandist2d(const int3 & o) const + constexpr double mandist2d(const int3 & o) const { - return abs(o.x - x) + abs(o.y - y); + return vstd::abs(o.x - x) + vstd::abs(o.y - y); } //chebyshev distance used for ambient sounds (z coord is not used) - double chebdist2d(const int3 & o) const + constexpr double chebdist2d(const int3 & o) const { - return std::max(std::abs(o.x - x), std::abs(o.y - y)); + return std::max(vstd::abs(o.x - x), vstd::abs(o.y - y)); } - bool areNeighbours(const int3 & o) const + constexpr bool areNeighbours(const int3 & o) const { return (dist2dSQ(o) < 4) && (z == o.z); } @@ -169,7 +162,7 @@ public: return result; } - bool valid() const //Should be named "isValid"? + constexpr bool valid() const //Should be named "isValid"? { return z >= 0; //minimal condition that needs to be fulfilled for tiles in the map } @@ -182,7 +175,7 @@ public: h & z; } - static std::array getDirs() + constexpr static std::array getDirs() { return { { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0), int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) } }; From 3cf303f1c7c484c1aed5fd19e9a2bd7356ff8a60 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sun, 12 Feb 2023 17:50:33 +0300 Subject: [PATCH 07/10] vcmi/client: make ColorRGBA constexpr 1. Replace overflowing int3 to ColorRGBA, which is more semantically correct 2. Make ColorRGBA constexpr, to make sure than hardcoded colors can be initialized in compile time --- client/adventureMap/mapHandler.cpp | 7 ++++--- lib/Color.h | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/client/adventureMap/mapHandler.cpp b/client/adventureMap/mapHandler.cpp index 70e02a41c..53c4f25e0 100644 --- a/client/adventureMap/mapHandler.cpp +++ b/client/adventureMap/mapHandler.cpp @@ -23,6 +23,7 @@ #include "../../lib/mapObjects/CGHeroInstance.h" #include "../../lib/mapObjects/CObjectClassesHandler.h" #include "../../lib/mapping/CMap.h" +#include "../../lib/Color.h" #include "../../lib/CConfigHandler.h" #include "../../lib/CGeneralTextHandler.h" #include "../../lib/CStopWatch.h" @@ -925,21 +926,21 @@ void CMapHandler::CMapBlitter::blit(SDL_Surface * targetSurf, const MapDrawingIn { for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize) { - const int3 color(0x555555, 0x555555, 0x555555); + constexpr ColorRGBA color(0x55, 0x55, 0x55); if (realPos.y >= info->drawBounds.y && realPos.y < info->drawBounds.y + info->drawBounds.h) for(int i = 0; i < tileSize; i++) if (realPos.x + i >= info->drawBounds.x && realPos.x + i < info->drawBounds.x + info->drawBounds.w) - CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x + i, realPos.y, color.x, color.y, color.z); + CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x + i, realPos.y, color.r, color.g, color.b); if (realPos.x >= info->drawBounds.x && realPos.x < info->drawBounds.x + info->drawBounds.w) for(int i = 0; i < tileSize; i++) if (realPos.y + i >= info->drawBounds.y && realPos.y + i < info->drawBounds.y + info->drawBounds.h) - CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x, realPos.y + i, color.x, color.y, color.z); + CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x, realPos.y + i, color.r, color.g, color.b); } } } diff --git a/lib/Color.h b/lib/Color.h index f41f53d46..e6558e9f3 100644 --- a/lib/Color.h +++ b/lib/Color.h @@ -27,7 +27,7 @@ public: uint8_t a; //constructors - ColorRGBA() + constexpr ColorRGBA() :r(0) ,g(0) ,b(0) @@ -35,14 +35,14 @@ public: { } - ColorRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) + constexpr ColorRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) : r(r) , g(g) , b(b) , a(a) {} - ColorRGBA(uint8_t r, uint8_t g, uint8_t b) + constexpr ColorRGBA(uint8_t r, uint8_t g, uint8_t b) : r(r) , g(g) , b(b) From 0627e1ecaaba8e9e3dd1c1b2846f8585604ea4cc Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sun, 12 Feb 2023 17:53:45 +0300 Subject: [PATCH 08/10] vcmi: remove unused variables from lib/rmg --- lib/rmg/ObjectManager.cpp | 2 -- lib/rmg/TreasurePlacer.cpp | 1 - 2 files changed, 3 deletions(-) diff --git a/lib/rmg/ObjectManager.cpp b/lib/rmg/ObjectManager.cpp index feb58fda7..a249bef9c 100644 --- a/lib/rmg/ObjectManager.cpp +++ b/lib/rmg/ObjectManager.cpp @@ -241,7 +241,6 @@ bool ObjectManager::createRequiredObjects() for(const auto & object : requiredObjects) { auto * obj = object.first; - int3 pos; rmg::Object rmgObject(*obj); rmgObject.setTemplate(zone.getTerrainType()); bool guarded = addGuard(rmgObject, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY)); @@ -278,7 +277,6 @@ bool ObjectManager::createRequiredObjects() for(const auto & object : closeObjects) { auto * obj = object.first; - int3 pos; auto possibleArea = zone.areaPossible(); rmg::Object rmgObject(*obj); rmgObject.setTemplate(zone.getTerrainType()); diff --git a/lib/rmg/TreasurePlacer.cpp b/lib/rmg/TreasurePlacer.cpp index 66bfe792e..a076a56eb 100644 --- a/lib/rmg/TreasurePlacer.cpp +++ b/lib/rmg/TreasurePlacer.cpp @@ -736,7 +736,6 @@ void TreasurePlacer::createTreasures(ObjectManager & manager) if(guarded) guarded = manager.addGuard(rmgObject, value); - int3 pos; auto possibleArea = zone.areaPossible(); auto path = rmg::Path::invalid(); From 6d8eac320db4280315c669284a8b5f33b9ab87cf Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sun, 12 Feb 2023 18:21:16 +0300 Subject: [PATCH 09/10] vcmi/client: add missing include to GUIclasses.cpp Fix building with clang++ version 15. --- client/windows/GUIClasses.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/client/windows/GUIClasses.cpp b/client/windows/GUIClasses.cpp index f35a0d949..bc77d6be7 100644 --- a/client/windows/GUIClasses.cpp +++ b/client/windows/GUIClasses.cpp @@ -40,6 +40,7 @@ #include "../lobby/CSavingScreen.h" #include "../renderSDL/SDL_Extensions.h" #include "../render/CAnimation.h" +#include "../CMT.h" #include "../../CCallback.h" From 34a0dbc0b6ce2bc7965201ee7f13cc1ba0302675 Mon Sep 17 00:00:00 2001 From: SoundSSGood <87084363+SoundSSGood@users.noreply.github.com> Date: Fri, 10 Feb 2023 13:46:34 +0200 Subject: [PATCH 10/10] misc slots. fixed combined arts moving --- client/widgets/CArtifactHolder.cpp | 102 ++++++++++------------------- client/widgets/CArtifactHolder.h | 1 - lib/CArtHandler.cpp | 6 +- 3 files changed, 38 insertions(+), 71 deletions(-) diff --git a/client/widgets/CArtifactHolder.cpp b/client/widgets/CArtifactHolder.cpp index 86a5c2850..b0f05ab26 100644 --- a/client/widgets/CArtifactHolder.cpp +++ b/client/widgets/CArtifactHolder.cpp @@ -149,19 +149,12 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState) select(); } } - else if(ourArt == ourOwner->commonInfo->src.art) //restore previously picked artifact - { - deselect(); - } - else //perform artifact transition + // Perform artifact transition + else if(ourArt != ourOwner->commonInfo->src.art) { if(inBackpack) // Backpack destination. { - if(srcInBackpack && slotID == ourOwner->commonInfo->src.slotID + 1) //next slot (our is not visible, so visually same as "old" place) to the art -> make nothing, return artifact to slot - { - deselect(); - } - else + if(!srcInBackpack || slotID != ourOwner->commonInfo->src.slotID + 1) { const CArtifact * const cur = ourOwner->commonInfo->src.art->artType; @@ -186,9 +179,7 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState) || ourOwner->commonInfo->src.slotID < ourOwner->commonInfo->dst.slotID) //rearranging arts in backpack after taking src artifact, the dest id will be shifted vstd::advance(ourOwner->commonInfo->dst.slotID, -1); } - if(srcInSameHero && ourOwner->commonInfo->dst.slotID == ourOwner->commonInfo->src.slotID) //we came to src == dst - deselect(); - else + if(!srcInSameHero || ourOwner->commonInfo->dst.slotID != ourOwner->commonInfo->src.slotID) ourOwner->realizeCurrentTransaction(); } } @@ -274,13 +265,13 @@ void CArtifactsOfHero::deactivate() /** * Selects artifact slot so that the containing artifact looks like it's picked up. */ -void CHeroArtPlace::select () +void CHeroArtPlace::select() { - if (locked) + if(locked) return; pickSlot(true); - if(ourArt->canBeDisassembled() && slotID < GameConstants::BACKPACK_START) //worn combined artifact -> locks have to disappear + if(ourArt->canBeDisassembled() && ArtifactUtils::isSlotEquipment(slotID)) //worn combined artifact -> locks have to disappear { for(auto slot : ArtifactUtils::constituentWornSlots()) { @@ -292,41 +283,10 @@ void CHeroArtPlace::select () CCS->curh->dragAndDropCursor("artifact", ourArt->artType->getIconIndex()); ourOwner->commonInfo->src.setTo(this, false); - ourOwner->markPossibleSlots(ourArt); + ourOwner->commonInfo->src.slotID = ArtifactPosition::TRANSITION_POS; - if(slotID >= GameConstants::BACKPACK_START) - ourOwner->scrollBackpack(0); //will update slots - - ourOwner->updateParentWindow(); - ourOwner->safeRedraw(); -} - -/** - * Deselects the artifact slot. - */ -void CHeroArtPlace::deselect () -{ - pickSlot(false); - if(ourArt && ourArt->canBeDisassembled()) //combined art returned to its slot -> restore locks - { - for(auto slot : ArtifactUtils::constituentWornSlots()) - { - auto place = ourOwner->getArtPlace(slot); - - if(nullptr != place)//getArtPlace may return null - place->pickSlot(false); - } - } - - CCS->curh->dragAndDropCursor(nullptr); - ourOwner->unmarkSlots(); - ourOwner->commonInfo->src.clear(); - if(slotID >= GameConstants::BACKPACK_START) - ourOwner->scrollBackpack(0); //will update slots - - - ourOwner->updateParentWindow(); - ourOwner->safeRedraw(); + LOCPLINT->cb->swapArtifacts(ArtifactLocation(ourOwner->curHero, slotID), + ArtifactLocation(ourOwner->curHero, ArtifactPosition::TRANSITION_POS)); } void CHeroArtPlace::showAll(SDL_Surface * to) @@ -760,35 +720,41 @@ void CArtifactsOfHero::artifactMoved(const ArtifactLocation & src, const Artifac commonInfo->src.slotID = src.slot; } // Artifact was taken from us - else if(commonInfo->src == src) + else if(commonInfo->src == src && dst.slot != ArtifactPosition::TRANSITION_POS) { // Expected movement from slot ot slot assert(commonInfo->dst == dst // Artifact moved back to backpack (eg. to make place for art we are moving) - || dst.slot == dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START + || dst.slot == dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START || dst.getHolderArtSet()->bearerType() != ArtBearer::HERO); commonInfo->reset(); unmarkSlots(); } - // The dest artifact was moved after the swap -> we are picking it - else if(commonInfo->dst == src) + else { - assert(dst.slot == ArtifactPosition::TRANSITION_POS); - commonInfo->reset(); - - for(CArtifactsOfHero * aoh : commonInfo->participants) + // The dest artifact was moved after the swap -> we are picking it + if(commonInfo->dst == src) { - if(dst.isHolder(aoh->curHero)) - { - commonInfo->src.AOH = aoh; - break; - } - } + assert(dst.slot == ArtifactPosition::TRANSITION_POS); + commonInfo->reset(); - commonInfo->src.art = dst.getArt(); - commonInfo->src.slotID = dst.slot; - assert(commonInfo->src.AOH); - CCS->curh->dragAndDropCursor("artifact", dst.getArt()->artType->getIconIndex()); + for(CArtifactsOfHero * aoh : commonInfo->participants) + { + if(dst.isHolder(aoh->curHero)) + { + commonInfo->src.AOH = aoh; + break; + } + } + + commonInfo->src.art = dst.getArt(); + commonInfo->src.slotID = dst.slot; + assert(commonInfo->src.AOH); + CCS->curh->dragAndDropCursor("artifact", dst.getArt()->artType->getIconIndex()); + } + auto art = dst.getArt(); + if(art && dst.slot == ArtifactPosition::TRANSITION_POS) + markPossibleSlots(art); } updateParentWindow(); diff --git a/client/widgets/CArtifactHolder.h b/client/widgets/CArtifactHolder.h index 0adfb0ec9..9ff040f4e 100644 --- a/client/widgets/CArtifactHolder.h +++ b/client/widgets/CArtifactHolder.h @@ -90,7 +90,6 @@ public: void clickLeft(tribool down, bool previousState) override; void clickRight(tribool down, bool previousState) override; void select(); - void deselect(); void showAll(SDL_Surface * to) override; bool fitsHere (const CArtifactInstance * art) const; //returns true if given artifact can be placed here diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index 0d218b2ad..3e3e2afcd 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -1365,8 +1365,10 @@ const ArtSlotInfo * CArtifactSet::getSlot(ArtifactPosition pos) const if(pos == ArtifactPosition::TRANSITION_POS) { // Always add to the end. Always take from the beginning. - assert(!artifactsTransitionPos.empty()); - return &(*artifactsTransitionPos.begin()); + if(artifactsTransitionPos.empty()) + return nullptr; + else + return &(*artifactsTransitionPos.begin()); } if(vstd::contains(artifactsWorn, pos)) return &artifactsWorn.at(pos);