BattleInterfaceClasses.cpp 40 KB

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