CCreatureSet.cpp 24 KB

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