BattleInterfaceClasses.cpp 38 KB

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