BattleResultProcessor.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /*
  2. * BattleResultProcessor.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleResultProcessor.h"
  12. #include "../CGameHandler.h"
  13. #include "../TurnTimerHandler.h"
  14. #include "../processors/HeroPoolProcessor.h"
  15. #include "../queries/QueriesProcessor.h"
  16. #include "../queries/BattleQueries.h"
  17. #include "../../lib/ArtifactUtils.h"
  18. #include "../../lib/CStack.h"
  19. #include "../../lib/CPlayerState.h"
  20. #include "../../lib/IGameSettings.h"
  21. #include "../../lib/battle/CBattleInfoCallback.h"
  22. #include "../../lib/battle/IBattleState.h"
  23. #include "../../lib/battle/SideInBattle.h"
  24. #include "../../lib/gameState/CGameState.h"
  25. #include "../../lib/mapObjects/CGTownInstance.h"
  26. #include "../../lib/networkPacks/PacksForClientBattle.h"
  27. #include "../../lib/networkPacks/PacksForClient.h"
  28. #include "../../lib/spells/CSpellHandler.h"
  29. #include <vstd/RNG.h>
  30. #include <boost/lexical_cast.hpp>
  31. BattleResultProcessor::BattleResultProcessor(BattleProcessor * owner, CGameHandler * newGameHandler)
  32. // : owner(owner)
  33. : gameHandler(newGameHandler)
  34. {
  35. }
  36. CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle, BattleSide sideInBattle):
  37. army(battle.battleGetArmyObject(sideInBattle))
  38. {
  39. heroWithDeadCommander = ObjectInstanceID();
  40. PlayerColor color = battle.sideToPlayer(sideInBattle);
  41. auto allStacks = battle.battleGetStacksIf([color](const CStack * stack){
  42. if (stack->summoned)//don't take into account temporary summoned stacks
  43. return false;
  44. if(stack->unitOwner() != color) //remove only our stacks
  45. return false;
  46. if (stack->isTurret())
  47. return false;
  48. return true;
  49. });
  50. for(const CStack * stConst : allStacks)
  51. {
  52. // Use const cast - in order to call non-const "takeResurrected" for proper calculation of casualties
  53. // TODO: better solution
  54. CStack * st = const_cast<CStack*>(stConst);
  55. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  56. st->health.takeResurrected();
  57. if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  58. {
  59. auto warMachine = st->unitType()->warMachine;
  60. if(warMachine == ArtifactID::NONE)
  61. {
  62. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  63. }
  64. //catapult artifact remain even if "creature" killed in siege
  65. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  66. {
  67. logGlobal->debug("War machine has been destroyed");
  68. auto hero = dynamic_cast<const CGHeroInstance*> (army);
  69. if (hero)
  70. removedWarMachines.push_back (ArtifactLocation(hero->id, hero->getArtPos(warMachine, true)));
  71. else
  72. logGlobal->error("War machine in army without hero");
  73. }
  74. }
  75. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  76. {
  77. if(st->alive() && st->getCount() > 0)
  78. {
  79. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  80. const CreatureID summonedType = st->creatureId();
  81. summoned[summonedType] += st->getCount();
  82. }
  83. }
  84. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  85. {
  86. if (nullptr == st->base)
  87. {
  88. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  89. }
  90. else
  91. {
  92. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  93. if(c)
  94. {
  95. auto h = dynamic_cast <const CGHeroInstance *>(army);
  96. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  97. {
  98. logGlobal->debug("Commander is dead.");
  99. heroWithDeadCommander = army->id; //TODO: unify commander handling
  100. }
  101. }
  102. else
  103. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  104. }
  105. }
  106. else if(st->base && !army->slotEmpty(st->unitSlot()))
  107. {
  108. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  109. if(st->getCount() == 0 || !st->alive())
  110. {
  111. logGlobal->debug("Stack has been destroyed.");
  112. StackLocation sl(army->id, st->unitSlot());
  113. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  114. }
  115. else if(st->getCount() != army->getStackCount(st->unitSlot()))
  116. {
  117. logGlobal->debug("Stack size changed: %d -> %d units.", army->getStackCount(st->unitSlot()), st->getCount());
  118. StackLocation sl(army->id, st->unitSlot());
  119. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  120. }
  121. }
  122. else
  123. {
  124. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  125. }
  126. }
  127. }
  128. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  129. {
  130. if (gh->getObjInstance(army->id) == nullptr)
  131. throw std::runtime_error("Object " + army->getObjectName() + " is not on the map!");
  132. for (TStackAndItsNewCount &ncount : newStackCounts)
  133. {
  134. if (ncount.second > 0)
  135. gh->changeStackCount(ncount.first, ncount.second, true);
  136. else
  137. gh->eraseStack(ncount.first, true);
  138. }
  139. for (auto summoned_iter : summoned)
  140. {
  141. SlotID slot = army->getSlotFor(summoned_iter.first);
  142. if (slot.validSlot())
  143. {
  144. StackLocation location(army->id, slot);
  145. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  146. }
  147. else
  148. {
  149. //even if it will be possible to summon anything permanently it should be checked for free slot
  150. //necromancy is handled separately
  151. gh->complain("No free slot to put summoned creature");
  152. }
  153. }
  154. for (auto al : removedWarMachines)
  155. {
  156. gh->removeArtifact(al);
  157. }
  158. if (heroWithDeadCommander != ObjectInstanceID())
  159. {
  160. SetCommanderProperty scp;
  161. scp.heroid = heroWithDeadCommander;
  162. scp.which = SetCommanderProperty::ALIVE;
  163. scp.amount = 0;
  164. gh->sendAndApply(scp);
  165. }
  166. }
  167. FinishingBattleHelper::FinishingBattleHelper(const CBattleInfoCallback & info, const BattleResult & result, int remainingBattleQueriesCount)
  168. {
  169. if (result.winner == BattleSide::ATTACKER)
  170. {
  171. winnerId = info.getBattle()->getSideArmy(BattleSide::ATTACKER)->id;
  172. loserId = info.getBattle()->getSideArmy(BattleSide::DEFENDER)->id;
  173. victor = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  174. loser = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  175. }
  176. else
  177. {
  178. winnerId = info.getBattle()->getSideArmy(BattleSide::DEFENDER)->id;
  179. loserId = info.getBattle()->getSideArmy(BattleSide::ATTACKER)->id;
  180. victor = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  181. loser = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  182. }
  183. winnerSide = result.winner;
  184. this->remainingBattleQueriesCount = remainingBattleQueriesCount;
  185. }
  186. void BattleResultProcessor::endBattle(const CBattleInfoCallback & battle)
  187. {
  188. auto const & giveExp = [&battle](BattleResult &r)
  189. {
  190. if (r.winner == BattleSide::NONE)
  191. {
  192. // draw
  193. return;
  194. }
  195. r.exp[BattleSide::ATTACKER] = 0;
  196. r.exp[BattleSide::DEFENDER] = 0;
  197. for (auto i = r.casualties[battle.otherSide(r.winner)].begin(); i!=r.casualties[battle.otherSide(r.winner)].end(); i++)
  198. {
  199. r.exp[r.winner] += LIBRARY->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  200. }
  201. };
  202. LOG_TRACE(logGlobal);
  203. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  204. const auto * heroAttacker = battle.battleGetFightingHero(BattleSide::ATTACKER);
  205. const auto * heroDefender = battle.battleGetFightingHero(BattleSide::DEFENDER);
  206. //Fill BattleResult structure with exp info
  207. giveExp(*battleResult);
  208. if (battleResult->result == EBattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  209. {
  210. if(heroAttacker)
  211. battleResult->exp[BattleSide::DEFENDER] += 500;
  212. if(heroDefender)
  213. battleResult->exp[BattleSide::ATTACKER] += 500;
  214. }
  215. // Give 500 exp to winner if a town was conquered during the battle
  216. const auto * defendedTown = battle.battleGetDefendedTown();
  217. if (defendedTown && battleResult->winner == BattleSide::ATTACKER)
  218. battleResult->exp[BattleSide::ATTACKER] += 500;
  219. if(heroAttacker)
  220. battleResult->exp[BattleSide::ATTACKER] = heroAttacker->calculateXp(battleResult->exp[BattleSide::ATTACKER]);//scholar skill
  221. if(heroDefender)
  222. battleResult->exp[BattleSide::DEFENDER] = heroDefender->calculateXp(battleResult->exp[BattleSide::DEFENDER]);
  223. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::ATTACKER)));
  224. if(!battleQuery)
  225. battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::DEFENDER)));
  226. if (!battleQuery)
  227. {
  228. logGlobal->error("Cannot find battle query!");
  229. gameHandler->complain("Player " + boost::lexical_cast<std::string>(battle.sideToPlayer(BattleSide::ATTACKER)) + " has no battle query at the top!");
  230. return;
  231. }
  232. battleQuery->result = std::make_optional(*battleResult);
  233. //Check how many battle gameHandler->queries were created (number of players blocked by battle)
  234. const int queriedPlayers = battleQuery ? (int)boost::count(gameHandler->queries->allQueries(), battleQuery) : 0;
  235. assert(finishingBattles.count(battle.getBattle()->getBattleID()) == 0);
  236. finishingBattles[battle.getBattle()->getBattleID()] = std::make_unique<FinishingBattleHelper>(battle, *battleResult, queriedPlayers);
  237. // in battles against neutrals, 1st player can ask to replay battle manually
  238. const auto * attackerPlayer = gameHandler->getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::ATTACKER));
  239. const auto * defenderPlayer = gameHandler->getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::DEFENDER));
  240. bool isAttackerHuman = attackerPlayer && attackerPlayer->isHuman();
  241. bool isDefenderHuman = defenderPlayer && defenderPlayer->isHuman();
  242. bool onlyOnePlayerHuman = isAttackerHuman != isDefenderHuman;
  243. // in battles against neutrals attacker can ask to replay battle manually, additionally in battles against AI player human side can also ask for replay
  244. if(onlyOnePlayerHuman)
  245. {
  246. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(gameHandler, battle.getBattle(), battleQuery->result);
  247. battleResult->queryID = battleDialogQuery->queryID;
  248. gameHandler->queries->addQuery(battleDialogQuery);
  249. }
  250. else
  251. battleResult->queryID = QueryID::NONE;
  252. //set same battle result for all gameHandler->queries
  253. for(auto q : gameHandler->queries->allQueries())
  254. {
  255. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  256. if(otherBattleQuery && otherBattleQuery->battleID == battle.getBattle()->getBattleID())
  257. otherBattleQuery->result = battleQuery->result;
  258. }
  259. gameHandler->turnTimerHandler->onBattleEnd(battle.getBattle()->getBattleID());
  260. gameHandler->sendAndApply(*battleResult);
  261. if (battleResult->queryID == QueryID::NONE)
  262. endBattleConfirm(battle);
  263. }
  264. void BattleResultProcessor::endBattleConfirm(const CBattleInfoCallback & battle)
  265. {
  266. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  267. auto * finishingBattle = finishingBattles.at(battle.getBattle()->getBattleID()).get();
  268. //calculate casualties before deleting battle
  269. CasualtiesAfterBattle cab1(battle, BattleSide::ATTACKER);
  270. CasualtiesAfterBattle cab2(battle, BattleSide::DEFENDER);
  271. cab1.updateArmy(gameHandler);
  272. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  273. const auto winnerHero = gameHandler->getHero(finishingBattle->winnerId);
  274. const auto loserHero = gameHandler->getHero(finishingBattle->loserId);
  275. if(battleResult->winner == BattleSide::DEFENDER
  276. && winnerHero
  277. && winnerHero->visitedTown
  278. && !winnerHero->inTownGarrison
  279. && winnerHero->visitedTown->garrisonHero == winnerHero)
  280. {
  281. gameHandler->swapGarrisonOnSiege(winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  282. }
  283. //give exp
  284. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide] && winnerHero)
  285. gameHandler->giveExperience(winnerHero, battleResult->exp[finishingBattle->winnerSide]);
  286. // Eagle Eye handling
  287. if(!finishingBattle->isDraw() && winnerHero)
  288. {
  289. ChangeSpells spells;
  290. if(auto eagleEyeLevel = winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT))
  291. {
  292. auto eagleEyeChance = winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE);
  293. for(auto & spellId : battle.getBattle()->getUsedSpells(battle.otherSide(battleResult->winner)))
  294. {
  295. auto spell = spellId.toEntity(LIBRARY->spells());
  296. if(spell
  297. && spell->getLevel() <= eagleEyeLevel
  298. && !winnerHero->spellbookContainsSpell(spell->getId())
  299. && gameHandler->getRandomGenerator().nextInt(99) < eagleEyeChance)
  300. {
  301. spells.spells.insert(spell->getId());
  302. }
  303. }
  304. }
  305. if(!spells.spells.empty())
  306. {
  307. spells.learn = 1;
  308. spells.hid = finishingBattle->winnerId;
  309. InfoWindow iw;
  310. iw.player = winnerHero->tempOwner;
  311. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  312. iw.text.replaceRawString(winnerHero->getNameTranslated());
  313. std::ostringstream names;
  314. for(int i = 0; i < spells.spells.size(); i++)
  315. {
  316. names << "%s";
  317. if(i < spells.spells.size() - 2)
  318. names << ", ";
  319. else if(i < spells.spells.size() - 1)
  320. names << "%s";
  321. }
  322. names << ".";
  323. iw.text.replaceRawString(names.str());
  324. auto it = spells.spells.begin();
  325. for(int i = 0; i < spells.spells.size(); i++, it++)
  326. {
  327. iw.text.replaceName(*it);
  328. if(i == spells.spells.size() - 2) //we just added pre-last name
  329. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  330. iw.components.emplace_back(ComponentType::SPELL, *it);
  331. }
  332. gameHandler->sendAndApply(iw);
  333. gameHandler->sendAndApply(spells);
  334. }
  335. }
  336. // Artifacts handling
  337. if(battleResult->result == EBattleResult::NORMAL && !finishingBattle->isDraw() && winnerHero)
  338. {
  339. CArtifactFittingSet artFittingSet(*winnerHero);
  340. const auto addArtifactToTransfer = [&artFittingSet](BulkMoveArtifacts & pack, const ArtifactPosition & srcSlot, const CArtifactInstance * art)
  341. {
  342. assert(art);
  343. const auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, art->getTypeId());
  344. if(dstSlot != ArtifactPosition::PRE_FIRST)
  345. {
  346. pack.artsPack0.emplace_back(MoveArtifactInfo(srcSlot, dstSlot));
  347. if(ArtifactUtils::isSlotEquipment(dstSlot))
  348. pack.artsPack0.back().askAssemble = true;
  349. artFittingSet.putArtifact(dstSlot, const_cast<CArtifactInstance*>(art));
  350. }
  351. };
  352. if(loserHero)
  353. {
  354. auto & packHero = finishingBattle->artifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  355. packHero.srcArtHolder = finishingBattle->loserId;
  356. for(const auto & slot : ArtifactUtils::commonWornSlots())
  357. {
  358. if(const auto artSlot = loserHero->artifactsWorn.find(slot); artSlot != loserHero->artifactsWorn.end() && ArtifactUtils::isArtRemovable(*artSlot))
  359. {
  360. addArtifactToTransfer(packHero, artSlot->first, artSlot->second.getArt());
  361. }
  362. }
  363. for(const auto & artSlot : loserHero->artifactsInBackpack)
  364. {
  365. if(const auto art = artSlot.getArt(); art->getTypeId() != ArtifactID::GRAIL)
  366. addArtifactToTransfer(packHero, loserHero->getArtPos(art), art);
  367. }
  368. if(loserHero->commander)
  369. {
  370. auto & packCommander = finishingBattle->artifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  371. packCommander.srcCreature = loserHero->findStack(loserHero->commander);
  372. for(const auto & artSlot : loserHero->commander->artifactsWorn)
  373. addArtifactToTransfer(packCommander, artSlot.first, artSlot.second.getArt());
  374. }
  375. auto armyObj = battle.battleGetArmyObject(battle.otherSide(battleResult->winner));
  376. for(const auto & armySlot : armyObj->stacks)
  377. {
  378. auto & packsArmy = finishingBattle->artifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  379. packsArmy.srcArtHolder = armyObj->id;
  380. packsArmy.srcCreature = armySlot.first;
  381. for(const auto & artSlot : armySlot.second->artifactsWorn)
  382. addArtifactToTransfer(packsArmy, artSlot.first, armySlot.second->getArt(artSlot.first));
  383. }
  384. }
  385. }
  386. // Remove beaten hero
  387. if(loserHero)
  388. {
  389. //add statistics
  390. if(!finishingBattle->isDraw())
  391. {
  392. ConstTransitivePtr<CGHeroInstance> strongestHero = nullptr;
  393. for(auto & hero : gameHandler->gameState()->getPlayerState(finishingBattle->loser)->getHeroes())
  394. if(!strongestHero || hero->exp > strongestHero->exp)
  395. strongestHero = hero;
  396. if(strongestHero->id == finishingBattle->loserId && strongestHero->level > 5)
  397. gameHandler->gameState()->statistic.accumulatedValues[finishingBattle->victor].lastDefeatedStrongestHeroDay = gameHandler->gameState()->getDate(Date::DAY);
  398. }
  399. gameHandler->removeAfterVisit(finishingBattle->loserId);
  400. }
  401. // For draw case both heroes should be removed
  402. if(finishingBattle->isDraw() && winnerHero)
  403. {
  404. gameHandler->removeAfterVisit(finishingBattle->winnerId);
  405. if(gameHandler->getSettings().getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  406. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, winnerHero);
  407. }
  408. // add statistic
  409. if(battle.sideToPlayer(BattleSide::ATTACKER) == PlayerColor::NEUTRAL || battle.sideToPlayer(BattleSide::DEFENDER) == PlayerColor::NEUTRAL)
  410. {
  411. gameHandler->gameState()->statistic.accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesNeutral++;
  412. gameHandler->gameState()->statistic.accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesNeutral++;
  413. if(!finishingBattle->isDraw())
  414. gameHandler->gameState()->statistic.accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesNeutral++;
  415. }
  416. else
  417. {
  418. gameHandler->gameState()->statistic.accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesPlayer++;
  419. gameHandler->gameState()->statistic.accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesPlayer++;
  420. if(!finishingBattle->isDraw())
  421. gameHandler->gameState()->statistic.accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesPlayer++;
  422. }
  423. BattleResultAccepted raccepted;
  424. raccepted.battleID = battle.getBattle()->getBattleID();
  425. raccepted.heroResult[BattleSide::ATTACKER].army = battle.battleGetArmyObject(BattleSide::ATTACKER)->id;
  426. raccepted.heroResult[BattleSide::DEFENDER].army = battle.battleGetArmyObject(BattleSide::DEFENDER)->id;
  427. raccepted.heroResult[BattleSide::ATTACKER].exp = battleResult->exp[BattleSide::ATTACKER];
  428. raccepted.heroResult[BattleSide::DEFENDER].exp = battleResult->exp[BattleSide::DEFENDER];
  429. raccepted.winnerSide = finishingBattle->winnerSide;
  430. raccepted.artifacts = finishingBattle->artifacts;
  431. gameHandler->sendAndApply(raccepted);
  432. //--> continuation (battleAfterLevelUp) occurs after level-up gameHandler->queries are handled or on removing query
  433. }
  434. void BattleResultProcessor::battleAfterLevelUp(const BattleID & battleID, const BattleResult & result)
  435. {
  436. LOG_TRACE(logGlobal);
  437. assert(finishingBattles.count(battleID) != 0);
  438. if(finishingBattles.count(battleID) == 0)
  439. return;
  440. auto & finishingBattle = finishingBattles[battleID];
  441. const auto winnerHero = gameHandler->getHero(finishingBattle->winnerId);
  442. const auto loserHero = gameHandler->getHero(finishingBattle->loserId);
  443. finishingBattle->remainingBattleQueriesCount--;
  444. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  445. if (finishingBattle->remainingBattleQueriesCount > 0)
  446. //Battle results will be handled when all battle gameHandler->queries are closed
  447. return;
  448. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  449. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  450. // Still, it looks like a hole.
  451. // Necromancy if applicable.
  452. const CStackBasicDescriptor raisedStack = winnerHero ? winnerHero->calculateNecromancy(result) : CStackBasicDescriptor();
  453. // Give raised units to winner and show dialog, if any were raised,
  454. // units will be given after casualties are taken
  455. const SlotID necroSlot = raisedStack.getCreature() ? winnerHero->getSlotFor(raisedStack.getCreature()) : SlotID();
  456. if (necroSlot != SlotID() && !finishingBattle->isDraw())
  457. {
  458. winnerHero->showNecromancyDialog(raisedStack, gameHandler->getRandomGenerator());
  459. gameHandler->addToSlot(StackLocation(finishingBattle->winnerId, necroSlot), raisedStack.getCreature(), raisedStack.count);
  460. }
  461. BattleResultsApplied resultsApplied;
  462. resultsApplied.battleID = battleID;
  463. resultsApplied.victor = finishingBattle->victor;
  464. resultsApplied.loser = finishingBattle->loser;
  465. resultsApplied.artifacts = finishingBattle->artifacts;
  466. gameHandler->sendAndApply(resultsApplied);
  467. //handle victory/loss of engaged players
  468. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  469. gameHandler->checkVictoryLossConditions(playerColors);
  470. if (result.result == EBattleResult::SURRENDER)
  471. {
  472. gameHandler->gameState()->statistic.accumulatedValues[finishingBattle->loser].numHeroSurrendered++;
  473. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, loserHero);
  474. }
  475. if (result.result == EBattleResult::ESCAPE)
  476. {
  477. gameHandler->gameState()->statistic.accumulatedValues[finishingBattle->loser].numHeroEscaped++;
  478. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, loserHero);
  479. }
  480. finishingBattles.erase(battleID);
  481. battleResults.erase(battleID);
  482. }
  483. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, BattleSide victoriusSide)
  484. {
  485. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  486. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  487. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  488. battleResult->battleID = battle.getBattle()->getBattleID();
  489. battleResult->result = resultType;
  490. battleResult->winner = victoriusSide; //surrendering side loses
  491. auto allStacks = battle.battleGetStacksIf([](const CStack * stack){
  492. if (stack->summoned)//don't take into account temporary summoned stacks
  493. return false;
  494. if (stack->isTurret())
  495. return false;
  496. return true;
  497. });
  498. for(const auto & st : allStacks) //setting casualties
  499. {
  500. si32 killed = st->getKilled();
  501. if(killed > 0)
  502. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  503. }
  504. }
  505. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  506. {
  507. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  508. }