CCreatureSet.cpp 27 KB

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