GUIClasses.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796
  1. /*
  2. * GUIClasses.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 "GUIClasses.h"
  12. #include "CCastleInterface.h"
  13. #include "CCreatureWindow.h"
  14. #include "CHeroWindow.h"
  15. #include "InfoWindows.h"
  16. #include "../CServerHandler.h"
  17. #include "../Client.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../GameEngine.h"
  20. #include "../GameInstance.h"
  21. #include "../gui/CursorHandler.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../widgets/CComponent.h"
  25. #include "../widgets/CGarrisonInt.h"
  26. #include "../widgets/CreatureCostBox.h"
  27. #include "../widgets/CTextInput.h"
  28. #include "../widgets/Buttons.h"
  29. #include "../widgets/Slider.h"
  30. #include "../widgets/TextControls.h"
  31. #include "../widgets/ObjectLists.h"
  32. #include "../widgets/VideoWidget.h"
  33. #include "../widgets/GraphicalPrimitiveCanvas.h"
  34. #include "../render/Canvas.h"
  35. #include "../render/IRenderHandler.h"
  36. #include "../render/IImage.h"
  37. #include "../render/IFont.h"
  38. #include "../../CCallback.h"
  39. #include "../lib/entities/building/CBuilding.h"
  40. #include "../lib/entities/faction/CTownHandler.h"
  41. #include "../lib/entities/hero/CHeroHandler.h"
  42. #include "../lib/mapObjectConstructors/CObjectClassesHandler.h"
  43. #include "../lib/mapObjectConstructors/CommonConstructors.h"
  44. #include "../lib/mapObjects/CGHeroInstance.h"
  45. #include "../lib/mapObjects/CGMarket.h"
  46. #include "../lib/mapObjects/CGTownInstance.h"
  47. #include "../lib/gameState/CGameState.h"
  48. #include "../lib/gameState/SThievesGuildInfo.h"
  49. #include "../lib/gameState/TavernHeroesPool.h"
  50. #include "../lib/gameState/UpgradeInfo.h"
  51. #include "../lib/texts/CGeneralTextHandler.h"
  52. #include "../lib/texts/TextOperations.h"
  53. #include "../lib/IGameSettings.h"
  54. #include "../lib/ConditionalWait.h"
  55. #include "../lib/CConfigHandler.h"
  56. #include "../lib/CRandomGenerator.h"
  57. #include "../lib/CSkillHandler.h"
  58. #include "../lib/CSoundBase.h"
  59. CRecruitmentWindow::CCreatureCard::CCreatureCard(CRecruitmentWindow * window, const CCreature * crea, int totalAmount)
  60. : CIntObject(LCLICK | SHOW_POPUP),
  61. parent(window),
  62. selected(false),
  63. creature(crea),
  64. amount(totalAmount)
  65. {
  66. OBJECT_CONSTRUCTION;
  67. animation = std::make_shared<CCreaturePic>(1, 1, creature, true, true);
  68. // 1 + 1 px for borders
  69. pos.w = animation->pos.w + 2;
  70. pos.h = animation->pos.h + 2;
  71. }
  72. void CRecruitmentWindow::CCreatureCard::select(bool on)
  73. {
  74. selected = on;
  75. redraw();
  76. }
  77. void CRecruitmentWindow::CCreatureCard::clickPressed(const Point & cursorPosition)
  78. {
  79. parent->select(this->shared_from_this());
  80. }
  81. void CRecruitmentWindow::CCreatureCard::showPopupWindow(const Point & cursorPosition)
  82. {
  83. ENGINE->windows().createAndPushWindow<CStackWindow>(creature, true);
  84. }
  85. void CRecruitmentWindow::CCreatureCard::showAll(Canvas & to)
  86. {
  87. CIntObject::showAll(to);
  88. if(selected)
  89. to.drawBorder(pos, Colors::RED);
  90. else
  91. to.drawBorder(pos, Colors::YELLOW);
  92. }
  93. void CRecruitmentWindow::select(std::shared_ptr<CCreatureCard> card)
  94. {
  95. if(card == selected)
  96. return;
  97. if(selected)
  98. selected->select(false);
  99. selected = card;
  100. if(selected)
  101. selected->select(true);
  102. if(card)
  103. {
  104. si32 maxAmount = card->creature->maxAmount(GAME->interface()->cb->getResourceAmount());
  105. vstd::amin(maxAmount, card->amount);
  106. slider->setAmount(maxAmount);
  107. if(slider->getValue() != maxAmount)
  108. slider->scrollTo(maxAmount);
  109. else // if slider already at 0 - emulate call to sliderMoved()
  110. sliderMoved(maxAmount);
  111. costPerTroopValue->createItems(card->creature->getFullRecruitCost());
  112. totalCostValue->createItems(card->creature->getFullRecruitCost());
  113. costPerTroopValue->set(card->creature->getFullRecruitCost());
  114. totalCostValue->set(card->creature->getFullRecruitCost() * maxAmount);
  115. //Recruit %s
  116. title->setText(boost::str(boost::format(LIBRARY->generaltexth->tcommands[21]) % card->creature->getNamePluralTranslated()));
  117. maxButton->block(maxAmount == 0);
  118. slider->block(maxAmount == 0);
  119. }
  120. }
  121. void CRecruitmentWindow::close()
  122. {
  123. if (onClose)
  124. onClose();
  125. CStatusbarWindow::close();
  126. }
  127. void CRecruitmentWindow::buy()
  128. {
  129. CreatureID crid = selected->creature->getId();
  130. SlotID dstslot = dst->getSlotFor(crid);
  131. if(!dstslot.validSlot() && (selected->creature->warMachine == ArtifactID::NONE)) //no available slot
  132. {
  133. std::pair<SlotID, SlotID> toMerge;
  134. bool allowMerge = GAME->interface()->cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  135. if (allowMerge && dst->mergeableStacks(toMerge))
  136. {
  137. GAME->interface()->cb->mergeStacks( dst, dst, toMerge.first, toMerge.second);
  138. }
  139. else
  140. {
  141. std::string txt;
  142. if(dwelling->ID != Obj::TOWN)
  143. {
  144. txt = LIBRARY->generaltexth->allTexts[425]; //The %s would join your hero, but there aren't enough provisions to support them.
  145. boost::algorithm::replace_first(txt, "%s", slider->getValue() > 1 ? LIBRARY->creh->objects[crid]->getNamePluralTranslated() : LIBRARY->creh->objects[crid]->getNameSingularTranslated());
  146. }
  147. else
  148. {
  149. txt = LIBRARY->generaltexth->allTexts[17]; //There is no room in the garrison for this army.
  150. }
  151. GAME->interface()->showInfoDialog(txt);
  152. return;
  153. }
  154. }
  155. onRecruit(crid, slider->getValue());
  156. if(level >= 0)
  157. close();
  158. }
  159. void CRecruitmentWindow::showAll(Canvas & to)
  160. {
  161. CWindowObject::showAll(to);
  162. Rect(172, 222, 67, 42) + pos.topLeft();
  163. // recruit\total values
  164. to.drawBorder(Rect(172, 222, 67, 42) + pos.topLeft(), Colors::YELLOW);
  165. to.drawBorder(Rect(246, 222, 67, 42) + pos.topLeft(), Colors::YELLOW);
  166. //cost boxes
  167. to.drawBorder(Rect( 64, 222, 99, 76) + pos.topLeft(), Colors::YELLOW);
  168. to.drawBorder(Rect(322, 222, 99, 76) + pos.topLeft(), Colors::YELLOW);
  169. //buttons borders
  170. to.drawBorder(Rect(133, 312, 66, 34) + pos.topLeft(), Colors::METALLIC_GOLD);
  171. to.drawBorder(Rect(211, 312, 66, 34) + pos.topLeft(), Colors::METALLIC_GOLD);
  172. to.drawBorder(Rect(289, 312, 66, 34) + pos.topLeft(), Colors::METALLIC_GOLD);
  173. }
  174. CRecruitmentWindow::CRecruitmentWindow(const CGDwelling * Dwelling, int Level, const CArmedInstance * Dst, const std::function<void(CreatureID,int)> & Recruit, const std::function<void()> & onClose, int y_offset):
  175. CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPRCRT")),
  176. onRecruit(Recruit),
  177. onClose(onClose),
  178. level(Level),
  179. dst(Dst),
  180. selected(nullptr),
  181. dwelling(Dwelling)
  182. {
  183. moveBy(Point(0, y_offset));
  184. OBJECT_CONSTRUCTION;
  185. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  186. slider = std::make_shared<CSlider>(Point(176, 279), 135, std::bind(&CRecruitmentWindow::sliderMoved, this, _1), 0, 0, 0, Orientation::HORIZONTAL);
  187. maxButton = std::make_shared<CButton>(Point(134, 313), AnimationPath::builtin("IRCBTNS.DEF"), LIBRARY->generaltexth->zelp[553], std::bind(&CSlider::scrollToMax, slider), EShortcut::RECRUITMENT_MAX);
  188. buyButton = std::make_shared<CButton>(Point(212, 313), AnimationPath::builtin("IBY6432.DEF"), LIBRARY->generaltexth->zelp[554], std::bind(&CRecruitmentWindow::buy, this), EShortcut::GLOBAL_ACCEPT);
  189. cancelButton = std::make_shared<CButton>(Point(290, 313), AnimationPath::builtin("ICN6432.DEF"), LIBRARY->generaltexth->zelp[555], std::bind(&CRecruitmentWindow::close, this), EShortcut::GLOBAL_CANCEL);
  190. title = std::make_shared<CLabel>(243, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW);
  191. availableValue = std::make_shared<CLabel>(205, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  192. toRecruitValue = std::make_shared<CLabel>(279, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  193. costPerTroopValue = std::make_shared<CreatureCostBox>(Rect(65, 222, 97, 74), LIBRARY->generaltexth->allTexts[346]);
  194. totalCostValue = std::make_shared<CreatureCostBox>(Rect(323, 222, 97, 74), LIBRARY->generaltexth->allTexts[466]);
  195. availableTitle = std::make_shared<CLabel>(205, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->allTexts[465]);
  196. toRecruitTitle = std::make_shared<CLabel>(279, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->allTexts[16]);
  197. availableCreaturesChanged();
  198. }
  199. void CRecruitmentWindow::availableCreaturesChanged()
  200. {
  201. OBJECT_CONSTRUCTION;
  202. size_t selectedIndex = 0;
  203. if(!cards.empty() && selected) // find position of selected item
  204. selectedIndex = std::find(cards.begin(), cards.end(), selected) - cards.begin();
  205. select(nullptr);
  206. cards.clear();
  207. for(int i=0; i<dwelling->creatures.size(); i++)
  208. {
  209. //find appropriate level
  210. if(level >= 0 && i != level)
  211. continue;
  212. int amount = dwelling->creatures[i].first;
  213. //create new cards
  214. for(auto & creature : boost::adaptors::reverse(dwelling->creatures[i].second))
  215. cards.push_back(std::make_shared<CCreatureCard>(this, creature.toCreature(), amount));
  216. }
  217. const int creatureWidth = 102;
  218. //normal distance between cards - 18px
  219. int requiredSpace = 18;
  220. //maximum distance we can use without reaching window borders
  221. int availableSpace = pos.w - 50 - creatureWidth * (int)cards.size();
  222. if (cards.size() > 1) // avoid division by zero
  223. availableSpace /= (int)cards.size() - 1;
  224. else
  225. availableSpace = 0;
  226. assert(availableSpace >= 0);
  227. const int spaceBetween = std::min(requiredSpace, availableSpace);
  228. const int totalCreatureWidth = spaceBetween + creatureWidth;
  229. //now we know total amount of cards and can move them to correct position
  230. int curx = pos.w / 2 - (creatureWidth*(int)cards.size()/2) - (spaceBetween*((int)cards.size()-1)/2);
  231. for(auto & card : cards)
  232. {
  233. card->moveBy(Point(curx, 64));
  234. curx += totalCreatureWidth;
  235. }
  236. //restore selection
  237. select(cards[selectedIndex]);
  238. if(slider->getValue() == slider->getAmount())
  239. slider->scrollToMax();
  240. else // if slider already at 0 - emulate call to sliderMoved()
  241. sliderMoved(slider->getAmount());
  242. }
  243. void CRecruitmentWindow::sliderMoved(int to)
  244. {
  245. if(!selected)
  246. return;
  247. buyButton->block(!to || !GAME->interface()->makingTurn);
  248. availableValue->setText(std::to_string(selected->amount - to));
  249. toRecruitValue->setText(std::to_string(to));
  250. totalCostValue->set(selected->creature->getFullRecruitCost() * to);
  251. }
  252. CSplitWindow::CSplitWindow(const CCreature * creature, std::function<void(int, int)> callback_, int leftMin_, int rightMin_, int leftAmount_, int rightAmount_)
  253. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("GPUCRDIV")),
  254. callback(callback_),
  255. leftAmount(leftAmount_),
  256. rightAmount(rightAmount_),
  257. leftMin(leftMin_),
  258. rightMin(rightMin_)
  259. {
  260. OBJECT_CONSTRUCTION;
  261. int total = leftAmount + rightAmount;
  262. int leftMax = total - rightMin;
  263. int rightMax = total - leftMin;
  264. ok = std::make_shared<CButton>(Point(20, 263), AnimationPath::builtin("IOK6432"), CButton::tooltip(), std::bind(&CSplitWindow::apply, this), EShortcut::GLOBAL_ACCEPT);
  265. cancel = std::make_shared<CButton>(Point(214, 263), AnimationPath::builtin("ICN6432"), CButton::tooltip(), std::bind(&CSplitWindow::close, this), EShortcut::GLOBAL_CANCEL);
  266. int sliderPosition = total - leftMin - rightMin;
  267. leftInput = std::make_shared<CTextInput>(Rect(20, 218, 100, 36), FONT_BIG, ETextAlignment::CENTER, true);
  268. rightInput = std::make_shared<CTextInput>(Rect(176, 218, 100, 36), FONT_BIG, ETextAlignment::CENTER, true);
  269. leftInput->setCallback(std::bind(&CSplitWindow::setAmountText, this, _1, true));
  270. rightInput->setCallback(std::bind(&CSplitWindow::setAmountText, this, _1, false));
  271. //add filters to allow only number input
  272. leftInput->setFilterNumber(leftMin, leftMax);
  273. rightInput->setFilterNumber(rightMin, rightMax);
  274. leftInput->setText(std::to_string(leftAmount));
  275. rightInput->setText(std::to_string(rightAmount));
  276. animLeft = std::make_shared<CCreaturePic>(20, 54, creature, true, false);
  277. animRight = std::make_shared<CCreaturePic>(177, 54,creature, true, false);
  278. slider = std::make_shared<CSlider>(Point(21, 194), 257, std::bind(&CSplitWindow::sliderMoved, this, _1), 0, sliderPosition, rightAmount - rightMin, Orientation::HORIZONTAL);
  279. std::string titleStr = LIBRARY->generaltexth->allTexts[256];
  280. boost::algorithm::replace_first(titleStr,"%s", creature->getNamePluralTranslated());
  281. title = std::make_shared<CLabel>(150, 34, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  282. }
  283. void CSplitWindow::setAmountText(std::string text, bool left)
  284. {
  285. int amount = 0;
  286. if(text.length())
  287. {
  288. try
  289. {
  290. amount = boost::lexical_cast<int>(text);
  291. }
  292. catch(boost::bad_lexical_cast &)
  293. {
  294. amount = left ? leftAmount : rightAmount;
  295. }
  296. int total = leftAmount + rightAmount;
  297. if(amount > total)
  298. amount = total;
  299. }
  300. setAmount(amount, left);
  301. slider->scrollTo(rightAmount - rightMin);
  302. }
  303. void CSplitWindow::setAmount(int value, bool left)
  304. {
  305. int total = leftAmount + rightAmount;
  306. leftAmount = left ? value : total - value;
  307. rightAmount = left ? total - value : value;
  308. leftInput->setText(std::to_string(leftAmount));
  309. rightInput->setText(std::to_string(rightAmount));
  310. }
  311. void CSplitWindow::apply()
  312. {
  313. callback(leftAmount, rightAmount);
  314. close();
  315. }
  316. void CSplitWindow::sliderMoved(int to)
  317. {
  318. setAmount(rightMin + to, false);
  319. }
  320. CLevelWindow::CLevelWindow(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, std::function<void(ui32)> callback)
  321. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("LVLUPBKG")),
  322. cb(callback)
  323. {
  324. OBJECT_CONSTRUCTION;
  325. GAME->interface()->showingDialog->setBusy();
  326. if(!skills.empty())
  327. {
  328. std::vector<std::shared_ptr<CSelectableComponent>> comps;
  329. for(auto & skill : skills)
  330. {
  331. auto comp = std::make_shared<CSelectableComponent>(ComponentType::SEC_SKILL, skill, hero->getSecSkillLevel(SecondarySkill(skill))+1, CComponent::medium);
  332. comp->onChoose = std::bind(&CLevelWindow::close, this);
  333. comps.push_back(comp);
  334. }
  335. box = std::make_shared<CComponentBox>(comps, Rect(75, 300, pos.w - 150, 100));
  336. }
  337. portrait = std::make_shared<CHeroArea>(170, 66, hero);
  338. portrait->addClickCallback(nullptr);
  339. portrait->addRClickCallback([hero](){ ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(hero)); });
  340. ok = std::make_shared<CButton>(Point(297, 413), AnimationPath::builtin("IOKAY"), CButton::tooltip(), std::bind(&CLevelWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  341. //%s has gained a level.
  342. mainTitle = std::make_shared<CLabel>(192, 33, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(LIBRARY->generaltexth->allTexts[444]) % hero->getNameTranslated()));
  343. //%s is now a level %d %s.
  344. std::string levelTitleText = LIBRARY->generaltexth->translate("core.genrltxt.445");
  345. boost::replace_first(levelTitleText, "%s", hero->getNameTranslated());
  346. boost::replace_first(levelTitleText, "%d", std::to_string(hero->level));
  347. boost::replace_first(levelTitleText, "%s", hero->getClassNameTranslated());
  348. levelTitle = std::make_shared<CLabel>(192, 162, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, levelTitleText);
  349. skillIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("PSKIL42"), static_cast<int>(pskill), 0, 174, 190);
  350. skillValue = std::make_shared<CLabel>(192, 253, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->primarySkillNames[static_cast<int>(pskill)] + " +1");
  351. }
  352. void CLevelWindow::close()
  353. {
  354. //FIXME: call callback if there was nothing to select?
  355. if (box && box->selectedIndex() != -1)
  356. cb(box->selectedIndex());
  357. GAME->interface()->showingDialog->setFree();
  358. CWindowObject::close();
  359. }
  360. CTavernWindow::CTavernWindow(const CGObjectInstance * TavernObj, const std::function<void()> & onWindowClosed)
  361. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPTAVERN")),
  362. onWindowClosed(onWindowClosed),
  363. tavernObj(TavernObj),
  364. heroToInvite(nullptr)
  365. {
  366. OBJECT_CONSTRUCTION;
  367. std::vector<const CGHeroInstance*> h = GAME->interface()->cb->getAvailableHeroes(TavernObj);
  368. if(h.size() < 2)
  369. h.resize(2, nullptr);
  370. selected = 0;
  371. if(!h[0])
  372. selected = 1;
  373. if(!h[0] && !h[1])
  374. selected = -1;
  375. oldSelected = -1;
  376. h1 = std::make_shared<HeroPortrait>(selected, 0, 72, 299, h[0], [this]() { if(!recruit->isBlocked()) recruitb(); });
  377. h2 = std::make_shared<HeroPortrait>(selected, 1, 162, 299, h[1], [this]() { if(!recruit->isBlocked()) recruitb(); });
  378. title = std::make_shared<CLabel>(197, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[37]);
  379. cost = std::make_shared<CLabel>(320, 328, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(GameConstants::HERO_GOLD_COST));
  380. heroDescription = std::make_shared<CTextBox>("", Rect(30, 373, 233, 35), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  381. heroesForHire = std::make_shared<CLabel>(145, 283, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[38]);
  382. rumor = std::make_shared<CTextBox>(GAME->interface()->cb->getTavernRumor(tavernObj), Rect(32, 188, 330, 66), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  383. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  384. cancel = std::make_shared<CButton>(Point(310, 428), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(LIBRARY->generaltexth->tavernInfo[7]), std::bind(&CTavernWindow::close, this), EShortcut::GLOBAL_CANCEL);
  385. recruit = std::make_shared<CButton>(Point(272, 355), AnimationPath::builtin("TPTAV01.DEF"), CButton::tooltip(), std::bind(&CTavernWindow::recruitb, this), EShortcut::GLOBAL_ACCEPT);
  386. thiefGuild = std::make_shared<CButton>(Point(22, 428), AnimationPath::builtin("TPTAV02.DEF"), CButton::tooltip(LIBRARY->generaltexth->tavernInfo[5]), std::bind(&CTavernWindow::thievesguildb, this), EShortcut::ADVENTURE_THIEVES_GUILD);
  387. if(!GAME->interface()->makingTurn)
  388. {
  389. recruit->block(true);
  390. }
  391. else if(GAME->interface()->cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //not enough gold
  392. {
  393. recruit->addHoverText(EButtonState::NORMAL, LIBRARY->generaltexth->tavernInfo[0]); //Cannot afford a Hero
  394. recruit->block(true);
  395. }
  396. else if(GAME->interface()->cb->howManyHeroes(true) >= GAME->interface()->cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP))
  397. {
  398. MetaString message;
  399. message.appendTextID("core.tvrninfo.1");
  400. message.replaceNumber(GAME->interface()->cb->howManyHeroes(true));
  401. //Cannot recruit. You already have %d Heroes.
  402. recruit->addHoverText(EButtonState::NORMAL, message.toString());
  403. recruit->block(true);
  404. }
  405. else if(GAME->interface()->cb->howManyHeroes(false) >= GAME->interface()->cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  406. {
  407. MetaString message;
  408. message.appendTextID("core.tvrninfo.1");
  409. message.replaceNumber(GAME->interface()->cb->howManyHeroes(false));
  410. recruit->addHoverText(EButtonState::NORMAL, message.toString());
  411. recruit->block(true);
  412. }
  413. else if(dynamic_cast<const CGTownInstance *>(TavernObj) && dynamic_cast<const CGTownInstance *>(TavernObj)->visitingHero)
  414. {
  415. recruit->addHoverText(EButtonState::NORMAL, LIBRARY->generaltexth->tavernInfo[2]); //Cannot recruit. You already have a Hero in this town.
  416. recruit->block(true);
  417. }
  418. else
  419. {
  420. if(selected == -1)
  421. recruit->block(true);
  422. }
  423. if(GAME->interface()->castleInt)
  424. videoPlayer = std::make_shared<VideoWidget>(Point(70, 56), GAME->interface()->castleInt->town->getTown()->clientInfo.tavernVideo, false);
  425. else if(const auto * townObj = dynamic_cast<const CGTownInstance *>(TavernObj))
  426. videoPlayer = std::make_shared<VideoWidget>(Point(70, 56), townObj->getTown()->clientInfo.tavernVideo, false);
  427. else
  428. videoPlayer = std::make_shared<VideoWidget>(Point(70, 56), VideoPath::builtin("TAVERN.BIK"), false);
  429. addInvite();
  430. }
  431. void CTavernWindow::addInvite()
  432. {
  433. OBJECT_CONSTRUCTION;
  434. if(!GAME->interface()->cb->getSettings().getBoolean(EGameSettings::HEROES_TAVERN_INVITE))
  435. return;
  436. const auto & heroesPool = GAME->server().client->gameState()->heroesPool;
  437. for(auto & elem : heroesPool->unusedHeroesFromPool())
  438. {
  439. bool heroAvailable = heroesPool->isHeroAvailableFor(elem.first, tavernObj->getOwner());
  440. if(heroAvailable)
  441. inviteableHeroes[elem.first] = elem.second;
  442. }
  443. if(!inviteableHeroes.empty())
  444. {
  445. int imageIndex = heroToInvite ? heroToInvite->getIconIndex() : 156; // 156 => special id for random
  446. if(!heroToInvite)
  447. heroToInvite = (*RandomGeneratorUtil::nextItem(inviteableHeroes, CRandomGenerator::getDefault())).second;
  448. inviteHero = std::make_shared<CLabel>(170, 444, EFonts::FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("vcmi.tavernWindow.inviteHero"));
  449. inviteHeroImage = std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsSmall"), imageIndex, 0, 245, 428);
  450. inviteHeroImageArea = std::make_shared<LRClickableArea>(Rect(245, 428, 48, 32), [this](){ ENGINE->windows().createAndPushWindow<HeroSelector>(inviteableHeroes, [this](CGHeroInstance* h){ heroToInvite = h; addInvite(); }); }, [this](){ ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(heroToInvite)); });
  451. }
  452. }
  453. void CTavernWindow::recruitb()
  454. {
  455. const CGHeroInstance *toBuy = (selected ? h2 : h1)->h;
  456. const CGObjectInstance *obj = tavernObj;
  457. GAME->interface()->cb->recruitHero(obj, toBuy, heroToInvite ? heroToInvite->getHeroTypeID() : HeroTypeID::NONE);
  458. close();
  459. }
  460. void CTavernWindow::thievesguildb()
  461. {
  462. ENGINE->windows().createAndPushWindow<CThievesGuildWindow>(tavernObj);
  463. }
  464. void CTavernWindow::close()
  465. {
  466. if (onWindowClosed)
  467. onWindowClosed();
  468. CStatusbarWindow::close();
  469. }
  470. void CTavernWindow::show(Canvas & to)
  471. {
  472. CWindowObject::show(to);
  473. if(selected >= 0)
  474. {
  475. auto sel = selected ? h2 : h1;
  476. if(selected != oldSelected)
  477. {
  478. // Selected hero just changed. Update RECRUIT button hover text if recruitment is allowed.
  479. oldSelected = selected;
  480. heroDescription->setText(sel->description);
  481. //Recruit %s the %s
  482. if (!recruit->isBlocked())
  483. recruit->addHoverText(EButtonState::NORMAL, boost::str(boost::format(LIBRARY->generaltexth->tavernInfo[3]) % sel->h->getNameTranslated() % sel->h->getClassNameTranslated()));
  484. }
  485. to.drawBorder(Rect::createAround(sel->pos, 2), Colors::BRIGHT_YELLOW, 2);
  486. }
  487. }
  488. void CTavernWindow::HeroPortrait::clickPressed(const Point & cursorPosition)
  489. {
  490. if(h)
  491. *_sel = _id;
  492. }
  493. void CTavernWindow::HeroPortrait::clickDouble(const Point & cursorPosition)
  494. {
  495. clickPressed(cursorPosition);
  496. if(onChoose)
  497. onChoose();
  498. }
  499. void CTavernWindow::HeroPortrait::showPopupWindow(const Point & cursorPosition)
  500. {
  501. // h3 behavior - right-click also selects hero
  502. clickPressed(cursorPosition);
  503. if(h)
  504. ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(h));
  505. }
  506. CTavernWindow::HeroPortrait::HeroPortrait(int & sel, int id, int x, int y, const CGHeroInstance * H, std::function<void()> OnChoose)
  507. : CIntObject(LCLICK | DOUBLECLICK | SHOW_POPUP | HOVER),
  508. h(H), _sel(&sel), _id(id), onChoose(OnChoose)
  509. {
  510. OBJECT_CONSTRUCTION;
  511. h = H;
  512. pos.x += x;
  513. pos.y += y;
  514. pos.w = 58;
  515. pos.h = 64;
  516. if(H)
  517. {
  518. hoverName = LIBRARY->generaltexth->tavernInfo[4];
  519. boost::algorithm::replace_first(hoverName,"%s",H->getNameTranslated());
  520. int artifs = (int)h->artifactsWorn.size() + (int)h->artifactsInBackpack.size();
  521. for(int i=13; i<=17; i++) //war machines and spellbook don't count
  522. if(vstd::contains(h->artifactsWorn, ArtifactPosition(i)))
  523. artifs--;
  524. description = LIBRARY->generaltexth->allTexts[215];
  525. boost::algorithm::replace_first(description, "%s", h->getNameTranslated());
  526. boost::algorithm::replace_first(description, "%d", std::to_string(h->level));
  527. boost::algorithm::replace_first(description, "%s", h->getClassNameTranslated());
  528. boost::algorithm::replace_first(description, "%d", std::to_string(artifs));
  529. portrait = std::make_shared<CAnimImage>(AnimationPath::builtin("portraitsLarge"), h->getIconIndex());
  530. }
  531. }
  532. void CTavernWindow::HeroPortrait::hover(bool on)
  533. {
  534. //Hoverable::hover(on);
  535. if(on)
  536. ENGINE->statusbar()->write(hoverName);
  537. else
  538. ENGINE->statusbar()->clear();
  539. }
  540. CTavernWindow::HeroSelector::HeroSelector(std::map<HeroTypeID, CGHeroInstance*> InviteableHeroes, std::function<void(CGHeroInstance*)> OnChoose)
  541. : CWindowObject(BORDERED), inviteableHeroes(InviteableHeroes), onChoose(OnChoose)
  542. {
  543. OBJECT_CONSTRUCTION;
  544. pos = Rect(
  545. pos.x,
  546. pos.y,
  547. ELEM_PER_LINES * 48,
  548. std::min((int)(inviteableHeroes.size() / ELEM_PER_LINES + (inviteableHeroes.size() % ELEM_PER_LINES != 0)), MAX_LINES) * 32
  549. );
  550. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  551. if(inviteableHeroes.size() / ELEM_PER_LINES > MAX_LINES)
  552. {
  553. pos.w += 16;
  554. slider = std::make_shared<CSlider>(Point(pos.w - 16, 0), pos.h, std::bind(&CTavernWindow::HeroSelector::sliderMove, this, _1), MAX_LINES, std::ceil((double)inviteableHeroes.size() / ELEM_PER_LINES), 0, Orientation::VERTICAL, CSlider::BROWN);
  555. slider->setPanningStep(32);
  556. slider->setScrollBounds(Rect(-pos.w + slider->pos.w, 0, pos.w, pos.h));
  557. }
  558. recreate();
  559. center();
  560. }
  561. void CTavernWindow::HeroSelector::sliderMove(int slidPos)
  562. {
  563. if(!slider)
  564. return; // ignore spurious call when slider is being created
  565. recreate();
  566. redraw();
  567. }
  568. void CTavernWindow::HeroSelector::recreate()
  569. {
  570. OBJECT_CONSTRUCTION;
  571. int sliderLine = slider ? slider->getValue() : 0;
  572. int x = 0;
  573. int y = -sliderLine;
  574. portraits.clear();
  575. portraitAreas.clear();
  576. for(auto & h : inviteableHeroes)
  577. {
  578. if(y >= 0 && y <= MAX_LINES - 1)
  579. {
  580. portraits.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsSmall"), (*LIBRARY->heroh)[h.first]->imageIndex, 0, x * 48, y * 32));
  581. portraitAreas.push_back(std::make_shared<LRClickableArea>(Rect(x * 48, y * 32, 48, 32), [this, h](){ close(); onChoose(inviteableHeroes[h.first]); }, [this, h](){ ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(inviteableHeroes[h.first])); }));
  582. }
  583. if(x > 0 && x % 15 == 0)
  584. {
  585. x = 0;
  586. y++;
  587. }
  588. else
  589. x++;
  590. }
  591. }
  592. CShipyardWindow::CShipyardWindow(const TResources & cost, int state, BoatId boatType, const std::function<void()> & onBuy)
  593. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPSHIP"))
  594. {
  595. OBJECT_CONSTRUCTION;
  596. bgWater = std::make_shared<CPicture>(ImagePath::builtin("TPSHIPBK"), 100, 69);
  597. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::BOAT, boatType);
  598. auto boatConstructor = std::dynamic_pointer_cast<const BoatInstanceConstructor>(handler);
  599. assert(boatConstructor);
  600. if (boatConstructor)
  601. {
  602. AnimationPath boatFilename = boatConstructor->getBoatAnimationName();
  603. Point waterCenter = Point(bgWater->pos.x+bgWater->pos.w/2, bgWater->pos.y+bgWater->pos.h/2);
  604. bgShip = std::make_shared<CShowableAnim>(120, 96, boatFilename, CShowableAnim::MAP_OBJECT_MODE, 100, 7);
  605. bgShip->center(waterCenter);
  606. bgWater->needRefresh = true;
  607. }
  608. // Create resource icons and costs.
  609. std::string goldValue = std::to_string(cost[EGameResID::GOLD]);
  610. std::string woodValue = std::to_string(cost[EGameResID::WOOD]);
  611. goldCost = std::make_shared<CLabel>(118, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, goldValue);
  612. woodCost = std::make_shared<CLabel>(212, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, woodValue);
  613. goldPic = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 100, 244);
  614. woodPic = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::WOOD), 0, 196, 244);
  615. quit = std::make_shared<CButton>(Point(224, 312), AnimationPath::builtin("ICANCEL"), CButton::tooltip(LIBRARY->generaltexth->allTexts[599]), std::bind(&CShipyardWindow::close, this), EShortcut::GLOBAL_CANCEL);
  616. build = std::make_shared<CButton>(Point(42, 312), AnimationPath::builtin("IBUY30"), CButton::tooltip(LIBRARY->generaltexth->allTexts[598]), std::bind(&CShipyardWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  617. build->addCallback(onBuy);
  618. for(GameResID i = EGameResID::WOOD; i <= EGameResID::GOLD; ++i)
  619. {
  620. if(cost[i] > GAME->interface()->cb->getResourceAmount(i))
  621. {
  622. build->block(true);
  623. break;
  624. }
  625. }
  626. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  627. title = std::make_shared<CLabel>(164, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[13]);
  628. costLabel = std::make_shared<CLabel>(164, 220, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->jktexts[14]);
  629. }
  630. void CTransformerWindow::CItem::move()
  631. {
  632. if(left)
  633. moveBy(Point(289, 0));
  634. else
  635. moveBy(Point(-289, 0));
  636. left = !left;
  637. }
  638. void CTransformerWindow::CItem::clickPressed(const Point & cursorPosition)
  639. {
  640. move();
  641. parent->redraw();
  642. }
  643. void CTransformerWindow::CItem::update()
  644. {
  645. icon->setFrame(parent->army->getCreature(SlotID(id))->getId() + 2);
  646. }
  647. CTransformerWindow::CItem::CItem(CTransformerWindow * parent_, int size_, int id_)
  648. : CIntObject(LCLICK),
  649. id(id_),
  650. size(size_),
  651. parent(parent_)
  652. {
  653. OBJECT_CONSTRUCTION;
  654. left = true;
  655. pos.w = 58;
  656. pos.h = 64;
  657. pos.x += 45 + (id%3)*83 + id/6*83;
  658. pos.y += 109 + (id/3)*98;
  659. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), parent->army->getCreature(SlotID(id))->getId() + 2);
  660. count = std::make_shared<CLabel>(28, 76,FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(size));
  661. }
  662. void CTransformerWindow::makeDeal()
  663. {
  664. for(auto & elem : items)
  665. {
  666. if(!elem->left)
  667. GAME->interface()->cb->trade(market->getObjInstanceID(), EMarketMode::CREATURE_UNDEAD, SlotID(elem->id), {}, {}, hero);
  668. }
  669. }
  670. void CTransformerWindow::addAll()
  671. {
  672. for(auto & elem : items)
  673. {
  674. if(elem->left)
  675. elem->move();
  676. }
  677. redraw();
  678. }
  679. void CTransformerWindow::updateGarrisons()
  680. {
  681. for(auto & item : items)
  682. item->update();
  683. }
  684. bool CTransformerWindow::holdsGarrison(const CArmedInstance * army)
  685. {
  686. return army == hero;
  687. }
  688. CTransformerWindow::CTransformerWindow(const IMarket * _market, const CGHeroInstance * _hero, const std::function<void()> & onWindowClosed)
  689. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("SKTRNBK")),
  690. hero(_hero),
  691. onWindowClosed(onWindowClosed),
  692. market(_market)
  693. {
  694. OBJECT_CONSTRUCTION;
  695. if(hero)
  696. army = hero;
  697. else
  698. army = dynamic_cast<const CArmedInstance *>(market); //for town only
  699. if(army)
  700. {
  701. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  702. {
  703. if(army->getCreature(SlotID(i)))
  704. items.push_back(std::make_shared<CItem>(this, army->getStackCount(SlotID(i)), i));
  705. }
  706. }
  707. all = std::make_shared<CButton>(Point(146, 416), AnimationPath::builtin("ALTARMY.DEF"), LIBRARY->generaltexth->zelp[590], [&](){ addAll(); }, EShortcut::RECRUITMENT_UPGRADE_ALL);
  708. convert = std::make_shared<CButton>(Point(269, 416), AnimationPath::builtin("ALTSACR.DEF"), LIBRARY->generaltexth->zelp[591], [&](){ makeDeal(); }, EShortcut::GLOBAL_ACCEPT);
  709. cancel = std::make_shared<CButton>(Point(392, 416), AnimationPath::builtin("ICANCEL.DEF"), LIBRARY->generaltexth->zelp[592], [&](){ close(); },EShortcut::GLOBAL_CANCEL);
  710. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  711. titleLeft = std::make_shared<CLabel>(153, 29,FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->allTexts[485]);//holding area
  712. titleRight = std::make_shared<CLabel>(153+295, 29, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->allTexts[486]);//transformer
  713. helpLeft = std::make_shared<CTextBox>(LIBRARY->generaltexth->allTexts[487], Rect(26, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//move creatures to create skeletons
  714. helpRight = std::make_shared<CTextBox>(LIBRARY->generaltexth->allTexts[488], Rect(320, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//creatures here will become skeletons
  715. }
  716. void CTransformerWindow::close()
  717. {
  718. if (onWindowClosed)
  719. onWindowClosed();
  720. CStatusbarWindow::close();
  721. }
  722. CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int Y)
  723. : CIntObject(LCLICK | SHOW_POPUP | HOVER),
  724. ID(_ID),
  725. parent(_parent)
  726. {
  727. OBJECT_CONSTRUCTION;
  728. pos.x += X;
  729. pos.y += Y;
  730. skill = std::make_shared<CSecSkillPlace>(Point(), CSecSkillPlace::ImageSize::MEDIUM, _ID, 1);
  731. skill->setClickPressedCallback([this](const CComponentHolder&, const Point& cursorPosition)
  732. {
  733. bool skillKnown = parent->hero->getSecSkillLevel(ID);
  734. bool canLearn = parent->hero->canLearnSkill(ID);
  735. if(!skillKnown && canLearn)
  736. ENGINE->windows().createAndPushWindow<CUnivConfirmWindow>(parent, ID, GAME->interface()->cb->getResourceAmount(EGameResID::GOLD) >= 2000);
  737. });
  738. update();
  739. }
  740. void CUniversityWindow::CItem::update()
  741. {
  742. bool skillKnown = parent->hero->getSecSkillLevel(ID);
  743. bool canLearn = parent->hero->canLearnSkill(ID);
  744. ImagePath image;
  745. if (skillKnown)
  746. image = ImagePath::builtin("UNIVGOLD");
  747. else if (canLearn)
  748. image = ImagePath::builtin("UNIVGREN");
  749. else
  750. image = ImagePath::builtin("UNIVRED");
  751. OBJECT_CONSTRUCTION;
  752. topBar = std::make_shared<CPicture>(image, Point(-28, -22));
  753. bottomBar = std::make_shared<CPicture>(image, Point(-28, 48));
  754. // needs to be on top of background bars
  755. name = std::make_shared<CLabel>(22, -13, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, ID.toEntity(LIBRARY)->getNameTranslated());
  756. level = std::make_shared<CLabel>(22, 57, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->levels[0]);
  757. }
  758. CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, BuildingID building, const IMarket * _market, const std::function<void()> & onWindowClosed)
  759. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("UNIVERS1")),
  760. hero(_hero),
  761. onWindowClosed(onWindowClosed),
  762. market(_market)
  763. {
  764. OBJECT_CONSTRUCTION;
  765. std::string titleStr = LIBRARY->generaltexth->allTexts[602];
  766. std::string speechStr = LIBRARY->generaltexth->allTexts[603];
  767. if(auto town = dynamic_cast<const CGTownInstance *>(_market))
  768. {
  769. auto faction = town->getTown()->faction->getId();
  770. titlePic = std::make_shared<CAnimImage>((*LIBRARY->townh)[faction]->town->clientInfo.buildingsIcons, building);
  771. }
  772. else if(auto uni = dynamic_cast<const CGUniversity *>(_market); uni->appearance)
  773. {
  774. titlePic = std::make_shared<CAnimImage>(uni->appearance->animationFile, 0, 0, 0, 0, CShowableAnim::MAP_OBJECT_MODE);
  775. titleStr = uni->getObjectName();
  776. speechStr = uni->getSpeechTranslated();
  777. }
  778. else
  779. {
  780. titlePic = std::make_shared<CPicture>(ImagePath::builtin("UNIVBLDG"));
  781. }
  782. titlePic->center(Point(232 + pos.x, 76 + pos.y));
  783. clerkSpeech = std::make_shared<CTextBox>(speechStr, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  784. title = std::make_shared<CLabel>(231, 26, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  785. std::vector<TradeItemBuy> goods = market->availableItemsIds(EMarketMode::RESOURCE_SKILL);
  786. for(int i=0; i<goods.size(); i++)//prepare clickable items
  787. items.push_back(std::make_shared<CItem>(this, goods[i].as<SecondarySkill>(), 54+i*104, 234));
  788. cancel = std::make_shared<CButton>(Point(200, 313), AnimationPath::builtin("IOKAY.DEF"), LIBRARY->generaltexth->zelp[632], [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  789. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  790. }
  791. void CUniversityWindow::close()
  792. {
  793. if (onWindowClosed)
  794. onWindowClosed();
  795. CStatusbarWindow::close();
  796. }
  797. void CUniversityWindow::updateSecondarySkills()
  798. {
  799. for (auto const & item : items)
  800. item->update();
  801. }
  802. void CUniversityWindow::makeDeal(SecondarySkill skill)
  803. {
  804. GAME->interface()->cb->trade(market->getObjInstanceID(), EMarketMode::RESOURCE_SKILL, GameResID(GameResID::GOLD), skill, 1, hero);
  805. }
  806. CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * owner_, SecondarySkill SKILL, bool available)
  807. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("UNIVERS2.PCX")),
  808. owner(owner_)
  809. {
  810. OBJECT_CONSTRUCTION;
  811. std::string text = LIBRARY->generaltexth->allTexts[608];
  812. boost::replace_first(text, "%s", LIBRARY->generaltexth->levels[0]);
  813. boost::replace_first(text, "%s", LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  814. boost::replace_first(text, "%d", "2000");
  815. clerkSpeech = std::make_shared<CTextBox>(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  816. name = std::make_shared<CLabel>(230, 37, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  817. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("SECSKILL"), SKILL*3+3, 0, 211, 51);
  818. level = std::make_shared<CLabel>(230, 107, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->levels[1]);
  819. costIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 210, 210);
  820. cost = std::make_shared<CLabel>(230, 267, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "2000");
  821. std::string hoverText = LIBRARY->generaltexth->allTexts[609];
  822. boost::replace_first(hoverText, "%s", LIBRARY->generaltexth->levels[0]+ " " + LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  823. text = LIBRARY->generaltexth->zelp[633].second;
  824. boost::replace_first(text, "%s", LIBRARY->generaltexth->levels[0]);
  825. boost::replace_first(text, "%s", LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  826. boost::replace_first(text, "%d", "2000");
  827. confirm = std::make_shared<CButton>(Point(148, 299), AnimationPath::builtin("IBY6432.DEF"), CButton::tooltip(hoverText, text), [this, SKILL](){makeDeal(SKILL);}, EShortcut::GLOBAL_ACCEPT);
  828. confirm->block(!available);
  829. cancel = std::make_shared<CButton>(Point(252,299), AnimationPath::builtin("ICANCEL.DEF"), LIBRARY->generaltexth->zelp[631], [&](){ close(); }, EShortcut::GLOBAL_CANCEL);
  830. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  831. }
  832. void CUnivConfirmWindow::makeDeal(SecondarySkill skill)
  833. {
  834. owner->makeDeal(skill);
  835. close();
  836. }
  837. CGarrisonWindow::CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits)
  838. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("GARRISON"))
  839. {
  840. OBJECT_CONSTRUCTION;
  841. garr = std::make_shared<CGarrisonInt>(Point(92, 127), 4, Point(0,96), up, down, removableUnits);
  842. {
  843. auto split = std::make_shared<CButton>(Point(88, 314), AnimationPath::builtin("IDV6432.DEF"), CButton::tooltip(LIBRARY->generaltexth->tcommands[3], ""), [this](){ garr->splitClick(); }, EShortcut::HERO_ARMY_SPLIT );
  844. garr->addSplitBtn(split);
  845. }
  846. quit = std::make_shared<CButton>(Point(399, 314), AnimationPath::builtin("IOK6432.DEF"), CButton::tooltip(LIBRARY->generaltexth->tcommands[8], ""), [this](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  847. std::string titleText;
  848. if(down->tempOwner == up->tempOwner)
  849. {
  850. titleText = LIBRARY->generaltexth->allTexts[709];
  851. }
  852. else
  853. {
  854. //assume that this is joining monsters dialog
  855. if(up->Slots().size() > 0)
  856. {
  857. titleText = LIBRARY->generaltexth->allTexts[35];
  858. boost::algorithm::replace_first(titleText, "%s", up->Slots().begin()->second->getType()->getNamePluralTranslated());
  859. }
  860. else
  861. {
  862. logGlobal->error("Invalid armed instance for garrison window.");
  863. }
  864. }
  865. title = std::make_shared<CLabel>(275, 30, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleText);
  866. banner = std::make_shared<CAnimImage>(AnimationPath::builtin("CREST58"), up->getOwner().getNum(), 0, 28, 124);
  867. portrait = std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), down->getIconIndex(), 0, 29, 222);
  868. }
  869. void CGarrisonWindow::updateGarrisons()
  870. {
  871. garr->recreateSlots();
  872. }
  873. bool CGarrisonWindow::holdsGarrison(const CArmedInstance * army)
  874. {
  875. return garr->upperArmy() == army || garr->lowerArmy() == army;
  876. }
  877. CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectInstance * object)
  878. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("APHLFTBK")),
  879. fort(object),
  880. hero(visitor)
  881. {
  882. OBJECT_CONSTRUCTION;
  883. title = std::make_shared<CLabel>(325, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, fort->getObjectName());
  884. heroPic = std::make_shared<CHeroArea>(30, 60, hero);
  885. for(int i=0; i < resCount; i++)
  886. {
  887. totalIcons[i] = std::make_shared<CAnimImage>(AnimationPath::builtin("SMALRES"), i, 0, 104 + 76 * i, 237);
  888. totalLabels[i] = std::make_shared<CLabel>(166 + 76 * i, 253, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  889. }
  890. for(int i = 0; i < slotsCount; i++)
  891. {
  892. upgrade[i] = std::make_shared<CButton>(Point(107 + i * 76, 171), AnimationPath::builtin("APHLF1R"), CButton::tooltip(getTextForSlot(SlotID(i))), [this, i](){ makeDeal(SlotID(i)); }, vstd::next(EShortcut::SELECT_INDEX_1, i));
  893. for(int j : {0,1})
  894. {
  895. slotIcons[i][j] = std::make_shared<CAnimImage>(AnimationPath::builtin("SMALRES"), 0, 0, 104 + 76 * i, 128 + 20 * j);
  896. slotLabels[i][j] = std::make_shared<CLabel>(168 + 76 * i, 144 + 20 * j, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  897. }
  898. }
  899. upgradeAll = std::make_shared<CButton>(Point(30, 231), AnimationPath::builtin("APHLF4R"), CButton::tooltip(LIBRARY->generaltexth->allTexts[432]), [this](){ makeDeal(SlotID(slotsCount));}, EShortcut::RECRUITMENT_UPGRADE_ALL);
  900. quit = std::make_shared<CButton>(Point(294, 275), AnimationPath::builtin("IOKAY.DEF"), CButton::tooltip(), [this](){close();}, EShortcut::GLOBAL_ACCEPT);
  901. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  902. garr = std::make_shared<CGarrisonInt>(Point(108, 60), 18, Point(), hero, nullptr);
  903. statusbar->write(LIBRARY->generaltexth->translate(dynamic_cast<const HillFort *>(fort)->getDescriptionToolTip()));
  904. updateGarrisons();
  905. }
  906. bool CHillFortWindow::holdsGarrison(const CArmedInstance * army)
  907. {
  908. return hero == army;
  909. }
  910. void CHillFortWindow::updateGarrisons()
  911. {
  912. constexpr std::array slotImages = { "APHLF1R.DEF", "APHLF1Y.DEF", "APHLF1G.DEF" };
  913. constexpr std::array allImages = { "APHLF4R.DEF", "APHLF4Y.DEF", "APHLF4G.DEF" };
  914. std::array<TResources, slotsCount> costs;// costs [slot ID] [resource ID] = resource count for upgrade
  915. TResources totalSum; // totalSum[resource ID] = value
  916. auto getImgIdx = [](CHillFortWindow::State st) -> std::size_t
  917. {
  918. switch (st)
  919. {
  920. case State::EMPTY:
  921. return 0;
  922. case State::UNAVAILABLE:
  923. case State::ALREADY_UPGRADED:
  924. return 1;
  925. default:
  926. return static_cast<std::size_t>(st);
  927. }
  928. };
  929. for(int i=0; i<slotsCount; i++)
  930. {
  931. std::fill(costs[i].begin(), costs[i].end(), 0);
  932. State newState = getState(SlotID(i));
  933. if(newState != State::EMPTY)
  934. {
  935. if(const CStackInstance * s = hero->getStackPtr(SlotID(i)))
  936. {
  937. UpgradeInfo info(s->getCreature()->getId());
  938. GAME->interface()->cb->fillUpgradeInfo(hero, SlotID(i), info);
  939. if(info.canUpgrade()) //we have upgrades here - update costs
  940. {
  941. costs[i] = info.getUpgradeCosts() * hero->getStackCount(SlotID(i));
  942. totalSum += costs[i];
  943. }
  944. }
  945. }
  946. currState[i] = newState;
  947. upgrade[i]->setImage(AnimationPath::builtin(slotImages[getImgIdx(currState[i])]));
  948. upgrade[i]->block(currState[i] == State::EMPTY);
  949. upgrade[i]->addHoverText(EButtonState::NORMAL, getTextForSlot(SlotID(i)));
  950. }
  951. //"Upgrade all" slot
  952. State newState = State::MAKE_UPGRADE;
  953. {
  954. TResources myRes = GAME->interface()->cb->getResourceAmount();
  955. bool allUpgraded = true;//All creatures are upgraded?
  956. for(int i=0; i<slotsCount; i++)
  957. allUpgraded &= currState[i] == State::ALREADY_UPGRADED || currState[i] == State::EMPTY || currState[i] == State::UNAVAILABLE;
  958. if (allUpgraded)
  959. newState = State::ALREADY_UPGRADED;
  960. if(!totalSum.canBeAfforded(myRes))
  961. newState = State::UNAFFORDABLE;
  962. }
  963. currState[slotsCount] = newState;
  964. upgradeAll->setImage(AnimationPath::builtin(allImages[static_cast<std::size_t>(newState)]));
  965. garr->recreateSlots();
  966. for(int i = 0; i < slotsCount; i++)
  967. {
  968. //hide all first
  969. for(int j : {0,1})
  970. {
  971. slotIcons[i][j]->visible = false;
  972. slotLabels[i][j]->setText("");
  973. }
  974. //if can upgrade or can not afford, draw cost
  975. if(currState[i] == State::UNAFFORDABLE || currState[i] == State::MAKE_UPGRADE)
  976. {
  977. if(costs[i].nonZero())
  978. {
  979. //reverse iterator is used to display gold as first element
  980. int j = 0;
  981. for(int res = (int)costs[i].size()-1; (res >= 0) && (j < 2); res--)
  982. {
  983. int val = costs[i][res];
  984. if(!val)
  985. continue;
  986. slotIcons[i][j]->visible = true;
  987. slotIcons[i][j]->setFrame(res);
  988. slotLabels[i][j]->setText(std::to_string(val));
  989. j++;
  990. }
  991. }
  992. else//free upgrade - print gold image and "Free" text
  993. {
  994. slotIcons[i][0]->visible = true;
  995. slotIcons[i][0]->setFrame(GameResID(EGameResID::GOLD));
  996. slotLabels[i][0]->setText(LIBRARY->generaltexth->allTexts[344]);
  997. }
  998. }
  999. }
  1000. for(int i = 0; i < resCount; i++)
  1001. {
  1002. if(totalSum[i] == 0)
  1003. {
  1004. totalIcons[i]->visible = false;
  1005. totalLabels[i]->setText("");
  1006. }
  1007. else
  1008. {
  1009. totalIcons[i]->visible = true;
  1010. totalLabels[i]->setText(std::to_string(totalSum[i]));
  1011. }
  1012. }
  1013. }
  1014. void CHillFortWindow::makeDeal(SlotID slot)
  1015. {
  1016. assert(slot.getNum() >= 0);
  1017. int offset = (slot.getNum() == slotsCount) ? 2 : 0;
  1018. switch(currState[slot.getNum()])
  1019. {
  1020. case State::ALREADY_UPGRADED:
  1021. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[313 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1022. break;
  1023. case State::UNAFFORDABLE:
  1024. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[314 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1025. break;
  1026. case State::UNAVAILABLE:
  1027. {
  1028. std::string message = LIBRARY->generaltexth->translate(dynamic_cast<const HillFort *>(fort)->getUnavailableUpgradeMessage());
  1029. GAME->interface()->showInfoDialog(message, std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1030. break;
  1031. }
  1032. case State::MAKE_UPGRADE:
  1033. for(int i = 0; i < slotsCount; i++)
  1034. {
  1035. if(slot.getNum() == i || ( slot.getNum() == slotsCount && currState[i] == State::MAKE_UPGRADE ))//this is activated slot or "upgrade all"
  1036. {
  1037. if(const CStackInstance * s = hero->getStackPtr(SlotID(i)))
  1038. {
  1039. UpgradeInfo info(s->getCreatureID());
  1040. GAME->interface()->cb->fillUpgradeInfo(hero, SlotID(i), info);
  1041. GAME->interface()->cb->upgradeCreature(hero, SlotID(i), info.getUpgrade());
  1042. }
  1043. }
  1044. }
  1045. break;
  1046. }
  1047. }
  1048. std::string CHillFortWindow::getTextForSlot(SlotID slot)
  1049. {
  1050. if(!hero->getCreature(slot))//we don`t have creature here
  1051. return "";
  1052. std::string str = LIBRARY->generaltexth->allTexts[318];
  1053. int amount = hero->getStackCount(slot);
  1054. if(amount == 1)
  1055. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNameSingularTranslated());
  1056. else
  1057. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNamePluralTranslated());
  1058. return str;
  1059. }
  1060. CHillFortWindow::State CHillFortWindow::getState(SlotID slot)
  1061. {
  1062. TResources myRes = GAME->interface()->cb->getResourceAmount();
  1063. if(hero->slotEmpty(slot))
  1064. return State::EMPTY;
  1065. UpgradeInfo info(hero->getStackPtr(slot)->getCreatureID());
  1066. GAME->interface()->cb->fillUpgradeInfo(hero, slot, info);
  1067. if(info.hasUpgrades() && !info.canUpgrade())
  1068. return State::UNAVAILABLE; // Hill Fort may limit level of upgradeable creatures, e.g. mini Hill Fort from HOTA
  1069. if(!info.hasUpgrades())
  1070. return State::ALREADY_UPGRADED;
  1071. if(!(info.getUpgradeCosts() * hero->getStackCount(slot)).canBeAfforded(myRes))
  1072. return State::UNAFFORDABLE;
  1073. return State::MAKE_UPGRADE;
  1074. }
  1075. CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
  1076. CWindowObject(PLAYER_COLORED | BORDERED, ImagePath::builtin("TpRank")),
  1077. owner(_owner)
  1078. {
  1079. OBJECT_CONSTRUCTION;
  1080. SThievesGuildInfo tgi; //info to be displayed
  1081. GAME->interface()->cb->getThievesGuildInfo(tgi, owner);
  1082. exitb = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1"), CButton::tooltip(LIBRARY->generaltexth->allTexts[600]), [&](){ close();}, EShortcut::GLOBAL_RETURN);
  1083. statusbar = CGStatusBar::create(3, 555, ImagePath::builtin("TStatBar.bmp"), 742);
  1084. resdatabar = std::make_shared<CMinorResDataBar>();
  1085. resdatabar->moveBy(pos.topLeft(), true);
  1086. //data for information table:
  1087. // fields[row][column] = list of id's of players for this box
  1088. constexpr std::vector< std::vector< PlayerColor > > SThievesGuildInfo::* fields[] =
  1089. { &SThievesGuildInfo::numOfTowns, &SThievesGuildInfo::numOfHeroes, &SThievesGuildInfo::gold,
  1090. &SThievesGuildInfo::woodOre, &SThievesGuildInfo::mercSulfCrystGems, &SThievesGuildInfo::obelisks,
  1091. &SThievesGuildInfo::artifacts, &SThievesGuildInfo::army, &SThievesGuildInfo::income };
  1092. for(int g=0; g<12; ++g)
  1093. {
  1094. int posY[] = {400, 460, 510};
  1095. int y;
  1096. if(g < 9)
  1097. y = 52 + 32*g;
  1098. else
  1099. y = posY[g-9];
  1100. std::string text = LIBRARY->generaltexth->jktexts[24+g];
  1101. boost::algorithm::trim_if(text,boost::algorithm::is_any_of("\""));
  1102. if(settings["general"]["enableUiEnhancements"].Bool() && g >= 2 && g <= 4) // add icons instead of text (text is OH3 behavior)
  1103. {
  1104. auto addicon = [this, y](GameResID res, int x){ columnHeaderIcons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SMALRES"), res, 0, x, y - 10)); };
  1105. if(g == 2) // gold
  1106. addicon(GameResID::GOLD, 125);
  1107. else if(g == 3) // wood, ore
  1108. {
  1109. addicon(GameResID::WOOD, 110);
  1110. addicon(GameResID::ORE, 140);
  1111. }
  1112. else if(g == 4) // mercury, sulfur, crystal, gems
  1113. {
  1114. addicon(GameResID::MERCURY, 80);
  1115. addicon(GameResID::SULFUR, 110);
  1116. addicon(GameResID::CRYSTAL, 140);
  1117. addicon(GameResID::GEMS, 170);
  1118. }
  1119. }
  1120. else
  1121. rowHeaders.push_back(std::make_shared<CLabel>(135, y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, text, 220));
  1122. }
  1123. for(int g=1; g<tgi.playerColors.size(); ++g)
  1124. columnBackgrounds.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PRSTRIPS"), g-1, 0, 250 + 66*g, 7));
  1125. for(int g=0; g<tgi.playerColors.size(); ++g)
  1126. columnHeaders.push_back(std::make_shared<CLabel>(283 + 66*g, 21, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[16+g]));
  1127. //printing flags
  1128. for(int g = 0; g < std::size(fields); ++g) //by lines
  1129. {
  1130. for(int b=0; b<(tgi .* fields[g]).size(); ++b) //by places (1st, 2nd, ...)
  1131. {
  1132. std::vector<PlayerColor> &players = (tgi .* fields[g])[b]; //get players with this place in this line
  1133. //position of box
  1134. int xpos = 259 + 66 * b;
  1135. int ypos = 41 + 32 * g;
  1136. size_t rowLength[2]; //size of each row
  1137. rowLength[0] = std::min<size_t>(players.size(), 4);
  1138. rowLength[1] = players.size() - rowLength[0];
  1139. for(size_t j=0; j < 2; j++)
  1140. {
  1141. // origin of this row | offset for 2nd row| shift right for short rows
  1142. //if we have 2 rows, start either from mid or beginning (depending on count), otherwise center the flags
  1143. int rowStartX = xpos + (j ? 6 + ((int)rowLength[j] < 3 ? 12 : 0) : 24 - 6 * (int)rowLength[j]);
  1144. int rowStartY = ypos + (j ? 4 : 0);
  1145. for(size_t i=0; i < rowLength[j]; i++)
  1146. cells.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("itgflags"), players[i + j*4].getNum(), 0, rowStartX + (int)i*12, rowStartY));
  1147. }
  1148. }
  1149. }
  1150. static const std::string colorToBox[] = {"PRRED.BMP", "PRBLUE.BMP", "PRTAN.BMP", "PRGREEN.BMP", "PRORANGE.BMP", "PRPURPLE.BMP", "PRTEAL.BMP", "PRROSE.bmp"};
  1151. //printing best hero
  1152. int counter = 0;
  1153. for(auto & iter : tgi.colorToBestHero)
  1154. {
  1155. banners.push_back(std::make_shared<CPicture>(ImagePath::builtin(colorToBox[iter.first.getNum()]), 253 + 66 * counter, 334));
  1156. if(iter.second.portraitSource.isValid())
  1157. {
  1158. bestHeroes.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsSmall"), iter.second.getIconIndex(), 0, 260 + 66 * counter, 360));
  1159. //TODO: r-click info:
  1160. // - r-click on hero
  1161. if(iter.second.details)
  1162. {
  1163. std::vector<std::string> lines;
  1164. boost::split(lines, LIBRARY->generaltexth->allTexts[184], boost::is_any_of("\n"));
  1165. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  1166. {
  1167. primSkillHeaders.push_back(std::make_shared<CLabel>(260 + 66 * counter, 407 + 11 * i, FONT_TINY, ETextAlignment::BOTTOMLEFT, Colors::WHITE, lines[i]));
  1168. primSkillHeadersArea.push_back(std::make_shared<LRClickableArea>(Rect(primSkillHeaders.back()->pos.x - pos.x, primSkillHeaders.back()->pos.y - pos.y - 11, 50, 11), nullptr, [i]{
  1169. CRClickPopup::createAndPush(LIBRARY->generaltexth->arraytxt[2 + i]);
  1170. }));
  1171. primSkillValues.push_back(std::make_shared<CLabel>(310 + 66 * counter, 407 + 11 * i, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE,
  1172. std::to_string(iter.second.details->primskills[i])));
  1173. }
  1174. }
  1175. }
  1176. counter++;
  1177. }
  1178. //printing best creature
  1179. counter = 0;
  1180. for(auto & it : tgi.bestCreature)
  1181. {
  1182. if(it.second != CreatureID::NONE)
  1183. bestCreatures.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), it.second+2, 0, 255 + 66 * counter, 479));
  1184. counter++;
  1185. }
  1186. //printing personality
  1187. counter = 0;
  1188. for(auto & it : tgi.personality)
  1189. {
  1190. std::string text;
  1191. if(it.second == EAiTactic::NONE)
  1192. {
  1193. text = LIBRARY->generaltexth->arraytxt[172];
  1194. }
  1195. else if(it.second != EAiTactic::RANDOM)
  1196. {
  1197. text = LIBRARY->generaltexth->arraytxt[168 + static_cast<int>(it.second)];
  1198. }
  1199. personalities.push_back(std::make_shared<CLabel>(283 + 66*counter, 459, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, text));
  1200. counter++;
  1201. }
  1202. }
  1203. CObjectListWindow::CItem::CItem(CObjectListWindow * _parent, size_t _id, std::string _text)
  1204. : CIntObject(LCLICK | DOUBLECLICK | RCLICK_POPUP),
  1205. parent(_parent),
  1206. index(_id)
  1207. {
  1208. OBJECT_CONSTRUCTION;
  1209. if(parent->images.size() > index)
  1210. icon = std::make_shared<CPicture>(parent->images[index], Point(1, 1));
  1211. border = std::make_shared<CPicture>(ImagePath::builtin("TPGATES"));
  1212. pos = border->pos;
  1213. setRedrawParent(true);
  1214. text = std::make_shared<CLabel>(pos.w/2, pos.h/2, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _text, 256);
  1215. select(index == parent->selected);
  1216. }
  1217. void CObjectListWindow::CItem::select(bool on)
  1218. {
  1219. ui8 mask = UPDATE | SHOWALL;
  1220. if(on)
  1221. border->recActions |= mask;
  1222. else
  1223. border->recActions &= ~mask;
  1224. redraw();//???
  1225. }
  1226. void CObjectListWindow::CItem::clickPressed(const Point & cursorPosition)
  1227. {
  1228. parent->changeSelection(index);
  1229. if(parent->onClicked)
  1230. parent->onClicked(index);
  1231. }
  1232. void CObjectListWindow::CItem::clickDouble(const Point & cursorPosition)
  1233. {
  1234. if (parent->selected != index)
  1235. {
  1236. clickPressed(cursorPosition);
  1237. return;
  1238. }
  1239. parent->elementSelected();
  1240. }
  1241. void CObjectListWindow::CItem::showPopupWindow(const Point & cursorPosition)
  1242. {
  1243. if(parent->onPopup)
  1244. parent->onPopup(index);
  1245. }
  1246. CObjectListWindow::CObjectListWindow(const std::vector<int> & _items, std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, std::function<void(int)> Callback, size_t initialSelection, std::vector<std::shared_ptr<IImage>> images, bool searchBoxEnabled)
  1247. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPGATE")),
  1248. onSelect(Callback),
  1249. selected(initialSelection),
  1250. images(images)
  1251. {
  1252. OBJECT_CONSTRUCTION;
  1253. addUsedEvents(KEYBOARD);
  1254. items.reserve(_items.size());
  1255. for(int id : _items)
  1256. {
  1257. std::string objectName = GAME->interface()->cb->getObjInstance(ObjectInstanceID(id))->getObjectName();
  1258. trimTextIfTooWide(objectName, id);
  1259. items.emplace_back(id, objectName);
  1260. }
  1261. itemsVisible = items;
  1262. init(titleWidget_, _title, _descr, searchBoxEnabled);
  1263. list->scrollTo(std::min(static_cast<int>(initialSelection + 4), static_cast<int>(items.size() - 1))); // 4 is for centering (list have 9 elements)
  1264. }
  1265. CObjectListWindow::CObjectListWindow(const std::vector<std::string> & _items, std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, std::function<void(int)> Callback, size_t initialSelection, std::vector<std::shared_ptr<IImage>> images, bool searchBoxEnabled)
  1266. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPGATE")),
  1267. onSelect(Callback),
  1268. selected(initialSelection),
  1269. images(images)
  1270. {
  1271. OBJECT_CONSTRUCTION;
  1272. addUsedEvents(KEYBOARD);
  1273. items.reserve(_items.size());
  1274. for(size_t i = 0; i < _items.size(); i++)
  1275. {
  1276. std::string objectName = _items[i];
  1277. trimTextIfTooWide(objectName, static_cast<int>(i));
  1278. items.emplace_back(static_cast<int>(i), objectName);
  1279. }
  1280. itemsVisible = items;
  1281. init(titleWidget_, _title, _descr, searchBoxEnabled);
  1282. list->scrollTo(std::min(static_cast<int>(initialSelection + 4), static_cast<int>(items.size() - 1))); // 4 is for centering (list have 9 elements)
  1283. }
  1284. void CObjectListWindow::init(std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, bool searchBoxEnabled)
  1285. {
  1286. titleWidget = titleWidget_;
  1287. title = std::make_shared<CLabel>(152, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, _title);
  1288. descr = std::make_shared<CLabel>(145, 133, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _descr);
  1289. exit = std::make_shared<CButton>( Point(228, 402), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(), std::bind(&CObjectListWindow::exitPressed, this), EShortcut::GLOBAL_CANCEL);
  1290. if(titleWidget)
  1291. {
  1292. addChild(titleWidget.get());
  1293. titleWidget->pos.x = pos.w/2 + pos.x - titleWidget->pos.w/2;
  1294. titleWidget->pos.y = 75 + pos.y - titleWidget->pos.h/2;
  1295. }
  1296. list = std::make_shared<CListBox>(std::bind(&CObjectListWindow::genItem, this, _1),
  1297. Point(14, 151), Point(0, 25), 9, itemsVisible.size(), 0, 1, Rect(262, -32, 256, 256) );
  1298. list->setRedrawParent(true);
  1299. ok = std::make_shared<CButton>(Point(15, 402), AnimationPath::builtin("IOKAY.DEF"), CButton::tooltip(), std::bind(&CObjectListWindow::elementSelected, this), EShortcut::GLOBAL_ACCEPT);
  1300. ok->block(!list->size());
  1301. if(!searchBoxEnabled)
  1302. return;
  1303. Rect r(50, 90, pos.w - 100, 16);
  1304. const ColorRGBA rectangleColor = ColorRGBA(0, 0, 0, 75);
  1305. const ColorRGBA borderColor = ColorRGBA(128, 100, 75);
  1306. const ColorRGBA grayedColor = ColorRGBA(158, 130, 105);
  1307. searchBoxRectangle = std::make_shared<TransparentFilledRectangle>(r.resize(1), rectangleColor, borderColor);
  1308. searchBoxDescription = std::make_shared<CLabel>(r.center().x, r.center().y, FONT_SMALL, ETextAlignment::CENTER, grayedColor, LIBRARY->generaltexth->translate("vcmi.spellBook.search"));
  1309. searchBox = std::make_shared<CTextInput>(r, FONT_SMALL, ETextAlignment::CENTER, true);
  1310. searchBox->setCallback(std::bind(&CObjectListWindow::itemsSearchCallback, this, std::placeholders::_1));
  1311. }
  1312. void CObjectListWindow::trimTextIfTooWide(std::string & text, int id) const
  1313. {
  1314. int maxWidth = pos.w - 60; // 60 px for scrollbar and borders
  1315. std::string idStr = '(' + std::to_string(id) + ')';
  1316. const auto & font = ENGINE->renderHandler().loadFont(FONT_SMALL);
  1317. std::string suffix = " ... " + idStr;
  1318. if(font->getStringWidth(text) >= maxWidth)
  1319. {
  1320. logGlobal->warn("Mapobject name '%s' is too long and probably needs to be fixed! Trimming...",
  1321. text.substr(0, text.size() - idStr.size() + 1));
  1322. // Trim text until it fits
  1323. while(!text.empty())
  1324. {
  1325. std::string trimmedText = text + suffix;
  1326. if(font->getStringWidth(trimmedText) < maxWidth)
  1327. break;
  1328. TextOperations::trimRightUnicode(text);
  1329. }
  1330. text += suffix;
  1331. }
  1332. }
  1333. void CObjectListWindow::itemsSearchCallback(const std::string & text)
  1334. {
  1335. searchBoxDescription->setEnabled(text.empty());
  1336. itemsVisible.clear();
  1337. std::vector<std::pair<int, decltype(items)::value_type>> rankedItems; // Store (score, item)
  1338. for(const auto & item : items)
  1339. {
  1340. if(auto score = TextOperations::textSearchSimilarityScore(text, item.second)) // Keep only relevant items
  1341. rankedItems.emplace_back(score.value(), item);
  1342. }
  1343. // Sort: Lower score is better match
  1344. std::sort(rankedItems.begin(), rankedItems.end(), [](const auto & a, const auto & b)
  1345. {
  1346. return a.first < b.first;
  1347. });
  1348. for(const auto & rankedItem : rankedItems)
  1349. itemsVisible.push_back(rankedItem.second);
  1350. selected = 0;
  1351. list->resize(itemsVisible.size());
  1352. list->scrollTo(0);
  1353. ok->block(!itemsVisible.size());
  1354. redraw();
  1355. }
  1356. std::shared_ptr<CIntObject> CObjectListWindow::genItem(size_t index)
  1357. {
  1358. if(index < itemsVisible.size())
  1359. return std::make_shared<CItem>(this, index, itemsVisible[index].second);
  1360. return std::shared_ptr<CIntObject>();
  1361. }
  1362. void CObjectListWindow::elementSelected()
  1363. {
  1364. std::function<void(int)> toCall = onSelect;//save
  1365. int where = itemsVisible[selected].first; //required variables
  1366. close();//then destroy window
  1367. toCall(where);//and send selected object
  1368. }
  1369. void CObjectListWindow::exitPressed()
  1370. {
  1371. std::function<void()> toCall = onExit;//save
  1372. close();//then destroy window
  1373. if(toCall)
  1374. toCall();
  1375. }
  1376. void CObjectListWindow::changeSelection(size_t which)
  1377. {
  1378. ok->block(false);
  1379. if(selected == which)
  1380. return;
  1381. for(std::shared_ptr<CIntObject> element : list->getItems())
  1382. {
  1383. CItem * item = dynamic_cast<CItem*>(element.get());
  1384. if(item)
  1385. {
  1386. if(item->index == selected)
  1387. item->select(false);
  1388. if(item->index == which)
  1389. item->select(true);
  1390. }
  1391. }
  1392. selected = which;
  1393. }
  1394. void CObjectListWindow::keyPressed(EShortcut key)
  1395. {
  1396. int sel = static_cast<int>(selected);
  1397. switch(key)
  1398. {
  1399. break; case EShortcut::MOVE_UP:
  1400. sel -=1;
  1401. break; case EShortcut::MOVE_DOWN:
  1402. sel +=1;
  1403. break; case EShortcut::MOVE_PAGE_UP:
  1404. sel -=9;
  1405. break; case EShortcut::MOVE_PAGE_DOWN:
  1406. sel +=9;
  1407. break; case EShortcut::MOVE_FIRST:
  1408. sel = 0;
  1409. break; case EShortcut::MOVE_LAST:
  1410. sel = static_cast<int>(itemsVisible.size());
  1411. break; default:
  1412. return;
  1413. }
  1414. vstd::abetween<int>(sel, 0, itemsVisible.size()-1);
  1415. list->scrollTo(sel);
  1416. changeSelection(sel);
  1417. }
  1418. VideoWindow::VideoWindow(const VideoPath & video, const ImagePath & rim, bool showBackground, float scaleFactor, const std::function<void(bool skipped)> & closeCb)
  1419. : CWindowObject(BORDERED | SHADOW_DISABLED | NEEDS_ANIMATED_BACKGROUND)
  1420. , showBackground(showBackground)
  1421. , closeCb(closeCb)
  1422. {
  1423. OBJECT_CONSTRUCTION;
  1424. addUsedEvents(LCLICK | KEYBOARD);
  1425. if(!rim.empty())
  1426. {
  1427. setBackground(rim);
  1428. videoPlayer = std::make_shared<VideoWidgetOnce>(Point(80, 186), video, true, this);
  1429. pos = center(Rect(0, 0, 800, 600));
  1430. }
  1431. else
  1432. {
  1433. blackBackground = std::make_shared<GraphicalPrimitiveCanvas>(Rect(0, 0, ENGINE->screenDimensions().x, ENGINE->screenDimensions().y));
  1434. videoPlayer = std::make_shared<VideoWidgetOnce>(Point(0, 0), video, true, scaleFactor, this);
  1435. pos = center(Rect(0, 0, videoPlayer->pos.w, videoPlayer->pos.h));
  1436. blackBackground->addBox(Point(0, 0), Point(videoPlayer->pos.w, videoPlayer->pos.h), Colors::BLACK);
  1437. }
  1438. }
  1439. void VideoWindow::showAll(Canvas & to)
  1440. {
  1441. if(showBackground)
  1442. to.fillTexture(ENGINE->renderHandler().loadImage(ImagePath::builtin("DiBoxBck"), EImageBlitMode::OPAQUE));
  1443. CWindowObject::showAll(to);
  1444. }
  1445. void VideoWindow::onVideoPlaybackFinished()
  1446. {
  1447. exit(false);
  1448. }
  1449. void VideoWindow::exit(bool skipped)
  1450. {
  1451. close();
  1452. if(closeCb)
  1453. closeCb(skipped);
  1454. }
  1455. void VideoWindow::clickPressed(const Point & cursorPosition)
  1456. {
  1457. exit(true);
  1458. }
  1459. void VideoWindow::keyPressed(EShortcut key)
  1460. {
  1461. if(key == EShortcut::GLOBAL_RETURN)
  1462. exit(true);
  1463. }
  1464. void VideoWindow::notFocusedClick()
  1465. {
  1466. exit(true);
  1467. }