CCreatureSet.cpp 23 KB

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