CCreatureSet.cpp 23 KB

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