CCastleInterface.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  1. /*
  2. * CCastleInterface.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 "CCastleInterface.h"
  12. #include "CHeroWindow.h"
  13. #include "CTradeWindow.h"
  14. #include "InfoWindows.h"
  15. #include "GUIClasses.h"
  16. #include "QuickRecruitmentWindow.h"
  17. #include "CCreatureWindow.h"
  18. #include "../CGameInfo.h"
  19. #include "../CMusicHandler.h"
  20. #include "../CPlayerInterface.h"
  21. #include "../PlayerLocalState.h"
  22. #include "../gui/CGuiHandler.h"
  23. #include "../gui/Shortcut.h"
  24. #include "../gui/WindowHandler.h"
  25. #include "../widgets/MiscWidgets.h"
  26. #include "../widgets/CComponent.h"
  27. #include "../widgets/CGarrisonInt.h"
  28. #include "../widgets/Buttons.h"
  29. #include "../widgets/TextControls.h"
  30. #include "../widgets/RadialMenu.h"
  31. #include "../widgets/CExchangeController.h"
  32. #include "../render/Canvas.h"
  33. #include "../render/IImage.h"
  34. #include "../render/IRenderHandler.h"
  35. #include "../render/ColorFilter.h"
  36. #include "../adventureMap/AdventureMapInterface.h"
  37. #include "../adventureMap/CList.h"
  38. #include "../adventureMap/CResDataBar.h"
  39. #include "../../CCallback.h"
  40. #include "../../lib/CArtHandler.h"
  41. #include "../../lib/CBuildingHandler.h"
  42. #include "../../lib/CCreatureHandler.h"
  43. #include "../../lib/CGeneralTextHandler.h"
  44. #include "../../lib/GameSettings.h"
  45. #include "../../lib/spells/CSpellHandler.h"
  46. #include "../../lib/CTownHandler.h"
  47. #include "../../lib/GameConstants.h"
  48. #include "../../lib/StartInfo.h"
  49. #include "../../lib/campaign/CampaignState.h"
  50. #include "../../lib/mapObjects/CGHeroInstance.h"
  51. #include "../../lib/mapObjects/CGTownInstance.h"
  52. static bool useCompactCreatureBox()
  53. {
  54. return settings["gameTweaks"]["compactTownCreatureInfo"].Bool();
  55. }
  56. static bool useAvailableAmountAsCreatureLabel()
  57. {
  58. return settings["gameTweaks"]["availableCreaturesAsDwellingLabel"].Bool();
  59. }
  60. CBuildingRect::CBuildingRect(CCastleBuildings * Par, const CGTownInstance * Town, const CStructure * Str)
  61. : CShowableAnim(0, 0, Str->defName, CShowableAnim::BASE, BUILDING_FRAME_TIME),
  62. parent(Par),
  63. town(Town),
  64. str(Str),
  65. border(nullptr),
  66. area(nullptr),
  67. stateTimeCounter(BUILD_ANIMATION_FINISHED_TIMEPOINT)
  68. {
  69. addUsedEvents(LCLICK | SHOW_POPUP | MOVE | HOVER | TIME);
  70. pos.x += str->pos.x;
  71. pos.y += str->pos.y;
  72. // special animation frame manipulation for castle shipyard with and without ship
  73. // done due to .def used in special way, not to animate building - first image is for shipyard without citadel moat, 2nd image is for including moat
  74. if(Town->town->faction->getId() == FactionID::CASTLE && Str->building &&
  75. (Str->building->bid == BuildingID::SHIPYARD || Str->building->bid == BuildingID::SHIP))
  76. {
  77. if(Town->hasBuilt(BuildingID::CITADEL))
  78. {
  79. this->first = 1;
  80. this->frame = 1;
  81. }
  82. else
  83. this->last = 0;
  84. }
  85. if(!str->borderName.empty())
  86. border = GH.renderHandler().loadImage(str->borderName, EImageBlitMode::ALPHA);
  87. if(!str->areaName.empty())
  88. area = GH.renderHandler().loadImage(str->areaName, EImageBlitMode::ALPHA);
  89. }
  90. const CBuilding * CBuildingRect::getBuilding()
  91. {
  92. if (!str->building)
  93. return nullptr;
  94. if (str->hiddenUpgrade) // hidden upgrades, e.g. hordes - return base (dwelling for hordes)
  95. return town->town->buildings.at(str->building->getBase());
  96. return str->building;
  97. }
  98. bool CBuildingRect::operator<(const CBuildingRect & p2) const
  99. {
  100. return (str->pos.z) < (p2.str->pos.z);
  101. }
  102. void CBuildingRect::hover(bool on)
  103. {
  104. if (!area)
  105. return;
  106. if(on)
  107. {
  108. if(! parent->selectedBuilding //no building hovered
  109. || (*parent->selectedBuilding)<(*this)) //or we are on top
  110. {
  111. parent->selectedBuilding = this;
  112. GH.statusbar()->write(getSubtitle());
  113. }
  114. }
  115. else
  116. {
  117. if(parent->selectedBuilding == this)
  118. {
  119. parent->selectedBuilding = nullptr;
  120. GH.statusbar()->clear();
  121. }
  122. }
  123. }
  124. void CBuildingRect::clickPressed(const Point & cursorPosition)
  125. {
  126. if(getBuilding() && area && (parent->selectedBuilding==this))
  127. {
  128. auto building = getBuilding();
  129. parent->buildingClicked(building->bid, building->subId, building->upgrade);
  130. }
  131. }
  132. void CBuildingRect::showPopupWindow(const Point & cursorPosition)
  133. {
  134. if((!area) || (this!=parent->selectedBuilding) || getBuilding() == nullptr)
  135. return;
  136. BuildingID bid = getBuilding()->bid;
  137. const CBuilding *bld = town->town->buildings.at(bid);
  138. if (bid < BuildingID::DWELL_FIRST)
  139. {
  140. CRClickPopup::createAndPush(CInfoWindow::genText(bld->getNameTranslated(), bld->getDescriptionTranslated()),
  141. std::make_shared<CComponent>(CComponent::building, bld->town->faction->getIndex(), bld->bid));
  142. }
  143. else
  144. {
  145. int level = ( bid - BuildingID::DWELL_FIRST ) % GameConstants::CREATURES_PER_TOWN;
  146. GH.windows().createAndPushWindow<CDwellingInfoBox>(parent->pos.x+parent->pos.w / 2, parent->pos.y+parent->pos.h /2, town, level);
  147. }
  148. }
  149. void CBuildingRect::show(Canvas & to)
  150. {
  151. uint32_t stageDelay = BUILDING_APPEAR_TIMEPOINT;
  152. if(stateTimeCounter < BUILDING_APPEAR_TIMEPOINT)
  153. {
  154. setAlpha(255 * stateTimeCounter / stageDelay);
  155. CShowableAnim::show(to);
  156. }
  157. else
  158. {
  159. setAlpha(255);
  160. CShowableAnim::show(to);
  161. }
  162. if(border && stateTimeCounter > BUILDING_APPEAR_TIMEPOINT)
  163. {
  164. if(stateTimeCounter >= BUILD_ANIMATION_FINISHED_TIMEPOINT)
  165. {
  166. if(parent->selectedBuilding == this)
  167. to.draw(border, pos.topLeft());
  168. return;
  169. }
  170. auto darkBorder = ColorFilter::genRangeShifter(0.f, 0.f, 0.f, 0.5f, 0.5f, 0.5f );
  171. auto lightBorder = ColorFilter::genRangeShifter(0.f, 0.f, 0.f, 2.0f, 2.0f, 2.0f );
  172. auto baseBorder = ColorFilter::genEmptyShifter();
  173. float progress = float(stateTimeCounter % stageDelay) / stageDelay;
  174. if (stateTimeCounter < BUILDING_WHITE_BORDER_TIMEPOINT)
  175. border->adjustPalette(ColorFilter::genInterpolated(lightBorder, darkBorder, progress), 0);
  176. else
  177. if (stateTimeCounter < BUILDING_YELLOW_BORDER_TIMEPOINT)
  178. border->adjustPalette(ColorFilter::genInterpolated(darkBorder, baseBorder, progress), 0);
  179. else
  180. border->adjustPalette(baseBorder, 0);
  181. to.draw(border, pos.topLeft());
  182. }
  183. }
  184. void CBuildingRect::tick(uint32_t msPassed)
  185. {
  186. CShowableAnim::tick(msPassed);
  187. stateTimeCounter += msPassed;
  188. }
  189. void CBuildingRect::showAll(Canvas & to)
  190. {
  191. if (stateTimeCounter == 0)
  192. return;
  193. CShowableAnim::showAll(to);
  194. if(!isActive() && parent->selectedBuilding == this && border)
  195. to.draw(border, pos.topLeft());
  196. }
  197. std::string CBuildingRect::getSubtitle()//hover text for building
  198. {
  199. if (!getBuilding())
  200. return "";
  201. int bid = getBuilding()->bid;
  202. if (bid<30)//non-dwellings - only buiding name
  203. return town->town->buildings.at(getBuilding()->bid)->getNameTranslated();
  204. else//dwellings - recruit %creature%
  205. {
  206. auto & availableCreatures = town->creatures[(bid-30)%GameConstants::CREATURES_PER_TOWN].second;
  207. if(availableCreatures.size())
  208. {
  209. int creaID = availableCreatures.back();//taking last of available creatures
  210. return CGI->generaltexth->allTexts[16] + " " + CGI->creh->objects.at(creaID)->getNamePluralTranslated();
  211. }
  212. else
  213. {
  214. logGlobal->warn("Dwelling with id %d offers no creatures!", bid);
  215. return "#ERROR#";
  216. }
  217. }
  218. }
  219. void CBuildingRect::mouseMoved (const Point & cursorPosition, const Point & lastUpdateDistance)
  220. {
  221. hover(true);
  222. }
  223. bool CBuildingRect::receiveEvent(const Point & position, int eventType) const
  224. {
  225. if (!pos.isInside(position.x, position.y))
  226. return false;
  227. if(area && area->isTransparent(position - pos.topLeft()))
  228. return false;
  229. return CIntObject::receiveEvent(position, eventType);
  230. }
  231. CDwellingInfoBox::CDwellingInfoBox(int centerX, int centerY, const CGTownInstance * Town, int level)
  232. : CWindowObject(RCLICK_POPUP, ImagePath::builtin("CRTOINFO"), Point(centerX, centerY))
  233. {
  234. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  235. background->colorize(Town->tempOwner);
  236. const CCreature * creature = CGI->creh->objects.at(Town->creatures.at(level).second.back());
  237. title = std::make_shared<CLabel>(80, 30, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, creature->getNamePluralTranslated());
  238. animation = std::make_shared<CCreaturePic>(30, 44, creature, true, true);
  239. std::string text = std::to_string(Town->creatures.at(level).first);
  240. available = std::make_shared<CLabel>(80,190, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[217] + text);
  241. costPerTroop = std::make_shared<CLabel>(80, 227, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[346]);
  242. for(int i = 0; i<GameConstants::RESOURCE_QUANTITY; i++)
  243. {
  244. auto res = static_cast<EGameResID>(i);
  245. if(creature->getRecruitCost(res))
  246. {
  247. resPicture.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), i, 0, 0, 0));
  248. resAmount.push_back(std::make_shared<CLabel>(0,0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(creature->getRecruitCost(res))));
  249. }
  250. }
  251. int posY = 238;
  252. int posX = pos.w/2 - (int)resAmount.size() * 25 + 5;
  253. for (size_t i=0; i<resAmount.size(); i++)
  254. {
  255. resPicture[i]->moveBy(Point(posX, posY));
  256. resAmount[i]->moveBy(Point(posX+16, posY+43));
  257. posX += 50;
  258. }
  259. }
  260. CDwellingInfoBox::~CDwellingInfoBox() = default;
  261. CHeroGSlot::CHeroGSlot(int x, int y, int updown, const CGHeroInstance * h, HeroSlots * Owner)
  262. {
  263. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  264. owner = Owner;
  265. pos.x += x;
  266. pos.y += y;
  267. pos.w = 58;
  268. pos.h = 64;
  269. upg = updown;
  270. portrait = std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), 0, 0, 0, 0);
  271. portrait->visible = false;
  272. flag = std::make_shared<CAnimImage>(AnimationPath::builtin("CREST58"), 0, 0, 0, 0);
  273. flag->visible = false;
  274. selection = std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), 1, 0);
  275. selection->visible = false;
  276. set(h);
  277. addUsedEvents(LCLICK | SHOW_POPUP | GESTURE | HOVER);
  278. }
  279. CHeroGSlot::~CHeroGSlot() = default;
  280. void CHeroGSlot::gesture(bool on, const Point & initialPosition, const Point & finalPosition)
  281. {
  282. if(!on)
  283. return;
  284. if(!hero)
  285. return;
  286. if (!settings["input"]["radialWheelGarrisonSwipe"].Bool())
  287. return;
  288. std::shared_ptr<CHeroGSlot> other = upg ? owner->garrisonedHero : owner->visitingHero;
  289. bool twoHeroes = hero && other->hero;
  290. ObjectInstanceID heroId = hero->id;
  291. ObjectInstanceID heroOtherId = twoHeroes ? other->hero->id : ObjectInstanceID::NONE;
  292. std::vector<RadialMenuConfig> menuElements = {
  293. { RadialMenuConfig::ITEM_NW, twoHeroes, "stackMerge", "vcmi.radialWheel.heroGetArmy", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).moveArmy(false, std::nullopt);} },
  294. { RadialMenuConfig::ITEM_NE, twoHeroes, "stackSplitDialog", "vcmi.radialWheel.heroSwapArmy", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).swapArmy();} },
  295. { RadialMenuConfig::ITEM_EE, twoHeroes, "trade", "vcmi.radialWheel.heroExchange", [heroId, heroOtherId](){LOCPLINT->showHeroExchange(heroId, heroOtherId);} },
  296. { RadialMenuConfig::ITEM_SW, twoHeroes, "getArtifacts", "vcmi.radialWheel.heroGetArtifacts", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).moveArtifacts(false, true, true);} },
  297. { RadialMenuConfig::ITEM_SE, twoHeroes, "swapArtifacts", "vcmi.radialWheel.heroSwapArtifacts", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).swapArtifacts(true, true);} },
  298. { RadialMenuConfig::ITEM_WW, true, "remove", "vcmi.radialWheel.heroDismiss", [this]()
  299. {
  300. CFunctionList<void()> ony = [=](){ };
  301. ony += [=](){ LOCPLINT->cb->dismissHero(hero); };
  302. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[22], ony, nullptr);
  303. } },
  304. };
  305. GH.windows().createAndPushWindow<RadialMenu>(pos.center(), menuElements);
  306. }
  307. void CHeroGSlot::hover(bool on)
  308. {
  309. if(!on)
  310. {
  311. GH.statusbar()->clear();
  312. return;
  313. }
  314. std::shared_ptr<CHeroGSlot> other = upg ? owner->garrisonedHero : owner->visitingHero;
  315. std::string temp;
  316. if(hero)
  317. {
  318. if(isSelected())//view NNN
  319. {
  320. temp = CGI->generaltexth->tcommands[4];
  321. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  322. }
  323. else if(other->hero && other->isSelected())//exchange
  324. {
  325. temp = CGI->generaltexth->tcommands[7];
  326. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  327. boost::algorithm::replace_first(temp,"%s",other->hero->getNameTranslated());
  328. }
  329. else// select NNN (in ZZZ)
  330. {
  331. if(upg)//down - visiting
  332. {
  333. temp = CGI->generaltexth->tcommands[32];
  334. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  335. }
  336. else //up - garrison
  337. {
  338. temp = CGI->generaltexth->tcommands[12];
  339. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  340. }
  341. }
  342. }
  343. else //we are empty slot
  344. {
  345. if(other->isSelected() && other->hero) //move NNNN
  346. {
  347. temp = CGI->generaltexth->tcommands[6];
  348. boost::algorithm::replace_first(temp,"%s",other->hero->getNameTranslated());
  349. }
  350. else //empty
  351. {
  352. temp = CGI->generaltexth->allTexts[507];
  353. }
  354. }
  355. if(temp.size())
  356. GH.statusbar()->write(temp);
  357. }
  358. void CHeroGSlot::clickPressed(const Point & cursorPosition)
  359. {
  360. std::shared_ptr<CHeroGSlot> other = upg ? owner->garrisonedHero : owner->visitingHero;
  361. owner->garr->setSplittingMode(false);
  362. owner->garr->selectSlot(nullptr);
  363. if(hero && isSelected())
  364. {
  365. setHighlight(false);
  366. LOCPLINT->openHeroWindow(hero);
  367. }
  368. else if(other->hero && other->isSelected())
  369. {
  370. owner->swapArmies();
  371. }
  372. else if(hero)
  373. {
  374. setHighlight(true);
  375. owner->garr->selectSlot(nullptr);
  376. redraw();
  377. }
  378. //refresh statusbar
  379. hover(false);
  380. hover(true);
  381. }
  382. void CHeroGSlot::showPopupWindow(const Point & cursorPosition)
  383. {
  384. if(hero)
  385. {
  386. GH.windows().createAndPushWindow<CInfoBoxPopup>(Point(pos.x + 175, pos.y + 100), hero);
  387. }
  388. }
  389. void CHeroGSlot::deactivate()
  390. {
  391. selection->visible = false;
  392. CIntObject::deactivate();
  393. }
  394. bool CHeroGSlot::isSelected() const
  395. {
  396. return selection->visible;
  397. }
  398. void CHeroGSlot::setHighlight(bool on)
  399. {
  400. selection->visible = on;
  401. if(owner->garrisonedHero->hero && owner->visitingHero->hero) //two heroes in town
  402. {
  403. for(auto & elem : owner->garr->splitButtons) //splitting enabled when slot higlighted
  404. elem->block(!on);
  405. }
  406. }
  407. void CHeroGSlot::set(const CGHeroInstance * newHero)
  408. {
  409. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  410. hero = newHero;
  411. selection->visible = false;
  412. portrait->visible = false;
  413. flag->visible = false;
  414. if(newHero)
  415. {
  416. portrait->visible = true;
  417. portrait->setFrame(newHero->getIconIndex());
  418. }
  419. else if(!upg && owner->showEmpty) //up garrison
  420. {
  421. flag->visible = true;
  422. flag->setFrame(LOCPLINT->castleInt->town->getOwner().getNum());
  423. }
  424. }
  425. HeroSlots::HeroSlots(const CGTownInstance * Town, Point garrPos, Point visitPos, std::shared_ptr<CGarrisonInt> Garrison, bool ShowEmpty):
  426. showEmpty(ShowEmpty),
  427. town(Town),
  428. garr(Garrison)
  429. {
  430. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  431. garrisonedHero = std::make_shared<CHeroGSlot>(garrPos.x, garrPos.y, 0, town->garrisonHero, this);
  432. visitingHero = std::make_shared<CHeroGSlot>(visitPos.x, visitPos.y, 1, town->visitingHero, this);
  433. }
  434. HeroSlots::~HeroSlots() = default;
  435. void HeroSlots::update()
  436. {
  437. garrisonedHero->set(town->garrisonHero);
  438. visitingHero->set(town->visitingHero);
  439. }
  440. void HeroSlots::splitClicked()
  441. {
  442. if(!!town->visitingHero && town->garrisonHero && (visitingHero->isSelected() || garrisonedHero->isSelected()))
  443. {
  444. LOCPLINT->showHeroExchange(town->visitingHero->id, town->garrisonHero->id);
  445. }
  446. }
  447. void HeroSlots::swapArmies()
  448. {
  449. bool allow = true;
  450. //moving hero out of town - check if it is allowed
  451. if (town->garrisonHero)
  452. {
  453. if (!town->visitingHero && LOCPLINT->cb->howManyHeroes(false) >= CGI->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  454. {
  455. std::string text = CGI->generaltexth->translate("core.genrltxt.18"); //You already have %d adventuring heroes under your command.
  456. boost::algorithm::replace_first(text,"%d",std::to_string(LOCPLINT->cb->howManyHeroes(false)));
  457. LOCPLINT->showInfoDialog(text, std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  458. allow = false;
  459. }
  460. else if (town->garrisonHero->stacksCount() == 0)
  461. {
  462. //This hero has no creatures. A hero must have creatures before he can brave the dangers of the countryside.
  463. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("core.genrltxt.19"), {}, soundBase::sound_todo);
  464. allow = false;
  465. }
  466. }
  467. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  468. {
  469. if(!town->visitingHero->canBeMergedWith(*town))
  470. {
  471. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[275], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  472. allow = false;
  473. }
  474. }
  475. garrisonedHero->setHighlight(false);
  476. visitingHero->setHighlight(false);
  477. if (allow)
  478. LOCPLINT->cb->swapGarrisonHero(town);
  479. }
  480. class SORTHELP
  481. {
  482. public:
  483. bool operator() (const CIntObject * a, const CIntObject * b)
  484. {
  485. auto b1 = dynamic_cast<const CBuildingRect *>(a);
  486. auto b2 = dynamic_cast<const CBuildingRect *>(b);
  487. if(!b1 && !b2)
  488. return intptr_t(a) < intptr_t(b);
  489. if(b1 && !b2)
  490. return false;
  491. if(!b1 && b2)
  492. return true;
  493. return (*b1)<(*b2);
  494. }
  495. };
  496. SORTHELP buildSorter;
  497. CCastleBuildings::CCastleBuildings(const CGTownInstance* Town):
  498. town(Town),
  499. selectedBuilding(nullptr)
  500. {
  501. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  502. background = std::make_shared<CPicture>(town->town->clientInfo.townBackground);
  503. background->needRefresh = true;
  504. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  505. pos.w = background->pos.w;
  506. pos.h = background->pos.h;
  507. recreate();
  508. }
  509. CCastleBuildings::~CCastleBuildings() = default;
  510. void CCastleBuildings::recreate()
  511. {
  512. selectedBuilding = nullptr;
  513. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  514. buildings.clear();
  515. groups.clear();
  516. //Generate buildings list
  517. auto buildingsCopy = town->builtBuildings;// a bit modified copy of built buildings
  518. if(vstd::contains(town->builtBuildings, BuildingID::SHIPYARD))
  519. {
  520. auto bayPos = town->bestLocation();
  521. if(!bayPos.valid())
  522. logGlobal->warn("Shipyard in non-coastal town!");
  523. std::vector <const CGObjectInstance *> vobjs = LOCPLINT->cb->getVisitableObjs(bayPos, false);
  524. //there is visitable obj at shipyard output tile and it's a boat or hero (on boat)
  525. if(!vobjs.empty() && (vobjs.front()->ID == Obj::BOAT || vobjs.front()->ID == Obj::HERO))
  526. {
  527. buildingsCopy.insert(BuildingID::SHIP);
  528. }
  529. }
  530. for(const CStructure * structure : town->town->clientInfo.structures)
  531. {
  532. if(!structure->building)
  533. {
  534. buildings.push_back(std::make_shared<CBuildingRect>(this, town, structure));
  535. continue;
  536. }
  537. if(vstd::contains(buildingsCopy, structure->building->bid))
  538. {
  539. groups[structure->building->getBase()].push_back(structure);
  540. }
  541. }
  542. for(auto & entry : groups)
  543. {
  544. const CBuilding * build = town->town->buildings.at(entry.first);
  545. const CStructure * toAdd = *boost::max_element(entry.second, [=](const CStructure * a, const CStructure * b)
  546. {
  547. return build->getDistance(a->building->bid) < build->getDistance(b->building->bid);
  548. });
  549. buildings.push_back(std::make_shared<CBuildingRect>(this, town, toAdd));
  550. }
  551. boost::sort(children, buildSorter); //TODO: create building in blit order
  552. }
  553. void CCastleBuildings::addBuilding(BuildingID building)
  554. {
  555. //FIXME: implement faster method without complete recreation of town
  556. BuildingID base = town->town->buildings.at(building)->getBase();
  557. recreate();
  558. auto & structures = groups.at(base);
  559. for(auto buildingRect : buildings)
  560. {
  561. if(vstd::contains(structures, buildingRect->str))
  562. {
  563. //reset animation
  564. if(structures.size() == 1)
  565. buildingRect->stateTimeCounter = 0; // transparency -> fully visible stage
  566. else
  567. buildingRect->stateTimeCounter = CBuildingRect::BUILDING_APPEAR_TIMEPOINT; // already in fully visible stage
  568. break;
  569. }
  570. }
  571. }
  572. void CCastleBuildings::removeBuilding(BuildingID building)
  573. {
  574. //FIXME: implement faster method without complete recreation of town
  575. recreate();
  576. }
  577. const CGHeroInstance * CCastleBuildings::getHero()
  578. {
  579. if(town->visitingHero)
  580. return town->visitingHero;
  581. else
  582. return town->garrisonHero;
  583. }
  584. void CCastleBuildings::buildingClicked(BuildingID building, BuildingSubID::EBuildingSubID subID, BuildingID upgrades)
  585. {
  586. logGlobal->trace("You've clicked on %d", (int)building.toEnum());
  587. const CBuilding *b = town->town->buildings.find(building)->second;
  588. if(building >= BuildingID::DWELL_FIRST)
  589. {
  590. enterDwelling((building-BuildingID::DWELL_FIRST)%GameConstants::CREATURES_PER_TOWN);
  591. }
  592. else
  593. {
  594. switch(building)
  595. {
  596. case BuildingID::MAGES_GUILD_1:
  597. case BuildingID::MAGES_GUILD_2:
  598. case BuildingID::MAGES_GUILD_3:
  599. case BuildingID::MAGES_GUILD_4:
  600. case BuildingID::MAGES_GUILD_5:
  601. enterMagesGuild();
  602. break;
  603. case BuildingID::TAVERN:
  604. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  605. break;
  606. case BuildingID::SHIPYARD:
  607. if(town->shipyardStatus() == IBoatGenerator::GOOD)
  608. LOCPLINT->showShipyardDialog(town);
  609. else if(town->shipyardStatus() == IBoatGenerator::BOAT_ALREADY_BUILT)
  610. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]);
  611. break;
  612. case BuildingID::FORT:
  613. case BuildingID::CITADEL:
  614. case BuildingID::CASTLE:
  615. GH.windows().createAndPushWindow<CFortScreen>(town);
  616. break;
  617. case BuildingID::VILLAGE_HALL:
  618. case BuildingID::CITY_HALL:
  619. case BuildingID::TOWN_HALL:
  620. case BuildingID::CAPITOL:
  621. enterTownHall();
  622. break;
  623. case BuildingID::MARKETPLACE:
  624. // can't use allied marketplace
  625. if (town->getOwner() == LOCPLINT->playerID)
  626. GH.windows().createAndPushWindow<CMarketplaceWindow>(town, town->visitingHero, nullptr, EMarketMode::RESOURCE_RESOURCE);
  627. else
  628. enterBuilding(building);
  629. break;
  630. case BuildingID::BLACKSMITH:
  631. enterBlacksmith(town->town->warMachine);
  632. break;
  633. case BuildingID::SHIP:
  634. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]); //Cannot build another boat
  635. break;
  636. case BuildingID::SPECIAL_1:
  637. case BuildingID::SPECIAL_2:
  638. case BuildingID::SPECIAL_3:
  639. switch(subID)
  640. {
  641. case BuildingSubID::NONE:
  642. enterBuilding(building);
  643. break;
  644. case BuildingSubID::MYSTIC_POND:
  645. enterFountain(building, subID, upgrades);
  646. break;
  647. case BuildingSubID::ARTIFACT_MERCHANT:
  648. if(town->visitingHero)
  649. GH.windows().createAndPushWindow<CMarketplaceWindow>(town, town->visitingHero, nullptr, EMarketMode::RESOURCE_ARTIFACT);
  650. else
  651. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % b->getNameTranslated())); //Only visiting heroes may use the %s.
  652. break;
  653. case BuildingSubID::FOUNTAIN_OF_FORTUNE:
  654. enterFountain(building, subID, upgrades);
  655. break;
  656. case BuildingSubID::FREELANCERS_GUILD:
  657. if(getHero())
  658. GH.windows().createAndPushWindow<CMarketplaceWindow>(town, getHero(), nullptr, EMarketMode::CREATURE_RESOURCE);
  659. else
  660. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % b->getNameTranslated())); //Only visiting heroes may use the %s.
  661. break;
  662. case BuildingSubID::MAGIC_UNIVERSITY:
  663. if (getHero())
  664. GH.windows().createAndPushWindow<CUniversityWindow>(getHero(), town, nullptr);
  665. else
  666. enterBuilding(building);
  667. break;
  668. case BuildingSubID::BROTHERHOOD_OF_SWORD:
  669. if(upgrades == BuildingID::TAVERN)
  670. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  671. else
  672. enterBuilding(building);
  673. break;
  674. case BuildingSubID::CASTLE_GATE:
  675. enterCastleGate();
  676. break;
  677. case BuildingSubID::CREATURE_TRANSFORMER: //Skeleton Transformer
  678. GH.windows().createAndPushWindow<CTransformerWindow>(town, getHero(), nullptr);
  679. break;
  680. case BuildingSubID::PORTAL_OF_SUMMONING:
  681. if (town->creatures[GameConstants::CREATURES_PER_TOWN].second.empty())//No creatures
  682. LOCPLINT->showInfoDialog(CGI->generaltexth->tcommands[30]);
  683. else
  684. enterDwelling(GameConstants::CREATURES_PER_TOWN);
  685. break;
  686. case BuildingSubID::BALLISTA_YARD:
  687. enterBlacksmith(ArtifactID::BALLISTA);
  688. break;
  689. default:
  690. enterBuilding(building);
  691. break;
  692. }
  693. break;
  694. default:
  695. enterBuilding(building);
  696. break;
  697. }
  698. }
  699. }
  700. void CCastleBuildings::enterBlacksmith(ArtifactID artifactID)
  701. {
  702. const CGHeroInstance *hero = town->visitingHero;
  703. if(!hero)
  704. {
  705. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % town->town->buildings.find(BuildingID::BLACKSMITH)->second->getNameTranslated()));
  706. return;
  707. }
  708. auto art = artifactID.toArtifact();
  709. int price = art->getPrice();
  710. bool possible = LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) >= price;
  711. if(possible)
  712. {
  713. for(auto slot : art->getPossibleSlots().at(ArtBearer::HERO))
  714. {
  715. if(hero->getArt(slot) == nullptr)
  716. {
  717. possible = true;
  718. break;
  719. }
  720. else
  721. {
  722. possible = false;
  723. }
  724. }
  725. }
  726. CreatureID cre = art->getWarMachine();
  727. GH.windows().createAndPushWindow<CBlacksmithDialog>(possible, cre, artifactID, hero->id);
  728. }
  729. void CCastleBuildings::enterBuilding(BuildingID building)
  730. {
  731. std::vector<std::shared_ptr<CComponent>> comps(1, std::make_shared<CComponent>(CComponent::building, town->subID, building));
  732. LOCPLINT->showInfoDialog( town->town->buildings.find(building)->second->getDescriptionTranslated(), comps);
  733. }
  734. void CCastleBuildings::enterCastleGate()
  735. {
  736. if (!town->visitingHero)
  737. {
  738. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[126]);
  739. return;//only visiting hero can use castle gates
  740. }
  741. std::vector <int> availableTowns;
  742. std::vector <const CGTownInstance*> Towns = LOCPLINT->cb->getTownsInfo(true);
  743. for(auto & Town : Towns)
  744. {
  745. const CGTownInstance *t = Town;
  746. if (t->id != this->town->id && t->visitingHero == nullptr && //another town, empty and this is
  747. t->town->faction->getId() == town->town->faction->getId() && //the town of the same faction
  748. t->hasBuilt(BuildingSubID::CASTLE_GATE)) //and the town has a castle gate
  749. {
  750. availableTowns.push_back(t->id.getNum());//add to the list
  751. }
  752. }
  753. auto gateIcon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, BuildingID::CASTLE_GATE);//will be deleted by selection window
  754. GH.windows().createAndPushWindow<CObjectListWindow>(availableTowns, gateIcon, CGI->generaltexth->jktexts[40],
  755. CGI->generaltexth->jktexts[41], std::bind (&CCastleInterface::castleTeleport, LOCPLINT->castleInt, _1));
  756. }
  757. void CCastleBuildings::enterDwelling(int level)
  758. {
  759. if (level < 0 || level >= town->creatures.size() || town->creatures[level].second.empty())
  760. {
  761. assert(0);
  762. logGlobal->error("Attempt to enter into invalid dwelling of level %d in town %s (%s)", level, town->getNameTranslated(), town->town->faction->getNameTranslated());
  763. return;
  764. }
  765. auto recruitCb = [=](CreatureID id, int count)
  766. {
  767. LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level);
  768. };
  769. GH.windows().createAndPushWindow<CRecruitmentWindow>(town, level, town, recruitCb, nullptr, -87);
  770. }
  771. void CCastleBuildings::enterToTheQuickRecruitmentWindow()
  772. {
  773. const auto beginIt = town->creatures.cbegin();
  774. const auto afterLastIt = town->creatures.size() > GameConstants::CREATURES_PER_TOWN
  775. ? std::next(beginIt, GameConstants::CREATURES_PER_TOWN)
  776. : town->creatures.cend();
  777. const auto hasSomeoneToRecruit = std::any_of(beginIt, afterLastIt,
  778. [](const auto & creatureInfo) { return creatureInfo.first > 0; });
  779. if(hasSomeoneToRecruit)
  780. GH.windows().createAndPushWindow<QuickRecruitmentWindow>(town, pos);
  781. else
  782. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.townHall.noCreaturesToRecruit"), {});
  783. }
  784. void CCastleBuildings::enterFountain(const BuildingID & building, BuildingSubID::EBuildingSubID subID, BuildingID upgrades)
  785. {
  786. std::vector<std::shared_ptr<CComponent>> comps(1, std::make_shared<CComponent>(CComponent::building,town->subID,building));
  787. std::string descr = town->town->buildings.find(building)->second->getDescriptionTranslated();
  788. std::string hasNotProduced;
  789. std::string hasProduced;
  790. if(this->town->town->faction->getIndex() == ETownType::RAMPART)
  791. {
  792. hasNotProduced = CGI->generaltexth->allTexts[677];
  793. hasProduced = CGI->generaltexth->allTexts[678];
  794. }
  795. else
  796. {
  797. auto buildingName = town->town->getSpecialBuilding(subID)->getNameTranslated();
  798. hasNotProduced = std::string(CGI->generaltexth->translate("vcmi.townHall.hasNotProduced"));
  799. hasProduced = std::string(CGI->generaltexth->translate("vcmi.townHall.hasProduced"));
  800. boost::algorithm::replace_first(hasNotProduced, "%s", buildingName);
  801. boost::algorithm::replace_first(hasProduced, "%s", buildingName);
  802. }
  803. bool isMysticPondOrItsUpgrade = subID == BuildingSubID::MYSTIC_POND
  804. || (upgrades != BuildingID::NONE
  805. && town->town->buildings.find(BuildingID(upgrades))->second->subId == BuildingSubID::MYSTIC_POND);
  806. if(upgrades != BuildingID::NONE)
  807. descr += "\n\n"+town->town->buildings.find(BuildingID(upgrades))->second->getDescriptionTranslated();
  808. if(isMysticPondOrItsUpgrade) //for vanila Rampart like towns
  809. {
  810. if(town->bonusValue.first == 0) //Mystic Pond produced nothing;
  811. descr += "\n\n" + hasNotProduced;
  812. else //Mystic Pond produced something;
  813. {
  814. descr += "\n\n" + hasProduced;
  815. boost::algorithm::replace_first(descr,"%s",CGI->generaltexth->restypes[town->bonusValue.first]);
  816. boost::algorithm::replace_first(descr,"%d",std::to_string(town->bonusValue.second));
  817. }
  818. }
  819. LOCPLINT->showInfoDialog(descr, comps);
  820. }
  821. void CCastleBuildings::enterMagesGuild()
  822. {
  823. const CGHeroInstance *hero = getHero();
  824. if(hero && !hero->hasSpellbook()) //hero doesn't have spellbok
  825. {
  826. const StartInfo *si = LOCPLINT->cb->getStartInfo();
  827. // it would be nice to find a way to move this hack to config/mapOverrides.json
  828. if(si && si->campState && si->campState && // We're in campaign,
  829. (si->campState->getFilename() == "DATA/YOG.H3C") && // which is "Birth of a Barbarian",
  830. (hero->subID == 45)) // and the hero is Yog (based on Solmyr)
  831. {
  832. // "Yog has given up magic in all its forms..."
  833. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[736]);
  834. }
  835. else if(LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) < 500) //not enough gold to buy spellbook
  836. {
  837. openMagesGuild();
  838. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[213]);
  839. }
  840. else
  841. {
  842. CFunctionList<void()> onYes = [this](){ openMagesGuild(); };
  843. CFunctionList<void()> onNo = onYes;
  844. onYes += [hero](){ LOCPLINT->cb->buyArtifact(hero, ArtifactID::SPELLBOOK); };
  845. std::vector<std::shared_ptr<CComponent>> components(1, std::make_shared<CComponent>(CComponent::artifact,ArtifactID::SPELLBOOK,0));
  846. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[214], onYes, onNo, components);
  847. }
  848. }
  849. else
  850. {
  851. openMagesGuild();
  852. }
  853. }
  854. void CCastleBuildings::enterTownHall()
  855. {
  856. if(town->visitingHero && town->visitingHero->hasArt(ArtifactID::GRAIL) &&
  857. !vstd::contains(town->builtBuildings, BuildingID::GRAIL)) //hero has grail, but town does not have it
  858. {
  859. if(!vstd::contains(town->forbiddenBuildings, BuildingID::GRAIL))
  860. {
  861. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[597], //Do you wish this to be the permanent home of the Grail?
  862. [&](){ LOCPLINT->cb->buildBuilding(town, BuildingID::GRAIL); },
  863. [&](){ openTownHall(); });
  864. }
  865. else
  866. {
  867. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[673]);
  868. assert(GH.windows().topWindow<CInfoWindow>() != nullptr);
  869. GH.windows().topWindow<CInfoWindow>()->buttons[0]->addCallback(std::bind(&CCastleBuildings::openTownHall, this));
  870. }
  871. }
  872. else
  873. {
  874. openTownHall();
  875. }
  876. }
  877. void CCastleBuildings::openMagesGuild()
  878. {
  879. auto mageGuildBackground = LOCPLINT->castleInt->town->town->clientInfo.guildBackground;
  880. GH.windows().createAndPushWindow<CMageGuildScreen>(LOCPLINT->castleInt, mageGuildBackground);
  881. }
  882. void CCastleBuildings::openTownHall()
  883. {
  884. GH.windows().createAndPushWindow<CHallInterface>(town);
  885. }
  886. CCreaInfo::CCreaInfo(Point position, const CGTownInstance * Town, int Level, bool compact, bool _showAvailable):
  887. town(Town),
  888. level(Level),
  889. showAvailable(_showAvailable)
  890. {
  891. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  892. pos += position;
  893. if(town->creatures.size() <= level || town->creatures[level].second.empty())
  894. {
  895. level = -1;
  896. return;//No creature
  897. }
  898. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  899. ui32 creatureID = town->creatures[level].second.back();
  900. creature = CGI->creh->objects[creatureID];
  901. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature->getIconIndex(), 0, 8, 0);
  902. std::string value;
  903. if(showAvailable)
  904. value = std::to_string(town->creatures[level].first);
  905. else
  906. value = std::string("+") + std::to_string(town->creatureGrowth(level));
  907. if(compact)
  908. {
  909. label = std::make_shared<CLabel>(40, 32, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, value);
  910. pos.x += 8;
  911. pos.w = 32;
  912. pos.h = 32;
  913. }
  914. else
  915. {
  916. label = std::make_shared<CLabel>(24, 40, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, value);
  917. pos.w = 48;
  918. pos.h = 48;
  919. }
  920. }
  921. void CCreaInfo::update()
  922. {
  923. if(label)
  924. {
  925. std::string value;
  926. if(showAvailable)
  927. value = std::to_string(town->creatures[level].first);
  928. else
  929. value = std::string("+") + std::to_string(town->creatureGrowth(level));
  930. if(value != label->getText())
  931. label->setText(value);
  932. }
  933. }
  934. void CCreaInfo::hover(bool on)
  935. {
  936. std::string message = CGI->generaltexth->allTexts[588];
  937. boost::algorithm::replace_first(message, "%s", creature->getNamePluralTranslated());
  938. if(on)
  939. {
  940. GH.statusbar()->write(message);
  941. }
  942. else
  943. {
  944. GH.statusbar()->clearIfMatching(message);
  945. }
  946. }
  947. void CCreaInfo::clickPressed(const Point & cursorPosition)
  948. {
  949. int offset = LOCPLINT->castleInt? (-87) : 0;
  950. auto recruitCb = [=](CreatureID id, int count)
  951. {
  952. LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level);
  953. };
  954. GH.windows().createAndPushWindow<CRecruitmentWindow>(town, level, town, recruitCb, nullptr, offset);
  955. }
  956. std::string CCreaInfo::genGrowthText()
  957. {
  958. GrowthInfo gi = town->getGrowthInfo(level);
  959. std::string descr = boost::str(boost::format(CGI->generaltexth->allTexts[589]) % creature->getNameSingularTranslated() % gi.totalGrowth());
  960. for(const GrowthInfo::Entry & entry : gi.entries)
  961. descr +="\n" + entry.description;
  962. return descr;
  963. }
  964. void CCreaInfo::showPopupWindow(const Point & cursorPosition)
  965. {
  966. if (showAvailable)
  967. GH.windows().createAndPushWindow<CDwellingInfoBox>(GH.screenDimensions().x / 2, GH.screenDimensions().y / 2, town, level);
  968. else
  969. CRClickPopup::createAndPush(genGrowthText(), std::make_shared<CComponent>(CComponent::creature, creature->getId()));
  970. }
  971. bool CCreaInfo::getShowAvailable()
  972. {
  973. return showAvailable;
  974. }
  975. CTownInfo::CTownInfo(int posX, int posY, const CGTownInstance * Town, bool townHall)
  976. : town(Town),
  977. building(nullptr)
  978. {
  979. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  980. addUsedEvents(SHOW_POPUP | HOVER);
  981. pos.x += posX;
  982. pos.y += posY;
  983. int buildID;
  984. if(townHall)
  985. {
  986. buildID = 10 + town->hallLevel();
  987. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("ITMTL.DEF"), town->hallLevel());
  988. }
  989. else
  990. {
  991. buildID = 6 + town->fortLevel();
  992. if(buildID == 6)
  993. return;//FIXME: suspicious statement, fix or comment
  994. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("ITMCL.DEF"), town->fortLevel()-1);
  995. }
  996. building = town->town->buildings.at(BuildingID(buildID));
  997. pos = picture->pos;
  998. }
  999. void CTownInfo::hover(bool on)
  1000. {
  1001. if(on)
  1002. {
  1003. if(building )
  1004. GH.statusbar()->write(building->getNameTranslated());
  1005. }
  1006. else
  1007. {
  1008. GH.statusbar()->clear();
  1009. }
  1010. }
  1011. void CTownInfo::showPopupWindow(const Point & cursorPosition)
  1012. {
  1013. if(building)
  1014. {
  1015. auto c = std::make_shared<CComponent>(CComponent::building, building->town->faction->getIndex(), building->bid);
  1016. CRClickPopup::createAndPush(CInfoWindow::genText(building->getNameTranslated(), building->getDescriptionTranslated()), c);
  1017. }
  1018. }
  1019. CCastleInterface::CCastleInterface(const CGTownInstance * Town, const CGTownInstance * from):
  1020. CStatusbarWindow(PLAYER_COLORED | BORDERED),
  1021. town(Town)
  1022. {
  1023. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1024. LOCPLINT->castleInt = this;
  1025. addUsedEvents(KEYBOARD);
  1026. builds = std::make_shared<CCastleBuildings>(town);
  1027. panel = std::make_shared<CPicture>(ImagePath::builtin("TOWNSCRN"), 0, builds->pos.h);
  1028. panel->colorize(LOCPLINT->playerID);
  1029. pos.w = panel->pos.w;
  1030. pos.h = builds->pos.h + panel->pos.h;
  1031. center();
  1032. updateShadow();
  1033. garr = std::make_shared<CGarrisonInt>(Point(305, 387), 4, Point(0,96), town->getUpperArmy(), town->visitingHero);
  1034. garr->setRedrawParent(true);
  1035. heroes = std::make_shared<HeroSlots>(town, Point(241, 387), Point(241, 483), garr, true);
  1036. title = std::make_shared<CLabel>(85, 387, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, town->getNameTranslated());
  1037. income = std::make_shared<CLabel>(195, 443, FONT_SMALL, ETextAlignment::CENTER);
  1038. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("ITPT"), 0, 0, 15, 387);
  1039. exit = std::make_shared<CButton>(Point(744, 544), AnimationPath::builtin("TSBTNS"), CButton::tooltip(CGI->generaltexth->tcommands[8]), [&](){close();}, EShortcut::GLOBAL_RETURN);
  1040. exit->setImageOrder(4, 5, 6, 7);
  1041. auto split = std::make_shared<CButton>(Point(744, 382), AnimationPath::builtin("TSBTNS"), CButton::tooltip(CGI->generaltexth->tcommands[3]), [&]()
  1042. {
  1043. garr->splitClick();
  1044. heroes->splitClicked();
  1045. });
  1046. garr->addSplitBtn(split);
  1047. Rect barRect(9, 182, 732, 18);
  1048. auto statusbarBackground = std::make_shared<CPicture>(panel->getSurface(), barRect, 9, 555);
  1049. statusbar = CGStatusBar::create(statusbarBackground);
  1050. resdatabar = std::make_shared<CResDataBar>(ImagePath::builtin("ARESBAR"), 3, 575, 37, 3, 84, 78);
  1051. townlist = std::make_shared<CTownList>(3, Rect(Point(743, 414), Point(48, 128)), Point(1,16), Point(0, 32), LOCPLINT->localState->getOwnedTowns().size() );
  1052. townlist->setScrollUpButton( std::make_shared<CButton>( Point(744, 414), AnimationPath::builtin("IAM014"), CButton::tooltipLocalized("core.help.306")));
  1053. townlist->setScrollDownButton( std::make_shared<CButton>( Point(744, 526), AnimationPath::builtin("IAM015"), CButton::tooltipLocalized("core.help.307")));
  1054. if(from)
  1055. townlist->select(from);
  1056. townlist->select(town); //this will scroll list to select current town
  1057. townlist->onSelect = std::bind(&CCastleInterface::townChange, this);
  1058. recreateIcons();
  1059. if (!from)
  1060. adventureInt->onAudioPaused();
  1061. CCS->musich->playMusic(town->town->clientInfo.musicTheme, true, false);
  1062. }
  1063. CCastleInterface::~CCastleInterface()
  1064. {
  1065. // resume map audio if:
  1066. // adventureInt exists (may happen on exiting client with open castle interface)
  1067. // castleInt has not been replaced (happens on switching between towns inside castle interface)
  1068. if (adventureInt && LOCPLINT->castleInt == this)
  1069. adventureInt->onAudioResumed();
  1070. if(LOCPLINT->castleInt == this)
  1071. LOCPLINT->castleInt = nullptr;
  1072. }
  1073. void CCastleInterface::updateGarrisons()
  1074. {
  1075. garr->setArmy(town->getUpperArmy(), EGarrisonType::UPPER);
  1076. garr->setArmy(town->visitingHero, EGarrisonType::LOWER);
  1077. garr->recreateSlots();
  1078. heroes->update();
  1079. redraw();
  1080. }
  1081. void CCastleInterface::close()
  1082. {
  1083. if(town->tempOwner == LOCPLINT->playerID) //we may have opened window for an allied town
  1084. {
  1085. if(town->visitingHero && town->visitingHero->tempOwner == LOCPLINT->playerID)
  1086. LOCPLINT->localState->setSelection(town->visitingHero);
  1087. else
  1088. LOCPLINT->localState->setSelection(town);
  1089. }
  1090. CWindowObject::close();
  1091. }
  1092. void CCastleInterface::castleTeleport(int where)
  1093. {
  1094. const CGTownInstance * dest = LOCPLINT->cb->getTown(ObjectInstanceID(where));
  1095. LOCPLINT->localState->setSelection(town->visitingHero);//according to assert(ho == adventureInt->selection) in the eraseCurrentPathOf
  1096. LOCPLINT->cb->teleportHero(town->visitingHero, dest);
  1097. LOCPLINT->localState->erasePath(town->visitingHero);
  1098. }
  1099. void CCastleInterface::townChange()
  1100. {
  1101. //TODO: do not recreate window
  1102. const CGTownInstance * dest = LOCPLINT->localState->getOwnedTown(townlist->getSelectedIndex());
  1103. const CGTownInstance * town = this->town;// "this" is going to be deleted
  1104. if ( dest == town )
  1105. return;
  1106. close();
  1107. GH.windows().createAndPushWindow<CCastleInterface>(dest, town);
  1108. }
  1109. void CCastleInterface::addBuilding(BuildingID bid)
  1110. {
  1111. deactivate();
  1112. builds->addBuilding(bid);
  1113. recreateIcons();
  1114. activate();
  1115. redraw();
  1116. }
  1117. void CCastleInterface::removeBuilding(BuildingID bid)
  1118. {
  1119. deactivate();
  1120. builds->removeBuilding(bid);
  1121. recreateIcons();
  1122. activate();
  1123. redraw();
  1124. }
  1125. void CCastleInterface::recreateIcons()
  1126. {
  1127. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  1128. size_t iconIndex = town->town->clientInfo.icons[town->hasFort()][town->builded >= CGI->settings()->getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP)];
  1129. icon->setFrame(iconIndex);
  1130. TResources townIncome = town->dailyIncome();
  1131. income->setText(std::to_string(townIncome[EGameResID::GOLD]));
  1132. hall = std::make_shared<CTownInfo>(80, 413, town, true);
  1133. fort = std::make_shared<CTownInfo>(122, 413, town, false);
  1134. fastTownHall = std::make_shared<CButton>(Point(80, 413), AnimationPath::builtin("ITMTL.def"), CButton::tooltip(), [&](){ builds->enterTownHall(); });
  1135. fastTownHall->setImageOrder(town->hallLevel() - 1, town->hallLevel() - 1, town->hallLevel() - 1, town->hallLevel() - 1);
  1136. fastTownHall->setAnimateLonelyFrame(true);
  1137. fastArmyPurchase = std::make_shared<CButton>(Point(122, 413), AnimationPath::builtin("itmcl.def"), CButton::tooltip(), [&](){ builds->enterToTheQuickRecruitmentWindow(); });
  1138. fastArmyPurchase->setImageOrder(town->fortLevel() - 1, town->fortLevel() - 1, town->fortLevel() - 1, town->fortLevel() - 1);
  1139. fastArmyPurchase->setAnimateLonelyFrame(true);
  1140. creainfo.clear();
  1141. bool compactCreatureInfo = useCompactCreatureBox();
  1142. bool useAvailableCreaturesForLabel = useAvailableAmountAsCreatureLabel();
  1143. for(size_t i=0; i<4; i++)
  1144. creainfo.push_back(std::make_shared<CCreaInfo>(Point(14 + 55 * (int)i, 459), town, (int)i, compactCreatureInfo, useAvailableCreaturesForLabel));
  1145. for(size_t i=0; i<4; i++)
  1146. creainfo.push_back(std::make_shared<CCreaInfo>(Point(14 + 55 * (int)i, 507), town, (int)i + 4, compactCreatureInfo, useAvailableCreaturesForLabel));
  1147. }
  1148. void CCastleInterface::keyPressed(EShortcut key)
  1149. {
  1150. switch(key)
  1151. {
  1152. case EShortcut::MOVE_UP:
  1153. townlist->selectPrev();
  1154. break;
  1155. case EShortcut::MOVE_DOWN:
  1156. townlist->selectNext();
  1157. break;
  1158. case EShortcut::TOWN_SWAP_ARMIES:
  1159. heroes->swapArmies();
  1160. break;
  1161. case EShortcut::TOWN_OPEN_TAVERN:
  1162. if(town->hasBuilt(BuildingID::TAVERN))
  1163. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  1164. break;
  1165. default:
  1166. break;
  1167. }
  1168. }
  1169. void CCastleInterface::creaturesChangedEventHandler()
  1170. {
  1171. for(auto creatureInfoBox : creainfo)
  1172. {
  1173. if(creatureInfoBox->getShowAvailable())
  1174. {
  1175. creatureInfoBox->update();
  1176. }
  1177. }
  1178. }
  1179. CHallInterface::CBuildingBox::CBuildingBox(int x, int y, const CGTownInstance * Town, const CBuilding * Building):
  1180. town(Town),
  1181. building(Building)
  1182. {
  1183. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1184. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1185. pos.x += x;
  1186. pos.y += y;
  1187. pos.w = 154;
  1188. pos.h = 92;
  1189. state = LOCPLINT->cb->canBuildStructure(town, building->bid);
  1190. static int panelIndex[12] =
  1191. {
  1192. 3, 3, 3, 0, 0, 2, 2, 1, 2, 2, 3, 3
  1193. };
  1194. static int iconIndex[12] =
  1195. {
  1196. -1, -1, -1, 0, 0, 1, 2, -1, 1, 1, -1, -1
  1197. };
  1198. icon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, building->bid, 0, 2, 2);
  1199. header = std::make_shared<CAnimImage>(AnimationPath::builtin("TPTHBAR"), panelIndex[static_cast<int>(state)], 0, 1, 73);
  1200. if(iconIndex[static_cast<int>(state)] >=0)
  1201. mark = std::make_shared<CAnimImage>(AnimationPath::builtin("TPTHCHK"), iconIndex[static_cast<int>(state)], 0, 136, 56);
  1202. name = std::make_shared<CLabel>(75, 81, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, building->getNameTranslated());
  1203. //todo: add support for all possible states
  1204. if(state >= EBuildingState::BUILDING_ERROR)
  1205. state = EBuildingState::FORBIDDEN;
  1206. }
  1207. void CHallInterface::CBuildingBox::hover(bool on)
  1208. {
  1209. if(on)
  1210. {
  1211. std::string toPrint;
  1212. if(state==EBuildingState::PREREQUIRES || state == EBuildingState::MISSING_BASE)
  1213. toPrint = CGI->generaltexth->hcommands[5];
  1214. else if(state==EBuildingState::CANT_BUILD_TODAY)
  1215. toPrint = CGI->generaltexth->allTexts[223];
  1216. else
  1217. toPrint = CGI->generaltexth->hcommands[static_cast<int>(state)];
  1218. boost::algorithm::replace_first(toPrint,"%s",building->getNameTranslated());
  1219. GH.statusbar()->write(toPrint);
  1220. }
  1221. else
  1222. {
  1223. GH.statusbar()->clear();
  1224. }
  1225. }
  1226. void CHallInterface::CBuildingBox::clickPressed(const Point & cursorPosition)
  1227. {
  1228. GH.windows().createAndPushWindow<CBuildWindow>(town,building,state,0);
  1229. }
  1230. void CHallInterface::CBuildingBox::showPopupWindow(const Point & cursorPosition)
  1231. {
  1232. GH.windows().createAndPushWindow<CBuildWindow>(town,building,state,1);
  1233. }
  1234. CHallInterface::CHallInterface(const CGTownInstance * Town):
  1235. CStatusbarWindow(PLAYER_COLORED | BORDERED, Town->town->clientInfo.hallBackground),
  1236. town(Town)
  1237. {
  1238. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1239. resdatabar = std::make_shared<CMinorResDataBar>();
  1240. resdatabar->moveBy(pos.topLeft(), true);
  1241. Rect barRect(5, 556, 740, 18);
  1242. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 5, 556);
  1243. statusbar = CGStatusBar::create(statusbarBackground);
  1244. title = std::make_shared<CLabel>(399, 12, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, town->town->buildings.at(BuildingID(town->hallLevel()+BuildingID::VILLAGE_HALL))->getNameTranslated());
  1245. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1.DEF"), CButton::tooltip(CGI->generaltexth->hcommands[8]), [&](){close();}, EShortcut::GLOBAL_RETURN);
  1246. auto & boxList = town->town->clientInfo.hallSlots;
  1247. boxes.resize(boxList.size());
  1248. for(size_t row=0; row<boxList.size(); row++) //for each row
  1249. {
  1250. for(size_t col=0; col<boxList[row].size(); col++) //for each box
  1251. {
  1252. const CBuilding * building = nullptr;
  1253. for(auto & buildingID : boxList[row][col])//we are looking for the first not built structure
  1254. {
  1255. const CBuilding * current = town->town->buildings.at(buildingID);
  1256. if(vstd::contains(town->builtBuildings, buildingID))
  1257. {
  1258. building = current;
  1259. }
  1260. else
  1261. {
  1262. if(current->mode == CBuilding::BUILD_NORMAL)
  1263. {
  1264. building = current;
  1265. break;
  1266. }
  1267. }
  1268. }
  1269. int posX = pos.w/2 - (int)boxList[row].size()*154/2 - ((int)boxList[row].size()-1)*20 + 194*(int)col,
  1270. posY = 35 + 104*(int)row;
  1271. if(building)
  1272. boxes[row].push_back(std::make_shared<CBuildingBox>(posX, posY, town, building));
  1273. }
  1274. }
  1275. }
  1276. CBuildWindow::CBuildWindow(const CGTownInstance *Town, const CBuilding * Building, EBuildingState state, bool rightClick):
  1277. CStatusbarWindow(PLAYER_COLORED | (rightClick ? RCLICK_POPUP : 0), ImagePath::builtin("TPUBUILD")),
  1278. town(Town),
  1279. building(Building)
  1280. {
  1281. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1282. icon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, building->bid, 0, 125, 50);
  1283. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26);
  1284. statusbar = CGStatusBar::create(statusbarBackground);
  1285. MetaString nameString;
  1286. nameString.appendTextID("core.hallinfo.7");
  1287. nameString.replaceTextID(building->getNameTextID());
  1288. name = std::make_shared<CLabel>(197, 30, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, nameString.toString());
  1289. description = std::make_shared<CTextBox>(building->getDescriptionTranslated(), Rect(33, 135, 329, 67), 0, FONT_MEDIUM, ETextAlignment::CENTER);
  1290. stateText = std::make_shared<CTextBox>(getTextForState(state), Rect(33, 216, 329, 67), 0, FONT_SMALL, ETextAlignment::CENTER);
  1291. //Create components for all required resources
  1292. std::vector<std::shared_ptr<CComponent>> components;
  1293. for(int i = 0; i<GameConstants::RESOURCE_QUANTITY; i++)
  1294. {
  1295. if(building->resources[i])
  1296. {
  1297. std::string text = std::to_string(building->resources[i]);
  1298. int resAfterBuy = LOCPLINT->cb->getResourceAmount(GameResID(i)) - building->resources[i];
  1299. if(resAfterBuy < 0 && state != EBuildingState::ALREADY_PRESENT && settings["general"]["enableUiEnhancements"].Bool())
  1300. text = "{H3Red|" + std::to_string(LOCPLINT->cb->getResourceAmount(GameResID(i))) + "}" + " / " + text;
  1301. components.push_back(std::make_shared<CComponent>(CComponent::resource, i, text, CComponent::small));
  1302. }
  1303. }
  1304. cost = std::make_shared<CComponentBox>(components, Rect(25, 300, pos.w - 50, 130));
  1305. if(!rightClick)
  1306. { //normal window
  1307. MetaString tooltipYes;
  1308. tooltipYes.appendTextID("core.genrltxt.595");
  1309. tooltipYes.replaceTextID(building->getNameTextID());
  1310. MetaString tooltipNo;
  1311. tooltipNo.appendTextID("core.genrltxt.596");
  1312. tooltipNo.replaceTextID(building->getNameTextID());
  1313. buy = std::make_shared<CButton>(Point(45, 446), AnimationPath::builtin("IBUY30"), CButton::tooltip(tooltipYes.toString()), [&](){ buyFunc(); }, EShortcut::GLOBAL_ACCEPT);
  1314. buy->setBorderColor(Colors::METALLIC_GOLD);
  1315. buy->block(state!=EBuildingState::ALLOWED || LOCPLINT->playerID != town->tempOwner);
  1316. cancel = std::make_shared<CButton>(Point(290, 445), AnimationPath::builtin("ICANCEL"), CButton::tooltip(tooltipNo.toString()), [&](){ close();}, EShortcut::GLOBAL_CANCEL);
  1317. cancel->setBorderColor(Colors::METALLIC_GOLD);
  1318. }
  1319. }
  1320. void CBuildWindow::buyFunc()
  1321. {
  1322. LOCPLINT->cb->buildBuilding(town,building->bid);
  1323. GH.windows().popWindows(2); //we - build window and hall screen
  1324. }
  1325. std::string CBuildWindow::getTextForState(EBuildingState state)
  1326. {
  1327. std::string ret;
  1328. if(state < EBuildingState::ALLOWED)
  1329. ret = CGI->generaltexth->hcommands[static_cast<int>(state)];
  1330. switch (state)
  1331. {
  1332. case EBuildingState::ALREADY_PRESENT:
  1333. case EBuildingState::CANT_BUILD_TODAY:
  1334. case EBuildingState::NO_RESOURCES:
  1335. ret.replace(ret.find_first_of("%s"), 2, building->getNameTranslated());
  1336. break;
  1337. case EBuildingState::ALLOWED:
  1338. return CGI->generaltexth->allTexts[219]; //all prereq. are met
  1339. case EBuildingState::PREREQUIRES:
  1340. {
  1341. auto toStr = [&](const BuildingID build) -> std::string
  1342. {
  1343. return town->town->buildings.at(build)->getNameTranslated();
  1344. };
  1345. ret = CGI->generaltexth->allTexts[52];
  1346. ret += "\n" + town->genBuildingRequirements(building->bid).toString(toStr);
  1347. break;
  1348. }
  1349. case EBuildingState::MISSING_BASE:
  1350. {
  1351. std::string msg = CGI->generaltexth->translate("vcmi.townHall.missingBase");
  1352. ret = boost::str(boost::format(msg) % town->town->buildings.at(building->upgrade)->getNameTranslated());
  1353. break;
  1354. }
  1355. }
  1356. return ret;
  1357. }
  1358. LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int min, int max)
  1359. {
  1360. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1361. pos.x+=size.x;
  1362. pos.y+=size.y;
  1363. pos.w = size.w;
  1364. pos.h = size.h;
  1365. init(name, descr, min, max);
  1366. }
  1367. LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int val)
  1368. {
  1369. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1370. pos.x+=size.x;
  1371. pos.y+=size.y;
  1372. pos.w = size.w;
  1373. pos.h = size.h;
  1374. init(name, descr, val, val);
  1375. }
  1376. void LabeledValue::init(std::string nameText, std::string descr, int min, int max)
  1377. {
  1378. addUsedEvents(HOVER);
  1379. hoverText = descr;
  1380. std::string valueText;
  1381. if(min && max)
  1382. {
  1383. valueText = std::to_string(min);
  1384. if(min != max)
  1385. valueText += '-' + std::to_string(max);
  1386. }
  1387. name = std::make_shared<CLabel>(3, 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, nameText);
  1388. value = std::make_shared<CLabel>(pos.w-3, pos.h-2, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, valueText);
  1389. }
  1390. void LabeledValue::hover(bool on)
  1391. {
  1392. if(on)
  1393. {
  1394. GH.statusbar()->write(hoverText);
  1395. }
  1396. else
  1397. {
  1398. GH.statusbar()->clear();
  1399. }
  1400. }
  1401. CFortScreen::CFortScreen(const CGTownInstance * town):
  1402. CStatusbarWindow(PLAYER_COLORED | BORDERED, getBgName(town))
  1403. {
  1404. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1405. ui32 fortSize = static_cast<ui32>(town->creatures.size());
  1406. if(fortSize > GameConstants::CREATURES_PER_TOWN && town->creatures.back().second.empty())
  1407. fortSize--;
  1408. const CBuilding * fortBuilding = town->town->buildings.at(BuildingID(town->fortLevel()+6));
  1409. title = std::make_shared<CLabel>(400, 12, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE, fortBuilding->getNameTranslated());
  1410. std::string text = boost::str(boost::format(CGI->generaltexth->fcommands[6]) % fortBuilding->getNameTranslated());
  1411. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1"), CButton::tooltip(text), [&](){ close(); }, EShortcut::GLOBAL_RETURN);
  1412. std::vector<Point> positions =
  1413. {
  1414. Point(10, 22), Point(404, 22),
  1415. Point(10, 155), Point(404,155),
  1416. Point(10, 288), Point(404,288)
  1417. };
  1418. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1419. {
  1420. positions.push_back(Point(206,421));
  1421. }
  1422. else
  1423. {
  1424. positions.push_back(Point(10, 421));
  1425. positions.push_back(Point(404,421));
  1426. }
  1427. for(ui32 i=0; i<fortSize; i++)
  1428. {
  1429. BuildingID buildingID;
  1430. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1431. {
  1432. BuildingID dwelling = BuildingID::DWELL_UP_FIRST+i;
  1433. if(vstd::contains(town->builtBuildings, dwelling))
  1434. buildingID = BuildingID(BuildingID::DWELL_UP_FIRST+i);
  1435. else
  1436. buildingID = BuildingID(BuildingID::DWELL_FIRST+i);
  1437. }
  1438. else
  1439. {
  1440. buildingID = BuildingID::SPECIAL_3;
  1441. }
  1442. recAreas.push_back(std::make_shared<RecruitArea>(positions[i].x, positions[i].y, town, i));
  1443. }
  1444. resdatabar = std::make_shared<CMinorResDataBar>();
  1445. resdatabar->moveBy(pos.topLeft(), true);
  1446. Rect barRect(4, 554, 740, 18);
  1447. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 4, 554);
  1448. statusbar = CGStatusBar::create(statusbarBackground);
  1449. }
  1450. ImagePath CFortScreen::getBgName(const CGTownInstance * town)
  1451. {
  1452. ui32 fortSize = static_cast<ui32>(town->creatures.size());
  1453. if(fortSize > GameConstants::CREATURES_PER_TOWN && town->creatures.back().second.empty())
  1454. fortSize--;
  1455. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1456. return ImagePath::builtin("TPCASTL7");
  1457. else
  1458. return ImagePath::builtin("TPCASTL8");
  1459. }
  1460. void CFortScreen::creaturesChangedEventHandler()
  1461. {
  1462. for(auto & elem : recAreas)
  1463. elem->creaturesChangedEventHandler();
  1464. LOCPLINT->castleInt->creaturesChangedEventHandler();
  1465. }
  1466. CFortScreen::RecruitArea::RecruitArea(int posX, int posY, const CGTownInstance * Town, int Level):
  1467. town(Town),
  1468. level(Level),
  1469. availableCount(nullptr)
  1470. {
  1471. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1472. pos.x +=posX;
  1473. pos.y +=posY;
  1474. pos.w = 386;
  1475. pos.h = 126;
  1476. if(!town->creatures[level].second.empty())
  1477. addUsedEvents(LCLICK | HOVER);//Activate only if dwelling is present
  1478. addUsedEvents(SHOW_POPUP);
  1479. icons = std::make_shared<CPicture>(ImagePath::builtin("TPCAINFO"), 261, 3);
  1480. if(getMyBuilding() != nullptr)
  1481. {
  1482. buildingIcon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, getMyBuilding()->bid, 0, 4, 21);
  1483. buildingName = std::make_shared<CLabel>(78, 101, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyBuilding()->getNameTranslated());
  1484. if(vstd::contains(town->builtBuildings, getMyBuilding()->bid))
  1485. {
  1486. ui32 available = town->creatures[level].first;
  1487. std::string availableText = CGI->generaltexth->allTexts[217]+ std::to_string(available);
  1488. availableCount = std::make_shared<CLabel>(78, 119, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, availableText);
  1489. }
  1490. }
  1491. if(getMyCreature() != nullptr)
  1492. {
  1493. hoverText = boost::str(boost::format(CGI->generaltexth->tcommands[21]) % getMyCreature()->getNamePluralTranslated());
  1494. new CCreaturePic(159, 4, getMyCreature(), false);
  1495. new CLabel(78, 11, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyCreature()->getNamePluralTranslated());
  1496. Rect sizes(287, 4, 96, 18);
  1497. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[190], CGI->generaltexth->fcommands[0], getMyCreature()->getAttack(false)));
  1498. sizes.y+=20;
  1499. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[191], CGI->generaltexth->fcommands[1], getMyCreature()->getDefense(false)));
  1500. sizes.y+=21;
  1501. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[199], CGI->generaltexth->fcommands[2], getMyCreature()->getMinDamage(false), getMyCreature()->getMaxDamage(false)));
  1502. sizes.y+=20;
  1503. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[388], CGI->generaltexth->fcommands[3], getMyCreature()->getMaxHealth()));
  1504. sizes.y+=21;
  1505. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[193], CGI->generaltexth->fcommands[4], getMyCreature()->valOfBonuses(BonusType::STACKS_SPEED)));
  1506. sizes.y+=20;
  1507. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[194], CGI->generaltexth->fcommands[5], town->creatureGrowth(level)));
  1508. }
  1509. }
  1510. const CCreature * CFortScreen::RecruitArea::getMyCreature()
  1511. {
  1512. if(!town->creatures.at(level).second.empty()) // built
  1513. return VLC->creh->objects[town->creatures.at(level).second.back()];
  1514. if(!town->town->creatures.at(level).empty()) // there are creatures on this level
  1515. return VLC->creh->objects[town->town->creatures.at(level).front()];
  1516. return nullptr;
  1517. }
  1518. const CBuilding * CFortScreen::RecruitArea::getMyBuilding()
  1519. {
  1520. BuildingID myID = BuildingID(BuildingID::DWELL_FIRST + level);
  1521. if (level == GameConstants::CREATURES_PER_TOWN)
  1522. return town->town->getSpecialBuilding(BuildingSubID::PORTAL_OF_SUMMONING);
  1523. if (!town->town->buildings.count(myID))
  1524. return nullptr;
  1525. const CBuilding * build = town->town->buildings.at(myID);
  1526. while (town->town->buildings.count(myID))
  1527. {
  1528. if (town->hasBuilt(myID))
  1529. build = town->town->buildings.at(myID);
  1530. myID.advance(GameConstants::CREATURES_PER_TOWN);
  1531. }
  1532. return build;
  1533. }
  1534. void CFortScreen::RecruitArea::hover(bool on)
  1535. {
  1536. if(on)
  1537. GH.statusbar()->write(hoverText);
  1538. else
  1539. GH.statusbar()->clear();
  1540. }
  1541. void CFortScreen::RecruitArea::creaturesChangedEventHandler()
  1542. {
  1543. if(availableCount)
  1544. {
  1545. std::string availableText = CGI->generaltexth->allTexts[217] + std::to_string(town->creatures[level].first);
  1546. availableCount->setText(availableText);
  1547. }
  1548. }
  1549. void CFortScreen::RecruitArea::clickPressed(const Point & cursorPosition)
  1550. {
  1551. LOCPLINT->castleInt->builds->enterDwelling(level);
  1552. }
  1553. void CFortScreen::RecruitArea::showPopupWindow(const Point & cursorPosition)
  1554. {
  1555. if (getMyCreature() != nullptr)
  1556. GH.windows().createAndPushWindow<CStackWindow>(getMyCreature(), true);
  1557. }
  1558. CMageGuildScreen::CMageGuildScreen(CCastleInterface * owner, const ImagePath & imagename)
  1559. : CStatusbarWindow(BORDERED, imagename)
  1560. {
  1561. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1562. window = std::make_shared<CPicture>(owner->town->town->clientInfo.guildWindow, 332, 76);
  1563. resdatabar = std::make_shared<CMinorResDataBar>();
  1564. resdatabar->moveBy(pos.topLeft(), true);
  1565. Rect barRect(7, 556, 737, 18);
  1566. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 7, 556);
  1567. statusbar = CGStatusBar::create(statusbarBackground);
  1568. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1.DEF"), CButton::tooltip(CGI->generaltexth->allTexts[593]), [&](){ close(); }, EShortcut::GLOBAL_RETURN);
  1569. static const std::vector<std::vector<Point> > positions =
  1570. {
  1571. {Point(222,445), Point(312,445), Point(402,445), Point(520,445), Point(610,445), Point(700,445)},
  1572. {Point(48,53), Point(48,147), Point(48,241), Point(48,335), Point(48,429)},
  1573. {Point(570,82), Point(672,82), Point(570,157), Point(672,157)},
  1574. {Point(183,42), Point(183,148), Point(183,253)},
  1575. {Point(491,325), Point(591,325)}
  1576. };
  1577. for(size_t i=0; i<owner->town->town->mageLevel; i++)
  1578. {
  1579. size_t spellCount = owner->town->spellsAtLevel((int)i+1,false); //spell at level with -1 hmmm?
  1580. for(size_t j=0; j<spellCount; j++)
  1581. {
  1582. if(i<owner->town->mageGuildLevel() && owner->town->spells[i].size()>j)
  1583. spells.push_back(std::make_shared<Scroll>(positions[i][j], CGI->spellh->objects[owner->town->spells[i][j]]));
  1584. else
  1585. emptyScrolls.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TPMAGES.DEF"), 1, 0, positions[i][j].x, positions[i][j].y));
  1586. }
  1587. }
  1588. }
  1589. CMageGuildScreen::Scroll::Scroll(Point position, const CSpell *Spell)
  1590. : spell(Spell)
  1591. {
  1592. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1593. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1594. pos += position;
  1595. image = std::make_shared<CAnimImage>(AnimationPath::builtin("SPELLSCR"), spell->id);
  1596. pos = image->pos;
  1597. }
  1598. void CMageGuildScreen::Scroll::clickPressed(const Point & cursorPosition)
  1599. {
  1600. LOCPLINT->showInfoDialog(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(CComponent::spell, spell->id));
  1601. }
  1602. void CMageGuildScreen::Scroll::showPopupWindow(const Point & cursorPosition)
  1603. {
  1604. CRClickPopup::createAndPush(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(CComponent::spell, spell->id));
  1605. }
  1606. void CMageGuildScreen::Scroll::hover(bool on)
  1607. {
  1608. if(on)
  1609. GH.statusbar()->write(spell->getNameTranslated());
  1610. else
  1611. GH.statusbar()->clear();
  1612. }
  1613. CBlacksmithDialog::CBlacksmithDialog(bool possible, CreatureID creMachineID, ArtifactID aid, ObjectInstanceID hid):
  1614. CStatusbarWindow(PLAYER_COLORED, ImagePath::builtin("TPSMITH"))
  1615. {
  1616. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1617. Rect barRect(8, pos.h - 26, pos.w - 16, 19);
  1618. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 8, pos.h - 26);
  1619. statusbar = CGStatusBar::create(statusbarBackground);
  1620. animBG = std::make_shared<CPicture>(ImagePath::builtin("TPSMITBK"), 64, 50);
  1621. animBG->needRefresh = true;
  1622. const CCreature * creature = CGI->creh->objects[creMachineID];
  1623. anim = std::make_shared<CCreatureAnim>(64, 50, creature->animDefName);
  1624. anim->clipRect(113,125,200,150);
  1625. MetaString titleString;
  1626. titleString.appendTextID("core.genrltxt.274");
  1627. titleString.replaceTextID(creature->getNameSingularTextID());
  1628. MetaString buyText;
  1629. buyText.appendTextID("core.genrltxt.595");
  1630. buyText.replaceTextID(creature->getNameSingularTextID());
  1631. MetaString cancelText;
  1632. cancelText.appendTextID("core.genrltxt.596");
  1633. cancelText.replaceTextID(creature->getNameSingularTextID());
  1634. std::string costString = std::to_string(aid.toArtifact(CGI->artifacts())->getPrice());
  1635. title = std::make_shared<CLabel>(165, 28, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleString.toString());
  1636. costText = std::make_shared<CLabel>(165, 218, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[43]);
  1637. costValue = std::make_shared<CLabel>(165, 292, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, costString);
  1638. buy = std::make_shared<CButton>(Point(42, 312), AnimationPath::builtin("IBUY30.DEF"), CButton::tooltip(buyText.toString()), [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  1639. cancel = std::make_shared<CButton>(Point(224, 312), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(cancelText.toString()), [&](){ close(); }, EShortcut::GLOBAL_CANCEL);
  1640. if(possible)
  1641. buy->addCallback([=](){ LOCPLINT->cb->buyArtifact(LOCPLINT->cb->getHero(hid),aid); });
  1642. else
  1643. buy->block(true);
  1644. costIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 148, 244);
  1645. }