CCreatureSet.cpp 25 KB

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