CGDwelling.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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->getFaction();
  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. {
  150. getObjectHandler()->configureObject(this, rand);
  151. assert(!creatures.empty());
  152. assert(!creatures[0].second.empty());
  153. break;
  154. }
  155. case Obj::REFUGEE_CAMP:
  156. //is handled within newturn func
  157. break;
  158. case Obj::WAR_MACHINE_FACTORY:
  159. creatures.resize(3);
  160. creatures[0].second.emplace_back(CreatureID::BALLISTA);
  161. creatures[1].second.emplace_back(CreatureID::FIRST_AID_TENT);
  162. creatures[2].second.emplace_back(CreatureID::AMMO_CART);
  163. break;
  164. default:
  165. assert(0);
  166. break;
  167. }
  168. }
  169. void CGDwelling::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  170. {
  171. switch (what)
  172. {
  173. case ObjProperty::AVAILABLE_CREATURE:
  174. creatures.resize(1);
  175. creatures[0].second.resize(1);
  176. creatures[0].second[0] = identifier.as<CreatureID>();
  177. break;
  178. }
  179. }
  180. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  181. {
  182. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  183. {
  184. InfoWindow iw;
  185. iw.type = EInfoWindowMode::AUTO;
  186. iw.player = h->tempOwner;
  187. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  188. iw.text.replaceName(ID);
  189. cb->sendAndApply(iw);
  190. return;
  191. }
  192. PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  193. if ( relations == PlayerRelations::ALLIES )
  194. return;//do not allow recruiting or capturing
  195. if(relations == PlayerRelations::ENEMIES && stacksCount() > 0) //object is guarded, owned by enemy
  196. {
  197. BlockingDialog bd(true,false);
  198. bd.player = h->tempOwner;
  199. 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?
  200. bd.text.replaceTextID(getObjectHandler()->getNameTextID());
  201. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  202. bd.text.replaceRawString(CCreature::getQuantityRangeStringForId(Slots().begin()->second->getQuantityID()));
  203. else
  204. bd.text.replaceLocalString(EMetaText::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
  205. bd.text.replaceName(*Slots().begin()->second);
  206. cb->showBlockingDialog(this, &bd);
  207. return;
  208. }
  209. // TODO this shouldn't be hardcoded
  210. if(relations == PlayerRelations::ENEMIES && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  211. {
  212. cb->setOwner(this, h->tempOwner);
  213. }
  214. BlockingDialog bd (true,false);
  215. bd.player = h->tempOwner;
  216. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  217. {
  218. 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?
  219. bd.text.replaceTextID(getObjectHandler()->getNameTextID());
  220. for(const auto & elem : creatures)
  221. bd.text.replaceNamePlural(elem.second[0]);
  222. }
  223. else if(ID == Obj::REFUGEE_CAMP)
  224. {
  225. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  226. bd.text.replaceName(ID);
  227. for(const auto & elem : creatures)
  228. bd.text.replaceNamePlural(elem.second[0]);
  229. }
  230. else if(ID == Obj::WAR_MACHINE_FACTORY)
  231. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  232. else
  233. throw std::runtime_error("Illegal dwelling!");
  234. if(ID == Obj::REFUGEE_CAMP || (ID == Obj::CREATURE_GENERATOR1 && VLC->creatures()->getById(creatures[0].second[0])->getLevel() != 1))
  235. {
  236. bd.flags |= BlockingDialog::SAFE_TO_AUTOACCEPT;
  237. }
  238. cb->showBlockingDialog(this, &bd);
  239. }
  240. void CGDwelling::newTurn(vstd::RNG & rand) const
  241. {
  242. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  243. return;
  244. //town growths and War Machines Factories are handled separately
  245. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  246. return;
  247. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  248. {
  249. cb->setObjPropertyID(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(rand));
  250. }
  251. bool change = false;
  252. SetAvailableCreatures sac;
  253. sac.creatures = creatures;
  254. sac.tid = id;
  255. for (size_t i = 0; i < creatures.size(); i++)
  256. {
  257. if(!creatures[i].second.empty())
  258. {
  259. bool creaturesAccumulate = false;
  260. if (tempOwner.isValidPlayer())
  261. creaturesAccumulate = cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  262. else
  263. creaturesAccumulate = cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_NEUTRAL);
  264. const CCreature * cre =creatures[i].second[0].toCreature();
  265. TQuantity amount = cre->getGrowth() * (1 + cre->valOfBonuses(BonusType::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(cre->getLevel()));
  266. if (creaturesAccumulate && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  267. sac.creatures[i].first += amount;
  268. else
  269. sac.creatures[i].first = amount;
  270. change = true;
  271. }
  272. }
  273. if(change)
  274. cb->sendAndApply(sac);
  275. updateGuards();
  276. }
  277. std::vector<Component> CGDwelling::getPopupComponents(PlayerColor player) const
  278. {
  279. bool visitedByOwner = getOwner() == player;
  280. std::vector<Component> result;
  281. if (ID == Obj::CREATURE_GENERATOR1 && !creatures.empty())
  282. {
  283. for (auto const & creature : creatures.front().second)
  284. {
  285. if (visitedByOwner)
  286. result.emplace_back(ComponentType::CREATURE, creature, creatures.front().first);
  287. else
  288. result.emplace_back(ComponentType::CREATURE, creature);
  289. }
  290. }
  291. if (ID == Obj::CREATURE_GENERATOR4)
  292. {
  293. for (auto const & creatureLevel : creatures)
  294. {
  295. if (!creatureLevel.second.empty())
  296. {
  297. if (visitedByOwner)
  298. result.emplace_back(ComponentType::CREATURE, creatureLevel.second.back(), creatureLevel.first);
  299. else
  300. result.emplace_back(ComponentType::CREATURE, creatureLevel.second.back());
  301. }
  302. }
  303. }
  304. return result;
  305. }
  306. void CGDwelling::updateGuards() const
  307. {
  308. //TODO: store custom guard config and use it
  309. //TODO: store boolean flag for guards
  310. bool guarded = false;
  311. //default condition - creatures are of level 5 or higher
  312. for (auto creatureEntry : creatures)
  313. {
  314. if (VLC->creatures()->getById(creatureEntry.second.at(0))->getLevel() >= 5 && ID != Obj::REFUGEE_CAMP)
  315. {
  316. guarded = true;
  317. break;
  318. }
  319. }
  320. if (guarded)
  321. {
  322. for (auto creatureEntry : creatures)
  323. {
  324. const CCreature * crea = creatureEntry.second.at(0).toCreature();
  325. SlotID slot = getSlotFor(crea->getId());
  326. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  327. {
  328. ChangeStackCount csc;
  329. csc.army = this->id;
  330. csc.slot = slot;
  331. csc.count = crea->getGrowth() * 3;
  332. csc.absoluteValue = true;
  333. cb->sendAndApply(csc);
  334. }
  335. else //slot is empty, create whole new stack
  336. {
  337. InsertNewStack ns;
  338. ns.army = this->id;
  339. ns.slot = slot;
  340. ns.type = crea->getId();
  341. ns.count = crea->getGrowth() * 3;
  342. cb->sendAndApply(ns);
  343. }
  344. }
  345. }
  346. }
  347. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  348. {
  349. CreatureID crid = creatures[0].second[0];
  350. auto *crs = crid.toCreature();
  351. TQuantity count = creatures[0].first;
  352. if(crs->getLevel() == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  353. {
  354. if(count) //there are available creatures
  355. {
  356. if (cb->getSettings().getBoolean(EGameSettings::DWELLINGS_MERGE_ON_RECRUIT))
  357. {
  358. SlotID testSlot = h->getSlotFor(crid);
  359. if(!testSlot.validSlot()) //no available slot - try merging army of visiting hero
  360. {
  361. std::pair<SlotID, SlotID> toMerge;
  362. if (h->mergeableStacks(toMerge))
  363. {
  364. cb->moveStack(StackLocation(h, toMerge.first), StackLocation(h, toMerge.second), -1); //merge toMerge.first into toMerge.second
  365. assert(!h->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  366. }
  367. }
  368. }
  369. SlotID slot = h->getSlotFor(crid);
  370. if(!slot.validSlot()) //no available slot
  371. {
  372. InfoWindow iw;
  373. iw.type = EInfoWindowMode::AUTO;
  374. iw.player = h->tempOwner;
  375. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  376. iw.text.replaceNamePlural(crid);
  377. cb->showInfoDialog(&iw);
  378. }
  379. else //give creatures
  380. {
  381. SetAvailableCreatures sac;
  382. sac.tid = id;
  383. sac.creatures = creatures;
  384. sac.creatures[0].first = 0;
  385. InfoWindow iw;
  386. iw.type = EInfoWindowMode::AUTO;
  387. iw.player = h->tempOwner;
  388. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 423); //%d %s join your army.
  389. iw.text.replaceNumber(count);
  390. iw.text.replaceNamePlural(crid);
  391. cb->showInfoDialog(&iw);
  392. cb->sendAndApply(sac);
  393. cb->addToSlot(StackLocation(h, slot), crs, count);
  394. }
  395. }
  396. else //there no creatures
  397. {
  398. InfoWindow iw;
  399. iw.type = EInfoWindowMode::AUTO;
  400. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 422); //There are no %s here to recruit.
  401. iw.text.replaceNamePlural(crid);
  402. iw.player = h->tempOwner;
  403. cb->sendAndApply(iw);
  404. }
  405. }
  406. else
  407. {
  408. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  409. {
  410. //there is 1 war machine available to recruit if hero doesn't have one
  411. SetAvailableCreatures sac;
  412. sac.tid = id;
  413. sac.creatures = creatures;
  414. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  415. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  416. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  417. cb->sendAndApply(sac);
  418. }
  419. auto windowMode = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP) ? EOpenWindowMode::RECRUITMENT_FIRST : EOpenWindowMode::RECRUITMENT_ALL;
  420. cb->showObjectWindow(this, windowMode, h, true);
  421. }
  422. }
  423. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  424. {
  425. if (result.winner == BattleSide::ATTACKER)
  426. {
  427. onHeroVisit(hero);
  428. }
  429. }
  430. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  431. {
  432. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  433. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  434. {
  435. if(answer)
  436. cb->startBattle(hero, this);
  437. }
  438. else if(answer)
  439. {
  440. heroAcceptsCreatures(hero);
  441. }
  442. }
  443. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  444. {
  445. switch (ID.toEnum())
  446. {
  447. case Obj::WAR_MACHINE_FACTORY:
  448. case Obj::REFUGEE_CAMP:
  449. //do nothing
  450. break;
  451. case Obj::RANDOM_DWELLING:
  452. case Obj::RANDOM_DWELLING_LVL:
  453. case Obj::RANDOM_DWELLING_FACTION:
  454. if (!handler.saving)
  455. randomizationInfo = CGDwellingRandomizationInfo();
  456. randomizationInfo->serializeJson(handler);
  457. [[fallthrough]];
  458. default:
  459. serializeJsonOwner(handler);
  460. break;
  461. }
  462. }
  463. const IOwnableObject * CGDwelling::asOwnable() const
  464. {
  465. switch (ID.toEnum())
  466. {
  467. case Obj::WAR_MACHINE_FACTORY:
  468. case Obj::REFUGEE_CAMP:
  469. return nullptr; // can't be owned
  470. default:
  471. return this;
  472. }
  473. }
  474. ResourceSet CGDwelling::dailyIncome() const
  475. {
  476. return {};
  477. }
  478. std::vector<CreatureID> CGDwelling::providedCreatures() const
  479. {
  480. if (ID == Obj::WAR_MACHINE_FACTORY || ID == Obj::REFUGEE_CAMP)
  481. return {};
  482. std::vector<CreatureID> result;
  483. for (const auto & level : creatures)
  484. result.insert(result.end(), level.second.begin(), level.second.end());
  485. return result;
  486. }
  487. VCMI_LIB_NAMESPACE_END