CCreatureSet.cpp 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. /*
  2. * CCreatureSet.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 "CCreatureSet.h"
  12. #include "ArtifactUtils.h"
  13. #include "CConfigHandler.h"
  14. #include "CCreatureHandler.h"
  15. #include "GameLibrary.h"
  16. #include "IGameSettings.h"
  17. #include "entities/hero/CHeroHandler.h"
  18. #include "mapObjects/CGHeroInstance.h"
  19. #include "modding/ModScope.h"
  20. #include "IGameCallback.h"
  21. #include "texts/CGeneralTextHandler.h"
  22. #include "spells/CSpellHandler.h"
  23. #include "IBonusTypeHandler.h"
  24. #include "serializer/JsonSerializeFormat.h"
  25. #include "gameState/CGameState.h"
  26. #include <vcmi/FactionService.h>
  27. #include <vcmi/Faction.h>
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. bool CreatureSlotComparer::operator()(const TPairCreatureSlot & lhs, const TPairCreatureSlot & rhs)
  30. {
  31. return lhs.first->getAIValue() < rhs.first->getAIValue(); // Descendant order sorting
  32. }
  33. const CStackInstance & CCreatureSet::operator[](const SlotID & slot) const
  34. {
  35. auto i = stacks.find(slot);
  36. if (i != stacks.end())
  37. return *i->second;
  38. else
  39. throw std::runtime_error("That slot is empty!");
  40. }
  41. const CCreature * CCreatureSet::getCreature(const SlotID & slot) const
  42. {
  43. auto i = stacks.find(slot);
  44. if (i != stacks.end())
  45. return i->second->getCreature();
  46. else
  47. return nullptr;
  48. }
  49. bool CCreatureSet::setCreature(SlotID slot, CreatureID type, TQuantity quantity) /*slots 0 to 6 */
  50. {
  51. if(!slot.validSlot())
  52. {
  53. logGlobal->error("Cannot set slot %d", slot.getNum());
  54. return false;
  55. }
  56. if(!quantity)
  57. {
  58. logGlobal->warn("Using set creature to delete stack?");
  59. eraseStack(slot);
  60. return true;
  61. }
  62. if(hasStackAtSlot(slot)) //remove old creature
  63. eraseStack(slot);
  64. auto * armyObj = getArmy();
  65. bool isHypotheticArmy = armyObj ? armyObj->isHypothetic() : false;
  66. putStack(slot, std::make_unique<CStackInstance>(armyObj ? armyObj->cb : nullptr, type, quantity, isHypotheticArmy));
  67. return true;
  68. }
  69. SlotID CCreatureSet::getSlotFor(const CreatureID & creature, ui32 slotsAmount) const /*returns -1 if no slot available */
  70. {
  71. return getSlotFor(creature.toCreature(), slotsAmount);
  72. }
  73. SlotID CCreatureSet::getSlotFor(const CCreature *c, ui32 slotsAmount) const
  74. {
  75. assert(c);
  76. for(const auto & elem : stacks)
  77. {
  78. if(elem.second->getType() == c)
  79. {
  80. return elem.first; //if there is already such creature we return its slot id
  81. }
  82. }
  83. return getFreeSlot(slotsAmount);
  84. }
  85. bool CCreatureSet::hasCreatureSlots(const CCreature * c, const SlotID & exclude) const
  86. {
  87. assert(c);
  88. for(const auto & elem : stacks) // elem is const
  89. {
  90. if(elem.first == exclude) // Check slot
  91. continue;
  92. if(!elem.second || !elem.second->getType()) // Check creature
  93. continue;
  94. if(elem.second->getType() == c)
  95. return true;
  96. }
  97. return false;
  98. }
  99. std::vector<SlotID> CCreatureSet::getCreatureSlots(const CCreature * c, const SlotID & exclude, TQuantity ignoreAmount) const
  100. {
  101. assert(c);
  102. std::vector<SlotID> result;
  103. for(const auto & elem : stacks)
  104. {
  105. if(elem.first == exclude)
  106. continue;
  107. if(!elem.second || !elem.second->getType() || elem.second->getType() != c)
  108. continue;
  109. if(elem.second->count == ignoreAmount || elem.second->count < 1)
  110. continue;
  111. result.push_back(elem.first);
  112. }
  113. return result;
  114. }
  115. bool CCreatureSet::isCreatureBalanced(const CCreature * c, TQuantity ignoreAmount) const
  116. {
  117. assert(c);
  118. TQuantity max = 0;
  119. auto min = std::numeric_limits<TQuantity>::max();
  120. for(const auto & elem : stacks)
  121. {
  122. if(!elem.second || !elem.second->getType() || elem.second->getType() != c)
  123. continue;
  124. const auto count = elem.second->count;
  125. if(count == ignoreAmount || count < 1)
  126. continue;
  127. if(count > max)
  128. max = count;
  129. if(count < min)
  130. min = count;
  131. if(max - min > 1)
  132. return false;
  133. }
  134. return true;
  135. }
  136. SlotID CCreatureSet::getFreeSlot(ui32 slotsAmount) const
  137. {
  138. for(ui32 i=0; i<slotsAmount; i++)
  139. {
  140. if(!vstd::contains(stacks, SlotID(i)))
  141. {
  142. return SlotID(i); //return first free slot
  143. }
  144. }
  145. return SlotID(); //no slot available
  146. }
  147. std::vector<SlotID> CCreatureSet::getFreeSlots(ui32 slotsAmount) const
  148. {
  149. std::vector<SlotID> freeSlots;
  150. for(ui32 i = 0; i < slotsAmount; i++)
  151. {
  152. auto slot = SlotID(i);
  153. if(!vstd::contains(stacks, slot))
  154. freeSlots.push_back(slot);
  155. }
  156. return freeSlots;
  157. }
  158. std::queue<SlotID> CCreatureSet::getFreeSlotsQueue(ui32 slotsAmount) const
  159. {
  160. std::queue<SlotID> freeSlots;
  161. for (ui32 i = 0; i < slotsAmount; i++)
  162. {
  163. auto slot = SlotID(i);
  164. if(!vstd::contains(stacks, slot))
  165. freeSlots.push(slot);
  166. }
  167. return freeSlots;
  168. }
  169. TMapCreatureSlot CCreatureSet::getCreatureMap() const
  170. {
  171. TMapCreatureSlot creatureMap;
  172. TMapCreatureSlot::key_compare keyComp = creatureMap.key_comp();
  173. // https://stackoverflow.com/questions/97050/stdmap-insert-or-stdmap-find
  174. // https://www.cplusplus.com/reference/map/map/key_comp/
  175. for(const auto & pair : stacks)
  176. {
  177. const auto * creature = pair.second->getCreature();
  178. auto slot = pair.first;
  179. auto lb = creatureMap.lower_bound(creature);
  180. if(lb != creatureMap.end() && !(keyComp(creature, lb->first)))
  181. continue;
  182. creatureMap.insert(lb, TMapCreatureSlot::value_type(creature, slot));
  183. }
  184. return creatureMap;
  185. }
  186. TCreatureQueue CCreatureSet::getCreatureQueue(const SlotID & exclude) const
  187. {
  188. TCreatureQueue creatureQueue;
  189. for(const auto & pair : stacks)
  190. {
  191. if(pair.first == exclude)
  192. continue;
  193. creatureQueue.push(std::make_pair(pair.second->getCreature(), pair.first));
  194. }
  195. return creatureQueue;
  196. }
  197. TQuantity CCreatureSet::getStackCount(const SlotID & slot) const
  198. {
  199. auto i = stacks.find(slot);
  200. if (i != stacks.end())
  201. return i->second->count;
  202. else
  203. return 0; //TODO? consider issuing a warning
  204. }
  205. TExpType CCreatureSet::getStackExperience(const SlotID & slot) const
  206. {
  207. auto i = stacks.find(slot);
  208. if (i != stacks.end())
  209. return i->second->experience;
  210. else
  211. return 0; //TODO? consider issuing a warning
  212. }
  213. bool CCreatureSet::mergeableStacks(std::pair<SlotID, SlotID> & out, const SlotID & preferable) const /*looks for two same stacks, returns slot positions */
  214. {
  215. //try to match creature to our preferred stack
  216. if(preferable.validSlot() && vstd::contains(stacks, preferable))
  217. {
  218. const CCreature *cr = stacks.find(preferable)->second->getCreature();
  219. for(const auto & elem : stacks)
  220. {
  221. if(cr == elem.second->getType() && elem.first != preferable)
  222. {
  223. out.first = preferable;
  224. out.second = elem.first;
  225. return true;
  226. }
  227. }
  228. }
  229. for(const auto & stack : stacks)
  230. {
  231. for(const auto & elem : stacks)
  232. {
  233. if(stack.second->getType() == elem.second->getType() && stack.first != elem.first)
  234. {
  235. out.first = stack.first;
  236. out.second = elem.first;
  237. return true;
  238. }
  239. }
  240. }
  241. return false;
  242. }
  243. void CCreatureSet::sweep()
  244. {
  245. for(auto i=stacks.begin(); i!=stacks.end(); ++i)
  246. {
  247. if(!i->second->count)
  248. {
  249. stacks.erase(i);
  250. sweep();
  251. break;
  252. }
  253. }
  254. }
  255. void CCreatureSet::addToSlot(const SlotID & slot, const CreatureID & cre, TQuantity count, bool allowMerging)
  256. {
  257. const CCreature *c = cre.toCreature();
  258. if(!hasStackAtSlot(slot))
  259. {
  260. setCreature(slot, cre, count);
  261. }
  262. else if(getCreature(slot) == c && allowMerging) //that slot was empty or contained same type creature
  263. {
  264. setStackCount(slot, getStackCount(slot) + count);
  265. }
  266. else
  267. {
  268. logGlobal->error("Failed adding to slot!");
  269. }
  270. }
  271. void CCreatureSet::addToSlot(const SlotID & slot, std::unique_ptr<CStackInstance> stack, bool allowMerging)
  272. {
  273. assert(stack->valid(true));
  274. if(!hasStackAtSlot(slot))
  275. {
  276. putStack(slot, std::move(stack));
  277. }
  278. else if(allowMerging && stack->getType() == getCreature(slot))
  279. {
  280. joinStack(slot, std::move(stack));
  281. }
  282. else
  283. {
  284. logGlobal->error("Cannot add to slot %d stack %s", slot.getNum(), stack->nodeName());
  285. }
  286. }
  287. void CCreatureSet::deserializationFix()
  288. {
  289. for(const auto & elem : stacks)
  290. {
  291. elem.second->attachTo(*getArmy());
  292. elem.second->artDeserializationFix(elem.second.get());
  293. }
  294. }
  295. bool CCreatureSet::validTypes(bool allowUnrandomized) const
  296. {
  297. for(const auto & elem : stacks)
  298. {
  299. if(!elem.second->valid(allowUnrandomized))
  300. return false;
  301. }
  302. return true;
  303. }
  304. bool CCreatureSet::slotEmpty(const SlotID & slot) const
  305. {
  306. return !hasStackAtSlot(slot);
  307. }
  308. bool CCreatureSet::needsLastStack() const
  309. {
  310. return false;
  311. }
  312. ui64 CCreatureSet::getArmyStrength(int fortLevel) const
  313. {
  314. ui64 ret = 0;
  315. for (const auto& elem : stacks)
  316. {
  317. ui64 powerToAdd = elem.second->getPower();
  318. if (fortLevel > 0)
  319. {
  320. if (!elem.second->hasBonusOfType(BonusType::FLYING))
  321. {
  322. powerToAdd /= fortLevel;
  323. if (!elem.second->hasBonusOfType(BonusType::SHOOTER))
  324. powerToAdd /= fortLevel;
  325. }
  326. }
  327. ret += powerToAdd;
  328. }
  329. return ret;
  330. }
  331. ui64 CCreatureSet::getArmyCost() const
  332. {
  333. ui64 ret = 0;
  334. for (const auto& elem : stacks)
  335. ret += elem.second->getMarketValue();
  336. return ret;
  337. }
  338. ui64 CCreatureSet::getPower(const SlotID & slot) const
  339. {
  340. return getStack(slot).getPower();
  341. }
  342. std::string CCreatureSet::getRoughAmount(const SlotID & slot, int mode) const
  343. {
  344. /// Mode represent return string format
  345. /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2
  346. CCreature::CreatureQuantityId quantity = CCreature::getQuantityID(getStackCount(slot));
  347. if((int)quantity)
  348. {
  349. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  350. return CCreature::getQuantityRangeStringForId(quantity);
  351. return LIBRARY->generaltexth->arraytxt[(174 + mode) + 3*(int)quantity];
  352. }
  353. return "";
  354. }
  355. std::string CCreatureSet::getArmyDescription() const
  356. {
  357. std::string text;
  358. std::vector<std::string> guards;
  359. for(const auto & elem : stacks)
  360. {
  361. auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->getNamePluralTranslated());
  362. guards.push_back(str);
  363. }
  364. if(!guards.empty())
  365. {
  366. for(int i = 0; i < guards.size(); i++)
  367. {
  368. text += guards[i];
  369. if(i + 2 < guards.size())
  370. text += ", ";
  371. else if(i + 2 == guards.size())
  372. text += LIBRARY->generaltexth->allTexts[237];
  373. }
  374. }
  375. return text;
  376. }
  377. int CCreatureSet::stacksCount() const
  378. {
  379. return static_cast<int>(stacks.size());
  380. }
  381. void CCreatureSet::setFormation(EArmyFormation mode)
  382. {
  383. formation = mode;
  384. }
  385. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  386. {
  387. assert(hasStackAtSlot(slot));
  388. assert(stacks[slot]->count + count > 0);
  389. if (count > stacks[slot]->count)
  390. stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
  391. stacks[slot]->count = count;
  392. armyChanged();
  393. }
  394. void CCreatureSet::giveStackExp(TExpType exp)
  395. {
  396. for(TSlots::const_iterator i = stacks.begin(); i != stacks.end(); i++)
  397. i->second->giveStackExp(exp);
  398. }
  399. void CCreatureSet::setStackExp(const SlotID & slot, TExpType exp)
  400. {
  401. assert(hasStackAtSlot(slot));
  402. stacks[slot]->experience = exp;
  403. }
  404. void CCreatureSet::clearSlots()
  405. {
  406. while(!stacks.empty())
  407. {
  408. eraseStack(stacks.begin()->first);
  409. }
  410. }
  411. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  412. {
  413. assert(hasStackAtSlot(slot));
  414. return *getStackPtr(slot);
  415. }
  416. CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  417. {
  418. if(hasStackAtSlot(slot))
  419. return stacks.find(slot)->second.get();
  420. else return nullptr;
  421. }
  422. void CCreatureSet::eraseStack(const SlotID & slot)
  423. {
  424. assert(hasStackAtSlot(slot));
  425. detachStack(slot);
  426. }
  427. bool CCreatureSet::contains(const CStackInstance *stack) const
  428. {
  429. if(!stack)
  430. return false;
  431. for(const auto & elem : stacks)
  432. if(elem.second.get() == stack)
  433. return true;
  434. return false;
  435. }
  436. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  437. {
  438. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  439. if (h && h->getCommander() == stack)
  440. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  441. if(!stack)
  442. return SlotID();
  443. for(const auto & elem : stacks)
  444. if(elem.second.get() == stack)
  445. return elem.first;
  446. return SlotID();
  447. }
  448. void CCreatureSet::putStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  449. {
  450. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  451. assert(!hasStackAtSlot(slot));
  452. stacks[slot] = std::move(stack);
  453. stacks[slot]->setArmy(getArmy());
  454. armyChanged();
  455. }
  456. void CCreatureSet::joinStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  457. {
  458. [[maybe_unused]] const CCreature *c = getCreature(slot);
  459. assert(c == stack->getType());
  460. assert(c);
  461. //TODO move stuff
  462. changeStackCount(slot, stack->count);
  463. }
  464. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  465. {
  466. setStackCount(slot, getStackCount(slot) + toAdd);
  467. }
  468. CCreatureSet::~CCreatureSet() = default;
  469. void CCreatureSet::setToArmy(CSimpleArmy &src)
  470. {
  471. clearSlots();
  472. while(src)
  473. {
  474. auto i = src.army.begin();
  475. putStack(i->first, std::make_unique<CStackInstance>(getArmy()->cb, i->second.first, i->second.second));
  476. src.army.erase(i);
  477. }
  478. }
  479. std::unique_ptr<CStackInstance> CCreatureSet::detachStack(const SlotID & slot)
  480. {
  481. assert(hasStackAtSlot(slot));
  482. std::unique_ptr<CStackInstance> ret = std::move(stacks[slot]);
  483. //if(CArmedInstance *armedObj = castToArmyObj())
  484. if(ret)
  485. {
  486. ret->setArmy(nullptr); //detaches from current armyobj
  487. assert(!ret->getArmy()); //we failed detaching?
  488. }
  489. stacks.erase(slot);
  490. armyChanged();
  491. return ret;
  492. }
  493. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  494. {
  495. assert(hasStackAtSlot(slot));
  496. stacks[slot]->setType(type);
  497. armyChanged();
  498. }
  499. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  500. {
  501. if(!allowMergingStacks)
  502. {
  503. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  504. std::set<const CCreature*> cresToAdd;
  505. for(const auto & elem : cs.stacks)
  506. {
  507. SlotID dest = getSlotFor(elem.second->getCreature());
  508. if(!dest.validSlot() || hasStackAtSlot(dest))
  509. cresToAdd.insert(elem.second->getCreature());
  510. }
  511. return cresToAdd.size() <= freeSlots;
  512. }
  513. else
  514. {
  515. CCreatureSet cres;
  516. SlotID j;
  517. //get types of creatures that need their own slot
  518. for(const auto & elem : cs.stacks)
  519. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  520. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  521. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  522. for(const auto & elem : stacks)
  523. {
  524. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  525. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  526. else
  527. return false; //no place found
  528. }
  529. return true; //all stacks found their slots
  530. }
  531. }
  532. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  533. {
  534. return vstd::contains(stacks, slot);
  535. }
  536. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  537. {
  538. assert(0);
  539. return *this;
  540. }
  541. void CCreatureSet::armyChanged()
  542. {
  543. }
  544. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & armyFieldName, const std::optional<int> fixedSize)
  545. {
  546. if(handler.saving && stacks.empty())
  547. return;
  548. handler.serializeEnum("formation", formation, NArmyFormation::names);
  549. auto a = handler.enterArray(armyFieldName);
  550. if(handler.saving)
  551. {
  552. size_t sz = 0;
  553. for(const auto & p : stacks)
  554. vstd::amax(sz, p.first.getNum()+1);
  555. if(fixedSize)
  556. vstd::amax(sz, fixedSize.value());
  557. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  558. for(const auto & p : stacks)
  559. {
  560. auto s = a.enterStruct(p.first.getNum());
  561. p.second->serializeJson(handler);
  562. }
  563. }
  564. else
  565. {
  566. for(size_t idx = 0; idx < a.size(); idx++)
  567. {
  568. auto s = a.enterStruct(idx);
  569. TQuantity amount = 0;
  570. handler.serializeInt("amount", amount);
  571. if(amount > 0)
  572. {
  573. auto newStack = std::make_unique<CStackInstance>(getArmy()->cb);
  574. newStack->serializeJson(handler);
  575. putStack(SlotID(static_cast<si32>(idx)), std::move(newStack));
  576. }
  577. }
  578. }
  579. }
  580. CStackInstance::CStackInstance(IGameCallback *cb, bool isHypothetic)
  581. : CBonusSystemNode(isHypothetic)
  582. , GameCallbackHolder(cb)
  583. , CArtifactSet(cb)
  584. , nativeTerrain(this, Selector::type()(BonusType::TERRAIN_NATIVE))
  585. , initiative(this, Selector::type()(BonusType::STACKS_SPEED))
  586. {
  587. experience = 0;
  588. count = 0;
  589. setType(nullptr);
  590. setNodeType(STACK_INSTANCE);
  591. }
  592. CStackInstance::CStackInstance(IGameCallback *cb, const CreatureID & id, TQuantity Count, bool isHypothetic)
  593. : CStackInstance(cb, false)
  594. {
  595. setType(id);
  596. count = Count;
  597. }
  598. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  599. {
  600. return CCreature::getQuantityID(count);
  601. }
  602. int CStackInstance::getExpRank() const
  603. {
  604. if (!LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  605. return 0;
  606. int tier = getType()->getLevel();
  607. if (vstd::iswithin(tier, 1, 7))
  608. {
  609. for(int i = static_cast<int>(LIBRARY->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  610. { //exp values vary from 1st level to max exp at 11th level
  611. if (experience >= LIBRARY->creh->expRanks[tier][i])
  612. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  613. }
  614. return 0;
  615. }
  616. else //higher tier
  617. {
  618. for(int i = static_cast<int>(LIBRARY->creh->expRanks[0].size()) - 2; i > -1; --i)
  619. {
  620. if (experience >= LIBRARY->creh->expRanks[0][i])
  621. return ++i;
  622. }
  623. return 0;
  624. }
  625. }
  626. int CStackInstance::getLevel() const
  627. {
  628. return std::max(1, getType()->getLevel());
  629. }
  630. void CStackInstance::giveStackExp(TExpType exp)
  631. {
  632. int level = getType()->getLevel();
  633. if (!vstd::iswithin(level, 1, 7))
  634. level = 0;
  635. ui32 maxExp = LIBRARY->creh->expRanks[level].back();
  636. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  637. vstd::amin(exp, (maxExp * LIBRARY->creh->maxExpPerBattle[level])/100);
  638. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  639. }
  640. void CStackInstance::setType(const CreatureID & creID)
  641. {
  642. if (creID == CreatureID::NONE)
  643. setType(nullptr);//FIXME: unused branch?
  644. else
  645. setType(creID.toCreature());
  646. }
  647. void CStackInstance::setType(const CCreature *c)
  648. {
  649. if(getCreature())
  650. {
  651. detachFromSource(*getCreature());
  652. if (getCreature()->isMyUpgrade(c) && LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  653. experience = static_cast<TExpType>(experience * LIBRARY->creh->expAfterUpgrade / 100.0);
  654. }
  655. CStackBasicDescriptor::setType(c);
  656. if(getCreature())
  657. attachToSource(*getCreature());
  658. }
  659. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  660. {
  661. return LIBRARY->getBth()->bonusToString(bonus, this, description);
  662. }
  663. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  664. {
  665. return LIBRARY->getBth()->bonusToGraphics(bonus);
  666. }
  667. CArmedInstance * CStackInstance::getArmy()
  668. {
  669. if (armyInstanceID.hasValue())
  670. return dynamic_cast<CArmedInstance*>(cb->gameState()->getObjInstance(armyInstanceID));
  671. return nullptr;
  672. }
  673. const CArmedInstance * CStackInstance::getArmy() const
  674. {
  675. if (armyInstanceID.hasValue())
  676. return dynamic_cast<const CArmedInstance*>(cb->getObjInstance(armyInstanceID));
  677. return nullptr;
  678. }
  679. void CStackInstance::setArmy(const CArmedInstance * ArmyObj)
  680. {
  681. auto oldArmy = getArmy();
  682. if(oldArmy)
  683. {
  684. detachFrom(*oldArmy);
  685. armyInstanceID = {};
  686. }
  687. if(ArmyObj)
  688. {
  689. attachTo(const_cast<CArmedInstance&>(*ArmyObj));
  690. armyInstanceID = ArmyObj->id;
  691. }
  692. }
  693. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  694. {
  695. CCreature::CreatureQuantityId quantity = getQuantityID();
  696. if ((int)quantity)
  697. {
  698. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  699. return CCreature::getQuantityRangeStringForId(quantity);
  700. return LIBRARY->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  701. }
  702. else
  703. return "";
  704. }
  705. bool CStackInstance::valid(bool allowUnrandomized) const
  706. {
  707. if(!randomStack)
  708. {
  709. return (getType() && getType() == getId().toEntity(LIBRARY));
  710. }
  711. else
  712. return allowUnrandomized;
  713. }
  714. std::string CStackInstance::nodeName() const
  715. {
  716. std::ostringstream oss;
  717. oss << "Stack of " << count << " of ";
  718. if(getType())
  719. oss << getType()->getNamePluralTextID();
  720. else
  721. oss << "[UNDEFINED TYPE]";
  722. return oss.str();
  723. }
  724. PlayerColor CStackInstance::getOwner() const
  725. {
  726. auto army = getArmy();
  727. return army ? army->getOwner() : PlayerColor::NEUTRAL;
  728. }
  729. int32_t CStackInstance::getInitiative(int turn) const
  730. {
  731. if (turn == 0)
  732. return initiative.getValue();
  733. return ACreature::getInitiative(turn);
  734. }
  735. TerrainId CStackInstance::getNativeTerrain() const
  736. {
  737. if (nativeTerrain.hasBonus())
  738. return TerrainId::ANY_TERRAIN;
  739. return getFactionID().toEntity(LIBRARY)->getNativeTerrain();
  740. }
  741. TerrainId CStackInstance::getCurrentTerrain() const
  742. {
  743. return getArmy()->getCurrentTerrain();
  744. }
  745. CreatureID CStackInstance::getCreatureID() const
  746. {
  747. if(getType())
  748. return getType()->getId();
  749. else
  750. return CreatureID::NONE;
  751. }
  752. std::string CStackInstance::getName() const
  753. {
  754. return (count > 1) ? getType()->getNamePluralTranslated() : getType()->getNameSingularTranslated();
  755. }
  756. ui64 CStackInstance::getPower() const
  757. {
  758. assert(getType());
  759. return static_cast<ui64>(getType()->getAIValue()) * count;
  760. }
  761. ui64 CStackInstance::getMarketValue() const
  762. {
  763. assert(getType());
  764. return getType()->getFullRecruitCost().marketValue() * count;
  765. }
  766. ArtBearer::ArtBearer CStackInstance::bearerType() const
  767. {
  768. return ArtBearer::CREATURE;
  769. }
  770. CStackInstance::ArtPlacementMap CStackInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  771. {
  772. assert(!getArt(pos));
  773. assert(art->canBePutAt(this, pos));
  774. attachToSource(*art);
  775. return CArtifactSet::putArtifact(pos, art);
  776. }
  777. void CStackInstance::removeArtifact(const ArtifactPosition & pos)
  778. {
  779. assert(getArt(pos));
  780. detachFromSource(*getArt(pos));
  781. CArtifactSet::removeArtifact(pos);
  782. }
  783. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  784. {
  785. //todo: artifacts
  786. CStackBasicDescriptor::serializeJson(handler);//must be first
  787. if(handler.saving)
  788. {
  789. if(randomStack)
  790. {
  791. int level = randomStack->level;
  792. int upgrade = randomStack->upgrade;
  793. handler.serializeInt("level", level, 0);
  794. handler.serializeInt("upgraded", upgrade, 0);
  795. }
  796. }
  797. else
  798. {
  799. //type set by CStackBasicDescriptor::serializeJson
  800. if(getType() == nullptr)
  801. {
  802. uint8_t level = 0;
  803. uint8_t upgrade = 0;
  804. handler.serializeInt("level", level, 0);
  805. handler.serializeInt("upgrade", upgrade, 0);
  806. randomStack = RandomStackInfo{ level, upgrade };
  807. }
  808. }
  809. }
  810. FactionID CStackInstance::getFactionID() const
  811. {
  812. if(getType())
  813. return getType()->getFactionID();
  814. return FactionID::NEUTRAL;
  815. }
  816. const IBonusBearer* CStackInstance::getBonusBearer() const
  817. {
  818. return this;
  819. }
  820. CCommanderInstance::CCommanderInstance(IGameCallback *cb)
  821. :CStackInstance(cb)
  822. {}
  823. CCommanderInstance::CCommanderInstance(IGameCallback *cb, const CreatureID & id)
  824. : CStackInstance(cb)
  825. , name("Commando")
  826. {
  827. alive = true;
  828. experience = 0;
  829. level = 1;
  830. count = 1;
  831. setType(nullptr);
  832. setNodeType (CBonusSystemNode::COMMANDER);
  833. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  834. setType(id);
  835. //TODO - parse them
  836. }
  837. void CCommanderInstance::setAlive (bool Alive)
  838. {
  839. //TODO: helm of immortality
  840. alive = Alive;
  841. if (!alive)
  842. {
  843. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  844. }
  845. }
  846. void CCommanderInstance::giveStackExp (TExpType exp)
  847. {
  848. if (alive)
  849. experience += exp;
  850. }
  851. int CCommanderInstance::getExpRank() const
  852. {
  853. return LIBRARY->heroh->level (experience);
  854. }
  855. int CCommanderInstance::getLevel() const
  856. {
  857. return std::max (1, getExpRank());
  858. }
  859. void CCommanderInstance::levelUp ()
  860. {
  861. level++;
  862. for(const auto & bonus : LIBRARY->creh->commanderLevelPremy)
  863. { //grant all regular level-up bonuses
  864. accumulateBonus(bonus);
  865. }
  866. }
  867. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  868. {
  869. return ArtBearer::COMMANDER;
  870. }
  871. bool CCommanderInstance::gainsLevel() const
  872. {
  873. return experience >= LIBRARY->heroh->reqExp(level + 1);
  874. }
  875. //This constructor should be placed here to avoid side effects
  876. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  877. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  878. typeID(id),
  879. count(Count)
  880. {
  881. }
  882. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  883. : typeID(c ? c->getId() : CreatureID()), count(Count)
  884. {
  885. }
  886. const CCreature * CStackBasicDescriptor::getCreature() const
  887. {
  888. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  889. }
  890. const Creature * CStackBasicDescriptor::getType() const
  891. {
  892. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  893. }
  894. CreatureID CStackBasicDescriptor::getId() const
  895. {
  896. return typeID;
  897. }
  898. TQuantity CStackBasicDescriptor::getCount() const
  899. {
  900. return count;
  901. }
  902. void CStackBasicDescriptor::setType(const CCreature * c)
  903. {
  904. typeID = c ? c->getId() : CreatureID();
  905. }
  906. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  907. {
  908. return l.typeID == r.typeID && l.count == r.count;
  909. }
  910. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  911. {
  912. handler.serializeInt("amount", count);
  913. if(handler.saving)
  914. {
  915. if(typeID.hasValue())
  916. {
  917. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  918. handler.serializeString("type", typeName);
  919. }
  920. }
  921. else
  922. {
  923. std::string typeName;
  924. handler.serializeString("type", typeName);
  925. if(!typeName.empty())
  926. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  927. }
  928. }
  929. void CSimpleArmy::clearSlots()
  930. {
  931. army.clear();
  932. }
  933. CSimpleArmy::operator bool() const
  934. {
  935. return !army.empty();
  936. }
  937. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  938. {
  939. assert(!vstd::contains(army, slot));
  940. army[slot] = std::make_pair(cre, count);
  941. return true;
  942. }
  943. VCMI_LIB_NAMESPACE_END