GUIClasses.cpp 57 KB

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