CGTownInstance.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. /*
  2. * CGTownInstance.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 "CGTownInstance.h"
  12. #include "CObjectClassesHandler.h"
  13. #include "../spells/CSpellHandler.h"
  14. #include "../battle/IBattleInfoCallback.h"
  15. #include "../NetPacks.h"
  16. #include "../CConfigHandler.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CModHandler.h"
  19. #include "../GameSettings.h"
  20. #include "../IGameCallback.h"
  21. #include "../CGameState.h"
  22. #include "../mapping/CMap.h"
  23. #include "../CPlayerState.h"
  24. #include "../TerrainHandler.h"
  25. #include "../serializer/JsonSerializeFormat.h"
  26. #include "../HeroBonus.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  29. std::vector<int> CGTownInstance::universitySkills;
  30. CSpecObjInfo::CSpecObjInfo():
  31. owner(nullptr)
  32. {
  33. }
  34. void CCreGenAsCastleInfo::serializeJson(JsonSerializeFormat & handler)
  35. {
  36. handler.serializeString("sameAsTown", instanceId);
  37. if(!handler.saving)
  38. {
  39. asCastle = !instanceId.empty();
  40. allowedFactions.clear();
  41. }
  42. if(!asCastle)
  43. {
  44. std::vector<bool> standard;
  45. standard.resize(VLC->townh->size(), true);
  46. JsonSerializeFormat::LIC allowedLIC(standard, &FactionID::decode, &FactionID::encode);
  47. allowedLIC.any = allowedFactions;
  48. handler.serializeLIC("allowedFactions", allowedLIC);
  49. if(!handler.saving)
  50. {
  51. allowedFactions = allowedLIC.any;
  52. }
  53. }
  54. }
  55. void CCreGenLeveledInfo::serializeJson(JsonSerializeFormat & handler)
  56. {
  57. handler.serializeInt("minLevel", minLevel, static_cast<uint8_t>(1));
  58. handler.serializeInt("maxLevel", maxLevel, static_cast<uint8_t>(7));
  59. if(!handler.saving)
  60. {
  61. //todo: safely allow any level > 7
  62. vstd::abetween<uint8_t>(minLevel, 1, 7);
  63. vstd::abetween<uint8_t>(maxLevel, minLevel, 7);
  64. }
  65. }
  66. void CCreGenLeveledCastleInfo::serializeJson(JsonSerializeFormat & handler)
  67. {
  68. CCreGenAsCastleInfo::serializeJson(handler);
  69. CCreGenLeveledInfo::serializeJson(handler);
  70. }
  71. CGDwelling::CGDwelling()
  72. : info(nullptr)
  73. {
  74. }
  75. CGDwelling::~CGDwelling()
  76. {
  77. vstd::clear_pointer(info);
  78. }
  79. void CGDwelling::initObj(CRandomGenerator & rand)
  80. {
  81. switch(ID)
  82. {
  83. case Obj::CREATURE_GENERATOR1:
  84. case Obj::CREATURE_GENERATOR4:
  85. {
  86. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  87. if (getOwner() != PlayerColor::NEUTRAL)
  88. cb->gameState()->players[getOwner()].dwellings.emplace_back(this);
  89. assert(!creatures.empty());
  90. assert(!creatures[0].second.empty());
  91. break;
  92. }
  93. case Obj::REFUGEE_CAMP:
  94. //is handled within newturn func
  95. break;
  96. case Obj::WAR_MACHINE_FACTORY:
  97. creatures.resize(3);
  98. creatures[0].second.emplace_back(CreatureID::BALLISTA);
  99. creatures[1].second.emplace_back(CreatureID::FIRST_AID_TENT);
  100. creatures[2].second.emplace_back(CreatureID::AMMO_CART);
  101. break;
  102. default:
  103. assert(0);
  104. break;
  105. }
  106. }
  107. void CGDwelling::initRandomObjectInfo()
  108. {
  109. vstd::clear_pointer(info);
  110. switch(ID)
  111. {
  112. case Obj::RANDOM_DWELLING: info = new CCreGenLeveledCastleInfo();
  113. break;
  114. case Obj::RANDOM_DWELLING_LVL: info = new CCreGenAsCastleInfo();
  115. break;
  116. case Obj::RANDOM_DWELLING_FACTION: info = new CCreGenLeveledInfo();
  117. break;
  118. }
  119. if(info)
  120. info->owner = this;
  121. }
  122. void CGDwelling::setPropertyDer(ui8 what, ui32 val)
  123. {
  124. switch (what)
  125. {
  126. case ObjProperty::OWNER: //change owner
  127. if (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR2
  128. || ID == Obj::CREATURE_GENERATOR3 || ID == Obj::CREATURE_GENERATOR4)
  129. {
  130. if (tempOwner != PlayerColor::NEUTRAL)
  131. {
  132. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  133. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  134. }
  135. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  136. cb->gameState()->players[PlayerColor(val)].dwellings.emplace_back(this);
  137. }
  138. break;
  139. case ObjProperty::AVAILABLE_CREATURE:
  140. creatures.resize(1);
  141. creatures[0].second.resize(1);
  142. creatures[0].second[0] = CreatureID(val);
  143. break;
  144. }
  145. }
  146. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  147. {
  148. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  149. {
  150. InfoWindow iw;
  151. iw.type = EInfoWindowMode::AUTO;
  152. iw.player = h->tempOwner;
  153. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  154. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  155. cb->sendAndApply(&iw);
  156. return;
  157. }
  158. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  159. if ( relations == PlayerRelations::ALLIES )
  160. return;//do not allow recruiting or capturing
  161. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  162. {
  163. BlockingDialog bd(true,false);
  164. bd.player = h->tempOwner;
  165. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  166. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  167. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  168. bd.text.addReplacement(CCreature::getQuantityRangeStringForId(Slots().begin()->second->getQuantityID()));
  169. else
  170. bd.text.addReplacement(MetaString::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
  171. bd.text.addReplacement(*Slots().begin()->second);
  172. cb->showBlockingDialog(&bd);
  173. return;
  174. }
  175. // TODO this shouldn't be hardcoded
  176. if(!relations && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  177. {
  178. cb->setOwner(this, h->tempOwner);
  179. }
  180. BlockingDialog bd (true,false);
  181. bd.player = h->tempOwner;
  182. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  183. {
  184. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  185. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  186. for(const auto & elem : creatures)
  187. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  188. }
  189. else if(ID == Obj::REFUGEE_CAMP)
  190. {
  191. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  192. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  193. for(const auto & elem : creatures)
  194. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  195. }
  196. else if(ID == Obj::WAR_MACHINE_FACTORY)
  197. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  198. else
  199. throw std::runtime_error("Illegal dwelling!");
  200. cb->showBlockingDialog(&bd);
  201. }
  202. void CGDwelling::newTurn(CRandomGenerator & rand) const
  203. {
  204. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  205. return;
  206. //town growths and War Machines Factories are handled separately
  207. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  208. return;
  209. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  210. {
  211. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(rand));
  212. }
  213. bool change = false;
  214. SetAvailableCreatures sac;
  215. sac.creatures = creatures;
  216. sac.tid = id;
  217. for (size_t i = 0; i < creatures.size(); i++)
  218. {
  219. if(!creatures[i].second.empty())
  220. {
  221. bool creaturesAccumulate = false;
  222. if (tempOwner.isValidPlayer())
  223. creaturesAccumulate = VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  224. else
  225. creaturesAccumulate = VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_NEUTRAL);
  226. CCreature *cre = VLC->creh->objects[creatures[i].second[0]];
  227. TQuantity amount = cre->getGrowth() * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  228. if (creaturesAccumulate && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  229. sac.creatures[i].first += amount;
  230. else
  231. sac.creatures[i].first = amount;
  232. change = true;
  233. }
  234. }
  235. if(change)
  236. cb->sendAndApply(&sac);
  237. updateGuards();
  238. }
  239. void CGDwelling::updateGuards() const
  240. {
  241. //TODO: store custom guard config and use it
  242. //TODO: store boolean flag for guards
  243. bool guarded = false;
  244. //default condition - creatures are of level 5 or higher
  245. for (auto creatureEntry : creatures)
  246. {
  247. if (VLC->creatures()->getByIndex(creatureEntry.second.at(0))->getLevel() >= 5 && ID != Obj::REFUGEE_CAMP)
  248. {
  249. guarded = true;
  250. break;
  251. }
  252. }
  253. if (guarded)
  254. {
  255. for (auto creatureEntry : creatures)
  256. {
  257. const CCreature * crea = VLC->creh->objects[creatureEntry.second.at(0)];
  258. SlotID slot = getSlotFor(crea->getId());
  259. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  260. {
  261. ChangeStackCount csc;
  262. csc.army = this->id;
  263. csc.slot = slot;
  264. csc.count = crea->getGrowth() * 3;
  265. csc.absoluteValue = true;
  266. cb->sendAndApply(&csc);
  267. }
  268. else //slot is empty, create whole new stack
  269. {
  270. InsertNewStack ns;
  271. ns.army = this->id;
  272. ns.slot = slot;
  273. ns.type = crea->getId();
  274. ns.count = crea->getGrowth() * 3;
  275. cb->sendAndApply(&ns);
  276. }
  277. }
  278. }
  279. }
  280. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  281. {
  282. CreatureID crid = creatures[0].second[0];
  283. auto *crs = crid.toCreature();
  284. TQuantity count = creatures[0].first;
  285. if(crs->getLevel() == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  286. {
  287. if(count) //there are available creatures
  288. {
  289. SlotID slot = h->getSlotFor(crid);
  290. if(!slot.validSlot()) //no available slot
  291. {
  292. InfoWindow iw;
  293. iw.type = EInfoWindowMode::AUTO;
  294. iw.player = h->tempOwner;
  295. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  296. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  297. cb->showInfoDialog(&iw);
  298. }
  299. else //give creatures
  300. {
  301. SetAvailableCreatures sac;
  302. sac.tid = id;
  303. sac.creatures = creatures;
  304. sac.creatures[0].first = 0;
  305. InfoWindow iw;
  306. iw.type = EInfoWindowMode::AUTO;
  307. iw.player = h->tempOwner;
  308. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  309. iw.text.addReplacement(count);
  310. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  311. cb->showInfoDialog(&iw);
  312. cb->sendAndApply(&sac);
  313. cb->addToSlot(StackLocation(h, slot), crs, count);
  314. }
  315. }
  316. else //there no creatures
  317. {
  318. InfoWindow iw;
  319. iw.type = EInfoWindowMode::AUTO;
  320. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  321. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  322. iw.player = h->tempOwner;
  323. cb->sendAndApply(&iw);
  324. }
  325. }
  326. else
  327. {
  328. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  329. {
  330. //there is 1 war machine available to recruit if hero doesn't have one
  331. SetAvailableCreatures sac;
  332. sac.tid = id;
  333. sac.creatures = creatures;
  334. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  335. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  336. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  337. cb->sendAndApply(&sac);
  338. }
  339. OpenWindow ow;
  340. ow.id1 = id.getNum();
  341. ow.id2 = h->id.getNum();
  342. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  343. ? EOpenWindowMode::RECRUITMENT_FIRST
  344. : EOpenWindowMode::RECRUITMENT_ALL;
  345. cb->sendAndApply(&ow);
  346. }
  347. }
  348. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  349. {
  350. if (result.winner == 0)
  351. {
  352. onHeroVisit(hero);
  353. }
  354. }
  355. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  356. {
  357. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  358. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  359. {
  360. if(answer)
  361. cb->startBattleI(hero, this);
  362. }
  363. else if(answer)
  364. {
  365. heroAcceptsCreatures(hero);
  366. }
  367. }
  368. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  369. {
  370. if(!handler.saving)
  371. initRandomObjectInfo();
  372. switch (ID)
  373. {
  374. case Obj::WAR_MACHINE_FACTORY:
  375. case Obj::REFUGEE_CAMP:
  376. //do nothing
  377. break;
  378. case Obj::RANDOM_DWELLING:
  379. case Obj::RANDOM_DWELLING_LVL:
  380. case Obj::RANDOM_DWELLING_FACTION:
  381. info->serializeJson(handler);
  382. //fall through
  383. default:
  384. serializeJsonOwner(handler);
  385. break;
  386. }
  387. }
  388. int CGTownInstance::getSightRadius() const //returns sight distance
  389. {
  390. auto ret = CBuilding::HEIGHT_NO_TOWER;
  391. for(const auto & bid : builtBuildings)
  392. {
  393. if(bid.IsSpecialOrGrail())
  394. {
  395. auto height = town->buildings.at(bid)->height;
  396. if(ret < height)
  397. ret = height;
  398. }
  399. }
  400. return ret;
  401. }
  402. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  403. {
  404. ///this is freakin' overcomplicated solution
  405. switch (what)
  406. {
  407. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  408. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  409. break;
  410. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  411. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  412. break;
  413. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  414. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  415. break;
  416. case ObjProperty::BONUS_VALUE_FIRST:
  417. bonusValue.first = val;
  418. break;
  419. case ObjProperty::BONUS_VALUE_SECOND:
  420. bonusValue.second = val;
  421. break;
  422. }
  423. }
  424. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  425. {
  426. if (hasBuilt(BuildingID::CASTLE))
  427. return CASTLE;
  428. if (hasBuilt(BuildingID::CITADEL))
  429. return CITADEL;
  430. if (hasBuilt(BuildingID::FORT))
  431. return FORT;
  432. return NONE;
  433. }
  434. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  435. {
  436. if (hasBuilt(BuildingID::CAPITOL))
  437. return 3;
  438. if (hasBuilt(BuildingID::CITY_HALL))
  439. return 2;
  440. if (hasBuilt(BuildingID::TOWN_HALL))
  441. return 1;
  442. if (hasBuilt(BuildingID::VILLAGE_HALL))
  443. return 0;
  444. return -1;
  445. }
  446. int CGTownInstance::mageGuildLevel() const
  447. {
  448. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  449. return 5;
  450. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  451. return 4;
  452. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  453. return 3;
  454. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  455. return 2;
  456. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  457. return 1;
  458. return 0;
  459. }
  460. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  461. {
  462. return town->hordeLvl.at(HID);
  463. }
  464. int CGTownInstance::creatureGrowth(const int & level) const
  465. {
  466. return getGrowthInfo(level).totalGrowth();
  467. }
  468. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  469. {
  470. GrowthInfo ret;
  471. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  472. return ret;
  473. if (creatures[level].second.empty())
  474. return ret; //no dwelling
  475. const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
  476. const int base = creature->getGrowth();
  477. int castleBonus = 0;
  478. ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  479. if (hasBuilt(BuildingID::CASTLE))
  480. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  481. else if (hasBuilt(BuildingID::CITADEL))
  482. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  483. if(town->hordeLvl.at(0) == level)//horde 1
  484. if(hasBuilt(BuildingID::HORDE_1))
  485. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  486. if(town->hordeLvl.at(1) == level)//horde 2
  487. if(hasBuilt(BuildingID::HORDE_2))
  488. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  489. //statue-of-legion-like bonus: % to base+castle
  490. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH_PERCENT));
  491. for(const auto & b : *bonuses2)
  492. {
  493. const auto growth = b->val * (base + castleBonus) / 100;
  494. ret.entries.emplace_back(growth, b->Description(growth));
  495. }
  496. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  497. TConstBonusListPtr bonuses = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH).And(Selector::subtype()(level)));
  498. for(const auto & b : *bonuses)
  499. ret.entries.emplace_back(b->val, b->Description());
  500. int dwellingBonus = 0;
  501. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  502. {
  503. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  504. }
  505. if(dwellingBonus)
  506. ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  507. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  508. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  509. return ret;
  510. }
  511. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  512. {
  513. int totalBonus = 0;
  514. for (const auto& dwelling : dwellings)
  515. {
  516. for (const auto& creature : dwelling->creatures)
  517. {
  518. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  519. }
  520. }
  521. return totalBonus;
  522. }
  523. TResources CGTownInstance::dailyIncome() const
  524. {
  525. TResources ret;
  526. for(const auto & p : town->buildings)
  527. {
  528. BuildingID buildingUpgrade;
  529. for(const auto & p2 : town->buildings)
  530. {
  531. if (p2.second->upgrade == p.first)
  532. {
  533. buildingUpgrade = p2.first;
  534. }
  535. }
  536. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  537. {
  538. ret += p.second->produce;
  539. }
  540. }
  541. return ret;
  542. }
  543. bool CGTownInstance::hasFort() const
  544. {
  545. return hasBuilt(BuildingID::FORT);
  546. }
  547. bool CGTownInstance::hasCapitol() const
  548. {
  549. return hasBuilt(BuildingID::CAPITOL);
  550. }
  551. CGTownInstance::CGTownInstance():
  552. IShipyard(this),
  553. IMarket(this),
  554. town(nullptr),
  555. builded(0),
  556. destroyed(0),
  557. identifier(0),
  558. alignmentToPlayer(PlayerColor::NEUTRAL)
  559. {
  560. this->setNodeType(CBonusSystemNode::TOWN);
  561. }
  562. CGTownInstance::~CGTownInstance()
  563. {
  564. for (auto & elem : bonusingBuildings)
  565. delete elem;
  566. }
  567. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  568. {
  569. if(checkGuild && mageGuildLevel() < level)
  570. return 0;
  571. int ret = 6 - level; //how many spells are available at this level
  572. if (hasBuilt(BuildingSubID::LIBRARY))
  573. ret++;
  574. return ret;
  575. }
  576. bool CGTownInstance::needsLastStack() const
  577. {
  578. return garrisonHero != nullptr;
  579. }
  580. void CGTownInstance::setOwner(const PlayerColor & player) const
  581. {
  582. removeCapitols(player);
  583. cb->setOwner(this, player);
  584. }
  585. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  586. {
  587. if(!cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  588. {
  589. if(armedGarrison() || visitingHero)
  590. {
  591. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  592. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  593. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  594. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  595. {
  596. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  597. auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  598. if(nodeSiege == (CBonusSystemNode *)this)
  599. cb->swapGarrisonOnSiege(this->id);
  600. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  601. }
  602. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  603. }
  604. else
  605. {
  606. auto heroColor = h->getOwner();
  607. onTownCaptured(heroColor);
  608. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  609. {
  610. return; //we just won game, we do not need to perform any extra actions
  611. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  612. }
  613. cb->heroVisitCastle(this, h);
  614. }
  615. }
  616. else if(h->visitablePos() == visitablePos())
  617. {
  618. bool commander_recover = h->commander && !h->commander->alive;
  619. if (commander_recover) // rise commander from dead
  620. {
  621. SetCommanderProperty scp;
  622. scp.heroid = h->id;
  623. scp.which = SetCommanderProperty::ALIVE;
  624. scp.amount = 1;
  625. cb->sendAndApply(&scp);
  626. }
  627. cb->heroVisitCastle(this, h);
  628. // TODO(vmarkovtsev): implement payment for rising the commander
  629. if (commander_recover) // info window about commander
  630. {
  631. InfoWindow iw;
  632. iw.player = h->tempOwner;
  633. iw.text << h->commander->getName();
  634. iw.components.emplace_back(*h->commander);
  635. cb->showInfoDialog(&iw);
  636. }
  637. }
  638. else
  639. {
  640. logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), name);
  641. }
  642. }
  643. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  644. {
  645. //FIXME: find out why this issue appears on random maps
  646. if(visitingHero == h)
  647. {
  648. cb->stopHeroVisitCastle(this, h);
  649. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), name);
  650. }
  651. else
  652. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), name);
  653. }
  654. std::string CGTownInstance::getObjectName() const
  655. {
  656. return name + ", " + town->faction->getNameTranslated();
  657. }
  658. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  659. {
  660. return town->getBuildingType(subId) != BuildingID::NONE;
  661. }
  662. void CGTownInstance::initOverriddenBids()
  663. {
  664. for(const auto & bid : builtBuildings)
  665. {
  666. const auto & overrideThem = town->buildings.at(bid)->overrideBids;
  667. for(const auto & overrideIt : overrideThem)
  668. overriddenBuildings.insert(overrideIt);
  669. }
  670. }
  671. bool CGTownInstance::isBonusingBuildingAdded(BuildingID::EBuildingID bid) const
  672. {
  673. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  674. {
  675. return building->getBuildingType().num == bid;
  676. });
  677. return present != bonusingBuildings.end();
  678. }
  679. //it does not check hasBuilt because this check is in the OnHeroVisit handler
  680. void CGTownInstance::tryAddOnePerWeekBonus(BuildingSubID::EBuildingSubID subID)
  681. {
  682. auto bid = town->getBuildingType(subID);
  683. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  684. bonusingBuildings.push_back(new COPWBonus(bid, subID, this));
  685. }
  686. void CGTownInstance::tryAddVisitingBonus(BuildingSubID::EBuildingSubID subID)
  687. {
  688. auto bid = town->getBuildingType(subID);
  689. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  690. bonusingBuildings.push_back(new CTownBonus(bid, subID, this));
  691. }
  692. void CGTownInstance::addTownBonuses()
  693. {
  694. for(const auto & kvp : town->buildings)
  695. {
  696. if(vstd::contains(overriddenBuildings, kvp.first))
  697. continue;
  698. if(kvp.second->IsVisitingBonus())
  699. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  700. if(kvp.second->IsWeekBonus())
  701. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  702. }
  703. }
  704. DamageRange CGTownInstance::getTowerDamageRange() const
  705. {
  706. assert(hasBuilt(BuildingID::CASTLE));
  707. // http://heroes.thelazy.net/wiki/Arrow_tower
  708. // base damage, irregardless of town level
  709. static constexpr int baseDamage = 6;
  710. // extra damage, for each building in town
  711. static constexpr int extraDamage = 1;
  712. const int minDamage = baseDamage + extraDamage * getTownLevel();
  713. return {
  714. minDamage,
  715. minDamage * 2
  716. };
  717. }
  718. DamageRange CGTownInstance::getKeepDamageRange() const
  719. {
  720. assert(hasBuilt(BuildingID::CITADEL));
  721. // http://heroes.thelazy.net/wiki/Arrow_tower
  722. // base damage, irregardless of town level
  723. static constexpr int baseDamage = 10;
  724. // extra damage, for each building in town
  725. static constexpr int extraDamage = 2;
  726. const int minDamage = baseDamage + extraDamage * getTownLevel();
  727. return {
  728. minDamage,
  729. minDamage * 2
  730. };
  731. }
  732. void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
  733. {
  734. size_t i = 0;
  735. CGTownBuilding * freeIt = nullptr;
  736. for(i = 0; i != bonusingBuildings.size(); i++)
  737. {
  738. if(bonusingBuildings[i]->getBuildingType() == bid)
  739. {
  740. freeIt = bonusingBuildings[i];
  741. break;
  742. }
  743. }
  744. if(freeIt == nullptr)
  745. return;
  746. auto building = town->buildings.at(bid);
  747. auto isVisitingBonus = building->IsVisitingBonus();
  748. auto isWeekBonus = building->IsWeekBonus();
  749. if(!isVisitingBonus && !isWeekBonus)
  750. return;
  751. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  752. delete freeIt;
  753. }
  754. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  755. {
  756. blockVisit = true;
  757. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  758. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  759. else
  760. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  761. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  762. {
  763. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  764. int upgradeNum = 0;
  765. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  766. {
  767. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  768. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  769. }
  770. }
  771. initOverriddenBids();
  772. addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
  773. recreateBuildingsBonuses();
  774. updateAppearance();
  775. }
  776. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, const BuildingID & bid) const
  777. {
  778. return (this->town->faction != nullptr && this->town->faction->getIndex() == type && hasBuilt(bid));
  779. }
  780. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  781. {
  782. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  783. {
  784. //give resources if there's a Mystic Pond
  785. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  786. && cb->getDate(Date::DAY) != 1
  787. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  788. )
  789. {
  790. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  791. resID = (resID==2)?1:resID;
  792. int resVal = rand.nextInt(1, 4);//with size 1..4
  793. cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
  794. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  795. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  796. }
  797. const auto * manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  798. if (manaVortex != nullptr)
  799. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  800. //get Mana Vortex or Stables bonuses
  801. //same code is in the CGameHandler::buildStructure method
  802. if (visitingHero != nullptr)
  803. cb->visitCastleObjects(this, visitingHero);
  804. if (garrisonHero != nullptr)
  805. cb->visitCastleObjects(this, garrisonHero);
  806. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  807. {
  808. std::vector<SlotID> nativeCrits; //slots
  809. for(const auto & elem : Slots())
  810. {
  811. if (elem.second->type->getFaction() == subID) //native
  812. {
  813. nativeCrits.push_back(elem.first); //collect matching slots
  814. }
  815. }
  816. if(!nativeCrits.empty())
  817. {
  818. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  819. StackLocation sl(this, pos);
  820. const CCreature *c = getCreature(pos);
  821. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  822. {
  823. cb->changeStackCount(sl, c->getGrowth());
  824. }
  825. else //upgrade
  826. {
  827. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  828. }
  829. }
  830. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  831. {
  832. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  833. if (!town->creatures[i].empty())
  834. {
  835. CreatureID c = town->creatures[i][0];
  836. SlotID n;
  837. TQuantity count = creatureGrowth(i);
  838. if (!count) // no dwelling
  839. count = VLC->creh->objects[c]->getGrowth();
  840. {//no lower tiers or above current month
  841. if ((n = getSlotFor(c)).validSlot())
  842. {
  843. StackLocation sl(this, n);
  844. if (slotEmpty(n))
  845. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  846. else //add to existing
  847. cb->changeStackCount(sl, count);
  848. }
  849. }
  850. }
  851. }
  852. }
  853. }
  854. }
  855. /*
  856. int3 CGTownInstance::getSightCenter() const
  857. {
  858. return pos - int3(2,0,0);
  859. }
  860. */
  861. bool CGTownInstance::passableFor(PlayerColor color) const
  862. {
  863. if (!armedGarrison())//empty castle - anyone can visit
  864. return true;
  865. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  866. return false;
  867. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  868. }
  869. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  870. {
  871. offsets = {int3(-1,2,0), int3(-3,2,0)};
  872. }
  873. void CGTownInstance::mergeGarrisonOnSiege() const
  874. {
  875. auto getWeakestStackSlot = [&](ui64 powerLimit)
  876. {
  877. std::vector<SlotID> weakSlots;
  878. auto stacksList = visitingHero->stacks;
  879. std::pair<SlotID, CStackInstance *> pair;
  880. while(!stacksList.empty())
  881. {
  882. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  883. if(powerLimit > pair.second->getPower() &&
  884. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  885. {
  886. weakSlots.push_back(pair.first);
  887. stacksList.erase(pair.first);
  888. }
  889. else
  890. break;
  891. }
  892. if(!weakSlots.empty())
  893. return *std::max_element(weakSlots.begin(), weakSlots.end());
  894. return SlotID();
  895. };
  896. auto count = static_cast<int>(stacks.size());
  897. for(int i = 0; i < count; i++)
  898. {
  899. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  900. {
  901. ui64 power = elem.second->getPower();
  902. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  903. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  904. power += visitingHero->getStack(dst).getPower();
  905. return power;
  906. });
  907. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  908. if(dst.validSlot())
  909. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  910. else
  911. {
  912. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  913. if(dst.validSlot())
  914. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  915. }
  916. }
  917. }
  918. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  919. {
  920. if (hasCapitol()) // search if there's an older capitol
  921. {
  922. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  923. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  924. {
  925. if (*i != this && (*i)->hasCapitol())
  926. {
  927. RazeStructures rs;
  928. rs.tid = id;
  929. rs.bid.insert(BuildingID::CAPITOL);
  930. rs.destroyed = destroyed;
  931. cb->sendAndApply(&rs);
  932. return;
  933. }
  934. }
  935. }
  936. }
  937. void CGTownInstance::clearArmy() const
  938. {
  939. while(!stacks.empty())
  940. {
  941. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  942. }
  943. }
  944. int CGTownInstance::getBoatType() const
  945. {
  946. switch (town->faction->alignment)
  947. {
  948. case EAlignment::EVIL : return 0;
  949. case EAlignment::GOOD : return 1;
  950. case EAlignment::NEUTRAL : return 2;
  951. }
  952. assert(0);
  953. return -1;
  954. }
  955. int CGTownInstance::getMarketEfficiency() const
  956. {
  957. if(!hasBuiltSomeTradeBuilding())
  958. return 0;
  959. const PlayerState *p = cb->getPlayerState(tempOwner);
  960. assert(p);
  961. int marketCount = 0;
  962. for(const CGTownInstance *t : p->towns)
  963. if(t->hasBuiltSomeTradeBuilding())
  964. marketCount++;
  965. return marketCount;
  966. }
  967. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  968. {
  969. switch(mode)
  970. {
  971. case EMarketMode::RESOURCE_RESOURCE:
  972. case EMarketMode::RESOURCE_PLAYER:
  973. return hasBuilt(BuildingID::MARKETPLACE);
  974. case EMarketMode::ARTIFACT_RESOURCE:
  975. case EMarketMode::RESOURCE_ARTIFACT:
  976. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  977. case EMarketMode::CREATURE_RESOURCE:
  978. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  979. case EMarketMode::CREATURE_UNDEAD:
  980. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  981. case EMarketMode::RESOURCE_SKILL:
  982. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  983. default:
  984. assert(0);
  985. return false;
  986. }
  987. }
  988. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  989. {
  990. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  991. {
  992. std::vector<int> ret;
  993. for(const CArtifact *a : merchantArtifacts)
  994. if(a)
  995. ret.push_back(a->getId());
  996. else
  997. ret.push_back(-1);
  998. return ret;
  999. }
  1000. else if ( mode == EMarketMode::RESOURCE_SKILL )
  1001. {
  1002. return universitySkills;
  1003. }
  1004. else
  1005. return IMarket::availableItemsIds(mode);
  1006. }
  1007. void CGTownInstance::setType(si32 ID, si32 subID)
  1008. {
  1009. assert(ID == Obj::TOWN); // just in case
  1010. CGObjectInstance::setType(ID, subID);
  1011. town = (*VLC->townh)[subID]->town;
  1012. randomizeArmy(subID);
  1013. updateAppearance();
  1014. }
  1015. void CGTownInstance::updateAppearance()
  1016. {
  1017. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  1018. //FIXME: not the best way to do this
  1019. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  1020. if (app)
  1021. appearance = app;
  1022. }
  1023. std::string CGTownInstance::nodeName() const
  1024. {
  1025. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  1026. }
  1027. void CGTownInstance::deserializationFix()
  1028. {
  1029. attachTo(townAndVis);
  1030. //Hero is already handled by CGameState::attachArmedObjects
  1031. // if(visitingHero)
  1032. // visitingHero->attachTo(&townAndVis);
  1033. // if(garrisonHero)
  1034. // garrisonHero->attachTo(this);
  1035. }
  1036. void CGTownInstance::updateMoraleBonusFromArmy()
  1037. {
  1038. auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
  1039. if(!b)
  1040. {
  1041. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  1042. addNewBonus(b);
  1043. }
  1044. if (garrisonHero)
  1045. {
  1046. b->val = 0;
  1047. CBonusSystemNode::treeHasChanged();
  1048. }
  1049. else
  1050. CArmedInstance::updateMoraleBonusFromArmy();
  1051. }
  1052. void CGTownInstance::recreateBuildingsBonuses()
  1053. {
  1054. BonusList bl;
  1055. getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
  1056. for(const auto & b : bl)
  1057. removeBonus(b);
  1058. for(const auto & bid : builtBuildings)
  1059. {
  1060. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  1061. continue;
  1062. auto building = town->buildings.at(bid);
  1063. if(building->buildingBonuses.empty())
  1064. continue;
  1065. for(auto & bonus : building->buildingBonuses)
  1066. addNewBonus(bonus);
  1067. }
  1068. }
  1069. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  1070. {
  1071. assert(!!visitingHero == !h);
  1072. if(h)
  1073. {
  1074. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1075. assert(p);
  1076. h->detachFrom(*p);
  1077. h->attachTo(townAndVis);
  1078. visitingHero = h;
  1079. h->visitedTown = this;
  1080. h->inTownGarrison = false;
  1081. }
  1082. else
  1083. {
  1084. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  1085. visitingHero->visitedTown = nullptr;
  1086. visitingHero->detachFrom(townAndVis);
  1087. visitingHero->attachTo(*p);
  1088. visitingHero = nullptr;
  1089. }
  1090. }
  1091. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  1092. {
  1093. assert(!!garrisonHero == !h);
  1094. if(h)
  1095. {
  1096. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1097. assert(p);
  1098. h->detachFrom(*p);
  1099. h->attachTo(*this);
  1100. garrisonHero = h;
  1101. h->visitedTown = this;
  1102. h->inTownGarrison = true;
  1103. }
  1104. else
  1105. {
  1106. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  1107. garrisonHero->visitedTown = nullptr;
  1108. garrisonHero->inTownGarrison = false;
  1109. garrisonHero->detachFrom(*this);
  1110. garrisonHero->attachTo(*p);
  1111. garrisonHero = nullptr;
  1112. }
  1113. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  1114. }
  1115. bool CGTownInstance::armedGarrison() const
  1116. {
  1117. return !stacks.empty() || garrisonHero;
  1118. }
  1119. const CTown * CGTownInstance::getTown() const
  1120. {
  1121. if(ID == Obj::RANDOM_TOWN)
  1122. return VLC->townh->randomTown;
  1123. else
  1124. {
  1125. if(nullptr == town)
  1126. {
  1127. return (*VLC->townh)[subID]->town;
  1128. }
  1129. else
  1130. return town;
  1131. }
  1132. }
  1133. int CGTownInstance::getTownLevel() const
  1134. {
  1135. // count all buildings that are not upgrades
  1136. int level = 0;
  1137. for(const auto & bid : builtBuildings)
  1138. {
  1139. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  1140. level++;
  1141. }
  1142. return level;
  1143. }
  1144. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  1145. {
  1146. return townAndVis;
  1147. }
  1148. std::string CGTownInstance::getNameTranslated() const
  1149. {
  1150. return name;
  1151. }
  1152. void CGTownInstance::setNameTranslated( const std::string & newName )
  1153. {
  1154. name = newName;
  1155. }
  1156. const CArmedInstance * CGTownInstance::getUpperArmy() const
  1157. {
  1158. if(garrisonHero)
  1159. return garrisonHero;
  1160. return this;
  1161. }
  1162. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  1163. {
  1164. for(auto * const building : bonusingBuildings)
  1165. {
  1166. if(building->getBuildingSubtype() == subId)
  1167. return building;
  1168. }
  1169. return nullptr;
  1170. }
  1171. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  1172. {
  1173. for(const auto & bid : builtBuildings)
  1174. {
  1175. if(town->buildings.at(bid)->IsTradeBuilding())
  1176. return true;
  1177. }
  1178. return false;
  1179. }
  1180. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  1181. {
  1182. for(const auto & bid : builtBuildings)
  1183. {
  1184. if(town->buildings.at(bid)->subId == buildingID)
  1185. return true;
  1186. }
  1187. return false;
  1188. }
  1189. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  1190. {
  1191. return vstd::contains(builtBuildings, buildingID);
  1192. }
  1193. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
  1194. {
  1195. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  1196. return hasBuilt(buildingID);
  1197. return false;
  1198. }
  1199. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  1200. {
  1201. if (vstd::contains(town->buildings, buildingID))
  1202. return town->buildings.at(buildingID)->resources;
  1203. else
  1204. {
  1205. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  1206. return TResources();
  1207. }
  1208. }
  1209. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  1210. {
  1211. const CBuilding * building = town->buildings.at(buildID);
  1212. //TODO: find better solution to prevent infinite loops
  1213. std::set<BuildingID> processed;
  1214. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  1215. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  1216. {
  1217. const CBuilding * build = town->buildings.at(id);
  1218. CBuilding::TRequired::OperatorAll requirements;
  1219. if (!hasBuilt(id))
  1220. {
  1221. if (deep)
  1222. requirements.expressions.emplace_back(id);
  1223. else
  1224. return id;
  1225. }
  1226. if(!vstd::contains(processed, id))
  1227. {
  1228. processed.insert(id);
  1229. if (build->upgrade != BuildingID::NONE)
  1230. requirements.expressions.push_back(dependTest(build->upgrade));
  1231. requirements.expressions.push_back(build->requirements.morph(dependTest));
  1232. }
  1233. return requirements;
  1234. };
  1235. CBuilding::TRequired::OperatorAll requirements;
  1236. if (building->upgrade != BuildingID::NONE)
  1237. {
  1238. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1239. requirements.expressions.push_back(dependTest(upgr->bid));
  1240. processed.clear();
  1241. }
  1242. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1243. CBuilding::TRequired::Variant variant(requirements);
  1244. CBuilding::TRequired ret(variant);
  1245. ret.minimize();
  1246. return ret;
  1247. }
  1248. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  1249. {
  1250. if(visitingHero == h)
  1251. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1252. else if(garrisonHero == h)
  1253. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1254. else
  1255. {
  1256. //should never ever happen
  1257. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  1258. throw std::runtime_error("internal error");
  1259. }
  1260. }
  1261. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  1262. {
  1263. if(result.winner == BattleSide::ATTACKER)
  1264. {
  1265. clearArmy();
  1266. onTownCaptured(hero->getOwner());
  1267. }
  1268. }
  1269. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  1270. {
  1271. setOwner(winner);
  1272. FoWChange fw;
  1273. fw.player = winner;
  1274. fw.mode = 1;
  1275. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  1276. cb->sendAndApply(& fw);
  1277. }
  1278. void CGTownInstance::afterAddToMap(CMap * map)
  1279. {
  1280. if(ID == Obj::TOWN)
  1281. map->towns.emplace_back(this);
  1282. }
  1283. void CGTownInstance::afterRemoveFromMap(CMap * map)
  1284. {
  1285. if (ID == Obj::TOWN)
  1286. vstd::erase_if_present(map->towns, this);
  1287. }
  1288. void CGTownInstance::reset()
  1289. {
  1290. CGTownInstance::merchantArtifacts.clear();
  1291. CGTownInstance::universitySkills.clear();
  1292. }
  1293. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1294. {
  1295. static const std::vector<std::string> FORMATIONS = { "wide", "tight" };
  1296. CGObjectInstance::serializeJsonOwner(handler);
  1297. CCreatureSet::serializeJson(handler, "army", 7);
  1298. handler.serializeEnum("tightFormation", formation, FORMATIONS);
  1299. handler.serializeString("name", name);
  1300. {
  1301. auto decodeBuilding = [this](const std::string & identifier) -> si32
  1302. {
  1303. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  1304. if(rawId)
  1305. return rawId.value();
  1306. else
  1307. return -1;
  1308. };
  1309. auto encodeBuilding = [this](si32 index) -> std::string
  1310. {
  1311. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  1312. };
  1313. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  1314. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  1315. if(handler.saving)
  1316. {
  1317. bool customBuildings = false;
  1318. boost::logic::tribool hasFort(false);
  1319. for(const BuildingID & id : forbiddenBuildings)
  1320. {
  1321. buildingsLIC.none.insert(id);
  1322. customBuildings = true;
  1323. }
  1324. for(const BuildingID & id : builtBuildings)
  1325. {
  1326. if(id == BuildingID::DEFAULT)
  1327. continue;
  1328. const CBuilding * building = getTown()->buildings.at(id);
  1329. if(building->mode == CBuilding::BUILD_AUTO)
  1330. continue;
  1331. if(id == BuildingID::FORT)
  1332. hasFort = true;
  1333. buildingsLIC.all.insert(id);
  1334. customBuildings = true;
  1335. }
  1336. if(customBuildings)
  1337. handler.serializeLIC("buildings", buildingsLIC);
  1338. else
  1339. handler.serializeBool("hasFort",hasFort);
  1340. }
  1341. else
  1342. {
  1343. handler.serializeLIC("buildings", buildingsLIC);
  1344. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1345. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1346. {
  1347. builtBuildings.insert(BuildingID::DEFAULT);
  1348. bool hasFort = false;
  1349. handler.serializeBool("hasFort",hasFort);
  1350. if(hasFort)
  1351. builtBuildings.insert(BuildingID::FORT);
  1352. }
  1353. else
  1354. {
  1355. for(const si32 item : buildingsLIC.none)
  1356. forbiddenBuildings.insert(BuildingID(item));
  1357. for(const si32 item : buildingsLIC.all)
  1358. builtBuildings.insert(BuildingID(item));
  1359. }
  1360. }
  1361. }
  1362. {
  1363. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1364. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1365. if(handler.saving)
  1366. {
  1367. for(const SpellID & id : possibleSpells)
  1368. spellsLIC.any[id.num] = true;
  1369. for(const SpellID & id : obligatorySpells)
  1370. spellsLIC.all[id.num] = true;
  1371. }
  1372. handler.serializeLIC("spells", spellsLIC);
  1373. if(!handler.saving)
  1374. {
  1375. possibleSpells.clear();
  1376. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1377. {
  1378. if(spellsLIC.any[idx])
  1379. possibleSpells.emplace_back(idx);
  1380. }
  1381. obligatorySpells.clear();
  1382. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1383. {
  1384. if(spellsLIC.all[idx])
  1385. obligatorySpells.emplace_back(idx);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. FactionID CGTownInstance::getFaction() const
  1391. {
  1392. return town->faction->getId();
  1393. }
  1394. TerrainId CGTownInstance::getNativeTerrain() const
  1395. {
  1396. return town->faction->getNativeTerrain();
  1397. }
  1398. PlayerColor CGTownBuilding::getOwner() const
  1399. {
  1400. return town->getOwner();
  1401. }
  1402. int32_t CGTownBuilding::getObjGroupIndex() const
  1403. {
  1404. return -1;
  1405. }
  1406. int32_t CGTownBuilding::getObjTypeIndex() const
  1407. {
  1408. return 0;
  1409. }
  1410. int3 CGTownBuilding::visitablePos() const
  1411. {
  1412. return town->visitablePos();
  1413. }
  1414. int3 CGTownBuilding::getPosition() const
  1415. {
  1416. return town->getPosition();
  1417. }
  1418. COPWBonus::COPWBonus(const BuildingID & bid, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1419. {
  1420. bID = bid;
  1421. bType = subId;
  1422. town = cgTown;
  1423. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1424. }
  1425. void COPWBonus::setProperty(ui8 what, ui32 val)
  1426. {
  1427. switch (what)
  1428. {
  1429. case ObjProperty::VISITORS:
  1430. visitors.insert(val);
  1431. break;
  1432. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1433. visitors.clear();
  1434. break;
  1435. }
  1436. }
  1437. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  1438. {
  1439. ObjectInstanceID heroID = h->id;
  1440. if(town->hasBuilt(bID))
  1441. {
  1442. InfoWindow iw;
  1443. iw.player = h->tempOwner;
  1444. switch (this->bType)
  1445. {
  1446. case BuildingSubID::STABLES:
  1447. if(!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1448. {
  1449. GiveBonus gb;
  1450. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100], 1);
  1451. gb.id = heroID.getNum();
  1452. cb->giveHeroBonus(&gb);
  1453. SetMovePoints mp;
  1454. mp.val = 600;
  1455. mp.absolute = false;
  1456. mp.hid = heroID;
  1457. cb->setMovePoints(&mp);
  1458. iw.text << VLC->generaltexth->allTexts[580];
  1459. cb->showInfoDialog(&iw);
  1460. }
  1461. break;
  1462. case BuildingSubID::MANA_VORTEX:
  1463. if(visitors.empty())
  1464. {
  1465. if(h->mana < h->manaLimit() * 2)
  1466. cb->setManaPoints (heroID, 2 * h->manaLimit());
  1467. //TODO: investigate line below
  1468. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1469. iw.text << getVisitingBonusGreeting();
  1470. cb->showInfoDialog(&iw);
  1471. //extra visit penalty if hero alredy had double mana points (or even more?!)
  1472. town->addHeroToStructureVisitors(h, indexOnTV);
  1473. }
  1474. break;
  1475. }
  1476. }
  1477. }
  1478. CTownBonus::CTownBonus(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1479. {
  1480. bID = index;
  1481. bType = subId;
  1482. town = cgTown;
  1483. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1484. }
  1485. void CTownBonus::setProperty (ui8 what, ui32 val)
  1486. {
  1487. if(what == ObjProperty::VISITORS)
  1488. visitors.insert(ObjectInstanceID(val));
  1489. }
  1490. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  1491. {
  1492. ObjectInstanceID heroID = h->id;
  1493. if(town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
  1494. {
  1495. si64 val = 0;
  1496. InfoWindow iw;
  1497. PrimarySkill::PrimarySkill what = PrimarySkill::NONE;
  1498. switch(bType)
  1499. {
  1500. case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge
  1501. what = PrimarySkill::KNOWLEDGE;
  1502. val = 1;
  1503. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 3, 1, 0);
  1504. break;
  1505. case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire
  1506. what = PrimarySkill::SPELL_POWER;
  1507. val = 1;
  1508. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 2, 1, 0);
  1509. break;
  1510. case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla
  1511. what = PrimarySkill::ATTACK;
  1512. val = 1;
  1513. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 0, 1, 0);
  1514. break;
  1515. case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars
  1516. what = PrimarySkill::EXPERIENCE;
  1517. val = static_cast<int>(h->calculateXp(1000));
  1518. iw.components.emplace_back(Component::EComponentType::EXPERIENCE, 0, val, 0);
  1519. break;
  1520. case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords
  1521. what = PrimarySkill::DEFENSE;
  1522. val = 1;
  1523. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 1, 1, 0);
  1524. break;
  1525. case BuildingSubID::CUSTOM_VISITING_BONUS:
  1526. const auto building = town->getTown()->buildings.at(bID);
  1527. if(!h->hasBonusFrom(Bonus::TOWN_STRUCTURE, Bonus::getSid32(building->town->faction->getIndex(), building->bid)))
  1528. {
  1529. const auto & bonuses = building->onVisitBonuses;
  1530. applyBonuses(const_cast<CGHeroInstance *>(h), bonuses);
  1531. }
  1532. break;
  1533. }
  1534. if(what != PrimarySkill::NONE)
  1535. {
  1536. iw.player = cb->getOwner(heroID);
  1537. iw.text << getVisitingBonusGreeting();
  1538. cb->showInfoDialog(&iw);
  1539. cb->changePrimSkill (cb->getHero(heroID), what, val);
  1540. town->addHeroToStructureVisitors(h, indexOnTV);
  1541. }
  1542. }
  1543. }
  1544. void CTownBonus::applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const
  1545. {
  1546. auto addToVisitors = false;
  1547. for(const auto & bonus : bonuses)
  1548. {
  1549. GiveBonus gb;
  1550. InfoWindow iw;
  1551. if(bonus->type == Bonus::TOWN_MAGIC_WELL)
  1552. {
  1553. if(h->mana >= h->manaLimit())
  1554. return;
  1555. cb->setManaPoints(h->id, h->manaLimit());
  1556. bonus->duration = Bonus::ONE_DAY;
  1557. }
  1558. gb.bonus = * bonus;
  1559. gb.id = h->id.getNum();
  1560. cb->giveHeroBonus(&gb);
  1561. if(bonus->duration == Bonus::PERMANENT)
  1562. addToVisitors = true;
  1563. iw.player = cb->getOwner(h->id);
  1564. iw.text << getCustomBonusGreeting(gb.bonus);
  1565. cb->showInfoDialog(&iw);
  1566. }
  1567. if(addToVisitors)
  1568. town->addHeroToStructureVisitors(h, indexOnTV);
  1569. }
  1570. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1571. : count(_count)
  1572. {
  1573. description = boost::str(boost::format(format) % count);
  1574. }
  1575. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1576. {
  1577. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1578. }
  1579. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1580. count(_count),
  1581. description(std::move(fullDescription))
  1582. {
  1583. }
  1584. CTownAndVisitingHero::CTownAndVisitingHero()
  1585. {
  1586. setNodeType(TOWN_AND_VISITOR);
  1587. }
  1588. int GrowthInfo::totalGrowth() const
  1589. {
  1590. int ret = 0;
  1591. for(const Entry &entry : entries)
  1592. ret += entry.count;
  1593. return ret;
  1594. }
  1595. std::string CGTownBuilding::getVisitingBonusGreeting() const
  1596. {
  1597. auto bonusGreeting = town->getTown()->getGreeting(bType);
  1598. if(!bonusGreeting.empty())
  1599. return bonusGreeting;
  1600. switch(bType)
  1601. {
  1602. case BuildingSubID::MANA_VORTEX:
  1603. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingManaVortex"));
  1604. break;
  1605. case BuildingSubID::KNOWLEDGE_VISITING_BONUS:
  1606. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingKnowledge"));
  1607. break;
  1608. case BuildingSubID::SPELL_POWER_VISITING_BONUS:
  1609. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingSpellPower"));
  1610. break;
  1611. case BuildingSubID::ATTACK_VISITING_BONUS:
  1612. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingAttack"));
  1613. break;
  1614. case BuildingSubID::EXPERIENCE_VISITING_BONUS:
  1615. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingExperience"));
  1616. break;
  1617. case BuildingSubID::DEFENSE_VISITING_BONUS:
  1618. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingDefence"));
  1619. break;
  1620. }
  1621. auto buildingName = town->getTown()->getSpecialBuilding(bType)->getNameTranslated();
  1622. if(bonusGreeting.empty())
  1623. {
  1624. bonusGreeting = "Error: Bonus greeting for '%s' is not localized.";
  1625. logGlobal->error("'%s' building of '%s' faction has not localized bonus greeting.", buildingName, town->getTown()->faction->getNameTranslated());
  1626. }
  1627. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1628. town->getTown()->setGreeting(bType, bonusGreeting);
  1629. return bonusGreeting;
  1630. }
  1631. std::string CGTownBuilding::getCustomBonusGreeting(const Bonus & bonus) const
  1632. {
  1633. if(bonus.type == Bonus::TOWN_MAGIC_WELL)
  1634. {
  1635. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingInTownMagicWell"));
  1636. auto buildingName = town->getTown()->getSpecialBuilding(bType)->getNameTranslated();
  1637. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1638. return bonusGreeting;
  1639. }
  1640. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingCustomBonus")); //"%s gives you +%d %s%s"
  1641. std::string param;
  1642. std::string until;
  1643. if(bonus.type == Bonus::MORALE)
  1644. param = VLC->generaltexth->allTexts[384];
  1645. else if(bonus.type == Bonus::LUCK)
  1646. param = VLC->generaltexth->allTexts[385];
  1647. until = bonus.duration == static_cast<ui16>(Bonus::ONE_BATTLE)
  1648. ? VLC->generaltexth->translate("vcmi.townHall.greetingCustomUntil")
  1649. : ".";
  1650. boost::format fmt = boost::format(bonusGreeting) % bonus.description % bonus.val % param % until;
  1651. std::string greeting = fmt.str();
  1652. return greeting;
  1653. }
  1654. VCMI_LIB_NAMESPACE_END