CCreatureSet.cpp 23 KB

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