CCreatureSet.cpp 24 KB

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