CGTownInstance.cpp 51 KB

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