CGDwelling.cpp 16 KB

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