From 9dfef2186d2161ba507c41f4132815c9ae9fb9c0 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Fri, 22 Jan 2016 22:29:53 +0300 Subject: [PATCH 01/15] Fix 1569 winning hero with no troops shall retreat --- server/CGameHandler.cpp | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 10ee4951d..19627cb5a 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -712,7 +712,7 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) setBattle(nullptr); - if(visitObjectAfterVictory && result.winner==0) + if(visitObjectAfterVictory && result.winner==0 && !finishingBattle->winnerHero->stacks.empty()) { logGlobal->traceStream() << "post-victory visit"; visitObjectOnTile(*getTile(finishingBattle->winnerHero->getPosition()), finishingBattle->winnerHero); @@ -741,6 +741,24 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) sendAndApply(&sah); } + if(finishingBattle->winnerHero->stacks.empty()) + { + RemoveObject ro(finishingBattle->winnerHero->id); + sendAndApply(&ro); + + SetAvailableHeroes sah; + sah.player = finishingBattle->victor; + sah.hid[0] = finishingBattle->winnerHero->subID; + sah.army[0].clear(); + sah.army[0].setCreature(SlotID(0), finishingBattle->winnerHero->type->initialArmy.at(0).creature, 1); + + if(const CGHeroInstance *another = getPlayer(finishingBattle->victor)->availableHeroes.at(1)) + sah.hid[1] = another->subID; + else + sah.hid[1] = -1; + + sendAndApply(&sah); + } } void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance, int targetHex) From 99992599dbea19221ced02de76de3e4a2de26933 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Fri, 22 Jan 2016 22:37:46 +0300 Subject: [PATCH 02/15] Partially fix 1416 tavern hero rotation --- server/CGameHandler.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 19627cb5a..03a703240 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -734,7 +734,7 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) sah.army[0].setCreature(SlotID(0), finishingBattle->loserHero->type->initialArmy.at(0).creature, 1); } - if(const CGHeroInstance *another = getPlayer(finishingBattle->loser)->availableHeroes.at(1)) + if(const CGHeroInstance *another = getPlayer(finishingBattle->loser)->availableHeroes.at(0)) sah.hid[1] = another->subID; else sah.hid[1] = -1; @@ -752,7 +752,7 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) sah.army[0].clear(); sah.army[0].setCreature(SlotID(0), finishingBattle->winnerHero->type->initialArmy.at(0).creature, 1); - if(const CGHeroInstance *another = getPlayer(finishingBattle->victor)->availableHeroes.at(1)) + if(const CGHeroInstance *another = getPlayer(finishingBattle->victor)->availableHeroes.at(0)) sah.hid[1] = another->subID; else sah.hid[1] = -1; From 2a6a8cd43356aeaec7a9355a8859a4d3a389e39c Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sat, 23 Jan 2016 19:42:56 +0300 Subject: [PATCH 03/15] Fix segfault when non-hero forces win --- server/CGameHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 03a703240..9912d53f8 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -741,7 +741,7 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) sendAndApply(&sah); } - if(finishingBattle->winnerHero->stacks.empty()) + if(finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()) { RemoveObject ro(finishingBattle->winnerHero->id); sendAndApply(&ro); From 7185890723031c033b87468a9f4edf4ae34c9b2c Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sun, 24 Jan 2016 01:31:39 +0300 Subject: [PATCH 04/15] Fix double free in battleAfterLevelUp() in case of a draw --- server/CGameHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 9912d53f8..75802cb9c 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -741,7 +741,7 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) sendAndApply(&sah); } - if(finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()) + if(result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()) { RemoveObject ro(finishingBattle->winnerHero->id); sendAndApply(&ro); From afa95312baaf5318301edb3ffd669443e64bb8f0 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Thu, 21 Jan 2016 20:23:45 +0300 Subject: [PATCH 05/15] Fix 2139 captured spell scroll descriptions --- client/widgets/CArtifactHolder.cpp | 98 ++++++++++-------------------- client/widgets/CComponent.cpp | 19 +++++- client/windows/CTradeWindow.cpp | 10 +-- lib/CArtHandler.cpp | 51 +++++++++++++++- lib/CArtHandler.h | 2 + server/CGameHandler.cpp | 66 +++++++++++--------- 6 files changed, 140 insertions(+), 106 deletions(-) diff --git a/client/widgets/CArtifactHolder.cpp b/client/widgets/CArtifactHolder.cpp index f885ad961..0af6f901a 100644 --- a/client/widgets/CArtifactHolder.cpp +++ b/client/widgets/CArtifactHolder.cpp @@ -32,7 +32,7 @@ */ CArtPlace::CArtPlace(Point position, const CArtifactInstance * Art): - locked(false), picked(false), marked(false), ourArt(Art) + locked(false), picked(false), marked(false), ourArt(Art) { pos += position; pos.w = pos.h = 44; @@ -180,7 +180,7 @@ void CArtPlace::clickLeft(tribool down, bool previousState) if(srcInBackpack && srcInSameHero) { if(!ourArt //cannot move from backpack to AFTER backpack -> combined with vstd::amin above it will guarantee that dest is at most the last artifact - || ourOwner->commonInfo->src.slotID < ourOwner->commonInfo->dst.slotID) //rearranging arts in backpack after taking src artifact, the dest id will be shifted + || 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 @@ -386,70 +386,36 @@ void CArtPlace::setArtifact(const CArtifactInstance *art) image->disable(); text = std::string(); hoverText = CGI->generaltexth->allTexts[507]; + return; + } + + image->enable(); + image->setFrame(locked ? ArtifactID::ART_LOCK : art->artType->iconIndex); + + text = art->getEffectiveDescription(ourOwner->curHero); + + if(art->artType->id == ArtifactID::SPELL_SCROLL) + { + int spellID = art->getGivenSpellID(); + if(spellID >= 0) + { + //add spell component info (used to provide a pic in r-click popup) + baseType = CComponent::spell; + type = spellID; + bonusValue = 0; + } } else { - image->enable(); - image->setFrame(locked ? ArtifactID::ART_LOCK : art->artType->iconIndex); - - std::string artDesc = ourArt->artType->Description(); - if (vstd::contains (artDesc, '{')) - text = artDesc; - else - text = '{' + ourArt->artType->Name() + "}\n\n" + artDesc; //workaround for new artifacts with single name, turns it to H3-style - - if(art->artType->id == ArtifactID::SPELL_SCROLL) - { - // we expect scroll description to be like this: This scroll contains the [spell name] spell which is added into your spell book for as long as you carry the scroll. - // so we want to replace text in [...] with a spell name - // however other language versions don't have name placeholder at all, so we have to be careful - int spellID = art->getGivenSpellID(); - size_t nameStart = text.find_first_of('['); - size_t nameEnd = text.find_first_of(']', nameStart); - if(spellID >= 0) - { - if(nameStart != std::string::npos && nameEnd != std::string::npos) - text = text.replace(nameStart, nameEnd - nameStart + 1, CGI->spellh->objects[spellID]->name); - - //add spell component info (used to provide a pic in r-click popup) - baseType = CComponent::spell; - type = spellID; - bonusValue = 0; - } - } - else - { - baseType = CComponent::artifact; - type = art->artType->id; - bonusValue = 0; - } - if (art->artType->constituents) //display info about components of combined artifact - { - //TODO - } - else if (art->artType->constituentOf.size()) //display info about set - { - std::string artList; - auto combinedArt = art->artType->constituentOf[0]; - text += "\n\n"; - text += "{" + combinedArt->Name() + "}"; - int wornArtifacts = 0; - for (auto a : *combinedArt->constituents) //TODO: can the artifact be a part of more than one set? - { - artList += "\n" + a->Name(); - if (ourOwner->curHero->hasArt(a->id, true)) - wornArtifacts++; - } - text += " (" + boost::str(boost::format("%d") % wornArtifacts) + " / " + - boost::str(boost::format("%d") % combinedArt->constituents->size()) + ")" + artList; - //TODO: fancy colors and fonts for this text - } - - if (locked) // Locks should appear as empty. - hoverText = CGI->generaltexth->allTexts[507]; - else - hoverText = boost::str(boost::format(CGI->generaltexth->heroscrn[1]) % ourArt->artType->Name()); + baseType = CComponent::artifact; + type = art->artType->id; + bonusValue = 0; } + + if (locked) // Locks should appear as empty. + hoverText = CGI->generaltexth->allTexts[507]; + else + hoverText = boost::str(boost::format(CGI->generaltexth->heroscrn[1]) % ourArt->artType->Name()); } void CArtifactsOfHero::SCommonPart::reset() @@ -811,7 +777,7 @@ void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const Artifact } else if(src.slot >= GameConstants::BACKPACK_START && src.slot < commonInfo->src.slotID && - src.isHolder(commonInfo->src.AOH->curHero)) //artifact taken from before currently picked one + src.isHolder(commonInfo->src.AOH->curHero)) //artifact taken from before currently picked one { //int fixedSlot = src.hero->getArtPos(commonInfo->src.art); vstd::advance(commonInfo->src.slotID, -1); @@ -825,14 +791,14 @@ void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const Artifact } updateParentWindow(); - int shift = 0; + int shift = 0; // if(dst.slot >= Arts::BACKPACK_START && dst.slot - Arts::BACKPACK_START < backpackPos) // shift++; // - if(src.slot < GameConstants::BACKPACK_START && dst.slot - GameConstants::BACKPACK_START < backpackPos) + if(src.slot < GameConstants::BACKPACK_START && dst.slot - GameConstants::BACKPACK_START < backpackPos) shift++; if(dst.slot < GameConstants::BACKPACK_START && src.slot - GameConstants::BACKPACK_START < backpackPos) - shift--; + shift--; if( (isCurHeroSrc && src.slot >= GameConstants::BACKPACK_START) || (isCurHeroDst && dst.slot >= GameConstants::BACKPACK_START) ) diff --git a/client/widgets/CComponent.cpp b/client/widgets/CComponent.cpp index 41f331539..e841f830c 100644 --- a/client/widgets/CComponent.cpp +++ b/client/widgets/CComponent.cpp @@ -7,6 +7,7 @@ #include "../CMessage.h" #include "../CGameInfo.h" #include "../widgets/Images.h" +#include "../widgets/CArtifactHolder.h" #include "../windows/CAdvmapInterface.h" #include "../../lib/CArtHandler.h" @@ -144,14 +145,26 @@ size_t CComponent::getIndex() std::string CComponent::getDescription() { - switch (compType) + switch(compType) { case primskill: return (subtype < 4)? CGI->generaltexth->arraytxt[2+subtype] //Primary skill : CGI->generaltexth->allTexts[149]; //mana case secskill: return CGI->generaltexth->skillInfoTexts[subtype][val-1]; case resource: return CGI->generaltexth->allTexts[242]; case creature: return ""; - case artifact: return CGI->arth->artifacts[subtype]->Description(); + case artifact: + { + std::unique_ptr art; + if (subtype != ArtifactID::SPELL_SCROLL) + { + art.reset(CArtifactInstance::createNewArtifactInstance(subtype)); + } + else + { + art.reset(CArtifactInstance::createScroll(static_cast(val))); + } + return art->getEffectiveDescription(); + } case experience: return CGI->generaltexth->allTexts[241]; case spell: return CGI->spellh->objects[subtype]->getLevelInfo(val).description; case morale: return CGI->generaltexth->heroscrn[ 4 - (val>0) + (val<0)]; @@ -166,7 +179,7 @@ std::string CComponent::getDescription() std::string CComponent::getSubtitle() { - if (!perDay) + if(!perDay) return getSubtitleInternal(); std::string ret = CGI->generaltexth->allTexts[3]; diff --git a/client/windows/CTradeWindow.cpp b/client/windows/CTradeWindow.cpp index a601d7e33..dda828c3a 100644 --- a/client/windows/CTradeWindow.cpp +++ b/client/windows/CTradeWindow.cpp @@ -269,7 +269,7 @@ void CTradeWindow::CTradeableItem::clickRight(tribool down, bool previousState) case ARTIFACT_TYPE: case ARTIFACT_PLACEHOLDER: if(id >= 0) - adventureInt->handleRightClick(CGI->arth->artifacts[id]->Description(), down); + adventureInt->handleRightClick(hlp->getEffectiveDescription(), down); break; } } @@ -500,14 +500,14 @@ void CTradeWindow::getPositionsFor(std::vector &poss, bool Left, EType typ int h, w, x, y, dx, dy; int leftToRightOffset; getBaseForPositions(type, dx, dy, x, y, h, w, !Left, leftToRightOffset); - - const std::vector tmp = + + const std::vector tmp = { genRect(h, w, x, y), genRect(h, w, x + dx, y), genRect(h, w, x + 2*dx, y), genRect(h, w, x, y + dy), genRect(h, w, x + dx, y + dy), genRect(h, w, x + 2*dx, y + dy), - genRect(h, w, x + dx, y + 2*dy) + genRect(h, w, x + dx, y + 2*dy) }; - + vstd::concatenate(poss, tmp); if(!Left) diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index 4e48b5ff3..80957e0eb 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -738,9 +738,14 @@ std::string CArtifactInstance::nodeName() const } CArtifactInstance * CArtifactInstance::createScroll( const CSpell *s) +{ + return createScroll(s->id); +} + +CArtifactInstance *CArtifactInstance::createScroll(SpellID sid) { auto ret = new CArtifactInstance(VLC->arth->artifacts[ArtifactID::SPELL_SCROLL]); - auto b = new Bonus(Bonus::PERMANENT, Bonus::SPELL, Bonus::ARTIFACT_INSTANCE, -1, ArtifactID::SPELL_SCROLL, s->id); + auto b = new Bonus(Bonus::PERMANENT, Bonus::SPELL, Bonus::ARTIFACT_INSTANCE, -1, ArtifactID::SPELL_SCROLL, sid); ret->addNewBonus(b); return ret; } @@ -752,6 +757,48 @@ void CArtifactInstance::init() setNodeType(ARTIFACT_INSTANCE); } +std::string CArtifactInstance::getEffectiveDescription( + const CGHeroInstance *hero) const +{ + std::string text = this->artType->Description(); + if (!vstd::contains(text, '{')) + text = '{' + this->artType->Name() + "}\n\n" + text; //workaround for new artifacts with single name, turns it to H3-style + + if(this->artType->id == ArtifactID::SPELL_SCROLL) + { + // we expect scroll description to be like this: This scroll contains the [spell name] spell which is added into your spell book for as long as you carry the scroll. + // so we want to replace text in [...] with a spell name + // however other language versions don't have name placeholder at all, so we have to be careful + int spellID = this->getGivenSpellID(); + size_t nameStart = text.find_first_of('['); + size_t nameEnd = text.find_first_of(']', nameStart); + if(spellID >= 0) + { + if(nameStart != std::string::npos && nameEnd != std::string::npos) + text = text.replace(nameStart, nameEnd - nameStart + 1, VLC->spellh->objects[spellID]->name); + } + } + else if (hero && this->artType->constituentOf.size()) //display info about set + { + std::string artList; + auto combinedArt = this->artType->constituentOf[0]; + text += "\n\n"; + text += "{" + combinedArt->Name() + "}"; + int wornArtifacts = 0; + for (auto a : *combinedArt->constituents) //TODO: can the artifact be a part of more than one set? + { + artList += "\n" + a->Name(); + if (hero->hasArt(a->id, true)) + wornArtifacts++; + } + text += " (" + boost::str(boost::format("%d") % wornArtifacts) + " / " + + boost::str(boost::format("%d") % combinedArt->constituents->size()) + ")" + artList; + //TODO: fancy colors and fonts for this text + } + + return text; +} + ArtifactPosition CArtifactInstance::firstAvailableSlot(const CArtifactSet *h) const { for(auto slot : artType->possibleSlots.at(h->bearerType())) @@ -900,7 +947,7 @@ SpellID CArtifactInstance::getGivenSpellID() const const Bonus * b = getBonusLocalFirst(Selector::type(Bonus::SPELL)); if(!b) { - logGlobal->warnStream() << "Warning: " << nodeName() << " doesn't bear any spell!"; + logGlobal->warnStream() << "Warning: " << nodeName() << " doesn't bear any spell!"; return SpellID::NONE; } return SpellID(b->subtype); diff --git a/lib/CArtHandler.h b/lib/CArtHandler.h index d9ffdc46e..a19539c12 100644 --- a/lib/CArtHandler.h +++ b/lib/CArtHandler.h @@ -119,6 +119,7 @@ public: void deserializationFix(); void setType(CArtifact *Art); + std::string getEffectiveDescription(const CGHeroInstance *hero = nullptr) const; ArtifactPosition firstAvailableSlot(const CArtifactSet *h) const; ArtifactPosition firstBackpackSlot(const CArtifactSet *h) const; SpellID getGivenSpellID() const; //to be used with scrolls (and similar arts), -1 if none @@ -143,6 +144,7 @@ public: } static CArtifactInstance *createScroll(const CSpell *s); + static CArtifactInstance *createScroll(SpellID sid); static CArtifactInstance *createNewArtifactInstance(CArtifact *Art); static CArtifactInstance *createNewArtifactInstance(int aid); }; diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 968c4b571..df0fe9c86 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -471,7 +471,7 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer const CArmedInstance *bEndArmy2 = gs->curB->sides.at(1).armyObject; const BattleResult::EResult result = battleResult.get()->result; - auto findBattleQuery = [this] () -> std::shared_ptr + auto findBattleQuery = [this]() -> std::shared_ptr { for(auto &q : queries.allQueries()) { @@ -526,66 +526,70 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer } - std::vector arts; //display them in window + std::vector arts; //display them in window - if (result == BattleResult::NORMAL && finishingBattle->winnerHero) + if(result == BattleResult::NORMAL && finishingBattle->winnerHero) { - if (finishingBattle->loserHero) + auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma) { - auto artifactsWorn = finishingBattle->loserHero->artifactsWorn; //TODO: wrap it into a function, somehow (boost::variant -_-) + arts.push_back(art); + ma->dst = ArtifactLocation(finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero)); + sendAndApply(ma); + }; + if(finishingBattle->loserHero) + { + //TODO: wrap it into a function, somehow (boost::variant -_-) + auto artifactsWorn = finishingBattle->loserHero->artifactsWorn; for (auto artSlot : artifactsWorn) { MoveArtifact ma; - ma.src = ArtifactLocation (finishingBattle->loserHero, artSlot.first); + ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first); const CArtifactInstance * art = ma.src.getArt(); - if (art && !art->artType->isBig() && art->artType->id != ArtifactID::SPELLBOOK) // don't move war machines or locked arts (spellbook) + if(art && !art->artType->isBig() && + art->artType->id != ArtifactID::SPELLBOOK) + // don't move war machines or locked arts (spellbook) { - arts.push_back (art->artType->id); - ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero)); - sendAndApply(&ma); + sendMoveArtifact(art, &ma); } } - while (!finishingBattle->loserHero->artifactsInBackpack.empty()) + while(!finishingBattle->loserHero->artifactsInBackpack.empty()) { //we assume that no big artifacts can be found MoveArtifact ma; - ma.src = ArtifactLocation (finishingBattle->loserHero, + ma.src = ArtifactLocation(finishingBattle->loserHero, ArtifactPosition(GameConstants::BACKPACK_START)); //backpack automatically shifts arts to beginning const CArtifactInstance * art = ma.src.getArt(); - arts.push_back (art->artType->id); - ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero)); - sendAndApply(&ma); + if(art->artType->id != ArtifactID::GRAIL) //grail may not be won + { + sendMoveArtifact(art, &ma); + } } - if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero? + if(finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero? { artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn; - for (auto artSlot : artifactsWorn) + for(auto artSlot : artifactsWorn) { MoveArtifact ma; - ma.src = ArtifactLocation (finishingBattle->loserHero->commander.get(), artSlot.first); + ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first); const CArtifactInstance * art = ma.src.getArt(); if (art && !art->artType->isBig()) { - arts.push_back (art->artType->id); - ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero)); - sendAndApply(&ma); + sendMoveArtifact(art, &ma); } } } } - for (auto armySlot : gs->curB->battleGetArmyObject(!battleResult.data->winner)->stacks) + for(auto armySlot : gs->curB->battleGetArmyObject(!battleResult.data->winner)->stacks) { auto artifactsWorn = armySlot.second->artifactsWorn; for (auto artSlot : artifactsWorn) { MoveArtifact ma; - ma.src = ArtifactLocation (armySlot.second, artSlot.first); + ma.src = ArtifactLocation(armySlot.second, artSlot.first); const CArtifactInstance * art = ma.src.getArt(); if (art && !art->artType->isBig()) { - arts.push_back (art->artType->id); - ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero)); - sendAndApply(&ma); + sendMoveArtifact(art, &ma); } } } @@ -593,23 +597,25 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer sendAndApply(battleResult.data); //after this point casualties objects are destroyed - if (arts.size()) //display loot + if(arts.size()) //display loot { InfoWindow iw; iw.player = finishingBattle->winnerHero->tempOwner; iw.text.addTxt (MetaString::GENERAL_TXT, 30); //You have captured enemy artifact - for (auto id : arts) //TODO; separate function to display loot for various ojects? + for(auto art : arts) //TODO; separate function to display loot for various ojects? { - iw.components.push_back (Component (Component::ARTIFACT, id, 0, 0)); + iw.components.push_back(Component( + Component::ARTIFACT, art->artType->id, + art->artType->id == ArtifactID::SPELL_SCROLL? art->getGivenSpellID() : 0, 0)); if(iw.components.size() >= 14) { sendAndApply(&iw); iw.components.clear(); } } - if (iw.components.size()) + if(iw.components.size()) { sendAndApply(&iw); } From a74fbff34ffe761f4c48a8909c447dba20a77a17 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Wed, 20 Jan 2016 14:22:12 +0300 Subject: [PATCH 06/15] Fix 2076 Grail removal --- lib/NetPacksLib.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index 7a5fe5c04..fd39d78d9 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -362,6 +362,10 @@ DLL_LINKAGE void RemoveObject::applyGs( CGameState *gs ) p->heroes -= h; h->detachFrom(h->whereShouldBeAttached(gs)); h->tempOwner = PlayerColor::NEUTRAL; //no one owns beaten hero + vstd::erase_if(h->artifactsInBackpack, [](const ArtSlotInfo& asi) + { + return asi.artifact->artType->id == ArtifactID::GRAIL; + }); if(h->visitedTown) { From 22eb71de0325d6ff672f0ac9c918befd6a7f9dfa Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Mon, 25 Jan 2016 14:14:32 +0300 Subject: [PATCH 07/15] Remove this-> occurrences in new code --- lib/CArtHandler.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index 80957e0eb..464f8d923 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -760,16 +760,16 @@ void CArtifactInstance::init() std::string CArtifactInstance::getEffectiveDescription( const CGHeroInstance *hero) const { - std::string text = this->artType->Description(); + std::string text = artType->Description(); if (!vstd::contains(text, '{')) - text = '{' + this->artType->Name() + "}\n\n" + text; //workaround for new artifacts with single name, turns it to H3-style + text = '{' + artType->Name() + "}\n\n" + text; //workaround for new artifacts with single name, turns it to H3-style - if(this->artType->id == ArtifactID::SPELL_SCROLL) + if(artType->id == ArtifactID::SPELL_SCROLL) { // we expect scroll description to be like this: This scroll contains the [spell name] spell which is added into your spell book for as long as you carry the scroll. // so we want to replace text in [...] with a spell name // however other language versions don't have name placeholder at all, so we have to be careful - int spellID = this->getGivenSpellID(); + int spellID = getGivenSpellID(); size_t nameStart = text.find_first_of('['); size_t nameEnd = text.find_first_of(']', nameStart); if(spellID >= 0) @@ -778,10 +778,10 @@ std::string CArtifactInstance::getEffectiveDescription( text = text.replace(nameStart, nameEnd - nameStart + 1, VLC->spellh->objects[spellID]->name); } } - else if (hero && this->artType->constituentOf.size()) //display info about set + else if (hero && artType->constituentOf.size()) //display info about set { std::string artList; - auto combinedArt = this->artType->constituentOf[0]; + auto combinedArt = artType->constituentOf[0]; text += "\n\n"; text += "{" + combinedArt->Name() + "}"; int wornArtifacts = 0; From 6849ff846c4afe3c2c46941148fea4819dd46126 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Mon, 25 Jan 2016 15:36:34 +0300 Subject: [PATCH 08/15] Fix memory corruption with a draw; race in setBattleResult() --- server/CGameHandler.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 75802cb9c..e9fe4ac3e 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -124,6 +124,11 @@ static inline double distance(int3 a, int3 b) } static void giveExp(BattleResult &r) { + if(r.winner > 1) + { + // draw + return; + } r.exp[0] = 0; r.exp[1] = 0; for(auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++) @@ -5679,16 +5684,18 @@ void CGameHandler::giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact void CGameHandler::setBattleResult(BattleResult::EResult resultType, int victoriusSide) { - if(battleResult.get()) + boost::unique_lock guard(battleResult.mx); + if(battleResult.data) { - complain("There is already set result?"); + complain((boost::format("The battle result has been already set (to %d, asked to %d)") + % battleResult.data->result % resultType).str()); return; } auto br = new BattleResult; br->result = resultType; br->winner = victoriusSide; //surrendering side loses gs->curB->calculateCasualties(br->casualties); - battleResult.set(br); + battleResult.data = br; } void CGameHandler::commitPackage( CPackForClient *pack ) From 97a8874ed73cb13529b6222dbd9ecc14f8a42130 Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Tue, 26 Jan 2016 08:41:09 +0300 Subject: [PATCH 09/15] CGCreature: fix crash on draw Also according to H3 behaviour if there artifact monster guarded it's will be lost on draw. --- lib/mapObjects/CGPandoraBox.cpp | 8 ++++---- lib/mapObjects/MiscObjects.cpp | 20 ++++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/lib/mapObjects/CGPandoraBox.cpp b/lib/mapObjects/CGPandoraBox.cpp index f512716d6..b21fc3ced 100644 --- a/lib/mapObjects/CGPandoraBox.cpp +++ b/lib/mapObjects/CGPandoraBox.cpp @@ -295,10 +295,10 @@ void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int nega void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const { - if(result.winner) - return; - - giveContentsUpToExp(hero); + if(result.winner == 0) + { + giveContentsUpToExp(hero); + } } void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index 51a293ed3..5f1014670 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -453,22 +453,26 @@ void CGCreature::flee( const CGHeroInstance * h ) const void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const { - - if(result.winner==0) + if(result.winner == 0) { giveReward(hero); cb->removeObject(this); } + else if(result.winner > 1) // draw + { + // guarded reward is lost forever on draw + cb->removeObject(this); + } else { //merge stacks into one TSlots::const_iterator i; CCreature * cre = VLC->creh->creatures[formation.basicType]; - for (i = stacks.begin(); i != stacks.end(); i++) + for(i = stacks.begin(); i != stacks.end(); i++) { - if (cre->isMyUpgrade(i->second->type)) + if(cre->isMyUpgrade(i->second->type)) { - cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures + cb->changeStackType(StackLocation(this, i->first), cre); //un-upgrade creatures } } @@ -476,16 +480,16 @@ void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult & if(!hasStackAtSlot(SlotID(0))) cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count); - while (stacks.size() > 1) //hopefully that's enough + while(stacks.size() > 1) //hopefully that's enough { // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere) i = stacks.end(); i--; SlotID slot = getSlotFor(i->second->type); - if (slot == i->first) //no reason to move stack to its own slot + if(slot == i->first) //no reason to move stack to its own slot break; else - cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count); + cb->moveStack(StackLocation(this, i->first), StackLocation(this, slot), i->second->count); } cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties From 40cb48d65edf7197c0542883cd3e96b278958530 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Tue, 26 Jan 2016 09:37:55 +0300 Subject: [PATCH 10/15] Replace std::remove_if with vstd::erase_if --- client/battle/CBattleInterface.cpp | 30 +++++++++++++++--------------- lib/CGameState.cpp | 4 ++-- lib/mapObjects/JsonRandom.cpp | 4 ++-- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/client/battle/CBattleInterface.cpp b/client/battle/CBattleInterface.cpp index 4c2725d9f..83bf8fde7 100644 --- a/client/battle/CBattleInterface.cpp +++ b/client/battle/CBattleInterface.cpp @@ -1017,7 +1017,7 @@ void CBattleInterface::stackRemoved(int stackID) setActiveStack(nullptr); } } - + delete creAnims[stackID]; creAnims.erase(stackID); creDir.erase(stackID); @@ -1201,18 +1201,18 @@ void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca) for(auto attackInfo : ca.attackedParts) { addNewAnim(new CShootingAnimation(this, stack, attackInfo.destinationTile, nullptr, true, attackInfo.damageDealt)); - } + } } else { - //no attacker stack, assume spell-related (earthquake) - only hit animation + //no attacker stack, assume spell-related (earthquake) - only hit animation for(auto attackInfo : ca.attackedParts) { Point destPos = CClickableHex::getXYUnitAnim(attackInfo.destinationTile, nullptr, this) + Point(99, 120); - + addNewAnim(new CSpellEffectAnimation(this, "SGEXPL.DEF", destPos.x, destPos.y)); } - } + } waitForAnims(); @@ -1323,9 +1323,9 @@ void CBattleInterface::spellCast( const BattleSpellCast * sc ) //displaying message in console std::vector logLines; - + spell.prepareBattleLog(curInt->cb.get(), sc, logLines); - + for(auto line : logLines) console->addText(line); @@ -1427,15 +1427,15 @@ void CBattleInterface::displayEffect(ui32 effect, int destTile, bool areaEffect) } void CBattleInterface::displaySpellAnimation(const CSpell::TAnimation & animation, BattleHex destinationTile, bool areaEffect) -{ +{ if(animation.pause > 0) { - addNewAnim(new CDummyAnimation(this, animation.pause)); + addNewAnim(new CDummyAnimation(this, animation.pause)); } else { - addNewAnim(new CSpellEffectAnimation(this, animation.resourceName, destinationTile, false, animation.verticalPosition == VerticalPosition::BOTTOM)); - } + addNewAnim(new CSpellEffectAnimation(this, animation.resourceName, destinationTile, false, animation.verticalPosition == VerticalPosition::BOTTOM)); + } } void CBattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile, bool areaEffect) @@ -1444,11 +1444,11 @@ void CBattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTi if(spell == nullptr) return; - + for(const CSpell::TAnimation & animation : spell->animationInfo.cast) { displaySpellAnimation(animation, destinationTile, areaEffect); - } + } } void CBattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile, bool areaEffect) @@ -1933,7 +1933,7 @@ void CBattleInterface::bTacticNextStack(const CStack *current /*= nullptr*/) waitForAnims(); TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE); - stacksOfMine.erase(std::remove_if(stacksOfMine.begin(), stacksOfMine.end(), &immobile), stacksOfMine.end()); + vstd::erase_if(stacksOfMine, &immobile); auto it = vstd::find(stacksOfMine, current); if(it != stacksOfMine.end() && ++it != stacksOfMine.end()) stackActivated(*it); @@ -2072,7 +2072,7 @@ void CBattleInterface::handleHex(BattleHex myNumber, int eventType) case ANY_CREATURE: if (shere && shere->alive() && isCastingPossibleHere (sactive, shere, myNumber)) legalAction = true; - break; + break; case HOSTILE_CREATURE_SPELL: if (shere && shere->alive() && !ourStack && isCastingPossibleHere (sactive, shere, myNumber)) legalAction = true; diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index 862e5db42..50b1c8afe 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -1219,8 +1219,8 @@ CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenar // remove heroes which didn't reached the end of the scenario, but were available at the start for(auto hero : lostCrossoverHeroes) { - crossoverHeroes.heroesFromAnyPreviousScenarios.erase(range::remove_if(crossoverHeroes.heroesFromAnyPreviousScenarios, - CGObjectInstanceBySubIdFinder(hero)), crossoverHeroes.heroesFromAnyPreviousScenarios.end()); + vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios, + CGObjectInstanceBySubIdFinder(hero)); } // now add heroes which completed the scenario diff --git a/lib/mapObjects/JsonRandom.cpp b/lib/mapObjects/JsonRandom.cpp index a64271c1e..36fdf59a3 100644 --- a/lib/mapObjects/JsonRandom.cpp +++ b/lib/mapObjects/JsonRandom.cpp @@ -133,10 +133,10 @@ namespace JsonRandom if (value["type"].getType() == JsonNode::DATA_STRING) return SpellID(VLC->modh->identifiers.getIdentifier("spell", value["type"]).get()); - spells.erase(std::remove_if(spells.begin(), spells.end(), [=](SpellID spell) + vstd::erase_if(spells, [=](SpellID spell) { return VLC->spellh->objects[spell]->level != si32(value["level"].Float()); - }), spells.end()); + }); return SpellID(*RandomGeneratorUtil::nextItem(spells, rng)); } From 7772b6de741c4f00a9248355fd2508fd3c719e44 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Tue, 26 Jan 2016 22:24:38 +0300 Subject: [PATCH 11/15] Fix 981 reset hero on hiring after retreat/surrender --- lib/NetPacksLib.cpp | 11 +++++- lib/mapObjects/CGHeroInstance.cpp | 61 ++++++++++++++++--------------- lib/mapObjects/CGHeroInstance.h | 22 +++++++---- server/CGameHandler.cpp | 23 ++++++++---- 4 files changed, 70 insertions(+), 47 deletions(-) diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index fd39d78d9..46d515a78 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -594,7 +594,11 @@ DLL_LINKAGE void HeroRecruited::applyGs( CGameState *gs ) h->setOwner(player); h->pos = tile; - h->movement = h->maxMovePoints(true); + bool fresh = !h->isInitialized(); + if(fresh) + { // this is a fresh hero who hasn't appeared yet + h->movement = h->maxMovePoints(true); + } gs->hpool.heroesPool.erase(hid); if(h->id == ObjectInstanceID()) @@ -608,7 +612,10 @@ DLL_LINKAGE void HeroRecruited::applyGs( CGameState *gs ) gs->map->heroesOnMap.push_back(h); p->heroes.push_back(h); h->attachTo(p); - h->initObj(); + if(fresh) + { + h->initObj(); + } gs->map->addBlockVisTiles(h); if(t) diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index 2299c42a0..13a25f9db 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -220,7 +220,9 @@ CGHeroInstance::CGHeroInstance() setNodeType(HERO); ID = Obj::HERO; tacticFormationEnabled = inTownGarrison = false; - mana = movement = portrait = -1; + mana = UNINITIALIZED_MANA; + movement = UNINITIALIZED_MOVEMENT; + portrait = UNINITIALIZED_PORTRAIT; isStanding = true; moveDir = 4; level = 1; @@ -868,18 +870,18 @@ TExpType CGHeroInstance::calculateXp(TExpType exp) const ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const { si16 skill = -1; //skill level - + spell->forEachSchool([&, this](const SpellSchoolInfo & cnf, bool & stop) { int thisSchool = std::max(getSecSkillLevel(cnf.skill), valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << ((ui8)cnf.id))); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies) - if(thisSchool > skill) - { - skill = thisSchool; - if(outSelectedSchool) - *outSelectedSchool = (ui8)cnf.id; - } + if(thisSchool > skill) + { + skill = thisSchool; + if(outSelectedSchool) + *outSelectedSchool = (ui8)cnf.id; + } }); - + vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect @@ -904,7 +906,7 @@ ui32 CGHeroInstance::getSpellBonus(const CSpell * spell, ui32 base, const CStack if (affectedStack && affectedStack->getCreature()->level) //Hero specials like Solmyr, Deemer base *= (100. + ((valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->id.toEnum()) * level) / affectedStack->getCreature()->level)) / 100.0; - return base; + return base; } int CGHeroInstance::getEffectLevel(const CSpell * spell) const @@ -912,7 +914,7 @@ int CGHeroInstance::getEffectLevel(const CSpell * spell) const if(hasBonusOfType(Bonus::MAXED_SPELL, spell->id)) return 3;//todo: recheck specialty from where this bonus is. possible bug else - return getSpellSchoolLevel(spell); + return getSpellSchoolLevel(spell); } int CGHeroInstance::getEffectPower(const CSpell * spell) const @@ -922,7 +924,7 @@ int CGHeroInstance::getEffectPower(const CSpell * spell) const int CGHeroInstance::getEnchantPower(const CSpell * spell) const { - return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION); + return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION); } int CGHeroInstance::getEffectValue(const CSpell * spell) const @@ -1107,8 +1109,8 @@ void CGHeroInstance::getOutOffsets(std::vector &offsets) const { // FIXME: Offsets need to be fixed once we get rid of convertPosition // Check issue 515 for details - offsets = - { + offsets = + { int3(-1,1,0), int3(-1,-1,0), int3(-2,0,0), int3(0,0,0), int3(0,1,0), int3(-2,1,0), int3(0,-1,0), int3(-2,-1,0) }; } @@ -1436,20 +1438,19 @@ void CGHeroInstance::levelUpAutomatically() bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const { //VISIONS spell support - - const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype)); - - const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached); - - int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER); - - if (visionsMultiplier > 0) - vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present - - const int distance = target->pos.dist2d(getPosition(false)); - - //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange)); - - return (distance < visionsRange) && (target->pos.z == pos.z); -} + const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype)); + + const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached); + + int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER); + + if (visionsMultiplier > 0) + vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present + + const int distance = target->pos.dist2d(getPosition(false)); + + //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange)); + + return (distance < visionsRange) && (target->pos.z == pos.z); +} diff --git a/lib/mapObjects/CGHeroInstance.h b/lib/mapObjects/CGHeroInstance.h index a6cc59cb1..0e902035c 100644 --- a/lib/mapObjects/CGHeroInstance.h +++ b/lib/mapObjects/CGHeroInstance.h @@ -64,6 +64,9 @@ public: ConstTransitivePtr commander; const CGBoat *boat; //set to CGBoat when sailing + static constexpr ui32 UNINITIALIZED_PORTRAIT = -1; + static constexpr ui32 UNINITIALIZED_MANA = -1; + static constexpr ui32 UNINITIALIZED_MOVEMENT = -1; //std::vector artifacts; //hero's artifacts from bag //std::map artifWorn; //map; positions: 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5 @@ -124,6 +127,11 @@ public: } } skillsInfo; + inline bool isInitialized() const + { // has this hero been on the map at least once? + return movement == UNINITIALIZED_MOVEMENT && mana == UNINITIALIZED_MANA; + } + //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated int getSightRadious() const override; //sight distance (should be used if player-owned structure) ////////////////////////////////////////////////////////////////////////// @@ -177,7 +185,7 @@ public: double getHeroStrength() const; // includes fighting and magic strength ui64 getTotalStrength() const; // includes fighting strength and army strength TExpType calculateXp(TExpType exp) const; //apply learning skill - + bool canCastThisSpell(const CSpell * spell) const; //determines if this hero can cast given spell; takes into account existing spell in spellbook, existing spellbook and artifact bonuses CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const; void showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const; @@ -201,23 +209,23 @@ public: void Updatespecialty(); void recreateSecondarySkillsBonuses(); void updateSkill(SecondarySkill which, int val); - + bool hasVisions(const CGObjectInstance * target, const int subtype) const; CGHeroInstance(); virtual ~CGHeroInstance(); - + ///ArtBearer ArtBearer::ArtBearer bearerType() const override; ///IBonusBearer CBonusSystemNode *whereShouldBeAttached(CGameState *gs) override; std::string nodeName() const override; - + ///ISpellCaster ui8 getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool = nullptr) const override; ui32 getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const override; - + ///default spell school level for effect calculation int getEffectLevel(const CSpell * spell) const override; @@ -229,9 +237,9 @@ public: ///damage/heal override(ignores spell configuration, effect level and effect power) int getEffectValue(const CSpell * spell) const override; - + const PlayerColor getOwner() const override; - + void deserializationFix(); void initObj() override; diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index df0fe9c86..ba585c7dd 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -3328,23 +3328,27 @@ bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor pl // || (getHeroCount(player, false) >= GameConstants::MAX_HEROES_PER_PLAYER && complain("Cannot hire hero, only 8 wandering heroes are allowed!"))) if((p->resources.at(Res::GOLD) < GameConstants::HERO_GOLD_COST && complain("Not enough gold for buying hero!")) || ((!t) && (getHeroCount(player, false) >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER && complain("Cannot hire hero, too many wandering heroes already!"))) - || ((t) && (getHeroCount(player, true) >= VLC->modh->settings.MAX_HEROES_AVAILABLE_PER_PLAYER && complain("Cannot hire hero, too many heroes garrizoned and wandering already!"))) ) - - return false; + || ((t) && (getHeroCount(player, true) >= VLC->modh->settings.MAX_HEROES_AVAILABLE_PER_PLAYER && complain("Cannot hire hero, too many heroes garrizoned and wandering already!"))) ) + { + return false; + } if(t) //tavern in town { - if( (!t->hasBuilt(BuildingID::TAVERN) && complain("No tavern!")) - || (t->visitingHero && complain("There is visiting hero - no place!"))) + if((!t->hasBuilt(BuildingID::TAVERN) && complain("No tavern!")) + || (t->visitingHero && complain("There is visiting hero - no place!"))) + { return false; + } } else if(obj->ID == Obj::TAVERN) { - if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!")) + if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!")) + { return false; + } } - const CGHeroInstance *nh = p->availableHeroes.at(hid); if (!nh) { @@ -3359,13 +3363,14 @@ bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor pl hr.tile = obj->visitablePos() + nh->getVisitableOffset(); sendAndApply(&hr); - std::map > pool = gs->unusedHeroesFromPool(); const CGHeroInstance *theOtherHero = p->availableHeroes.at(!hid); const CGHeroInstance *newHero = nullptr; if (theOtherHero) //on XXL maps all heroes can be imprisoned :( + { newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, gs->getRandomGenerator(), theOtherHero->type->heroClass); + } SetAvailableHeroes sah; sah.player = player; @@ -3377,7 +3382,9 @@ bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor pl sah.army[hid].setCreature(SlotID(0), newHero->type->initialArmy[0].creature, 1); } else + { sah.hid[hid] = -1; + } sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1; sendAndApply(&sah); From f6679bba509dda46100636569b1fa225417c98a0 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Wed, 27 Jan 2016 09:44:04 +0300 Subject: [PATCH 12/15] Fix CGHeroInstance::isInitialized implementation --- lib/mapObjects/CGHeroInstance.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/mapObjects/CGHeroInstance.h b/lib/mapObjects/CGHeroInstance.h index 0e902035c..41ccbcdda 100644 --- a/lib/mapObjects/CGHeroInstance.h +++ b/lib/mapObjects/CGHeroInstance.h @@ -129,7 +129,7 @@ public: inline bool isInitialized() const { // has this hero been on the map at least once? - return movement == UNINITIALIZED_MOVEMENT && mana == UNINITIALIZED_MANA; + return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA; } //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated From 94ecc3f52035196177c0ec46a4b5f43231bdf283 Mon Sep 17 00:00:00 2001 From: DjWarmonger Date: Wed, 27 Jan 2016 10:13:33 +0100 Subject: [PATCH 13/15] Compilation fix. MVS 2013 doesn't support constexpr and it's not needed either. --- lib/mapObjects/CGHeroInstance.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/mapObjects/CGHeroInstance.h b/lib/mapObjects/CGHeroInstance.h index 41ccbcdda..196c06af3 100644 --- a/lib/mapObjects/CGHeroInstance.h +++ b/lib/mapObjects/CGHeroInstance.h @@ -64,9 +64,9 @@ public: ConstTransitivePtr commander; const CGBoat *boat; //set to CGBoat when sailing - static constexpr ui32 UNINITIALIZED_PORTRAIT = -1; - static constexpr ui32 UNINITIALIZED_MANA = -1; - static constexpr ui32 UNINITIALIZED_MOVEMENT = -1; + static const ui32 UNINITIALIZED_PORTRAIT = -1; + static const ui32 UNINITIALIZED_MANA = -1; + static const ui32 UNINITIALIZED_MOVEMENT = -1; //std::vector artifacts; //hero's artifacts from bag //std::map artifWorn; //map; positions: 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5 From 36eaa399e7fc5c7a0a8c69e35ec6882138f8faf5 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Wed, 27 Jan 2016 11:38:35 +0300 Subject: [PATCH 14/15] Add hardcodedFeature to switch winner's retreating with no troops --- config/defaultMods.json | 3 ++- lib/CModHandler.cpp | 33 +++++++++++++++++++++----- lib/CModHandler.h | 16 ++++++++++--- lib/Connection.h | 2 +- lib/JsonNode.cpp | 13 ++++++++-- lib/JsonNode.h | 19 ++++++++------- lib/filesystem/AdapterLoaders.cpp | 14 +++++++++++ lib/filesystem/AdapterLoaders.h | 14 ++++------- lib/filesystem/ISimpleResourceLoader.h | 16 +++++++++++++ server/CGameHandler.cpp | 23 ++++++++++-------- 10 files changed, 111 insertions(+), 42 deletions(-) diff --git a/config/defaultMods.json b/config/defaultMods.json index 6413b79af..e84c877f8 100644 --- a/config/defaultMods.json +++ b/config/defaultMods.json @@ -23,7 +23,8 @@ "ALL_CREATURES_GET_DOUBLE_MONTHS" : false, "NEGATIVE_LUCK" : false, "MAX_HEROES_AVAILABLE_PER_PLAYER" : 16, - "MAX_HEROES_ON_MAP_PER_PLAYER" : 8 + "MAX_HEROES_ON_MAP_PER_PLAYER" : 8, + "WINNING_HERO_WITH_NO_TROOPS_RETREATS": true }, "modules": diff --git a/lib/CModHandler.cpp b/lib/CModHandler.cpp index 571d5c10b..5d5095c5f 100644 --- a/lib/CModHandler.cpp +++ b/lib/CModHandler.cpp @@ -101,9 +101,9 @@ void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, void CIdentifierStorage::requestIdentifier(std::string scope, std::string fullName, const std::function& callback) { - auto scopeAndFullName = splitString(fullName, ':'); - auto typeAndName = splitString(scopeAndFullName.second, '.'); - + auto scopeAndFullName = splitString(fullName, ':'); + auto typeAndName = splitString(scopeAndFullName.second, '.'); + requestIdentifier(ObjectCallback(scope, scopeAndFullName.first, typeAndName.first, typeAndName.second, callback, false)); } @@ -331,11 +331,11 @@ bool CContentHandler::ContentTypeHandler::loadMod(std::string modName, bool vali { ModInfo & modInfo = modData[modName]; bool result = true; - + auto performValidate = [&,this](JsonNode & data, const std::string & name){ handler->beforeValidate(data); if (validate) - result &= JsonUtils::validate(data, "vcmi:" + objectName, name); + result &= JsonUtils::validate(data, "vcmi:" + objectName, name); }; // apply patches @@ -355,7 +355,7 @@ bool CContentHandler::ContentTypeHandler::loadMod(std::string modName, bool vali if (originalData.size() > index) { JsonUtils::merge(originalData[index], data); - + performValidate(originalData[index],name); handler->loadObject(modName, name, originalData[index], index); @@ -550,21 +550,42 @@ CModHandler::CModHandler() void CModHandler::loadConfigFromFile (std::string name) { + std::string paths; + for(auto& p : CResourceHandler::get()->getResourceNames(ResourceID("config/" + name))) + { + paths += p + ", "; + } + paths = paths.substr(0, paths.size() - 2); + logGlobal->debugStream() << "Loading hardcoded features settings from [" << paths << "], result:"; settings.data = JsonUtils::assembleFromFiles("config/" + name); const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"]; settings.MAX_HEROES_AVAILABLE_PER_PLAYER = hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Float(); + logGlobal->debugStream() << "\tMAX_HEROES_AVAILABLE_PER_PLAYER\t" << settings.MAX_HEROES_AVAILABLE_PER_PLAYER; settings.MAX_HEROES_ON_MAP_PER_PLAYER = hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Float(); + logGlobal->debugStream() << "\tMAX_HEROES_ON_MAP_PER_PLAYER\t" << settings.MAX_HEROES_ON_MAP_PER_PLAYER; settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float(); + logGlobal->debugStream() << "\tCREEP_SIZE\t" << settings.CREEP_SIZE; settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float(); + logGlobal->debugStream() << "\tWEEKLY_GROWTH\t" << settings.WEEKLY_GROWTH; settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float(); + logGlobal->debugStream() << "\tNEUTRAL_STACK_EXP\t" << settings.NEUTRAL_STACK_EXP; settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float(); + logGlobal->debugStream() << "\tMAX_BUILDING_PER_TURN\t" << settings.MAX_BUILDING_PER_TURN; settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool(); + logGlobal->debugStream() << "\tDWELLINGS_ACCUMULATE_CREATURES\t" << settings.DWELLINGS_ACCUMULATE_CREATURES; settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool(); + logGlobal->debugStream() << "\tALL_CREATURES_GET_DOUBLE_MONTHS\t" << settings.ALL_CREATURES_GET_DOUBLE_MONTHS; + settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS = hardcodedFeatures["WINNING_HERO_WITH_NO_TROOPS_RETREATS"].Bool(); + logGlobal->debugStream() << "\tWINNING_HERO_WITH_NO_TROOPS_RETREATS\t" << settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS; const JsonNode & gameModules = settings.data["modules"]; modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool(); + logGlobal->debugStream() << "\tSTACK_EXP\t" << modules.STACK_EXP; modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool(); + logGlobal->debugStream() << "\tSTACK_ARTIFACT\t" << modules.STACK_ARTIFACT; modules.COMMANDERS = gameModules["COMMANDERS"].Bool(); + logGlobal->debugStream() << "\tCOMMANDERS\t" << modules.COMMANDERS; modules.MITHRIL = gameModules["MITHRIL"].Bool(); + logGlobal->debugStream() << "\tMITHRIL\t" << modules.MITHRIL; } // currentList is passed by value to get current list of depending mods diff --git a/lib/CModHandler.h b/lib/CModHandler.h index 7d4f00fe5..b74918ca7 100644 --- a/lib/CModHandler.h +++ b/lib/CModHandler.h @@ -73,7 +73,7 @@ public: /// Function callback will be called during ID resolution phase of loading void requestIdentifier(std::string scope, std::string type, std::string name, const std::function & callback); ///fullName = [remoteScope:]type.name - void requestIdentifier(std::string scope, std::string fullName, const std::function & callback); + void requestIdentifier(std::string scope, std::string fullName, const std::function & callback); void requestIdentifier(std::string type, const JsonNode & name, const std::function & callback); void requestIdentifier(const JsonNode & name, const std::function & callback); @@ -253,17 +253,27 @@ public: int CREEP_SIZE; // neutral stacks won't grow beyond this number int WEEKLY_GROWTH; //percent - int NEUTRAL_STACK_EXP; + int NEUTRAL_STACK_EXP; int MAX_BUILDING_PER_TURN; bool DWELLINGS_ACCUMULATE_CREATURES; bool ALL_CREATURES_GET_DOUBLE_MONTHS; int MAX_HEROES_AVAILABLE_PER_PLAYER; int MAX_HEROES_ON_MAP_PER_PLAYER; + bool WINNING_HERO_WITH_NO_TROOPS_RETREATS; template void serialize(Handler &h, const int version) { h & data & CREEP_SIZE & WEEKLY_GROWTH & NEUTRAL_STACK_EXP & MAX_BUILDING_PER_TURN; - h & DWELLINGS_ACCUMULATE_CREATURES & ALL_CREATURES_GET_DOUBLE_MONTHS & MAX_HEROES_AVAILABLE_PER_PLAYER & MAX_HEROES_ON_MAP_PER_PLAYER; + h & DWELLINGS_ACCUMULATE_CREATURES & ALL_CREATURES_GET_DOUBLE_MONTHS & + MAX_HEROES_AVAILABLE_PER_PLAYER & MAX_HEROES_ON_MAP_PER_PLAYER; + if(version >= 756) + { + h & WINNING_HERO_WITH_NO_TROOPS_RETREATS; + } + else if(!h.saving) + { + WINNING_HERO_WITH_NO_TROOPS_RETREATS = true; + } } } settings; diff --git a/lib/Connection.h b/lib/Connection.h index 259b9f23f..00a16afac 100644 --- a/lib/Connection.h +++ b/lib/Connection.h @@ -27,7 +27,7 @@ #include "mapping/CCampaignHandler.h" //for CCampaignState #include "rmg/CMapGenerator.h" // for CMapGenOptions -const ui32 version = 755; +const ui32 version = 756; const ui32 minSupportedVersion = 753; class CISer; diff --git a/lib/JsonNode.cpp b/lib/JsonNode.cpp index c9ea181b2..8128efcbc 100644 --- a/lib/JsonNode.cpp +++ b/lib/JsonNode.cpp @@ -56,6 +56,15 @@ JsonNode::JsonNode(ResourceID && fileURI): *this = parser.parse(fileURI.getName()); } +JsonNode::JsonNode(const ResourceID & fileURI): + type(DATA_NULL) +{ + auto file = CResourceHandler::get()->load(fileURI)->readAll(); + + JsonParser parser(reinterpret_cast(file.first.get()), file.second); + *this = parser.parse(fileURI.getName()); +} + JsonNode::JsonNode(ResourceID && fileURI, bool &isValidSyntax): type(DATA_NULL) { @@ -328,7 +337,7 @@ void JsonUtils::parseTypedBonusShort(const JsonVector& source, Bonus *dest) resolveIdentifier(source[2],dest->subtype); dest->additionalInfo = source[3].Float(); dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer) - dest->turnsRemain = 0; + dest->turnsRemain = 0; } @@ -343,7 +352,7 @@ Bonus * JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with return b; } b->type = it->second; - + parseTypedBonusShort(ability_vec, b); return b; } diff --git a/lib/JsonNode.h b/lib/JsonNode.h index dfe9aba0b..b926a4d6d 100644 --- a/lib/JsonNode.h +++ b/lib/JsonNode.h @@ -7,7 +7,7 @@ * Full text of license available in license.txt file, in main folder * */ - + #pragma once class JsonNode; @@ -55,6 +55,7 @@ public: explicit JsonNode(const char * data, size_t datasize); //Create tree from JSON file explicit JsonNode(ResourceID && fileURI); + explicit JsonNode(const ResourceID & fileURI); explicit JsonNode(ResourceID && fileURI, bool & isValidSyntax); //Copy c-tor JsonNode(const JsonNode ©); @@ -125,9 +126,9 @@ namespace JsonUtils /** * @brief parse short bonus format, excluding type * @note sets duration to Permament - */ + */ DLL_LINKAGE void parseTypedBonusShort(const JsonVector &source, Bonus *dest); - + /// DLL_LINKAGE Bonus * parseBonus (const JsonVector &ability_vec); DLL_LINKAGE Bonus * parseBonus (const JsonNode &bonus); @@ -144,7 +145,7 @@ namespace JsonUtils * @note this function will destroy data in source */ DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source); - + /** * @brief recursively merges source into dest, replacing identical fields * struct : recursively calls this function @@ -152,12 +153,12 @@ namespace JsonUtils * values : value in source will replace value in dest * null : if value in source is present but set to null it will delete entry in dest * @note this function will preserve data stored in source by creating copy - */ + */ DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source); - + /** @brief recursively merges descendant into copy of base node * Result emulates inheritance semantic - * + * * */ DLL_LINKAGE void inherit(JsonNode & descendant, const JsonNode & base); @@ -200,7 +201,7 @@ namespace JsonDetail { // conversion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++) - template + template struct JsonConvImpl; template @@ -229,7 +230,7 @@ namespace JsonDetail ///this should be triggered only for numeric types and enums static_assert(boost::mpl::or_, std::is_enum, boost::is_class >::value, "Unsupported type for JsonNode::convertTo()!"); return JsonConvImpl, boost::is_class >::value >::convertImpl(node); - + } }; diff --git a/lib/filesystem/AdapterLoaders.cpp b/lib/filesystem/AdapterLoaders.cpp index cb2ceaf23..8c20743e5 100644 --- a/lib/filesystem/AdapterLoaders.cpp +++ b/lib/filesystem/AdapterLoaders.cpp @@ -87,6 +87,20 @@ boost::optional CFilesystemList::getResourceName(const ResourceID & return boost::optional(); } +std::set CFilesystemList::getResourceNames(const ResourceID & resourceName) const +{ + std::set paths; + for(auto& loader : getResourcesWithName(resourceName)) + { + auto rn = loader->getResourceName(resourceName); + if(rn) + { + paths.insert(*rn); + } + } + return std::move(paths); +} + std::unordered_set CFilesystemList::getFilteredFiles(std::function filter) const { std::unordered_set ret; diff --git a/lib/filesystem/AdapterLoaders.h b/lib/filesystem/AdapterLoaders.h index cabe5760e..2abe5fcb9 100644 --- a/lib/filesystem/AdapterLoaders.h +++ b/lib/filesystem/AdapterLoaders.h @@ -59,16 +59,9 @@ class DLL_LINKAGE CFilesystemList : public ISimpleResourceLoader std::set writeableLoaders; //FIXME: this is only compile fix, should be removed in the end - CFilesystemList(CFilesystemList &) - { - //class is not copyable - } - CFilesystemList &operator=(CFilesystemList &) - { - //class is not copyable - return *this; - } - + CFilesystemList(CFilesystemList &) = delete; + CFilesystemList &operator=(CFilesystemList &) = delete; + public: CFilesystemList(); ~CFilesystemList(); @@ -78,6 +71,7 @@ public: bool existsResource(const ResourceID & resourceName) const override; std::string getMountPoint() const override; boost::optional getResourceName(const ResourceID & resourceName) const override; + std::set getResourceNames(const ResourceID & resourceName) const override; std::unordered_set getFilteredFiles(std::function filter) const override; bool createResource(std::string filename, bool update = false) override; std::vector getResourcesWithName(const ResourceID & resourceName) const override; diff --git a/lib/filesystem/ISimpleResourceLoader.h b/lib/filesystem/ISimpleResourceLoader.h index f04762210..f3d0be633 100644 --- a/lib/filesystem/ISimpleResourceLoader.h +++ b/lib/filesystem/ISimpleResourceLoader.h @@ -53,6 +53,22 @@ public: return boost::optional(); } + /** + * Gets all full names of matching resources, e.g. names of files in filesystem. + * + * @return std::set with names. + */ + virtual std::set getResourceNames(const ResourceID & resourceName) const + { + std::set result; + auto rn = getResourceName(resourceName); + if(rn) + { + result.insert(*rn); + } + return result; + } + /** * Get list of files that matches filter function * diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index e2e56e113..368201a81 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -757,18 +757,21 @@ void CGameHandler::battleAfterLevelUp( const BattleResult &result ) RemoveObject ro(finishingBattle->winnerHero->id); sendAndApply(&ro); - SetAvailableHeroes sah; - sah.player = finishingBattle->victor; - sah.hid[0] = finishingBattle->winnerHero->subID; - sah.army[0].clear(); - sah.army[0].setCreature(SlotID(0), finishingBattle->winnerHero->type->initialArmy.at(0).creature, 1); + if (VLC->modh->settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS) + { + SetAvailableHeroes sah; + sah.player = finishingBattle->victor; + sah.hid[0] = finishingBattle->winnerHero->subID; + sah.army[0].clear(); + sah.army[0].setCreature(SlotID(0), finishingBattle->winnerHero->type->initialArmy.at(0).creature, 1); - if(const CGHeroInstance *another = getPlayer(finishingBattle->victor)->availableHeroes.at(0)) - sah.hid[1] = another->subID; - else - sah.hid[1] = -1; + if(const CGHeroInstance *another = getPlayer(finishingBattle->victor)->availableHeroes.at(0)) + sah.hid[1] = another->subID; + else + sah.hid[1] = -1; - sendAndApply(&sah); + sendAndApply(&sah); + } } } From 9f3313524e11dcd486b2b53e22fc22817af9f8e5 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Wed, 27 Jan 2016 13:47:42 +0300 Subject: [PATCH 15/15] Fix 2160 dismissing a VIP hero --- client/windows/CHeroWindow.cpp | 12 +++-- lib/CGameInfoCallback.cpp | 73 ++++++++++++++++--------------- lib/CGameState.cpp | 4 +- lib/mapObjects/CGHeroInstance.cpp | 25 +++++++++++ lib/mapObjects/CGHeroInstance.h | 3 ++ 5 files changed, 76 insertions(+), 41 deletions(-) diff --git a/client/windows/CHeroWindow.cpp b/client/windows/CHeroWindow.cpp index 06ca90d6e..7246e1ff8 100644 --- a/client/windows/CHeroWindow.cpp +++ b/client/windows/CHeroWindow.cpp @@ -28,6 +28,7 @@ #include "../lib/CHeroHandler.h" #include "../lib/mapObjects/CGHeroInstance.h" #include "../lib/NetPacksBase.h" +#include "../mapHandler.h" /* * CHeroWindow.cpp, part of VCMI engine @@ -275,6 +276,9 @@ void CHeroWindow::update(const CGHeroInstance * hero, bool redrawNeeded /*= fals if(!LOCPLINT->cb->howManyTowns() && LOCPLINT->cb->howManyHeroes() == 1) noDismiss = true; + if(curHero->isMissionCritical()) + noDismiss = true; + dismissButton->block(!!curHero->visitedTown || noDismiss); if(curHero->getSecSkillLevel(SecondarySkill::TACTICS) == 0) @@ -343,10 +347,10 @@ void CHeroWindow::commanderWindow() void CHeroWindow::showAll(SDL_Surface * to) { CIntObject::showAll(to); - + //printing hero's name printAtMiddleLoc(curHero->name, 190, 38, FONT_BIG, Colors::YELLOW, to); - + //printing hero's level std::string secondLine= CGI->generaltexth->allTexts[342]; boost::algorithm::replace_first(secondLine,"%d",boost::lexical_cast(curHero->level)); @@ -360,14 +364,14 @@ void CHeroWindow::showAll(SDL_Surface * to) primarySkill << primSkillAreas[m]->bonusValue; printAtMiddleLoc(primarySkill.str(), 53 + 70 * m, 166, FONT_SMALL, Colors::WHITE, to); } - + //secondary skills for(size_t v=0; vsecSkills.size()); ++v) { printAtLoc(CGI->generaltexth->levels[curHero->secSkills[v].second-1], (v%2) ? 212 : 68, 280 + 48 * (v/2), FONT_SMALL, Colors::WHITE, to); printAtLoc(CGI->generaltexth->skillName[curHero->secSkills[v].first], (v%2) ? 212 : 68, 300 + 48 * (v/2), FONT_SMALL, Colors::WHITE, to); } - + //printing special ability printAtLoc(curHero->type->specName, 69, 205, FONT_SMALL, Colors::WHITE, to); std::ostringstream expstr; diff --git a/lib/CGameInfoCallback.cpp b/lib/CGameInfoCallback.cpp index 9abf44444..08af6db42 100644 --- a/lib/CGameInfoCallback.cpp +++ b/lib/CGameInfoCallback.cpp @@ -66,6 +66,10 @@ const PlayerState * CGameInfoCallback::getPlayer(PlayerColor color, bool verbose { //funtion written from scratch since it's accessed A LOT by AI + if(!color.isValidPlayer()) + { + return nullptr; + } auto player = gs->players.find(color); if (player != gs->players.end()) { @@ -229,13 +233,13 @@ bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown { if(!detailed && nullptr != selectedObject) { - const CGHeroInstance * selectedHero = dynamic_cast(selectedObject); + const CGHeroInstance * selectedHero = dynamic_cast(selectedObject); if(nullptr != selectedHero) - detailed = selectedHero->hasVisions(town, 1); + detailed = selectedHero->hasVisions(town, 1); } - + dest.initFromTown(static_cast(town), detailed); - } + } else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2) dest.initFromArmy(static_cast(town), detailed); else @@ -268,28 +272,28 @@ bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero ERROR_RET_VAL_IF(!isVisible(h->getPosition(false)), "That hero is not visible!", false); bool accessFlag = hasAccess(h->tempOwner); - + if(!accessFlag && nullptr != selectedObject) { - const CGHeroInstance * selectedHero = dynamic_cast(selectedObject); + const CGHeroInstance * selectedHero = dynamic_cast(selectedObject); if(nullptr != selectedHero) - accessFlag = selectedHero->hasVisions(hero, 1); + accessFlag = selectedHero->hasVisions(hero, 1); } - + dest.initFromHero(h, accessFlag); - + //DISGUISED bonus implementation - + if(getPlayerRelations(getLocalPlayer(), hero->tempOwner) == PlayerRelations::ENEMIES) { - //todo: bonus cashing + //todo: bonus cashing int disguiseLevel = h->valOfBonuses(Selector::typeSubtype(Bonus::DISGUISED, 0)); - - auto doBasicDisguise = [disguiseLevel](InfoAboutHero & info) + + auto doBasicDisguise = [disguiseLevel](InfoAboutHero & info) { int maxAIValue = 0; const CCreature * mostStrong = nullptr; - + for(auto & elem : info.army) { if(elem.second.type->AIValue > maxAIValue) @@ -298,7 +302,7 @@ bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero mostStrong = elem.second.type; } } - + if(nullptr == mostStrong)//just in case logGlobal->errorStream() << "CGameInfoCallback::getHeroInfo: Unable to select most strong stack" << disguiseLevel; else @@ -307,25 +311,25 @@ bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero elem.second.type = mostStrong; } }; - - auto doAdvancedDisguise = [accessFlag, &doBasicDisguise](InfoAboutHero & info) + + auto doAdvancedDisguise = [accessFlag, &doBasicDisguise](InfoAboutHero & info) { doBasicDisguise(info); - + for(auto & elem : info.army) elem.second.count = 0; }; - - auto doExpertDisguise = [this,h](InfoAboutHero & info) + + auto doExpertDisguise = [this,h](InfoAboutHero & info) { for(auto & elem : info.army) elem.second.count = 0; - + const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle; - + int maxAIValue = 0; const CCreature * mostStrong = nullptr; - + for(auto creature : VLC->creh->creatures) { if(creature->faction == factionIndex && creature->AIValue > maxAIValue) @@ -334,35 +338,35 @@ bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero mostStrong = creature; } } - + if(nullptr != mostStrong) //possible, faction may have no creatures at all for(auto & elem : info.army) elem.second.type = mostStrong; - }; - - + }; + + switch (disguiseLevel) { case 0: //no bonus at all - do nothing - break; + break; case 1: doBasicDisguise(dest); - break; + break; case 2: doAdvancedDisguise(dest); - break; + break; case 3: doExpertDisguise(dest); - break; + break; default: //invalid value logGlobal->errorStream() << "CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value " << disguiseLevel; break; } - + } - + return true; } @@ -486,7 +490,7 @@ std::shared_ptr> CGameInfoCallback::getAllVi boost::multi_array tileArray(boost::extents[width][height][levels]); - + for (size_t x = 0; x < width; x++) for (size_t y = 0; y < height; y++) for (size_t z = 0; z < levels; z++) @@ -964,4 +968,3 @@ void IGameEventRealizer::setObjProperty(ObjectInstanceID objid, int prop, si64 v sob.val = static_cast(val); commitPackage(&sob); } - diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index 50b1c8afe..cc3ded16b 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -2268,7 +2268,7 @@ EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) c for (const TriggeredEvent & event : map->triggeredEvents) { - if ((event.trigger.test(evaluateEvent))) + if (event.trigger.test(evaluateEvent)) { if (event.effect.type == EventEffect::VICTORY) return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage); @@ -2285,7 +2285,7 @@ EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) c return EVictoryLossCheckResult(); } -bool CGameState::checkForVictory( PlayerColor player, const EventCondition & condition ) const +bool CGameState::checkForVictory(PlayerColor player, const EventCondition & condition) const { const PlayerState *p = CGameInfoCallback::getPlayer(player); switch (condition.condition) diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index 13a25f9db..c03e3419d 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -23,6 +23,7 @@ #include "../CCreatureHandler.h" #include "../BattleState.h" #include "../CTownHandler.h" +#include "../mapping/CMap.h" #include "CGTownInstance.h" ///helpers @@ -1454,3 +1455,27 @@ bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subty return (distance < visionsRange) && (target->pos.z == pos.z); } + +bool CGHeroInstance::isMissionCritical() const +{ + for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents) + { + if(event.trigger.test([&](const EventCondition & condition) + { + if (condition.condition == EventCondition::CONTROL && condition.object) + { + auto hero = dynamic_cast(condition.object); + return (hero != this); + } + else if(condition.condition == EventCondition::IS_HUMAN) + { + return true; + } + return false; + })) + { + return true; + } + } + return false; +} diff --git a/lib/mapObjects/CGHeroInstance.h b/lib/mapObjects/CGHeroInstance.h index 41ccbcdda..90177cfe3 100644 --- a/lib/mapObjects/CGHeroInstance.h +++ b/lib/mapObjects/CGHeroInstance.h @@ -20,6 +20,7 @@ class CHero; class CGBoat; class CGTownInstance; +class CMap; struct TerrainTile; struct TurnInfo; @@ -211,6 +212,8 @@ public: void updateSkill(SecondarySkill which, int val); bool hasVisions(const CGObjectInstance * target, const int subtype) const; + /// If this hero perishes, the scenario is failed + bool isMissionCritical() const; CGHeroInstance(); virtual ~CGHeroInstance();