CGTownInstance.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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. int dwellingBonus = 0;
  485. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  486. {
  487. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  488. }
  489. if(dwellingBonus)
  490. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  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. //statue-of-legion-like bonus: % to base+castle
  496. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH_PERCENT));
  497. for(const auto & b : *bonuses2)
  498. ret.entries.push_back(GrowthInfo::Entry(b->val * (base + castleBonus) / 100, b->Description()));
  499. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  500. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  501. return ret;
  502. }
  503. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  504. {
  505. int totalBonus = 0;
  506. for (const auto& dwelling : dwellings)
  507. {
  508. for (const auto& creature : dwelling->creatures)
  509. {
  510. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  511. }
  512. }
  513. return totalBonus;
  514. }
  515. TResources CGTownInstance::dailyIncome() const
  516. {
  517. TResources ret;
  518. for (auto & p : town->buildings)
  519. {
  520. BuildingID buildingUpgrade;
  521. for (auto & p2 : town->buildings)
  522. {
  523. if (p2.second->upgrade == p.first)
  524. {
  525. buildingUpgrade = p2.first;
  526. }
  527. }
  528. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  529. {
  530. ret += p.second->produce;
  531. }
  532. }
  533. return ret;
  534. }
  535. bool CGTownInstance::hasFort() const
  536. {
  537. return hasBuilt(BuildingID::FORT);
  538. }
  539. bool CGTownInstance::hasCapitol() const
  540. {
  541. return hasBuilt(BuildingID::CAPITOL);
  542. }
  543. CGTownInstance::CGTownInstance()
  544. :CGDwelling(), IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  545. {
  546. this->setNodeType(CBonusSystemNode::TOWN);
  547. }
  548. CGTownInstance::~CGTownInstance()
  549. {
  550. for (auto & elem : bonusingBuildings)
  551. delete elem;
  552. }
  553. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  554. {
  555. if(checkGuild && mageGuildLevel() < level)
  556. return 0;
  557. int ret = 6 - level; //how many spells are available at this level
  558. if (hasBuilt(BuildingSubID::LIBRARY))
  559. ret++;
  560. return ret;
  561. }
  562. bool CGTownInstance::needsLastStack() const
  563. {
  564. if(garrisonHero)
  565. return true;
  566. else return false;
  567. }
  568. void CGTownInstance::setOwner(const PlayerColor player) const
  569. {
  570. removeCapitols(player);
  571. cb->setOwner(this, player);
  572. }
  573. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  574. {
  575. if(!cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  576. {
  577. if(armedGarrison() || visitingHero)
  578. {
  579. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  580. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  581. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  582. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  583. {
  584. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  585. auto nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  586. if(nodeSiege == (CBonusSystemNode *)this)
  587. cb->swapGarrisonOnSiege(this->id);
  588. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  589. }
  590. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  591. }
  592. else
  593. {
  594. auto heroColor = h->getOwner();
  595. onTownCaptured(heroColor);
  596. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  597. {
  598. return; //we just won game, we do not need to perform any extra actions
  599. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  600. }
  601. cb->heroVisitCastle(this, h);
  602. }
  603. }
  604. else if(h->visitablePos() == visitablePos())
  605. {
  606. bool commander_recover = h->commander && !h->commander->alive;
  607. if (commander_recover) // rise commander from dead
  608. {
  609. SetCommanderProperty scp;
  610. scp.heroid = h->id;
  611. scp.which = SetCommanderProperty::ALIVE;
  612. scp.amount = 1;
  613. cb->sendAndApply(&scp);
  614. }
  615. cb->heroVisitCastle(this, h);
  616. // TODO(vmarkovtsev): implement payment for rising the commander
  617. if (commander_recover) // info window about commander
  618. {
  619. InfoWindow iw;
  620. iw.player = h->tempOwner;
  621. iw.text << h->commander->getName();
  622. iw.components.push_back(Component(*h->commander));
  623. cb->showInfoDialog(&iw);
  624. }
  625. }
  626. else
  627. {
  628. logGlobal->error("%s visits allied town of %s from different pos?", h->name, name);
  629. }
  630. }
  631. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  632. {
  633. //FIXME: find out why this issue appears on random maps
  634. if(visitingHero == h)
  635. {
  636. cb->stopHeroVisitCastle(this, h);
  637. logGlobal->trace("%s correctly left town %s", h->name, name);
  638. }
  639. else
  640. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->name, name);
  641. }
  642. std::string CGTownInstance::getObjectName() const
  643. {
  644. return name + ", " + town->faction->name;
  645. }
  646. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  647. {
  648. return town->getBuildingType(subId) != BuildingID::NONE;
  649. }
  650. void CGTownInstance::initOverriddenBids()
  651. {
  652. for(const auto & bid : builtBuildings)
  653. {
  654. auto & overrideThem = town->buildings.at(bid)->overrideBids;
  655. for(auto & overrideIt : overrideThem)
  656. overriddenBuildings.insert(overrideIt);
  657. }
  658. }
  659. bool CGTownInstance::isBonusingBuildingAdded(BuildingID::EBuildingID bid) const
  660. {
  661. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  662. {
  663. return building->getBuildingType().num == bid;
  664. });
  665. return present != bonusingBuildings.end();
  666. }
  667. //it does not check hasBuilt because this check is in the OnHeroVisit handler
  668. void CGTownInstance::tryAddOnePerWeekBonus(BuildingSubID::EBuildingSubID subID)
  669. {
  670. auto bid = town->getBuildingType(subID);
  671. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  672. bonusingBuildings.push_back(new COPWBonus(bid, subID, this));
  673. }
  674. void CGTownInstance::tryAddVisitingBonus(BuildingSubID::EBuildingSubID subID)
  675. {
  676. auto bid = town->getBuildingType(subID);
  677. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  678. bonusingBuildings.push_back(new CTownBonus(bid, subID, this));
  679. }
  680. void CGTownInstance::addTownBonuses()
  681. {
  682. for(const auto & kvp : town->buildings)
  683. {
  684. if(vstd::contains(overriddenBuildings, kvp.first))
  685. continue;
  686. if(kvp.second->IsVisitingBonus())
  687. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  688. if(kvp.second->IsWeekBonus())
  689. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  690. }
  691. }
  692. void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
  693. {
  694. size_t i = 0;
  695. CGTownBuilding * freeIt = nullptr;
  696. for(i = 0; i != bonusingBuildings.size(); i++)
  697. {
  698. if(bonusingBuildings[i]->getBuildingType() == bid)
  699. {
  700. freeIt = bonusingBuildings[i];
  701. break;
  702. }
  703. }
  704. if(freeIt == nullptr)
  705. return;
  706. auto building = town->buildings.at(bid);
  707. auto isVisitingBonus = building->IsVisitingBonus();
  708. auto isWeekBonus = building->IsWeekBonus();
  709. if(!isVisitingBonus && !isWeekBonus)
  710. return;
  711. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  712. if(isVisitingBonus)
  713. delete (CTownBonus *)freeIt;
  714. else if(isWeekBonus)
  715. delete (COPWBonus *)freeIt;
  716. }
  717. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  718. {
  719. blockVisit = true;
  720. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  721. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  722. else
  723. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  724. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  725. {
  726. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  727. int upgradeNum = 0;
  728. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  729. {
  730. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  731. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  732. }
  733. }
  734. initOverriddenBids();
  735. addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
  736. recreateBuildingsBonuses();
  737. updateAppearance();
  738. }
  739. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, BuildingID bid) const
  740. {
  741. return (this->town->faction != nullptr && this->town->faction->index == type && hasBuilt(bid));
  742. }
  743. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  744. {
  745. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  746. {
  747. //give resources if there's a Mystic Pond
  748. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  749. && cb->getDate(Date::DAY) != 1
  750. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  751. )
  752. {
  753. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  754. resID = (resID==2)?1:resID;
  755. int resVal = rand.nextInt(1, 4);//with size 1..4
  756. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  757. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  758. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  759. }
  760. auto manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  761. if (manaVortex != nullptr)
  762. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  763. //get Mana Vortex or Stables bonuses
  764. //same code is in the CGameHandler::buildStructure method
  765. if (visitingHero != nullptr)
  766. cb->visitCastleObjects(this, visitingHero);
  767. if (garrisonHero != nullptr)
  768. cb->visitCastleObjects(this, garrisonHero);
  769. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  770. {
  771. std::vector<SlotID> nativeCrits; //slots
  772. for (auto & elem : Slots())
  773. {
  774. if (elem.second->type->faction == subID) //native
  775. {
  776. nativeCrits.push_back(elem.first); //collect matching slots
  777. }
  778. }
  779. if (nativeCrits.size())
  780. {
  781. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  782. StackLocation sl(this, pos);
  783. const CCreature *c = getCreature(pos);
  784. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  785. {
  786. cb->changeStackCount(sl, c->growth);
  787. }
  788. else //upgrade
  789. {
  790. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  791. }
  792. }
  793. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  794. {
  795. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  796. if (!town->creatures[i].empty())
  797. {
  798. CreatureID c = town->creatures[i][0];
  799. SlotID n;
  800. TQuantity count = creatureGrowth(i);
  801. if (!count) // no dwelling
  802. count = VLC->creh->objects[c]->growth;
  803. {//no lower tiers or above current month
  804. if ((n = getSlotFor(c)).validSlot())
  805. {
  806. StackLocation sl(this, n);
  807. if (slotEmpty(n))
  808. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  809. else //add to existing
  810. cb->changeStackCount(sl, count);
  811. }
  812. }
  813. }
  814. }
  815. }
  816. }
  817. }
  818. /*
  819. int3 CGTownInstance::getSightCenter() const
  820. {
  821. return pos - int3(2,0,0);
  822. }
  823. */
  824. bool CGTownInstance::passableFor(PlayerColor color) const
  825. {
  826. if (!armedGarrison())//empty castle - anyone can visit
  827. return true;
  828. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  829. return false;
  830. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  831. }
  832. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  833. {
  834. offsets = {int3(-1,2,0), int3(-3,2,0)};
  835. }
  836. void CGTownInstance::mergeGarrisonOnSiege() const
  837. {
  838. auto getWeakestStackSlot = [&](ui64 powerLimit)
  839. {
  840. std::vector<SlotID> weakSlots;
  841. auto stacksList = visitingHero->stacks;
  842. std::pair<SlotID, CStackInstance *> pair;
  843. while(stacksList.size())
  844. {
  845. pair = *vstd::minElementByFun(stacksList, [&](std::pair<SlotID, CStackInstance *> elem)
  846. {
  847. return elem.second->getPower();
  848. });
  849. if(powerLimit > pair.second->getPower() &&
  850. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  851. {
  852. weakSlots.push_back(pair.first);
  853. stacksList.erase(pair.first);
  854. }
  855. else
  856. break;
  857. }
  858. if(weakSlots.size())
  859. return *std::max_element(weakSlots.begin(), weakSlots.end());
  860. return SlotID();
  861. };
  862. auto count = static_cast<int>(stacks.size());
  863. for(int i = 0; i < count; i++)
  864. {
  865. auto pair = *vstd::maxElementByFun(stacks, [&](std::pair<SlotID, CStackInstance *> elem)
  866. {
  867. ui64 power = elem.second->getPower();
  868. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  869. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  870. power += visitingHero->getStack(dst).getPower();
  871. return power;
  872. });
  873. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  874. if(dst.validSlot())
  875. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  876. else
  877. {
  878. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  879. if(dst.validSlot())
  880. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  881. }
  882. }
  883. }
  884. void CGTownInstance::removeCapitols (PlayerColor owner) const
  885. {
  886. if (hasCapitol()) // search if there's an older capitol
  887. {
  888. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  889. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  890. {
  891. if (*i != this && (*i)->hasCapitol())
  892. {
  893. RazeStructures rs;
  894. rs.tid = id;
  895. rs.bid.insert(BuildingID::CAPITOL);
  896. rs.destroyed = destroyed;
  897. cb->sendAndApply(&rs);
  898. return;
  899. }
  900. }
  901. }
  902. }
  903. void CGTownInstance::clearArmy() const
  904. {
  905. while(!stacks.empty())
  906. {
  907. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  908. }
  909. }
  910. int CGTownInstance::getBoatType() const
  911. {
  912. switch (town->faction->alignment)
  913. {
  914. case EAlignment::EVIL : return 0;
  915. case EAlignment::GOOD : return 1;
  916. case EAlignment::NEUTRAL : return 2;
  917. }
  918. assert(0);
  919. return -1;
  920. }
  921. int CGTownInstance::getMarketEfficiency() const
  922. {
  923. if(!hasBuiltSomeTradeBuilding())
  924. return 0;
  925. const PlayerState *p = cb->getPlayerState(tempOwner);
  926. assert(p);
  927. int marketCount = 0;
  928. for(const CGTownInstance *t : p->towns)
  929. if(t->hasBuiltSomeTradeBuilding())
  930. marketCount++;
  931. return marketCount;
  932. }
  933. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  934. {
  935. switch(mode)
  936. {
  937. case EMarketMode::RESOURCE_RESOURCE:
  938. case EMarketMode::RESOURCE_PLAYER:
  939. return hasBuilt(BuildingID::MARKETPLACE);
  940. case EMarketMode::ARTIFACT_RESOURCE:
  941. case EMarketMode::RESOURCE_ARTIFACT:
  942. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  943. case EMarketMode::CREATURE_RESOURCE:
  944. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  945. case EMarketMode::CREATURE_UNDEAD:
  946. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  947. case EMarketMode::RESOURCE_SKILL:
  948. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  949. default:
  950. assert(0);
  951. return false;
  952. }
  953. }
  954. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  955. {
  956. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  957. {
  958. std::vector<int> ret;
  959. for(const CArtifact *a : merchantArtifacts)
  960. if(a)
  961. ret.push_back(a->id);
  962. else
  963. ret.push_back(-1);
  964. return ret;
  965. }
  966. else if ( mode == EMarketMode::RESOURCE_SKILL )
  967. {
  968. return universitySkills;
  969. }
  970. else
  971. return IMarket::availableItemsIds(mode);
  972. }
  973. void CGTownInstance::setType(si32 ID, si32 subID)
  974. {
  975. assert(ID == Obj::TOWN); // just in case
  976. CGObjectInstance::setType(ID, subID);
  977. town = (*VLC->townh)[subID]->town;
  978. randomizeArmy(subID);
  979. updateAppearance();
  980. }
  981. void CGTownInstance::updateAppearance()
  982. {
  983. auto terrain = cb->gameState()->getTile(visitablePos())->terType->id;
  984. //FIXME: not the best way to do this
  985. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  986. if (app)
  987. appearance = app;
  988. }
  989. std::string CGTownInstance::nodeName() const
  990. {
  991. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  992. }
  993. void CGTownInstance::deserializationFix()
  994. {
  995. attachTo(townAndVis);
  996. //Hero is already handled by CGameState::attachArmedObjects
  997. // if(visitingHero)
  998. // visitingHero->attachTo(&townAndVis);
  999. // if(garrisonHero)
  1000. // garrisonHero->attachTo(this);
  1001. }
  1002. void CGTownInstance::updateMoraleBonusFromArmy()
  1003. {
  1004. auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
  1005. if(!b)
  1006. {
  1007. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  1008. addNewBonus(b);
  1009. }
  1010. if (garrisonHero)
  1011. {
  1012. b->val = 0;
  1013. CBonusSystemNode::treeHasChanged();
  1014. }
  1015. else
  1016. CArmedInstance::updateMoraleBonusFromArmy();
  1017. }
  1018. void CGTownInstance::recreateBuildingsBonuses()
  1019. {
  1020. BonusList bl;
  1021. getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
  1022. for(auto b : bl)
  1023. removeBonus(b);
  1024. for(const auto & bid : builtBuildings)
  1025. {
  1026. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  1027. continue;
  1028. auto building = town->buildings.at(bid);
  1029. if(building->buildingBonuses.empty())
  1030. continue;
  1031. for(auto & bonus : building->buildingBonuses)
  1032. {
  1033. if(bonus->limiter && bonus->effectRange == Bonus::ONLY_ENEMY_ARMY) //ONLY_ENEMY_ARMY is only mark for OppositeSide limiter to avoid extra dynamic_cast.
  1034. {
  1035. auto bCopy = std::make_shared<Bonus>(*bonus); //just a copy of the shared_ptr has been changed and reassigned.
  1036. bCopy->limiter = std::make_shared<OppositeSideLimiter>(this->getOwner());
  1037. addNewBonus(bCopy);
  1038. continue;
  1039. }
  1040. if(bonus->propagator != nullptr && bonus->propagator->getPropagatorType() == ALL_CREATURES)
  1041. VLC->creh->addBonusForAllCreatures(bonus);
  1042. else
  1043. addNewBonus(bonus);
  1044. }
  1045. }
  1046. }
  1047. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  1048. {
  1049. assert(!!visitingHero == !h);
  1050. if(h)
  1051. {
  1052. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1053. assert(p);
  1054. h->detachFrom(*p);
  1055. h->attachTo(townAndVis);
  1056. visitingHero = h;
  1057. h->visitedTown = this;
  1058. h->inTownGarrison = false;
  1059. }
  1060. else
  1061. {
  1062. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  1063. visitingHero->visitedTown = nullptr;
  1064. visitingHero->detachFrom(townAndVis);
  1065. visitingHero->attachTo(*p);
  1066. visitingHero = nullptr;
  1067. }
  1068. }
  1069. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  1070. {
  1071. assert(!!garrisonHero == !h);
  1072. if(h)
  1073. {
  1074. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1075. assert(p);
  1076. h->detachFrom(*p);
  1077. h->attachTo(*this);
  1078. garrisonHero = h;
  1079. h->visitedTown = this;
  1080. h->inTownGarrison = true;
  1081. }
  1082. else
  1083. {
  1084. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  1085. garrisonHero->visitedTown = nullptr;
  1086. garrisonHero->inTownGarrison = false;
  1087. garrisonHero->detachFrom(*this);
  1088. garrisonHero->attachTo(*p);
  1089. garrisonHero = nullptr;
  1090. }
  1091. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  1092. }
  1093. bool CGTownInstance::armedGarrison() const
  1094. {
  1095. return !stacks.empty() || garrisonHero;
  1096. }
  1097. const CTown * CGTownInstance::getTown() const
  1098. {
  1099. if(ID == Obj::RANDOM_TOWN)
  1100. return VLC->townh->randomTown;
  1101. else
  1102. {
  1103. if(nullptr == town)
  1104. {
  1105. return (*VLC->townh)[subID]->town;
  1106. }
  1107. else
  1108. return town;
  1109. }
  1110. }
  1111. int CGTownInstance::getTownLevel() const
  1112. {
  1113. // count all buildings that are not upgrades
  1114. int level = 0;
  1115. for(const auto & bid : builtBuildings)
  1116. {
  1117. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  1118. level++;
  1119. }
  1120. return level;
  1121. }
  1122. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  1123. {
  1124. return townAndVis;
  1125. }
  1126. const CArmedInstance * CGTownInstance::getUpperArmy() const
  1127. {
  1128. if(garrisonHero)
  1129. return garrisonHero;
  1130. return this;
  1131. }
  1132. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  1133. {
  1134. for(const auto building : bonusingBuildings)
  1135. {
  1136. if(building->getBuildingSubtype() == subId)
  1137. return building;
  1138. }
  1139. return nullptr;
  1140. }
  1141. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  1142. {
  1143. for(const auto & bid : builtBuildings)
  1144. {
  1145. if(town->buildings.at(bid)->IsTradeBuilding())
  1146. return true;
  1147. }
  1148. return false;
  1149. }
  1150. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  1151. {
  1152. for(const auto & bid : builtBuildings)
  1153. {
  1154. if(town->buildings.at(bid)->subId == buildingID)
  1155. return true;
  1156. }
  1157. return false;
  1158. }
  1159. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  1160. {
  1161. return vstd::contains(builtBuildings, buildingID);
  1162. }
  1163. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  1164. {
  1165. if (townID == town->faction->index || townID == ETownType::ANY)
  1166. return hasBuilt(buildingID);
  1167. return false;
  1168. }
  1169. TResources CGTownInstance::getBuildingCost(BuildingID buildingID) const
  1170. {
  1171. if (vstd::contains(town->buildings, buildingID))
  1172. return town->buildings.at(buildingID)->resources;
  1173. else
  1174. {
  1175. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  1176. return TResources();
  1177. }
  1178. }
  1179. CBuilding::TRequired CGTownInstance::genBuildingRequirements(BuildingID buildID, bool deep) const
  1180. {
  1181. const CBuilding * building = town->buildings.at(buildID);
  1182. //TODO: find better solution to prevent infinite loops
  1183. std::set<BuildingID> processed;
  1184. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  1185. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  1186. {
  1187. const CBuilding * build = town->buildings.at(id);
  1188. CBuilding::TRequired::OperatorAll requirements;
  1189. if (!hasBuilt(id))
  1190. {
  1191. if (deep)
  1192. requirements.expressions.push_back(id);
  1193. else
  1194. return id;
  1195. }
  1196. if(!vstd::contains(processed, id))
  1197. {
  1198. processed.insert(id);
  1199. if (build->upgrade != BuildingID::NONE)
  1200. requirements.expressions.push_back(dependTest(build->upgrade));
  1201. requirements.expressions.push_back(build->requirements.morph(dependTest));
  1202. }
  1203. return requirements;
  1204. };
  1205. CBuilding::TRequired::OperatorAll requirements;
  1206. if (building->upgrade != BuildingID::NONE)
  1207. {
  1208. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1209. requirements.expressions.push_back(dependTest(upgr->bid));
  1210. processed.clear();
  1211. }
  1212. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1213. CBuilding::TRequired::Variant variant(requirements);
  1214. CBuilding::TRequired ret(variant);
  1215. ret.minimize();
  1216. return ret;
  1217. }
  1218. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  1219. {
  1220. if(visitingHero == h)
  1221. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1222. else if(garrisonHero == h)
  1223. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1224. else
  1225. {
  1226. //should never ever happen
  1227. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->name, structureInstanceID);
  1228. throw std::runtime_error("internal error");
  1229. }
  1230. }
  1231. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  1232. {
  1233. if(result.winner == BattleSide::ATTACKER)
  1234. {
  1235. clearArmy();
  1236. onTownCaptured(hero->getOwner());
  1237. }
  1238. }
  1239. void CGTownInstance::onTownCaptured(const PlayerColor winner) const
  1240. {
  1241. setOwner(winner);
  1242. FoWChange fw;
  1243. fw.player = winner;
  1244. fw.mode = 1;
  1245. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  1246. cb->sendAndApply(& fw);
  1247. }
  1248. void CGTownInstance::afterAddToMap(CMap * map)
  1249. {
  1250. if(ID == Obj::TOWN)
  1251. map->towns.push_back(this);
  1252. }
  1253. void CGTownInstance::afterRemoveFromMap(CMap * map)
  1254. {
  1255. if (ID == Obj::TOWN)
  1256. vstd::erase_if_present(map->towns, this);
  1257. }
  1258. void CGTownInstance::reset()
  1259. {
  1260. CGTownInstance::merchantArtifacts.clear();
  1261. CGTownInstance::universitySkills.clear();
  1262. }
  1263. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1264. {
  1265. CGObjectInstance::serializeJsonOwner(handler);
  1266. CCreatureSet::serializeJson(handler, "army", 7);
  1267. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1268. handler.serializeString("name", name);
  1269. {
  1270. auto decodeBuilding = [this](const std::string & identifier) -> si32
  1271. {
  1272. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  1273. if(rawId)
  1274. return rawId.get();
  1275. else
  1276. return -1;
  1277. };
  1278. auto encodeBuilding = [this](si32 index) -> std::string
  1279. {
  1280. return getTown()->buildings.at(BuildingID(index))->identifier;
  1281. };
  1282. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  1283. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  1284. if(handler.saving)
  1285. {
  1286. bool customBuildings = false;
  1287. boost::logic::tribool hasFort(false);
  1288. for(const BuildingID & id : forbiddenBuildings)
  1289. {
  1290. buildingsLIC.none.insert(id);
  1291. customBuildings = true;
  1292. }
  1293. for(const BuildingID & id : builtBuildings)
  1294. {
  1295. if(id == BuildingID::DEFAULT)
  1296. continue;
  1297. const CBuilding * building = getTown()->buildings.at(id);
  1298. if(building->mode == CBuilding::BUILD_AUTO)
  1299. continue;
  1300. if(id == BuildingID::FORT)
  1301. hasFort = true;
  1302. buildingsLIC.all.insert(id);
  1303. customBuildings = true;
  1304. }
  1305. if(customBuildings)
  1306. handler.serializeLIC("buildings", buildingsLIC);
  1307. else
  1308. handler.serializeBool("hasFort",hasFort);
  1309. }
  1310. else
  1311. {
  1312. handler.serializeLIC("buildings", buildingsLIC);
  1313. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1314. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1315. {
  1316. builtBuildings.insert(BuildingID::DEFAULT);
  1317. bool hasFort = false;
  1318. handler.serializeBool("hasFort",hasFort);
  1319. if(hasFort)
  1320. builtBuildings.insert(BuildingID::FORT);
  1321. }
  1322. else
  1323. {
  1324. for(const si32 item : buildingsLIC.none)
  1325. forbiddenBuildings.insert(BuildingID(item));
  1326. for(const si32 item : buildingsLIC.all)
  1327. builtBuildings.insert(BuildingID(item));
  1328. }
  1329. }
  1330. }
  1331. {
  1332. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1333. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1334. if(handler.saving)
  1335. {
  1336. for(SpellID id : possibleSpells)
  1337. spellsLIC.any[id.num] = true;
  1338. for(SpellID id : obligatorySpells)
  1339. spellsLIC.all[id.num] = true;
  1340. }
  1341. handler.serializeLIC("spells", spellsLIC);
  1342. if(!handler.saving)
  1343. {
  1344. possibleSpells.clear();
  1345. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1346. {
  1347. if(spellsLIC.any[idx])
  1348. possibleSpells.push_back(SpellID(idx));
  1349. }
  1350. obligatorySpells.clear();
  1351. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1352. {
  1353. if(spellsLIC.all[idx])
  1354. obligatorySpells.push_back(SpellID(idx));
  1355. }
  1356. }
  1357. }
  1358. }
  1359. PlayerColor CGTownBuilding::getOwner() const
  1360. {
  1361. return town->getOwner();
  1362. }
  1363. int32_t CGTownBuilding::getObjGroupIndex() const
  1364. {
  1365. return -1;
  1366. }
  1367. int32_t CGTownBuilding::getObjTypeIndex() const
  1368. {
  1369. return 0;
  1370. }
  1371. int3 CGTownBuilding::visitablePos() const
  1372. {
  1373. return town->visitablePos();
  1374. }
  1375. int3 CGTownBuilding::getPosition() const
  1376. {
  1377. return town->getPosition();
  1378. }
  1379. COPWBonus::COPWBonus(BuildingID bid, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1380. {
  1381. bID = bid;
  1382. bType = subId;
  1383. town = cgTown;
  1384. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1385. }
  1386. void COPWBonus::setProperty(ui8 what, ui32 val)
  1387. {
  1388. switch (what)
  1389. {
  1390. case ObjProperty::VISITORS:
  1391. visitors.insert(val);
  1392. break;
  1393. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1394. visitors.clear();
  1395. break;
  1396. }
  1397. }
  1398. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  1399. {
  1400. ObjectInstanceID heroID = h->id;
  1401. if(town->hasBuilt(bID))
  1402. {
  1403. InfoWindow iw;
  1404. iw.player = h->tempOwner;
  1405. switch (this->bType)
  1406. {
  1407. case BuildingSubID::STABLES:
  1408. if(!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1409. {
  1410. GiveBonus gb;
  1411. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  1412. gb.id = heroID.getNum();
  1413. cb->giveHeroBonus(&gb);
  1414. SetMovePoints mp;
  1415. mp.val = 600;
  1416. mp.absolute = false;
  1417. mp.hid = heroID;
  1418. cb->setMovePoints(&mp);
  1419. iw.text << VLC->generaltexth->allTexts[580];
  1420. cb->showInfoDialog(&iw);
  1421. }
  1422. break;
  1423. case BuildingSubID::MANA_VORTEX:
  1424. if(visitors.empty())
  1425. {
  1426. if(h->mana < h->manaLimit() * 2)
  1427. cb->setManaPoints (heroID, 2 * h->manaLimit());
  1428. //TODO: investigate line below
  1429. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1430. iw.text << getVisitingBonusGreeting();
  1431. cb->showInfoDialog(&iw);
  1432. //extra visit penalty if hero alredy had double mana points (or even more?!)
  1433. town->addHeroToStructureVisitors(h, indexOnTV);
  1434. }
  1435. break;
  1436. }
  1437. }
  1438. }
  1439. CTownBonus::CTownBonus(BuildingID index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1440. {
  1441. bID = index;
  1442. bType = subId;
  1443. town = cgTown;
  1444. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1445. }
  1446. void CTownBonus::setProperty (ui8 what, ui32 val)
  1447. {
  1448. if(what == ObjProperty::VISITORS)
  1449. visitors.insert(ObjectInstanceID(val));
  1450. }
  1451. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  1452. {
  1453. ObjectInstanceID heroID = h->id;
  1454. if(town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
  1455. {
  1456. si64 val = 0;
  1457. InfoWindow iw;
  1458. PrimarySkill::PrimarySkill what = PrimarySkill::NONE;
  1459. switch(bType)
  1460. {
  1461. case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge
  1462. what = PrimarySkill::KNOWLEDGE;
  1463. val = 1;
  1464. iw.components.push_back(Component(Component::PRIM_SKILL, 3, 1, 0));
  1465. break;
  1466. case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire
  1467. what = PrimarySkill::SPELL_POWER;
  1468. val = 1;
  1469. iw.components.push_back(Component(Component::PRIM_SKILL, 2, 1, 0));
  1470. break;
  1471. case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla
  1472. what = PrimarySkill::ATTACK;
  1473. val = 1;
  1474. iw.components.push_back(Component(Component::PRIM_SKILL, 0, 1, 0));
  1475. break;
  1476. case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars
  1477. what = PrimarySkill::EXPERIENCE;
  1478. val = static_cast<int>(h->calculateXp(1000));
  1479. iw.components.push_back(Component(Component::EXPERIENCE, 0, val, 0));
  1480. break;
  1481. case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords
  1482. what = PrimarySkill::DEFENSE;
  1483. val = 1;
  1484. iw.components.push_back(Component(Component::PRIM_SKILL, 1, 1, 0));
  1485. break;
  1486. case BuildingSubID::CUSTOM_VISITING_BONUS:
  1487. const auto building = town->town->buildings.at(bID);
  1488. if(!h->hasBonusFrom(Bonus::TOWN_STRUCTURE, Bonus::getSid32(building->town->faction->index, building->bid)))
  1489. {
  1490. const auto & bonuses = building->onVisitBonuses;
  1491. applyBonuses(const_cast<CGHeroInstance *>(h), bonuses);
  1492. }
  1493. break;
  1494. }
  1495. if(what != PrimarySkill::NONE)
  1496. {
  1497. iw.player = cb->getOwner(heroID);
  1498. iw.text << getVisitingBonusGreeting();
  1499. cb->showInfoDialog(&iw);
  1500. cb->changePrimSkill (cb->getHero(heroID), what, val);
  1501. town->addHeroToStructureVisitors(h, indexOnTV);
  1502. }
  1503. }
  1504. }
  1505. void CTownBonus::applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const
  1506. {
  1507. auto addToVisitors = false;
  1508. for(auto bonus : bonuses)
  1509. {
  1510. GiveBonus gb;
  1511. InfoWindow iw;
  1512. if(bonus->type == Bonus::TOWN_MAGIC_WELL)
  1513. {
  1514. if(h->mana >= h->manaLimit())
  1515. return;
  1516. cb->setManaPoints(h->id, h->manaLimit());
  1517. bonus->duration = Bonus::ONE_DAY;
  1518. }
  1519. gb.bonus = * bonus;
  1520. gb.id = h->id.getNum();
  1521. cb->giveHeroBonus(&gb);
  1522. if(bonus->duration == Bonus::PERMANENT)
  1523. addToVisitors = true;
  1524. iw.player = cb->getOwner(h->id);
  1525. iw.text << getCustomBonusGreeting(gb.bonus);
  1526. cb->showInfoDialog(&iw);
  1527. }
  1528. if(addToVisitors)
  1529. town->addHeroToStructureVisitors(h, indexOnTV);
  1530. }
  1531. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1532. : count(_count)
  1533. {
  1534. description = boost::str(boost::format(format) % count);
  1535. }
  1536. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  1537. : count(_count)
  1538. {
  1539. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->Name() % count);
  1540. }
  1541. GrowthInfo::Entry::Entry(int _count, const std::string &fullDescription)
  1542. : count(_count)
  1543. {
  1544. description = fullDescription;
  1545. }
  1546. CTownAndVisitingHero::CTownAndVisitingHero()
  1547. {
  1548. setNodeType(TOWN_AND_VISITOR);
  1549. }
  1550. int GrowthInfo::totalGrowth() const
  1551. {
  1552. int ret = 0;
  1553. for(const Entry &entry : entries)
  1554. ret += entry.count;
  1555. return ret;
  1556. }
  1557. const std::string CGTownBuilding::getVisitingBonusGreeting() const
  1558. {
  1559. auto bonusGreeting = town->town->getGreeting(bType);
  1560. if(!bonusGreeting.empty())
  1561. return bonusGreeting;
  1562. switch(bType)
  1563. {
  1564. case BuildingSubID::MANA_VORTEX:
  1565. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingManaVortex"));
  1566. break;
  1567. case BuildingSubID::KNOWLEDGE_VISITING_BONUS:
  1568. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingKnowledge"));
  1569. break;
  1570. case BuildingSubID::SPELL_POWER_VISITING_BONUS:
  1571. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingSpellPower"));
  1572. break;
  1573. case BuildingSubID::ATTACK_VISITING_BONUS:
  1574. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingAttack"));
  1575. break;
  1576. case BuildingSubID::EXPERIENCE_VISITING_BONUS:
  1577. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingExperience"));
  1578. break;
  1579. case BuildingSubID::DEFENSE_VISITING_BONUS:
  1580. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingDefence"));
  1581. break;
  1582. }
  1583. auto buildingName = town->town->getSpecialBuilding(bType)->Name();
  1584. if(bonusGreeting.empty())
  1585. {
  1586. bonusGreeting = "Error: Bonus greeting for '%s' is not localized.";
  1587. logGlobal->error("'%s' building of '%s' faction has not localized bonus greeting.", buildingName, town->town->getLocalizedFactionName());
  1588. }
  1589. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1590. town->town->setGreeting(bType, bonusGreeting);
  1591. return bonusGreeting;
  1592. }
  1593. const std::string CGTownBuilding::getCustomBonusGreeting(const Bonus & bonus) const
  1594. {
  1595. if(bonus.type == Bonus::TOWN_MAGIC_WELL)
  1596. {
  1597. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingInTownMagicWell"));
  1598. auto buildingName = town->town->getSpecialBuilding(bType)->Name();
  1599. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1600. return bonusGreeting;
  1601. }
  1602. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingCustomBonus")); //"%s gives you +%d %s%s"
  1603. std::string param = "";
  1604. std::string until = "";
  1605. if(bonus.type == Bonus::MORALE)
  1606. param = VLC->generaltexth->allTexts[384];
  1607. else if(bonus.type == Bonus::LUCK)
  1608. param = VLC->generaltexth->allTexts[385];
  1609. until = bonus.duration == (ui16)Bonus::ONE_BATTLE
  1610. ? VLC->generaltexth->translate("vcmi.townHall.greetingCustomUntil") : ".";
  1611. boost::format fmt = boost::format(bonusGreeting) % bonus.description % bonus.val % param % until;
  1612. std::string greeting = fmt.str();
  1613. return greeting;
  1614. }
  1615. VCMI_LIB_NAMESPACE_END