CGTownInstance.cpp 49 KB

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