CCastleInterface.cpp 64 KB

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