CGDwelling.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. /*
  2. * CGDwelling.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 "CGDwelling.h"
  12. #include "../callback/IGameInfoCallback.h"
  13. #include "../callback/IGameEventCallback.h"
  14. #include "../callback/IGameRandomizer.h"
  15. #include "../serializer/JsonSerializeFormat.h"
  16. #include "../entities/faction/CTownHandler.h"
  17. #include "../mapping/CMap.h"
  18. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  19. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  20. #include "../mapObjectConstructors/DwellingInstanceConstructor.h"
  21. #include "../mapObjects/CGHeroInstance.h"
  22. #include "../mapObjects/CGTownInstance.h"
  23. #include "../networkPacks/StackLocation.h"
  24. #include "../networkPacks/PacksForClient.h"
  25. #include "../networkPacks/PacksForClientBattle.h"
  26. #include "../gameState/CGameState.h"
  27. #include "../CPlayerState.h"
  28. #include "../IGameSettings.h"
  29. #include "../CConfigHandler.h"
  30. #include <vstd/RNG.h>
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void CGDwellingRandomizationInfo::serializeJson(JsonSerializeFormat & handler)
  33. {
  34. handler.serializeString("sameAsTown", instanceId);
  35. handler.serializeIdArray("allowedFactions", allowedFactions);
  36. handler.serializeInt("minLevel", minLevel, static_cast<uint8_t>(1));
  37. handler.serializeInt("maxLevel", maxLevel, static_cast<uint8_t>(7));
  38. if(!handler.saving)
  39. {
  40. //todo: safely allow any level > 7
  41. vstd::abetween<uint8_t>(minLevel, 1, 7);
  42. vstd::abetween<uint8_t>(maxLevel, minLevel, 7);
  43. }
  44. }
  45. CGDwelling::CGDwelling(IGameInfoCallback *cb):
  46. CArmedInstance(cb)
  47. {}
  48. CGDwelling::~CGDwelling() = default;
  49. FactionID CGDwelling::randomizeFaction(IGameRandomizer & gameRandomizer)
  50. {
  51. if (ID == Obj::RANDOM_DWELLING_FACTION)
  52. return FactionID(subID.getNum());
  53. assert(ID == Obj::RANDOM_DWELLING || ID == Obj::RANDOM_DWELLING_LVL);
  54. assert(randomizationInfo.has_value());
  55. if (!randomizationInfo)
  56. return FactionID::CASTLE;
  57. CGTownInstance * linkedTown = nullptr;
  58. if (!randomizationInfo->instanceId.empty())
  59. {
  60. auto iter = cb->gameState().getMap().instanceNames.find(randomizationInfo->instanceId);
  61. if(iter == cb->gameState().getMap().instanceNames.end())
  62. logGlobal->error("Map object not found: %s", randomizationInfo->instanceId);
  63. linkedTown = dynamic_cast<CGTownInstance *>(iter->second.get());
  64. }
  65. if (randomizationInfo->identifier != 0)
  66. {
  67. for(auto & townID : cb->gameState().getMap().getAllTowns())
  68. {
  69. auto town = cb->gameState().getTown(townID);
  70. if(town && town->identifier == randomizationInfo->identifier)
  71. {
  72. linkedTown = town;
  73. break;
  74. }
  75. }
  76. }
  77. if (linkedTown)
  78. {
  79. if(linkedTown->ID==Obj::RANDOM_TOWN)
  80. linkedTown->pickRandomObject(gameRandomizer); //we have to randomize the castle first
  81. assert(linkedTown->ID == Obj::TOWN);
  82. if(linkedTown->ID==Obj::TOWN)
  83. return linkedTown->getFactionID();
  84. }
  85. if(!randomizationInfo->allowedFactions.empty())
  86. return *RandomGeneratorUtil::nextItem(randomizationInfo->allowedFactions, gameRandomizer.getDefault());
  87. std::vector<FactionID> potentialPicks;
  88. for (FactionID faction(0); faction < FactionID(LIBRARY->townh->size()); ++faction)
  89. if (LIBRARY->factions()->getById(faction)->hasTown())
  90. potentialPicks.push_back(faction);
  91. assert(!potentialPicks.empty());
  92. return *RandomGeneratorUtil::nextItem(potentialPicks, gameRandomizer.getDefault());
  93. }
  94. int CGDwelling::randomizeLevel(vstd::RNG & rand)
  95. {
  96. if (ID == Obj::RANDOM_DWELLING_LVL)
  97. return subID.getNum();
  98. assert(ID == Obj::RANDOM_DWELLING || ID == Obj::RANDOM_DWELLING_FACTION);
  99. assert(randomizationInfo.has_value());
  100. if (!randomizationInfo)
  101. return rand.nextInt(1, 7) - 1;
  102. if(randomizationInfo->minLevel == randomizationInfo->maxLevel)
  103. return randomizationInfo->minLevel - 1;
  104. return rand.nextInt(randomizationInfo->minLevel, randomizationInfo->maxLevel) - 1;
  105. }
  106. void CGDwelling::pickRandomObject(IGameRandomizer & gameRandomizer)
  107. {
  108. if (ID == Obj::RANDOM_DWELLING || ID == Obj::RANDOM_DWELLING_LVL || ID == Obj::RANDOM_DWELLING_FACTION)
  109. {
  110. FactionID faction = randomizeFaction(gameRandomizer);
  111. int level = randomizeLevel(gameRandomizer.getDefault());
  112. assert(faction != FactionID::NONE && faction != FactionID::NEUTRAL);
  113. assert(level >= 0 && level <= 6);
  114. randomizationInfo.reset();
  115. CreatureID cid = (*LIBRARY->townh)[faction]->town->creatures[level][0];
  116. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  117. //check for block map equality is better but more complex solution
  118. auto testID = [&](const Obj & primaryID) -> MapObjectSubID
  119. {
  120. auto dwellingIDs = LIBRARY->objtypeh->knownSubObjects(primaryID);
  121. for (MapObjectSubID entry : dwellingIDs)
  122. {
  123. const auto * handler = dynamic_cast<const DwellingInstanceConstructor *>(LIBRARY->objtypeh->getHandlerFor(primaryID, entry).get());
  124. if (!handler->isBannedForRandomDwelling() && handler->producesCreature(cid.toCreature()))
  125. return MapObjectSubID(entry);
  126. }
  127. return MapObjectSubID();
  128. };
  129. ID = Obj::CREATURE_GENERATOR1;
  130. subID = testID(Obj::CREATURE_GENERATOR1);
  131. if (subID == MapObjectSubID())
  132. {
  133. ID = Obj::CREATURE_GENERATOR4;
  134. subID = testID(Obj::CREATURE_GENERATOR4);
  135. }
  136. if (subID == MapObjectSubID())
  137. {
  138. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*LIBRARY->townh)[faction]->getNameTranslated(), int(level));
  139. ID = Obj::CREATURE_GENERATOR1;
  140. subID = *RandomGeneratorUtil::nextItem(LIBRARY->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), gameRandomizer.getDefault());
  141. }
  142. setType(ID, subID);
  143. }
  144. }
  145. void CGDwelling::initObj(IGameRandomizer & gameRandomizer)
  146. {
  147. switch(ID.toEnum())
  148. {
  149. case Obj::CREATURE_GENERATOR1:
  150. case Obj::CREATURE_GENERATOR4:
  151. case Obj::WAR_MACHINE_FACTORY:
  152. {
  153. getObjectHandler()->configureObject(this, gameRandomizer);
  154. assert(!creatures.empty());
  155. assert(!creatures[0].second.empty());
  156. break;
  157. }
  158. case Obj::REFUGEE_CAMP:
  159. //is handled within newturn func
  160. break;
  161. default:
  162. assert(0);
  163. break;
  164. }
  165. }
  166. void CGDwelling::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  167. {
  168. switch (what)
  169. {
  170. case ObjProperty::AVAILABLE_CREATURE:
  171. creatures.resize(1);
  172. creatures[0].second.resize(1);
  173. creatures[0].second[0] = identifier.as<CreatureID>();
  174. break;
  175. }
  176. }
  177. void CGDwelling::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  178. {
  179. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  180. {
  181. InfoWindow iw;
  182. iw.type = EInfoWindowMode::AUTO;
  183. iw.player = h->tempOwner;
  184. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  185. iw.text.replaceName(ID, subID);
  186. gameEvents.sendAndApply(iw);
  187. return;
  188. }
  189. PlayerRelations relations = cb->getPlayerRelations( h->tempOwner, tempOwner );
  190. if ( relations == PlayerRelations::ALLIES )
  191. return;//do not allow recruiting or capturing
  192. if(relations == PlayerRelations::ENEMIES && stacksCount() > 0) //object is guarded, owned by enemy
  193. {
  194. BlockingDialog bd(true,false);
  195. bd.player = h->tempOwner;
  196. bd.text.appendLocalString(EMetaText::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  197. bd.text.replaceTextID(getObjectHandler()->getNameTextID());
  198. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  199. bd.text.replaceRawString(CCreature::getQuantityRangeStringForId(Slots().begin()->second->getQuantityID()));
  200. else
  201. bd.text.replaceLocalString(EMetaText::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
  202. bd.text.replaceName(*Slots().begin()->second);
  203. gameEvents.showBlockingDialog(this, &bd);
  204. return;
  205. }
  206. // TODO this shouldn't be hardcoded
  207. if(relations == PlayerRelations::ENEMIES && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  208. {
  209. gameEvents.setOwner(this, h->tempOwner);
  210. }
  211. BlockingDialog bd (true,false);
  212. bd.player = h->tempOwner;
  213. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  214. {
  215. bd.text.appendLocalString(EMetaText::ADVOB_TXT, creatures.size() == 1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  216. bd.text.replaceTextID(getObjectHandler()->getNameTextID());
  217. for(const auto & elem : creatures)
  218. bd.text.replaceNamePlural(elem.second[0]);
  219. }
  220. else if(ID == Obj::REFUGEE_CAMP)
  221. {
  222. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  223. bd.text.replaceName(ID, subID);
  224. for(const auto & elem : creatures)
  225. bd.text.replaceNamePlural(elem.second[0]);
  226. }
  227. else if(ID == Obj::WAR_MACHINE_FACTORY)
  228. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  229. else
  230. throw std::runtime_error("Illegal dwelling!");
  231. if(ID == Obj::REFUGEE_CAMP || (ID == Obj::CREATURE_GENERATOR1 && LIBRARY->creatures()->getById(creatures[0].second[0])->getLevel() != 1))
  232. {
  233. bd.flags |= BlockingDialog::SAFE_TO_AUTOACCEPT;
  234. }
  235. gameEvents.showBlockingDialog(this, &bd);
  236. }
  237. void CGDwelling::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  238. {
  239. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  240. return;
  241. //town growths and War Machines Factories are handled separately
  242. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  243. return;
  244. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  245. {
  246. gameEvents.setObjPropertyID(id, ObjProperty::AVAILABLE_CREATURE, gameRandomizer.rollCreature());
  247. }
  248. bool change = false;
  249. SetAvailableCreatures sac;
  250. sac.creatures = creatures;
  251. sac.tid = id;
  252. for (size_t i = 0; i < creatures.size(); i++)
  253. {
  254. if(!creatures[i].second.empty())
  255. {
  256. bool creaturesAccumulate = false;
  257. if (tempOwner.isValidPlayer())
  258. creaturesAccumulate = cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  259. else
  260. creaturesAccumulate = cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_NEUTRAL);
  261. const CCreature * cre =creatures[i].second[0].toCreature();
  262. TQuantity amount = cre->getGrowth() * (1 + cre->valOfBonuses(BonusType::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(cre->getLevel()));
  263. if (creaturesAccumulate && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  264. sac.creatures[i].first += amount;
  265. else
  266. sac.creatures[i].first = amount;
  267. change = true;
  268. }
  269. }
  270. if(change)
  271. gameEvents.sendAndApply(sac);
  272. updateGuards(gameEvents);
  273. }
  274. std::vector<Component> CGDwelling::getPopupComponents(PlayerColor player) const
  275. {
  276. bool visitedByOwner = getOwner() == player;
  277. std::vector<Component> result;
  278. if (ID == Obj::CREATURE_GENERATOR1 && !creatures.empty())
  279. {
  280. for (auto const & creature : creatures.front().second)
  281. {
  282. if (visitedByOwner)
  283. result.emplace_back(ComponentType::CREATURE, creature, creatures.front().first);
  284. else
  285. result.emplace_back(ComponentType::CREATURE, creature);
  286. }
  287. }
  288. if (ID == Obj::CREATURE_GENERATOR4)
  289. {
  290. for (auto const & creatureLevel : creatures)
  291. {
  292. if (!creatureLevel.second.empty())
  293. {
  294. if (visitedByOwner)
  295. result.emplace_back(ComponentType::CREATURE, creatureLevel.second.back(), creatureLevel.first);
  296. else
  297. result.emplace_back(ComponentType::CREATURE, creatureLevel.second.back());
  298. }
  299. }
  300. }
  301. return result;
  302. }
  303. void CGDwelling::updateGuards(IGameEventCallback & gameEvents) const
  304. {
  305. //TODO: store custom guard config and use it
  306. //TODO: store boolean flag for guards
  307. bool guarded = false;
  308. //default condition - creatures are of level 5 or higher
  309. for (auto creatureEntry : creatures)
  310. {
  311. if (LIBRARY->creatures()->getById(creatureEntry.second.at(0))->getLevel() >= 5 && ID != Obj::REFUGEE_CAMP)
  312. {
  313. guarded = true;
  314. break;
  315. }
  316. }
  317. if (guarded)
  318. {
  319. for (auto creatureEntry : creatures)
  320. {
  321. const CCreature * crea = creatureEntry.second.at(0).toCreature();
  322. SlotID slot = getSlotFor(crea->getId());
  323. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  324. {
  325. ChangeStackCount csc;
  326. csc.army = this->id;
  327. csc.slot = slot;
  328. csc.count = crea->getGrowth() * 3;
  329. csc.mode = ChangeValueMode::ABSOLUTE;
  330. gameEvents.sendAndApply(csc);
  331. }
  332. else //slot is empty, create whole new stack
  333. {
  334. InsertNewStack ns;
  335. ns.army = this->id;
  336. ns.slot = slot;
  337. ns.type = crea->getId();
  338. ns.count = crea->getGrowth() * 3;
  339. gameEvents.sendAndApply(ns);
  340. }
  341. }
  342. }
  343. }
  344. void CGDwelling::heroAcceptsCreatures(IGameEventCallback & gameEvents, const CGHeroInstance *h) const
  345. {
  346. CreatureID crid = creatures[0].second[0];
  347. auto *crs = crid.toCreature();
  348. TQuantity count = creatures[0].first;
  349. if(crs->getLevel() == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  350. {
  351. if(count) //there are available creatures
  352. {
  353. if (cb->getSettings().getBoolean(EGameSettings::DWELLINGS_MERGE_ON_RECRUIT))
  354. {
  355. SlotID testSlot = h->getSlotFor(crid);
  356. if(!testSlot.validSlot()) //no available slot - try merging army of visiting hero
  357. {
  358. std::pair<SlotID, SlotID> toMerge;
  359. if (h->mergeableStacks(toMerge))
  360. {
  361. gameEvents.moveStack(StackLocation(h->id, toMerge.first), StackLocation(h->id, toMerge.second), -1); //merge toMerge.first into toMerge.second
  362. assert(!h->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  363. }
  364. }
  365. }
  366. SlotID slot = h->getSlotFor(crid);
  367. if(!slot.validSlot()) //no available slot
  368. {
  369. InfoWindow iw;
  370. iw.type = EInfoWindowMode::AUTO;
  371. iw.player = h->tempOwner;
  372. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  373. iw.text.replaceNamePlural(crid);
  374. gameEvents.showInfoDialog(&iw);
  375. }
  376. else //give creatures
  377. {
  378. SetAvailableCreatures sac;
  379. sac.tid = id;
  380. sac.creatures = creatures;
  381. sac.creatures[0].first = 0;
  382. InfoWindow iw;
  383. iw.type = EInfoWindowMode::AUTO;
  384. iw.player = h->tempOwner;
  385. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 423); //%d %s join your army.
  386. iw.text.replaceNumber(count);
  387. iw.text.replaceNamePlural(crid);
  388. gameEvents.showInfoDialog(&iw);
  389. gameEvents.sendAndApply(sac);
  390. gameEvents.addToSlot(StackLocation(h->id, slot), crs, count);
  391. }
  392. }
  393. else //there no creatures
  394. {
  395. InfoWindow iw;
  396. iw.type = EInfoWindowMode::AUTO;
  397. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 422); //There are no %s here to recruit.
  398. iw.text.replaceNamePlural(crid);
  399. iw.player = h->tempOwner;
  400. gameEvents.sendAndApply(iw);
  401. }
  402. }
  403. else
  404. {
  405. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  406. {
  407. //there is 1 war machine available to recruit if hero doesn't have one
  408. SetAvailableCreatures sac;
  409. sac.tid = id;
  410. sac.creatures = creatures;
  411. for (auto & entry : sac.creatures)
  412. {
  413. CreatureID creature = entry.second.at(0);
  414. ArtifactID warMachine = creature.toCreature()->warMachine;
  415. if (h->hasArt(warMachine, true, false))
  416. entry.first = 0;
  417. else
  418. entry.first = 1;
  419. }
  420. gameEvents.sendAndApply(sac);
  421. }
  422. auto windowMode = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP) ? EOpenWindowMode::RECRUITMENT_FIRST : EOpenWindowMode::RECRUITMENT_ALL;
  423. gameEvents.showObjectWindow(this, windowMode, h, true);
  424. }
  425. }
  426. void CGDwelling::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance *hero, const BattleResult &result) const
  427. {
  428. if (result.winner == BattleSide::ATTACKER)
  429. {
  430. onHeroVisit(gameEvents, hero);
  431. }
  432. }
  433. void CGDwelling::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  434. {
  435. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  436. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  437. {
  438. if(answer)
  439. gameEvents.startBattle(hero, this);
  440. }
  441. else if(answer)
  442. {
  443. heroAcceptsCreatures(gameEvents, hero);
  444. }
  445. }
  446. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  447. {
  448. switch (ID.toEnum())
  449. {
  450. case Obj::WAR_MACHINE_FACTORY:
  451. case Obj::REFUGEE_CAMP:
  452. //do nothing
  453. break;
  454. case Obj::RANDOM_DWELLING:
  455. case Obj::RANDOM_DWELLING_LVL:
  456. case Obj::RANDOM_DWELLING_FACTION:
  457. if (!handler.saving)
  458. randomizationInfo = CGDwellingRandomizationInfo();
  459. randomizationInfo->serializeJson(handler);
  460. [[fallthrough]];
  461. default:
  462. serializeJsonOwner(handler);
  463. break;
  464. }
  465. }
  466. const IOwnableObject * CGDwelling::asOwnable() const
  467. {
  468. switch (ID.toEnum())
  469. {
  470. case Obj::WAR_MACHINE_FACTORY:
  471. case Obj::REFUGEE_CAMP:
  472. return nullptr; // can't be owned
  473. default:
  474. return this;
  475. }
  476. }
  477. ResourceSet CGDwelling::dailyIncome() const
  478. {
  479. return {};
  480. }
  481. std::vector<CreatureID> CGDwelling::providedCreatures() const
  482. {
  483. if (ID == Obj::WAR_MACHINE_FACTORY || ID == Obj::REFUGEE_CAMP)
  484. return {};
  485. std::vector<CreatureID> result;
  486. for (const auto & level : creatures)
  487. result.insert(result.end(), level.second.begin(), level.second.end());
  488. return result;
  489. }
  490. VCMI_LIB_NAMESPACE_END