BattleInterfaceClasses.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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 "../../CCallback.h"
  46. #include "../../lib/CStack.h"
  47. #include "../../lib/CConfigHandler.h"
  48. #include "../../lib/CCreatureHandler.h"
  49. #include "../../lib/gameState/InfoAboutArmy.h"
  50. #include "../../lib/CGeneralTextHandler.h"
  51. #include "../../lib/CTownHandler.h"
  52. #include "../../lib/CHeroHandler.h"
  53. #include "../../lib/StartInfo.h"
  54. #include "../../lib/mapObjects/CGTownInstance.h"
  55. #include "../../lib/networkPacks/PacksForClientBattle.h"
  56. #include "../../lib/TextOperations.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. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  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. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  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);
  334. animation->preload();
  335. pos.w = 64;
  336. pos.h = 136;
  337. pos.x = owner.fieldController->pos.x + (defender ? (owner.fieldController->pos.w - pos.w) : 0);
  338. pos.y = owner.fieldController->pos.y;
  339. if(defender)
  340. animation->verticalFlip();
  341. if(defender)
  342. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGR"));
  343. else
  344. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGL"));
  345. flagAnimation->preload();
  346. flagAnimation->playerColored(hero->tempOwner);
  347. switchToNextPhase();
  348. play();
  349. addUsedEvents(TIME);
  350. }
  351. QuickSpellPanel::QuickSpellPanel(BattleInterface & owner)
  352. : CIntObject(0), owner(owner)
  353. {
  354. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  355. addUsedEvents(LCLICK | SHOW_POPUP | MOVE);
  356. pos = Rect(0, 0, 52, 600);
  357. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), pos);
  358. rect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, pos.w + 1, pos.h + 1), ColorRGBA(0, 0, 0, 0), ColorRGBA(241, 216, 120, 255));
  359. create();
  360. }
  361. void QuickSpellPanel::create()
  362. {
  363. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  364. const JsonNode config = JsonUtils::assembleFromFiles("config/shortcutsConfig");
  365. labels.clear();
  366. buttons.clear();
  367. buttonsDisabled.clear();
  368. auto hero = owner.getBattle()->battleGetMyHero();
  369. if(!hero)
  370. return;
  371. for(int i = 0; i < 16; i++) {
  372. std::string spellIdentifier = persistentStorage["quickSpell"][std::to_string(i)].String();
  373. SpellID id;
  374. try
  375. {
  376. id = SpellID::decode(spellIdentifier);
  377. }
  378. catch(const IdentifierResolutionException& e)
  379. {
  380. id = SpellID::NONE;
  381. }
  382. auto button = std::make_shared<CButton>(Point(2, 5 + 37 * i), AnimationPath::builtin("spellint"), CButton::tooltip(), [this, id, hero](){
  383. if(id.hasValue() && id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, hero))
  384. {
  385. owner.castThisSpell(id);
  386. }
  387. });
  388. button->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("spellint"), !spellIdentifier.empty() ? id.num + 1 : 0));
  389. button->addPopupCallback([this, i](){
  390. auto panelSelect = std::make_shared<QuickSpellPanelSelect>(this);
  391. panelSelect->spellSlot = i;
  392. panelSelect->moveTo(Point(pos.x + 54, pos.y + 4));
  393. GH.windows().pushWindow(panelSelect);
  394. });
  395. if(!id.hasValue() || !id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, hero))
  396. {
  397. buttonsDisabled.push_back(std::make_shared<TransparentFilledRectangle>(Rect(2, 5 + 37 * i, 48, 36), ColorRGBA(0, 0, 0, 172)));
  398. }
  399. labels.push_back(std::make_shared<CLabel>(7, 8 + 37 * i, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, config["keyboard"]["battleSpellShortcut" + std::to_string(i)].String()));
  400. buttons.push_back(button);
  401. }
  402. }
  403. void QuickSpellPanel::show(Canvas & to)
  404. {
  405. showAll(to);
  406. CIntObject::show(to);
  407. }
  408. QuickSpellPanelSelect::QuickSpellPanelSelect(QuickSpellPanel * Parent)
  409. : parent(Parent)
  410. {
  411. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  412. addUsedEvents(LCLICK);
  413. std::vector<std::shared_ptr<CSpell>> spellList;
  414. for (auto const & s : VLC->spellh->objects)
  415. if (s->isCombat() && !s->isSpecial() && !s->isCreatureAbility())
  416. spellList.push_back(s);
  417. auto ceil = [](int x, int y){ return(x + y - 1) / y; };
  418. int columnsNeeded = ceil(spellList.size(), NUM_PER_COLUMN);
  419. pos = Rect(pos.x, pos.y, columnsNeeded * 50 + 2, 2 + 37 * NUM_PER_COLUMN);
  420. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  421. rect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, pos.w + 1, pos.h + 1), ColorRGBA(0, 0, 0, 0), ColorRGBA(241, 216, 120, 255));
  422. for(int i = 0; i < spellList.size(); i++)
  423. {
  424. int y = i % NUM_PER_COLUMN;
  425. int x = i / NUM_PER_COLUMN;
  426. std::shared_ptr<CSpell> spell = spellList[i];
  427. auto button = std::make_shared<CButton>(Point(2 + 50 * x, 1 + 37 * y), AnimationPath::builtin("spellint"), CButton::tooltip(), [this, spell](){
  428. close();
  429. GH.windows().totalRedraw();
  430. Settings configID = persistentStorage.write["quickSpell"][std::to_string(spellSlot)];
  431. configID->String() = spell->identifier;
  432. parent->create();
  433. });
  434. button->addPopupCallback([spell](){
  435. CRClickPopup::createAndPush(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(ComponentType::SPELL, spell->id));
  436. });
  437. button->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("spellint"), spellList[i]->getId().num + 1));
  438. buttons.push_back(button);
  439. }
  440. }
  441. void QuickSpellPanelSelect::clickReleased(const Point & cursorPosition)
  442. {
  443. if(!pos.isInside(cursorPosition) && !parent->pos.isInside(cursorPosition))
  444. close();
  445. }
  446. bool QuickSpellPanelSelect::receiveEvent(const Point & position, int eventType) const
  447. {
  448. return true; // capture click also outside of window
  449. }
  450. HeroInfoBasicPanel::HeroInfoBasicPanel(const InfoAboutHero & hero, Point * position, bool initializeBackground)
  451. : CIntObject(0)
  452. {
  453. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  454. if (position != nullptr)
  455. moveTo(*position);
  456. if(initializeBackground)
  457. {
  458. background = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  459. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  460. background->colorize(hero.owner);
  461. }
  462. initializeData(hero);
  463. }
  464. void HeroInfoBasicPanel::initializeData(const InfoAboutHero & hero)
  465. {
  466. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  467. auto attack = hero.details->primskills[0];
  468. auto defense = hero.details->primskills[1];
  469. auto power = hero.details->primskills[2];
  470. auto knowledge = hero.details->primskills[3];
  471. auto morale = hero.details->morale;
  472. auto luck = hero.details->luck;
  473. auto currentSpellPoints = hero.details->mana;
  474. auto maxSpellPoints = hero.details->manaLimit;
  475. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), hero.getIconIndex(), 0, 10, 6));
  476. //primary stats
  477. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  478. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  479. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
  480. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
  481. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
  482. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
  483. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
  484. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
  485. //morale+luck
  486. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  487. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  488. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  489. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  490. //spell points
  491. labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
  492. labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
  493. }
  494. void HeroInfoBasicPanel::update(const InfoAboutHero & updatedInfo)
  495. {
  496. icons.clear();
  497. labels.clear();
  498. initializeData(updatedInfo);
  499. }
  500. void HeroInfoBasicPanel::show(Canvas & to)
  501. {
  502. showAll(to);
  503. CIntObject::show(to);
  504. }
  505. StackInfoBasicPanel::StackInfoBasicPanel(const CStack * stack, bool initializeBackground)
  506. : CIntObject(0)
  507. {
  508. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  509. if(initializeBackground)
  510. {
  511. background = std::make_shared<CPicture>(ImagePath::builtin("CCRPOP"));
  512. background->pos.y += 37;
  513. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  514. background->colorize(stack->getOwner());
  515. background2 = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  516. background2->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  517. background2->colorize(stack->getOwner());
  518. }
  519. initializeData(stack);
  520. }
  521. void StackInfoBasicPanel::initializeData(const CStack * stack)
  522. {
  523. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  524. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), stack->creatureId() + 2, 0, 10, 6));
  525. labels.push_back(std::make_shared<CLabel>(10 + 58, 6 + 64, FONT_MEDIUM, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, TextOperations::formatMetric(stack->getCount(), 4)));
  526. auto attack = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getAttack(stack->isShooter())) + "(" + std::to_string(stack->getAttack(stack->isShooter())) + ")";
  527. auto defense = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getDefense(stack->isShooter())) + "(" + std::to_string(stack->getDefense(stack->isShooter())) + ")";
  528. auto damage = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getMinDamage(stack->isShooter())) + "-" + std::to_string(stack->getMaxDamage(stack->isShooter()));
  529. auto health = CGI->creatures()->getByIndex(stack->creatureIndex())->getMaxHealth();
  530. auto morale = stack->moraleVal();
  531. auto luck = stack->luckVal();
  532. auto killed = stack->getKilled();
  533. auto healthRemaining = TextOperations::formatMetric(std::max(stack->getAvailableHealth() - (stack->getCount() - 1) * health, (si64)0), 4);
  534. //primary stats*/
  535. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  536. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  537. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[386] + ":"));
  538. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[389] + ":"));
  539. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, attack));
  540. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, defense));
  541. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, damage));
  542. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(health)));
  543. //morale+luck
  544. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  545. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  546. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  547. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  548. //extra information
  549. labels.push_back(std::make_shared<CLabel>(9, 168, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, VLC->generaltexth->translate("vcmi.battleWindow.killed") + ":"));
  550. labels.push_back(std::make_shared<CLabel>(9, 180, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[389] + ":"));
  551. labels.push_back(std::make_shared<CLabel>(69, 180, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(killed)));
  552. labels.push_back(std::make_shared<CLabel>(69, 192, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, healthRemaining));
  553. //spells
  554. static const Point firstPos(15, 206); // position of 1st spell box
  555. static const Point offset(0, 38); // offset of each spell box from previous
  556. for(int i = 0; i < 3; i++)
  557. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), 78, 0, firstPos.x + offset.x * i, firstPos.y + offset.y * i));
  558. int printed=0; //how many effect pics have been printed
  559. std::vector<SpellID> spells = stack->activeSpells();
  560. for(SpellID effect : spells)
  561. {
  562. //not all effects have graphics (for eg. Acid Breath)
  563. //for modded spells iconEffect is added to SpellInt.def
  564. const bool hasGraphics = (effect < SpellID::THUNDERBOLT) || (effect >= SpellID::AFTER_LAST);
  565. if (hasGraphics)
  566. {
  567. //FIXME: support permanent duration
  568. int duration = stack->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(effect)))->turnsRemain;
  569. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), effect + 1, 0, firstPos.x + offset.x * printed, firstPos.y + offset.y * printed));
  570. if(settings["general"]["enableUiEnhancements"].Bool())
  571. 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)));
  572. if(++printed >= 3 || (printed == 2 && spells.size() > 3)) // interface limit reached
  573. break;
  574. }
  575. }
  576. if(spells.size() == 0)
  577. 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]));
  578. if(spells.size() > 3)
  579. 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, "..."));
  580. }
  581. void StackInfoBasicPanel::update(const CStack * updatedInfo)
  582. {
  583. icons.clear();
  584. labels.clear();
  585. labelsMultiline.clear();
  586. initializeData(updatedInfo);
  587. }
  588. void StackInfoBasicPanel::show(Canvas & to)
  589. {
  590. showAll(to);
  591. CIntObject::show(to);
  592. }
  593. HeroInfoWindow::HeroInfoWindow(const InfoAboutHero & hero, Point * position)
  594. : CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, ImagePath::builtin("CHRPOP"))
  595. {
  596. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  597. if (position != nullptr)
  598. moveTo(*position);
  599. background->colorize(hero.owner); //maybe add this functionality to base class?
  600. content = std::make_shared<HeroInfoBasicPanel>(hero, nullptr, false);
  601. }
  602. BattleResultWindow::BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner, bool allowReplay)
  603. : owner(_owner)
  604. {
  605. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  606. background = std::make_shared<CPicture>(ImagePath::builtin("CPRESULT"));
  607. background->colorize(owner.playerID);
  608. pos = center(background->pos);
  609. exit = std::make_shared<CButton>(Point(384, 505), AnimationPath::builtin("iok6432.def"), std::make_pair("", ""), [&](){ bExitf();}, EShortcut::GLOBAL_ACCEPT);
  610. exit->setBorderColor(Colors::METALLIC_GOLD);
  611. if(allowReplay || owner.cb->getStartInfo()->extraOptionsInfo.unlimitedReplay)
  612. {
  613. repeat = std::make_shared<CButton>(Point(24, 505), AnimationPath::builtin("icn6432.def"), std::make_pair("", ""), [&](){ bRepeatf();}, EShortcut::GLOBAL_CANCEL);
  614. repeat->setBorderColor(Colors::METALLIC_GOLD);
  615. labels.push_back(std::make_shared<CLabel>(232, 520, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("vcmi.battleResultsWindow.applyResultsLabel")));
  616. }
  617. if(br.winner == 0) //attacker won
  618. {
  619. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  620. }
  621. else
  622. {
  623. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  624. }
  625. if(br.winner == 1)
  626. {
  627. labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  628. }
  629. else
  630. {
  631. labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  632. }
  633. labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[407]));
  634. labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
  635. labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
  636. std::string sideNames[2] = {"N/A", "N/A"};
  637. for(int i = 0; i < 2; i++)
  638. {
  639. auto heroInfo = owner.cb->getBattle(br.battleID)->battleGetHeroInfo(i);
  640. const int xs[] = {21, 392};
  641. if(heroInfo.portraitSource.isValid()) //attacking hero
  642. {
  643. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), heroInfo.getIconIndex(), 0, xs[i], 38));
  644. sideNames[i] = heroInfo.name;
  645. }
  646. else
  647. {
  648. auto stacks = owner.cb->getBattle(br.battleID)->battleGetAllStacks();
  649. vstd::erase_if(stacks, [i](const CStack * stack) //erase stack of other side and not coming from garrison
  650. {
  651. return stack->unitSide() != i || !stack->base;
  652. });
  653. auto best = vstd::maxElementByFun(stacks, [](const CStack * stack)
  654. {
  655. return stack->unitType()->getAIValue();
  656. });
  657. if(best != stacks.end()) //should be always but to be safe...
  658. {
  659. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), (*best)->unitType()->getIconIndex(), 0, xs[i], 38));
  660. sideNames[i] = (*best)->unitType()->getNamePluralTranslated();
  661. }
  662. }
  663. }
  664. //printing attacker and defender's names
  665. labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, sideNames[0]));
  666. labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
  667. //printing casualties
  668. for(int step = 0; step < 2; ++step)
  669. {
  670. if(br.casualties[step].size()==0)
  671. {
  672. labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
  673. }
  674. else
  675. {
  676. int xPos = 235 - ((int)br.casualties[step].size()*32 + ((int)br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  677. int yPos = 344 + step * 97;
  678. for(auto & elem : br.casualties[step])
  679. {
  680. auto creature = CGI->creatures()->getByIndex(elem.first);
  681. if (creature->getId() == CreatureID::ARROW_TOWERS )
  682. continue; // do not show destroyed towers in battle results
  683. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature->getIconIndex(), 0, xPos, yPos));
  684. std::ostringstream amount;
  685. amount<<elem.second;
  686. labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, amount.str()));
  687. xPos += 42;
  688. }
  689. }
  690. }
  691. auto resources = getResources(br);
  692. description = std::make_shared<CTextBox>(resources.resultText.toString(), Rect(69, 203, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  693. videoPlayer = std::make_shared<VideoWidget>(Point(107, 70), resources.prologueVideo, resources.loopedVideo, false);
  694. CCS->musich->playMusic(resources.musicName, false, true);
  695. }
  696. BattleResultResources BattleResultWindow::getResources(const BattleResult & br)
  697. {
  698. //printing result description
  699. bool weAreAttacker = !(owner.cb->getBattle(br.battleID)->battleGetMySide());
  700. bool weAreDefender = !weAreAttacker;
  701. bool weWon = (br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker);
  702. bool isSiege = owner.cb->getBattle(br.battleID)->battleGetDefendedTown() != nullptr;
  703. BattleResultResources resources;
  704. if(weWon)
  705. {
  706. if(isSiege && weAreDefender)
  707. {
  708. resources.musicName = AudioPath::builtin("Music/Defend Castle");
  709. resources.prologueVideo = VideoPath::builtin("DEFENDALL.BIK");
  710. resources.loopedVideo = VideoPath::builtin("defendloop.bik");
  711. }
  712. else
  713. {
  714. resources.musicName = AudioPath::builtin("Music/Win Battle");
  715. resources.prologueVideo = VideoPath();
  716. resources.loopedVideo = VideoPath::builtin("WIN3.BIK");
  717. }
  718. switch(br.result)
  719. {
  720. case EBattleResult::NORMAL:
  721. resources.resultText.appendTextID("core.genrltxt.304");
  722. break;
  723. case EBattleResult::ESCAPE:
  724. resources.resultText.appendTextID("core.genrltxt.303");
  725. break;
  726. case EBattleResult::SURRENDER:
  727. resources.resultText.appendTextID("core.genrltxt.302");
  728. break;
  729. default:
  730. throw std::runtime_error("Invalid battle result!");
  731. }
  732. const CGHeroInstance * ourHero = owner.cb->getBattle(br.battleID)->battleGetMyHero();
  733. if (ourHero)
  734. {
  735. resources.resultText.appendTextID("core.genrltxt.305");
  736. resources.resultText.replaceTextID(ourHero->getNameTranslated());
  737. resources.resultText.replaceNumber(br.exp[weAreAttacker ? 0 : 1]);
  738. }
  739. }
  740. else // we lose
  741. {
  742. switch(br.result)
  743. {
  744. case EBattleResult::NORMAL:
  745. resources.resultText.appendTextID("core.genrltxt.311");
  746. resources.musicName = AudioPath::builtin("Music/LoseCombat");
  747. resources.prologueVideo = VideoPath::builtin("LBSTART.BIK");
  748. resources.loopedVideo = VideoPath::builtin("LBLOOP.BIK");
  749. break;
  750. case EBattleResult::ESCAPE:
  751. resources.resultText.appendTextID("core.genrltxt.310");
  752. resources.musicName = AudioPath::builtin("Music/Retreat Battle");
  753. resources.prologueVideo = VideoPath::builtin("RTSTART.BIK");
  754. resources.loopedVideo = VideoPath::builtin("RTLOOP.BIK");
  755. break;
  756. case EBattleResult::SURRENDER:
  757. resources.resultText.appendTextID("core.genrltxt.309");
  758. resources.musicName = AudioPath::builtin("Music/Surrender Battle");
  759. resources.prologueVideo = VideoPath();
  760. resources.loopedVideo = VideoPath::builtin("SURRENDER.BIK");
  761. break;
  762. default:
  763. throw std::runtime_error("Invalid battle result!");
  764. }
  765. if(isSiege && weAreDefender)
  766. {
  767. resources.musicName = AudioPath::builtin("Music/LoseCastle");
  768. resources.prologueVideo = VideoPath::builtin("LOSECSTL.BIK");
  769. resources.loopedVideo = VideoPath::builtin("LOSECSLP.BIK");
  770. }
  771. }
  772. return resources;
  773. }
  774. void BattleResultWindow::activate()
  775. {
  776. owner.showingDialog->setBusy();
  777. CIntObject::activate();
  778. }
  779. void BattleResultWindow::buttonPressed(int button)
  780. {
  781. if (resultCallback)
  782. resultCallback(button);
  783. CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
  784. close();
  785. if(GH.windows().topWindow<BattleWindow>())
  786. GH.windows().popWindows(1); //pop battle interface if present
  787. //Result window and battle interface are gone. We requested all dialogs to be closed before opening the battle,
  788. //so we can be sure that there is no dialogs left on GUI stack.
  789. intTmp.showingDialog->setFree();
  790. }
  791. void BattleResultWindow::bExitf()
  792. {
  793. buttonPressed(0);
  794. }
  795. void BattleResultWindow::bRepeatf()
  796. {
  797. buttonPressed(1);
  798. }
  799. StackQueue::StackQueue(bool Embedded, BattleInterface & owner)
  800. : embedded(Embedded),
  801. owner(owner)
  802. {
  803. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  804. uint32_t queueSize = QUEUE_SIZE_BIG;
  805. if(embedded)
  806. {
  807. int32_t queueSmallOutsideYOffset = 65;
  808. bool queueSmallOutside = settings["battle"]["queueSmallOutside"].Bool() && (pos.y - queueSmallOutsideYOffset) >= 0;
  809. queueSize = std::clamp(static_cast<int>(settings["battle"]["queueSmallSlots"].Float()), 1, queueSmallOutside ? GH.screenDimensions().x / 41 : 19);
  810. pos.w = queueSize * 41;
  811. pos.h = 49;
  812. pos.x += parent->pos.w/2 - pos.w/2;
  813. pos.y += queueSmallOutside ? -queueSmallOutsideYOffset : 10;
  814. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("CPRSMALL"));
  815. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  816. }
  817. else
  818. {
  819. pos.w = 800;
  820. pos.h = 85;
  821. pos.x += 0;
  822. pos.y -= pos.h;
  823. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  824. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("TWCRPORT"));
  825. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  826. //TODO: where use big icons?
  827. //stateIcons = GH.renderHandler().loadAnimation("VCMI/BATTLEQUEUE/STATESBIG");
  828. }
  829. stateIcons->preload();
  830. stackBoxes.resize(queueSize);
  831. for (int i = 0; i < stackBoxes.size(); i++)
  832. {
  833. stackBoxes[i] = std::make_shared<StackBox>(this);
  834. stackBoxes[i]->moveBy(Point(1 + (embedded ? 41 : 80) * i, 0));
  835. }
  836. }
  837. void StackQueue::show(Canvas & to)
  838. {
  839. if (embedded)
  840. showAll(to);
  841. CIntObject::show(to);
  842. }
  843. void StackQueue::update()
  844. {
  845. std::vector<battle::Units> queueData;
  846. owner.getBattle()->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
  847. size_t boxIndex = 0;
  848. ui32 tmpTurn = -1;
  849. for(size_t turn = 0; turn < queueData.size() && boxIndex < stackBoxes.size(); turn++)
  850. {
  851. for(size_t unitIndex = 0; unitIndex < queueData[turn].size() && boxIndex < stackBoxes.size(); boxIndex++, unitIndex++)
  852. {
  853. ui32 currentTurn = owner.round + turn;
  854. stackBoxes[boxIndex]->setUnit(queueData[turn][unitIndex], turn, tmpTurn != currentTurn && owner.round != 0 && (!embedded || tmpTurn != -1) ? (std::optional<ui32>)currentTurn : std::nullopt);
  855. tmpTurn = currentTurn;
  856. }
  857. }
  858. for(; boxIndex < stackBoxes.size(); boxIndex++)
  859. stackBoxes[boxIndex]->setUnit(nullptr);
  860. }
  861. int32_t StackQueue::getSiegeShooterIconID()
  862. {
  863. return owner.siegeController->getSiegedTown()->town->faction->getIndex();
  864. }
  865. std::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const
  866. {
  867. for(const auto & stackBox : stackBoxes)
  868. {
  869. if(stackBox->isHovered())
  870. {
  871. return stackBox->getBoundUnitID();
  872. }
  873. }
  874. return std::nullopt;
  875. }
  876. StackQueue::StackBox::StackBox(StackQueue * owner):
  877. CIntObject(SHOW_POPUP | HOVER), owner(owner)
  878. {
  879. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  880. background = std::make_shared<CPicture>(ImagePath::builtin(owner->embedded ? "StackQueueSmall" : "StackQueueLarge"));
  881. pos.w = background->pos.w;
  882. pos.h = background->pos.h;
  883. if(owner->embedded)
  884. {
  885. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 5, 2);
  886. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  887. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 2, 48), ColorRGBA(0, 0, 0, 255), ColorRGBA(0, 255, 0, 255));
  888. }
  889. else
  890. {
  891. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 9, 1);
  892. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
  893. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 15, 18), ColorRGBA(0, 0, 0, 255), ColorRGBA(241, 216, 120, 255));
  894. round = std::make_shared<CLabel>(4, 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
  895. int icon_x = pos.w - 17;
  896. int icon_y = pos.h - 18;
  897. stateIcon = std::make_shared<CAnimImage>(owner->stateIcons, 0, 0, icon_x, icon_y);
  898. stateIcon->visible = false;
  899. }
  900. roundRect->disable();
  901. }
  902. void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn, std::optional<ui32> currentTurn)
  903. {
  904. if(unit)
  905. {
  906. boundUnitID = unit->unitId();
  907. background->colorize(unit->unitOwner());
  908. icon->visible = true;
  909. // temporary code for mod compatibility:
  910. // first, set icon that should definitely exist (arrow tower icon in base vcmi mod)
  911. // second, try to switch to icon that should be provided by mod
  912. // if mod is not up to date and does have arrow tower icon yet - second setFrame call will fail and retain previously set image
  913. // for 1.2 release & later next line should be moved into 'else' block
  914. icon->setFrame(unit->creatureIconIndex(), 0);
  915. if (unit->unitType()->getId() == CreatureID::ARROW_TOWERS)
  916. icon->setFrame(owner->getSiegeShooterIconID(), 1);
  917. roundRect->setEnabled(currentTurn.has_value());
  918. if(!owner->embedded)
  919. round->setEnabled(currentTurn.has_value());
  920. amount->setText(TextOperations::formatMetric(unit->getCount(), 4));
  921. if(currentTurn && !owner->embedded)
  922. {
  923. std::string tmp = std::to_string(*currentTurn);
  924. int len = graphics->fonts[FONT_SMALL]->getStringWidth(tmp);
  925. roundRect->pos.w = len + 6;
  926. round->setText(tmp);
  927. }
  928. if(stateIcon)
  929. {
  930. if(unit->defended((int)turn) || (turn > 0 && unit->defended((int)turn - 1)))
  931. {
  932. stateIcon->setFrame(0, 0);
  933. stateIcon->visible = true;
  934. }
  935. else if(unit->waited((int)turn))
  936. {
  937. stateIcon->setFrame(1, 0);
  938. stateIcon->visible = true;
  939. }
  940. else
  941. {
  942. stateIcon->visible = false;
  943. }
  944. }
  945. }
  946. else
  947. {
  948. boundUnitID = std::nullopt;
  949. background->colorize(PlayerColor::NEUTRAL);
  950. icon->visible = false;
  951. icon->setFrame(0);
  952. amount->setText("");
  953. if(stateIcon)
  954. stateIcon->visible = false;
  955. }
  956. }
  957. std::optional<uint32_t> StackQueue::StackBox::getBoundUnitID() const
  958. {
  959. return boundUnitID;
  960. }
  961. bool StackQueue::StackBox::isBoundUnitHighlighted() const
  962. {
  963. auto unitIdsToHighlight = owner->owner.stacksController->getHoveredStacksUnitIds();
  964. return vstd::contains(unitIdsToHighlight, getBoundUnitID());
  965. }
  966. void StackQueue::StackBox::showAll(Canvas & to)
  967. {
  968. CIntObject::showAll(to);
  969. if(isBoundUnitHighlighted())
  970. to.drawBorder(background->pos, Colors::CYAN, 2);
  971. }
  972. void StackQueue::StackBox::show(Canvas & to)
  973. {
  974. CIntObject::show(to);
  975. if(isBoundUnitHighlighted())
  976. to.drawBorder(background->pos, Colors::CYAN, 2);
  977. }
  978. void StackQueue::StackBox::showPopupWindow(const Point & cursorPosition)
  979. {
  980. auto stacks = owner->owner.getBattle()->battleGetAllStacks();
  981. for(const CStack * stack : stacks)
  982. if(boundUnitID.has_value() && stack->unitId() == *boundUnitID)
  983. GH.windows().createAndPushWindow<CStackWindow>(stack, true);
  984. }