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