CGTownInstance.cpp 36 KB

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