CUnitState.cpp 21 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. /*
  2. * CUnitState.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 "CUnitState.h"
  12. #include "../NetPacks.h"
  13. #include "../CCreatureHandler.h"
  14. #include "../serializer/JsonDeserializer.h"
  15. #include "../serializer/JsonSerializer.h"
  16. namespace battle
  17. {
  18. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue)
  19. : target(Target),
  20. selector(Selector),
  21. initialValue(InitialValue),
  22. meleeCachedLast(0),
  23. meleeValue(0),
  24. rangedCachedLast(0),
  25. rangedValue(0)
  26. {
  27. }
  28. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  29. : target(other.target),
  30. selector(other.selector),
  31. initialValue(other.initialValue),
  32. meleeCachedLast(other.meleeCachedLast),
  33. meleeValue(other.meleeValue),
  34. rangedCachedLast(other.rangedCachedLast),
  35. rangedValue(other.rangedValue)
  36. {
  37. }
  38. CTotalsProxy & CTotalsProxy::operator=(const CTotalsProxy & other)
  39. {
  40. initialValue = other.initialValue;
  41. meleeCachedLast = other.meleeCachedLast;
  42. meleeValue = other.meleeValue;
  43. rangedCachedLast = other.rangedCachedLast;
  44. rangedValue = other.rangedValue;
  45. return *this;
  46. }
  47. int CTotalsProxy::getMeleeValue() const
  48. {
  49. static const auto limit = Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_MELEE_FIGHT));
  50. const auto treeVersion = target->getTreeVersion();
  51. if(treeVersion != meleeCachedLast)
  52. {
  53. auto bonuses = target->getBonuses(selector, limit);
  54. meleeValue = initialValue + bonuses->totalValue();
  55. meleeCachedLast = treeVersion;
  56. }
  57. return meleeValue;
  58. }
  59. int CTotalsProxy::getRangedValue() const
  60. {
  61. static const auto limit = Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT));
  62. const auto treeVersion = target->getTreeVersion();
  63. if(treeVersion != rangedCachedLast)
  64. {
  65. auto bonuses = target->getBonuses(selector, limit);
  66. rangedValue = initialValue + bonuses->totalValue();
  67. rangedCachedLast = treeVersion;
  68. }
  69. return rangedValue;
  70. }
  71. ///CCheckProxy
  72. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector)
  73. : target(Target),
  74. selector(Selector),
  75. cachedLast(0),
  76. hasBonus(false)
  77. {
  78. }
  79. CCheckProxy::CCheckProxy(const CCheckProxy & other)
  80. : target(other.target),
  81. selector(other.selector),
  82. cachedLast(other.cachedLast),
  83. hasBonus(other.hasBonus)
  84. {
  85. }
  86. bool CCheckProxy::getHasBonus() const
  87. {
  88. const auto treeVersion = target->getTreeVersion();
  89. if(treeVersion != cachedLast)
  90. {
  91. hasBonus = target->hasBonus(selector);
  92. cachedLast = treeVersion;
  93. }
  94. return hasBonus;
  95. }
  96. ///CAmmo
  97. CAmmo::CAmmo(const battle::Unit * Owner, CSelector totalSelector)
  98. : used(0),
  99. owner(Owner),
  100. totalProxy(Owner, totalSelector)
  101. {
  102. reset();
  103. }
  104. CAmmo::CAmmo(const CAmmo & other)
  105. : used(other.used),
  106. owner(other.owner),
  107. totalProxy(other.totalProxy)
  108. {
  109. }
  110. CAmmo & CAmmo::operator= (const CAmmo & other)
  111. {
  112. used = other.used;
  113. totalProxy = other.totalProxy;
  114. return *this;
  115. }
  116. int32_t CAmmo::available() const
  117. {
  118. return total() - used;
  119. }
  120. bool CAmmo::canUse(int32_t amount) const
  121. {
  122. return !isLimited() || (available() - amount >= 0);
  123. }
  124. bool CAmmo::isLimited() const
  125. {
  126. return true;
  127. }
  128. void CAmmo::reset()
  129. {
  130. used = 0;
  131. }
  132. int32_t CAmmo::total() const
  133. {
  134. return totalProxy->totalValue();
  135. }
  136. void CAmmo::use(int32_t amount)
  137. {
  138. if(!isLimited())
  139. return;
  140. if(available() - amount < 0)
  141. {
  142. logGlobal->error("Stack ammo overuse. total: %d, used: %d, requested: %d", total(), used, amount);
  143. used += available();
  144. }
  145. else
  146. used += amount;
  147. }
  148. void CAmmo::serializeJson(JsonSerializeFormat & handler)
  149. {
  150. handler.serializeInt("used", used, 0);
  151. }
  152. ///CShots
  153. CShots::CShots(const battle::Unit * Owner)
  154. : CAmmo(Owner, Selector::type(Bonus::SHOTS)),
  155. shooter(Owner, Selector::type(Bonus::SHOOTER))
  156. {
  157. }
  158. CShots::CShots(const CShots & other)
  159. : CAmmo(other),
  160. env(other.env),
  161. shooter(other.shooter)
  162. {
  163. }
  164. CShots & CShots::operator=(const CShots & other)
  165. {
  166. CAmmo::operator=(other);
  167. shooter = other.shooter;
  168. return *this;
  169. }
  170. bool CShots::isLimited() const
  171. {
  172. return !env->unitHasAmmoCart(owner) || !shooter.getHasBonus();
  173. }
  174. void CShots::setEnv(const IUnitEnvironment * env_)
  175. {
  176. env = env_;
  177. }
  178. int32_t CShots::total() const
  179. {
  180. if(shooter.getHasBonus())
  181. return CAmmo::total();
  182. else
  183. return 0;
  184. }
  185. ///CCasts
  186. CCasts::CCasts(const battle::Unit * Owner):
  187. CAmmo(Owner, Selector::type(Bonus::CASTS))
  188. {
  189. }
  190. CCasts::CCasts(const CCasts & other)
  191. : CAmmo(other)
  192. {
  193. }
  194. CCasts & CCasts::operator=(const CCasts & other)
  195. {
  196. CAmmo::operator=(other);
  197. return *this;
  198. }
  199. ///CRetaliations
  200. CRetaliations::CRetaliations(const battle::Unit * Owner)
  201. : CAmmo(Owner, Selector::type(Bonus::ADDITIONAL_RETALIATION)),
  202. totalCache(0),
  203. noRetaliation(Owner, Selector::type(Bonus::SIEGE_WEAPON).Or(Selector::type(Bonus::HYPNOTIZED)).Or(Selector::type(Bonus::NO_RETALIATION))),
  204. unlimited(Owner, Selector::type(Bonus::UNLIMITED_RETALIATIONS))
  205. {
  206. }
  207. CRetaliations::CRetaliations(const CRetaliations & other)
  208. : CAmmo(other),
  209. totalCache(other.totalCache),
  210. noRetaliation(other.noRetaliation),
  211. unlimited(other.unlimited)
  212. {
  213. }
  214. CRetaliations & CRetaliations::operator=(const CRetaliations & other)
  215. {
  216. CAmmo::operator=(other);
  217. totalCache = other.totalCache;
  218. noRetaliation = other.noRetaliation;
  219. unlimited = other.unlimited;
  220. return *this;
  221. }
  222. bool CRetaliations::isLimited() const
  223. {
  224. return !unlimited.getHasBonus() || noRetaliation.getHasBonus();
  225. }
  226. int32_t CRetaliations::total() const
  227. {
  228. if(noRetaliation.getHasBonus())
  229. return 0;
  230. //after dispell bonus should remain during current round
  231. int32_t val = 1 + totalProxy->totalValue();
  232. vstd::amax(totalCache, val);
  233. return totalCache;
  234. }
  235. void CRetaliations::reset()
  236. {
  237. CAmmo::reset();
  238. totalCache = 0;
  239. }
  240. void CRetaliations::serializeJson(JsonSerializeFormat & handler)
  241. {
  242. CAmmo::serializeJson(handler);
  243. //we may be serialized in the middle of turn
  244. handler.serializeInt("totalCache", totalCache, 0);
  245. }
  246. ///CHealth
  247. CHealth::CHealth(const battle::Unit * Owner):
  248. owner(Owner)
  249. {
  250. reset();
  251. }
  252. CHealth::CHealth(const CHealth & other):
  253. owner(other.owner),
  254. firstHPleft(other.firstHPleft),
  255. fullUnits(other.fullUnits),
  256. resurrected(other.resurrected)
  257. {
  258. }
  259. CHealth & CHealth::operator=(const CHealth & other)
  260. {
  261. //do not change owner
  262. firstHPleft = other.firstHPleft;
  263. fullUnits = other.fullUnits;
  264. resurrected = other.resurrected;
  265. return *this;
  266. }
  267. void CHealth::init()
  268. {
  269. reset();
  270. fullUnits = owner->unitBaseAmount() > 1 ? owner->unitBaseAmount() - 1 : 0;
  271. firstHPleft = owner->unitBaseAmount() > 0 ? owner->MaxHealth() : 0;
  272. }
  273. void CHealth::addResurrected(int32_t amount)
  274. {
  275. resurrected += amount;
  276. vstd::amax(resurrected, 0);
  277. }
  278. int64_t CHealth::available() const
  279. {
  280. return static_cast<int64_t>(firstHPleft) + owner->MaxHealth() * fullUnits;
  281. }
  282. int64_t CHealth::total() const
  283. {
  284. return static_cast<int64_t>(owner->MaxHealth()) * owner->unitBaseAmount();
  285. }
  286. void CHealth::damage(int64_t & amount)
  287. {
  288. const int32_t oldCount = getCount();
  289. const bool withKills = amount >= firstHPleft;
  290. if(withKills)
  291. {
  292. int64_t totalHealth = available();
  293. if(amount > totalHealth)
  294. amount = totalHealth;
  295. totalHealth -= amount;
  296. if(totalHealth <= 0)
  297. {
  298. fullUnits = 0;
  299. firstHPleft = 0;
  300. }
  301. else
  302. {
  303. setFromTotal(totalHealth);
  304. }
  305. }
  306. else
  307. {
  308. firstHPleft -= amount;
  309. }
  310. addResurrected(getCount() - oldCount);
  311. }
  312. void CHealth::heal(int64_t & amount, EHealLevel level, EHealPower power)
  313. {
  314. const int32_t unitHealth = owner->MaxHealth();
  315. const int32_t oldCount = getCount();
  316. int64_t maxHeal = std::numeric_limits<int64_t>::max();
  317. switch(level)
  318. {
  319. case EHealLevel::HEAL:
  320. maxHeal = std::max(0, unitHealth - firstHPleft);
  321. break;
  322. case EHealLevel::RESURRECT:
  323. maxHeal = total() - available();
  324. break;
  325. default:
  326. assert(level == EHealLevel::OVERHEAL);
  327. break;
  328. }
  329. vstd::amax(maxHeal, 0);
  330. vstd::abetween(amount, 0, maxHeal);
  331. if(amount == 0)
  332. return;
  333. int64_t availableHealth = available();
  334. availableHealth += amount;
  335. setFromTotal(availableHealth);
  336. if(power == EHealPower::ONE_BATTLE)
  337. addResurrected(getCount() - oldCount);
  338. else
  339. assert(power == EHealPower::PERMANENT);
  340. }
  341. void CHealth::setFromTotal(const int64_t totalHealth)
  342. {
  343. const int32_t unitHealth = owner->MaxHealth();
  344. firstHPleft = totalHealth % unitHealth;
  345. fullUnits = totalHealth / unitHealth;
  346. if(firstHPleft == 0 && fullUnits >= 1)
  347. {
  348. firstHPleft = unitHealth;
  349. fullUnits -= 1;
  350. }
  351. }
  352. void CHealth::reset()
  353. {
  354. fullUnits = 0;
  355. firstHPleft = 0;
  356. resurrected = 0;
  357. }
  358. int32_t CHealth::getCount() const
  359. {
  360. return fullUnits + (firstHPleft > 0 ? 1 : 0);
  361. }
  362. int32_t CHealth::getFirstHPleft() const
  363. {
  364. return firstHPleft;
  365. }
  366. int32_t CHealth::getResurrected() const
  367. {
  368. return resurrected;
  369. }
  370. void CHealth::takeResurrected()
  371. {
  372. if(resurrected != 0)
  373. {
  374. int64_t totalHealth = available();
  375. totalHealth -= resurrected * owner->MaxHealth();
  376. vstd::amax(totalHealth, 0);
  377. setFromTotal(totalHealth);
  378. resurrected = 0;
  379. }
  380. }
  381. void CHealth::serializeJson(JsonSerializeFormat & handler)
  382. {
  383. handler.serializeInt("firstHPleft", firstHPleft, 0);
  384. handler.serializeInt("fullUnits", fullUnits, 0);
  385. handler.serializeInt("resurrected", resurrected, 0);
  386. }
  387. ///CUnitState
  388. CUnitState::CUnitState()
  389. : env(nullptr),
  390. cloned(false),
  391. defending(false),
  392. defendingAnim(false),
  393. drainedMana(false),
  394. fear(false),
  395. hadMorale(false),
  396. ghost(false),
  397. ghostPending(false),
  398. movedThisRound(false),
  399. summoned(false),
  400. waiting(false),
  401. waitedThisTurn(false),
  402. casts(this),
  403. counterAttacks(this),
  404. health(this),
  405. shots(this),
  406. totalAttacks(this, Selector::type(Bonus::ADDITIONAL_ATTACK), 1),
  407. minDamage(this, Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1)), 0),
  408. maxDamage(this, Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2)), 0),
  409. attack(this, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), 0),
  410. defence(this, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE), 0),
  411. inFrenzy(this, Selector::type(Bonus::IN_FRENZY)),
  412. cloneLifetimeMarker(this, Selector::type(Bonus::NONE).And(Selector::source(Bonus::SPELL_EFFECT, SpellID::CLONE))),
  413. cloneID(-1),
  414. position()
  415. {
  416. }
  417. CUnitState & CUnitState::operator=(const CUnitState & other)
  418. {
  419. //do not change unit and bonus info
  420. cloned = other.cloned;
  421. defending = other.defending;
  422. defendingAnim = other.defendingAnim;
  423. drainedMana = other.drainedMana;
  424. fear = other.fear;
  425. hadMorale = other.hadMorale;
  426. ghost = other.ghost;
  427. ghostPending = other.ghostPending;
  428. movedThisRound = other.movedThisRound;
  429. summoned = other.summoned;
  430. waiting = other.waiting;
  431. waitedThisTurn = other.waitedThisTurn;
  432. casts = other.casts;
  433. counterAttacks = other.counterAttacks;
  434. health = other.health;
  435. shots = other.shots;
  436. totalAttacks = other.totalAttacks;
  437. minDamage = other.minDamage;
  438. maxDamage = other.maxDamage;
  439. attack = other.attack;
  440. defence = other.defence;
  441. inFrenzy = other.inFrenzy;
  442. cloneLifetimeMarker = other.cloneLifetimeMarker;
  443. cloneID = other.cloneID;
  444. position = other.position;
  445. return *this;
  446. }
  447. int32_t CUnitState::creatureIndex() const
  448. {
  449. return static_cast<int32_t>(creatureId().toEnum());
  450. }
  451. CreatureID CUnitState::creatureId() const
  452. {
  453. return unitType()->idNumber;
  454. }
  455. int32_t CUnitState::creatureLevel() const
  456. {
  457. return static_cast<int32_t>(unitType()->level);
  458. }
  459. bool CUnitState::doubleWide() const
  460. {
  461. return unitType()->doubleWide;
  462. }
  463. int32_t CUnitState::creatureCost() const
  464. {
  465. return unitType()->cost[Res::GOLD];
  466. }
  467. int32_t CUnitState::creatureIconIndex() const
  468. {
  469. return unitType()->iconIndex;
  470. }
  471. int32_t CUnitState::getCasterUnitId() const
  472. {
  473. return static_cast<int32_t>(unitId());
  474. }
  475. ui8 CUnitState::getSpellSchoolLevel(const spells::Spell * spell, int * outSelectedSchool) const
  476. {
  477. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->getIndex()));
  478. vstd::abetween(skill, 0, 3);
  479. return skill;
  480. }
  481. int64_t CUnitState::getSpellBonus(const spells::Spell * spell, int64_t base, const Unit * affectedStack) const
  482. {
  483. //does not have sorcery-like bonuses (yet?)
  484. return base;
  485. }
  486. int64_t CUnitState::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  487. {
  488. return base;
  489. }
  490. int CUnitState::getEffectLevel(const spells::Spell * spell) const
  491. {
  492. return getSpellSchoolLevel(spell);
  493. }
  494. int CUnitState::getEffectPower(const spells::Spell * spell) const
  495. {
  496. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * getCount() / 100;
  497. }
  498. int CUnitState::getEnchantPower(const spells::Spell * spell) const
  499. {
  500. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  501. if(res <= 0)
  502. res = 3;//default for creatures
  503. return res;
  504. }
  505. int64_t CUnitState::getEffectValue(const spells::Spell * spell) const
  506. {
  507. return static_cast<int64_t>(getCount()) * valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->getIndex());
  508. }
  509. const PlayerColor CUnitState::getOwner() const
  510. {
  511. return env->unitEffectiveOwner(this);
  512. }
  513. void CUnitState::getCasterName(MetaString & text) const
  514. {
  515. //always plural name in case of spell cast.
  516. addNameReplacement(text, true);
  517. }
  518. void CUnitState::getCastDescription(const spells::Spell * spell, const std::vector<const Unit *> & attacked, MetaString & text) const
  519. {
  520. text.addTxt(MetaString::GENERAL_TXT, 565);//The %s casts %s
  521. //todo: use text 566 for single creature
  522. getCasterName(text);
  523. text.addReplacement(MetaString::SPELL_NAME, spell->getIndex());
  524. }
  525. bool CUnitState::ableToRetaliate() const
  526. {
  527. return alive()
  528. && counterAttacks.canUse();
  529. }
  530. bool CUnitState::alive() const
  531. {
  532. return health.getCount() > 0;
  533. }
  534. bool CUnitState::isGhost() const
  535. {
  536. return ghost;
  537. }
  538. bool CUnitState::isValidTarget(bool allowDead) const
  539. {
  540. return (alive() || (allowDead && isDead())) && getPosition().isValid() && !isTurret();
  541. }
  542. bool CUnitState::isClone() const
  543. {
  544. return cloned;
  545. }
  546. bool CUnitState::hasClone() const
  547. {
  548. return cloneID > 0;
  549. }
  550. bool CUnitState::canCast() const
  551. {
  552. return casts.canUse(1);//do not check specific cast abilities here
  553. }
  554. bool CUnitState::isCaster() const
  555. {
  556. return casts.total() > 0;//do not check specific cast abilities here
  557. }
  558. bool CUnitState::canShoot() const
  559. {
  560. return shots.canUse(1);
  561. }
  562. bool CUnitState::isShooter() const
  563. {
  564. return shots.total() > 0;
  565. }
  566. int32_t CUnitState::getKilled() const
  567. {
  568. int32_t res = unitBaseAmount() - health.getCount() + health.getResurrected();
  569. vstd::amax(res, 0);
  570. return res;
  571. }
  572. int32_t CUnitState::getCount() const
  573. {
  574. return health.getCount();
  575. }
  576. int32_t CUnitState::getFirstHPleft() const
  577. {
  578. return health.getFirstHPleft();
  579. }
  580. int64_t CUnitState::getAvailableHealth() const
  581. {
  582. return health.available();
  583. }
  584. int64_t CUnitState::getTotalHealth() const
  585. {
  586. return health.total();
  587. }
  588. BattleHex CUnitState::getPosition() const
  589. {
  590. return position;
  591. }
  592. void CUnitState::setPosition(BattleHex hex)
  593. {
  594. position = hex;
  595. }
  596. int32_t CUnitState::getInitiative(int turn) const
  597. {
  598. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  599. }
  600. bool CUnitState::canMove(int turn) const
  601. {
  602. return alive() && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  603. }
  604. bool CUnitState::defended(int turn) const
  605. {
  606. return !turn && defending;
  607. }
  608. bool CUnitState::moved(int turn) const
  609. {
  610. if(!turn && !waiting)
  611. return movedThisRound;
  612. else
  613. return false;
  614. }
  615. bool CUnitState::willMove(int turn) const
  616. {
  617. return (turn ? true : !defending)
  618. && !moved(turn)
  619. && canMove(turn);
  620. }
  621. bool CUnitState::waited(int turn) const
  622. {
  623. if(!turn)
  624. return waiting;
  625. else
  626. return false;
  627. }
  628. int CUnitState::battleQueuePhase(int turn) const
  629. {
  630. if(turn <= 0 && waited()) //consider waiting state only for ongoing round
  631. {
  632. if(hadMorale)
  633. return 2;
  634. else
  635. return 3;
  636. }
  637. else if(creatureIndex() == CreatureID::CATAPULT || isTurret()) //catapult and turrets are first
  638. {
  639. return 0;
  640. }
  641. else
  642. {
  643. return 1;
  644. }
  645. }
  646. int CUnitState::getTotalAttacks(bool ranged) const
  647. {
  648. return ranged ? totalAttacks.getRangedValue() : totalAttacks.getMeleeValue();
  649. }
  650. int CUnitState::getMinDamage(bool ranged) const
  651. {
  652. return ranged ? minDamage.getRangedValue() : minDamage.getMeleeValue();
  653. }
  654. int CUnitState::getMaxDamage(bool ranged) const
  655. {
  656. return ranged ? maxDamage.getRangedValue() : maxDamage.getMeleeValue();
  657. }
  658. int CUnitState::getAttack(bool ranged) const
  659. {
  660. int ret = ranged ? attack.getRangedValue() : attack.getMeleeValue();
  661. if(!inFrenzy->empty())
  662. {
  663. double frenzyPower = (double)inFrenzy->totalValue() / 100;
  664. frenzyPower *= (double) (ranged ? defence.getRangedValue() : defence.getMeleeValue());
  665. ret += frenzyPower;
  666. }
  667. vstd::amax(ret, 0);
  668. return ret;
  669. }
  670. int CUnitState::getDefence(bool ranged) const
  671. {
  672. if(!inFrenzy->empty())
  673. {
  674. return 0;
  675. }
  676. else
  677. {
  678. int ret = ranged ? defence.getRangedValue() : defence.getMeleeValue();
  679. vstd::amax(ret, 0);
  680. return ret;
  681. }
  682. }
  683. std::shared_ptr<Unit> CUnitState::acquire() const
  684. {
  685. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  686. ret->localInit(env);
  687. *ret = *this;
  688. return ret;
  689. }
  690. std::shared_ptr<CUnitState> CUnitState::acquireState() const
  691. {
  692. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  693. ret->localInit(env);
  694. *ret = *this;
  695. return ret;
  696. }
  697. void CUnitState::serializeJson(JsonSerializeFormat & handler)
  698. {
  699. if(!handler.saving)
  700. reset();
  701. handler.serializeBool("cloned", cloned);
  702. handler.serializeBool("defending", defending);
  703. handler.serializeBool("defendingAnim", defendingAnim);
  704. handler.serializeBool("drainedMana", drainedMana);
  705. handler.serializeBool("fear", fear);
  706. handler.serializeBool("hadMorale", hadMorale);
  707. handler.serializeBool("ghost", ghost);
  708. handler.serializeBool("ghostPending", ghostPending);
  709. handler.serializeBool("moved", movedThisRound);
  710. handler.serializeBool("summoned", summoned);
  711. handler.serializeBool("waiting", waiting);
  712. handler.serializeBool("waitedThisTurn", waitedThisTurn);
  713. handler.serializeStruct("casts", casts);
  714. handler.serializeStruct("counterAttacks", counterAttacks);
  715. handler.serializeStruct("health", health);
  716. handler.serializeStruct("shots", shots);
  717. handler.serializeInt("cloneID", cloneID);
  718. handler.serializeInt("position", position);
  719. }
  720. void CUnitState::localInit(const IUnitEnvironment * env_)
  721. {
  722. env = env_;
  723. shots.setEnv(env);
  724. reset();
  725. health.init();
  726. }
  727. void CUnitState::reset()
  728. {
  729. cloned = false;
  730. defending = false;
  731. defendingAnim = false;
  732. drainedMana = false;
  733. fear = false;
  734. hadMorale = false;
  735. ghost = false;
  736. ghostPending = false;
  737. movedThisRound = false;
  738. summoned = false;
  739. waiting = false;
  740. waitedThisTurn = false;
  741. casts.reset();
  742. counterAttacks.reset();
  743. health.reset();
  744. shots.reset();
  745. cloneID = -1;
  746. position = BattleHex::INVALID;
  747. }
  748. void CUnitState::save(JsonNode & data)
  749. {
  750. //TODO: use instance resolver
  751. data.clear();
  752. JsonSerializer ser(nullptr, data);
  753. ser.serializeStruct("state", *this);
  754. }
  755. void CUnitState::load(const JsonNode & data)
  756. {
  757. //TODO: use instance resolver
  758. reset();
  759. JsonDeserializer deser(nullptr, data);
  760. deser.serializeStruct("state", *this);
  761. }
  762. void CUnitState::damage(int64_t & amount)
  763. {
  764. if(cloned)
  765. {
  766. // block ability should not kill clone (0 damage)
  767. if(amount > 0)
  768. {
  769. amount = 1;//TODO: what should be actual damage against clone?
  770. health.reset();
  771. }
  772. }
  773. else
  774. {
  775. health.damage(amount);
  776. }
  777. if(health.available() <= 0 && (cloned || summoned))
  778. ghostPending = true;
  779. }
  780. void CUnitState::heal(int64_t & amount, EHealLevel level, EHealPower power)
  781. {
  782. if(level == EHealLevel::HEAL && power == EHealPower::ONE_BATTLE)
  783. logGlobal->error("Heal for one battle does not make sense");
  784. else if(cloned)
  785. logGlobal->error("Attempt to heal clone");
  786. else
  787. health.heal(amount, level, power);
  788. }
  789. void CUnitState::afterAttack(bool ranged, bool counter)
  790. {
  791. if(counter)
  792. counterAttacks.use();
  793. if(ranged)
  794. shots.use();
  795. }
  796. void CUnitState::afterNewRound()
  797. {
  798. defending = false;
  799. waiting = false;
  800. waitedThisTurn = false;
  801. movedThisRound = false;
  802. hadMorale = false;
  803. fear = false;
  804. drainedMana = false;
  805. counterAttacks.reset();
  806. if(alive() && isClone())
  807. {
  808. if(!cloneLifetimeMarker.getHasBonus())
  809. makeGhost();
  810. }
  811. }
  812. void CUnitState::afterGetsTurn()
  813. {
  814. //if moving second time this round it must be high morale bonus
  815. if(movedThisRound)
  816. hadMorale = true;
  817. }
  818. void CUnitState::makeGhost()
  819. {
  820. health.reset();
  821. ghostPending = true;
  822. }
  823. void CUnitState::onRemoved()
  824. {
  825. health.reset();
  826. ghostPending = false;
  827. ghost = true;
  828. }
  829. CUnitStateDetached::CUnitStateDetached(const IUnitInfo * unit_, const IBonusBearer * bonus_)
  830. : CUnitState(),
  831. unit(unit_),
  832. bonus(bonus_)
  833. {
  834. }
  835. const TBonusListPtr CUnitStateDetached::getAllBonuses(const CSelector & selector, const CSelector & limit, const CBonusSystemNode * root, const std::string & cachingStr) const
  836. {
  837. return bonus->getAllBonuses(selector, limit, root, cachingStr);
  838. }
  839. int64_t CUnitStateDetached::getTreeVersion() const
  840. {
  841. return bonus->getTreeVersion();
  842. }
  843. CUnitStateDetached & CUnitStateDetached::operator=(const CUnitState & other)
  844. {
  845. CUnitState::operator=(other);
  846. return *this;
  847. }
  848. uint32_t CUnitStateDetached::unitId() const
  849. {
  850. return unit->unitId();
  851. }
  852. ui8 CUnitStateDetached::unitSide() const
  853. {
  854. return unit->unitSide();
  855. }
  856. const CCreature * CUnitStateDetached::unitType() const
  857. {
  858. return unit->unitType();
  859. }
  860. PlayerColor CUnitStateDetached::unitOwner() const
  861. {
  862. return unit->unitOwner();
  863. }
  864. SlotID CUnitStateDetached::unitSlot() const
  865. {
  866. return unit->unitSlot();
  867. }
  868. int32_t CUnitStateDetached::unitBaseAmount() const
  869. {
  870. return unit->unitBaseAmount();
  871. }
  872. void CUnitStateDetached::spendMana(const spells::PacketSender * server, const int spellCost) const
  873. {
  874. if(spellCost != 1)
  875. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  876. //this is evil, but
  877. //use of netpacks in detached state is an error
  878. //non const API is more evil for hero
  879. const_cast<CUnitStateDetached *>(this)->casts.use(spellCost);
  880. }
  881. }