CCreatureSet.cpp 25 KB

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