CCastleInterface.cpp 78 KB

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