BattleInterfaceClasses.cpp 39 KB

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