2
0

CCreatureSet.cpp 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. /*
  2. * CCreatureSet.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CCreatureSet.h"
  12. #include "ArtifactUtils.h"
  13. #include "CConfigHandler.h"
  14. #include "CCreatureHandler.h"
  15. #include "VCMI_Lib.h"
  16. #include "GameSettings.h"
  17. #include "mapObjects/CGHeroInstance.h"
  18. #include "modding/ModScope.h"
  19. #include "IGameCallback.h"
  20. #include "CGeneralTextHandler.h"
  21. #include "spells/CSpellHandler.h"
  22. #include "CHeroHandler.h"
  23. #include "IBonusTypeHandler.h"
  24. #include "serializer/JsonSerializeFormat.h"
  25. #include "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. if (tight)
  361. formation = EArmyFormation::TIGHT;
  362. else
  363. formation = EArmyFormation::LOOSE;
  364. }
  365. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  366. {
  367. assert(hasStackAtSlot(slot));
  368. assert(stacks[slot]->count + count > 0);
  369. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE) && count > stacks[slot]->count)
  370. stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
  371. stacks[slot]->count = count;
  372. armyChanged();
  373. }
  374. void CCreatureSet::giveStackExp(TExpType exp)
  375. {
  376. for(TSlots::const_iterator i = stacks.begin(); i != stacks.end(); i++)
  377. i->second->giveStackExp(exp);
  378. }
  379. void CCreatureSet::setStackExp(const SlotID & slot, TExpType exp)
  380. {
  381. assert(hasStackAtSlot(slot));
  382. stacks[slot]->experience = exp;
  383. }
  384. void CCreatureSet::clearSlots()
  385. {
  386. while(!stacks.empty())
  387. {
  388. eraseStack(stacks.begin()->first);
  389. }
  390. }
  391. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  392. {
  393. assert(hasStackAtSlot(slot));
  394. return *getStackPtr(slot);
  395. }
  396. const CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  397. {
  398. if(hasStackAtSlot(slot))
  399. return stacks.find(slot)->second;
  400. else return nullptr;
  401. }
  402. void CCreatureSet::eraseStack(const SlotID & slot)
  403. {
  404. assert(hasStackAtSlot(slot));
  405. CStackInstance *toErase = detachStack(slot);
  406. vstd::clear_pointer(toErase);
  407. }
  408. bool CCreatureSet::contains(const CStackInstance *stack) const
  409. {
  410. if(!stack)
  411. return false;
  412. for(const auto & elem : stacks)
  413. if(elem.second == stack)
  414. return true;
  415. return false;
  416. }
  417. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  418. {
  419. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  420. if (h && h->commander == stack)
  421. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  422. if(!stack)
  423. return SlotID();
  424. for(const auto & elem : stacks)
  425. if(elem.second == stack)
  426. return elem.first;
  427. return SlotID();
  428. }
  429. CArmedInstance * CCreatureSet::castToArmyObj()
  430. {
  431. return dynamic_cast<CArmedInstance *>(this);
  432. }
  433. void CCreatureSet::putStack(const SlotID & slot, CStackInstance * stack)
  434. {
  435. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  436. assert(!hasStackAtSlot(slot));
  437. stacks[slot] = stack;
  438. stack->setArmyObj(castToArmyObj());
  439. armyChanged();
  440. }
  441. void CCreatureSet::joinStack(const SlotID & slot, CStackInstance * stack)
  442. {
  443. [[maybe_unused]] const CCreature *c = getCreature(slot);
  444. assert(c == stack->type);
  445. assert(c);
  446. //TODO move stuff
  447. changeStackCount(slot, stack->count);
  448. vstd::clear_pointer(stack);
  449. }
  450. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  451. {
  452. setStackCount(slot, getStackCount(slot) + toAdd);
  453. }
  454. CCreatureSet::~CCreatureSet()
  455. {
  456. clearSlots();
  457. }
  458. void CCreatureSet::setToArmy(CSimpleArmy &src)
  459. {
  460. clearSlots();
  461. while(src)
  462. {
  463. auto i = src.army.begin();
  464. putStack(i->first, new CStackInstance(i->second.first, i->second.second));
  465. src.army.erase(i);
  466. }
  467. }
  468. CStackInstance * CCreatureSet::detachStack(const SlotID & slot)
  469. {
  470. assert(hasStackAtSlot(slot));
  471. CStackInstance *ret = stacks[slot];
  472. //if(CArmedInstance *armedObj = castToArmyObj())
  473. if(ret)
  474. {
  475. ret->setArmyObj(nullptr); //detaches from current armyobj
  476. assert(!ret->armyObj); //we failed detaching?
  477. }
  478. stacks.erase(slot);
  479. armyChanged();
  480. return ret;
  481. }
  482. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  483. {
  484. assert(hasStackAtSlot(slot));
  485. CStackInstance *s = stacks[slot];
  486. s->setType(type);
  487. armyChanged();
  488. }
  489. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  490. {
  491. if(!allowMergingStacks)
  492. {
  493. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  494. std::set<const CCreature*> cresToAdd;
  495. for(const auto & elem : cs.stacks)
  496. {
  497. SlotID dest = getSlotFor(elem.second->type);
  498. if(!dest.validSlot() || hasStackAtSlot(dest))
  499. cresToAdd.insert(elem.second->type);
  500. }
  501. return cresToAdd.size() <= freeSlots;
  502. }
  503. else
  504. {
  505. CCreatureSet cres;
  506. SlotID j;
  507. //get types of creatures that need their own slot
  508. for(const auto & elem : cs.stacks)
  509. if ((j = cres.getSlotFor(elem.second->type)).validSlot())
  510. cres.addToSlot(j, elem.second->type->getId(), 1, true); //merge if possible
  511. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  512. for(const auto & elem : stacks)
  513. {
  514. if ((j = cres.getSlotFor(elem.second->type)).validSlot())
  515. cres.addToSlot(j, elem.second->type->getId(), 1, true); //merge if possible
  516. else
  517. return false; //no place found
  518. }
  519. return true; //all stacks found their slots
  520. }
  521. }
  522. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  523. {
  524. return vstd::contains(stacks, slot);
  525. }
  526. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  527. {
  528. assert(0);
  529. return *this;
  530. }
  531. void CCreatureSet::armyChanged()
  532. {
  533. }
  534. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const std::optional<int> fixedSize)
  535. {
  536. if(handler.saving && stacks.empty())
  537. return;
  538. auto a = handler.enterArray(fieldName);
  539. if(handler.saving)
  540. {
  541. size_t sz = 0;
  542. for(const auto & p : stacks)
  543. vstd::amax(sz, p.first.getNum()+1);
  544. if(fixedSize)
  545. vstd::amax(sz, fixedSize.value());
  546. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  547. for(const auto & p : stacks)
  548. {
  549. auto s = a.enterStruct(p.first.getNum());
  550. p.second->serializeJson(handler);
  551. }
  552. }
  553. else
  554. {
  555. for(size_t idx = 0; idx < a.size(); idx++)
  556. {
  557. auto s = a.enterStruct(idx);
  558. TQuantity amount = 0;
  559. handler.serializeInt("amount", amount);
  560. if(amount > 0)
  561. {
  562. auto * new_stack = new CStackInstance();
  563. new_stack->serializeJson(handler);
  564. putStack(SlotID(static_cast<si32>(idx)), new_stack);
  565. }
  566. }
  567. }
  568. }
  569. CStackInstance::CStackInstance()
  570. : armyObj(_armyObj)
  571. {
  572. init();
  573. }
  574. CStackInstance::CStackInstance(const CreatureID & id, TQuantity Count, bool isHypothetic):
  575. CBonusSystemNode(isHypothetic), armyObj(_armyObj)
  576. {
  577. init();
  578. setType(id);
  579. count = Count;
  580. }
  581. CStackInstance::CStackInstance(const CCreature *cre, TQuantity Count, bool isHypothetic)
  582. : CBonusSystemNode(isHypothetic), armyObj(_armyObj)
  583. {
  584. init();
  585. setType(cre);
  586. count = Count;
  587. }
  588. void CStackInstance::init()
  589. {
  590. experience = 0;
  591. count = 0;
  592. type = nullptr;
  593. _armyObj = nullptr;
  594. setNodeType(STACK_INSTANCE);
  595. }
  596. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  597. {
  598. return CCreature::getQuantityID(count);
  599. }
  600. int CStackInstance::getExpRank() const
  601. {
  602. if (!VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  603. return 0;
  604. int tier = type->getLevel();
  605. if (vstd::iswithin(tier, 1, 7))
  606. {
  607. for(int i = static_cast<int>(VLC->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  608. { //exp values vary from 1st level to max exp at 11th level
  609. if (experience >= VLC->creh->expRanks[tier][i])
  610. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  611. }
  612. return 0;
  613. }
  614. else //higher tier
  615. {
  616. for(int i = static_cast<int>(VLC->creh->expRanks[0].size()) - 2; i > -1; --i)
  617. {
  618. if (experience >= VLC->creh->expRanks[0][i])
  619. return ++i;
  620. }
  621. return 0;
  622. }
  623. }
  624. int CStackInstance::getLevel() const
  625. {
  626. return std::max(1, static_cast<int>(type->getLevel()));
  627. }
  628. void CStackInstance::giveStackExp(TExpType exp)
  629. {
  630. int level = type->getLevel();
  631. if (!vstd::iswithin(level, 1, 7))
  632. level = 0;
  633. CCreatureHandler * creh = VLC->creh;
  634. ui32 maxExp = creh->expRanks[level].back();
  635. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  636. vstd::amin(exp, (maxExp * creh->maxExpPerBattle[level])/100);
  637. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  638. }
  639. void CStackInstance::setType(const CreatureID & creID)
  640. {
  641. if(creID >= 0 && creID < VLC->creh->objects.size())
  642. setType(VLC->creh->objects[creID]);
  643. else
  644. setType((const CCreature*)nullptr);
  645. }
  646. void CStackInstance::setType(const CCreature *c)
  647. {
  648. if(type)
  649. {
  650. detachFrom(const_cast<CCreature&>(*type));
  651. if (type->isMyUpgrade(c) && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  652. experience = static_cast<TExpType>(experience * VLC->creh->expAfterUpgrade / 100.0);
  653. }
  654. CStackBasicDescriptor::setType(c);
  655. if(type)
  656. attachTo(const_cast<CCreature&>(*type));
  657. }
  658. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  659. {
  660. return VLC->getBth()->bonusToString(bonus, this, description);
  661. }
  662. std::string CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  663. {
  664. return VLC->getBth()->bonusToGraphics(bonus);
  665. }
  666. void CStackInstance::setArmyObj(const CArmedInstance * ArmyObj)
  667. {
  668. if(_armyObj)
  669. detachFrom(const_cast<CArmedInstance&>(*_armyObj));
  670. _armyObj = ArmyObj;
  671. if(ArmyObj)
  672. attachTo(const_cast<CArmedInstance&>(*_armyObj));
  673. }
  674. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  675. {
  676. CCreature::CreatureQuantityId quantity = getQuantityID();
  677. if ((int)quantity)
  678. {
  679. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  680. return CCreature::getQuantityRangeStringForId(quantity);
  681. return VLC->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  682. }
  683. else
  684. return "";
  685. }
  686. bool CStackInstance::valid(bool allowUnrandomized) const
  687. {
  688. if(!randomStack)
  689. {
  690. return (type && type == VLC->creh->objects[type->getId()]);
  691. }
  692. else
  693. return allowUnrandomized;
  694. }
  695. std::string CStackInstance::nodeName() const
  696. {
  697. std::ostringstream oss;
  698. oss << "Stack of " << count << " of ";
  699. if(type)
  700. oss << type->getNamePluralTextID();
  701. else
  702. oss << "[UNDEFINED TYPE]";
  703. return oss.str();
  704. }
  705. PlayerColor CStackInstance::getOwner() const
  706. {
  707. return _armyObj ? _armyObj->getOwner() : PlayerColor::NEUTRAL;
  708. }
  709. void CStackInstance::deserializationFix()
  710. {
  711. const CArmedInstance *armyBackup = _armyObj;
  712. _armyObj = nullptr;
  713. setArmyObj(armyBackup);
  714. artDeserializationFix(this);
  715. }
  716. CreatureID CStackInstance::getCreatureID() const
  717. {
  718. if(type)
  719. return type->getId();
  720. else
  721. return CreatureID::NONE;
  722. }
  723. std::string CStackInstance::getName() const
  724. {
  725. return (count > 1) ? type->getNamePluralTranslated() : type->getNameSingularTranslated();
  726. }
  727. ui64 CStackInstance::getPower() const
  728. {
  729. assert(type);
  730. return type->getAIValue() * count;
  731. }
  732. ArtBearer::ArtBearer CStackInstance::bearerType() const
  733. {
  734. return ArtBearer::CREATURE;
  735. }
  736. void CStackInstance::putArtifact(ArtifactPosition pos, CArtifactInstance * art)
  737. {
  738. assert(!getArt(pos));
  739. assert(art->artType->canBePutAt(this, pos));
  740. CArtifactSet::putArtifact(pos, art);
  741. if(ArtifactUtils::isSlotEquipment(pos))
  742. attachTo(*art);
  743. }
  744. void CStackInstance::removeArtifact(ArtifactPosition pos)
  745. {
  746. assert(getArt(pos));
  747. detachFrom(*getArt(pos));
  748. CArtifactSet::removeArtifact(pos);
  749. }
  750. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  751. {
  752. //todo: artifacts
  753. CStackBasicDescriptor::serializeJson(handler);//must be first
  754. if(handler.saving)
  755. {
  756. if(randomStack)
  757. {
  758. int level = randomStack->level;
  759. int upgrade = randomStack->upgrade;
  760. handler.serializeInt("level", level, 0);
  761. handler.serializeInt("upgraded", upgrade, 0);
  762. }
  763. }
  764. else
  765. {
  766. //type set by CStackBasicDescriptor::serializeJson
  767. if(type == nullptr)
  768. {
  769. uint8_t level = 0;
  770. uint8_t upgrade = 0;
  771. handler.serializeInt("level", level, 0);
  772. handler.serializeInt("upgrade", upgrade, 0);
  773. randomStack = RandomStackInfo{ level, upgrade };
  774. }
  775. }
  776. }
  777. FactionID CStackInstance::getFaction() const
  778. {
  779. if(type)
  780. return type->getFaction();
  781. return FactionID::NEUTRAL;
  782. }
  783. const IBonusBearer* CStackInstance::getBonusBearer() const
  784. {
  785. return this;
  786. }
  787. CCommanderInstance::CCommanderInstance()
  788. {
  789. init();
  790. }
  791. CCommanderInstance::CCommanderInstance(const CreatureID & id): name("Commando")
  792. {
  793. init();
  794. setType(id);
  795. //TODO - parse them
  796. }
  797. void CCommanderInstance::init()
  798. {
  799. alive = true;
  800. experience = 0;
  801. level = 1;
  802. count = 1;
  803. type = nullptr;
  804. _armyObj = nullptr;
  805. setNodeType (CBonusSystemNode::COMMANDER);
  806. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  807. }
  808. void CCommanderInstance::setAlive (bool Alive)
  809. {
  810. //TODO: helm of immortality
  811. alive = Alive;
  812. if (!alive)
  813. {
  814. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  815. }
  816. }
  817. void CCommanderInstance::giveStackExp (TExpType exp)
  818. {
  819. if (alive)
  820. experience += exp;
  821. }
  822. int CCommanderInstance::getExpRank() const
  823. {
  824. return VLC->heroh->level (experience);
  825. }
  826. int CCommanderInstance::getLevel() const
  827. {
  828. return std::max (1, getExpRank());
  829. }
  830. void CCommanderInstance::levelUp ()
  831. {
  832. level++;
  833. for(const auto & bonus : VLC->creh->commanderLevelPremy)
  834. { //grant all regular level-up bonuses
  835. accumulateBonus(bonus);
  836. }
  837. }
  838. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  839. {
  840. return ArtBearer::COMMANDER;
  841. }
  842. bool CCommanderInstance::gainsLevel() const
  843. {
  844. return experience >= static_cast<TExpType>(VLC->heroh->reqExp(level + 1));
  845. }
  846. //This constructor should be placed here to avoid side effects
  847. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  848. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  849. type(VLC->creh->objects[id]),
  850. count(Count)
  851. {
  852. }
  853. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  854. : type(c), count(Count)
  855. {
  856. }
  857. const Creature * CStackBasicDescriptor::getType() const
  858. {
  859. return type;
  860. }
  861. TQuantity CStackBasicDescriptor::getCount() const
  862. {
  863. return count;
  864. }
  865. void CStackBasicDescriptor::setType(const CCreature * c)
  866. {
  867. type = c;
  868. }
  869. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  870. {
  871. handler.serializeInt("amount", count);
  872. if(handler.saving)
  873. {
  874. if(type)
  875. {
  876. std::string typeName = type->getJsonKey();
  877. handler.serializeString("type", typeName);
  878. }
  879. }
  880. else
  881. {
  882. std::string typeName;
  883. handler.serializeString("type", typeName);
  884. if(!typeName.empty())
  885. setType(VLC->creh->getCreature(ModScope::scopeMap(), typeName));
  886. }
  887. }
  888. void CSimpleArmy::clearSlots()
  889. {
  890. army.clear();
  891. }
  892. CSimpleArmy::operator bool() const
  893. {
  894. return !army.empty();
  895. }
  896. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  897. {
  898. assert(!vstd::contains(army, slot));
  899. army[slot] = std::make_pair(cre, count);
  900. return true;
  901. }
  902. VCMI_LIB_NAMESPACE_END