CGTownInstance.cpp 40 KB

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