BattleResultProcessor.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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/GameSettings.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/serializer/Cast.h"
  29. #include "../../lib/spells/CSpellHandler.h"
  30. #include <vstd/RNG.h>
  31. BattleResultProcessor::BattleResultProcessor(BattleProcessor * owner, CGameHandler * newGameHandler)
  32. // : owner(owner)
  33. : gameHandler(newGameHandler)
  34. {
  35. }
  36. CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle, uint8_t 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_ptr_cast<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, 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, 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, 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. winnerHero = info.getBattle()->getSideHero(BattleSide::ATTACKER);
  172. loserHero = info.getBattle()->getSideHero(BattleSide::DEFENDER);
  173. victor = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  174. loser = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  175. }
  176. else
  177. {
  178. winnerHero = info.getBattle()->getSideHero(BattleSide::DEFENDER);
  179. loserHero = info.getBattle()->getSideHero(BattleSide::ATTACKER);
  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. //FinishingBattleHelper::FinishingBattleHelper()
  187. //{
  188. // winnerHero = loserHero = nullptr;
  189. // winnerSide = 0;
  190. // remainingBattleQueriesCount = 0;
  191. //}
  192. void BattleResultProcessor::endBattle(const CBattleInfoCallback & battle)
  193. {
  194. auto const & giveExp = [](BattleResult &r)
  195. {
  196. if (r.winner > 1)
  197. {
  198. // draw
  199. return;
  200. }
  201. r.exp[0] = 0;
  202. r.exp[1] = 0;
  203. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  204. {
  205. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  206. }
  207. };
  208. LOG_TRACE(logGlobal);
  209. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  210. const auto * heroAttacker = battle.battleGetFightingHero(BattleSide::ATTACKER);
  211. const auto * heroDefender = battle.battleGetFightingHero(BattleSide::DEFENDER);
  212. //Fill BattleResult structure with exp info
  213. giveExp(*battleResult);
  214. if (battleResult->result == EBattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  215. {
  216. if(heroAttacker)
  217. battleResult->exp[1] += 500;
  218. if(heroDefender)
  219. battleResult->exp[0] += 500;
  220. }
  221. // Give 500 exp to winner if a town was conquered during the battle
  222. const auto * defendedTown = battle.battleGetDefendedTown();
  223. if (defendedTown && battleResult->winner == BattleSide::ATTACKER)
  224. battleResult->exp[BattleSide::ATTACKER] += 500;
  225. if(heroAttacker)
  226. battleResult->exp[0] = heroAttacker->calculateXp(battleResult->exp[0]);//scholar skill
  227. if(heroDefender)
  228. battleResult->exp[1] = heroDefender->calculateXp(battleResult->exp[1]);
  229. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(0)));
  230. if(!battleQuery)
  231. battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(1)));
  232. if (!battleQuery)
  233. {
  234. logGlobal->error("Cannot find battle query!");
  235. gameHandler->complain("Player " + boost::lexical_cast<std::string>(battle.sideToPlayer(0)) + " has no battle query at the top!");
  236. return;
  237. }
  238. battleQuery->result = std::make_optional(*battleResult);
  239. //Check how many battle gameHandler->queries were created (number of players blocked by battle)
  240. const int queriedPlayers = battleQuery ? (int)boost::count(gameHandler->queries->allQueries(), battleQuery) : 0;
  241. assert(finishingBattles.count(battle.getBattle()->getBattleID()) == 0);
  242. finishingBattles[battle.getBattle()->getBattleID()] = std::make_unique<FinishingBattleHelper>(battle, *battleResult, queriedPlayers);
  243. // in battles against neutrals, 1st player can ask to replay battle manually
  244. const auto * attackerPlayer = gameHandler->getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::ATTACKER));
  245. const auto * defenderPlayer = gameHandler->getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::DEFENDER));
  246. bool isAttackerHuman = attackerPlayer && attackerPlayer->isHuman();
  247. bool isDefenderHuman = defenderPlayer && defenderPlayer->isHuman();
  248. bool onlyOnePlayerHuman = isAttackerHuman != isDefenderHuman;
  249. // in battles against neutrals attacker can ask to replay battle manually, additionally in battles against AI player human side can also ask for replay
  250. if(onlyOnePlayerHuman)
  251. {
  252. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(gameHandler, battle.getBattle(), battleQuery->result);
  253. battleResult->queryID = battleDialogQuery->queryID;
  254. gameHandler->queries->addQuery(battleDialogQuery);
  255. }
  256. else
  257. battleResult->queryID = QueryID::NONE;
  258. //set same battle result for all gameHandler->queries
  259. for(auto q : gameHandler->queries->allQueries())
  260. {
  261. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  262. if(otherBattleQuery && otherBattleQuery->battleID == battle.getBattle()->getBattleID())
  263. otherBattleQuery->result = battleQuery->result;
  264. }
  265. gameHandler->turnTimerHandler->onBattleEnd(battle.getBattle()->getBattleID());
  266. gameHandler->sendAndApply(battleResult);
  267. if (battleResult->queryID == QueryID::NONE)
  268. endBattleConfirm(battle);
  269. }
  270. void BattleResultProcessor::endBattleConfirm(const CBattleInfoCallback & battle)
  271. {
  272. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(0)));
  273. if(!battleQuery)
  274. battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(1)));
  275. if(!battleQuery)
  276. {
  277. logGlobal->trace("No battle query, battle end was confirmed by another player");
  278. return;
  279. }
  280. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  281. auto * finishingBattle = finishingBattles.at(battle.getBattle()->getBattleID()).get();
  282. const EBattleResult result = battleResult->result;
  283. //calculate casualties before deleting battle
  284. CasualtiesAfterBattle cab1(battle, BattleSide::ATTACKER);
  285. CasualtiesAfterBattle cab2(battle, BattleSide::DEFENDER);
  286. cab1.updateArmy(gameHandler);
  287. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  288. if(battleResult->winner == BattleSide::DEFENDER
  289. && finishingBattle->winnerHero
  290. && finishingBattle->winnerHero->visitedTown
  291. && !finishingBattle->winnerHero->inTownGarrison
  292. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  293. {
  294. gameHandler->swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  295. }
  296. //give exp
  297. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  298. gameHandler->giveExperience(finishingBattle->winnerHero, battleResult->exp[finishingBattle->winnerSide]);
  299. // Eagle Eye handling
  300. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  301. {
  302. ChangeSpells spells;
  303. if(auto eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT))
  304. {
  305. auto eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE);
  306. for(auto & spellId : battle.getBattle()->getUsedSpells(battle.otherSide(battleResult->winner)))
  307. {
  308. auto spell = spellId.toEntity(VLC->spells());
  309. if(spell
  310. && spell->getLevel() <= eagleEyeLevel
  311. && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId())
  312. && gameHandler->getRandomGenerator().nextInt(99) < eagleEyeChance)
  313. {
  314. spells.spells.insert(spell->getId());
  315. }
  316. }
  317. }
  318. if(!spells.spells.empty())
  319. {
  320. spells.learn = 1;
  321. spells.hid = finishingBattle->winnerHero->id;
  322. InfoWindow iw;
  323. iw.player = finishingBattle->winnerHero->tempOwner;
  324. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  325. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  326. std::ostringstream names;
  327. for(int i = 0; i < spells.spells.size(); i++)
  328. {
  329. names << "%s";
  330. if(i < spells.spells.size() - 2)
  331. names << ", ";
  332. else if(i < spells.spells.size() - 1)
  333. names << "%s";
  334. }
  335. names << ".";
  336. iw.text.replaceRawString(names.str());
  337. auto it = spells.spells.begin();
  338. for(int i = 0; i < spells.spells.size(); i++, it++)
  339. {
  340. iw.text.replaceName(*it);
  341. if(i == spells.spells.size() - 2) //we just added pre-last name
  342. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  343. iw.components.emplace_back(ComponentType::SPELL, *it);
  344. }
  345. gameHandler->sendAndApply(&iw);
  346. gameHandler->sendAndApply(&spells);
  347. }
  348. }
  349. // Artifacts handling
  350. if(result == EBattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  351. {
  352. std::vector<const CArtifactInstance*> arts; // display them in window
  353. CArtifactFittingSet artFittingSet(*finishingBattle->winnerHero);
  354. const auto addArtifactToTransfer = [&artFittingSet, &arts](BulkMoveArtifacts & pack, const ArtifactPosition & srcSlot, const CArtifactInstance * art)
  355. {
  356. assert(art);
  357. const auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, art->getTypeId());
  358. if(dstSlot != ArtifactPosition::PRE_FIRST)
  359. {
  360. pack.artsPack0.emplace_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  361. if(ArtifactUtils::isSlotEquipment(dstSlot))
  362. pack.artsPack0.back().askAssemble = true;
  363. arts.emplace_back(art);
  364. artFittingSet.putArtifact(dstSlot, const_cast<CArtifactInstance*>(art));
  365. }
  366. };
  367. const auto sendArtifacts = [this](BulkMoveArtifacts & bma)
  368. {
  369. if(!bma.artsPack0.empty())
  370. gameHandler->sendAndApply(&bma);
  371. };
  372. BulkMoveArtifacts packHero(finishingBattle->winnerHero->getOwner(), ObjectInstanceID::NONE, finishingBattle->winnerHero->id, false);
  373. if(finishingBattle->loserHero)
  374. {
  375. packHero.srcArtHolder = finishingBattle->loserHero->id;
  376. for(const auto & slot : ArtifactUtils::commonWornSlots())
  377. {
  378. if(const auto artSlot = finishingBattle->loserHero->artifactsWorn.find(slot);
  379. artSlot != finishingBattle->loserHero->artifactsWorn.end() && ArtifactUtils::isArtRemovable(*artSlot))
  380. {
  381. addArtifactToTransfer(packHero, artSlot->first, artSlot->second.getArt());
  382. }
  383. }
  384. for(const auto & artSlot : finishingBattle->loserHero->artifactsInBackpack)
  385. {
  386. if(const auto art = artSlot.getArt(); art->getTypeId() != ArtifactID::GRAIL)
  387. addArtifactToTransfer(packHero, finishingBattle->loserHero->getArtPos(art), art);
  388. }
  389. if(finishingBattle->loserHero->commander)
  390. {
  391. BulkMoveArtifacts packCommander(finishingBattle->winnerHero->getOwner(), finishingBattle->loserHero->id, finishingBattle->winnerHero->id, false);
  392. packCommander.srcCreature = finishingBattle->loserHero->findStack(finishingBattle->loserHero->commander);
  393. for(const auto & artSlot : finishingBattle->loserHero->commander->artifactsWorn)
  394. addArtifactToTransfer(packCommander, artSlot.first, artSlot.second.getArt());
  395. sendArtifacts(packCommander);
  396. }
  397. }
  398. auto armyObj = battle.battleGetArmyObject(battle.otherSide(battleResult->winner));
  399. for(const auto & armySlot : armyObj->stacks)
  400. {
  401. BulkMoveArtifacts packsArmy(finishingBattle->winnerHero->getOwner(), finishingBattle->loserHero->id, finishingBattle->winnerHero->id, false);
  402. packsArmy.srcArtHolder = armyObj->id;
  403. packsArmy.srcCreature = armySlot.first;
  404. for(const auto & artSlot : armySlot.second->artifactsWorn)
  405. addArtifactToTransfer(packsArmy, artSlot.first, armySlot.second->getArt(artSlot.first));
  406. sendArtifacts(packsArmy);
  407. }
  408. // Display loot
  409. if(!arts.empty())
  410. {
  411. InfoWindow iw;
  412. iw.player = finishingBattle->winnerHero->tempOwner;
  413. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  414. for(const auto art : arts) //TODO; separate function to display loot for various objects?
  415. {
  416. if(art->isScroll())
  417. iw.components.emplace_back(ComponentType::SPELL_SCROLL, art->getScrollSpellID());
  418. else
  419. iw.components.emplace_back(ComponentType::ARTIFACT, art->getTypeId());
  420. if(iw.components.size() >= GameConstants::INFO_WINDOW_ARTIFACTS_MAX_ITEMS)
  421. {
  422. gameHandler->sendAndApply(&iw);
  423. iw.components.clear();
  424. }
  425. }
  426. gameHandler->sendAndApply(&iw);
  427. }
  428. if(!packHero.artsPack0.empty())
  429. sendArtifacts(packHero);
  430. }
  431. // Remove beaten hero
  432. if(finishingBattle->loserHero)
  433. {
  434. RemoveObject ro(finishingBattle->loserHero->id, finishingBattle->victor);
  435. gameHandler->sendAndApply(&ro);
  436. }
  437. // For draw case both heroes should be removed
  438. if(finishingBattle->isDraw() && finishingBattle->winnerHero)
  439. {
  440. RemoveObject ro(finishingBattle->winnerHero->id, finishingBattle->loser);
  441. gameHandler->sendAndApply(&ro);
  442. }
  443. BattleResultAccepted raccepted;
  444. raccepted.battleID = battle.getBattle()->getBattleID();
  445. raccepted.heroResult[0].army = const_cast<CArmedInstance*>(battle.battleGetArmyObject(BattleSide::ATTACKER));
  446. raccepted.heroResult[1].army = const_cast<CArmedInstance*>(battle.battleGetArmyObject(BattleSide::DEFENDER));
  447. raccepted.heroResult[0].hero = const_cast<CGHeroInstance*>(battle.battleGetFightingHero(BattleSide::ATTACKER));
  448. raccepted.heroResult[1].hero = const_cast<CGHeroInstance*>(battle.battleGetFightingHero(BattleSide::DEFENDER));
  449. raccepted.heroResult[0].exp = battleResult->exp[0];
  450. raccepted.heroResult[1].exp = battleResult->exp[1];
  451. raccepted.winnerSide = finishingBattle->winnerSide;
  452. gameHandler->sendAndApply(&raccepted);
  453. gameHandler->queries->popIfTop(battleQuery);
  454. //--> continuation (battleAfterLevelUp) occurs after level-up gameHandler->queries are handled or on removing query
  455. }
  456. void BattleResultProcessor::battleAfterLevelUp(const BattleID & battleID, const BattleResult & result)
  457. {
  458. LOG_TRACE(logGlobal);
  459. assert(finishingBattles.count(battleID) != 0);
  460. if(finishingBattles.count(battleID) == 0)
  461. return;
  462. auto & finishingBattle = finishingBattles[battleID];
  463. finishingBattle->remainingBattleQueriesCount--;
  464. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  465. if (finishingBattle->remainingBattleQueriesCount > 0)
  466. //Battle results will be handled when all battle gameHandler->queries are closed
  467. return;
  468. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  469. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  470. // Still, it looks like a hole.
  471. // Necromancy if applicable.
  472. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(result) : CStackBasicDescriptor();
  473. // Give raised units to winner and show dialog, if any were raised,
  474. // units will be given after casualties are taken
  475. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  476. if (necroSlot != SlotID() && !finishingBattle->isDraw())
  477. {
  478. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, gameHandler->getRandomGenerator());
  479. gameHandler->addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  480. }
  481. BattleResultsApplied resultsApplied;
  482. resultsApplied.battleID = battleID;
  483. resultsApplied.player1 = finishingBattle->victor;
  484. resultsApplied.player2 = finishingBattle->loser;
  485. gameHandler->sendAndApply(&resultsApplied);
  486. //handle victory/loss of engaged players
  487. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  488. gameHandler->checkVictoryLossConditions(playerColors);
  489. if (result.result == EBattleResult::SURRENDER)
  490. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, finishingBattle->loserHero);
  491. if (result.result == EBattleResult::ESCAPE)
  492. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, finishingBattle->loserHero);
  493. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  494. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  495. {
  496. RemoveObject ro(finishingBattle->winnerHero->id, finishingBattle->winnerHero->getOwner());
  497. gameHandler->sendAndApply(&ro);
  498. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  499. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, finishingBattle->winnerHero);
  500. }
  501. finishingBattles.erase(battleID);
  502. battleResults.erase(battleID);
  503. }
  504. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, int victoriusSide)
  505. {
  506. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  507. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  508. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  509. battleResult->battleID = battle.getBattle()->getBattleID();
  510. battleResult->result = resultType;
  511. battleResult->winner = victoriusSide; //surrendering side loses
  512. auto allStacks = battle.battleGetStacksIf([](const CStack * stack){
  513. if (stack->summoned)//don't take into account temporary summoned stacks
  514. return false;
  515. if (stack->isTurret())
  516. return false;
  517. return true;
  518. });
  519. for(const auto & st : allStacks) //setting casualties
  520. {
  521. si32 killed = st->getKilled();
  522. if(killed > 0)
  523. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  524. }
  525. }
  526. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  527. {
  528. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  529. }