CGDwelling.cpp 16 KB

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