CGTownInstance.cpp 43 KB

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