CGTownInstance.cpp 50 KB

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