GUIClasses.cpp 65 KB

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