CGTownInstance.cpp 51 KB

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