CCastleInterface.cpp 76 KB

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