GUIClasses.cpp 64 KB

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