BattleInterfaceClasses.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. /*
  2. * BattleInterfaceClasses.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 "BattleInterfaceClasses.h"
  12. #include "BattleInterface.h"
  13. #include "BattleActionsController.h"
  14. #include "BattleRenderer.h"
  15. #include "BattleSiegeController.h"
  16. #include "BattleFieldController.h"
  17. #include "BattleStacksController.h"
  18. #include "BattleWindow.h"
  19. #include "../CGameInfo.h"
  20. #include "../CMusicHandler.h"
  21. #include "../CPlayerInterface.h"
  22. #include "../CVideoHandler.h"
  23. #include "../gui/CursorHandler.h"
  24. #include "../gui/CGuiHandler.h"
  25. #include "../gui/Shortcut.h"
  26. #include "../gui/MouseButton.h"
  27. #include "../gui/WindowHandler.h"
  28. #include "../render/Canvas.h"
  29. #include "../render/IImage.h"
  30. #include "../render/IFont.h"
  31. #include "../render/Graphics.h"
  32. #include "../widgets/Buttons.h"
  33. #include "../widgets/Images.h"
  34. #include "../widgets/TextControls.h"
  35. #include "../widgets/MiscWidgets.h"
  36. #include "../windows/CMessage.h"
  37. #include "../windows/CSpellWindow.h"
  38. #include "../render/CAnimation.h"
  39. #include "../render/IRenderHandler.h"
  40. #include "../adventureMap/CInGameConsole.h"
  41. #include "../../CCallback.h"
  42. #include "../../lib/CStack.h"
  43. #include "../../lib/CConfigHandler.h"
  44. #include "../../lib/CCreatureHandler.h"
  45. #include "../../lib/gameState/InfoAboutArmy.h"
  46. #include "../../lib/CGeneralTextHandler.h"
  47. #include "../../lib/CTownHandler.h"
  48. #include "../../lib/CHeroHandler.h"
  49. #include "../../lib/StartInfo.h"
  50. #include "../../lib/CondSh.h"
  51. #include "../../lib/mapObjects/CGTownInstance.h"
  52. #include "../../lib/networkPacks/PacksForClientBattle.h"
  53. #include "../../lib/TextOperations.h"
  54. void BattleConsole::showAll(Canvas & to)
  55. {
  56. CIntObject::showAll(to);
  57. Point line1 (pos.x + pos.w/2, pos.y + 8);
  58. Point line2 (pos.x + pos.w/2, pos.y + 24);
  59. auto visibleText = getVisibleText();
  60. if(visibleText.size() > 0)
  61. to.drawText(line1, FONT_SMALL, Colors::WHITE, ETextAlignment::CENTER, visibleText[0]);
  62. if(visibleText.size() > 1)
  63. to.drawText(line2, FONT_SMALL, Colors::WHITE, ETextAlignment::CENTER, visibleText[1]);
  64. }
  65. std::vector<std::string> BattleConsole::getVisibleText()
  66. {
  67. // high priority texts that hide battle log entries
  68. for(const auto & text : {consoleText, hoverText})
  69. {
  70. if (text.empty())
  71. continue;
  72. auto result = CMessage::breakText(text, pos.w, FONT_SMALL);
  73. if(result.size() > 2)
  74. result.resize(2);
  75. return result;
  76. }
  77. // log is small enough to fit entirely - display it as such
  78. if (logEntries.size() < 3)
  79. return logEntries;
  80. return { logEntries[scrollPosition - 1], logEntries[scrollPosition] };
  81. }
  82. std::vector<std::string> BattleConsole::splitText(const std::string &text)
  83. {
  84. std::vector<std::string> lines;
  85. std::vector<std::string> output;
  86. boost::split(lines, text, boost::is_any_of("\n"));
  87. for(const auto & line : lines)
  88. {
  89. if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w)
  90. {
  91. output.push_back(line);
  92. }
  93. else
  94. {
  95. std::vector<std::string> substrings = CMessage::breakText(line, pos.w, FONT_SMALL);
  96. output.insert(output.end(), substrings.begin(), substrings.end());
  97. }
  98. }
  99. return output;
  100. }
  101. bool BattleConsole::addText(const std::string & text)
  102. {
  103. logGlobal->trace("CBattleConsole message: %s", text);
  104. auto newLines = splitText(text);
  105. logEntries.insert(logEntries.end(), newLines.begin(), newLines.end());
  106. scrollPosition = (int)logEntries.size()-1;
  107. redraw();
  108. return true;
  109. }
  110. void BattleConsole::scrollUp(ui32 by)
  111. {
  112. if(scrollPosition > static_cast<int>(by))
  113. scrollPosition -= by;
  114. redraw();
  115. }
  116. void BattleConsole::scrollDown(ui32 by)
  117. {
  118. if(scrollPosition + by < logEntries.size())
  119. scrollPosition += by;
  120. redraw();
  121. }
  122. BattleConsole::BattleConsole(std::shared_ptr<CPicture> backgroundSource, const Point & objectPos, const Point & imagePos, const Point &size)
  123. : scrollPosition(-1)
  124. , enteringText(false)
  125. {
  126. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  127. pos += objectPos;
  128. pos.w = size.x;
  129. pos.h = size.y;
  130. background = std::make_shared<CPicture>(backgroundSource->getSurface(), Rect(imagePos, size), 0, 0 );
  131. }
  132. void BattleConsole::deactivate()
  133. {
  134. if (enteringText)
  135. LOCPLINT->cingconsole->endEnteringText(false);
  136. CIntObject::deactivate();
  137. }
  138. void BattleConsole::setEnteringMode(bool on)
  139. {
  140. consoleText.clear();
  141. if (on)
  142. {
  143. assert(enteringText == false);
  144. GH.startTextInput(pos);
  145. }
  146. else
  147. {
  148. assert(enteringText == true);
  149. GH.stopTextInput();
  150. }
  151. enteringText = on;
  152. redraw();
  153. }
  154. void BattleConsole::setEnteredText(const std::string & text)
  155. {
  156. assert(enteringText == true);
  157. consoleText = text;
  158. redraw();
  159. }
  160. void BattleConsole::write(const std::string & Text)
  161. {
  162. hoverText = Text;
  163. redraw();
  164. }
  165. void BattleConsole::clearIfMatching(const std::string & Text)
  166. {
  167. if (hoverText == Text)
  168. clear();
  169. }
  170. void BattleConsole::clear()
  171. {
  172. write({});
  173. }
  174. const CGHeroInstance * BattleHero::instance()
  175. {
  176. return hero;
  177. }
  178. void BattleHero::tick(uint32_t msPassed)
  179. {
  180. size_t groupIndex = static_cast<size_t>(phase);
  181. float timePassed = msPassed / 1000.f;
  182. flagCurrentFrame += currentSpeed * timePassed;
  183. currentFrame += currentSpeed * timePassed;
  184. if(flagCurrentFrame >= flagAnimation->size(0))
  185. flagCurrentFrame -= flagAnimation->size(0);
  186. if(currentFrame >= animation->size(groupIndex))
  187. {
  188. currentFrame -= animation->size(groupIndex);
  189. switchToNextPhase();
  190. }
  191. }
  192. void BattleHero::render(Canvas & canvas)
  193. {
  194. size_t groupIndex = static_cast<size_t>(phase);
  195. auto flagFrame = flagAnimation->getImage(flagCurrentFrame, 0, true);
  196. auto heroFrame = animation->getImage(currentFrame, groupIndex, true);
  197. Point heroPosition = pos.center() - parent->pos.topLeft() - heroFrame->dimensions() / 2;
  198. Point flagPosition = pos.center() - parent->pos.topLeft() - flagFrame->dimensions() / 2;
  199. if(defender)
  200. flagPosition += Point(-4, -41);
  201. else
  202. flagPosition += Point(4, -41);
  203. canvas.draw(flagFrame, flagPosition);
  204. canvas.draw(heroFrame, heroPosition);
  205. }
  206. void BattleHero::pause()
  207. {
  208. currentSpeed = 0.f;
  209. }
  210. void BattleHero::play()
  211. {
  212. //H3 speed: 10 fps ( 100 ms per frame)
  213. currentSpeed = 10.f;
  214. }
  215. float BattleHero::getFrame() const
  216. {
  217. return currentFrame;
  218. }
  219. void BattleHero::collectRenderableObjects(BattleRenderer & renderer)
  220. {
  221. auto hex = defender ? BattleHex(GameConstants::BFIELD_WIDTH-1) : BattleHex(0);
  222. renderer.insert(EBattleFieldLayer::HEROES, hex, [this](BattleRenderer::RendererRef canvas)
  223. {
  224. render(canvas);
  225. });
  226. }
  227. void BattleHero::onPhaseFinished(const std::function<void()> & callback)
  228. {
  229. phaseFinishedCallback = callback;
  230. }
  231. void BattleHero::setPhase(EHeroAnimType newPhase)
  232. {
  233. nextPhase = newPhase;
  234. switchToNextPhase(); //immediately switch to next phase and then restore idling phase
  235. nextPhase = EHeroAnimType::HOLDING;
  236. }
  237. void BattleHero::heroLeftClicked()
  238. {
  239. if(owner.actionsController->spellcastingModeActive()) //we are casting a spell
  240. return;
  241. if(!hero || !owner.makingTurn())
  242. return;
  243. if(owner.getBattle()->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK) //check conditions
  244. {
  245. CCS->curh->set(Cursor::Map::POINTER);
  246. GH.windows().createAndPushWindow<CSpellWindow>(hero, owner.getCurrentPlayerInterface());
  247. }
  248. }
  249. void BattleHero::heroRightClicked()
  250. {
  251. if(settings["battle"]["stickyHeroInfoWindows"].Bool())
  252. return;
  253. Point windowPosition;
  254. if(GH.screenDimensions().x < 1000)
  255. {
  256. windowPosition.x = (!defender) ? owner.fieldController->pos.left() + 1 : owner.fieldController->pos.right() - 79;
  257. windowPosition.y = owner.fieldController->pos.y + 135;
  258. }
  259. else
  260. {
  261. windowPosition.x = (!defender) ? owner.fieldController->pos.left() - 93 : owner.fieldController->pos.right() + 15;
  262. windowPosition.y = owner.fieldController->pos.y;
  263. }
  264. InfoAboutHero targetHero;
  265. if(owner.makingTurn() || settings["session"]["spectate"].Bool())
  266. {
  267. auto h = defender ? owner.defendingHeroInstance : owner.attackingHeroInstance;
  268. targetHero.initFromHero(h, InfoAboutHero::EInfoLevel::INBATTLE);
  269. GH.windows().createAndPushWindow<HeroInfoWindow>(targetHero, &windowPosition);
  270. }
  271. }
  272. void BattleHero::switchToNextPhase()
  273. {
  274. phase = nextPhase;
  275. currentFrame = 0.f;
  276. auto copy = phaseFinishedCallback;
  277. phaseFinishedCallback.clear();
  278. copy();
  279. }
  280. BattleHero::BattleHero(const BattleInterface & owner, const CGHeroInstance * hero, bool defender):
  281. defender(defender),
  282. hero(hero),
  283. owner(owner),
  284. phase(EHeroAnimType::HOLDING),
  285. nextPhase(EHeroAnimType::HOLDING),
  286. currentSpeed(0.f),
  287. currentFrame(0.f),
  288. flagCurrentFrame(0.f)
  289. {
  290. AnimationPath animationPath;
  291. if(!hero->type->battleImage.empty())
  292. animationPath = hero->type->battleImage;
  293. else
  294. if(hero->gender == EHeroGender::FEMALE)
  295. animationPath = hero->type->heroClass->imageBattleFemale;
  296. else
  297. animationPath = hero->type->heroClass->imageBattleMale;
  298. animation = GH.renderHandler().loadAnimation(animationPath);
  299. animation->preload();
  300. pos.w = 64;
  301. pos.h = 136;
  302. pos.x = owner.fieldController->pos.x + (defender ? (owner.fieldController->pos.w - pos.w) : 0);
  303. pos.y = owner.fieldController->pos.y;
  304. if(defender)
  305. animation->verticalFlip();
  306. if(defender)
  307. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGR"));
  308. else
  309. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGL"));
  310. flagAnimation->preload();
  311. flagAnimation->playerColored(hero->tempOwner);
  312. switchToNextPhase();
  313. play();
  314. addUsedEvents(TIME);
  315. }
  316. HeroInfoBasicPanel::HeroInfoBasicPanel(const InfoAboutHero & hero, Point * position, bool initializeBackground)
  317. : CIntObject(0)
  318. {
  319. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  320. if (position != nullptr)
  321. moveTo(*position);
  322. if(initializeBackground)
  323. {
  324. background = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  325. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  326. background->colorize(hero.owner);
  327. }
  328. initializeData(hero);
  329. }
  330. void HeroInfoBasicPanel::initializeData(const InfoAboutHero & hero)
  331. {
  332. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  333. auto attack = hero.details->primskills[0];
  334. auto defense = hero.details->primskills[1];
  335. auto power = hero.details->primskills[2];
  336. auto knowledge = hero.details->primskills[3];
  337. auto morale = hero.details->morale;
  338. auto luck = hero.details->luck;
  339. auto currentSpellPoints = hero.details->mana;
  340. auto maxSpellPoints = hero.details->manaLimit;
  341. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), hero.getIconIndex(), 0, 10, 6));
  342. //primary stats
  343. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  344. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  345. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
  346. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
  347. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
  348. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
  349. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
  350. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
  351. //morale+luck
  352. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  353. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  354. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  355. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  356. //spell points
  357. labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
  358. labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
  359. }
  360. void HeroInfoBasicPanel::update(const InfoAboutHero & updatedInfo)
  361. {
  362. icons.clear();
  363. labels.clear();
  364. initializeData(updatedInfo);
  365. }
  366. void HeroInfoBasicPanel::show(Canvas & to)
  367. {
  368. showAll(to);
  369. CIntObject::show(to);
  370. }
  371. HeroInfoWindow::HeroInfoWindow(const InfoAboutHero & hero, Point * position)
  372. : CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, ImagePath::builtin("CHRPOP"))
  373. {
  374. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  375. if (position != nullptr)
  376. moveTo(*position);
  377. background->colorize(hero.owner); //maybe add this functionality to base class?
  378. content = std::make_shared<HeroInfoBasicPanel>(hero, nullptr, false);
  379. }
  380. BattleResultWindow::BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner, bool allowReplay)
  381. : owner(_owner), currentVideo(BattleResultVideo::NONE)
  382. {
  383. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  384. background = std::make_shared<CPicture>(ImagePath::builtin("CPRESULT"));
  385. background->colorize(owner.playerID);
  386. pos = center(background->pos);
  387. exit = std::make_shared<CButton>(Point(384, 505), AnimationPath::builtin("iok6432.def"), std::make_pair("", ""), [&](){ bExitf();}, EShortcut::GLOBAL_ACCEPT);
  388. exit->setBorderColor(Colors::METALLIC_GOLD);
  389. if(allowReplay || owner.cb->getStartInfo()->extraOptionsInfo.unlimitedReplay)
  390. {
  391. repeat = std::make_shared<CButton>(Point(24, 505), AnimationPath::builtin("icn6432.def"), std::make_pair("", ""), [&](){ bRepeatf();}, EShortcut::GLOBAL_CANCEL);
  392. repeat->setBorderColor(Colors::METALLIC_GOLD);
  393. labels.push_back(std::make_shared<CLabel>(232, 520, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("vcmi.battleResultsWindow.applyResultsLabel")));
  394. }
  395. if(br.winner == 0) //attacker won
  396. {
  397. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  398. }
  399. else
  400. {
  401. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  402. }
  403. if(br.winner == 1)
  404. {
  405. labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  406. }
  407. else
  408. {
  409. labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  410. }
  411. labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[407]));
  412. labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
  413. labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
  414. std::string sideNames[2] = {"N/A", "N/A"};
  415. for(int i = 0; i < 2; i++)
  416. {
  417. auto heroInfo = owner.cb->getBattle(br.battleID)->battleGetHeroInfo(i);
  418. const int xs[] = {21, 392};
  419. if(heroInfo.portraitSource.isValid()) //attacking hero
  420. {
  421. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), heroInfo.getIconIndex(), 0, xs[i], 38));
  422. sideNames[i] = heroInfo.name;
  423. }
  424. else
  425. {
  426. auto stacks = owner.cb->getBattle(br.battleID)->battleGetAllStacks();
  427. vstd::erase_if(stacks, [i](const CStack * stack) //erase stack of other side and not coming from garrison
  428. {
  429. return stack->unitSide() != i || !stack->base;
  430. });
  431. auto best = vstd::maxElementByFun(stacks, [](const CStack * stack)
  432. {
  433. return stack->unitType()->getAIValue();
  434. });
  435. if(best != stacks.end()) //should be always but to be safe...
  436. {
  437. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), (*best)->unitType()->getIconIndex(), 0, xs[i], 38));
  438. sideNames[i] = (*best)->unitType()->getNamePluralTranslated();
  439. }
  440. }
  441. }
  442. //printing attacker and defender's names
  443. labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, sideNames[0]));
  444. labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
  445. //printing casualties
  446. for(int step = 0; step < 2; ++step)
  447. {
  448. if(br.casualties[step].size()==0)
  449. {
  450. labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
  451. }
  452. else
  453. {
  454. int xPos = 235 - ((int)br.casualties[step].size()*32 + ((int)br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  455. int yPos = 344 + step * 97;
  456. for(auto & elem : br.casualties[step])
  457. {
  458. auto creature = CGI->creatures()->getByIndex(elem.first);
  459. if (creature->getId() == CreatureID::ARROW_TOWERS )
  460. continue; // do not show destroyed towers in battle results
  461. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature->getIconIndex(), 0, xPos, yPos));
  462. std::ostringstream amount;
  463. amount<<elem.second;
  464. labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, amount.str()));
  465. xPos += 42;
  466. }
  467. }
  468. }
  469. //printing result description
  470. bool weAreAttacker = !(owner.cb->getBattle(br.battleID)->battleGetMySide());
  471. if((br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker)) //we've won
  472. {
  473. int text = 304;
  474. currentVideo = BattleResultVideo::WIN;
  475. switch(br.result)
  476. {
  477. case EBattleResult::NORMAL:
  478. if(owner.cb->getBattle(br.battleID)->battleGetDefendedTown() && !weAreAttacker)
  479. currentVideo = BattleResultVideo::WIN_SIEGE;
  480. break;
  481. case EBattleResult::ESCAPE:
  482. text = 303;
  483. break;
  484. case EBattleResult::SURRENDER:
  485. text = 302;
  486. break;
  487. default:
  488. logGlobal->error("Invalid battle result code %d. Assumed normal.", static_cast<int>(br.result));
  489. break;
  490. }
  491. playVideo();
  492. std::string str = CGI->generaltexth->allTexts[text];
  493. const CGHeroInstance * ourHero = owner.cb->getBattle(br.battleID)->battleGetMyHero();
  494. if (ourHero)
  495. {
  496. str += CGI->generaltexth->allTexts[305];
  497. boost::algorithm::replace_first(str, "%s", ourHero->getNameTranslated());
  498. boost::algorithm::replace_first(str, "%d", std::to_string(br.exp[weAreAttacker ? 0 : 1]));
  499. }
  500. description = std::make_shared<CTextBox>(str, Rect(69, 203, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  501. }
  502. else // we lose
  503. {
  504. int text = 311;
  505. currentVideo = BattleResultVideo::DEFEAT;
  506. switch(br.result)
  507. {
  508. case EBattleResult::NORMAL:
  509. if(owner.cb->getBattle(br.battleID)->battleGetDefendedTown() && !weAreAttacker)
  510. currentVideo = BattleResultVideo::DEFEAT_SIEGE;
  511. break;
  512. case EBattleResult::ESCAPE:
  513. currentVideo = BattleResultVideo::RETREAT;
  514. text = 310;
  515. break;
  516. case EBattleResult::SURRENDER:
  517. currentVideo = BattleResultVideo::SURRENDER;
  518. text = 309;
  519. break;
  520. default:
  521. logGlobal->error("Invalid battle result code %d. Assumed normal.", static_cast<int>(br.result));
  522. break;
  523. }
  524. playVideo();
  525. labels.push_back(std::make_shared<CLabel>(235, 235, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[text]));
  526. }
  527. }
  528. void BattleResultWindow::activate()
  529. {
  530. owner.showingDialog->set(true);
  531. CIntObject::activate();
  532. }
  533. void BattleResultWindow::show(Canvas & to)
  534. {
  535. CIntObject::show(to);
  536. CCS->videoh->update(pos.x + 107, pos.y + 70, to.getInternalSurface(), true, false,
  537. [&]()
  538. {
  539. playVideo(true);
  540. });
  541. }
  542. void BattleResultWindow::playVideo(bool startLoop)
  543. {
  544. AudioPath musicName = AudioPath();
  545. VideoPath videoName = VideoPath();
  546. if(!startLoop)
  547. {
  548. switch(currentVideo)
  549. {
  550. case BattleResultVideo::WIN:
  551. musicName = AudioPath::builtin("Music/Win Battle");
  552. videoName = VideoPath::builtin("WIN3.BIK");
  553. break;
  554. case BattleResultVideo::SURRENDER:
  555. musicName = AudioPath::builtin("Music/Surrender Battle");
  556. videoName = VideoPath::builtin("SURRENDER.BIK");
  557. break;
  558. case BattleResultVideo::RETREAT:
  559. musicName = AudioPath::builtin("Music/Retreat Battle");
  560. videoName = VideoPath::builtin("RTSTART.BIK");
  561. break;
  562. case BattleResultVideo::DEFEAT:
  563. musicName = AudioPath::builtin("Music/LoseCombat");
  564. videoName = VideoPath::builtin("LBSTART.BIK");
  565. break;
  566. case BattleResultVideo::DEFEAT_SIEGE:
  567. musicName = AudioPath::builtin("Music/LoseCastle");
  568. videoName = VideoPath::builtin("LOSECSTL.BIK");
  569. break;
  570. case BattleResultVideo::WIN_SIEGE:
  571. musicName = AudioPath::builtin("Music/Defend Castle");
  572. videoName = VideoPath::builtin("DEFENDALL.BIK");
  573. break;
  574. }
  575. }
  576. else
  577. {
  578. switch(currentVideo)
  579. {
  580. case BattleResultVideo::RETREAT:
  581. currentVideo = BattleResultVideo::RETREAT_LOOP;
  582. videoName = VideoPath::builtin("RTLOOP.BIK");
  583. break;
  584. case BattleResultVideo::DEFEAT:
  585. currentVideo = BattleResultVideo::DEFEAT_LOOP;
  586. videoName = VideoPath::builtin("LBLOOP.BIK");
  587. break;
  588. case BattleResultVideo::DEFEAT_SIEGE:
  589. currentVideo = BattleResultVideo::DEFEAT_SIEGE_LOOP;
  590. videoName = VideoPath::builtin("LOSECSLP.BIK");
  591. break;
  592. case BattleResultVideo::WIN_SIEGE:
  593. currentVideo = BattleResultVideo::WIN_SIEGE_LOOP;
  594. videoName = VideoPath::builtin("DEFENDLOOP.BIK");
  595. break;
  596. }
  597. }
  598. if(musicName != AudioPath())
  599. CCS->musich->playMusic(musicName, false, true);
  600. if(videoName != VideoPath())
  601. CCS->videoh->open(videoName);
  602. }
  603. void BattleResultWindow::buttonPressed(int button)
  604. {
  605. if (resultCallback)
  606. resultCallback(button);
  607. CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
  608. close();
  609. if(GH.windows().topWindow<BattleWindow>())
  610. GH.windows().popWindows(1); //pop battle interface if present
  611. //Result window and battle interface are gone. We requested all dialogs to be closed before opening the battle,
  612. //so we can be sure that there is no dialogs left on GUI stack.
  613. intTmp.showingDialog->setn(false);
  614. CCS->videoh->close();
  615. }
  616. void BattleResultWindow::bExitf()
  617. {
  618. buttonPressed(0);
  619. }
  620. void BattleResultWindow::bRepeatf()
  621. {
  622. buttonPressed(1);
  623. }
  624. StackQueue::StackQueue(bool Embedded, BattleInterface & owner)
  625. : embedded(Embedded),
  626. owner(owner)
  627. {
  628. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  629. if(embedded)
  630. {
  631. pos.w = QUEUE_SIZE * 41;
  632. pos.h = 49;
  633. pos.x += parent->pos.w/2 - pos.w/2;
  634. pos.y += 10;
  635. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("CPRSMALL"));
  636. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  637. }
  638. else
  639. {
  640. pos.w = 800;
  641. pos.h = 85;
  642. pos.x += 0;
  643. pos.y -= pos.h;
  644. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  645. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("TWCRPORT"));
  646. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  647. //TODO: where use big icons?
  648. //stateIcons = GH.renderHandler().loadAnimation("VCMI/BATTLEQUEUE/STATESBIG");
  649. }
  650. stateIcons->preload();
  651. stackBoxes.resize(QUEUE_SIZE);
  652. for (int i = 0; i < stackBoxes.size(); i++)
  653. {
  654. stackBoxes[i] = std::make_shared<StackBox>(this);
  655. stackBoxes[i]->moveBy(Point(1 + (embedded ? 41 : 80) * i, 0));
  656. }
  657. }
  658. void StackQueue::show(Canvas & to)
  659. {
  660. if (embedded)
  661. showAll(to);
  662. CIntObject::show(to);
  663. }
  664. void StackQueue::update()
  665. {
  666. std::vector<battle::Units> queueData;
  667. owner.getBattle()->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
  668. size_t boxIndex = 0;
  669. ui32 tmpTurn = -1;
  670. for(size_t turn = 0; turn < queueData.size() && boxIndex < stackBoxes.size(); turn++)
  671. {
  672. for(size_t unitIndex = 0; unitIndex < queueData[turn].size() && boxIndex < stackBoxes.size(); boxIndex++, unitIndex++)
  673. {
  674. ui32 currentTurn = owner.round + turn;
  675. stackBoxes[boxIndex]->setUnit(queueData[turn][unitIndex], turn, tmpTurn != currentTurn && owner.round != 0 && (!embedded || tmpTurn != -1) ? (std::optional<ui32>)currentTurn : std::nullopt);
  676. tmpTurn = currentTurn;
  677. }
  678. }
  679. for(; boxIndex < stackBoxes.size(); boxIndex++)
  680. stackBoxes[boxIndex]->setUnit(nullptr);
  681. }
  682. int32_t StackQueue::getSiegeShooterIconID()
  683. {
  684. return owner.siegeController->getSiegedTown()->town->faction->getIndex();
  685. }
  686. std::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const
  687. {
  688. for(const auto & stackBox : stackBoxes)
  689. {
  690. if(stackBox->isHovered())
  691. {
  692. return stackBox->getBoundUnitID();
  693. }
  694. }
  695. return std::nullopt;
  696. }
  697. StackQueue::StackBox::StackBox(StackQueue * owner):
  698. CIntObject(SHOW_POPUP | HOVER), owner(owner)
  699. {
  700. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  701. background = std::make_shared<CPicture>(ImagePath::builtin(owner->embedded ? "StackQueueSmall" : "StackQueueLarge"));
  702. pos.w = background->pos.w;
  703. pos.h = background->pos.h;
  704. if(owner->embedded)
  705. {
  706. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 5, 2);
  707. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  708. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 2, 48), ColorRGBA(0, 0, 0, 255), ColorRGBA(0, 255, 0, 255));
  709. }
  710. else
  711. {
  712. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 9, 1);
  713. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
  714. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 15, 18), ColorRGBA(0, 0, 0, 255), ColorRGBA(241, 216, 120, 255));
  715. round = std::make_shared<CLabel>(4, 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
  716. int icon_x = pos.w - 17;
  717. int icon_y = pos.h - 18;
  718. stateIcon = std::make_shared<CAnimImage>(owner->stateIcons, 0, 0, icon_x, icon_y);
  719. stateIcon->visible = false;
  720. }
  721. roundRect->disable();
  722. }
  723. void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn, std::optional<ui32> currentTurn)
  724. {
  725. if(unit)
  726. {
  727. boundUnitID = unit->unitId();
  728. background->colorize(unit->unitOwner());
  729. icon->visible = true;
  730. // temporary code for mod compatibility:
  731. // first, set icon that should definitely exist (arrow tower icon in base vcmi mod)
  732. // second, try to switch to icon that should be provided by mod
  733. // if mod is not up to date and does have arrow tower icon yet - second setFrame call will fail and retain previously set image
  734. // for 1.2 release & later next line should be moved into 'else' block
  735. icon->setFrame(unit->creatureIconIndex(), 0);
  736. if (unit->unitType()->getId() == CreatureID::ARROW_TOWERS)
  737. icon->setFrame(owner->getSiegeShooterIconID(), 1);
  738. amount->setText(TextOperations::formatMetric(unit->getCount(), 4));
  739. if(currentTurn && !owner->embedded)
  740. {
  741. std::string tmp = std::to_string(*currentTurn);
  742. int len = graphics->fonts[FONT_SMALL]->getStringWidth(tmp);
  743. roundRect->pos.w = len + 6;
  744. round->setText(tmp);
  745. }
  746. roundRect->setEnabled(currentTurn.has_value());
  747. if(!owner->embedded)
  748. round->setEnabled(currentTurn.has_value());
  749. if(stateIcon)
  750. {
  751. if(unit->defended((int)turn) || (turn > 0 && unit->defended((int)turn - 1)))
  752. {
  753. stateIcon->setFrame(0, 0);
  754. stateIcon->visible = true;
  755. }
  756. else if(unit->waited((int)turn))
  757. {
  758. stateIcon->setFrame(1, 0);
  759. stateIcon->visible = true;
  760. }
  761. else
  762. {
  763. stateIcon->visible = false;
  764. }
  765. }
  766. }
  767. else
  768. {
  769. boundUnitID = std::nullopt;
  770. background->colorize(PlayerColor::NEUTRAL);
  771. icon->visible = false;
  772. icon->setFrame(0);
  773. amount->setText("");
  774. if(stateIcon)
  775. stateIcon->visible = false;
  776. }
  777. }
  778. std::optional<uint32_t> StackQueue::StackBox::getBoundUnitID() const
  779. {
  780. return boundUnitID;
  781. }
  782. bool StackQueue::StackBox::isBoundUnitHighlighted() const
  783. {
  784. auto unitIdsToHighlight = owner->owner.stacksController->getHoveredStacksUnitIds();
  785. return vstd::contains(unitIdsToHighlight, getBoundUnitID());
  786. }
  787. void StackQueue::StackBox::showAll(Canvas & to)
  788. {
  789. CIntObject::showAll(to);
  790. if(isBoundUnitHighlighted())
  791. to.drawBorder(background->pos, Colors::CYAN, 2);
  792. }
  793. void StackQueue::StackBox::show(Canvas & to)
  794. {
  795. CIntObject::show(to);
  796. if(isBoundUnitHighlighted())
  797. to.drawBorder(background->pos, Colors::CYAN, 2);
  798. }