GUIClasses.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  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 "../CMusicHandler.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../CVideoHandler.h"
  20. #include "../CServerHandler.h"
  21. #include "../adventureMap/mapHandler.h"
  22. #include "../adventureMap/CResDataBar.h"
  23. #include "../battle/BattleInterfaceClasses.h"
  24. #include "../battle/BattleInterface.h"
  25. #include "../gui/CGuiHandler.h"
  26. #include "../gui/CursorHandler.h"
  27. #include "../gui/TextAlignment.h"
  28. #include "../widgets/CComponent.h"
  29. #include "../widgets/MiscWidgets.h"
  30. #include "../widgets/CreatureCostBox.h"
  31. #include "../widgets/Buttons.h"
  32. #include "../widgets/TextControls.h"
  33. #include "../widgets/ObjectLists.h"
  34. #include "../lobby/CSavingScreen.h"
  35. #include "../renderSDL/SDL_Extensions.h"
  36. #include "../render/CAnimation.h"
  37. #include "../../CCallback.h"
  38. #include "../lib/mapObjects/CGHeroInstance.h"
  39. #include "../lib/CArtHandler.h"
  40. #include "../lib/CBuildingHandler.h"
  41. #include "../lib/CConfigHandler.h"
  42. #include "../lib/CCreatureHandler.h"
  43. #include "../lib/CGameState.h"
  44. #include "../lib/CGeneralTextHandler.h"
  45. #include "../lib/CHeroHandler.h"
  46. #include "../lib/CModHandler.h"
  47. #include "../lib/CondSh.h"
  48. #include "../lib/CSkillHandler.h"
  49. #include "../lib/spells/CSpellHandler.h"
  50. #include "../lib/CStopWatch.h"
  51. #include "../lib/CTownHandler.h"
  52. #include "../lib/GameConstants.h"
  53. #include "../lib/HeroBonus.h"
  54. #include "../lib/mapping/CMap.h"
  55. #include "../lib/NetPacksBase.h"
  56. #include "../lib/StartInfo.h"
  57. using namespace CSDL_Ext;
  58. CRecruitmentWindow::CCreatureCard::CCreatureCard(CRecruitmentWindow * window, const CCreature * crea, int totalAmount)
  59. : CIntObject(LCLICK | RCLICK),
  60. parent(window),
  61. selected(false),
  62. creature(crea),
  63. amount(totalAmount)
  64. {
  65. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  66. animation = std::make_shared<CCreaturePic>(1, 1, creature, true, true);
  67. // 1 + 1 px for borders
  68. pos.w = animation->pos.w + 2;
  69. pos.h = animation->pos.h + 2;
  70. }
  71. void CRecruitmentWindow::CCreatureCard::select(bool on)
  72. {
  73. selected = on;
  74. redraw();
  75. }
  76. void CRecruitmentWindow::CCreatureCard::clickLeft(tribool down, bool previousState)
  77. {
  78. if(down)
  79. parent->select(this->shared_from_this());
  80. }
  81. void CRecruitmentWindow::CCreatureCard::clickRight(tribool down, bool previousState)
  82. {
  83. if(down)
  84. GH.pushIntT<CStackWindow>(creature, true);
  85. }
  86. void CRecruitmentWindow::CCreatureCard::showAll(SDL_Surface * to)
  87. {
  88. CIntObject::showAll(to);
  89. if(selected)
  90. drawBorder(to, pos, Colors::RED);
  91. else
  92. drawBorder(to, pos, Colors::YELLOW);
  93. }
  94. void CRecruitmentWindow::select(std::shared_ptr<CCreatureCard> card)
  95. {
  96. if(card == selected)
  97. return;
  98. if(selected)
  99. selected->select(false);
  100. selected = card;
  101. if(selected)
  102. selected->select(true);
  103. if(card)
  104. {
  105. si32 maxAmount = card->creature->maxAmount(LOCPLINT->cb->getResourceAmount());
  106. vstd::amin(maxAmount, card->amount);
  107. slider->setAmount(maxAmount);
  108. if(slider->getValue() != maxAmount)
  109. slider->moveTo(maxAmount);
  110. else // if slider already at 0 - emulate call to sliderMoved()
  111. sliderMoved(maxAmount);
  112. costPerTroopValue->createItems(card->creature->cost);
  113. totalCostValue->createItems(card->creature->cost);
  114. costPerTroopValue->set(card->creature->cost);
  115. totalCostValue->set(card->creature->cost * maxAmount);
  116. //Recruit %s
  117. title->setText(boost::str(boost::format(CGI->generaltexth->tcommands[21]) % card->creature->getNamePluralTranslated()));
  118. maxButton->block(maxAmount == 0);
  119. slider->block(maxAmount == 0);
  120. }
  121. }
  122. void CRecruitmentWindow::buy()
  123. {
  124. CreatureID crid = selected->creature->idNumber;
  125. SlotID dstslot = dst-> getSlotFor(crid);
  126. if(!dstslot.validSlot() && (selected->creature->warMachine == ArtifactID::NONE)) //no available slot
  127. {
  128. std::string txt;
  129. if(dst->ID == Obj::HERO)
  130. {
  131. txt = CGI->generaltexth->allTexts[425]; //The %s would join your hero, but there aren't enough provisions to support them.
  132. boost::algorithm::replace_first(txt, "%s", slider->getValue() > 1 ? CGI->creh->objects[crid]->getNamePluralTranslated() : CGI->creh->objects[crid]->getNameSingularTranslated());
  133. }
  134. else
  135. {
  136. txt = CGI->generaltexth->allTexts[17]; //There is no room in the garrison for this army.
  137. }
  138. LOCPLINT->showInfoDialog(txt);
  139. return;
  140. }
  141. onRecruit(crid, slider->getValue());
  142. if(level >= 0)
  143. close();
  144. }
  145. void CRecruitmentWindow::showAll(SDL_Surface * to)
  146. {
  147. CWindowObject::showAll(to);
  148. // recruit\total values
  149. drawBorder(to, pos.x + 172, pos.y + 222, 67, 42, Colors::YELLOW);
  150. drawBorder(to, pos.x + 246, pos.y + 222, 67, 42, Colors::YELLOW);
  151. //cost boxes
  152. drawBorder(to, pos.x + 64, pos.y + 222, 99, 76, Colors::YELLOW);
  153. drawBorder(to, pos.x + 322, pos.y + 222, 99, 76, Colors::YELLOW);
  154. //buttons borders
  155. drawBorder(to, pos.x + 133, pos.y + 312, 66, 34, Colors::METALLIC_GOLD);
  156. drawBorder(to, pos.x + 211, pos.y + 312, 66, 34, Colors::METALLIC_GOLD);
  157. drawBorder(to, pos.x + 289, pos.y + 312, 66, 34, Colors::METALLIC_GOLD);
  158. }
  159. CRecruitmentWindow::CRecruitmentWindow(const CGDwelling * Dwelling, int Level, const CArmedInstance * Dst, const std::function<void(CreatureID,int)> & Recruit, int y_offset):
  160. CStatusbarWindow(PLAYER_COLORED, "TPRCRT"),
  161. onRecruit(Recruit),
  162. level(Level),
  163. dst(Dst),
  164. selected(nullptr),
  165. dwelling(Dwelling)
  166. {
  167. moveBy(Point(0, y_offset));
  168. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  169. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  170. slider = std::make_shared<CSlider>(Point(176,279),135,std::bind(&CRecruitmentWindow::sliderMoved,this, _1),0,0,0,true);
  171. maxButton = std::make_shared<CButton>(Point(134, 313), "IRCBTNS.DEF", CGI->generaltexth->zelp[553], std::bind(&CSlider::moveToMax, slider), SDLK_m);
  172. buyButton = std::make_shared<CButton>(Point(212, 313), "IBY6432.DEF", CGI->generaltexth->zelp[554], std::bind(&CRecruitmentWindow::buy, this), SDLK_RETURN);
  173. cancelButton = std::make_shared<CButton>(Point(290, 313), "ICN6432.DEF", CGI->generaltexth->zelp[555], std::bind(&CRecruitmentWindow::close, this), SDLK_ESCAPE);
  174. title = std::make_shared<CLabel>(243, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW);
  175. availableValue = std::make_shared<CLabel>(205, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  176. toRecruitValue = std::make_shared<CLabel>(279, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  177. costPerTroopValue = std::make_shared<CreatureCostBox>(Rect(65, 222, 97, 74), CGI->generaltexth->allTexts[346]);
  178. totalCostValue = std::make_shared<CreatureCostBox>(Rect(323, 222, 97, 74), CGI->generaltexth->allTexts[466]);
  179. availableTitle = std::make_shared<CLabel>(205, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[465]);
  180. toRecruitTitle = std::make_shared<CLabel>(279, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[16]);
  181. availableCreaturesChanged();
  182. }
  183. void CRecruitmentWindow::availableCreaturesChanged()
  184. {
  185. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  186. size_t selectedIndex = 0;
  187. if(!cards.empty() && selected) // find position of selected item
  188. selectedIndex = std::find(cards.begin(), cards.end(), selected) - cards.begin();
  189. select(nullptr);
  190. cards.clear();
  191. for(int i=0; i<dwelling->creatures.size(); i++)
  192. {
  193. //find appropriate level
  194. if(level >= 0 && i != level)
  195. continue;
  196. int amount = dwelling->creatures[i].first;
  197. //create new cards
  198. for(auto & creature : boost::adaptors::reverse(dwelling->creatures[i].second))
  199. cards.push_back(std::make_shared<CCreatureCard>(this, CGI->creh->objects[creature], amount));
  200. }
  201. const int creatureWidth = 102;
  202. //normal distance between cards - 18px
  203. int requiredSpace = 18;
  204. //maximum distance we can use without reaching window borders
  205. int availableSpace = pos.w - 50 - creatureWidth * (int)cards.size();
  206. if (cards.size() > 1) // avoid division by zero
  207. availableSpace /= (int)cards.size() - 1;
  208. else
  209. availableSpace = 0;
  210. assert(availableSpace >= 0);
  211. const int spaceBetween = std::min(requiredSpace, availableSpace);
  212. const int totalCreatureWidth = spaceBetween + creatureWidth;
  213. //now we know total amount of cards and can move them to correct position
  214. int curx = pos.w / 2 - (creatureWidth*(int)cards.size()/2) - (spaceBetween*((int)cards.size()-1)/2);
  215. for(auto & card : cards)
  216. {
  217. card->moveBy(Point(curx, 64));
  218. curx += totalCreatureWidth;
  219. }
  220. //restore selection
  221. select(cards[selectedIndex]);
  222. if(slider->getValue() == slider->getAmount())
  223. slider->moveToMax();
  224. else // if slider already at 0 - emulate call to sliderMoved()
  225. sliderMoved(slider->getAmount());
  226. }
  227. void CRecruitmentWindow::sliderMoved(int to)
  228. {
  229. if(!selected)
  230. return;
  231. buyButton->block(!to);
  232. availableValue->setText(boost::lexical_cast<std::string>(selected->amount - to));
  233. toRecruitValue->setText(boost::lexical_cast<std::string>(to));
  234. totalCostValue->set(selected->creature->cost * to);
  235. }
  236. CSplitWindow::CSplitWindow(const CCreature * creature, std::function<void(int, int)> callback_, int leftMin_, int rightMin_, int leftAmount_, int rightAmount_)
  237. : CWindowObject(PLAYER_COLORED, "GPUCRDIV"),
  238. callback(callback_),
  239. leftAmount(leftAmount_),
  240. rightAmount(rightAmount_),
  241. leftMin(leftMin_),
  242. rightMin(rightMin_)
  243. {
  244. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  245. int total = leftAmount + rightAmount;
  246. int leftMax = total - rightMin;
  247. int rightMax = total - leftMin;
  248. ok = std::make_shared<CButton>(Point(20, 263), "IOK6432", CButton::tooltip(), std::bind(&CSplitWindow::apply, this), SDLK_RETURN);
  249. cancel = std::make_shared<CButton>(Point(214, 263), "ICN6432", CButton::tooltip(), std::bind(&CSplitWindow::close, this), SDLK_ESCAPE);
  250. int sliderPosition = total - leftMin - rightMin;
  251. leftInput = std::make_shared<CTextInput>(Rect(20, 218, 100, 36), FONT_BIG, std::bind(&CSplitWindow::setAmountText, this, _1, true));
  252. rightInput = std::make_shared<CTextInput>(Rect(176, 218, 100, 36), FONT_BIG, std::bind(&CSplitWindow::setAmountText, this, _1, false));
  253. //add filters to allow only number input
  254. leftInput->filters += std::bind(&CTextInput::numberFilter, _1, _2, leftMin, leftMax);
  255. rightInput->filters += std::bind(&CTextInput::numberFilter, _1, _2, rightMin, rightMax);
  256. leftInput->setText(boost::lexical_cast<std::string>(leftAmount), false);
  257. rightInput->setText(boost::lexical_cast<std::string>(rightAmount), false);
  258. animLeft = std::make_shared<CCreaturePic>(20, 54, creature, true, false);
  259. animRight = std::make_shared<CCreaturePic>(177, 54,creature, true, false);
  260. slider = std::make_shared<CSlider>(Point(21, 194), 257, std::bind(&CSplitWindow::sliderMoved, this, _1), 0, sliderPosition, rightAmount - rightMin, true);
  261. std::string titleStr = CGI->generaltexth->allTexts[256];
  262. boost::algorithm::replace_first(titleStr,"%s", creature->getNamePluralTranslated());
  263. title = std::make_shared<CLabel>(150, 34, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  264. }
  265. void CSplitWindow::setAmountText(std::string text, bool left)
  266. {
  267. int amount = 0;
  268. if(text.length())
  269. {
  270. try
  271. {
  272. amount = boost::lexical_cast<int>(text);
  273. }
  274. catch(boost::bad_lexical_cast &)
  275. {
  276. amount = left ? leftAmount : rightAmount;
  277. }
  278. int total = leftAmount + rightAmount;
  279. if(amount > total)
  280. amount = total;
  281. }
  282. setAmount(amount, left);
  283. slider->moveTo(rightAmount - rightMin);
  284. }
  285. void CSplitWindow::setAmount(int value, bool left)
  286. {
  287. int total = leftAmount + rightAmount;
  288. leftAmount = left ? value : total - value;
  289. rightAmount = left ? total - value : value;
  290. leftInput->setText(boost::lexical_cast<std::string>(leftAmount));
  291. rightInput->setText(boost::lexical_cast<std::string>(rightAmount));
  292. }
  293. void CSplitWindow::apply()
  294. {
  295. callback(leftAmount, rightAmount);
  296. close();
  297. }
  298. void CSplitWindow::sliderMoved(int to)
  299. {
  300. setAmount(rightMin + to, false);
  301. }
  302. CLevelWindow::CLevelWindow(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, std::function<void(ui32)> callback)
  303. : CWindowObject(PLAYER_COLORED, "LVLUPBKG"),
  304. cb(callback)
  305. {
  306. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  307. LOCPLINT->showingDialog->setn(true);
  308. if(!skills.empty())
  309. {
  310. std::vector<std::shared_ptr<CSelectableComponent>> comps;
  311. for(auto & skill : skills)
  312. {
  313. auto comp = std::make_shared<CSelectableComponent>(CComponent::secskill, skill, hero->getSecSkillLevel(SecondarySkill(skill))+1, CComponent::medium);
  314. comps.push_back(comp);
  315. }
  316. box = std::make_shared<CComponentBox>(comps, Rect(75, 300, pos.w - 150, 100));
  317. }
  318. portrait = std::make_shared<CAnimImage>("PortraitsLarge", hero->portrait, 0, 170, 66);
  319. ok = std::make_shared<CButton>(Point(297, 413), "IOKAY", CButton::tooltip(), std::bind(&CLevelWindow::close, this), SDLK_RETURN);
  320. //%s has gained a level.
  321. mainTitle = std::make_shared<CLabel>(192, 33, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[444]) % hero->getNameTranslated()));
  322. //%s is now a level %d %s.
  323. levelTitle = std::make_shared<CLabel>(192, 162, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE,
  324. boost::str(boost::format(CGI->generaltexth->allTexts[445]) % hero->getNameTranslated() % hero->level % hero->type->heroClass->getNameTranslated()));
  325. skillIcon = std::make_shared<CAnimImage>("PSKIL42", pskill, 0, 174, 190);
  326. skillValue = std::make_shared<CLabel>(192, 253, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->primarySkillNames[pskill] + " +1");
  327. }
  328. CLevelWindow::~CLevelWindow()
  329. {
  330. //FIXME: call callback if there was nothing to select?
  331. if (box && box->selectedIndex() != -1)
  332. cb(box->selectedIndex());
  333. LOCPLINT->showingDialog->setn(false);
  334. }
  335. static void setIntSetting(std::string group, std::string field, int value)
  336. {
  337. Settings entry = settings.write[group][field];
  338. entry->Float() = value;
  339. }
  340. static void setBoolSetting(std::string group, std::string field, bool value)
  341. {
  342. Settings fullscreen = settings.write[group][field];
  343. fullscreen->Bool() = value;
  344. }
  345. static std::string resolutionToString(int w, int h)
  346. {
  347. return std::to_string(w) + 'x' + std::to_string(h);
  348. }
  349. CSystemOptionsWindow::CSystemOptionsWindow()
  350. : CWindowObject(PLAYER_COLORED, "SysOpBck"),
  351. onFullscreenChanged(settings.listen["video"]["fullscreen"])
  352. {
  353. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  354. title = std::make_shared<CLabel>(242, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[568]);
  355. //left window section
  356. leftGroup = std::make_shared<CLabelGroup>(FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);
  357. leftGroup->add(122, 64, CGI->generaltexth->allTexts[569]);
  358. leftGroup->add(122, 130, CGI->generaltexth->allTexts[570]);
  359. leftGroup->add(122, 196, CGI->generaltexth->allTexts[571]);
  360. leftGroup->add(122, 262, CGI->generaltexth->translate("vcmi.systemOptions.resolutionButton.hover"));
  361. leftGroup->add(122, 347, CGI->generaltexth->allTexts[394]);
  362. leftGroup->add(122, 412, CGI->generaltexth->allTexts[395]);
  363. //right section
  364. rightGroup = std::make_shared<CLabelGroup>(FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE);
  365. rightGroup->add(282, 57, CGI->generaltexth->allTexts[572]);
  366. rightGroup->add(282, 89, CGI->generaltexth->allTexts[573]);
  367. rightGroup->add(282, 121, CGI->generaltexth->allTexts[574]);
  368. rightGroup->add(282, 153, CGI->generaltexth->allTexts[577]);
  369. rightGroup->add(282, 217, CGI->generaltexth->translate("vcmi.systemOptions.fullscreenButton.hover"));
  370. //setting up buttons
  371. load = std::make_shared<CButton>(Point(246, 298), "SOLOAD.DEF", CGI->generaltexth->zelp[321], [&](){ bloadf(); }, SDLK_l);
  372. load->setImageOrder(1, 0, 2, 3);
  373. save = std::make_shared<CButton>(Point(357, 298), "SOSAVE.DEF", CGI->generaltexth->zelp[322], [&](){ bsavef(); }, SDLK_s);
  374. save->setImageOrder(1, 0, 2, 3);
  375. restart = std::make_shared<CButton>(Point(246, 357), "SORSTRT", CGI->generaltexth->zelp[323], [&](){ brestartf(); }, SDLK_r);
  376. restart->setImageOrder(1, 0, 2, 3);
  377. if(CSH->isGuest())
  378. {
  379. load->block(true);
  380. save->block(true);
  381. restart->block(true);
  382. }
  383. mainMenu = std::make_shared<CButton>(Point(357, 357), "SOMAIN.DEF", CGI->generaltexth->zelp[320], [&](){ bmainmenuf(); }, SDLK_m);
  384. mainMenu->setImageOrder(1, 0, 2, 3);
  385. quitGame = std::make_shared<CButton>(Point(246, 415), "soquit.def", CGI->generaltexth->zelp[324], [&](){ bquitf(); }, SDLK_q);
  386. quitGame->setImageOrder(1, 0, 2, 3);
  387. backToMap = std::make_shared<CButton>( Point(357, 415), "soretrn.def", CGI->generaltexth->zelp[325], [&](){ breturnf(); }, SDLK_RETURN);
  388. backToMap->setImageOrder(1, 0, 2, 3);
  389. backToMap->assignedKeys.insert(SDLK_ESCAPE);
  390. heroMoveSpeed = std::make_shared<CToggleGroup>(0);
  391. enemyMoveSpeed = std::make_shared<CToggleGroup>(0);
  392. mapScrollSpeed = std::make_shared<CToggleGroup>(0);
  393. heroMoveSpeed->addToggle(1, std::make_shared<CToggleButton>(Point( 28, 77), "sysopb1.def", CGI->generaltexth->zelp[349]));
  394. heroMoveSpeed->addToggle(2, std::make_shared<CToggleButton>(Point( 76, 77), "sysopb2.def", CGI->generaltexth->zelp[350]));
  395. heroMoveSpeed->addToggle(4, std::make_shared<CToggleButton>(Point(124, 77), "sysopb3.def", CGI->generaltexth->zelp[351]));
  396. heroMoveSpeed->addToggle(8, std::make_shared<CToggleButton>(Point(172, 77), "sysopb4.def", CGI->generaltexth->zelp[352]));
  397. heroMoveSpeed->setSelected((int)settings["adventure"]["heroSpeed"].Float());
  398. heroMoveSpeed->addCallback(std::bind(&setIntSetting, "adventure", "heroSpeed", _1));
  399. enemyMoveSpeed->addToggle(2, std::make_shared<CToggleButton>(Point( 28, 144), "sysopb5.def", CGI->generaltexth->zelp[353]));
  400. enemyMoveSpeed->addToggle(4, std::make_shared<CToggleButton>(Point( 76, 144), "sysopb6.def", CGI->generaltexth->zelp[354]));
  401. enemyMoveSpeed->addToggle(8, std::make_shared<CToggleButton>(Point(124, 144), "sysopb7.def", CGI->generaltexth->zelp[355]));
  402. enemyMoveSpeed->addToggle(0, std::make_shared<CToggleButton>(Point(172, 144), "sysopb8.def", CGI->generaltexth->zelp[356]));
  403. enemyMoveSpeed->setSelected((int)settings["adventure"]["enemySpeed"].Float());
  404. enemyMoveSpeed->addCallback(std::bind(&setIntSetting, "adventure", "enemySpeed", _1));
  405. mapScrollSpeed->addToggle(1, std::make_shared<CToggleButton>(Point( 28, 210), "sysopb9.def", CGI->generaltexth->zelp[357]));
  406. mapScrollSpeed->addToggle(2, std::make_shared<CToggleButton>(Point( 92, 210), "sysob10.def", CGI->generaltexth->zelp[358]));
  407. mapScrollSpeed->addToggle(4, std::make_shared<CToggleButton>(Point(156, 210), "sysob11.def", CGI->generaltexth->zelp[359]));
  408. mapScrollSpeed->setSelected((int)settings["adventure"]["scrollSpeed"].Float());
  409. mapScrollSpeed->addCallback(std::bind(&setIntSetting, "adventure", "scrollSpeed", _1));
  410. musicVolume = std::make_shared<CVolumeSlider>(Point(29, 359), "syslb.def", CCS->musich->getVolume(), CVolumeSlider::MUSIC);
  411. musicVolume->addCallback(std::bind(&setIntSetting, "general", "music", _1));
  412. effectsVolume = std::make_shared<CVolumeSlider>(Point(29, 425), "syslb.def", CCS->soundh->getVolume(), CVolumeSlider::SOUND);
  413. effectsVolume->addCallback(std::bind(&setIntSetting, "general", "sound", _1));
  414. showReminder = std::make_shared<CToggleButton>(Point(246, 87), "sysopchk.def", CGI->generaltexth->zelp[361], [&](bool value)
  415. {
  416. setBoolSetting("adventure", "heroReminder", value);
  417. });
  418. showReminder->setSelected(settings["adventure"]["heroReminder"].Bool());
  419. quickCombat = std::make_shared<CToggleButton>(Point(246, 87+32), "sysopchk.def", CGI->generaltexth->zelp[362], [&](bool value)
  420. {
  421. setBoolSetting("adventure", "quickCombat", value);
  422. });
  423. quickCombat->setSelected(settings["adventure"]["quickCombat"].Bool());
  424. spellbookAnim = std::make_shared<CToggleButton>(Point(246, 87+64), "sysopchk.def", CGI->generaltexth->zelp[364], [&](bool value)
  425. {
  426. setBoolSetting("video", "spellbookAnimation", value);
  427. });
  428. spellbookAnim->setSelected(settings["video"]["spellbookAnimation"].Bool());
  429. fullscreen = std::make_shared<CToggleButton>(Point(246, 215), "sysopchk.def", CButton::tooltipLocalized("vcmi.systemOptions.fullscreenButton"), [&](bool value)
  430. {
  431. setBoolSetting("video", "fullscreen", value);
  432. });
  433. fullscreen->setSelected(settings["video"]["fullscreen"].Bool());
  434. onFullscreenChanged([&](const JsonNode &newState){ fullscreen->setSelected(newState.Bool());});
  435. gameResButton = std::make_shared<CButton>(Point(28, 275),"buttons/resolution", CButton::tooltipLocalized("vcmi.systemOptions.resolutionButton"), std::bind(&CSystemOptionsWindow::selectGameRes, this), SDLK_g);
  436. const auto & screenRes = settings["video"]["screenRes"];
  437. gameResLabel = std::make_shared<CLabel>(170, 292, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, resolutionToString(screenRes["width"].Integer(), screenRes["height"].Integer()));
  438. }
  439. void CSystemOptionsWindow::selectGameRes()
  440. {
  441. std::vector<std::string> items;
  442. #ifndef VCMI_IOS
  443. Rect displayBounds = CSDL_Ext::getDisplayBounds();
  444. #endif
  445. size_t currentResolutionIndex = 0;
  446. size_t i = 0;
  447. for(const auto & it : conf.guiOptions)
  448. {
  449. const auto & resolution = it.first;
  450. #ifndef VCMI_IOS
  451. if(displayBounds.w < resolution.first || displayBounds.h < resolution.second)
  452. continue;
  453. #endif
  454. auto resolutionStr = resolutionToString(resolution.first, resolution.second);
  455. if(gameResLabel->getText() == resolutionStr)
  456. currentResolutionIndex = i;
  457. items.push_back(std::move(resolutionStr));
  458. ++i;
  459. }
  460. GH.pushIntT<CObjectListWindow>(items, nullptr,
  461. CGI->generaltexth->translate("vcmi.systemOptions.resolutionMenu.hover"),
  462. CGI->generaltexth->translate("vcmi.systemOptions.resolutionMenu.help"),
  463. std::bind(&CSystemOptionsWindow::setGameRes, this, _1),
  464. currentResolutionIndex);
  465. }
  466. void CSystemOptionsWindow::setGameRes(int index)
  467. {
  468. auto iter = conf.guiOptions.begin();
  469. std::advance(iter, index);
  470. //do not set resolution to illegal one (0x0)
  471. assert(iter!=conf.guiOptions.end() && iter->first.first > 0 && iter->first.second > 0);
  472. Settings gameRes = settings.write["video"]["screenRes"];
  473. gameRes["width"].Float() = iter->first.first;
  474. gameRes["height"].Float() = iter->first.second;
  475. std::string resText;
  476. resText += boost::lexical_cast<std::string>(iter->first.first);
  477. resText += "x";
  478. resText += boost::lexical_cast<std::string>(iter->first.second);
  479. gameResLabel->setText(resText);
  480. }
  481. void CSystemOptionsWindow::bquitf()
  482. {
  483. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[578], [this](){ closeAndPushEvent(EUserEvent::FORCE_QUIT); }, 0);
  484. }
  485. void CSystemOptionsWindow::breturnf()
  486. {
  487. close();
  488. }
  489. void CSystemOptionsWindow::bmainmenuf()
  490. {
  491. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[578], [this](){ closeAndPushEvent(EUserEvent::RETURN_TO_MAIN_MENU); }, 0);
  492. }
  493. void CSystemOptionsWindow::bloadf()
  494. {
  495. close();
  496. LOCPLINT->proposeLoadingGame();
  497. }
  498. void CSystemOptionsWindow::bsavef()
  499. {
  500. close();
  501. GH.pushIntT<CSavingScreen>();
  502. }
  503. void CSystemOptionsWindow::brestartf()
  504. {
  505. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[67], [this](){ closeAndPushEvent(EUserEvent::RESTART_GAME); }, 0);
  506. }
  507. void CSystemOptionsWindow::closeAndPushEvent(EUserEvent code)
  508. {
  509. close();
  510. GH.pushUserEvent(code);
  511. }
  512. CTavernWindow::CTavernWindow(const CGObjectInstance * TavernObj)
  513. : CStatusbarWindow(PLAYER_COLORED, "TPTAVERN"),
  514. tavernObj(TavernObj)
  515. {
  516. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  517. std::vector<const CGHeroInstance*> h = LOCPLINT->cb->getAvailableHeroes(TavernObj);
  518. if(h.size() < 2)
  519. h.resize(2, nullptr);
  520. selected = 0;
  521. if(!h[0])
  522. selected = 1;
  523. if(!h[0] && !h[1])
  524. selected = -1;
  525. oldSelected = -1;
  526. h1 = std::make_shared<HeroPortrait>(selected, 0, 72, 299, h[0]);
  527. h2 = std::make_shared<HeroPortrait>(selected, 1, 162, 299, h[1]);
  528. title = std::make_shared<CLabel>(200, 35, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[37]);
  529. cost = std::make_shared<CLabel>(320, 328, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(GameConstants::HERO_GOLD_COST));
  530. auto rumorText = boost::str(boost::format(CGI->generaltexth->allTexts[216]) % LOCPLINT->cb->getTavernRumor(tavernObj));
  531. rumor = std::make_shared<CTextBox>(rumorText, Rect(32, 190, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  532. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  533. cancel = std::make_shared<CButton>(Point(310, 428), "ICANCEL.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[7]), std::bind(&CTavernWindow::close, this), SDLK_ESCAPE);
  534. recruit = std::make_shared<CButton>(Point(272, 355), "TPTAV01.DEF", CButton::tooltip(), std::bind(&CTavernWindow::recruitb, this), SDLK_RETURN);
  535. thiefGuild = std::make_shared<CButton>(Point(22, 428), "TPTAV02.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[5]), std::bind(&CTavernWindow::thievesguildb, this), SDLK_t);
  536. if(LOCPLINT->cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) //not enough gold
  537. {
  538. recruit->addHoverText(CButton::NORMAL, CGI->generaltexth->tavernInfo[0]); //Cannot afford a Hero
  539. recruit->block(true);
  540. }
  541. else if(LOCPLINT->cb->howManyHeroes(true) >= VLC->modh->settings.MAX_HEROES_AVAILABLE_PER_PLAYER)
  542. {
  543. //Cannot recruit. You already have %d Heroes.
  544. recruit->addHoverText(CButton::NORMAL, boost::str(boost::format(CGI->generaltexth->tavernInfo[1]) % LOCPLINT->cb->howManyHeroes(true)));
  545. recruit->block(true);
  546. }
  547. else if(LOCPLINT->cb->howManyHeroes(false) >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
  548. {
  549. //Cannot recruit. You already have %d Heroes.
  550. recruit->addHoverText(CButton::NORMAL, boost::str(boost::format(CGI->generaltexth->tavernInfo[1]) % LOCPLINT->cb->howManyHeroes(false)));
  551. recruit->block(true);
  552. }
  553. else if(LOCPLINT->castleInt && LOCPLINT->castleInt->town->visitingHero)
  554. {
  555. recruit->addHoverText(CButton::NORMAL, CGI->generaltexth->tavernInfo[2]); //Cannot recruit. You already have a Hero in this town.
  556. recruit->block(true);
  557. }
  558. else
  559. {
  560. if(selected == -1)
  561. recruit->block(true);
  562. }
  563. if(LOCPLINT->castleInt)
  564. CCS->videoh->open(LOCPLINT->castleInt->town->town->clientInfo.tavernVideo);
  565. else
  566. CCS->videoh->open("TAVERN.BIK");
  567. }
  568. void CTavernWindow::recruitb()
  569. {
  570. const CGHeroInstance *toBuy = (selected ? h2 : h1)->h;
  571. const CGObjectInstance *obj = tavernObj;
  572. close();
  573. LOCPLINT->cb->recruitHero(obj, toBuy);
  574. }
  575. void CTavernWindow::thievesguildb()
  576. {
  577. GH.pushIntT<CThievesGuildWindow>(tavernObj);
  578. }
  579. CTavernWindow::~CTavernWindow()
  580. {
  581. CCS->videoh->close();
  582. }
  583. void CTavernWindow::show(SDL_Surface * to)
  584. {
  585. CWindowObject::show(to);
  586. CCS->videoh->update(pos.x+70, pos.y+56, to, true, false);
  587. if(selected >= 0)
  588. {
  589. auto sel = selected ? h2 : h1;
  590. if (selected != oldSelected && !recruit->isBlocked())
  591. {
  592. // Selected hero just changed. Update RECRUIT button hover text if recruitment is allowed.
  593. oldSelected = selected;
  594. //Recruit %s the %s
  595. recruit->addHoverText(CButton::NORMAL, boost::str(boost::format(CGI->generaltexth->tavernInfo[3]) % sel->h->getNameTranslated() % sel->h->type->heroClass->getNameTranslated()));
  596. }
  597. printAtMiddleWBLoc(sel->description, 146, 395, FONT_SMALL, 200, Colors::WHITE, to);
  598. CSDL_Ext::drawBorder(to,sel->pos.x-2,sel->pos.y-2,sel->pos.w+4,sel->pos.h+4,Colors::BRIGHT_YELLOW);
  599. }
  600. }
  601. void CTavernWindow::HeroPortrait::clickLeft(tribool down, bool previousState)
  602. {
  603. if(h && previousState && !down)
  604. *_sel = _id;
  605. }
  606. void CTavernWindow::HeroPortrait::clickRight(tribool down, bool previousState)
  607. {
  608. if(h && down)
  609. GH.pushIntT<CRClickPopupInt>(std::make_shared<CHeroWindow>(h));
  610. }
  611. CTavernWindow::HeroPortrait::HeroPortrait(int & sel, int id, int x, int y, const CGHeroInstance * H)
  612. : CIntObject(LCLICK | RCLICK | HOVER),
  613. h(H), _sel(&sel), _id(id)
  614. {
  615. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  616. h = H;
  617. pos.x += x;
  618. pos.y += y;
  619. pos.w = 58;
  620. pos.h = 64;
  621. if(H)
  622. {
  623. hoverName = CGI->generaltexth->tavernInfo[4];
  624. boost::algorithm::replace_first(hoverName,"%s",H->getNameTranslated());
  625. int artifs = (int)h->artifactsWorn.size() + (int)h->artifactsInBackpack.size();
  626. for(int i=13; i<=17; i++) //war machines and spellbook don't count
  627. if(vstd::contains(h->artifactsWorn, ArtifactPosition(i)))
  628. artifs--;
  629. description = CGI->generaltexth->allTexts[215];
  630. boost::algorithm::replace_first(description, "%s", h->getNameTranslated());
  631. boost::algorithm::replace_first(description, "%d", boost::lexical_cast<std::string>(h->level));
  632. boost::algorithm::replace_first(description, "%s", h->type->heroClass->getNameTranslated());
  633. boost::algorithm::replace_first(description, "%d", boost::lexical_cast<std::string>(artifs));
  634. portrait = std::make_shared<CAnimImage>("portraitsLarge", h->portrait);
  635. }
  636. }
  637. void CTavernWindow::HeroPortrait::hover(bool on)
  638. {
  639. //Hoverable::hover(on);
  640. if(on)
  641. GH.statusbar->write(hoverName);
  642. else
  643. GH.statusbar->clear();
  644. }
  645. static const std::string QUICK_EXCHANGE_MOD_PREFIX = "quick-exchange";
  646. static const std::string QUICK_EXCHANGE_BG = QUICK_EXCHANGE_MOD_PREFIX + "/TRADEQE";
  647. static bool isQuickExchangeLayoutAvailable()
  648. {
  649. return CResourceHandler::get()->existsResource(ResourceID(std::string("SPRITES/") + QUICK_EXCHANGE_BG, EResType::IMAGE));
  650. }
  651. // Runs a task asynchronously with gamestate locking and waitTillRealize set to true
  652. class GsThread
  653. {
  654. private:
  655. std::function<void()> action;
  656. std::shared_ptr<CCallback> cb;
  657. public:
  658. static void run(std::function<void()> action)
  659. {
  660. std::shared_ptr<GsThread> instance(new GsThread(action));
  661. boost::thread(std::bind(&GsThread::staticRun, instance));
  662. }
  663. private:
  664. GsThread(std::function<void()> action)
  665. :action(action), cb(LOCPLINT->cb)
  666. {
  667. }
  668. static void staticRun(std::shared_ptr<GsThread> instance)
  669. {
  670. instance->run();
  671. }
  672. void run()
  673. {
  674. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  675. auto originalWaitTillRealize = cb->waitTillRealize;
  676. auto originalUnlockGsWhenWating = cb->unlockGsWhenWaiting;
  677. cb->waitTillRealize = true;
  678. cb->unlockGsWhenWaiting = true;
  679. action();
  680. cb->waitTillRealize = originalWaitTillRealize;
  681. cb->unlockGsWhenWaiting = originalUnlockGsWhenWating;
  682. }
  683. };
  684. CExchangeController::CExchangeController(CExchangeWindow * view, ObjectInstanceID hero1, ObjectInstanceID hero2)
  685. :left(LOCPLINT->cb->getHero(hero1)), right(LOCPLINT->cb->getHero(hero2)), cb(LOCPLINT->cb), view(view)
  686. {
  687. }
  688. std::function<void()> CExchangeController::onMoveArmyToLeft()
  689. {
  690. return [&]() { moveArmy(false); };
  691. }
  692. std::function<void()> CExchangeController::onMoveArmyToRight()
  693. {
  694. return [&]() { moveArmy(true); };
  695. }
  696. std::vector<CArtifactInstance *> getBackpackArts(const CGHeroInstance * hero)
  697. {
  698. std::vector<CArtifactInstance *> result;
  699. for(auto slot : hero->artifactsInBackpack)
  700. {
  701. result.push_back(slot.artifact);
  702. }
  703. return result;
  704. }
  705. std::function<void()> CExchangeController::onSwapArtifacts()
  706. {
  707. return [&]()
  708. {
  709. GsThread::run([=]
  710. {
  711. cb->bulkMoveArtifacts(left->id, right->id, true);
  712. });
  713. };
  714. }
  715. std::function<void()> CExchangeController::onMoveArtifactsToLeft()
  716. {
  717. return [&]() { moveArtifacts(false); };
  718. }
  719. std::function<void()> CExchangeController::onMoveArtifactsToRight()
  720. {
  721. return [&]() { moveArtifacts(true); };
  722. }
  723. std::vector<std::pair<SlotID, CStackInstance *>> getStacks(const CArmedInstance * source)
  724. {
  725. auto slots = source->Slots();
  726. return std::vector<std::pair<SlotID, CStackInstance *>>(slots.begin(), slots.end());
  727. }
  728. std::function<void()> CExchangeController::onSwapArmy()
  729. {
  730. return [&]()
  731. {
  732. GsThread::run([=]
  733. {
  734. if(left->tempOwner != cb->getMyColor()
  735. || right->tempOwner != cb->getMyColor())
  736. {
  737. return;
  738. }
  739. auto leftSlots = getStacks(left);
  740. auto rightSlots = getStacks(right);
  741. auto i = leftSlots.begin(), j = rightSlots.begin();
  742. for(; i != leftSlots.end() && j != rightSlots.end(); i++, j++)
  743. {
  744. cb->swapCreatures(left, right, i->first, j->first);
  745. }
  746. if(i != leftSlots.end())
  747. {
  748. for(; i != leftSlots.end(); i++)
  749. {
  750. cb->swapCreatures(left, right, i->first, right->getFreeSlot());
  751. }
  752. }
  753. else if(j != rightSlots.end())
  754. {
  755. for(; j != rightSlots.end(); j++)
  756. {
  757. cb->swapCreatures(left, right, left->getFreeSlot(), j->first);
  758. }
  759. }
  760. });
  761. };
  762. }
  763. std::function<void()> CExchangeController::onMoveStackToLeft(SlotID slotID)
  764. {
  765. return [=]()
  766. {
  767. if(right->tempOwner != cb->getMyColor())
  768. {
  769. return;
  770. }
  771. moveStack(right, left, slotID);
  772. };
  773. }
  774. std::function<void()> CExchangeController::onMoveStackToRight(SlotID slotID)
  775. {
  776. return [=]()
  777. {
  778. if(left->tempOwner != cb->getMyColor())
  779. {
  780. return;
  781. }
  782. moveStack(left, right, slotID);
  783. };
  784. }
  785. void CExchangeController::moveStack(
  786. const CGHeroInstance * source,
  787. const CGHeroInstance * target,
  788. SlotID sourceSlot)
  789. {
  790. auto creature = source->getCreature(sourceSlot);
  791. SlotID targetSlot = target->getSlotFor(creature);
  792. if(targetSlot.validSlot())
  793. {
  794. if(source->stacksCount() == 1 && source->needsLastStack())
  795. {
  796. cb->splitStack(
  797. source,
  798. target,
  799. sourceSlot,
  800. targetSlot,
  801. target->getStackCount(targetSlot) + source->getStackCount(sourceSlot) - 1);
  802. }
  803. else
  804. {
  805. cb->mergeOrSwapStacks(source, target, sourceSlot, targetSlot);
  806. }
  807. }
  808. }
  809. void CExchangeController::moveArmy(bool leftToRight)
  810. {
  811. const CGHeroInstance * source = leftToRight ? left : right;
  812. const CGHeroInstance * target = leftToRight ? right : left;
  813. const CGarrisonSlot * selection = this->view->getSelectedSlotID();
  814. SlotID slot;
  815. if(source->tempOwner != cb->getMyColor())
  816. {
  817. return;
  818. }
  819. if(selection && selection->our() && selection->getObj() == source)
  820. {
  821. slot = selection->getSlot();
  822. }
  823. else
  824. {
  825. auto weakestSlot = vstd::minElementByFun(
  826. source->Slots(),
  827. [](const std::pair<SlotID, CStackInstance *> & s) -> int
  828. {
  829. return s.second->getCreatureID().toCreature()->AIValue;
  830. });
  831. slot = weakestSlot->first;
  832. }
  833. cb->bulkMoveArmy(source->id, target->id, slot);
  834. }
  835. void CExchangeController::moveArtifacts(bool leftToRight)
  836. {
  837. const CGHeroInstance * source = leftToRight ? left : right;
  838. const CGHeroInstance * target = leftToRight ? right : left;
  839. if(source->tempOwner != cb->getMyColor())
  840. {
  841. return;
  842. }
  843. GsThread::run([=]
  844. {
  845. cb->bulkMoveArtifacts(source->id, target->id, false);
  846. });
  847. }
  848. void CExchangeController::moveArtifact(
  849. const CGHeroInstance * source,
  850. const CGHeroInstance * target,
  851. ArtifactPosition srcPosition)
  852. {
  853. auto srcLocation = ArtifactLocation(source, srcPosition);
  854. auto dstLocation = ArtifactLocation(target,
  855. ArtifactUtils::getArtifactDstPosition(source->getArt(srcPosition), target, target->bearerType()));
  856. cb->swapArtifacts(srcLocation, dstLocation);
  857. }
  858. CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID queryID)
  859. : CStatusbarWindow(PLAYER_COLORED | BORDERED, isQuickExchangeLayoutAvailable() ? QUICK_EXCHANGE_BG : "TRADE2"),
  860. controller(this, hero1, hero2),
  861. moveStackLeftButtons(),
  862. moveStackRightButtons()
  863. {
  864. const bool qeLayout = isQuickExchangeLayoutAvailable();
  865. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  866. heroInst[0] = LOCPLINT->cb->getHero(hero1);
  867. heroInst[1] = LOCPLINT->cb->getHero(hero2);
  868. auto genTitle = [](const CGHeroInstance * h)
  869. {
  870. boost::format fmt(CGI->generaltexth->allTexts[138]);
  871. fmt % h->getNameTranslated() % h->level % h->type->heroClass->getNameTranslated();
  872. return boost::str(fmt);
  873. };
  874. titles[0] = std::make_shared<CLabel>(147, 25, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, genTitle(heroInst[0]));
  875. titles[1] = std::make_shared<CLabel>(653, 25, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, genTitle(heroInst[1]));
  876. auto PSKIL32 = std::make_shared<CAnimation>("PSKIL32");
  877. PSKIL32->preload();
  878. auto SECSK32 = std::make_shared<CAnimation>("SECSK32");
  879. for(int g = 0; g < 4; ++g)
  880. {
  881. if (qeLayout)
  882. primSkillImages.push_back(std::make_shared<CAnimImage>(PSKIL32, g, Rect(389, 12 + 26 * g, 22, 22)));
  883. else
  884. primSkillImages.push_back(std::make_shared<CAnimImage>(PSKIL32, g, 0, 385, 19 + 36 * g));
  885. }
  886. for(int leftRight : {0, 1})
  887. {
  888. const CGHeroInstance * hero = heroInst.at(leftRight);
  889. herosWArt[leftRight] = std::make_shared<CHeroWithMaybePickedArtifact>(this, hero);
  890. for(int m=0; m<GameConstants::PRIMARY_SKILLS; ++m)
  891. primSkillValues[leftRight].push_back(std::make_shared<CLabel>(352 + (qeLayout ? 96 : 93) * leftRight, (qeLayout ? 22 : 35) + (qeLayout ? 26 : 36) * m, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE));
  892. for(int m=0; m < hero->secSkills.size(); ++m)
  893. secSkillIcons[leftRight].push_back(std::make_shared<CAnimImage>(SECSK32, 0, 0, 32 + 36 * m + 454 * leftRight, qeLayout ? 83 : 88));
  894. specImages[leftRight] = std::make_shared<CAnimImage>("UN32", hero->type->imageIndex, 0, 67 + 490 * leftRight, qeLayout ? 41 : 45);
  895. expImages[leftRight] = std::make_shared<CAnimImage>(PSKIL32, 4, 0, 103 + 490 * leftRight, qeLayout ? 41 : 45);
  896. expValues[leftRight] = std::make_shared<CLabel>(119 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  897. manaImages[leftRight] = std::make_shared<CAnimImage>(PSKIL32, 5, 0, 139 + 490 * leftRight, qeLayout ? 41 : 45);
  898. manaValues[leftRight] = std::make_shared<CLabel>(155 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  899. }
  900. portraits[0] = std::make_shared<CAnimImage>("PortraitsLarge", heroInst[0]->portrait, 0, 257, 13);
  901. portraits[1] = std::make_shared<CAnimImage>("PortraitsLarge", heroInst[1]->portrait, 0, 485, 13);
  902. artifs[0] = std::make_shared<CArtifactsOfHero>(Point(-334, 150));
  903. artifs[0]->commonInfo = std::make_shared<CArtifactsOfHero::SCommonPart>();
  904. artifs[0]->commonInfo->participants.insert(artifs[0].get());
  905. artifs[0]->setHero(heroInst[0]);
  906. artifs[1] = std::make_shared<CArtifactsOfHero>(Point(96, 150));
  907. artifs[1]->commonInfo = artifs[0]->commonInfo;
  908. artifs[1]->commonInfo->participants.insert(artifs[1].get());
  909. artifs[1]->setHero(heroInst[1]);
  910. addSet(artifs[0]);
  911. addSet(artifs[1]);
  912. for(int g=0; g<4; ++g)
  913. {
  914. primSkillAreas.push_back(std::make_shared<LRClickableAreaWTextComp>());
  915. if (qeLayout)
  916. primSkillAreas[g]->pos = genRect(22, 152, pos.x + 324, pos.y + 12 + 26 * g);
  917. else
  918. primSkillAreas[g]->pos = genRect(32, 140, pos.x + 329, pos.y + 19 + 36 * g);
  919. primSkillAreas[g]->text = CGI->generaltexth->arraytxt[2+g];
  920. primSkillAreas[g]->type = g;
  921. primSkillAreas[g]->bonusValue = -1;
  922. primSkillAreas[g]->baseType = 0;
  923. primSkillAreas[g]->hoverText = CGI->generaltexth->heroscrn[1];
  924. boost::replace_first(primSkillAreas[g]->hoverText, "%s", CGI->generaltexth->primarySkillNames[g]);
  925. }
  926. //heroes related thing
  927. for(int b=0; b < heroInst.size(); b++)
  928. {
  929. const CGHeroInstance * hero = heroInst.at(b);
  930. //secondary skill's clickable areas
  931. for(int g=0; g<hero->secSkills.size(); ++g)
  932. {
  933. int skill = hero->secSkills[g].first,
  934. level = hero->secSkills[g].second; // <1, 3>
  935. secSkillAreas[b].push_back(std::make_shared<LRClickableAreaWTextComp>());
  936. secSkillAreas[b][g]->pos = genRect(32, 32, pos.x + 32 + g*36 + b*454 , pos.y + (qeLayout ? 83 : 88));
  937. secSkillAreas[b][g]->baseType = 1;
  938. secSkillAreas[b][g]->type = skill;
  939. secSkillAreas[b][g]->bonusValue = level;
  940. secSkillAreas[b][g]->text = CGI->skillh->getByIndex(skill)->getDescriptionTranslated(level);
  941. secSkillAreas[b][g]->hoverText = CGI->generaltexth->heroscrn[21];
  942. boost::algorithm::replace_first(secSkillAreas[b][g]->hoverText, "%s", CGI->generaltexth->levels[level - 1]);
  943. boost::algorithm::replace_first(secSkillAreas[b][g]->hoverText, "%s", CGI->skillh->getByIndex(skill)->getNameTranslated());
  944. }
  945. heroAreas[b] = std::make_shared<CHeroArea>(257 + 228*b, 13, hero);
  946. specialtyAreas[b] = std::make_shared<LRClickableAreaWText>();
  947. specialtyAreas[b]->pos = genRect(32, 32, pos.x + 69 + 490*b, pos.y + (qeLayout ? 41 : 45));
  948. specialtyAreas[b]->hoverText = CGI->generaltexth->heroscrn[27];
  949. specialtyAreas[b]->text = hero->type->getSpecialtyDescriptionTranslated();
  950. experienceAreas[b] = std::make_shared<LRClickableAreaWText>();
  951. experienceAreas[b]->pos = genRect(32, 32, pos.x + 105 + 490*b, pos.y + (qeLayout ? 41 : 45));
  952. experienceAreas[b]->hoverText = CGI->generaltexth->heroscrn[9];
  953. experienceAreas[b]->text = CGI->generaltexth->allTexts[2];
  954. boost::algorithm::replace_first(experienceAreas[b]->text, "%d", boost::lexical_cast<std::string>(hero->level));
  955. boost::algorithm::replace_first(experienceAreas[b]->text, "%d", boost::lexical_cast<std::string>(CGI->heroh->reqExp(hero->level+1)));
  956. boost::algorithm::replace_first(experienceAreas[b]->text, "%d", boost::lexical_cast<std::string>(hero->exp));
  957. spellPointsAreas[b] = std::make_shared<LRClickableAreaWText>();
  958. spellPointsAreas[b]->pos = genRect(32, 32, pos.x + 141 + 490*b, pos.y + (qeLayout ? 41 : 45));
  959. spellPointsAreas[b]->hoverText = CGI->generaltexth->heroscrn[22];
  960. spellPointsAreas[b]->text = CGI->generaltexth->allTexts[205];
  961. boost::algorithm::replace_first(spellPointsAreas[b]->text, "%s", hero->getNameTranslated());
  962. boost::algorithm::replace_first(spellPointsAreas[b]->text, "%d", boost::lexical_cast<std::string>(hero->mana));
  963. boost::algorithm::replace_first(spellPointsAreas[b]->text, "%d", boost::lexical_cast<std::string>(hero->manaLimit()));
  964. morale[b] = std::make_shared<MoraleLuckBox>(true, genRect(32, 32, 176 + 490 * b, 39), true);
  965. luck[b] = std::make_shared<MoraleLuckBox>(false, genRect(32, 32, 212 + 490 * b, 39), true);
  966. }
  967. quit = std::make_shared<CButton>(Point(732, 567), "IOKAY.DEF", CGI->generaltexth->zelp[600], std::bind(&CExchangeWindow::close, this), SDLK_RETURN);
  968. if(queryID.getNum() > 0)
  969. quit->addCallback([=](){ LOCPLINT->cb->selectionMade(0, queryID); });
  970. questlogButton[0] = std::make_shared<CButton>(Point( 10, qeLayout ? 39 : 44), "hsbtns4.def", CButton::tooltip(CGI->generaltexth->heroscrn[0]), std::bind(&CExchangeWindow::questlog, this, 0));
  971. questlogButton[1] = std::make_shared<CButton>(Point(740, qeLayout ? 39 : 44), "hsbtns4.def", CButton::tooltip(CGI->generaltexth->heroscrn[0]), std::bind(&CExchangeWindow::questlog, this, 1));
  972. Rect barRect(5, 578, 725, 18);
  973. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), barRect, 5, 578));
  974. //garrison interface
  975. garr = std::make_shared<CGarrisonInt>(69, qeLayout ? 122 : 131, 4, Point(418,0), heroInst[0], heroInst[1], true, true);
  976. auto splitButtonCallback = [&](){ garr->splitClick(); };
  977. garr->addSplitBtn(std::make_shared<CButton>( Point( 10, qeLayout ? 122 : 132), "TSBTNS.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3]), splitButtonCallback));
  978. garr->addSplitBtn(std::make_shared<CButton>( Point(744, qeLayout ? 122 : 132), "TSBTNS.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3]), splitButtonCallback));
  979. if(qeLayout)
  980. {
  981. moveAllGarrButtonLeft = std::make_shared<CButton>(Point(325, 118), QUICK_EXCHANGE_MOD_PREFIX + "/armRight.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[1]), controller.onMoveArmyToRight());
  982. echangeGarrButton = std::make_shared<CButton>(Point(377, 118), QUICK_EXCHANGE_MOD_PREFIX + "/swapAll.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[2]), controller.onSwapArmy());
  983. moveAllGarrButtonRight = std::make_shared<CButton>(Point(425, 118), QUICK_EXCHANGE_MOD_PREFIX + "/armLeft.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[1]), controller.onMoveArmyToLeft());
  984. moveArtifactsButtonLeft = std::make_shared<CButton>(Point(325, 154), QUICK_EXCHANGE_MOD_PREFIX + "/artRight.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[3]), controller.onMoveArtifactsToRight());
  985. echangeArtifactsButton = std::make_shared<CButton>(Point(377, 154), QUICK_EXCHANGE_MOD_PREFIX + "/swapAll.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[4]), controller.onSwapArtifacts());
  986. moveArtifactsButtonRight = std::make_shared<CButton>(Point(425, 154), QUICK_EXCHANGE_MOD_PREFIX + "/artLeft.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[3]), controller.onMoveArtifactsToLeft());
  987. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  988. {
  989. moveStackLeftButtons.push_back(
  990. std::make_shared<CButton>(
  991. Point(484 + 35 * i, 154),
  992. QUICK_EXCHANGE_MOD_PREFIX + "/unitLeft.DEF",
  993. CButton::tooltip(CGI->generaltexth->qeModCommands[1]),
  994. controller.onMoveStackToLeft(SlotID(i))));
  995. moveStackRightButtons.push_back(
  996. std::make_shared<CButton>(
  997. Point(66 + 35 * i, 154),
  998. QUICK_EXCHANGE_MOD_PREFIX + "/unitRight.DEF",
  999. CButton::tooltip(CGI->generaltexth->qeModCommands[1]),
  1000. controller.onMoveStackToRight(SlotID(i))));
  1001. }
  1002. }
  1003. updateWidgets();
  1004. }
  1005. const CGarrisonSlot * CExchangeWindow::getSelectedSlotID() const
  1006. {
  1007. return garr->getSelection();
  1008. }
  1009. void CExchangeWindow::updateGarrisons()
  1010. {
  1011. garr->recreateSlots();
  1012. updateWidgets();
  1013. }
  1014. void CExchangeWindow::questlog(int whichHero)
  1015. {
  1016. CCS->curh->dragAndDropCursor(nullptr);
  1017. LOCPLINT->showQuestLog();
  1018. }
  1019. void CExchangeWindow::updateWidgets()
  1020. {
  1021. for(size_t leftRight : {0, 1})
  1022. {
  1023. const CGHeroInstance * hero = heroInst.at(leftRight);
  1024. for(int m=0; m<GameConstants::PRIMARY_SKILLS; ++m)
  1025. {
  1026. auto value = herosWArt[leftRight]->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(m));
  1027. primSkillValues[leftRight][m]->setText(boost::lexical_cast<std::string>(value));
  1028. }
  1029. for(int m=0; m < hero->secSkills.size(); ++m)
  1030. {
  1031. int id = hero->secSkills[m].first;
  1032. int level = hero->secSkills[m].second;
  1033. secSkillIcons[leftRight][m]->setFrame(2 + id * 3 + level);
  1034. }
  1035. expValues[leftRight]->setText(makeNumberShort(hero->exp));
  1036. manaValues[leftRight]->setText(makeNumberShort(hero->mana));
  1037. morale[leftRight]->set(hero);
  1038. luck[leftRight]->set(hero);
  1039. }
  1040. }
  1041. CShipyardWindow::CShipyardWindow(const std::vector<si32> & cost, int state, int boatType, const std::function<void()> & onBuy)
  1042. : CStatusbarWindow(PLAYER_COLORED, "TPSHIP")
  1043. {
  1044. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1045. bgWater = std::make_shared<CPicture>("TPSHIPBK", 100, 69);
  1046. std::string boatFilenames[3] = {"AB01_", "AB02_", "AB03_"};
  1047. Point waterCenter = Point(bgWater->pos.x+bgWater->pos.w/2, bgWater->pos.y+bgWater->pos.h/2);
  1048. bgShip = std::make_shared<CAnimImage>(boatFilenames[boatType], 0, 7, 120, 96, 0);
  1049. bgShip->center(waterCenter);
  1050. // Create resource icons and costs.
  1051. std::string goldValue = boost::lexical_cast<std::string>(cost[Res::GOLD]);
  1052. std::string woodValue = boost::lexical_cast<std::string>(cost[Res::WOOD]);
  1053. goldCost = std::make_shared<CLabel>(118, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, goldValue);
  1054. woodCost = std::make_shared<CLabel>(212, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, woodValue);
  1055. goldPic = std::make_shared<CAnimImage>("RESOURCE", Res::GOLD, 0, 100, 244);
  1056. woodPic = std::make_shared<CAnimImage>("RESOURCE", Res::WOOD, 0, 196, 244);
  1057. quit = std::make_shared<CButton>(Point(224, 312), "ICANCEL", CButton::tooltip(CGI->generaltexth->allTexts[599]), std::bind(&CShipyardWindow::close, this), SDLK_ESCAPE);
  1058. build = std::make_shared<CButton>(Point(42, 312), "IBUY30", CButton::tooltip(CGI->generaltexth->allTexts[598]), std::bind(&CShipyardWindow::close, this), SDLK_RETURN);
  1059. build->addCallback(onBuy);
  1060. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1061. {
  1062. if(cost[i] > LOCPLINT->cb->getResourceAmount(i))
  1063. {
  1064. build->block(true);
  1065. break;
  1066. }
  1067. }
  1068. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1069. title = std::make_shared<CLabel>(164, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[13]);
  1070. costLabel = std::make_shared<CLabel>(164, 220, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[14]);
  1071. }
  1072. CPuzzleWindow::CPuzzleWindow(const int3 & GrailPos, double discoveredRatio)
  1073. : CWindowObject(PLAYER_COLORED | BORDERED, "PUZZLE"),
  1074. grailPos(GrailPos),
  1075. currentAlpha(SDL_ALPHA_OPAQUE)
  1076. {
  1077. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1078. CCS->soundh->playSound(soundBase::OBELISK);
  1079. quitb = std::make_shared<CButton>(Point(670, 538), "IOK6432.DEF", CButton::tooltip(CGI->generaltexth->allTexts[599]), std::bind(&CPuzzleWindow::close, this), SDLK_RETURN);
  1080. quitb->assignedKeys.insert(SDLK_ESCAPE);
  1081. quitb->setBorderColor(Colors::METALLIC_GOLD);
  1082. logo = std::make_shared<CPicture>("PUZZLOGO", 607, 3);
  1083. title = std::make_shared<CLabel>(700, 95, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[463]);
  1084. resDataBar = std::make_shared<CResDataBar>("ARESBAR.bmp", 3, 575, 32, 2, 85, 85);
  1085. int faction = LOCPLINT->cb->getStartInfo()->playerInfos.find(LOCPLINT->playerID)->second.castle;
  1086. auto & puzzleMap = (*CGI->townh)[faction]->puzzleMap;
  1087. for(auto & elem : puzzleMap)
  1088. {
  1089. const SPuzzleInfo & info = elem;
  1090. auto piece = std::make_shared<CPicture>(info.filename, info.x, info.y);
  1091. //piece that will slowly disappear
  1092. if(info.whenUncovered <= GameConstants::PUZZLE_MAP_PIECES * discoveredRatio)
  1093. {
  1094. piecesToRemove.push_back(piece);
  1095. piece->needRefresh = true;
  1096. piece->recActions = piece->recActions & ~SHOWALL;
  1097. }
  1098. else
  1099. {
  1100. visiblePieces.push_back(piece);
  1101. }
  1102. }
  1103. }
  1104. void CPuzzleWindow::showAll(SDL_Surface * to)
  1105. {
  1106. int3 moveInt = int3(8, 9, 0);
  1107. Rect mapRect = genRect(544, 591, pos.x + 8, pos.y + 7);
  1108. int3 topTile = grailPos - moveInt;
  1109. MapDrawingInfo info(topTile, LOCPLINT->cb->getVisibilityMap(), mapRect);
  1110. info.puzzleMode = true;
  1111. info.grailPos = grailPos;
  1112. CGI->mh->drawTerrainRectNew(to, &info);
  1113. CWindowObject::showAll(to);
  1114. }
  1115. void CPuzzleWindow::show(SDL_Surface * to)
  1116. {
  1117. static int animSpeed = 2;
  1118. if(currentAlpha < animSpeed)
  1119. {
  1120. piecesToRemove.clear();
  1121. }
  1122. else
  1123. {
  1124. //update disappearing puzzles
  1125. for(auto & piece : piecesToRemove)
  1126. piece->setAlpha(currentAlpha);
  1127. currentAlpha -= animSpeed;
  1128. }
  1129. CWindowObject::show(to);
  1130. }
  1131. void CTransformerWindow::CItem::move()
  1132. {
  1133. if(left)
  1134. moveBy(Point(289, 0));
  1135. else
  1136. moveBy(Point(-289, 0));
  1137. left = !left;
  1138. }
  1139. void CTransformerWindow::CItem::clickLeft(tribool down, bool previousState)
  1140. {
  1141. if(previousState && (!down))
  1142. {
  1143. move();
  1144. parent->redraw();
  1145. }
  1146. }
  1147. void CTransformerWindow::CItem::update()
  1148. {
  1149. icon->setFrame(parent->army->getCreature(SlotID(id))->idNumber + 2);
  1150. }
  1151. CTransformerWindow::CItem::CItem(CTransformerWindow * parent_, int size_, int id_)
  1152. : CIntObject(LCLICK),
  1153. id(id_),
  1154. size(size_),
  1155. parent(parent_)
  1156. {
  1157. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1158. left = true;
  1159. pos.w = 58;
  1160. pos.h = 64;
  1161. pos.x += 45 + (id%3)*83 + id/6*83;
  1162. pos.y += 109 + (id/3)*98;
  1163. icon = std::make_shared<CAnimImage>("TWCRPORT", parent->army->getCreature(SlotID(id))->idNumber + 2);
  1164. count = std::make_shared<CLabel>(28, 76,FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(size));
  1165. }
  1166. void CTransformerWindow::makeDeal()
  1167. {
  1168. for(auto & elem : items)
  1169. {
  1170. if(!elem->left)
  1171. LOCPLINT->cb->trade(town, EMarketMode::CREATURE_UNDEAD, elem->id, 0, 0, hero);
  1172. }
  1173. }
  1174. void CTransformerWindow::addAll()
  1175. {
  1176. for(auto & elem : items)
  1177. {
  1178. if(elem->left)
  1179. elem->move();
  1180. }
  1181. redraw();
  1182. }
  1183. void CTransformerWindow::updateGarrisons()
  1184. {
  1185. for(auto & item : items)
  1186. item->update();
  1187. }
  1188. CTransformerWindow::CTransformerWindow(const CGHeroInstance * _hero, const CGTownInstance * _town)
  1189. : CStatusbarWindow(PLAYER_COLORED, "SKTRNBK"),
  1190. hero(_hero),
  1191. town(_town)
  1192. {
  1193. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1194. if(hero)
  1195. army = hero;
  1196. else
  1197. army = town;
  1198. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1199. {
  1200. if(army->getCreature(SlotID(i)))
  1201. items.push_back(std::make_shared<CItem>(this, army->getStackCount(SlotID(i)), i));
  1202. }
  1203. all = std::make_shared<CButton>(Point(146, 416), "ALTARMY.DEF", CGI->generaltexth->zelp[590], [&](){ addAll(); }, SDLK_a);
  1204. convert = std::make_shared<CButton>(Point(269, 416), "ALTSACR.DEF", CGI->generaltexth->zelp[591], [&](){ makeDeal(); }, SDLK_RETURN);
  1205. cancel = std::make_shared<CButton>(Point(392, 416), "ICANCEL.DEF", CGI->generaltexth->zelp[592], [&](){ close(); },SDLK_ESCAPE);
  1206. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1207. titleLeft = std::make_shared<CLabel>(153, 29,FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[485]);//holding area
  1208. titleRight = std::make_shared<CLabel>(153+295, 29, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[486]);//transformer
  1209. 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
  1210. 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
  1211. }
  1212. CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int Y)
  1213. : CIntObject(LCLICK | RCLICK | HOVER),
  1214. ID(_ID),
  1215. parent(_parent)
  1216. {
  1217. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1218. pos.x += X;
  1219. pos.y += Y;
  1220. topBar = std::make_shared<CAnimImage>(parent->bars, 0, 0, -28, -22);
  1221. bottomBar = std::make_shared<CAnimImage>(parent->bars, 0, 0, -28, 48);
  1222. icon = std::make_shared<CAnimImage>("SECSKILL", _ID * 3 + 3, 0);
  1223. name = std::make_shared<CLabel>(22, -13, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->skillh->getByIndex(ID)->getNameTranslated());
  1224. level = std::make_shared<CLabel>(22, 57, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->levels[0]);
  1225. pos.h = icon->pos.h;
  1226. pos.w = icon->pos.w;
  1227. }
  1228. void CUniversityWindow::CItem::clickLeft(tribool down, bool previousState)
  1229. {
  1230. if(previousState && (!down))
  1231. {
  1232. if(state() == 2)
  1233. GH.pushIntT<CUnivConfirmWindow>(parent, ID, LOCPLINT->cb->getResourceAmount(Res::GOLD) >= 2000);
  1234. }
  1235. }
  1236. void CUniversityWindow::CItem::clickRight(tribool down, bool previousState)
  1237. {
  1238. if(down)
  1239. {
  1240. CRClickPopup::createAndPush(CGI->skillh->getByIndex(ID)->getDescriptionTranslated(1), std::make_shared<CComponent>(CComponent::secskill, ID, 1));
  1241. }
  1242. }
  1243. void CUniversityWindow::CItem::hover(bool on)
  1244. {
  1245. if(on)
  1246. GH.statusbar->write(CGI->skillh->getByIndex(ID)->getNameTranslated());
  1247. else
  1248. GH.statusbar->clear();
  1249. }
  1250. int CUniversityWindow::CItem::state()
  1251. {
  1252. if(parent->hero->getSecSkillLevel(SecondarySkill(ID)))//hero know this skill
  1253. return 1;
  1254. if(!parent->hero->canLearnSkill(SecondarySkill(ID)))//can't learn more skills
  1255. return 0;
  1256. return 2;
  1257. }
  1258. void CUniversityWindow::CItem::showAll(SDL_Surface * to)
  1259. {
  1260. //TODO: update when state actually changes
  1261. auto stateIndex = state();
  1262. topBar->setFrame(stateIndex);
  1263. bottomBar->setFrame(stateIndex);
  1264. CIntObject::showAll(to);
  1265. }
  1266. CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, const IMarket * _market)
  1267. : CStatusbarWindow(PLAYER_COLORED, "UNIVERS1"),
  1268. hero(_hero),
  1269. market(_market)
  1270. {
  1271. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1272. bars = std::make_shared<CAnimation>();
  1273. bars->setCustom("UNIVRED", 0, 0);
  1274. bars->setCustom("UNIVGOLD", 1, 0);
  1275. bars->setCustom("UNIVGREN", 2, 0);
  1276. bars->preload();
  1277. if(market->o->ID == Obj::TOWN)
  1278. {
  1279. auto town = dynamic_cast<const CGTownInstance *>(_market);
  1280. if(town)
  1281. {
  1282. auto faction = town->town->faction->getId();
  1283. auto bid = town->town->getSpecialBuilding(BuildingSubID::MAGIC_UNIVERSITY)->bid;
  1284. titlePic = std::make_shared<CAnimImage>((*CGI->townh)[faction]->town->clientInfo.buildingsIcons, bid);
  1285. }
  1286. else
  1287. titlePic = std::make_shared<CAnimImage>((*CGI->townh)[ETownType::CONFLUX]->town->clientInfo.buildingsIcons, BuildingID::MAGIC_UNIVERSITY);
  1288. }
  1289. else
  1290. titlePic = std::make_shared<CPicture>("UNIVBLDG");
  1291. titlePic->center(Point(232 + pos.x, 76 + pos.y));
  1292. clerkSpeech = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[603], Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  1293. title = std::make_shared<CLabel>(231, 26, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[602]);
  1294. std::vector<int> goods = market->availableItemsIds(EMarketMode::RESOURCE_SKILL);
  1295. assert(goods.size() == 4);
  1296. for(int i=0; i<goods.size(); i++)//prepare clickable items
  1297. items.push_back(std::make_shared<CItem>(this, goods[i], 54+i*104, 234));
  1298. cancel = std::make_shared<CButton>(Point(200, 313), "IOKAY.DEF", CGI->generaltexth->zelp[632], [&](){ close(); }, SDLK_RETURN);
  1299. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1300. }
  1301. void CUniversityWindow::makeDeal(int skill)
  1302. {
  1303. LOCPLINT->cb->trade(market->o, EMarketMode::RESOURCE_SKILL, 6, skill, 1, hero);
  1304. }
  1305. CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * owner_, int SKILL, bool available)
  1306. : CStatusbarWindow(PLAYER_COLORED, "UNIVERS2.PCX"),
  1307. owner(owner_)
  1308. {
  1309. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1310. std::string text = CGI->generaltexth->allTexts[608];
  1311. boost::replace_first(text, "%s", CGI->generaltexth->levels[0]);
  1312. boost::replace_first(text, "%s", CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1313. boost::replace_first(text, "%d", "2000");
  1314. clerkSpeech = std::make_shared<CTextBox>(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  1315. name = std::make_shared<CLabel>(230, 37, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1316. icon = std::make_shared<CAnimImage>("SECSKILL", SKILL*3+3, 0, 211, 51);
  1317. level = std::make_shared<CLabel>(230, 107, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->levels[1]);
  1318. costIcon = std::make_shared<CAnimImage>("RESOURCE", Res::GOLD, 0, 210, 210);
  1319. cost = std::make_shared<CLabel>(230, 267, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "2000");
  1320. std::string hoverText = CGI->generaltexth->allTexts[609];
  1321. boost::replace_first(hoverText, "%s", CGI->generaltexth->levels[0]+ " " + CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1322. text = CGI->generaltexth->zelp[633].second;
  1323. boost::replace_first(text, "%s", CGI->generaltexth->levels[0]);
  1324. boost::replace_first(text, "%s", CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1325. boost::replace_first(text, "%d", "2000");
  1326. confirm = std::make_shared<CButton>(Point(148, 299), "IBY6432.DEF", CButton::tooltip(hoverText, text), [=](){makeDeal(SKILL);}, SDLK_RETURN);
  1327. confirm->block(!available);
  1328. cancel = std::make_shared<CButton>(Point(252,299), "ICANCEL.DEF", CGI->generaltexth->zelp[631], [&](){ close(); }, SDLK_ESCAPE);
  1329. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1330. }
  1331. void CUnivConfirmWindow::makeDeal(int skill)
  1332. {
  1333. owner->makeDeal(skill);
  1334. close();
  1335. }
  1336. CGarrisonWindow::CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits)
  1337. : CWindowObject(PLAYER_COLORED, "GARRISON")
  1338. {
  1339. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1340. garr = std::make_shared<CGarrisonInt>(92, 127, 4, Point(0,96), up, down, removableUnits);
  1341. {
  1342. auto split = std::make_shared<CButton>(Point(88, 314), "IDV6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3], ""), [&](){ garr->splitClick(); } );
  1343. garr->addSplitBtn(split);
  1344. }
  1345. quit = std::make_shared<CButton>(Point(399, 314), "IOK6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[8], ""), [&](){ close(); }, SDLK_RETURN);
  1346. std::string titleText;
  1347. if(down->tempOwner == up->tempOwner)
  1348. {
  1349. titleText = CGI->generaltexth->allTexts[709];
  1350. }
  1351. else
  1352. {
  1353. //assume that this is joining monsters dialog
  1354. if(up->Slots().size() > 0)
  1355. {
  1356. titleText = CGI->generaltexth->allTexts[35];
  1357. boost::algorithm::replace_first(titleText, "%s", up->Slots().begin()->second->type->getNamePluralTranslated());
  1358. }
  1359. else
  1360. {
  1361. logGlobal->error("Invalid armed instance for garrison window.");
  1362. }
  1363. }
  1364. title = std::make_shared<CLabel>(275, 30, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleText);
  1365. banner = std::make_shared<CAnimImage>("CREST58", up->getOwner().getNum(), 0, 28, 124);
  1366. portrait = std::make_shared<CAnimImage>("PortraitsLarge", down->portrait, 0, 29, 222);
  1367. }
  1368. void CGarrisonWindow::updateGarrisons()
  1369. {
  1370. garr->recreateSlots();
  1371. }
  1372. CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectInstance * object)
  1373. : CStatusbarWindow(PLAYER_COLORED, "APHLFTBK"),
  1374. fort(object),
  1375. hero(visitor)
  1376. {
  1377. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1378. title = std::make_shared<CLabel>(325, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, fort->getObjectName());
  1379. heroPic = std::make_shared<CHeroArea>(30, 60, hero);
  1380. for(int i=0; i < resCount; i++)
  1381. {
  1382. totalIcons[i] = std::make_shared<CAnimImage>("SMALRES", i, 0, 104 + 76 * i, 237);
  1383. totalLabels[i] = std::make_shared<CLabel>(166 + 76 * i, 253, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  1384. }
  1385. for(int i = 0; i < slotsCount; i++)
  1386. {
  1387. upgrade[i] = std::make_shared<CButton>(Point(107 + i * 76, 171), "", CButton::tooltip(getTextForSlot(SlotID(i))), [=](){ makeDeal(SlotID(i)); }, SDLK_1 + i);
  1388. for(auto image : { "APHLF1R.DEF", "APHLF1Y.DEF", "APHLF1G.DEF" })
  1389. upgrade[i]->addImage(image);
  1390. for(int j : {0,1})
  1391. {
  1392. slotIcons[i][j] = std::make_shared<CAnimImage>("SMALRES", 0, 0, 104 + 76 * i, 128 + 20 * j);
  1393. slotLabels[i][j] = std::make_shared<CLabel>(168 + 76 * i, 144 + 20 * j, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  1394. }
  1395. }
  1396. upgradeAll = std::make_shared<CButton>(Point(30, 231), "", CButton::tooltip(CGI->generaltexth->allTexts[432]), [&](){ makeDeal(SlotID(slotsCount));}, SDLK_0);
  1397. for(auto image : { "APHLF4R.DEF", "APHLF4Y.DEF", "APHLF4G.DEF" })
  1398. upgradeAll->addImage(image);
  1399. quit = std::make_shared<CButton>(Point(294, 275), "IOKAY.DEF", CButton::tooltip(), std::bind(&CHillFortWindow::close, this), SDLK_RETURN);
  1400. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1401. garr = std::make_shared<CGarrisonInt>(108, 60, 18, Point(), hero, nullptr);
  1402. updateGarrisons();
  1403. }
  1404. void CHillFortWindow::updateGarrisons()
  1405. {
  1406. std::array<TResources, slotsCount> costs;// costs [slot ID] [resource ID] = resource count for upgrade
  1407. TResources totalSumm; // totalSum[resource ID] = value
  1408. totalSumm.resize(GameConstants::RESOURCE_QUANTITY);
  1409. for(int i=0; i<GameConstants::RESOURCE_QUANTITY; i++)
  1410. totalSumm[i]=0;
  1411. for(int i=0; i<slotsCount; i++)
  1412. {
  1413. costs[i].clear();
  1414. int newState = getState(SlotID(i));
  1415. if(newState != -1)
  1416. {
  1417. UpgradeInfo info;
  1418. LOCPLINT->cb->fillUpgradeInfo(hero, SlotID(i), info);
  1419. if(info.newID.size())//we have upgrades here - update costs
  1420. {
  1421. costs[i] = info.cost[0] * hero->getStackCount(SlotID(i));
  1422. totalSumm += costs[i];
  1423. }
  1424. }
  1425. currState[i] = newState;
  1426. upgrade[i]->setIndex(currState[i] == -1 ? 0 : currState[i]);
  1427. upgrade[i]->block(currState[i] == -1);
  1428. upgrade[i]->addHoverText(CButton::NORMAL, getTextForSlot(SlotID(i)));
  1429. }
  1430. //"Upgrade all" slot
  1431. int newState = 2;
  1432. {
  1433. TResources myRes = LOCPLINT->cb->getResourceAmount();
  1434. bool allUpgraded = true;//All creatures are upgraded?
  1435. for(int i=0; i<slotsCount; i++)
  1436. allUpgraded &= currState[i] == 1 || currState[i] == -1;
  1437. if(allUpgraded)
  1438. newState = 1;
  1439. if(!totalSumm.canBeAfforded(myRes))
  1440. newState = 0;
  1441. }
  1442. currState[slotsCount] = newState;
  1443. upgradeAll->setIndex(newState);
  1444. garr->recreateSlots();
  1445. for(int i = 0; i < slotsCount; i++)
  1446. {
  1447. //hide all first
  1448. for(int j : {0,1})
  1449. {
  1450. slotIcons[i][j]->visible = false;
  1451. slotLabels[i][j]->setText("");
  1452. }
  1453. //if can upgrade or can not afford, draw cost
  1454. if(currState[i] == 0 || currState[i] == 2)
  1455. {
  1456. if(costs[i].nonZero())
  1457. {
  1458. //reverse iterator is used to display gold as first element
  1459. int j = 0;
  1460. for(int res = (int)costs[i].size()-1; (res >= 0) && (j < 2); res--)
  1461. {
  1462. int val = costs[i][res];
  1463. if(!val)
  1464. continue;
  1465. slotIcons[i][j]->visible = true;
  1466. slotIcons[i][j]->setFrame(res);
  1467. slotLabels[i][j]->setText(boost::lexical_cast<std::string>(val));
  1468. j++;
  1469. }
  1470. }
  1471. else//free upgrade - print gold image and "Free" text
  1472. {
  1473. slotIcons[i][0]->visible = true;
  1474. slotIcons[i][0]->setFrame(Res::GOLD);
  1475. slotLabels[i][0]->setText(CGI->generaltexth->allTexts[344]);
  1476. }
  1477. }
  1478. }
  1479. for(int i = 0; i < resCount; i++)
  1480. {
  1481. if(totalSumm[i] == 0)
  1482. {
  1483. totalIcons[i]->visible = false;
  1484. totalLabels[i]->setText("");
  1485. }
  1486. else
  1487. {
  1488. totalIcons[i]->visible = true;
  1489. totalLabels[i]->setText(boost::lexical_cast<std::string>(totalSumm[i]));
  1490. }
  1491. }
  1492. }
  1493. void CHillFortWindow::makeDeal(SlotID slot)
  1494. {
  1495. assert(slot.getNum()>=0);
  1496. int offset = (slot.getNum() == slotsCount)?2:0;
  1497. switch(currState[slot.getNum()])
  1498. {
  1499. case 0:
  1500. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[314 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1501. break;
  1502. case 1:
  1503. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[313 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1504. break;
  1505. case 2:
  1506. for(int i=0; i<slotsCount; i++)
  1507. {
  1508. if(slot.getNum() ==i || ( slot.getNum() == slotsCount && currState[i] == 2 ))//this is activated slot or "upgrade all"
  1509. {
  1510. UpgradeInfo info;
  1511. LOCPLINT->cb->fillUpgradeInfo(hero, SlotID(i), info);
  1512. LOCPLINT->cb->upgradeCreature(hero, SlotID(i), info.newID[0]);
  1513. }
  1514. }
  1515. break;
  1516. }
  1517. }
  1518. std::string CHillFortWindow::getTextForSlot(SlotID slot)
  1519. {
  1520. if(!hero->getCreature(slot))//we don`t have creature here
  1521. return "";
  1522. std::string str = CGI->generaltexth->allTexts[318];
  1523. int amount = hero->getStackCount(slot);
  1524. if(amount == 1)
  1525. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNameSingularTranslated());
  1526. else
  1527. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNamePluralTranslated());
  1528. return str;
  1529. }
  1530. int CHillFortWindow::getState(SlotID slot)
  1531. {
  1532. TResources myRes = LOCPLINT->cb->getResourceAmount();
  1533. if(hero->slotEmpty(slot))//no creature here
  1534. return -1;
  1535. UpgradeInfo info;
  1536. LOCPLINT->cb->fillUpgradeInfo(hero, slot, info);
  1537. if(!info.newID.size())//already upgraded
  1538. return 1;
  1539. if(!(info.cost[0] * hero->getStackCount(slot)).canBeAfforded(myRes))
  1540. return 0;
  1541. return 2;//can upgrade
  1542. }
  1543. CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
  1544. CStatusbarWindow(PLAYER_COLORED | BORDERED, "TpRank"),
  1545. owner(_owner)
  1546. {
  1547. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1548. type |= BLOCK_ADV_HOTKEYS;
  1549. SThievesGuildInfo tgi; //info to be displayed
  1550. LOCPLINT->cb->getThievesGuildInfo(tgi, owner);
  1551. exitb = std::make_shared<CButton>(Point(748, 556), "TPMAGE1", CButton::tooltip(CGI->generaltexth->allTexts[600]), [&](){ close();}, SDLK_RETURN);
  1552. exitb->assignedKeys.insert(SDLK_ESCAPE);
  1553. statusbar = CGStatusBar::create(3, 555, "TStatBar.bmp", 742);
  1554. resdatabar = std::make_shared<CMinorResDataBar>();
  1555. resdatabar->moveBy(pos.topLeft(), true);
  1556. //data for information table:
  1557. // fields[row][column] = list of id's of players for this box
  1558. static std::vector< std::vector< PlayerColor > > SThievesGuildInfo::* fields[] =
  1559. { &SThievesGuildInfo::numOfTowns, &SThievesGuildInfo::numOfHeroes, &SThievesGuildInfo::gold,
  1560. &SThievesGuildInfo::woodOre, &SThievesGuildInfo::mercSulfCrystGems, &SThievesGuildInfo::obelisks,
  1561. &SThievesGuildInfo::artifacts, &SThievesGuildInfo::army, &SThievesGuildInfo::income };
  1562. for(int g=0; g<12; ++g)
  1563. {
  1564. int posY[] = {400, 460, 510};
  1565. int y;
  1566. if(g < 9)
  1567. y = 52 + 32*g;
  1568. else
  1569. y = posY[g-9];
  1570. std::string text = CGI->generaltexth->jktexts[24+g];
  1571. boost::algorithm::trim_if(text,boost::algorithm::is_any_of("\""));
  1572. rowHeaders.push_back(std::make_shared<CLabel>(135, y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, text));
  1573. }
  1574. auto PRSTRIPS = std::make_shared<CAnimation>("PRSTRIPS");
  1575. PRSTRIPS->preload();
  1576. for(int g=1; g<tgi.playerColors.size(); ++g)
  1577. columnBackgrounds.push_back(std::make_shared<CAnimImage>(PRSTRIPS, g-1, 0, 250 + 66*g, 7));
  1578. for(int g=0; g<tgi.playerColors.size(); ++g)
  1579. columnHeaders.push_back(std::make_shared<CLabel>(283 + 66*g, 24, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[16+g]));
  1580. auto itgflags = std::make_shared<CAnimation>("itgflags");
  1581. itgflags->preload();
  1582. //printing flags
  1583. for(int g = 0; g < ARRAY_COUNT(fields); ++g) //by lines
  1584. {
  1585. for(int b=0; b<(tgi .* fields[g]).size(); ++b) //by places (1st, 2nd, ...)
  1586. {
  1587. std::vector<PlayerColor> &players = (tgi .* fields[g])[b]; //get players with this place in this line
  1588. //position of box
  1589. int xpos = 259 + 66 * b;
  1590. int ypos = 41 + 32 * g;
  1591. size_t rowLength[2]; //size of each row
  1592. rowLength[0] = std::min<size_t>(players.size(), 4);
  1593. rowLength[1] = players.size() - rowLength[0];
  1594. for(size_t j=0; j < 2; j++)
  1595. {
  1596. // origin of this row | offset for 2nd row| shift right for short rows
  1597. //if we have 2 rows, start either from mid or beginning (depending on count), otherwise center the flags
  1598. int rowStartX = xpos + (j ? 6 + ((int)rowLength[j] < 3 ? 12 : 0) : 24 - 6 * (int)rowLength[j]);
  1599. int rowStartY = ypos + (j ? 4 : 0);
  1600. for(size_t i=0; i < rowLength[j]; i++)
  1601. cells.push_back(std::make_shared<CAnimImage>(itgflags, players[i + j*4].getNum(), 0, rowStartX + (int)i*12, rowStartY));
  1602. }
  1603. }
  1604. }
  1605. static const std::string colorToBox[] = {"PRRED.BMP", "PRBLUE.BMP", "PRTAN.BMP", "PRGREEN.BMP", "PRORANGE.BMP", "PRPURPLE.BMP", "PRTEAL.BMP", "PRROSE.bmp"};
  1606. //printing best hero
  1607. int counter = 0;
  1608. for(auto & iter : tgi.colorToBestHero)
  1609. {
  1610. banners.push_back(std::make_shared<CPicture>(colorToBox[iter.first.getNum()], 253 + 66 * counter, 334));
  1611. if(iter.second.portrait >= 0)
  1612. {
  1613. bestHeroes.push_back(std::make_shared<CAnimImage>("PortraitsSmall", iter.second.portrait, 0, 260 + 66 * counter, 360));
  1614. //TODO: r-click info:
  1615. // - r-click on hero
  1616. // - r-click on primary skill label
  1617. if(iter.second.details)
  1618. {
  1619. primSkillHeaders.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[184], Rect(260 + 66*counter, 396, 52, 64),
  1620. 0, FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE));
  1621. for(int i=0; i<iter.second.details->primskills.size(); ++i)
  1622. {
  1623. primSkillValues.push_back(std::make_shared<CLabel>(310 + 66 * counter, 407 + 11*i, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE,
  1624. boost::lexical_cast<std::string>(iter.second.details->primskills[i])));
  1625. }
  1626. }
  1627. }
  1628. counter++;
  1629. }
  1630. //printing best creature
  1631. counter = 0;
  1632. for(auto & it : tgi.bestCreature)
  1633. {
  1634. if(it.second >= 0)
  1635. bestCreatures.push_back(std::make_shared<CAnimImage>("TWCRPORT", it.second+2, 0, 255 + 66 * counter, 479));
  1636. counter++;
  1637. }
  1638. //printing personality
  1639. counter = 0;
  1640. for(auto & it : tgi.personality)
  1641. {
  1642. std::string text;
  1643. if(it.second == EAiTactic::NONE)
  1644. {
  1645. text = CGI->generaltexth->arraytxt[172];
  1646. }
  1647. else if(it.second != EAiTactic::RANDOM)
  1648. {
  1649. text = CGI->generaltexth->arraytxt[168 + it.second];
  1650. }
  1651. personalities.push_back(std::make_shared<CLabel>(283 + 66*counter, 459, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, text));
  1652. counter++;
  1653. }
  1654. }
  1655. CObjectListWindow::CItem::CItem(CObjectListWindow * _parent, size_t _id, std::string _text)
  1656. : CIntObject(LCLICK | DOUBLECLICK),
  1657. parent(_parent),
  1658. index(_id)
  1659. {
  1660. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1661. border = std::make_shared<CPicture>("TPGATES");
  1662. pos = border->pos;
  1663. type |= REDRAW_PARENT;
  1664. text = std::make_shared<CLabel>(pos.w/2, pos.h/2, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _text);
  1665. select(index == parent->selected);
  1666. }
  1667. void CObjectListWindow::CItem::select(bool on)
  1668. {
  1669. ui8 mask = UPDATE | SHOWALL;
  1670. if(on)
  1671. border->recActions |= mask;
  1672. else
  1673. border->recActions &= ~mask;
  1674. redraw();//???
  1675. }
  1676. void CObjectListWindow::CItem::clickLeft(tribool down, bool previousState)
  1677. {
  1678. if( previousState && !down)
  1679. parent->changeSelection(index);
  1680. }
  1681. void CObjectListWindow::CItem::onDoubleClick()
  1682. {
  1683. parent->elementSelected();
  1684. }
  1685. 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)
  1686. : CWindowObject(PLAYER_COLORED, "TPGATE"),
  1687. onSelect(Callback),
  1688. selected(initialSelection)
  1689. {
  1690. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1691. items.reserve(_items.size());
  1692. for(int id : _items)
  1693. {
  1694. items.push_back(std::make_pair(id, CGI->mh->map->objects[id]->getObjectName()));
  1695. }
  1696. init(titleWidget_, _title, _descr);
  1697. }
  1698. 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)
  1699. : CWindowObject(PLAYER_COLORED, "TPGATE"),
  1700. onSelect(Callback),
  1701. selected(initialSelection)
  1702. {
  1703. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1704. items.reserve(_items.size());
  1705. for(size_t i=0; i<_items.size(); i++)
  1706. items.push_back(std::make_pair(int(i), _items[i]));
  1707. init(titleWidget_, _title, _descr);
  1708. }
  1709. void CObjectListWindow::init(std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr)
  1710. {
  1711. titleWidget = titleWidget_;
  1712. title = std::make_shared<CLabel>(152, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, _title);
  1713. descr = std::make_shared<CLabel>(145, 133, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _descr);
  1714. exit = std::make_shared<CButton>( Point(228, 402), "ICANCEL.DEF", CButton::tooltip(), std::bind(&CObjectListWindow::exitPressed, this), SDLK_ESCAPE);
  1715. if(titleWidget)
  1716. {
  1717. addChild(titleWidget.get());
  1718. titleWidget->recActions = 255-DISPOSE;
  1719. titleWidget->pos.x = pos.w/2 + pos.x - titleWidget->pos.w/2;
  1720. titleWidget->pos.y =75 + pos.y - titleWidget->pos.h/2;
  1721. }
  1722. list = std::make_shared<CListBox>(std::bind(&CObjectListWindow::genItem, this, _1),
  1723. Point(14, 151), Point(0, 25), 9, items.size(), 0, 1, Rect(262, -32, 256, 256) );
  1724. list->type |= REDRAW_PARENT;
  1725. ok = std::make_shared<CButton>(Point(15, 402), "IOKAY.DEF", CButton::tooltip(), std::bind(&CObjectListWindow::elementSelected, this), SDLK_RETURN);
  1726. ok->block(!list->size());
  1727. }
  1728. std::shared_ptr<CIntObject> CObjectListWindow::genItem(size_t index)
  1729. {
  1730. if(index < items.size())
  1731. return std::make_shared<CItem>(this, index, items[index].second);
  1732. return std::shared_ptr<CIntObject>();
  1733. }
  1734. void CObjectListWindow::elementSelected()
  1735. {
  1736. std::function<void(int)> toCall = onSelect;//save
  1737. int where = items[selected].first; //required variables
  1738. close();//then destroy window
  1739. toCall(where);//and send selected object
  1740. }
  1741. void CObjectListWindow::exitPressed()
  1742. {
  1743. std::function<void()> toCall = onExit;//save
  1744. close();//then destroy window
  1745. if(toCall)
  1746. toCall();
  1747. }
  1748. void CObjectListWindow::changeSelection(size_t which)
  1749. {
  1750. ok->block(false);
  1751. if(selected == which)
  1752. return;
  1753. for(std::shared_ptr<CIntObject> element : list->getItems())
  1754. {
  1755. CItem * item = dynamic_cast<CItem*>(element.get());
  1756. if(item)
  1757. {
  1758. if(item->index == selected)
  1759. item->select(false);
  1760. if(item->index == which)
  1761. item->select(true);
  1762. }
  1763. }
  1764. selected = which;
  1765. }
  1766. void CObjectListWindow::keyPressed (const SDL_Keycode & key)
  1767. {
  1768. int sel = static_cast<int>(selected);
  1769. switch(key)
  1770. {
  1771. break; case SDLK_UP:
  1772. sel -=1;
  1773. break; case SDLK_DOWN:
  1774. sel +=1;
  1775. break; case SDLK_PAGEUP:
  1776. sel -=9;
  1777. break; case SDLK_PAGEDOWN:
  1778. sel +=9;
  1779. break; case SDLK_HOME:
  1780. sel = 0;
  1781. break; case SDLK_END:
  1782. sel = static_cast<int>(items.size());
  1783. break; default:
  1784. return;
  1785. }
  1786. vstd::abetween(sel, 0, items.size()-1);
  1787. list->scrollTo(sel);
  1788. changeSelection(sel);
  1789. }