BattleResultProcessor.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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 "../processors/HeroPoolProcessor.h"
  14. #include "../queries/QueriesProcessor.h"
  15. #include "../queries/BattleQueries.h"
  16. #include "../../lib/ArtifactUtils.h"
  17. #include "../../lib/CStack.h"
  18. #include "../../lib/GameSettings.h"
  19. #include "../../lib/battle/CBattleInfoCallback.h"
  20. #include "../../lib/battle/IBattleState.h"
  21. #include "../../lib/battle/SideInBattle.h"
  22. #include "../../lib/gameState/CGameState.h"
  23. #include "../../lib/mapObjects/CGTownInstance.h"
  24. #include "../../lib/serializer/Cast.h"
  25. #include "../../lib/spells/CSpellHandler.h"
  26. BattleResultProcessor::BattleResultProcessor(BattleProcessor * owner)
  27. // : owner(owner)
  28. : gameHandler(nullptr)
  29. {
  30. }
  31. void BattleResultProcessor::setGameHandler(CGameHandler * newGameHandler)
  32. {
  33. gameHandler = newGameHandler;
  34. }
  35. CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle, uint8_t sideInBattle):
  36. army(battle.battleGetArmyObject(sideInBattle))
  37. {
  38. heroWithDeadCommander = ObjectInstanceID();
  39. PlayerColor color = battle.sideToPlayer(sideInBattle);
  40. for(const CStack * stConst : battle.battleGetAllStacks(true))
  41. {
  42. // Use const cast - in order to call non-const "takeResurrected" for proper calculation of casualties
  43. // TODO: better solution
  44. CStack * st = const_cast<CStack*>(stConst);
  45. if(st->summoned) //don't take into account temporary summoned stacks
  46. continue;
  47. if(st->unitOwner() != color) //remove only our stacks
  48. continue;
  49. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  50. st->health.takeResurrected();
  51. if(st->unitSlot() == SlotID::ARROW_TOWERS_SLOT)
  52. {
  53. logGlobal->debug("Ignored arrow towers stack.");
  54. }
  55. else if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  56. {
  57. auto warMachine = st->unitType()->warMachine;
  58. if(warMachine == ArtifactID::NONE)
  59. {
  60. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  61. }
  62. //catapult artifact remain even if "creature" killed in siege
  63. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  64. {
  65. logGlobal->debug("War machine has been destroyed");
  66. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  67. if (hero)
  68. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  69. else
  70. logGlobal->error("War machine in army without hero");
  71. }
  72. }
  73. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  74. {
  75. if(st->alive() && st->getCount() > 0)
  76. {
  77. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  78. const CreatureID summonedType = st->creatureId();
  79. summoned[summonedType] += st->getCount();
  80. }
  81. }
  82. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  83. {
  84. if (nullptr == st->base)
  85. {
  86. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  87. }
  88. else
  89. {
  90. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  91. if(c)
  92. {
  93. auto h = dynamic_cast <const CGHeroInstance *>(army);
  94. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  95. {
  96. logGlobal->debug("Commander is dead.");
  97. heroWithDeadCommander = army->id; //TODO: unify commander handling
  98. }
  99. }
  100. else
  101. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  102. }
  103. }
  104. else if(st->base && !army->slotEmpty(st->unitSlot()))
  105. {
  106. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  107. if(st->getCount() == 0 || !st->alive())
  108. {
  109. logGlobal->debug("Stack has been destroyed.");
  110. StackLocation sl(army, st->unitSlot());
  111. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  112. }
  113. else if(st->getCount() < army->getStackCount(st->unitSlot()))
  114. {
  115. logGlobal->debug("Stack lost %d units.", army->getStackCount(st->unitSlot()) - st->getCount());
  116. StackLocation sl(army, st->unitSlot());
  117. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  118. }
  119. else if(st->getCount() > army->getStackCount(st->unitSlot()))
  120. {
  121. logGlobal->debug("Stack gained %d units.", st->getCount() - army->getStackCount(st->unitSlot()));
  122. StackLocation sl(army, st->unitSlot());
  123. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  124. }
  125. }
  126. else
  127. {
  128. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  129. }
  130. }
  131. }
  132. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  133. {
  134. for (TStackAndItsNewCount &ncount : newStackCounts)
  135. {
  136. if (ncount.second > 0)
  137. gh->changeStackCount(ncount.first, ncount.second, true);
  138. else
  139. gh->eraseStack(ncount.first, true);
  140. }
  141. for (auto summoned_iter : summoned)
  142. {
  143. SlotID slot = army->getSlotFor(summoned_iter.first);
  144. if (slot.validSlot())
  145. {
  146. StackLocation location(army, slot);
  147. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  148. }
  149. else
  150. {
  151. //even if it will be possible to summon anything permanently it should be checked for free slot
  152. //necromancy is handled separately
  153. gh->complain("No free slot to put summoned creature");
  154. }
  155. }
  156. for (auto al : removedWarMachines)
  157. {
  158. gh->removeArtifact(al);
  159. }
  160. if (heroWithDeadCommander != ObjectInstanceID())
  161. {
  162. SetCommanderProperty scp;
  163. scp.heroid = heroWithDeadCommander;
  164. scp.which = SetCommanderProperty::ALIVE;
  165. scp.amount = 0;
  166. gh->sendAndApply(&scp);
  167. }
  168. }
  169. FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int remainingBattleQueriesCount)
  170. {
  171. assert(Query->result);
  172. assert(Query->bi);
  173. auto &result = *Query->result;
  174. auto &info = *Query->bi;
  175. if (result.winner == BattleSide::ATTACKER)
  176. {
  177. winnerHero = info.getSideHero(BattleSide::ATTACKER);
  178. loserHero = info.getSideHero(BattleSide::DEFENDER);
  179. victor = info.getSidePlayer(BattleSide::ATTACKER);
  180. loser = info.getSidePlayer(BattleSide::DEFENDER);
  181. }
  182. else
  183. {
  184. winnerHero = info.getSideHero(BattleSide::DEFENDER);
  185. loserHero = info.getSideHero(BattleSide::ATTACKER);
  186. victor = info.getSidePlayer(BattleSide::DEFENDER);
  187. loser = info.getSidePlayer(BattleSide::ATTACKER);
  188. }
  189. winnerSide = result.winner;
  190. this->remainingBattleQueriesCount = remainingBattleQueriesCount;
  191. }
  192. FinishingBattleHelper::FinishingBattleHelper()
  193. {
  194. winnerHero = loserHero = nullptr;
  195. winnerSide = 0;
  196. remainingBattleQueriesCount = 0;
  197. }
  198. void BattleResultProcessor::endBattle(const CBattleInfoCallback & battle)
  199. {
  200. auto const & giveExp = [](BattleResult &r)
  201. {
  202. if (r.winner > 1)
  203. {
  204. // draw
  205. return;
  206. }
  207. r.exp[0] = 0;
  208. r.exp[1] = 0;
  209. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  210. {
  211. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  212. }
  213. };
  214. LOG_TRACE(logGlobal);
  215. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  216. const auto * heroAttacker = battle.battleGetFightingHero(BattleSide::ATTACKER);
  217. const auto * heroDefender = battle.battleGetFightingHero(BattleSide::DEFENDER);
  218. //Fill BattleResult structure with exp info
  219. giveExp(*battleResult);
  220. if (battleResult->result == EBattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  221. {
  222. if(heroAttacker)
  223. battleResult->exp[1] += 500;
  224. if(heroDefender)
  225. battleResult->exp[0] += 500;
  226. }
  227. if(heroAttacker)
  228. battleResult->exp[0] = heroAttacker->calculateXp(battleResult->exp[0]);//scholar skill
  229. if(heroDefender)
  230. battleResult->exp[1] = heroDefender->calculateXp(battleResult->exp[1]);
  231. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(0)));
  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>(battleQuery, queriedPlayers);
  243. // in battles against neutrals, 1st player can ask to replay battle manually
  244. if (!battle.sideToPlayer(1).isValidPlayer())
  245. {
  246. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(gameHandler, battle.getBattle());
  247. battleResult->queryID = battleDialogQuery->queryID;
  248. gameHandler->queries->addQuery(battleDialogQuery);
  249. }
  250. else
  251. battleResult->queryID = -1;
  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)
  257. otherBattleQuery->result = battleQuery->result;
  258. }
  259. gameHandler->turnTimerHandler.onBattleEnd(battle.battleID);
  260. if (battleResult->queryID == QueryID::NONE)
  261. endBattleConfirm(battle);
  262. }
  263. void BattleResultProcessor::endBattleConfirm(const CBattleInfoCallback & battle)
  264. {
  265. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(0)));
  266. if(!battleQuery)
  267. {
  268. logGlobal->trace("No battle query, battle end was confirmed by another player");
  269. return;
  270. }
  271. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  272. auto * finishingBattle = finishingBattles.at(battle.getBattle()->getBattleID()).get();
  273. const EBattleResult result = battleResult->result;
  274. //calculate casualties before deleting battle
  275. CasualtiesAfterBattle cab1(battle, BattleSide::ATTACKER);
  276. CasualtiesAfterBattle cab2(battle, BattleSide::DEFENDER);
  277. ChangeSpells cs; //for Eagle Eye
  278. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  279. {
  280. if (int eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT, -1))
  281. {
  282. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE, 0);
  283. for(auto & spellId : battle.getBattle()->getUsedSpells(battle.otherSide(battleResult->winner)))
  284. {
  285. auto spell = spellId.toSpell(VLC->spells());
  286. if(spell && spell->getLevel() <= eagleEyeLevel && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId()) && gameHandler->getRandomGenerator().nextInt(99) < eagleEyeChance)
  287. cs.spells.insert(spell->getId());
  288. }
  289. }
  290. }
  291. std::vector<const CArtifactInstance *> arts; //display them in window
  292. if(result == EBattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  293. {
  294. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  295. {
  296. const auto slot = ArtifactUtils::getArtAnyPosition(finishingBattle->winnerHero, art->getTypeId());
  297. if(slot != ArtifactPosition::PRE_FIRST)
  298. {
  299. arts.push_back(art);
  300. ma->dst = ArtifactLocation(finishingBattle->winnerHero, slot);
  301. if(ArtifactUtils::isSlotBackpack(slot))
  302. ma->askAssemble = false;
  303. gameHandler->sendAndApply(ma);
  304. }
  305. };
  306. if (finishingBattle->loserHero)
  307. {
  308. //TODO: wrap it into a function, somehow (std::variant -_-)
  309. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  310. for (auto artSlot : artifactsWorn)
  311. {
  312. MoveArtifact ma;
  313. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  314. const CArtifactInstance * art = ma.src.getArt();
  315. if (art && !art->artType->isBig() &&
  316. art->artType->getId() != ArtifactID::SPELLBOOK)
  317. // don't move war machines or locked arts (spellbook)
  318. {
  319. sendMoveArtifact(art, &ma);
  320. }
  321. }
  322. for(int slotNumber = finishingBattle->loserHero->artifactsInBackpack.size() - 1; slotNumber >= 0; slotNumber--)
  323. {
  324. //we assume that no big artifacts can be found
  325. MoveArtifact ma;
  326. ma.src = ArtifactLocation(finishingBattle->loserHero,
  327. ArtifactPosition(ArtifactPosition::BACKPACK_START + slotNumber)); //backpack automatically shifts arts to beginning
  328. const CArtifactInstance * art = ma.src.getArt();
  329. if (art->artType->getId() != ArtifactID::GRAIL) //grail may not be won
  330. {
  331. sendMoveArtifact(art, &ma);
  332. }
  333. }
  334. if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  335. {
  336. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  337. for (auto artSlot : artifactsWorn)
  338. {
  339. MoveArtifact ma;
  340. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  341. const CArtifactInstance * art = ma.src.getArt();
  342. if (art && !art->artType->isBig())
  343. {
  344. sendMoveArtifact(art, &ma);
  345. }
  346. }
  347. }
  348. }
  349. auto loser = battle.otherSide(battleResult->winner);
  350. for (auto armySlot : battle.battleGetArmyObject(loser)->stacks)
  351. {
  352. auto artifactsWorn = armySlot.second->artifactsWorn;
  353. for (auto artSlot : artifactsWorn)
  354. {
  355. MoveArtifact ma;
  356. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  357. const CArtifactInstance * art = ma.src.getArt();
  358. if (art && !art->artType->isBig())
  359. {
  360. sendMoveArtifact(art, &ma);
  361. }
  362. }
  363. }
  364. }
  365. if (arts.size()) //display loot
  366. {
  367. InfoWindow iw;
  368. iw.player = finishingBattle->winnerHero->tempOwner;
  369. iw.text.appendLocalString (EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  370. for (auto art : arts) //TODO; separate function to display loot for various ojects?
  371. {
  372. iw.components.emplace_back(
  373. Component::EComponentType::ARTIFACT, art->artType->getId(),
  374. art->artType->getId() == ArtifactID::SPELL_SCROLL? art->getScrollSpellID() : SpellID(0), 0);
  375. if (iw.components.size() >= 14)
  376. {
  377. gameHandler->sendAndApply(&iw);
  378. iw.components.clear();
  379. }
  380. }
  381. if (iw.components.size())
  382. {
  383. gameHandler->sendAndApply(&iw);
  384. }
  385. }
  386. //Eagle Eye secondary skill handling
  387. if (!cs.spells.empty())
  388. {
  389. cs.learn = 1;
  390. cs.hid = finishingBattle->winnerHero->id;
  391. InfoWindow iw;
  392. iw.player = finishingBattle->winnerHero->tempOwner;
  393. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  394. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  395. std::ostringstream names;
  396. for (int i = 0; i < cs.spells.size(); i++)
  397. {
  398. names << "%s";
  399. if (i < cs.spells.size() - 2)
  400. names << ", ";
  401. else if (i < cs.spells.size() - 1)
  402. names << "%s";
  403. }
  404. names << ".";
  405. iw.text.replaceRawString(names.str());
  406. auto it = cs.spells.begin();
  407. for (int i = 0; i < cs.spells.size(); i++, it++)
  408. {
  409. iw.text.replaceLocalString(EMetaText::SPELL_NAME, it->toEnum());
  410. if (i == cs.spells.size() - 2) //we just added pre-last name
  411. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  412. iw.components.emplace_back(Component::EComponentType::SPELL, *it, 0, 0);
  413. }
  414. gameHandler->sendAndApply(&iw);
  415. gameHandler->sendAndApply(&cs);
  416. }
  417. cab1.updateArmy(gameHandler);
  418. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  419. if(finishingBattle->loserHero) //remove beaten hero
  420. {
  421. RemoveObject ro(finishingBattle->loserHero->id);
  422. gameHandler->sendAndApply(&ro);
  423. }
  424. if(finishingBattle->isDraw() && finishingBattle->winnerHero) //for draw case both heroes should be removed
  425. {
  426. RemoveObject ro(finishingBattle->winnerHero->id);
  427. gameHandler->sendAndApply(&ro);
  428. }
  429. if(battleResult->winner == BattleSide::DEFENDER
  430. && finishingBattle->winnerHero
  431. && finishingBattle->winnerHero->visitedTown
  432. && !finishingBattle->winnerHero->inTownGarrison
  433. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  434. {
  435. gameHandler->swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  436. }
  437. //give exp
  438. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  439. gameHandler->changePrimSkill(finishingBattle->winnerHero, PrimarySkill::EXPERIENCE, battleResult->exp[finishingBattle->winnerSide]);
  440. BattleResultAccepted raccepted;
  441. raccepted.heroResult[0].army = const_cast<CArmedInstance*>(battle.battleGetArmyObject(0));
  442. raccepted.heroResult[1].army = const_cast<CArmedInstance*>(battle.battleGetArmyObject(1));
  443. raccepted.heroResult[0].hero = const_cast<CGHeroInstance*>(battle.battleGetFightingHero(0));
  444. raccepted.heroResult[1].hero = const_cast<CGHeroInstance*>(battle.battleGetFightingHero(1));
  445. raccepted.heroResult[0].exp = battleResult->exp[0];
  446. raccepted.heroResult[1].exp = battleResult->exp[1];
  447. raccepted.winnerSide = finishingBattle->winnerSide;
  448. gameHandler->sendAndApply(&raccepted);
  449. gameHandler->queries->popIfTop(battleQuery);
  450. //--> continuation (battleAfterLevelUp) occurs after level-up gameHandler->queries are handled or on removing query
  451. }
  452. void BattleResultProcessor::battleAfterLevelUp(const CBattleInfoCallback & battle, const BattleResult & result)
  453. {
  454. LOG_TRACE(logGlobal);
  455. assert(finishingBattles.count(battle.getBattle()->getBattleID()) != 0);
  456. if(finishingBattles.count(battle.getBattle()->getBattleID()) == 0)
  457. return;
  458. auto & finishingBattle = finishingBattles[battle.getBattle()->getBattleID()];
  459. finishingBattle->remainingBattleQueriesCount--;
  460. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  461. if (finishingBattle->remainingBattleQueriesCount > 0)
  462. //Battle results will be handled when all battle gameHandler->queries are closed
  463. return;
  464. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  465. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  466. // Still, it looks like a hole.
  467. // Necromancy if applicable.
  468. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(result) : CStackBasicDescriptor();
  469. // Give raised units to winner and show dialog, if any were raised,
  470. // units will be given after casualties are taken
  471. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  472. if (necroSlot != SlotID())
  473. {
  474. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, gameHandler->getRandomGenerator());
  475. gameHandler->addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  476. }
  477. BattleResultsApplied resultsApplied;
  478. resultsApplied.player1 = finishingBattle->victor;
  479. resultsApplied.player2 = finishingBattle->loser;
  480. gameHandler->sendAndApply(&resultsApplied);
  481. //handle victory/loss of engaged players
  482. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  483. gameHandler->checkVictoryLossConditions(playerColors);
  484. if (result.result == EBattleResult::SURRENDER)
  485. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, finishingBattle->loserHero);
  486. if (result.result == EBattleResult::ESCAPE)
  487. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, finishingBattle->loserHero);
  488. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  489. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  490. {
  491. RemoveObject ro(finishingBattle->winnerHero->id);
  492. gameHandler->sendAndApply(&ro);
  493. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  494. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, finishingBattle->winnerHero);
  495. }
  496. finishingBattles.erase(battle.getBattle()->getBattleID());
  497. battleResults.erase(battle.getBattle()->getBattleID());
  498. }
  499. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, int victoriusSide)
  500. {
  501. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  502. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  503. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  504. battleResult->result = resultType;
  505. battleResult->winner = victoriusSide; //surrendering side loses
  506. for(const auto & st : battle.battleGetAllStacks(true)) //setting casualties
  507. {
  508. si32 killed = st->getKilled();
  509. if(killed > 0)
  510. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  511. }
  512. }
  513. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  514. {
  515. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  516. }