CCreatureSet.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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, bool isHypothetic)
  598. : CBonusSystemNode(isHypothetic)
  599. , CStackBasicDescriptor(nullptr, 0)
  600. , CArtifactSet(cb)
  601. , GameCallbackHolder(cb)
  602. , nativeTerrain(this, Selector::type()(BonusType::TERRAIN_NATIVE))
  603. , initiative(this, Selector::type()(BonusType::STACKS_SPEED))
  604. , totalExperience(0)
  605. {
  606. setNodeType(STACK_INSTANCE);
  607. }
  608. CStackInstance::CStackInstance(IGameInfoCallback *cb, const CreatureID & id, TQuantity Count, bool isHypothetic)
  609. : CStackInstance(cb, false)
  610. {
  611. setType(id);
  612. setCount(Count);
  613. }
  614. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  615. {
  616. return CCreature::getQuantityID(getCount());
  617. }
  618. int CStackInstance::getExpRank() const
  619. {
  620. if (!LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  621. return 0;
  622. int tier = getType()->getLevel();
  623. if (vstd::iswithin(tier, 1, 7))
  624. {
  625. for(int i = static_cast<int>(LIBRARY->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  626. { //exp values vary from 1st level to max exp at 11th level
  627. if (getAverageExperience() >= LIBRARY->creh->expRanks[tier][i])
  628. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  629. }
  630. return 0;
  631. }
  632. else //higher tier
  633. {
  634. for(int i = static_cast<int>(LIBRARY->creh->expRanks[0].size()) - 2; i > -1; --i)
  635. {
  636. if (getAverageExperience() >= LIBRARY->creh->expRanks[0][i])
  637. return ++i;
  638. }
  639. return 0;
  640. }
  641. }
  642. int CStackInstance::getLevel() const
  643. {
  644. return std::max(1, getType()->getLevel());
  645. }
  646. void CStackInstance::giveAverageStackExperience(TExpType desiredAmountPerUnit)
  647. {
  648. if (!canGainExperience())
  649. return;
  650. int level = std::clamp(getLevel(), 1, 7);
  651. TExpType maxAmountPerUnit = LIBRARY->creh->expRanks[level].back();
  652. TExpType actualAmountPerUnit = std::min(desiredAmountPerUnit, maxAmountPerUnit * LIBRARY->creh->maxExpPerBattle[level]/100);
  653. TExpType maxExperience = maxAmountPerUnit * getCount();
  654. TExpType maxExperienceToGain = maxExperience - totalExperience;
  655. TExpType actualGainedExperience = std::min(maxExperienceToGain, actualAmountPerUnit * getCount());
  656. totalExperience += actualGainedExperience;
  657. }
  658. void CStackInstance::giveTotalStackExperience(TExpType experienceToGive)
  659. {
  660. if (!canGainExperience())
  661. return;
  662. totalExperience += experienceToGive;
  663. }
  664. TExpType CStackInstance::getTotalExperience() const
  665. {
  666. return totalExperience;
  667. }
  668. TExpType CStackInstance::getAverageExperience() const
  669. {
  670. return totalExperience / getCount();
  671. }
  672. bool CStackInstance::canGainExperience() const
  673. {
  674. return cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE);
  675. }
  676. void CStackInstance::setType(const CreatureID & creID)
  677. {
  678. if (creID == CreatureID::NONE)
  679. setType(nullptr);//FIXME: unused branch?
  680. else
  681. setType(creID.toCreature());
  682. }
  683. void CStackInstance::setType(const CCreature *c)
  684. {
  685. if(getCreature())
  686. {
  687. detachFromSource(*getCreature());
  688. if (LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  689. totalExperience = totalExperience * LIBRARY->creh->expAfterUpgrade / 100;
  690. }
  691. CStackBasicDescriptor::setType(c);
  692. if(getCreature())
  693. attachToSource(*getCreature());
  694. }
  695. void CStackInstance::setCount(TQuantity newCount)
  696. {
  697. assert(newCount >= 0);
  698. if (newCount < getCount())
  699. {
  700. TExpType averageExperience = totalExperience / getCount();
  701. totalExperience = averageExperience * newCount;
  702. }
  703. CStackBasicDescriptor::setCount(newCount);
  704. }
  705. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  706. {
  707. if (!bonus->description.empty())
  708. {
  709. if (description)
  710. return bonus->description.toString();
  711. else
  712. return {};
  713. }
  714. return LIBRARY->getBth()->bonusToString(bonus, this, description);
  715. }
  716. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  717. {
  718. if (!bonus->customIconPath.empty())
  719. return bonus->customIconPath;
  720. return LIBRARY->getBth()->bonusToGraphics(bonus);
  721. }
  722. CArmedInstance * CStackInstance::getArmy()
  723. {
  724. return armyInstance;
  725. }
  726. const CArmedInstance * CStackInstance::getArmy() const
  727. {
  728. return armyInstance;
  729. }
  730. void CStackInstance::setArmy(CArmedInstance * ArmyObj)
  731. {
  732. auto oldArmy = getArmy();
  733. if(oldArmy)
  734. {
  735. detachFrom(*oldArmy);
  736. armyInstance = nullptr;
  737. }
  738. if(ArmyObj)
  739. {
  740. attachTo(const_cast<CArmedInstance&>(*ArmyObj));
  741. armyInstance = ArmyObj;
  742. }
  743. }
  744. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  745. {
  746. CCreature::CreatureQuantityId quantity = getQuantityID();
  747. if ((int)quantity)
  748. {
  749. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  750. return CCreature::getQuantityRangeStringForId(quantity);
  751. return LIBRARY->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  752. }
  753. else
  754. return "";
  755. }
  756. bool CStackInstance::valid(bool allowUnrandomized) const
  757. {
  758. if(!randomStack)
  759. {
  760. return (getType() && getType() == getId().toEntity(LIBRARY));
  761. }
  762. else
  763. return allowUnrandomized;
  764. }
  765. std::string CStackInstance::nodeName() const
  766. {
  767. std::ostringstream oss;
  768. oss << "Stack of " << getCount() << " of ";
  769. if(getType())
  770. oss << getType()->getNamePluralTextID();
  771. else
  772. oss << "[UNDEFINED TYPE]";
  773. return oss.str();
  774. }
  775. PlayerColor CStackInstance::getOwner() const
  776. {
  777. auto army = getArmy();
  778. return army ? army->getOwner() : PlayerColor::NEUTRAL;
  779. }
  780. int32_t CStackInstance::getInitiative(int turn) const
  781. {
  782. if (turn == 0)
  783. return initiative.getValue();
  784. return ACreature::getInitiative(turn);
  785. }
  786. TerrainId CStackInstance::getNativeTerrain() const
  787. {
  788. if (nativeTerrain.hasBonus())
  789. return TerrainId::ANY_TERRAIN;
  790. return getFactionID().toEntity(LIBRARY)->getNativeTerrain();
  791. }
  792. TerrainId CStackInstance::getCurrentTerrain() const
  793. {
  794. assert(getArmy() != nullptr);
  795. return getArmy()->getCurrentTerrain();
  796. }
  797. CreatureID CStackInstance::getCreatureID() const
  798. {
  799. if(getType())
  800. return getType()->getId();
  801. else
  802. return CreatureID::NONE;
  803. }
  804. std::string CStackInstance::getName() const
  805. {
  806. return (getCount() > 1) ? getType()->getNamePluralTranslated() : getType()->getNameSingularTranslated();
  807. }
  808. ui64 CStackInstance::getPower() const
  809. {
  810. assert(getType());
  811. return static_cast<ui64>(getType()->getAIValue()) * getCount();
  812. }
  813. ui64 CStackInstance::getMarketValue() const
  814. {
  815. assert(getType());
  816. return getType()->getFullRecruitCost().marketValue() * getCount();
  817. }
  818. ArtBearer CStackInstance::bearerType() const
  819. {
  820. return ArtBearer::CREATURE;
  821. }
  822. CStackInstance::ArtPlacementMap CStackInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  823. {
  824. assert(!getArt(pos));
  825. assert(art->canBePutAt(this, pos));
  826. attachToSource(*art);
  827. return CArtifactSet::putArtifact(pos, art);
  828. }
  829. void CStackInstance::removeArtifact(const ArtifactPosition & pos)
  830. {
  831. assert(getArt(pos));
  832. detachFromSource(*getArt(pos));
  833. CArtifactSet::removeArtifact(pos);
  834. }
  835. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  836. {
  837. //todo: artifacts
  838. CStackBasicDescriptor::serializeJson(handler);//must be first
  839. if(handler.saving)
  840. {
  841. if(randomStack)
  842. {
  843. int level = randomStack->level;
  844. int upgrade = randomStack->upgrade;
  845. handler.serializeInt("level", level, 0);
  846. handler.serializeInt("upgraded", upgrade, 0);
  847. }
  848. }
  849. else
  850. {
  851. //type set by CStackBasicDescriptor::serializeJson
  852. if(getType() == nullptr)
  853. {
  854. uint8_t level = 0;
  855. uint8_t upgrade = 0;
  856. handler.serializeInt("level", level, 0);
  857. handler.serializeInt("upgrade", upgrade, 0);
  858. randomStack = RandomStackInfo{ level, upgrade };
  859. }
  860. }
  861. }
  862. FactionID CStackInstance::getFactionID() const
  863. {
  864. if(getType())
  865. return getType()->getFactionID();
  866. return FactionID::NEUTRAL;
  867. }
  868. const IBonusBearer* CStackInstance::getBonusBearer() const
  869. {
  870. return this;
  871. }
  872. CCommanderInstance::CCommanderInstance(IGameInfoCallback *cb)
  873. :CStackInstance(cb)
  874. {}
  875. CCommanderInstance::CCommanderInstance(IGameInfoCallback *cb, const CreatureID & id)
  876. : CStackInstance(cb)
  877. , name("Commando")
  878. {
  879. alive = true;
  880. level = 1;
  881. setCount(1);
  882. setType(nullptr);
  883. setNodeType (CBonusSystemNode::COMMANDER);
  884. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  885. setType(id);
  886. //TODO - parse them
  887. }
  888. void CCommanderInstance::setAlive (bool Alive)
  889. {
  890. //TODO: helm of immortality
  891. alive = Alive;
  892. if (!alive)
  893. {
  894. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  895. }
  896. }
  897. bool CCommanderInstance::canGainExperience() const
  898. {
  899. return alive;
  900. }
  901. int CCommanderInstance::getExpRank() const
  902. {
  903. return LIBRARY->heroh->level (getTotalExperience());
  904. }
  905. int CCommanderInstance::getLevel() const
  906. {
  907. return std::max (1, getExpRank());
  908. }
  909. void CCommanderInstance::levelUp ()
  910. {
  911. level++;
  912. for(const auto & bonus : LIBRARY->creh->commanderLevelPremy)
  913. { //grant all regular level-up bonuses
  914. accumulateBonus(bonus);
  915. }
  916. }
  917. ArtBearer CCommanderInstance::bearerType() const
  918. {
  919. return ArtBearer::COMMANDER;
  920. }
  921. bool CCommanderInstance::gainsLevel() const
  922. {
  923. return getTotalExperience() >= LIBRARY->heroh->reqExp(level + 1);
  924. }
  925. //This constructor should be placed here to avoid side effects
  926. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  927. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  928. typeID(id),
  929. count(Count)
  930. {
  931. }
  932. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  933. : typeID(c ? c->getId() : CreatureID()), count(Count)
  934. {
  935. }
  936. const CCreature * CStackBasicDescriptor::getCreature() const
  937. {
  938. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  939. }
  940. const Creature * CStackBasicDescriptor::getType() const
  941. {
  942. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  943. }
  944. CreatureID CStackBasicDescriptor::getId() const
  945. {
  946. return typeID;
  947. }
  948. TQuantity CStackBasicDescriptor::getCount() const
  949. {
  950. return count;
  951. }
  952. void CStackBasicDescriptor::setType(const CCreature * c)
  953. {
  954. typeID = c ? c->getId() : CreatureID();
  955. }
  956. void CStackBasicDescriptor::setCount(TQuantity newCount)
  957. {
  958. assert(newCount >= 0);
  959. count = newCount;
  960. }
  961. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  962. {
  963. return l.typeID == r.typeID && l.count == r.count;
  964. }
  965. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  966. {
  967. handler.serializeInt("amount", count);
  968. if(handler.saving)
  969. {
  970. if(typeID.hasValue())
  971. {
  972. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  973. handler.serializeString("type", typeName);
  974. }
  975. }
  976. else
  977. {
  978. std::string typeName;
  979. handler.serializeString("type", typeName);
  980. if(!typeName.empty())
  981. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  982. }
  983. }
  984. void CSimpleArmy::clearSlots()
  985. {
  986. army.clear();
  987. }
  988. CSimpleArmy::operator bool() const
  989. {
  990. return !army.empty();
  991. }
  992. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  993. {
  994. assert(!vstd::contains(army, slot));
  995. army[slot] = std::make_pair(cre, count);
  996. return true;
  997. }
  998. VCMI_LIB_NAMESPACE_END