CCreatureSet.cpp 27 KB

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