CGTownInstance.cpp 44 KB

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