CGTownInstance.cpp 49 KB

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