BattleInterfaceClasses.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 "../CPlayerInterface.h"
  21. #include "../gui/CursorHandler.h"
  22. #include "../gui/CGuiHandler.h"
  23. #include "../gui/Shortcut.h"
  24. #include "../gui/MouseButton.h"
  25. #include "../gui/WindowHandler.h"
  26. #include "../media/IMusicPlayer.h"
  27. #include "../render/Canvas.h"
  28. #include "../render/IImage.h"
  29. #include "../render/IFont.h"
  30. #include "../render/Graphics.h"
  31. #include "../widgets/Buttons.h"
  32. #include "../widgets/CComponent.h"
  33. #include "../widgets/Images.h"
  34. #include "../widgets/Slider.h"
  35. #include "../widgets/TextControls.h"
  36. #include "../widgets/VideoWidget.h"
  37. #include "../widgets/GraphicalPrimitiveCanvas.h"
  38. #include "../windows/CMessage.h"
  39. #include "../windows/CCreatureWindow.h"
  40. #include "../windows/CSpellWindow.h"
  41. #include "../windows/InfoWindows.h"
  42. #include "../render/CAnimation.h"
  43. #include "../render/IRenderHandler.h"
  44. #include "../adventureMap/CInGameConsole.h"
  45. #include "../eventsSDL/InputHandler.h"
  46. #include "../../CCallback.h"
  47. #include "../../lib/CStack.h"
  48. #include "../../lib/CConfigHandler.h"
  49. #include "../../lib/CCreatureHandler.h"
  50. #include "../../lib/gameState/InfoAboutArmy.h"
  51. #include "../../lib/CGeneralTextHandler.h"
  52. #include "../../lib/CTownHandler.h"
  53. #include "../../lib/CHeroHandler.h"
  54. #include "../../lib/StartInfo.h"
  55. #include "../../lib/mapObjects/CGTownInstance.h"
  56. #include "../../lib/networkPacks/PacksForClientBattle.h"
  57. #include "../../lib/TextOperations.h"
  58. #include "../../lib/json/JsonUtils.h"
  59. void BattleConsole::showAll(Canvas & to)
  60. {
  61. CIntObject::showAll(to);
  62. Point line1 (pos.x + pos.w/2, pos.y + 8);
  63. Point line2 (pos.x + pos.w/2, pos.y + 24);
  64. auto visibleText = getVisibleText();
  65. if(visibleText.size() > 0)
  66. to.drawText(line1, FONT_SMALL, Colors::WHITE, ETextAlignment::CENTER, visibleText[0]);
  67. if(visibleText.size() > 1)
  68. to.drawText(line2, FONT_SMALL, Colors::WHITE, ETextAlignment::CENTER, visibleText[1]);
  69. }
  70. std::vector<std::string> BattleConsole::getVisibleText() const
  71. {
  72. // high priority texts that hide battle log entries
  73. for(const auto & text : {consoleText, hoverText})
  74. {
  75. if (text.empty())
  76. continue;
  77. auto result = CMessage::breakText(text, pos.w, FONT_SMALL);
  78. if(result.size() > 2 && text.find('\n') != std::string::npos)
  79. {
  80. // Text has too many lines to fit into console, but has line breaks. Try ignore them and fit text that way
  81. std::string cleanText = boost::algorithm::replace_all_copy(text, "\n", " ");
  82. result = CMessage::breakText(cleanText, pos.w, FONT_SMALL);
  83. }
  84. if(result.size() > 2)
  85. result.resize(2);
  86. return result;
  87. }
  88. // log is small enough to fit entirely - display it as such
  89. if (logEntries.size() < 3)
  90. return logEntries;
  91. return { logEntries[scrollPosition - 1], logEntries[scrollPosition] };
  92. }
  93. std::vector<std::string> BattleConsole::splitText(const std::string &text)
  94. {
  95. std::vector<std::string> lines;
  96. std::vector<std::string> output;
  97. boost::split(lines, text, boost::is_any_of("\n"));
  98. for(const auto & line : lines)
  99. {
  100. if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w)
  101. {
  102. output.push_back(line);
  103. }
  104. else
  105. {
  106. std::vector<std::string> substrings = CMessage::breakText(line, pos.w, FONT_SMALL);
  107. output.insert(output.end(), substrings.begin(), substrings.end());
  108. }
  109. }
  110. return output;
  111. }
  112. bool BattleConsole::addText(const std::string & text)
  113. {
  114. logGlobal->trace("CBattleConsole message: %s", text);
  115. auto newLines = splitText(text);
  116. logEntries.insert(logEntries.end(), newLines.begin(), newLines.end());
  117. scrollPosition = (int)logEntries.size()-1;
  118. redraw();
  119. return true;
  120. }
  121. void BattleConsole::scrollUp(ui32 by)
  122. {
  123. if(scrollPosition > static_cast<int>(by))
  124. scrollPosition -= by;
  125. redraw();
  126. }
  127. void BattleConsole::scrollDown(ui32 by)
  128. {
  129. if(scrollPosition + by < logEntries.size())
  130. scrollPosition += by;
  131. redraw();
  132. }
  133. BattleConsole::BattleConsole(const BattleInterface & owner, std::shared_ptr<CPicture> backgroundSource, const Point & objectPos, const Point & imagePos, const Point &size)
  134. : CIntObject(LCLICK)
  135. , owner(owner)
  136. , scrollPosition(-1)
  137. , enteringText(false)
  138. {
  139. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  140. pos += objectPos;
  141. pos.w = size.x;
  142. pos.h = size.y;
  143. background = std::make_shared<CPicture>(backgroundSource->getSurface(), Rect(imagePos, size), 0, 0 );
  144. }
  145. void BattleConsole::deactivate()
  146. {
  147. if (enteringText)
  148. LOCPLINT->cingconsole->endEnteringText(false);
  149. CIntObject::deactivate();
  150. }
  151. void BattleConsole::clickPressed(const Point & cursorPosition)
  152. {
  153. if(owner.makingTurn() && !owner.openingPlaying())
  154. {
  155. GH.windows().createAndPushWindow<BattleConsoleWindow>(boost::algorithm::join(logEntries, "\n"));
  156. }
  157. }
  158. void BattleConsole::setEnteringMode(bool on)
  159. {
  160. consoleText.clear();
  161. if (on)
  162. {
  163. assert(enteringText == false);
  164. GH.startTextInput(pos);
  165. }
  166. else
  167. {
  168. assert(enteringText == true);
  169. GH.stopTextInput();
  170. }
  171. enteringText = on;
  172. redraw();
  173. }
  174. void BattleConsole::setEnteredText(const std::string & text)
  175. {
  176. assert(enteringText == true);
  177. consoleText = text;
  178. redraw();
  179. }
  180. void BattleConsole::write(const std::string & Text)
  181. {
  182. hoverText = Text;
  183. redraw();
  184. }
  185. void BattleConsole::clearIfMatching(const std::string & Text)
  186. {
  187. if (hoverText == Text)
  188. clear();
  189. }
  190. void BattleConsole::clear()
  191. {
  192. write({});
  193. }
  194. BattleConsoleWindow::BattleConsoleWindow(const std::string & text)
  195. : CWindowObject(BORDERED)
  196. {
  197. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  198. pos.w = 429;
  199. pos.h = 434;
  200. updateShadow();
  201. center();
  202. backgroundTexture = std::make_shared<CFilledTexture>(ImagePath::builtin("DiBoxBck"), Rect(0, 0, pos.w, pos.h));
  203. buttonOk = std::make_shared<CButton>(Point(183, 388), AnimationPath::builtin("IOKAY"), CButton::tooltip(), [this](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  204. Rect textArea(18, 17, 393, 354);
  205. textBoxBackgroundBorder = std::make_shared<TransparentFilledRectangle>(textArea, ColorRGBA(0, 0, 0, 75), ColorRGBA(128, 100, 75));
  206. textBox = std::make_shared<CTextBox>(text, textArea.resize(-5), CSlider::BROWN);
  207. if(textBox->slider)
  208. textBox->slider->scrollToMax();
  209. }
  210. const CGHeroInstance * BattleHero::instance()
  211. {
  212. return hero;
  213. }
  214. void BattleHero::tick(uint32_t msPassed)
  215. {
  216. size_t groupIndex = static_cast<size_t>(phase);
  217. float timePassed = msPassed / 1000.f;
  218. flagCurrentFrame += currentSpeed * timePassed;
  219. currentFrame += currentSpeed * timePassed;
  220. if(flagCurrentFrame >= flagAnimation->size(0))
  221. flagCurrentFrame -= flagAnimation->size(0);
  222. if(currentFrame >= animation->size(groupIndex))
  223. {
  224. currentFrame -= animation->size(groupIndex);
  225. switchToNextPhase();
  226. }
  227. }
  228. void BattleHero::render(Canvas & canvas)
  229. {
  230. size_t groupIndex = static_cast<size_t>(phase);
  231. auto flagFrame = flagAnimation->getImage(flagCurrentFrame, 0, true);
  232. auto heroFrame = animation->getImage(currentFrame, groupIndex, true);
  233. Point heroPosition = pos.center() - parent->pos.topLeft() - heroFrame->dimensions() / 2;
  234. Point flagPosition = pos.center() - parent->pos.topLeft() - flagFrame->dimensions() / 2;
  235. if(defender)
  236. flagPosition += Point(-4, -41);
  237. else
  238. flagPosition += Point(4, -41);
  239. canvas.draw(flagFrame, flagPosition);
  240. canvas.draw(heroFrame, heroPosition);
  241. }
  242. void BattleHero::pause()
  243. {
  244. currentSpeed = 0.f;
  245. }
  246. void BattleHero::play()
  247. {
  248. //H3 speed: 10 fps ( 100 ms per frame)
  249. currentSpeed = 10.f;
  250. }
  251. float BattleHero::getFrame() const
  252. {
  253. return currentFrame;
  254. }
  255. void BattleHero::collectRenderableObjects(BattleRenderer & renderer)
  256. {
  257. auto hex = defender ? BattleHex(GameConstants::BFIELD_WIDTH-1) : BattleHex(0);
  258. renderer.insert(EBattleFieldLayer::HEROES, hex, [this](BattleRenderer::RendererRef canvas)
  259. {
  260. render(canvas);
  261. });
  262. }
  263. void BattleHero::onPhaseFinished(const std::function<void()> & callback)
  264. {
  265. phaseFinishedCallback = callback;
  266. }
  267. void BattleHero::setPhase(EHeroAnimType newPhase)
  268. {
  269. nextPhase = newPhase;
  270. switchToNextPhase(); //immediately switch to next phase and then restore idling phase
  271. nextPhase = EHeroAnimType::HOLDING;
  272. }
  273. void BattleHero::heroLeftClicked()
  274. {
  275. if(owner.actionsController->spellcastingModeActive()) //we are casting a spell
  276. return;
  277. if(!hero || !owner.makingTurn())
  278. return;
  279. if(owner.getBattle()->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK) //check conditions
  280. {
  281. CCS->curh->set(Cursor::Map::POINTER);
  282. GH.windows().createAndPushWindow<CSpellWindow>(hero, owner.getCurrentPlayerInterface());
  283. }
  284. }
  285. void BattleHero::heroRightClicked()
  286. {
  287. if(settings["battle"]["stickyHeroInfoWindows"].Bool())
  288. return;
  289. Point windowPosition;
  290. if(GH.screenDimensions().x < 1000)
  291. {
  292. windowPosition.x = (!defender) ? owner.fieldController->pos.left() + 1 : owner.fieldController->pos.right() - 79;
  293. windowPosition.y = owner.fieldController->pos.y + 135;
  294. }
  295. else
  296. {
  297. windowPosition.x = (!defender) ? owner.fieldController->pos.left() - 93 : owner.fieldController->pos.right() + 15;
  298. windowPosition.y = owner.fieldController->pos.y;
  299. }
  300. InfoAboutHero targetHero;
  301. if(owner.makingTurn() || settings["session"]["spectate"].Bool())
  302. {
  303. auto h = defender ? owner.defendingHeroInstance : owner.attackingHeroInstance;
  304. targetHero.initFromHero(h, InfoAboutHero::EInfoLevel::INBATTLE);
  305. GH.windows().createAndPushWindow<HeroInfoWindow>(targetHero, &windowPosition);
  306. }
  307. }
  308. void BattleHero::switchToNextPhase()
  309. {
  310. phase = nextPhase;
  311. currentFrame = 0.f;
  312. auto copy = phaseFinishedCallback;
  313. phaseFinishedCallback.clear();
  314. copy();
  315. }
  316. BattleHero::BattleHero(const BattleInterface & owner, const CGHeroInstance * hero, bool defender):
  317. defender(defender),
  318. hero(hero),
  319. owner(owner),
  320. phase(EHeroAnimType::HOLDING),
  321. nextPhase(EHeroAnimType::HOLDING),
  322. currentSpeed(0.f),
  323. currentFrame(0.f),
  324. flagCurrentFrame(0.f)
  325. {
  326. AnimationPath animationPath;
  327. if(!hero->type->battleImage.empty())
  328. animationPath = hero->type->battleImage;
  329. else
  330. if(hero->gender == EHeroGender::FEMALE)
  331. animationPath = hero->type->heroClass->imageBattleFemale;
  332. else
  333. animationPath = hero->type->heroClass->imageBattleMale;
  334. animation = GH.renderHandler().loadAnimation(animationPath);
  335. animation->preload();
  336. pos.w = 64;
  337. pos.h = 136;
  338. pos.x = owner.fieldController->pos.x + (defender ? (owner.fieldController->pos.w - pos.w) : 0);
  339. pos.y = owner.fieldController->pos.y;
  340. if(defender)
  341. animation->verticalFlip();
  342. if(defender)
  343. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGR"));
  344. else
  345. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGL"));
  346. flagAnimation->preload();
  347. flagAnimation->playerColored(hero->tempOwner);
  348. switchToNextPhase();
  349. play();
  350. addUsedEvents(TIME);
  351. }
  352. QuickSpellPanel::QuickSpellPanel(BattleInterface & owner)
  353. : CIntObject(0), owner(owner)
  354. {
  355. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  356. addUsedEvents(LCLICK | SHOW_POPUP | MOVE);
  357. pos = Rect(0, 0, 52, 600);
  358. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), pos);
  359. rect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, pos.w + 1, pos.h + 1), ColorRGBA(0, 0, 0, 0), ColorRGBA(241, 216, 120, 255));
  360. create();
  361. }
  362. void QuickSpellPanel::create()
  363. {
  364. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  365. const JsonNode config = JsonUtils::assembleFromFiles("config/shortcutsConfig");
  366. labels.clear();
  367. buttons.clear();
  368. buttonsDisabled.clear();
  369. auto hero = owner.getBattle()->battleGetMyHero();
  370. if(!hero)
  371. return;
  372. for(int i = 0; i < 12; i++) {
  373. std::string spellIdentifier = persistentStorage["quickSpell"][std::to_string(i)].String();
  374. SpellID id;
  375. try
  376. {
  377. id = SpellID::decode(spellIdentifier);
  378. }
  379. catch(const IdentifierResolutionException& e)
  380. {
  381. id = SpellID::NONE;
  382. }
  383. auto button = std::make_shared<CButton>(Point(2, 7 + 50 * i), AnimationPath::builtin("spellint"), CButton::tooltip(), [this, id, hero](){
  384. if(id.hasValue() && id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, hero))
  385. {
  386. owner.castThisSpell(id);
  387. }
  388. });
  389. button->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("spellint"), !spellIdentifier.empty() ? id.num + 1 : 0));
  390. button->addPopupCallback([this, i, hero](){
  391. GH.input().hapticFeedback();
  392. GH.windows().createAndPushWindow<CSpellWindow>(hero, owner.curInt.get(), true, [this, i](SpellID spell){
  393. Settings configID = persistentStorage.write["quickSpell"][std::to_string(i)];
  394. configID->String() = spell.toSpell()->identifier;
  395. create();
  396. });
  397. });
  398. if(!id.hasValue() || !id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, hero))
  399. {
  400. buttonsDisabled.push_back(std::make_shared<TransparentFilledRectangle>(Rect(2, 7 + 50 * i, 48, 36), ColorRGBA(0, 0, 0, 172)));
  401. }
  402. labels.push_back(std::make_shared<CLabel>(7, 10 + 50 * i, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, config["keyboard"]["battleSpellShortcut" + std::to_string(i)].String()));
  403. buttons.push_back(button);
  404. }
  405. }
  406. void QuickSpellPanel::show(Canvas & to)
  407. {
  408. showAll(to);
  409. CIntObject::show(to);
  410. }
  411. HeroInfoBasicPanel::HeroInfoBasicPanel(const InfoAboutHero & hero, Point * position, bool initializeBackground)
  412. : CIntObject(0)
  413. {
  414. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  415. if (position != nullptr)
  416. moveTo(*position);
  417. if(initializeBackground)
  418. {
  419. background = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  420. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  421. background->colorize(hero.owner);
  422. }
  423. initializeData(hero);
  424. }
  425. void HeroInfoBasicPanel::initializeData(const InfoAboutHero & hero)
  426. {
  427. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  428. auto attack = hero.details->primskills[0];
  429. auto defense = hero.details->primskills[1];
  430. auto power = hero.details->primskills[2];
  431. auto knowledge = hero.details->primskills[3];
  432. auto morale = hero.details->morale;
  433. auto luck = hero.details->luck;
  434. auto currentSpellPoints = hero.details->mana;
  435. auto maxSpellPoints = hero.details->manaLimit;
  436. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), hero.getIconIndex(), 0, 10, 6));
  437. //primary stats
  438. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  439. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  440. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
  441. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
  442. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
  443. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
  444. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
  445. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
  446. //morale+luck
  447. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  448. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  449. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  450. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  451. //spell points
  452. labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
  453. labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
  454. }
  455. void HeroInfoBasicPanel::update(const InfoAboutHero & updatedInfo)
  456. {
  457. icons.clear();
  458. labels.clear();
  459. initializeData(updatedInfo);
  460. }
  461. void HeroInfoBasicPanel::show(Canvas & to)
  462. {
  463. showAll(to);
  464. CIntObject::show(to);
  465. }
  466. StackInfoBasicPanel::StackInfoBasicPanel(const CStack * stack, bool initializeBackground)
  467. : CIntObject(0)
  468. {
  469. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  470. if(initializeBackground)
  471. {
  472. background = std::make_shared<CPicture>(ImagePath::builtin("CCRPOP"));
  473. background->pos.y += 37;
  474. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  475. background->colorize(stack->getOwner());
  476. background2 = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  477. background2->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  478. background2->colorize(stack->getOwner());
  479. }
  480. initializeData(stack);
  481. }
  482. void StackInfoBasicPanel::initializeData(const CStack * stack)
  483. {
  484. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  485. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), stack->creatureId() + 2, 0, 10, 6));
  486. labels.push_back(std::make_shared<CLabel>(10 + 58, 6 + 64, FONT_MEDIUM, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, TextOperations::formatMetric(stack->getCount(), 4)));
  487. auto attack = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getAttack(stack->isShooter())) + "(" + std::to_string(stack->getAttack(stack->isShooter())) + ")";
  488. auto defense = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getDefense(stack->isShooter())) + "(" + std::to_string(stack->getDefense(stack->isShooter())) + ")";
  489. auto damage = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getMinDamage(stack->isShooter())) + "-" + std::to_string(stack->getMaxDamage(stack->isShooter()));
  490. auto health = CGI->creatures()->getByIndex(stack->creatureIndex())->getMaxHealth();
  491. auto morale = stack->moraleVal();
  492. auto luck = stack->luckVal();
  493. auto killed = stack->getKilled();
  494. auto healthRemaining = TextOperations::formatMetric(std::max(stack->getAvailableHealth() - (stack->getCount() - 1) * health, (si64)0), 4);
  495. //primary stats*/
  496. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  497. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  498. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[386] + ":"));
  499. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[389] + ":"));
  500. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, attack));
  501. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, defense));
  502. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, damage));
  503. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(health)));
  504. //morale+luck
  505. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  506. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  507. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  508. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  509. //extra information
  510. labels.push_back(std::make_shared<CLabel>(9, 168, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, VLC->generaltexth->translate("vcmi.battleWindow.killed") + ":"));
  511. labels.push_back(std::make_shared<CLabel>(9, 180, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[389] + ":"));
  512. labels.push_back(std::make_shared<CLabel>(69, 180, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(killed)));
  513. labels.push_back(std::make_shared<CLabel>(69, 192, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, healthRemaining));
  514. //spells
  515. static const Point firstPos(15, 206); // position of 1st spell box
  516. static const Point offset(0, 38); // offset of each spell box from previous
  517. for(int i = 0; i < 3; i++)
  518. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), 78, 0, firstPos.x + offset.x * i, firstPos.y + offset.y * i));
  519. int printed=0; //how many effect pics have been printed
  520. std::vector<SpellID> spells = stack->activeSpells();
  521. for(SpellID effect : spells)
  522. {
  523. //not all effects have graphics (for eg. Acid Breath)
  524. //for modded spells iconEffect is added to SpellInt.def
  525. const bool hasGraphics = (effect < SpellID::THUNDERBOLT) || (effect >= SpellID::AFTER_LAST);
  526. if (hasGraphics)
  527. {
  528. //FIXME: support permanent duration
  529. int duration = stack->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(effect)))->turnsRemain;
  530. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), effect + 1, 0, firstPos.x + offset.x * printed, firstPos.y + offset.y * printed));
  531. if(settings["general"]["enableUiEnhancements"].Bool())
  532. labels.push_back(std::make_shared<CLabel>(firstPos.x + offset.x * printed + 46, firstPos.y + offset.y * printed + 36, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(duration)));
  533. if(++printed >= 3 || (printed == 2 && spells.size() > 3)) // interface limit reached
  534. break;
  535. }
  536. }
  537. if(spells.size() == 0)
  538. labelsMultiline.push_back(std::make_shared<CMultiLineLabel>(Rect(firstPos.x, firstPos.y, 48, 36), EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[674]));
  539. if(spells.size() > 3)
  540. labelsMultiline.push_back(std::make_shared<CMultiLineLabel>(Rect(firstPos.x + offset.x * 2, firstPos.y + offset.y * 2 - 4, 48, 36), EFonts::FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, "..."));
  541. }
  542. void StackInfoBasicPanel::update(const CStack * updatedInfo)
  543. {
  544. icons.clear();
  545. labels.clear();
  546. labelsMultiline.clear();
  547. initializeData(updatedInfo);
  548. }
  549. void StackInfoBasicPanel::show(Canvas & to)
  550. {
  551. showAll(to);
  552. CIntObject::show(to);
  553. }
  554. HeroInfoWindow::HeroInfoWindow(const InfoAboutHero & hero, Point * position)
  555. : CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, ImagePath::builtin("CHRPOP"))
  556. {
  557. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  558. if (position != nullptr)
  559. moveTo(*position);
  560. background->colorize(hero.owner); //maybe add this functionality to base class?
  561. content = std::make_shared<HeroInfoBasicPanel>(hero, nullptr, false);
  562. }
  563. BattleResultWindow::BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner, bool allowReplay)
  564. : owner(_owner)
  565. {
  566. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  567. background = std::make_shared<CPicture>(ImagePath::builtin("CPRESULT"));
  568. background->colorize(owner.playerID);
  569. pos = center(background->pos);
  570. exit = std::make_shared<CButton>(Point(384, 505), AnimationPath::builtin("iok6432.def"), std::make_pair("", ""), [&](){ bExitf();}, EShortcut::GLOBAL_ACCEPT);
  571. exit->setBorderColor(Colors::METALLIC_GOLD);
  572. if(allowReplay || owner.cb->getStartInfo()->extraOptionsInfo.unlimitedReplay)
  573. {
  574. repeat = std::make_shared<CButton>(Point(24, 505), AnimationPath::builtin("icn6432.def"), std::make_pair("", ""), [&](){ bRepeatf();}, EShortcut::GLOBAL_CANCEL);
  575. repeat->setBorderColor(Colors::METALLIC_GOLD);
  576. labels.push_back(std::make_shared<CLabel>(232, 520, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("vcmi.battleResultsWindow.applyResultsLabel")));
  577. }
  578. if(br.winner == 0) //attacker won
  579. {
  580. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  581. }
  582. else
  583. {
  584. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  585. }
  586. if(br.winner == 1)
  587. {
  588. labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  589. }
  590. else
  591. {
  592. labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  593. }
  594. labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[407]));
  595. labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
  596. labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
  597. std::string sideNames[2] = {"N/A", "N/A"};
  598. for(int i = 0; i < 2; i++)
  599. {
  600. auto heroInfo = owner.cb->getBattle(br.battleID)->battleGetHeroInfo(i);
  601. const int xs[] = {21, 392};
  602. if(heroInfo.portraitSource.isValid()) //attacking hero
  603. {
  604. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), heroInfo.getIconIndex(), 0, xs[i], 38));
  605. sideNames[i] = heroInfo.name;
  606. }
  607. else
  608. {
  609. auto stacks = owner.cb->getBattle(br.battleID)->battleGetAllStacks();
  610. vstd::erase_if(stacks, [i](const CStack * stack) //erase stack of other side and not coming from garrison
  611. {
  612. return stack->unitSide() != i || !stack->base;
  613. });
  614. auto best = vstd::maxElementByFun(stacks, [](const CStack * stack)
  615. {
  616. return stack->unitType()->getAIValue();
  617. });
  618. if(best != stacks.end()) //should be always but to be safe...
  619. {
  620. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), (*best)->unitType()->getIconIndex(), 0, xs[i], 38));
  621. sideNames[i] = (*best)->unitType()->getNamePluralTranslated();
  622. }
  623. }
  624. }
  625. //printing attacker and defender's names
  626. labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, sideNames[0]));
  627. labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
  628. //printing casualties
  629. for(int step = 0; step < 2; ++step)
  630. {
  631. if(br.casualties[step].size()==0)
  632. {
  633. labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
  634. }
  635. else
  636. {
  637. int xPos = 235 - ((int)br.casualties[step].size()*32 + ((int)br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  638. int yPos = 344 + step * 97;
  639. for(auto & elem : br.casualties[step])
  640. {
  641. auto creature = CGI->creatures()->getByIndex(elem.first);
  642. if (creature->getId() == CreatureID::ARROW_TOWERS )
  643. continue; // do not show destroyed towers in battle results
  644. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature->getIconIndex(), 0, xPos, yPos));
  645. std::ostringstream amount;
  646. amount<<elem.second;
  647. labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, amount.str()));
  648. xPos += 42;
  649. }
  650. }
  651. }
  652. auto resources = getResources(br);
  653. description = std::make_shared<CTextBox>(resources.resultText.toString(), Rect(69, 203, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  654. videoPlayer = std::make_shared<VideoWidget>(Point(107, 70), resources.prologueVideo, resources.loopedVideo, false);
  655. CCS->musich->playMusic(resources.musicName, false, true);
  656. }
  657. BattleResultResources BattleResultWindow::getResources(const BattleResult & br)
  658. {
  659. //printing result description
  660. bool weAreAttacker = !(owner.cb->getBattle(br.battleID)->battleGetMySide());
  661. bool weAreDefender = !weAreAttacker;
  662. bool weWon = (br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker);
  663. bool isSiege = owner.cb->getBattle(br.battleID)->battleGetDefendedTown() != nullptr;
  664. BattleResultResources resources;
  665. if(weWon)
  666. {
  667. if(isSiege && weAreDefender)
  668. {
  669. resources.musicName = AudioPath::builtin("Music/Defend Castle");
  670. resources.prologueVideo = VideoPath::builtin("DEFENDALL.BIK");
  671. resources.loopedVideo = VideoPath::builtin("defendloop.bik");
  672. }
  673. else
  674. {
  675. resources.musicName = AudioPath::builtin("Music/Win Battle");
  676. resources.prologueVideo = VideoPath();
  677. resources.loopedVideo = VideoPath::builtin("WIN3.BIK");
  678. }
  679. switch(br.result)
  680. {
  681. case EBattleResult::NORMAL:
  682. resources.resultText.appendTextID("core.genrltxt.304");
  683. break;
  684. case EBattleResult::ESCAPE:
  685. resources.resultText.appendTextID("core.genrltxt.303");
  686. break;
  687. case EBattleResult::SURRENDER:
  688. resources.resultText.appendTextID("core.genrltxt.302");
  689. break;
  690. default:
  691. throw std::runtime_error("Invalid battle result!");
  692. }
  693. const CGHeroInstance * ourHero = owner.cb->getBattle(br.battleID)->battleGetMyHero();
  694. if (ourHero)
  695. {
  696. resources.resultText.appendTextID("core.genrltxt.305");
  697. resources.resultText.replaceTextID(ourHero->getNameTranslated());
  698. resources.resultText.replaceNumber(br.exp[weAreAttacker ? 0 : 1]);
  699. }
  700. }
  701. else // we lose
  702. {
  703. switch(br.result)
  704. {
  705. case EBattleResult::NORMAL:
  706. resources.resultText.appendTextID("core.genrltxt.311");
  707. resources.musicName = AudioPath::builtin("Music/LoseCombat");
  708. resources.prologueVideo = VideoPath::builtin("LBSTART.BIK");
  709. resources.loopedVideo = VideoPath::builtin("LBLOOP.BIK");
  710. break;
  711. case EBattleResult::ESCAPE:
  712. resources.resultText.appendTextID("core.genrltxt.310");
  713. resources.musicName = AudioPath::builtin("Music/Retreat Battle");
  714. resources.prologueVideo = VideoPath::builtin("RTSTART.BIK");
  715. resources.loopedVideo = VideoPath::builtin("RTLOOP.BIK");
  716. break;
  717. case EBattleResult::SURRENDER:
  718. resources.resultText.appendTextID("core.genrltxt.309");
  719. resources.musicName = AudioPath::builtin("Music/Surrender Battle");
  720. resources.prologueVideo = VideoPath();
  721. resources.loopedVideo = VideoPath::builtin("SURRENDER.BIK");
  722. break;
  723. default:
  724. throw std::runtime_error("Invalid battle result!");
  725. }
  726. if(isSiege && weAreDefender)
  727. {
  728. resources.musicName = AudioPath::builtin("Music/LoseCastle");
  729. resources.prologueVideo = VideoPath::builtin("LOSECSTL.BIK");
  730. resources.loopedVideo = VideoPath::builtin("LOSECSLP.BIK");
  731. }
  732. }
  733. return resources;
  734. }
  735. void BattleResultWindow::activate()
  736. {
  737. owner.showingDialog->setBusy();
  738. CIntObject::activate();
  739. }
  740. void BattleResultWindow::buttonPressed(int button)
  741. {
  742. if (resultCallback)
  743. resultCallback(button);
  744. CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
  745. close();
  746. if(GH.windows().topWindow<BattleWindow>())
  747. GH.windows().popWindows(1); //pop battle interface if present
  748. //Result window and battle interface are gone. We requested all dialogs to be closed before opening the battle,
  749. //so we can be sure that there is no dialogs left on GUI stack.
  750. intTmp.showingDialog->setFree();
  751. }
  752. void BattleResultWindow::bExitf()
  753. {
  754. buttonPressed(0);
  755. }
  756. void BattleResultWindow::bRepeatf()
  757. {
  758. buttonPressed(1);
  759. }
  760. StackQueue::StackQueue(bool Embedded, BattleInterface & owner)
  761. : embedded(Embedded),
  762. owner(owner)
  763. {
  764. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  765. uint32_t queueSize = QUEUE_SIZE_BIG;
  766. if(embedded)
  767. {
  768. int32_t queueSmallOutsideYOffset = 65;
  769. bool queueSmallOutside = settings["battle"]["queueSmallOutside"].Bool() && (pos.y - queueSmallOutsideYOffset) >= 0;
  770. queueSize = std::clamp(static_cast<int>(settings["battle"]["queueSmallSlots"].Float()), 1, queueSmallOutside ? GH.screenDimensions().x / 41 : 19);
  771. pos.w = queueSize * 41;
  772. pos.h = 49;
  773. pos.x += parent->pos.w/2 - pos.w/2;
  774. pos.y += queueSmallOutside ? -queueSmallOutsideYOffset : 10;
  775. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("CPRSMALL"));
  776. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  777. }
  778. else
  779. {
  780. pos.w = 800;
  781. pos.h = 85;
  782. pos.x += 0;
  783. pos.y -= pos.h;
  784. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  785. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("TWCRPORT"));
  786. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  787. //TODO: where use big icons?
  788. //stateIcons = GH.renderHandler().loadAnimation("VCMI/BATTLEQUEUE/STATESBIG");
  789. }
  790. stateIcons->preload();
  791. stackBoxes.resize(queueSize);
  792. for (int i = 0; i < stackBoxes.size(); i++)
  793. {
  794. stackBoxes[i] = std::make_shared<StackBox>(this);
  795. stackBoxes[i]->moveBy(Point(1 + (embedded ? 41 : 80) * i, 0));
  796. }
  797. }
  798. void StackQueue::show(Canvas & to)
  799. {
  800. if (embedded)
  801. showAll(to);
  802. CIntObject::show(to);
  803. }
  804. void StackQueue::update()
  805. {
  806. std::vector<battle::Units> queueData;
  807. owner.getBattle()->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
  808. size_t boxIndex = 0;
  809. ui32 tmpTurn = -1;
  810. for(size_t turn = 0; turn < queueData.size() && boxIndex < stackBoxes.size(); turn++)
  811. {
  812. for(size_t unitIndex = 0; unitIndex < queueData[turn].size() && boxIndex < stackBoxes.size(); boxIndex++, unitIndex++)
  813. {
  814. ui32 currentTurn = owner.round + turn;
  815. stackBoxes[boxIndex]->setUnit(queueData[turn][unitIndex], turn, tmpTurn != currentTurn && owner.round != 0 && (!embedded || tmpTurn != -1) ? (std::optional<ui32>)currentTurn : std::nullopt);
  816. tmpTurn = currentTurn;
  817. }
  818. }
  819. for(; boxIndex < stackBoxes.size(); boxIndex++)
  820. stackBoxes[boxIndex]->setUnit(nullptr);
  821. }
  822. int32_t StackQueue::getSiegeShooterIconID()
  823. {
  824. return owner.siegeController->getSiegedTown()->town->faction->getIndex();
  825. }
  826. std::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const
  827. {
  828. for(const auto & stackBox : stackBoxes)
  829. {
  830. if(stackBox->isHovered())
  831. {
  832. return stackBox->getBoundUnitID();
  833. }
  834. }
  835. return std::nullopt;
  836. }
  837. StackQueue::StackBox::StackBox(StackQueue * owner):
  838. CIntObject(SHOW_POPUP | HOVER), owner(owner)
  839. {
  840. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  841. background = std::make_shared<CPicture>(ImagePath::builtin(owner->embedded ? "StackQueueSmall" : "StackQueueLarge"));
  842. pos.w = background->pos.w;
  843. pos.h = background->pos.h;
  844. if(owner->embedded)
  845. {
  846. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 5, 2);
  847. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  848. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 2, 48), ColorRGBA(0, 0, 0, 255), ColorRGBA(0, 255, 0, 255));
  849. }
  850. else
  851. {
  852. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 9, 1);
  853. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
  854. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 15, 18), ColorRGBA(0, 0, 0, 255), ColorRGBA(241, 216, 120, 255));
  855. round = std::make_shared<CLabel>(4, 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
  856. int icon_x = pos.w - 17;
  857. int icon_y = pos.h - 18;
  858. stateIcon = std::make_shared<CAnimImage>(owner->stateIcons, 0, 0, icon_x, icon_y);
  859. stateIcon->visible = false;
  860. }
  861. roundRect->disable();
  862. }
  863. void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn, std::optional<ui32> currentTurn)
  864. {
  865. if(unit)
  866. {
  867. boundUnitID = unit->unitId();
  868. background->colorize(unit->unitOwner());
  869. icon->visible = true;
  870. // temporary code for mod compatibility:
  871. // first, set icon that should definitely exist (arrow tower icon in base vcmi mod)
  872. // second, try to switch to icon that should be provided by mod
  873. // if mod is not up to date and does have arrow tower icon yet - second setFrame call will fail and retain previously set image
  874. // for 1.2 release & later next line should be moved into 'else' block
  875. icon->setFrame(unit->creatureIconIndex(), 0);
  876. if (unit->unitType()->getId() == CreatureID::ARROW_TOWERS)
  877. icon->setFrame(owner->getSiegeShooterIconID(), 1);
  878. roundRect->setEnabled(currentTurn.has_value());
  879. if(!owner->embedded)
  880. round->setEnabled(currentTurn.has_value());
  881. amount->setText(TextOperations::formatMetric(unit->getCount(), 4));
  882. if(currentTurn && !owner->embedded)
  883. {
  884. std::string tmp = std::to_string(*currentTurn);
  885. int len = graphics->fonts[FONT_SMALL]->getStringWidth(tmp);
  886. roundRect->pos.w = len + 6;
  887. round->setText(tmp);
  888. }
  889. if(stateIcon)
  890. {
  891. if(unit->defended((int)turn) || (turn > 0 && unit->defended((int)turn - 1)))
  892. {
  893. stateIcon->setFrame(0, 0);
  894. stateIcon->visible = true;
  895. }
  896. else if(unit->waited((int)turn))
  897. {
  898. stateIcon->setFrame(1, 0);
  899. stateIcon->visible = true;
  900. }
  901. else
  902. {
  903. stateIcon->visible = false;
  904. }
  905. }
  906. }
  907. else
  908. {
  909. boundUnitID = std::nullopt;
  910. background->colorize(PlayerColor::NEUTRAL);
  911. icon->visible = false;
  912. icon->setFrame(0);
  913. amount->setText("");
  914. if(stateIcon)
  915. stateIcon->visible = false;
  916. }
  917. }
  918. std::optional<uint32_t> StackQueue::StackBox::getBoundUnitID() const
  919. {
  920. return boundUnitID;
  921. }
  922. bool StackQueue::StackBox::isBoundUnitHighlighted() const
  923. {
  924. auto unitIdsToHighlight = owner->owner.stacksController->getHoveredStacksUnitIds();
  925. return vstd::contains(unitIdsToHighlight, getBoundUnitID());
  926. }
  927. void StackQueue::StackBox::showAll(Canvas & to)
  928. {
  929. CIntObject::showAll(to);
  930. if(isBoundUnitHighlighted())
  931. to.drawBorder(background->pos, Colors::CYAN, 2);
  932. }
  933. void StackQueue::StackBox::show(Canvas & to)
  934. {
  935. CIntObject::show(to);
  936. if(isBoundUnitHighlighted())
  937. to.drawBorder(background->pos, Colors::CYAN, 2);
  938. }
  939. void StackQueue::StackBox::showPopupWindow(const Point & cursorPosition)
  940. {
  941. auto stacks = owner->owner.getBattle()->battleGetAllStacks();
  942. for(const CStack * stack : stacks)
  943. if(boundUnitID.has_value() && stack->unitId() == *boundUnitID)
  944. GH.windows().createAndPushWindow<CStackWindow>(stack, true);
  945. }