BattleInterfaceClasses.cpp 38 KB

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