CCreatureSet.cpp 24 KB

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