CCreatureSet.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. [[maybe_unused]] const CCreature *c = getCreature(slot);
  441. assert(c == stack->type);
  442. assert(c);
  443. //TODO move stuff
  444. changeStackCount(slot, stack->count);
  445. vstd::clear_pointer(stack);
  446. }
  447. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  448. {
  449. setStackCount(slot, getStackCount(slot) + toAdd);
  450. }
  451. CCreatureSet::~CCreatureSet()
  452. {
  453. clear();
  454. }
  455. void CCreatureSet::setToArmy(CSimpleArmy &src)
  456. {
  457. clear();
  458. while(src)
  459. {
  460. auto i = src.army.begin();
  461. putStack(i->first, new CStackInstance(i->second.first, i->second.second));
  462. src.army.erase(i);
  463. }
  464. }
  465. CStackInstance * CCreatureSet::detachStack(const SlotID & slot)
  466. {
  467. assert(hasStackAtSlot(slot));
  468. CStackInstance *ret = stacks[slot];
  469. //if(CArmedInstance *armedObj = castToArmyObj())
  470. if(ret)
  471. {
  472. ret->setArmyObj(nullptr); //detaches from current armyobj
  473. assert(!ret->armyObj); //we failed detaching?
  474. }
  475. stacks.erase(slot);
  476. armyChanged();
  477. return ret;
  478. }
  479. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  480. {
  481. assert(hasStackAtSlot(slot));
  482. CStackInstance *s = stacks[slot];
  483. s->setType(type);
  484. armyChanged();
  485. }
  486. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  487. {
  488. if(!allowMergingStacks)
  489. {
  490. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  491. std::set<const CCreature*> cresToAdd;
  492. for(const auto & elem : cs.stacks)
  493. {
  494. SlotID dest = getSlotFor(elem.second->type);
  495. if(!dest.validSlot() || hasStackAtSlot(dest))
  496. cresToAdd.insert(elem.second->type);
  497. }
  498. return cresToAdd.size() <= freeSlots;
  499. }
  500. else
  501. {
  502. CCreatureSet cres;
  503. SlotID j;
  504. //get types of creatures that need their own slot
  505. for(const auto & elem : cs.stacks)
  506. if ((j = cres.getSlotFor(elem.second->type)).validSlot())
  507. cres.addToSlot(j, elem.second->type->getId(), 1, true); //merge if possible
  508. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  509. for(const auto & elem : stacks)
  510. {
  511. if ((j = cres.getSlotFor(elem.second->type)).validSlot())
  512. cres.addToSlot(j, elem.second->type->getId(), 1, true); //merge if possible
  513. else
  514. return false; //no place found
  515. }
  516. return true; //all stacks found their slots
  517. }
  518. }
  519. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  520. {
  521. return vstd::contains(stacks, slot);
  522. }
  523. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  524. {
  525. assert(0);
  526. return *this;
  527. }
  528. void CCreatureSet::armyChanged()
  529. {
  530. }
  531. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const boost::optional<int> fixedSize)
  532. {
  533. if(handler.saving && stacks.empty())
  534. return;
  535. auto a = handler.enterArray(fieldName);
  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.get());
  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. idRand = -1;
  591. _armyObj = nullptr;
  592. setNodeType(STACK_INSTANCE);
  593. }
  594. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  595. {
  596. return CCreature::getQuantityID(count);
  597. }
  598. int CStackInstance::getExpRank() const
  599. {
  600. if (!VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  601. return 0;
  602. int tier = type->getLevel();
  603. if (vstd::iswithin(tier, 1, 7))
  604. {
  605. for(int i = static_cast<int>(VLC->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  606. { //exp values vary from 1st level to max exp at 11th level
  607. if (experience >= VLC->creh->expRanks[tier][i])
  608. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  609. }
  610. return 0;
  611. }
  612. else //higher tier
  613. {
  614. for(int i = static_cast<int>(VLC->creh->expRanks[0].size()) - 2; i > -1; --i)
  615. {
  616. if (experience >= VLC->creh->expRanks[0][i])
  617. return ++i;
  618. }
  619. return 0;
  620. }
  621. }
  622. int CStackInstance::getLevel() const
  623. {
  624. return std::max(1, static_cast<int>(type->getLevel()));
  625. }
  626. si32 CStackInstance::magicResistance() const
  627. {
  628. si32 val = valOfBonuses(Selector::type()(Bonus::MAGIC_RESISTANCE));
  629. vstd::amin (val, 100);
  630. return val;
  631. }
  632. void CStackInstance::giveStackExp(TExpType exp)
  633. {
  634. int level = type->getLevel();
  635. if (!vstd::iswithin(level, 1, 7))
  636. level = 0;
  637. CCreatureHandler * creh = VLC->creh;
  638. ui32 maxExp = creh->expRanks[level].back();
  639. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  640. vstd::amin(exp, (maxExp * creh->maxExpPerBattle[level])/100);
  641. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  642. }
  643. void CStackInstance::setType(const CreatureID & creID)
  644. {
  645. if(creID >= 0 && creID < VLC->creh->objects.size())
  646. setType(VLC->creh->objects[creID]);
  647. else
  648. setType((const CCreature*)nullptr);
  649. }
  650. void CStackInstance::setType(const CCreature *c)
  651. {
  652. if(type)
  653. {
  654. detachFrom(const_cast<CCreature&>(*type));
  655. if (type->isMyUpgrade(c) && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  656. experience = static_cast<TExpType>(experience * VLC->creh->expAfterUpgrade / 100.0);
  657. }
  658. CStackBasicDescriptor::setType(c);
  659. if(type)
  660. attachTo(const_cast<CCreature&>(*type));
  661. }
  662. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  663. {
  664. return VLC->getBth()->bonusToString(bonus, this, description);
  665. }
  666. std::string CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  667. {
  668. return VLC->getBth()->bonusToGraphics(bonus);
  669. }
  670. void CStackInstance::setArmyObj(const CArmedInstance * ArmyObj)
  671. {
  672. if(_armyObj)
  673. detachFrom(const_cast<CArmedInstance&>(*_armyObj));
  674. _armyObj = ArmyObj;
  675. if(ArmyObj)
  676. attachTo(const_cast<CArmedInstance&>(*_armyObj));
  677. }
  678. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  679. {
  680. CCreature::CreatureQuantityId quantity = getQuantityID();
  681. if ((int)quantity)
  682. {
  683. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  684. return CCreature::getQuantityRangeStringForId(quantity);
  685. return VLC->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  686. }
  687. else
  688. return "";
  689. }
  690. bool CStackInstance::valid(bool allowUnrandomized) const
  691. {
  692. bool isRand = (idRand != -1);
  693. if(!isRand)
  694. {
  695. return (type && type == VLC->creh->objects[type->getId()]);
  696. }
  697. else
  698. return allowUnrandomized;
  699. }
  700. std::string CStackInstance::nodeName() const
  701. {
  702. std::ostringstream oss;
  703. oss << "Stack of " << count << " of ";
  704. if(type)
  705. oss << type->getNamePluralTextID();
  706. else if(idRand >= 0)
  707. oss << "[no type, idRand=" << idRand << "]";
  708. else
  709. oss << "[UNDEFINED TYPE]";
  710. return oss.str();
  711. }
  712. PlayerColor CStackInstance::getOwner() const
  713. {
  714. return _armyObj ? _armyObj->getOwner() : PlayerColor::NEUTRAL;
  715. }
  716. void CStackInstance::deserializationFix()
  717. {
  718. const CArmedInstance *armyBackup = _armyObj;
  719. _armyObj = nullptr;
  720. setArmyObj(armyBackup);
  721. artDeserializationFix(this);
  722. }
  723. CreatureID CStackInstance::getCreatureID() const
  724. {
  725. if(type)
  726. return type->getId();
  727. else
  728. return CreatureID::NONE;
  729. }
  730. std::string CStackInstance::getName() const
  731. {
  732. return (count > 1) ? type->getNamePluralTranslated() : type->getNameSingularTranslated();
  733. }
  734. ui64 CStackInstance::getPower() const
  735. {
  736. assert(type);
  737. return type->getAIValue() * count;
  738. }
  739. ArtBearer::ArtBearer CStackInstance::bearerType() const
  740. {
  741. return ArtBearer::CREATURE;
  742. }
  743. void CStackInstance::putArtifact(ArtifactPosition pos, CArtifactInstance * art)
  744. {
  745. assert(!getArt(pos));
  746. art->putAt(ArtifactLocation(this, pos));
  747. }
  748. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  749. {
  750. //todo: artifacts
  751. CStackBasicDescriptor::serializeJson(handler);//must be first
  752. if(handler.saving)
  753. {
  754. if(idRand > -1)
  755. {
  756. int level = idRand / 2;
  757. boost::logic::tribool upgraded = (idRand % 2) > 0;
  758. handler.serializeInt("level", level, 0);
  759. handler.serializeBool("upgraded", upgraded);
  760. }
  761. }
  762. else
  763. {
  764. //type set by CStackBasicDescriptor::serializeJson
  765. if(type == nullptr)
  766. {
  767. int level = 0;
  768. bool upgraded = false;
  769. handler.serializeInt("level", level, 0);
  770. handler.serializeBool("upgraded", upgraded);
  771. idRand = level * 2 + static_cast<int>(upgraded);
  772. }
  773. }
  774. }
  775. FactionID CStackInstance::getFaction() const
  776. {
  777. if(type)
  778. return type->getFaction();
  779. return FactionID::NEUTRAL;
  780. }
  781. const IBonusBearer* CStackInstance::getBonusBearer() const
  782. {
  783. return this;
  784. }
  785. CCommanderInstance::CCommanderInstance()
  786. {
  787. init();
  788. }
  789. CCommanderInstance::CCommanderInstance(const CreatureID & id): name("Commando")
  790. {
  791. init();
  792. setType(id);
  793. //TODO - parse them
  794. }
  795. void CCommanderInstance::init()
  796. {
  797. alive = true;
  798. experience = 0;
  799. level = 1;
  800. count = 1;
  801. type = nullptr;
  802. idRand = -1;
  803. _armyObj = nullptr;
  804. setNodeType (CBonusSystemNode::COMMANDER);
  805. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  806. }
  807. void CCommanderInstance::setAlive (bool Alive)
  808. {
  809. //TODO: helm of immortality
  810. alive = Alive;
  811. if (!alive)
  812. {
  813. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  814. }
  815. }
  816. void CCommanderInstance::giveStackExp (TExpType exp)
  817. {
  818. if (alive)
  819. experience += exp;
  820. }
  821. int CCommanderInstance::getExpRank() const
  822. {
  823. return VLC->heroh->level (experience);
  824. }
  825. int CCommanderInstance::getLevel() const
  826. {
  827. return std::max (1, getExpRank());
  828. }
  829. void CCommanderInstance::levelUp ()
  830. {
  831. level++;
  832. for(const auto & bonus : VLC->creh->commanderLevelPremy)
  833. { //grant all regular level-up bonuses
  834. accumulateBonus(bonus);
  835. }
  836. }
  837. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  838. {
  839. return ArtBearer::COMMANDER;
  840. }
  841. bool CCommanderInstance::gainsLevel() const
  842. {
  843. return experience >= static_cast<TExpType>(VLC->heroh->reqExp(level + 1));
  844. }
  845. //This constructor should be placed here to avoid side effects
  846. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  847. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  848. type(VLC->creh->objects[id]),
  849. count(Count)
  850. {
  851. }
  852. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  853. : type(c), count(Count)
  854. {
  855. }
  856. const Creature * CStackBasicDescriptor::getType() const
  857. {
  858. return type;
  859. }
  860. TQuantity CStackBasicDescriptor::getCount() const
  861. {
  862. return count;
  863. }
  864. void CStackBasicDescriptor::setType(const CCreature * c)
  865. {
  866. type = c;
  867. }
  868. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  869. {
  870. handler.serializeInt("amount", count);
  871. if(handler.saving)
  872. {
  873. if(type)
  874. {
  875. std::string typeName = type->getJsonKey();
  876. handler.serializeString("type", typeName);
  877. }
  878. }
  879. else
  880. {
  881. std::string typeName;
  882. handler.serializeString("type", typeName);
  883. if(!typeName.empty())
  884. setType(VLC->creh->getCreature(CModHandler::scopeMap(), typeName));
  885. }
  886. }
  887. void CSimpleArmy::clear()
  888. {
  889. army.clear();
  890. }
  891. CSimpleArmy::operator bool() const
  892. {
  893. return !army.empty();
  894. }
  895. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  896. {
  897. assert(!vstd::contains(army, slot));
  898. army[slot] = std::make_pair(cre, count);
  899. return true;
  900. }
  901. VCMI_LIB_NAMESPACE_END