CGTownInstance.cpp 44 KB

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