CCastleInterface.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  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/IGameSettings.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);
  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 = BuildingID::getLevelFromDwelling(bid);
  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)%town->town->creatures.size()].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) >= LOCPLINT->cb->getSettings().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->getBuildings();// a bit modified copy of built buildings
  499. if(town->hasBuilt(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)
  578. {
  579. BuildingID buildingToEnter = building;
  580. for(;;)
  581. {
  582. const CBuilding *b = town->town->buildings.find(buildingToEnter)->second;
  583. if (buildingTryActivateCustomUI(buildingToEnter, building))
  584. return;
  585. if (!b->upgrade.hasValue())
  586. {
  587. enterBuilding(building);
  588. return;
  589. }
  590. buildingToEnter = b->upgrade;
  591. }
  592. }
  593. bool CCastleBuildings::buildingTryActivateCustomUI(BuildingID buildingToTest, BuildingID buildingTarget)
  594. {
  595. logGlobal->trace("You've clicked on %d", (int)buildingToTest.toEnum());
  596. const CBuilding *b = town->town->buildings.at(buildingToTest);
  597. if (town->getWarMachineInBuilding(buildingToTest).hasValue())
  598. {
  599. enterBlacksmith(buildingTarget, town->getWarMachineInBuilding(buildingToTest));
  600. return true;
  601. }
  602. if (!b->marketModes.empty())
  603. {
  604. switch (*b->marketModes.begin())
  605. {
  606. case EMarketMode::CREATURE_UNDEAD:
  607. GH.windows().createAndPushWindow<CTransformerWindow>(town, getHero(), nullptr);
  608. return true;
  609. case EMarketMode::RESOURCE_SKILL:
  610. if (getHero())
  611. GH.windows().createAndPushWindow<CUniversityWindow>(getHero(), buildingTarget, town, nullptr);
  612. return true;
  613. case EMarketMode::RESOURCE_RESOURCE:
  614. // can't use allied marketplace
  615. if (town->getOwner() == LOCPLINT->playerID)
  616. {
  617. GH.windows().createAndPushWindow<CMarketWindow>(town, getHero(), nullptr, *b->marketModes.begin());
  618. return true;
  619. }
  620. else
  621. return false;
  622. default:
  623. if(getHero())
  624. GH.windows().createAndPushWindow<CMarketWindow>(town, getHero(), nullptr, *b->marketModes.begin());
  625. else
  626. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % b->getNameTranslated())); //Only visiting heroes may use the %s.
  627. return true;
  628. }
  629. }
  630. if (town->rewardableBuildings.count(buildingToTest) && town->town->buildings.at(buildingToTest)->manualHeroVisit)
  631. {
  632. enterRewardable(buildingToTest);
  633. return true;
  634. }
  635. if (buildingToTest >= BuildingID::DWELL_FIRST)
  636. {
  637. enterDwelling((BuildingID::getLevelFromDwelling(buildingToTest)));
  638. return true;
  639. }
  640. else
  641. {
  642. switch(buildingToTest)
  643. {
  644. case BuildingID::MAGES_GUILD_1:
  645. case BuildingID::MAGES_GUILD_2:
  646. case BuildingID::MAGES_GUILD_3:
  647. case BuildingID::MAGES_GUILD_4:
  648. case BuildingID::MAGES_GUILD_5:
  649. enterMagesGuild();
  650. return true;
  651. case BuildingID::TAVERN:
  652. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  653. return true;
  654. case BuildingID::SHIPYARD:
  655. if(town->shipyardStatus() == IBoatGenerator::GOOD)
  656. {
  657. LOCPLINT->showShipyardDialog(town);
  658. return true;
  659. }
  660. else if(town->shipyardStatus() == IBoatGenerator::BOAT_ALREADY_BUILT)
  661. {
  662. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]);
  663. return true;
  664. }
  665. return false;
  666. case BuildingID::FORT:
  667. case BuildingID::CITADEL:
  668. case BuildingID::CASTLE:
  669. GH.windows().createAndPushWindow<CFortScreen>(town);
  670. return true;
  671. case BuildingID::VILLAGE_HALL:
  672. case BuildingID::CITY_HALL:
  673. case BuildingID::TOWN_HALL:
  674. case BuildingID::CAPITOL:
  675. enterTownHall();
  676. return true;
  677. case BuildingID::SHIP:
  678. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]); //Cannot build another boat
  679. return true;
  680. case BuildingID::SPECIAL_1:
  681. case BuildingID::SPECIAL_2:
  682. case BuildingID::SPECIAL_3:
  683. case BuildingID::SPECIAL_4:
  684. switch (b->subId)
  685. {
  686. case BuildingSubID::MYSTIC_POND:
  687. enterFountain(buildingToTest, b->subId, buildingTarget);
  688. return true;
  689. case BuildingSubID::CASTLE_GATE:
  690. if (LOCPLINT->makingTurn)
  691. {
  692. enterCastleGate();
  693. return true;
  694. }
  695. return false;
  696. case BuildingSubID::PORTAL_OF_SUMMONING:
  697. if (town->creatures[town->town->creatures.size()].second.empty())//No creatures
  698. LOCPLINT->showInfoDialog(CGI->generaltexth->tcommands[30]);
  699. else
  700. enterDwelling(town->town->creatures.size());
  701. return true;
  702. case BuildingSubID::BANK:
  703. enterBank(buildingTarget);
  704. return true;
  705. }
  706. }
  707. }
  708. for (auto const & bonus : b->buildingBonuses)
  709. {
  710. if (bonus->type == BonusType::THIEVES_GUILD_ACCESS)
  711. {
  712. enterAnyThievesGuild();
  713. return true;
  714. }
  715. }
  716. return false;
  717. }
  718. void CCastleBuildings::enterRewardable(BuildingID building)
  719. {
  720. LOCPLINT->cb->visitTownBuilding(town, building);
  721. }
  722. void CCastleBuildings::enterBlacksmith(BuildingID building, ArtifactID artifactID)
  723. {
  724. const CGHeroInstance *hero = town->visitingHero;
  725. if(!hero)
  726. {
  727. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % town->town->buildings.find(building)->second->getNameTranslated()));
  728. return;
  729. }
  730. auto art = artifactID.toArtifact();
  731. int price = art->getPrice();
  732. bool possible = LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) >= price;
  733. if(possible)
  734. {
  735. for(auto slot : art->getPossibleSlots().at(ArtBearer::HERO))
  736. {
  737. if(hero->getArt(slot) == nullptr || hero->getArt(slot)->getTypeId() != artifactID)
  738. {
  739. possible = true;
  740. break;
  741. }
  742. else
  743. {
  744. possible = false;
  745. }
  746. }
  747. }
  748. CreatureID creatureID = artifactID.toArtifact()->getWarMachine();
  749. GH.windows().createAndPushWindow<CBlacksmithDialog>(possible, creatureID, artifactID, hero->id);
  750. }
  751. void CCastleBuildings::enterBuilding(BuildingID building)
  752. {
  753. std::vector<std::shared_ptr<CComponent>> comps(1, std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(town->getFaction(), building)));
  754. LOCPLINT->showInfoDialog( town->town->buildings.find(building)->second->getDescriptionTranslated(), comps);
  755. }
  756. void CCastleBuildings::enterCastleGate()
  757. {
  758. if (!town->visitingHero)
  759. {
  760. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[126]);
  761. return;//only visiting hero can use castle gates
  762. }
  763. std::vector <int> availableTowns;
  764. std::vector<std::shared_ptr<IImage>> images;
  765. std::vector <const CGTownInstance*> Towns = LOCPLINT->localState->getOwnedTowns();
  766. for(auto & Town : Towns)
  767. {
  768. const CGTownInstance *t = Town;
  769. if (t->id != this->town->id && t->visitingHero == nullptr && //another town, empty and this is
  770. t->town->faction->getId() == town->town->faction->getId() && //the town of the same faction
  771. t->hasBuilt(BuildingSubID::CASTLE_GATE)) //and the town has a castle gate
  772. {
  773. availableTowns.push_back(t->id.getNum());//add to the list
  774. if(settings["general"]["enableUiEnhancements"].Bool())
  775. {
  776. auto image = GH.renderHandler().loadImage(AnimationPath::builtin("ITPA"), t->town->clientInfo.icons[t->hasFort()][false] + 2, 0, EImageBlitMode::OPAQUE);
  777. image->scaleTo(Point(35, 23));
  778. images.push_back(image);
  779. }
  780. }
  781. }
  782. auto gateIcon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, BuildingID::CASTLE_GATE);//will be deleted by selection window
  783. auto wnd = std::make_shared<CObjectListWindow>(availableTowns, gateIcon, CGI->generaltexth->jktexts[40],
  784. CGI->generaltexth->jktexts[41], std::bind (&CCastleInterface::castleTeleport, LOCPLINT->castleInt, _1), 0, images);
  785. wnd->onPopup = [availableTowns](int index) { CRClickPopup::createAndPush(LOCPLINT->cb->getObjInstance(ObjectInstanceID(availableTowns[index])), GH.getCursorPosition()); };
  786. GH.windows().pushWindow(wnd);
  787. }
  788. void CCastleBuildings::enterDwelling(int level)
  789. {
  790. if (level < 0 || level >= town->creatures.size() || town->creatures[level].second.empty())
  791. {
  792. assert(0);
  793. logGlobal->error("Attempt to enter into invalid dwelling of level %d in town %s (%s)", level, town->getNameTranslated(), town->town->faction->getNameTranslated());
  794. return;
  795. }
  796. auto recruitCb = [=](CreatureID id, int count)
  797. {
  798. LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level);
  799. };
  800. GH.windows().createAndPushWindow<CRecruitmentWindow>(town, level, town->getUpperArmy(), recruitCb, nullptr, -87);
  801. }
  802. void CCastleBuildings::enterToTheQuickRecruitmentWindow()
  803. {
  804. const auto beginIt = town->creatures.cbegin();
  805. const auto afterLastIt = town->creatures.size() > town->town->creatures.size()
  806. ? std::next(beginIt, town->town->creatures.size())
  807. : town->creatures.cend();
  808. const auto hasSomeoneToRecruit = std::any_of(beginIt, afterLastIt,
  809. [](const auto & creatureInfo) { return creatureInfo.first > 0; });
  810. if(hasSomeoneToRecruit)
  811. GH.windows().createAndPushWindow<QuickRecruitmentWindow>(town, pos);
  812. else
  813. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.townHall.noCreaturesToRecruit"), {});
  814. }
  815. void CCastleBuildings::enterFountain(const BuildingID & building, BuildingSubID::EBuildingSubID subID, BuildingID upgrades)
  816. {
  817. std::vector<std::shared_ptr<CComponent>> comps(1, std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(town->getFaction(), building)));
  818. std::string descr = town->town->buildings.find(building)->second->getDescriptionTranslated();
  819. std::string hasNotProduced;
  820. std::string hasProduced;
  821. hasNotProduced = CGI->generaltexth->allTexts[677];
  822. hasProduced = CGI->generaltexth->allTexts[678];
  823. bool isMysticPondOrItsUpgrade = subID == BuildingSubID::MYSTIC_POND
  824. || (upgrades != BuildingID::NONE
  825. && town->town->buildings.find(BuildingID(upgrades))->second->subId == BuildingSubID::MYSTIC_POND);
  826. if(upgrades != BuildingID::NONE)
  827. descr += "\n\n"+town->town->buildings.find(BuildingID(upgrades))->second->getDescriptionTranslated();
  828. if(isMysticPondOrItsUpgrade) //for vanila Rampart like towns
  829. {
  830. if(town->bonusValue.first == 0) //Mystic Pond produced nothing;
  831. descr += "\n\n" + hasNotProduced;
  832. else //Mystic Pond produced something;
  833. {
  834. descr += "\n\n" + hasProduced;
  835. boost::algorithm::replace_first(descr,"%s",CGI->generaltexth->restypes[town->bonusValue.first]);
  836. boost::algorithm::replace_first(descr,"%d",std::to_string(town->bonusValue.second));
  837. }
  838. }
  839. LOCPLINT->showInfoDialog(descr, comps);
  840. }
  841. void CCastleBuildings::enterMagesGuild()
  842. {
  843. const CGHeroInstance *hero = getHero();
  844. // hero doesn't have spellbok
  845. // or it is not our turn and we can't make actions
  846. if(hero && !hero->hasSpellbook() && LOCPLINT->makingTurn)
  847. {
  848. if(hero->isCampaignYog())
  849. {
  850. // "Yog has given up magic in all its forms..."
  851. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[736]);
  852. }
  853. else if(LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) < 500) //not enough gold to buy spellbook
  854. {
  855. openMagesGuild();
  856. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[213]);
  857. }
  858. else
  859. {
  860. CFunctionList<void()> onYes = [this](){ openMagesGuild(); };
  861. CFunctionList<void()> onNo = onYes;
  862. onYes += [hero](){ LOCPLINT->cb->buyArtifact(hero, ArtifactID::SPELLBOOK); };
  863. std::vector<std::shared_ptr<CComponent>> components(1, std::make_shared<CComponent>(ComponentType::ARTIFACT, ArtifactID(ArtifactID::SPELLBOOK)));
  864. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[214], onYes, onNo, components);
  865. }
  866. }
  867. else
  868. {
  869. openMagesGuild();
  870. }
  871. }
  872. void CCastleBuildings::enterTownHall()
  873. {
  874. if(town->visitingHero && town->visitingHero->hasArt(ArtifactID::GRAIL) &&
  875. !town->hasBuilt(BuildingID::GRAIL)) //hero has grail, but town does not have it
  876. {
  877. if(!vstd::contains(town->forbiddenBuildings, BuildingID::GRAIL))
  878. {
  879. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[597], //Do you wish this to be the permanent home of the Grail?
  880. [&](){ LOCPLINT->cb->buildBuilding(town, BuildingID::GRAIL); },
  881. [&](){ openTownHall(); });
  882. }
  883. else
  884. {
  885. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[673]);
  886. assert(GH.windows().topWindow<CInfoWindow>() != nullptr);
  887. GH.windows().topWindow<CInfoWindow>()->buttons[0]->addCallback(std::bind(&CCastleBuildings::openTownHall, this));
  888. }
  889. }
  890. else
  891. {
  892. openTownHall();
  893. }
  894. }
  895. void CCastleBuildings::openMagesGuild()
  896. {
  897. auto mageGuildBackground = LOCPLINT->castleInt->town->town->clientInfo.guildBackground;
  898. GH.windows().createAndPushWindow<CMageGuildScreen>(LOCPLINT->castleInt, mageGuildBackground);
  899. }
  900. void CCastleBuildings::openTownHall()
  901. {
  902. GH.windows().createAndPushWindow<CHallInterface>(town);
  903. }
  904. void CCastleBuildings::enterAnyThievesGuild()
  905. {
  906. std::vector<const CGTownInstance*> towns = LOCPLINT->cb->getTownsInfo(true);
  907. for(auto & ownedTown : towns)
  908. {
  909. if(ownedTown->hasBuilt(BuildingID::TAVERN))
  910. {
  911. LOCPLINT->showThievesGuildWindow(ownedTown);
  912. return;
  913. }
  914. }
  915. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.adventureMap.noTownWithTavern"));
  916. }
  917. void CCastleBuildings::enterBank(BuildingID building)
  918. {
  919. std::vector<std::shared_ptr<CComponent>> components;
  920. if(town->bonusValue.second > 0)
  921. {
  922. components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE_PER_DAY, GameResID(GameResID::GOLD), -500));
  923. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.townStructure.bank.payBack"), components);
  924. }
  925. else{
  926. components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, GameResID(GameResID::GOLD), 2500));
  927. LOCPLINT->showYesNoDialog(CGI->generaltexth->translate("vcmi.townStructure.bank.borrow"), [this, building](){ LOCPLINT->cb->visitTownBuilding(town, building); }, nullptr, components);
  928. }
  929. }
  930. void CCastleBuildings::enterAnyMarket()
  931. {
  932. if(town->hasBuilt(BuildingID::MARKETPLACE))
  933. {
  934. GH.windows().createAndPushWindow<CMarketWindow>(town, nullptr, nullptr, EMarketMode::RESOURCE_RESOURCE);
  935. return;
  936. }
  937. std::vector<const CGTownInstance*> towns = LOCPLINT->cb->getTownsInfo(true);
  938. for(auto & town : towns)
  939. {
  940. if(town->hasBuilt(BuildingID::MARKETPLACE))
  941. {
  942. GH.windows().createAndPushWindow<CMarketWindow>(town, nullptr, nullptr, EMarketMode::RESOURCE_RESOURCE);
  943. return;
  944. }
  945. }
  946. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.adventureMap.noTownWithMarket"));
  947. }
  948. CCreaInfo::CCreaInfo(Point position, const CGTownInstance * Town, int Level, bool compact, bool _showAvailable):
  949. town(Town),
  950. level(Level),
  951. showAvailable(_showAvailable)
  952. {
  953. OBJECT_CONSTRUCTION;
  954. pos += position;
  955. if(town->creatures.size() <= level || town->creatures[level].second.empty())
  956. {
  957. level = -1;
  958. return;//No creature
  959. }
  960. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  961. creature = town->creatures[level].second.back();
  962. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature.toEntity(VLC)->getIconIndex(), 0, 8, 0);
  963. std::string value;
  964. if(showAvailable)
  965. value = std::to_string(town->creatures[level].first);
  966. else
  967. value = std::string("+") + std::to_string(town->creatureGrowth(level));
  968. if(compact)
  969. {
  970. label = std::make_shared<CLabel>(40, 32, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, value);
  971. pos.x += 8;
  972. pos.w = 32;
  973. pos.h = 32;
  974. }
  975. else
  976. {
  977. label = std::make_shared<CLabel>(24, 40, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, value);
  978. pos.w = 48;
  979. pos.h = 48;
  980. }
  981. }
  982. void CCreaInfo::update()
  983. {
  984. if(label)
  985. {
  986. std::string value;
  987. if(showAvailable)
  988. value = std::to_string(town->creatures[level].first);
  989. else
  990. value = std::string("+") + std::to_string(town->creatureGrowth(level));
  991. if(value != label->getText())
  992. label->setText(value);
  993. }
  994. }
  995. void CCreaInfo::hover(bool on)
  996. {
  997. MetaString message;
  998. message.appendTextID("core.genrltxt.588");
  999. message.replaceNameSingular(creature);
  1000. if(on)
  1001. {
  1002. GH.statusbar()->write(message.toString());
  1003. }
  1004. else
  1005. {
  1006. GH.statusbar()->clearIfMatching(message.toString());
  1007. }
  1008. }
  1009. void CCreaInfo::clickPressed(const Point & cursorPosition)
  1010. {
  1011. int offset = LOCPLINT->castleInt? (-87) : 0;
  1012. auto recruitCb = [=](CreatureID id, int count)
  1013. {
  1014. LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level);
  1015. };
  1016. GH.windows().createAndPushWindow<CRecruitmentWindow>(town, level, town->getUpperArmy(), recruitCb, nullptr, offset);
  1017. }
  1018. std::string CCreaInfo::genGrowthText()
  1019. {
  1020. GrowthInfo gi = town->getGrowthInfo(level);
  1021. MetaString descr;
  1022. descr.appendTextID("core.genrltxt.589");
  1023. descr.replaceNameSingular(creature);
  1024. descr.replaceNumber(gi.totalGrowth());
  1025. for(const GrowthInfo::Entry & entry : gi.entries)
  1026. {
  1027. descr.appendEOL();
  1028. descr.appendRawString(entry.description);
  1029. }
  1030. return descr.toString();
  1031. }
  1032. void CCreaInfo::showPopupWindow(const Point & cursorPosition)
  1033. {
  1034. if (showAvailable)
  1035. GH.windows().createAndPushWindow<CDwellingInfoBox>(GH.screenDimensions().x / 2, GH.screenDimensions().y / 2, town, level);
  1036. else
  1037. CRClickPopup::createAndPush(genGrowthText(), std::make_shared<CComponent>(ComponentType::CREATURE, creature));
  1038. }
  1039. bool CCreaInfo::getShowAvailable()
  1040. {
  1041. return showAvailable;
  1042. }
  1043. CTownInfo::CTownInfo(int posX, int posY, const CGTownInstance * Town, bool townHall)
  1044. : town(Town),
  1045. building(nullptr)
  1046. {
  1047. OBJECT_CONSTRUCTION;
  1048. addUsedEvents(SHOW_POPUP | HOVER);
  1049. pos.x += posX;
  1050. pos.y += posY;
  1051. int buildID;
  1052. if(townHall)
  1053. {
  1054. buildID = 10 + town->hallLevel();
  1055. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("ITMTL.DEF"), town->hallLevel());
  1056. }
  1057. else
  1058. {
  1059. buildID = 6 + town->fortLevel();
  1060. if(buildID == 6)
  1061. return;//FIXME: suspicious statement, fix or comment
  1062. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("ITMCL.DEF"), town->fortLevel()-1);
  1063. }
  1064. building = town->town->buildings.at(BuildingID(buildID));
  1065. pos = picture->pos;
  1066. }
  1067. void CTownInfo::hover(bool on)
  1068. {
  1069. if(on)
  1070. {
  1071. if(building )
  1072. GH.statusbar()->write(building->getNameTranslated());
  1073. }
  1074. else
  1075. {
  1076. GH.statusbar()->clear();
  1077. }
  1078. }
  1079. void CTownInfo::showPopupWindow(const Point & cursorPosition)
  1080. {
  1081. if(building)
  1082. {
  1083. auto c = std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(building->town->faction->getId(), building->bid));
  1084. CRClickPopup::createAndPush(CInfoWindow::genText(building->getNameTranslated(), building->getDescriptionTranslated()), c);
  1085. }
  1086. }
  1087. CCastleInterface::CCastleInterface(const CGTownInstance * Town, const CGTownInstance * from):
  1088. CWindowObject(PLAYER_COLORED | BORDERED),
  1089. town(Town)
  1090. {
  1091. OBJECT_CONSTRUCTION;
  1092. LOCPLINT->castleInt = this;
  1093. addUsedEvents(KEYBOARD);
  1094. builds = std::make_shared<CCastleBuildings>(town);
  1095. panel = std::make_shared<CPicture>(ImagePath::builtin("TOWNSCRN"), 0, builds->pos.h);
  1096. panel->setPlayerColor(LOCPLINT->playerID);
  1097. pos.w = panel->pos.w;
  1098. pos.h = builds->pos.h + panel->pos.h;
  1099. center();
  1100. updateShadow();
  1101. garr = std::make_shared<CGarrisonInt>(Point(305, 387), 4, Point(0,96), town->getUpperArmy(), town->visitingHero);
  1102. garr->setRedrawParent(true);
  1103. heroes = std::make_shared<HeroSlots>(town, Point(241, 387), Point(241, 483), garr, true);
  1104. title = std::make_shared<CLabel>(85, 387, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, town->getNameTranslated());
  1105. income = std::make_shared<CLabel>(195, 443, FONT_SMALL, ETextAlignment::CENTER);
  1106. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("ITPT"), 0, 0, 15, 387);
  1107. exit = std::make_shared<CButton>(Point(744, 544), AnimationPath::builtin("TSBTNS"), CButton::tooltip(CGI->generaltexth->tcommands[8]), [&](){close();}, EShortcut::GLOBAL_RETURN);
  1108. exit->setImageOrder(4, 5, 6, 7);
  1109. 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);
  1110. garr->addSplitBtn(split);
  1111. Rect barRect(9, 182, 732, 18);
  1112. auto statusbarBackground = std::make_shared<CPicture>(panel->getSurface(), barRect, 9, 555);
  1113. statusbar = CGStatusBar::create(statusbarBackground);
  1114. resdatabar = std::make_shared<CResDataBar>(ImagePath::builtin("ARESBAR"), 3, 575, 37, 3, 84, 78);
  1115. townlist = std::make_shared<CTownList>(3, Rect(Point(743, 414), Point(48, 128)), Point(1,16), Point(0, 32), LOCPLINT->localState->getOwnedTowns().size() );
  1116. townlist->setScrollUpButton( std::make_shared<CButton>( Point(744, 414), AnimationPath::builtin("IAM014"), CButton::tooltipLocalized("core.help.306"), 0));
  1117. townlist->setScrollDownButton( std::make_shared<CButton>( Point(744, 526), AnimationPath::builtin("IAM015"), CButton::tooltipLocalized("core.help.307"), 0));
  1118. if(from)
  1119. townlist->select(from);
  1120. townlist->select(town); //this will scroll list to select current town
  1121. townlist->onSelect = std::bind(&CCastleInterface::townChange, this);
  1122. recreateIcons();
  1123. if (!from)
  1124. adventureInt->onAudioPaused();
  1125. CCS->musich->playMusicFromSet("faction", town->town->faction->getJsonKey(), true, false);
  1126. }
  1127. CCastleInterface::~CCastleInterface()
  1128. {
  1129. // resume map audio if:
  1130. // adventureInt exists (may happen on exiting client with open castle interface)
  1131. // castleInt has not been replaced (happens on switching between towns inside castle interface)
  1132. if (adventureInt && LOCPLINT->castleInt == this)
  1133. adventureInt->onAudioResumed();
  1134. if(LOCPLINT->castleInt == this)
  1135. LOCPLINT->castleInt = nullptr;
  1136. }
  1137. void CCastleInterface::updateGarrisons()
  1138. {
  1139. garr->setArmy(town->getUpperArmy(), EGarrisonType::UPPER);
  1140. garr->setArmy(town->visitingHero, EGarrisonType::LOWER);
  1141. garr->recreateSlots();
  1142. heroes->update();
  1143. redraw();
  1144. }
  1145. bool CCastleInterface::holdsGarrison(const CArmedInstance * army)
  1146. {
  1147. return army == town || army == town->getUpperArmy() || army == town->visitingHero;
  1148. }
  1149. void CCastleInterface::close()
  1150. {
  1151. if(town->tempOwner == LOCPLINT->playerID) //we may have opened window for an allied town
  1152. {
  1153. if(town->visitingHero && town->visitingHero->tempOwner == LOCPLINT->playerID)
  1154. LOCPLINT->localState->setSelection(town->visitingHero);
  1155. else
  1156. LOCPLINT->localState->setSelection(town);
  1157. }
  1158. CWindowObject::close();
  1159. }
  1160. void CCastleInterface::castleTeleport(int where)
  1161. {
  1162. const CGTownInstance * dest = LOCPLINT->cb->getTown(ObjectInstanceID(where));
  1163. LOCPLINT->localState->setSelection(town->visitingHero);//according to assert(ho == adventureInt->selection) in the eraseCurrentPathOf
  1164. LOCPLINT->cb->teleportHero(town->visitingHero, dest);
  1165. LOCPLINT->localState->erasePath(town->visitingHero);
  1166. }
  1167. void CCastleInterface::townChange()
  1168. {
  1169. //TODO: do not recreate window
  1170. const CGTownInstance * dest = LOCPLINT->localState->getOwnedTown(townlist->getSelectedIndex());
  1171. const CGTownInstance * town = this->town;// "this" is going to be deleted
  1172. if ( dest == town )
  1173. return;
  1174. close();
  1175. GH.windows().createAndPushWindow<CCastleInterface>(dest, town);
  1176. }
  1177. void CCastleInterface::addBuilding(BuildingID bid)
  1178. {
  1179. deactivate();
  1180. builds->addBuilding(bid);
  1181. recreateIcons();
  1182. activate();
  1183. redraw();
  1184. }
  1185. void CCastleInterface::removeBuilding(BuildingID bid)
  1186. {
  1187. deactivate();
  1188. builds->removeBuilding(bid);
  1189. recreateIcons();
  1190. activate();
  1191. redraw();
  1192. }
  1193. void CCastleInterface::recreateIcons()
  1194. {
  1195. OBJECT_CONSTRUCTION;
  1196. size_t iconIndex = town->town->clientInfo.icons[town->hasFort()][town->built >= LOCPLINT->cb->getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP)];
  1197. icon->setFrame(iconIndex);
  1198. TResources townIncome = town->dailyIncome();
  1199. income->setText(std::to_string(townIncome[EGameResID::GOLD]));
  1200. hall = std::make_shared<CTownInfo>(80, 413, town, true);
  1201. fort = std::make_shared<CTownInfo>(122, 413, town, false);
  1202. fastTownHall = std::make_shared<CButton>(Point(80, 413), AnimationPath::builtin("castleInterfaceQuickAccess"), CButton::tooltip(), [this](){ builds->enterTownHall(); }, EShortcut::TOWN_OPEN_HALL);
  1203. fastTownHall->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("ITMTL"), town->hallLevel()));
  1204. int imageIndex = town->fortLevel() == CGTownInstance::EFortLevel::NONE ? 3 : town->fortLevel() - 1;
  1205. fastArmyPurchase = std::make_shared<CButton>(Point(122, 413), AnimationPath::builtin("castleInterfaceQuickAccess"), CButton::tooltip(), [this](){ builds->enterToTheQuickRecruitmentWindow(); }, EShortcut::TOWN_OPEN_RECRUITMENT);
  1206. fastArmyPurchase->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("itmcl"), imageIndex));
  1207. fastMarket = std::make_shared<LRClickableArea>(Rect(163, 410, 64, 42), [this]() { builds->enterAnyMarket(); });
  1208. fastTavern = std::make_shared<LRClickableArea>(Rect(15, 387, 58, 64), [&]()
  1209. {
  1210. if(town->hasBuilt(BuildingID::TAVERN))
  1211. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  1212. }, [this]{
  1213. if(!town->town->faction->getDescriptionTranslated().empty())
  1214. CRClickPopup::createAndPush(town->town->faction->getDescriptionTranslated());
  1215. });
  1216. creainfo.clear();
  1217. bool compactCreatureInfo = useCompactCreatureBox();
  1218. bool useAvailableCreaturesForLabel = useAvailableAmountAsCreatureLabel();
  1219. for(size_t i=0; i<4; i++)
  1220. creainfo.push_back(std::make_shared<CCreaInfo>(Point(14 + 55 * (int)i, 459), town, (int)i, compactCreatureInfo, useAvailableCreaturesForLabel));
  1221. for(size_t i=0; i<4; i++)
  1222. creainfo.push_back(std::make_shared<CCreaInfo>(Point(14 + 55 * (int)i, 507), town, (int)i + 4, compactCreatureInfo, useAvailableCreaturesForLabel));
  1223. }
  1224. void CCastleInterface::keyPressed(EShortcut key)
  1225. {
  1226. switch(key)
  1227. {
  1228. case EShortcut::MOVE_UP:
  1229. townlist->selectPrev();
  1230. break;
  1231. case EShortcut::MOVE_DOWN:
  1232. townlist->selectNext();
  1233. break;
  1234. case EShortcut::TOWN_OPEN_FORT:
  1235. GH.windows().createAndPushWindow<CFortScreen>(town);
  1236. break;
  1237. case EShortcut::TOWN_OPEN_MARKET:
  1238. builds->enterAnyMarket();
  1239. break;
  1240. case EShortcut::TOWN_OPEN_MAGE_GUILD:
  1241. if(town->hasBuilt(BuildingID::MAGES_GUILD_1))
  1242. builds->enterMagesGuild();
  1243. break;
  1244. case EShortcut::TOWN_OPEN_THIEVES_GUILD:
  1245. break;
  1246. case EShortcut::TOWN_OPEN_HERO_EXCHANGE:
  1247. if (town->visitingHero && town->garrisonHero)
  1248. LOCPLINT->showHeroExchange(town->visitingHero->id, town->garrisonHero->id);
  1249. break;
  1250. case EShortcut::TOWN_OPEN_HERO:
  1251. if (town->visitingHero)
  1252. LOCPLINT->openHeroWindow(town->visitingHero);
  1253. else if (town->garrisonHero)
  1254. LOCPLINT->openHeroWindow(town->garrisonHero);
  1255. break;
  1256. case EShortcut::TOWN_OPEN_VISITING_HERO:
  1257. if (town->visitingHero)
  1258. LOCPLINT->openHeroWindow(town->visitingHero);
  1259. break;
  1260. case EShortcut::TOWN_OPEN_GARRISONED_HERO:
  1261. if (town->garrisonHero)
  1262. LOCPLINT->openHeroWindow(town->garrisonHero);
  1263. break;
  1264. case EShortcut::TOWN_SWAP_ARMIES:
  1265. heroes->swapArmies();
  1266. break;
  1267. case EShortcut::TOWN_OPEN_TAVERN:
  1268. if(town->hasBuilt(BuildingID::TAVERN))
  1269. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  1270. break;
  1271. default:
  1272. break;
  1273. }
  1274. }
  1275. void CCastleInterface::creaturesChangedEventHandler()
  1276. {
  1277. for(auto creatureInfoBox : creainfo)
  1278. {
  1279. if(creatureInfoBox->getShowAvailable())
  1280. {
  1281. creatureInfoBox->update();
  1282. }
  1283. }
  1284. }
  1285. CHallInterface::CBuildingBox::CBuildingBox(int x, int y, const CGTownInstance * Town, const CBuilding * Building):
  1286. town(Town),
  1287. building(Building)
  1288. {
  1289. OBJECT_CONSTRUCTION;
  1290. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1291. pos.x += x;
  1292. pos.y += y;
  1293. pos.w = 154;
  1294. pos.h = 92;
  1295. state = LOCPLINT->cb->canBuildStructure(town, building->bid);
  1296. constexpr std::array panelIndex =
  1297. {
  1298. 3, 3, 3, 0, 0, 2, 2, 1, 2, 2, 3, 3
  1299. };
  1300. constexpr std::array iconIndex =
  1301. {
  1302. -1, -1, -1, 0, 0, 1, 2, -1, 1, 1, -1, -1
  1303. };
  1304. icon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, building->bid, 0, 2, 2);
  1305. header = std::make_shared<CAnimImage>(AnimationPath::builtin("TPTHBAR"), panelIndex[static_cast<int>(state)], 0, 1, 73);
  1306. if(iconIndex[static_cast<int>(state)] >=0)
  1307. mark = std::make_shared<CAnimImage>(AnimationPath::builtin("TPTHCHK"), iconIndex[static_cast<int>(state)], 0, 136, 56);
  1308. name = std::make_shared<CLabel>(78, 81, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, building->getNameTranslated(), 150);
  1309. //todo: add support for all possible states
  1310. if(state >= EBuildingState::BUILDING_ERROR)
  1311. state = EBuildingState::FORBIDDEN;
  1312. }
  1313. void CHallInterface::CBuildingBox::hover(bool on)
  1314. {
  1315. if(on)
  1316. {
  1317. std::string toPrint;
  1318. if(state==EBuildingState::PREREQUIRES || state == EBuildingState::MISSING_BASE)
  1319. toPrint = CGI->generaltexth->hcommands[5];
  1320. else if(state==EBuildingState::CANT_BUILD_TODAY)
  1321. toPrint = CGI->generaltexth->allTexts[223];
  1322. else
  1323. toPrint = CGI->generaltexth->hcommands[static_cast<int>(state)];
  1324. boost::algorithm::replace_first(toPrint,"%s",building->getNameTranslated());
  1325. GH.statusbar()->write(toPrint);
  1326. }
  1327. else
  1328. {
  1329. GH.statusbar()->clear();
  1330. }
  1331. }
  1332. void CHallInterface::CBuildingBox::clickPressed(const Point & cursorPosition)
  1333. {
  1334. GH.windows().createAndPushWindow<CBuildWindow>(town,building,state,0);
  1335. }
  1336. void CHallInterface::CBuildingBox::showPopupWindow(const Point & cursorPosition)
  1337. {
  1338. GH.windows().createAndPushWindow<CBuildWindow>(town,building,state,1);
  1339. }
  1340. CHallInterface::CHallInterface(const CGTownInstance * Town):
  1341. CWindowObject(PLAYER_COLORED | BORDERED, Town->town->clientInfo.hallBackground),
  1342. town(Town)
  1343. {
  1344. OBJECT_CONSTRUCTION;
  1345. resdatabar = std::make_shared<CMinorResDataBar>();
  1346. resdatabar->moveBy(pos.topLeft(), true);
  1347. Rect barRect(5, 556, 740, 18);
  1348. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 5, 556);
  1349. statusbar = CGStatusBar::create(statusbarBackground);
  1350. title = std::make_shared<CLabel>(399, 12, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, town->town->buildings.at(BuildingID(town->hallLevel()+BuildingID::VILLAGE_HALL))->getNameTranslated());
  1351. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1.DEF"), CButton::tooltip(CGI->generaltexth->hcommands[8]), [&](){close();}, EShortcut::GLOBAL_RETURN);
  1352. auto & boxList = town->town->clientInfo.hallSlots;
  1353. boxes.resize(boxList.size());
  1354. for(size_t row=0; row<boxList.size(); row++) //for each row
  1355. {
  1356. for(size_t col=0; col<boxList[row].size(); col++) //for each box
  1357. {
  1358. const CBuilding * building = nullptr;
  1359. for(auto & buildingID : boxList[row][col])//we are looking for the first not built structure
  1360. {
  1361. if (!buildingID.hasValue())
  1362. {
  1363. logMod->warn("Invalid building ID found in hallSlots of town '%s'", town->town->faction->getJsonKey() );
  1364. continue;
  1365. }
  1366. const CBuilding * current = town->town->buildings.at(buildingID);
  1367. if(town->hasBuilt(buildingID))
  1368. {
  1369. building = current;
  1370. }
  1371. else
  1372. {
  1373. if(current->mode == CBuilding::BUILD_NORMAL)
  1374. {
  1375. building = current;
  1376. break;
  1377. }
  1378. }
  1379. }
  1380. int posX = pos.w/2 - (int)boxList[row].size()*154/2 - ((int)boxList[row].size()-1)*20 + 194*(int)col;
  1381. int posY = 35 + 104*(int)row;
  1382. if(building)
  1383. boxes[row].push_back(std::make_shared<CBuildingBox>(posX, posY, town, building));
  1384. }
  1385. }
  1386. }
  1387. CBuildWindow::CBuildWindow(const CGTownInstance *Town, const CBuilding * Building, EBuildingState state, bool rightClick):
  1388. CWindowObject(PLAYER_COLORED | (rightClick ? RCLICK_POPUP : 0), ImagePath::builtin("TPUBUILD")),
  1389. town(Town),
  1390. building(Building)
  1391. {
  1392. OBJECT_CONSTRUCTION;
  1393. icon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, building->bid, 0, 125, 50);
  1394. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26);
  1395. statusbar = CGStatusBar::create(statusbarBackground);
  1396. MetaString nameString;
  1397. nameString.appendTextID("core.hallinfo.7");
  1398. nameString.replaceTextID(building->getNameTextID());
  1399. name = std::make_shared<CLabel>(197, 30, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, nameString.toString());
  1400. description = std::make_shared<CTextBox>(building->getDescriptionTranslated(), Rect(33, 135, 329, 67), 0, FONT_MEDIUM, ETextAlignment::CENTER);
  1401. stateText = std::make_shared<CTextBox>(getTextForState(state), Rect(33, 216, 329, 67), 0, FONT_SMALL, ETextAlignment::CENTER);
  1402. //Create components for all required resources
  1403. std::vector<std::shared_ptr<CComponent>> components;
  1404. for(GameResID i : GameResID::ALL_RESOURCES())
  1405. {
  1406. if(building->resources[i])
  1407. {
  1408. MetaString message;
  1409. int resourceAmount = LOCPLINT->cb->getResourceAmount(i);
  1410. bool canAfford = resourceAmount >= building->resources[i];
  1411. if(!canAfford && state != EBuildingState::ALREADY_PRESENT && settings["general"]["enableUiEnhancements"].Bool())
  1412. {
  1413. message.appendRawString("{H3Red|%d}/%d");
  1414. message.replaceNumber(resourceAmount);
  1415. }
  1416. else
  1417. message.appendRawString("%d");
  1418. message.replaceNumber(building->resources[i]);
  1419. components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, i, message.toString(), CComponent::small));
  1420. }
  1421. }
  1422. cost = std::make_shared<CComponentBox>(components, Rect(25, 300, pos.w - 50, 130));
  1423. if(!rightClick)
  1424. { //normal window
  1425. MetaString tooltipYes;
  1426. tooltipYes.appendTextID("core.genrltxt.595");
  1427. tooltipYes.replaceTextID(building->getNameTextID());
  1428. MetaString tooltipNo;
  1429. tooltipNo.appendTextID("core.genrltxt.596");
  1430. tooltipNo.replaceTextID(building->getNameTextID());
  1431. buy = std::make_shared<CButton>(Point(45, 446), AnimationPath::builtin("IBUY30"), CButton::tooltip(tooltipYes.toString()), [&](){ buyFunc(); }, EShortcut::GLOBAL_ACCEPT);
  1432. buy->setBorderColor(Colors::METALLIC_GOLD);
  1433. buy->block(state != EBuildingState::ALLOWED || LOCPLINT->playerID != town->tempOwner || !LOCPLINT->makingTurn);
  1434. cancel = std::make_shared<CButton>(Point(290, 445), AnimationPath::builtin("ICANCEL"), CButton::tooltip(tooltipNo.toString()), [&](){ close();}, EShortcut::GLOBAL_CANCEL);
  1435. cancel->setBorderColor(Colors::METALLIC_GOLD);
  1436. }
  1437. }
  1438. void CBuildWindow::buyFunc()
  1439. {
  1440. LOCPLINT->cb->buildBuilding(town,building->bid);
  1441. GH.windows().popWindows(2); //we - build window and hall screen
  1442. }
  1443. std::string CBuildWindow::getTextForState(EBuildingState state)
  1444. {
  1445. std::string ret;
  1446. if(state < EBuildingState::ALLOWED)
  1447. ret = CGI->generaltexth->hcommands[static_cast<int>(state)];
  1448. switch (state)
  1449. {
  1450. case EBuildingState::ALREADY_PRESENT:
  1451. case EBuildingState::CANT_BUILD_TODAY:
  1452. case EBuildingState::NO_RESOURCES:
  1453. ret.replace(ret.find_first_of("%s"), 2, building->getNameTranslated());
  1454. break;
  1455. case EBuildingState::ALLOWED:
  1456. return CGI->generaltexth->allTexts[219]; //all prereq. are met
  1457. case EBuildingState::PREREQUIRES:
  1458. {
  1459. auto toStr = [&](const BuildingID build) -> std::string
  1460. {
  1461. return town->town->buildings.at(build)->getNameTranslated();
  1462. };
  1463. ret = CGI->generaltexth->allTexts[52];
  1464. ret += "\n" + town->genBuildingRequirements(building->bid).toString(toStr);
  1465. break;
  1466. }
  1467. case EBuildingState::MISSING_BASE:
  1468. {
  1469. std::string msg = CGI->generaltexth->translate("vcmi.townHall.missingBase");
  1470. ret = boost::str(boost::format(msg) % town->town->buildings.at(building->upgrade)->getNameTranslated());
  1471. break;
  1472. }
  1473. }
  1474. return ret;
  1475. }
  1476. LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int min, int max)
  1477. {
  1478. OBJECT_CONSTRUCTION;
  1479. pos.x+=size.x;
  1480. pos.y+=size.y;
  1481. pos.w = size.w;
  1482. pos.h = size.h;
  1483. init(name, descr, min, max);
  1484. }
  1485. LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int val)
  1486. {
  1487. OBJECT_CONSTRUCTION;
  1488. pos.x+=size.x;
  1489. pos.y+=size.y;
  1490. pos.w = size.w;
  1491. pos.h = size.h;
  1492. init(name, descr, val, val);
  1493. }
  1494. void LabeledValue::init(std::string nameText, std::string descr, int min, int max)
  1495. {
  1496. addUsedEvents(HOVER);
  1497. hoverText = descr;
  1498. std::string valueText;
  1499. if(min && max)
  1500. {
  1501. valueText = std::to_string(min);
  1502. if(min != max)
  1503. valueText += '-' + std::to_string(max);
  1504. }
  1505. name = std::make_shared<CLabel>(3, 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, nameText);
  1506. value = std::make_shared<CLabel>(pos.w-3, pos.h-2, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, valueText);
  1507. }
  1508. void LabeledValue::hover(bool on)
  1509. {
  1510. if(on)
  1511. {
  1512. GH.statusbar()->write(hoverText);
  1513. }
  1514. else
  1515. {
  1516. GH.statusbar()->clear();
  1517. }
  1518. }
  1519. CFortScreen::CFortScreen(const CGTownInstance * town):
  1520. CWindowObject(PLAYER_COLORED | BORDERED, getBgName(town))
  1521. {
  1522. OBJECT_CONSTRUCTION;
  1523. ui32 fortSize = static_cast<ui32>(town->creatures.size());
  1524. if(fortSize > town->town->creatures.size() && town->creatures.back().second.empty())
  1525. fortSize--;
  1526. const CBuilding * fortBuilding = town->town->buildings.at(BuildingID(town->fortLevel()+6));
  1527. title = std::make_shared<CLabel>(400, 12, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE, fortBuilding->getNameTranslated());
  1528. std::string text = boost::str(boost::format(CGI->generaltexth->fcommands[6]) % fortBuilding->getNameTranslated());
  1529. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1"), CButton::tooltip(text), [&](){ close(); }, EShortcut::GLOBAL_RETURN);
  1530. std::vector<Point> positions =
  1531. {
  1532. Point(10, 22), Point(404, 22),
  1533. Point(10, 155), Point(404,155),
  1534. Point(10, 288), Point(404,288)
  1535. };
  1536. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1537. {
  1538. positions.push_back(Point(10, 421));
  1539. positions.push_back(Point(404,421));
  1540. }
  1541. else
  1542. {
  1543. positions.push_back(Point(206,421));
  1544. }
  1545. for(ui32 i=0; i<fortSize; i++)
  1546. {
  1547. BuildingID buildingID;
  1548. if(fortSize == town->town->creatures.size())
  1549. {
  1550. BuildingID dwelling = BuildingID::getDwellingFromLevel(i, 1);
  1551. if(town->hasBuilt(dwelling))
  1552. buildingID = BuildingID(BuildingID::getDwellingFromLevel(i, 1));
  1553. else
  1554. buildingID = BuildingID(BuildingID::getDwellingFromLevel(i, 0));
  1555. }
  1556. else
  1557. {
  1558. buildingID = BuildingID::SPECIAL_3;
  1559. }
  1560. recAreas.push_back(std::make_shared<RecruitArea>(positions[i].x, positions[i].y, town, i));
  1561. }
  1562. resdatabar = std::make_shared<CMinorResDataBar>();
  1563. resdatabar->moveBy(pos.topLeft(), true);
  1564. Rect barRect(4, 554, 740, 18);
  1565. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 4, 554);
  1566. statusbar = CGStatusBar::create(statusbarBackground);
  1567. }
  1568. ImagePath CFortScreen::getBgName(const CGTownInstance * town)
  1569. {
  1570. ui32 fortSize = static_cast<ui32>(town->creatures.size());
  1571. if(fortSize > town->town->creatures.size() && town->creatures.back().second.empty())
  1572. fortSize--;
  1573. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1574. return ImagePath::builtin("TPCASTL8");
  1575. else
  1576. return ImagePath::builtin("TPCASTL7");
  1577. }
  1578. void CFortScreen::creaturesChangedEventHandler()
  1579. {
  1580. for(auto & elem : recAreas)
  1581. elem->creaturesChangedEventHandler();
  1582. LOCPLINT->castleInt->creaturesChangedEventHandler();
  1583. }
  1584. CFortScreen::RecruitArea::RecruitArea(int posX, int posY, const CGTownInstance * Town, int Level):
  1585. town(Town),
  1586. level(Level),
  1587. availableCount(nullptr)
  1588. {
  1589. OBJECT_CONSTRUCTION;
  1590. pos.x +=posX;
  1591. pos.y +=posY;
  1592. pos.w = 386;
  1593. pos.h = 126;
  1594. if(!town->creatures[level].second.empty())
  1595. addUsedEvents(LCLICK | HOVER);//Activate only if dwelling is present
  1596. addUsedEvents(SHOW_POPUP);
  1597. icons = std::make_shared<CPicture>(ImagePath::builtin("TPCAINFO"), 261, 3);
  1598. if(getMyBuilding() != nullptr)
  1599. {
  1600. buildingIcon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, getMyBuilding()->bid, 0, 4, 21);
  1601. buildingName = std::make_shared<CLabel>(78, 101, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyBuilding()->getNameTranslated(), 152);
  1602. if(town->hasBuilt(getMyBuilding()->bid))
  1603. {
  1604. ui32 available = town->creatures[level].first;
  1605. std::string availableText = CGI->generaltexth->allTexts[217]+ std::to_string(available);
  1606. availableCount = std::make_shared<CLabel>(78, 119, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, availableText);
  1607. }
  1608. }
  1609. if(getMyCreature() != nullptr)
  1610. {
  1611. hoverText = boost::str(boost::format(CGI->generaltexth->tcommands[21]) % getMyCreature()->getNamePluralTranslated());
  1612. new CCreaturePic(159, 4, getMyCreature(), false);
  1613. new CLabel(78, 11, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyCreature()->getNamePluralTranslated(), 152);
  1614. Rect sizes(287, 4, 96, 18);
  1615. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[190], CGI->generaltexth->fcommands[0], getMyCreature()->getAttack(false)));
  1616. sizes.y+=20;
  1617. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[191], CGI->generaltexth->fcommands[1], getMyCreature()->getDefense(false)));
  1618. sizes.y+=21;
  1619. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[199], CGI->generaltexth->fcommands[2], getMyCreature()->getMinDamage(false), getMyCreature()->getMaxDamage(false)));
  1620. sizes.y+=20;
  1621. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[388], CGI->generaltexth->fcommands[3], getMyCreature()->getMaxHealth()));
  1622. sizes.y+=21;
  1623. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[193], CGI->generaltexth->fcommands[4], getMyCreature()->valOfBonuses(BonusType::STACKS_SPEED)));
  1624. sizes.y+=20;
  1625. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[194], CGI->generaltexth->fcommands[5], town->creatureGrowth(level)));
  1626. }
  1627. }
  1628. const CCreature * CFortScreen::RecruitArea::getMyCreature()
  1629. {
  1630. if(!town->creatures.at(level).second.empty()) // built
  1631. return town->creatures.at(level).second.back().toCreature();
  1632. if(!town->town->creatures.at(level).empty()) // there are creatures on this level
  1633. return town->town->creatures.at(level).front().toCreature();
  1634. return nullptr;
  1635. }
  1636. const CBuilding * CFortScreen::RecruitArea::getMyBuilding()
  1637. {
  1638. BuildingID myID = BuildingID(BuildingID::getDwellingFromLevel(level, 0));
  1639. if (level == town->town->creatures.size())
  1640. return town->town->getSpecialBuilding(BuildingSubID::PORTAL_OF_SUMMONING);
  1641. if (!town->town->buildings.count(myID))
  1642. return nullptr;
  1643. const CBuilding * build = town->town->buildings.at(myID);
  1644. while (town->town->buildings.count(myID))
  1645. {
  1646. if (town->hasBuilt(myID))
  1647. build = town->town->buildings.at(myID);
  1648. BuildingID::advanceDwelling(myID);
  1649. }
  1650. return build;
  1651. }
  1652. void CFortScreen::RecruitArea::hover(bool on)
  1653. {
  1654. if(on)
  1655. GH.statusbar()->write(hoverText);
  1656. else
  1657. GH.statusbar()->clear();
  1658. }
  1659. void CFortScreen::RecruitArea::creaturesChangedEventHandler()
  1660. {
  1661. if(availableCount)
  1662. {
  1663. std::string availableText = CGI->generaltexth->allTexts[217] + std::to_string(town->creatures[level].first);
  1664. availableCount->setText(availableText);
  1665. }
  1666. }
  1667. void CFortScreen::RecruitArea::clickPressed(const Point & cursorPosition)
  1668. {
  1669. LOCPLINT->castleInt->builds->enterDwelling(level);
  1670. }
  1671. void CFortScreen::RecruitArea::showPopupWindow(const Point & cursorPosition)
  1672. {
  1673. if (getMyCreature() != nullptr)
  1674. GH.windows().createAndPushWindow<CStackWindow>(getMyCreature(), true);
  1675. }
  1676. CMageGuildScreen::CMageGuildScreen(CCastleInterface * owner, const ImagePath & imagename)
  1677. : CWindowObject(BORDERED, imagename)
  1678. {
  1679. OBJECT_CONSTRUCTION;
  1680. window = std::make_shared<CPicture>(owner->town->town->clientInfo.guildWindow, 332, 76);
  1681. resdatabar = std::make_shared<CMinorResDataBar>();
  1682. resdatabar->moveBy(pos.topLeft(), true);
  1683. Rect barRect(7, 556, 737, 18);
  1684. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 7, 556);
  1685. statusbar = CGStatusBar::create(statusbarBackground);
  1686. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1.DEF"), CButton::tooltip(CGI->generaltexth->allTexts[593]), [&](){ close(); }, EShortcut::GLOBAL_RETURN);
  1687. static const std::vector<std::vector<Point> > positions =
  1688. {
  1689. {Point(222,445), Point(312,445), Point(402,445), Point(520,445), Point(610,445), Point(700,445)},
  1690. {Point(48,53), Point(48,147), Point(48,241), Point(48,335), Point(48,429)},
  1691. {Point(570,82), Point(672,82), Point(570,157), Point(672,157)},
  1692. {Point(183,42), Point(183,148), Point(183,253)},
  1693. {Point(491,325), Point(591,325)}
  1694. };
  1695. for(size_t i=0; i<owner->town->town->mageLevel; i++)
  1696. {
  1697. size_t spellCount = owner->town->spellsAtLevel((int)i+1,false); //spell at level with -1 hmmm?
  1698. for(size_t j=0; j<spellCount; j++)
  1699. {
  1700. if(i<owner->town->mageGuildLevel() && owner->town->spells[i].size()>j)
  1701. spells.push_back(std::make_shared<Scroll>(positions[i][j], owner->town->spells[i][j].toSpell()));
  1702. else
  1703. emptyScrolls.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TPMAGES.DEF"), 1, 0, positions[i][j].x, positions[i][j].y));
  1704. }
  1705. }
  1706. }
  1707. CMageGuildScreen::Scroll::Scroll(Point position, const CSpell *Spell)
  1708. : spell(Spell)
  1709. {
  1710. OBJECT_CONSTRUCTION;
  1711. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1712. pos += position;
  1713. image = std::make_shared<CAnimImage>(AnimationPath::builtin("SPELLSCR"), spell->id);
  1714. pos = image->pos;
  1715. }
  1716. void CMageGuildScreen::Scroll::clickPressed(const Point & cursorPosition)
  1717. {
  1718. LOCPLINT->showInfoDialog(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(ComponentType::SPELL, spell->id));
  1719. }
  1720. void CMageGuildScreen::Scroll::showPopupWindow(const Point & cursorPosition)
  1721. {
  1722. CRClickPopup::createAndPush(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(ComponentType::SPELL, spell->id));
  1723. }
  1724. void CMageGuildScreen::Scroll::hover(bool on)
  1725. {
  1726. if(on)
  1727. GH.statusbar()->write(spell->getNameTranslated());
  1728. else
  1729. GH.statusbar()->clear();
  1730. }
  1731. CBlacksmithDialog::CBlacksmithDialog(bool possible, CreatureID creMachineID, ArtifactID aid, ObjectInstanceID hid):
  1732. CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPSMITH"))
  1733. {
  1734. OBJECT_CONSTRUCTION;
  1735. Rect barRect(8, pos.h - 26, pos.w - 16, 19);
  1736. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 8, pos.h - 26);
  1737. statusbar = CGStatusBar::create(statusbarBackground);
  1738. animBG = std::make_shared<CPicture>(ImagePath::builtin("TPSMITBK"), 64, 50);
  1739. animBG->needRefresh = true;
  1740. const CCreature * creature = creMachineID.toCreature();
  1741. anim = std::make_shared<CCreatureAnim>(64, 50, creature->animDefName);
  1742. anim->clipRect(113,125,200,150);
  1743. MetaString titleString;
  1744. titleString.appendTextID("core.genrltxt.274");
  1745. titleString.replaceTextID(creature->getNameSingularTextID());
  1746. MetaString buyText;
  1747. buyText.appendTextID("core.genrltxt.595");
  1748. buyText.replaceTextID(creature->getNameSingularTextID());
  1749. MetaString cancelText;
  1750. cancelText.appendTextID("core.genrltxt.596");
  1751. cancelText.replaceTextID(creature->getNameSingularTextID());
  1752. std::string costString = std::to_string(aid.toEntity(CGI)->getPrice());
  1753. title = std::make_shared<CLabel>(165, 28, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleString.toString());
  1754. costText = std::make_shared<CLabel>(165, 218, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[43]);
  1755. costValue = std::make_shared<CLabel>(165, 292, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, costString);
  1756. buy = std::make_shared<CButton>(Point(42, 312), AnimationPath::builtin("IBUY30.DEF"), CButton::tooltip(buyText.toString()), [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  1757. cancel = std::make_shared<CButton>(Point(224, 312), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(cancelText.toString()), [&](){ close(); }, EShortcut::GLOBAL_CANCEL);
  1758. if(possible)
  1759. buy->addCallback([=](){ LOCPLINT->cb->buyArtifact(LOCPLINT->cb->getHero(hid),aid); });
  1760. else
  1761. buy->block(true);
  1762. costIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 148, 244);
  1763. }