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