BattleResultProcessor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 "battle/BattleInfo.h"
  13. #include "../CGameHandler.h"
  14. #include "../TurnTimerHandler.h"
  15. #include "../processors/HeroPoolProcessor.h"
  16. #include "../queries/QueriesProcessor.h"
  17. #include "../queries/BattleQueries.h"
  18. #include "../../lib/CStack.h"
  19. #include "../../lib/CPlayerState.h"
  20. #include "../../lib/IGameSettings.h"
  21. #include "../../lib/battle/SideInBattle.h"
  22. #include "../../lib/entities/artifact/ArtifactUtils.h"
  23. #include "../../lib/entities/artifact/CArtifact.h"
  24. #include "../../lib/entities/artifact/CArtifactFittingSet.h"
  25. #include "../../lib/gameState/CGameState.h"
  26. #include "../../lib/mapObjects/CGTownInstance.h"
  27. #include "../../lib/networkPacks/PacksForClientBattle.h"
  28. #include "../../lib/spells/CSpellHandler.h"
  29. #include <boost/lexical_cast.hpp>
  30. BattleResultProcessor::BattleResultProcessor(CGameHandler * gameHandler)
  31. : gameHandler(gameHandler)
  32. {
  33. }
  34. CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle, BattleSide sideInBattle):
  35. army(battle.battleGetArmyObject(sideInBattle))
  36. {
  37. heroWithDeadCommander = ObjectInstanceID();
  38. PlayerColor color = battle.sideToPlayer(sideInBattle);
  39. auto allStacks = battle.battleGetStacksIf([color](const CStack * stack){
  40. if (stack->summoned)//don't take into account temporary summoned stacks
  41. return false;
  42. if(stack->unitOwner() != color) //remove only our stacks
  43. return false;
  44. if (stack->isTurret())
  45. return false;
  46. return true;
  47. });
  48. for(const CStack * stConst : allStacks)
  49. {
  50. // Use const cast - in order to call non-const "takeResurrected" for proper calculation of casualties
  51. // TODO: better solution
  52. auto * st = const_cast<CStack*>(stConst);
  53. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  54. st->health.takeResurrected();
  55. 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_cast<const CGHeroInstance*> (army);
  67. if (hero)
  68. removedWarMachines.push_back (ArtifactLocation(hero->id, 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->getCommander() == 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->id, st->unitSlot());
  111. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  112. }
  113. else if(st->getCount() != army->getStackCount(st->unitSlot()))
  114. {
  115. logGlobal->debug("Stack size changed: %d -> %d units.", army->getStackCount(st->unitSlot()), st->getCount());
  116. StackLocation sl(army->id, st->unitSlot());
  117. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  118. }
  119. }
  120. else
  121. {
  122. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  123. }
  124. }
  125. }
  126. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  127. {
  128. if (gh->gameInfo().getObjInstance(army->id) == nullptr)
  129. throw std::runtime_error("Object " + army->getObjectName() + " is not on the map!");
  130. for (const auto & ncount : newStackCounts)
  131. {
  132. if (ncount.second > 0)
  133. gh->changeStackCount(ncount.first, ncount.second, ChangeValueMode::ABSOLUTE);
  134. else
  135. gh->eraseStack(ncount.first, true);
  136. }
  137. for (auto summoned_iter : summoned)
  138. {
  139. SlotID slot = army->getSlotFor(summoned_iter.first);
  140. if (slot.validSlot())
  141. {
  142. StackLocation location(army->id, slot);
  143. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  144. }
  145. else
  146. {
  147. //even if it will be possible to summon anything permanently it should be checked for free slot
  148. //necromancy is handled separately
  149. gh->complain("No free slot to put summoned creature");
  150. }
  151. }
  152. for (auto al : removedWarMachines)
  153. {
  154. gh->removeArtifact(al);
  155. }
  156. if (heroWithDeadCommander != ObjectInstanceID())
  157. {
  158. SetCommanderProperty scp;
  159. scp.heroid = heroWithDeadCommander;
  160. scp.which = SetCommanderProperty::ALIVE;
  161. scp.amount = 0;
  162. gh->sendAndApply(scp);
  163. }
  164. }
  165. FinishingBattleHelper::FinishingBattleHelper(const CBattleInfoCallback & info, const BattleResult & result, int remainingBattleQueriesCount)
  166. {
  167. const auto attackerHero = info.getBattle()->getSideHero(BattleSide::ATTACKER);
  168. const auto defenderHero = info.getBattle()->getSideHero(BattleSide::DEFENDER);
  169. if (result.winner == BattleSide::ATTACKER)
  170. {
  171. winnerId = attackerHero ? attackerHero->id : ObjectInstanceID::NONE;
  172. loserId = defenderHero ? defenderHero->id : ObjectInstanceID::NONE;
  173. victor = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  174. loser = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  175. }
  176. else
  177. {
  178. winnerId = defenderHero ? defenderHero->id : ObjectInstanceID::NONE;
  179. loserId = attackerHero ? attackerHero->id : ObjectInstanceID::NONE;
  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] += i->first.toCreature()->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 ? 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->gameInfo().getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::ATTACKER));
  239. const auto * defenderPlayer = gameHandler->gameInfo().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 battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::ATTACKER)));
  267. if(!battleQuery)
  268. battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::DEFENDER)));
  269. if(!battleQuery)
  270. {
  271. logGlobal->trace("No battle query, battle end was confirmed by another player");
  272. return;
  273. }
  274. const auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  275. const auto * finishingBattle = finishingBattles.at(battle.getBattle()->getBattleID()).get();
  276. //calculate casualties before deleting battle
  277. CasualtiesAfterBattle cab1(battle, BattleSide::ATTACKER);
  278. CasualtiesAfterBattle cab2(battle, BattleSide::DEFENDER);
  279. cab1.updateArmy(gameHandler);
  280. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  281. const auto winnerHero = battle.battleGetFightingHero(finishingBattle->winnerSide);
  282. const auto loserHero = battle.battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  283. if(battleResult->winner == BattleSide::DEFENDER
  284. && winnerHero
  285. && winnerHero->getVisitedTown()
  286. && !winnerHero->isGarrisoned()
  287. && winnerHero->getVisitedTown()->getGarrisonHero() == winnerHero)
  288. {
  289. gameHandler->swapGarrisonOnSiege(winnerHero->getVisitedTown()->id); //return defending visitor from garrison to its rightful place
  290. }
  291. //give exp
  292. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide])
  293. {
  294. gameHandler->giveStackExperience(battle.battleGetArmyObject(finishingBattle->winnerSide), battleResult->exp[finishingBattle->winnerSide]);
  295. if (winnerHero)
  296. gameHandler->giveExperience(winnerHero, battleResult->exp[finishingBattle->winnerSide]);
  297. }
  298. // Add statistics
  299. if(loserHero && !finishingBattle->isDraw())
  300. {
  301. const CGHeroInstance * strongestHero = nullptr;
  302. for(auto & hero : gameHandler->gameState().getPlayerState(finishingBattle->loser)->getHeroes())
  303. if(!strongestHero || hero->exp > strongestHero->exp)
  304. strongestHero = hero;
  305. if(strongestHero->id == finishingBattle->loserId && strongestHero->level > 5)
  306. gameHandler->statistics->accumulatedValues[finishingBattle->victor].lastDefeatedStrongestHeroDay = gameHandler->gameState().getDate(Date::DAY);
  307. }
  308. if(battle.sideToPlayer(BattleSide::ATTACKER) == PlayerColor::NEUTRAL || battle.sideToPlayer(BattleSide::DEFENDER) == PlayerColor::NEUTRAL)
  309. {
  310. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesNeutral++;
  311. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesNeutral++;
  312. if(!finishingBattle->isDraw())
  313. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesNeutral++;
  314. }
  315. else
  316. {
  317. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesPlayer++;
  318. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesPlayer++;
  319. if(!finishingBattle->isDraw())
  320. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesPlayer++;
  321. }
  322. BattleResultAccepted raccepted;
  323. raccepted.battleID = battle.getBattle()->getBattleID();
  324. raccepted.heroResult[finishingBattle->winnerSide].heroID = winnerHero ? winnerHero->id : ObjectInstanceID::NONE;
  325. raccepted.heroResult[CBattleInfoEssentials::otherSide(finishingBattle->winnerSide)].heroID = loserHero ? loserHero->id : ObjectInstanceID::NONE;
  326. raccepted.heroResult[BattleSide::ATTACKER].armyID = battle.battleGetArmyObject(BattleSide::ATTACKER)->id;
  327. raccepted.heroResult[BattleSide::DEFENDER].armyID = battle.battleGetArmyObject(BattleSide::DEFENDER)->id;
  328. raccepted.heroResult[BattleSide::ATTACKER].exp = battleResult->exp[BattleSide::ATTACKER];
  329. raccepted.heroResult[BattleSide::DEFENDER].exp = battleResult->exp[BattleSide::DEFENDER];
  330. raccepted.winnerSide = finishingBattle->winnerSide;
  331. gameHandler->sendAndApply(raccepted);
  332. gameHandler->queries->popIfTop(battleQuery); // Workaround to remove battle query for AI case. TODO Think of a cleaner solution.
  333. //--> continuation (battleFinalize) occurs after level-up gameHandler->queries are handled or on removing query
  334. }
  335. void BattleResultProcessor::battleFinalize(const BattleID & battleID, const BattleResult & result)
  336. {
  337. LOG_TRACE(logGlobal);
  338. assert(finishingBattles.count(battleID) != 0);
  339. if(finishingBattles.count(battleID) == 0)
  340. return;
  341. auto & finishingBattle = finishingBattles[battleID];
  342. finishingBattle->remainingBattleQueriesCount--;
  343. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  344. if (finishingBattle->remainingBattleQueriesCount > 0)
  345. //Battle results will be handled when all battle gameHandler->queries are closed
  346. return;
  347. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  348. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  349. // Still, it looks like a hole.
  350. const auto battle = std::find_if(gameHandler->gameState().currentBattles.begin(), gameHandler->gameState().currentBattles.end(),
  351. [battleID](const auto & desiredBattle)
  352. {
  353. return desiredBattle->battleID == battleID;
  354. });
  355. assert(battle != gameHandler->gameState().currentBattles.end());
  356. const auto winnerHero = (*battle)->battleGetFightingHero(finishingBattle->winnerSide);
  357. const auto loserHero = (*battle)->battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  358. BattleResultsApplied resultsApplied;
  359. // Eagle Eye handling
  360. if(!finishingBattle->isDraw() && winnerHero)
  361. {
  362. if(auto eagleEyeLevel = winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT))
  363. {
  364. resultsApplied.learnedSpells.learn = 1;
  365. resultsApplied.learnedSpells.hid = finishingBattle->winnerId;
  366. for(const auto & spellId : (*battle)->getUsedSpells(CBattleInfoEssentials::otherSide(result.winner)))
  367. {
  368. const auto spell = spellId.toEntity(LIBRARY->spells());
  369. if(spell
  370. && spell->getLevel() <= eagleEyeLevel
  371. && !winnerHero->spellbookContainsSpell(spell->getId())
  372. && gameHandler->getRandomGenerator().nextInt(99) < winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE))
  373. {
  374. resultsApplied.learnedSpells.spells.insert(spell->getId());
  375. }
  376. }
  377. }
  378. }
  379. // Moving artifacts handling
  380. if(result.result == EBattleResult::NORMAL && !finishingBattle->isDraw() && winnerHero)
  381. {
  382. CArtifactFittingSet artFittingSet(*winnerHero);
  383. const auto addArtifactToTransfer = [&artFittingSet](BulkMoveArtifacts & pack, const ArtifactPosition & srcSlot, const CArtifactInstance * art)
  384. {
  385. assert(art);
  386. const auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, art->getTypeId());
  387. if(dstSlot != ArtifactPosition::PRE_FIRST)
  388. {
  389. pack.artsPack0.emplace_back(MoveArtifactInfo(srcSlot, dstSlot));
  390. if(ArtifactUtils::isSlotEquipment(dstSlot))
  391. pack.artsPack0.back().askAssemble = true;
  392. artFittingSet.putArtifact(dstSlot, const_cast<CArtifactInstance*>(art));
  393. }
  394. };
  395. if(loserHero)
  396. {
  397. auto & packHero = resultsApplied.movingArtifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  398. packHero.srcArtHolder = finishingBattle->loserId;
  399. for(const auto & slot : ArtifactUtils::commonWornSlots())
  400. {
  401. if(const auto artSlot = loserHero->artifactsWorn.find(slot); artSlot != loserHero->artifactsWorn.end() && ArtifactUtils::isArtRemovable(*artSlot))
  402. {
  403. addArtifactToTransfer(packHero, artSlot->first, artSlot->second.getArt());
  404. }
  405. }
  406. for(const auto & artSlot : loserHero->artifactsInBackpack)
  407. {
  408. if(const auto art = artSlot.getArt(); art->getTypeId() != ArtifactID::GRAIL)
  409. addArtifactToTransfer(packHero, loserHero->getArtPos(art), art);
  410. }
  411. if(loserHero->getCommander())
  412. {
  413. auto & packCommander = resultsApplied.movingArtifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  414. packCommander.srcCreature = loserHero->findStack(loserHero->getCommander());
  415. for(const auto & artSlot : loserHero->getCommander()->artifactsWorn)
  416. addArtifactToTransfer(packCommander, artSlot.first, artSlot.second.getArt());
  417. }
  418. auto armyObj = dynamic_cast<const CArmedInstance*>(gameHandler->gameInfo().getObj(finishingBattle->loserId));
  419. for(const auto & armySlot : armyObj->stacks)
  420. {
  421. auto & packsArmy = resultsApplied.movingArtifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  422. packsArmy.srcArtHolder = armyObj->id;
  423. packsArmy.srcCreature = armySlot.first;
  424. for(const auto & artSlot : armySlot.second->artifactsWorn)
  425. addArtifactToTransfer(packsArmy, artSlot.first, armySlot.second->getArt(artSlot.first));
  426. }
  427. }
  428. }
  429. // Growing artifacts handling
  430. if(!finishingBattle->isDraw() && winnerHero)
  431. {
  432. const auto addArtifactToGrowing = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap)
  433. {
  434. for(const auto & [slot, slotInfo] : artMap)
  435. {
  436. const auto artInst = slotInfo.getArt();
  437. assert(artInst);
  438. if(artInst->getType()->isGrowing())
  439. resultsApplied.growingArtifacts.emplace_back(artInst->getId());
  440. }
  441. };
  442. if(const auto commander = winnerHero->getCommander(); commander && commander->alive)
  443. addArtifactToGrowing(commander->artifactsWorn);
  444. addArtifactToGrowing(winnerHero->artifactsWorn);
  445. }
  446. // Charged artifacts handling
  447. const auto addArtifactToDischarging = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap,
  448. const ObjectInstanceID & id, const std::optional<SlotID> & creature = std::nullopt)
  449. {
  450. for(const auto & [slot, slotInfo] : artMap)
  451. {
  452. auto artInst = slotInfo.getArt();
  453. assert(artInst);
  454. if(const auto condition = artInst->getType()->getDischargeCondition(); condition == DischargeArtifactCondition::BATTLE)
  455. {
  456. auto & discharging = resultsApplied.dischargingArtifacts.emplace_back(artInst->getId(), 1);
  457. discharging.artLoc.emplace(id, creature, slot);
  458. }
  459. }
  460. };
  461. if(winnerHero)
  462. {
  463. addArtifactToDischarging(winnerHero->artifactsWorn, winnerHero->id);
  464. if(const auto commander = winnerHero->getCommander())
  465. addArtifactToDischarging(commander->artifactsWorn, winnerHero->id, winnerHero->findStack(winnerHero->getCommander()));
  466. }
  467. if(loserHero)
  468. {
  469. addArtifactToDischarging(loserHero->artifactsWorn, loserHero->id);
  470. if(const auto commander = loserHero->getCommander())
  471. addArtifactToDischarging(commander->artifactsWorn, loserHero->id, loserHero->findStack(loserHero->getCommander()));
  472. }
  473. // Necromancy handling
  474. // Give raised units to winner, if any were raised, units will be given after casualties are taken
  475. if(winnerHero)
  476. {
  477. resultsApplied.raisedStack = winnerHero->calculateNecromancy(result);
  478. const SlotID necroSlot = resultsApplied.raisedStack.getCreature() ? winnerHero->getSlotFor(resultsApplied.raisedStack.getCreature()) : SlotID();
  479. if(necroSlot != SlotID() && !finishingBattle->isDraw())
  480. gameHandler->addToSlot(StackLocation(finishingBattle->winnerId, necroSlot), resultsApplied.raisedStack.getCreature(), resultsApplied.raisedStack.getCount());
  481. }
  482. resultsApplied.battleID = battleID;
  483. resultsApplied.victor = finishingBattle->victor;
  484. resultsApplied.loser = finishingBattle->loser;
  485. gameHandler->sendAndApply(resultsApplied);
  486. //handle victory/loss of engaged players
  487. gameHandler->checkVictoryLossConditions({finishingBattle->loser, finishingBattle->victor});
  488. // Remove beaten hero
  489. if(loserHero)
  490. {
  491. RemoveObject ro(loserHero->id, finishingBattle->victor);
  492. gameHandler->sendAndApply(ro);
  493. }
  494. // For draw case both heroes should be removed
  495. if(finishingBattle->isDraw() && winnerHero)
  496. {
  497. RemoveObject ro(winnerHero->id, finishingBattle->loser);
  498. gameHandler->sendAndApply(ro);
  499. if(gameHandler->gameInfo().getSettings().getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  500. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, winnerHero);
  501. }
  502. if (result.result == EBattleResult::SURRENDER)
  503. {
  504. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroSurrendered++;
  505. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, loserHero);
  506. }
  507. if (result.result == EBattleResult::ESCAPE)
  508. {
  509. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroEscaped++;
  510. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, loserHero);
  511. }
  512. finishingBattles.erase(battleID);
  513. battleResults.erase(battleID);
  514. }
  515. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, BattleSide victoriusSide)
  516. {
  517. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  518. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  519. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  520. battleResult->battleID = battle.getBattle()->getBattleID();
  521. battleResult->result = resultType;
  522. battleResult->winner = victoriusSide; //surrendering side loses
  523. auto allStacks = battle.battleGetStacksIf([](const CStack * stack){
  524. if (stack->summoned)//don't take into account temporary summoned stacks
  525. return false;
  526. if (stack->isTurret())
  527. return false;
  528. return true;
  529. });
  530. for(const auto & st : allStacks) //setting casualties
  531. {
  532. si32 killed = st->getKilled();
  533. if(killed > 0)
  534. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  535. }
  536. }
  537. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  538. {
  539. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  540. }