2
0

CGDwelling.cpp 16 KB

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