BattleInterfaceClasses.cpp 39 KB

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