CUnitState.cpp 21 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. casts(this),
  402. counterAttacks(this),
  403. health(this),
  404. shots(this),
  405. totalAttacks(this, Selector::type(Bonus::ADDITIONAL_ATTACK), 1),
  406. minDamage(this, Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1)), 0),
  407. maxDamage(this, Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2)), 0),
  408. attack(this, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), 0),
  409. defence(this, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE), 0),
  410. inFrenzy(this, Selector::type(Bonus::IN_FRENZY)),
  411. cloneLifetimeMarker(this, Selector::type(Bonus::NONE).And(Selector::source(Bonus::SPELL_EFFECT, SpellID::CLONE))),
  412. cloneID(-1),
  413. position()
  414. {
  415. }
  416. CUnitState & CUnitState::operator=(const CUnitState & other)
  417. {
  418. //do not change unit and bonus info
  419. cloned = other.cloned;
  420. defending = other.defending;
  421. defendingAnim = other.defendingAnim;
  422. drainedMana = other.drainedMana;
  423. fear = other.fear;
  424. hadMorale = other.hadMorale;
  425. ghost = other.ghost;
  426. ghostPending = other.ghostPending;
  427. movedThisRound = other.movedThisRound;
  428. summoned = other.summoned;
  429. waiting = other.waiting;
  430. casts = other.casts;
  431. counterAttacks = other.counterAttacks;
  432. health = other.health;
  433. shots = other.shots;
  434. totalAttacks = other.totalAttacks;
  435. minDamage = other.minDamage;
  436. maxDamage = other.maxDamage;
  437. attack = other.attack;
  438. defence = other.defence;
  439. inFrenzy = other.inFrenzy;
  440. cloneLifetimeMarker = other.cloneLifetimeMarker;
  441. cloneID = other.cloneID;
  442. position = other.position;
  443. return *this;
  444. }
  445. int32_t CUnitState::creatureIndex() const
  446. {
  447. return static_cast<int32_t>(creatureId().toEnum());
  448. }
  449. CreatureID CUnitState::creatureId() const
  450. {
  451. return unitType()->idNumber;
  452. }
  453. int32_t CUnitState::creatureLevel() const
  454. {
  455. return static_cast<int32_t>(unitType()->level);
  456. }
  457. bool CUnitState::doubleWide() const
  458. {
  459. return unitType()->doubleWide;
  460. }
  461. int32_t CUnitState::creatureCost() const
  462. {
  463. return unitType()->cost[Res::GOLD];
  464. }
  465. int32_t CUnitState::creatureIconIndex() const
  466. {
  467. return unitType()->iconIndex;
  468. }
  469. ui8 CUnitState::getSpellSchoolLevel(const spells::Spell * spell, int * outSelectedSchool) const
  470. {
  471. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->getIndex()));
  472. vstd::abetween(skill, 0, 3);
  473. return skill;
  474. }
  475. int64_t CUnitState::getSpellBonus(const spells::Spell * spell, int64_t base, const Unit * affectedStack) const
  476. {
  477. //does not have sorcery-like bonuses (yet?)
  478. return base;
  479. }
  480. int64_t CUnitState::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  481. {
  482. return base;
  483. }
  484. int CUnitState::getEffectLevel(const spells::Spell * spell) const
  485. {
  486. return getSpellSchoolLevel(spell);
  487. }
  488. int CUnitState::getEffectPower(const spells::Spell * spell) const
  489. {
  490. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * getCount() / 100;
  491. }
  492. int CUnitState::getEnchantPower(const spells::Spell * spell) const
  493. {
  494. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  495. if(res <= 0)
  496. res = 3;//default for creatures
  497. return res;
  498. }
  499. int64_t CUnitState::getEffectValue(const spells::Spell * spell) const
  500. {
  501. return static_cast<int64_t>(getCount()) * valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->getIndex());
  502. }
  503. const PlayerColor CUnitState::getOwner() const
  504. {
  505. return env->unitEffectiveOwner(this);
  506. }
  507. void CUnitState::getCasterName(MetaString & text) const
  508. {
  509. //always plural name in case of spell cast.
  510. addNameReplacement(text, true);
  511. }
  512. void CUnitState::getCastDescription(const spells::Spell * spell, const std::vector<const Unit *> & attacked, MetaString & text) const
  513. {
  514. text.addTxt(MetaString::GENERAL_TXT, 565);//The %s casts %s
  515. //todo: use text 566 for single creature
  516. getCasterName(text);
  517. text.addReplacement(MetaString::SPELL_NAME, spell->getIndex());
  518. }
  519. bool CUnitState::ableToRetaliate() const
  520. {
  521. return alive()
  522. && counterAttacks.canUse();
  523. }
  524. bool CUnitState::alive() const
  525. {
  526. return health.getCount() > 0;
  527. }
  528. bool CUnitState::isGhost() const
  529. {
  530. return ghost;
  531. }
  532. bool CUnitState::isValidTarget(bool allowDead) const
  533. {
  534. return (alive() || (allowDead && isDead())) && getPosition().isValid() && !isTurret();
  535. }
  536. bool CUnitState::isClone() const
  537. {
  538. return cloned;
  539. }
  540. bool CUnitState::hasClone() const
  541. {
  542. return cloneID > 0;
  543. }
  544. bool CUnitState::canCast() const
  545. {
  546. return casts.canUse(1);//do not check specific cast abilities here
  547. }
  548. bool CUnitState::isCaster() const
  549. {
  550. return casts.total() > 0;//do not check specific cast abilities here
  551. }
  552. bool CUnitState::canShoot() const
  553. {
  554. return shots.canUse(1);
  555. }
  556. bool CUnitState::isShooter() const
  557. {
  558. return shots.total() > 0;
  559. }
  560. int32_t CUnitState::getKilled() const
  561. {
  562. int32_t res = unitBaseAmount() - health.getCount() + health.getResurrected();
  563. vstd::amax(res, 0);
  564. return res;
  565. }
  566. int32_t CUnitState::getCount() const
  567. {
  568. return health.getCount();
  569. }
  570. int32_t CUnitState::getFirstHPleft() const
  571. {
  572. return health.getFirstHPleft();
  573. }
  574. int64_t CUnitState::getAvailableHealth() const
  575. {
  576. return health.available();
  577. }
  578. int64_t CUnitState::getTotalHealth() const
  579. {
  580. return health.total();
  581. }
  582. BattleHex CUnitState::getPosition() const
  583. {
  584. return position;
  585. }
  586. void CUnitState::setPosition(BattleHex hex)
  587. {
  588. position = hex;
  589. }
  590. int32_t CUnitState::getInitiative(int turn) const
  591. {
  592. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  593. }
  594. bool CUnitState::canMove(int turn) const
  595. {
  596. return alive() && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  597. }
  598. bool CUnitState::defended(int turn) const
  599. {
  600. if(!turn)
  601. return defending;
  602. else
  603. return false;
  604. }
  605. bool CUnitState::moved(int turn) const
  606. {
  607. if(!turn)
  608. return movedThisRound;
  609. else
  610. return false;
  611. }
  612. bool CUnitState::willMove(int turn) const
  613. {
  614. return (turn ? true : !defending)
  615. && !moved(turn)
  616. && canMove(turn);
  617. }
  618. bool CUnitState::waited(int turn) const
  619. {
  620. if(!turn)
  621. return waiting;
  622. else
  623. return false;
  624. }
  625. int CUnitState::battleQueuePhase(int turn) const
  626. {
  627. if(turn <= 0 && waited()) //consider waiting state only for ongoing round
  628. {
  629. if(hadMorale)
  630. return 2;
  631. else
  632. return 3;
  633. }
  634. else if(creatureIndex() == CreatureID::CATAPULT || isTurret()) //catapult and turrets are first
  635. {
  636. return 0;
  637. }
  638. else
  639. {
  640. return 1;
  641. }
  642. }
  643. int CUnitState::getTotalAttacks(bool ranged) const
  644. {
  645. return ranged ? totalAttacks.getRangedValue() : totalAttacks.getMeleeValue();
  646. }
  647. int CUnitState::getMinDamage(bool ranged) const
  648. {
  649. return ranged ? minDamage.getRangedValue() : minDamage.getMeleeValue();
  650. }
  651. int CUnitState::getMaxDamage(bool ranged) const
  652. {
  653. return ranged ? maxDamage.getRangedValue() : maxDamage.getMeleeValue();
  654. }
  655. int CUnitState::getAttack(bool ranged) const
  656. {
  657. int ret = ranged ? attack.getRangedValue() : attack.getMeleeValue();
  658. if(!inFrenzy->empty())
  659. {
  660. double frenzyPower = (double)inFrenzy->totalValue() / 100;
  661. frenzyPower *= (double) (ranged ? defence.getRangedValue() : defence.getMeleeValue());
  662. ret += frenzyPower;
  663. }
  664. vstd::amax(ret, 0);
  665. return ret;
  666. }
  667. int CUnitState::getDefence(bool ranged) const
  668. {
  669. if(!inFrenzy->empty())
  670. {
  671. return 0;
  672. }
  673. else
  674. {
  675. int ret = ranged ? defence.getRangedValue() : defence.getMeleeValue();
  676. vstd::amax(ret, 0);
  677. return ret;
  678. }
  679. }
  680. std::shared_ptr<Unit> CUnitState::acquire() const
  681. {
  682. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  683. ret->localInit(env);
  684. *ret = *this;
  685. return ret;
  686. }
  687. std::shared_ptr<CUnitState> CUnitState::acquireState() const
  688. {
  689. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  690. ret->localInit(env);
  691. *ret = *this;
  692. return ret;
  693. }
  694. void CUnitState::serializeJson(JsonSerializeFormat & handler)
  695. {
  696. if(!handler.saving)
  697. reset();
  698. handler.serializeBool("cloned", cloned);
  699. handler.serializeBool("defending", defending);
  700. handler.serializeBool("defendingAnim", defendingAnim);
  701. handler.serializeBool("drainedMana", drainedMana);
  702. handler.serializeBool("fear", fear);
  703. handler.serializeBool("hadMorale", hadMorale);
  704. handler.serializeBool("ghost", ghost);
  705. handler.serializeBool("ghostPending", ghostPending);
  706. handler.serializeBool("moved", movedThisRound);
  707. handler.serializeBool("summoned", summoned);
  708. handler.serializeBool("waiting", waiting);
  709. handler.serializeStruct("casts", casts);
  710. handler.serializeStruct("counterAttacks", counterAttacks);
  711. handler.serializeStruct("health", health);
  712. handler.serializeStruct("shots", shots);
  713. handler.serializeInt("cloneID", cloneID);
  714. handler.serializeInt("position", position);
  715. }
  716. void CUnitState::localInit(const IUnitEnvironment * env_)
  717. {
  718. env = env_;
  719. shots.setEnv(env);
  720. reset();
  721. health.init();
  722. }
  723. void CUnitState::reset()
  724. {
  725. cloned = false;
  726. defending = false;
  727. defendingAnim = false;
  728. drainedMana = false;
  729. fear = false;
  730. hadMorale = false;
  731. ghost = false;
  732. ghostPending = false;
  733. movedThisRound = false;
  734. summoned = false;
  735. waiting = false;
  736. casts.reset();
  737. counterAttacks.reset();
  738. health.reset();
  739. shots.reset();
  740. cloneID = -1;
  741. position = BattleHex::INVALID;
  742. }
  743. void CUnitState::save(JsonNode & data)
  744. {
  745. //TODO: use instance resolver
  746. data.clear();
  747. JsonSerializer ser(nullptr, data);
  748. ser.serializeStruct("state", *this);
  749. }
  750. void CUnitState::load(const JsonNode & data)
  751. {
  752. //TODO: use instance resolver
  753. reset();
  754. JsonDeserializer deser(nullptr, data);
  755. deser.serializeStruct("state", *this);
  756. }
  757. void CUnitState::damage(int64_t & amount)
  758. {
  759. if(cloned)
  760. {
  761. // block ability should not kill clone (0 damage)
  762. if(amount > 0)
  763. {
  764. amount = 1;//TODO: what should be actual damage against clone?
  765. health.reset();
  766. }
  767. }
  768. else
  769. {
  770. health.damage(amount);
  771. }
  772. if(health.available() <= 0 && (cloned || summoned))
  773. ghostPending = true;
  774. }
  775. void CUnitState::heal(int64_t & amount, EHealLevel level, EHealPower power)
  776. {
  777. if(level == EHealLevel::HEAL && power == EHealPower::ONE_BATTLE)
  778. logGlobal->error("Heal for one battle does not make sense");
  779. else if(cloned)
  780. logGlobal->error("Attempt to heal clone");
  781. else
  782. health.heal(amount, level, power);
  783. }
  784. void CUnitState::afterAttack(bool ranged, bool counter)
  785. {
  786. if(counter)
  787. counterAttacks.use();
  788. if(ranged)
  789. shots.use();
  790. }
  791. void CUnitState::afterNewRound()
  792. {
  793. defending = false;
  794. waiting = false;
  795. movedThisRound = false;
  796. hadMorale = false;
  797. fear = false;
  798. drainedMana = false;
  799. counterAttacks.reset();
  800. if(alive() && isClone())
  801. {
  802. if(!cloneLifetimeMarker.getHasBonus())
  803. makeGhost();
  804. }
  805. }
  806. void CUnitState::afterGetsTurn()
  807. {
  808. //if moving second time this round it must be high morale bonus
  809. if(movedThisRound)
  810. hadMorale = true;
  811. }
  812. void CUnitState::makeGhost()
  813. {
  814. health.reset();
  815. ghostPending = true;
  816. }
  817. void CUnitState::onRemoved()
  818. {
  819. health.reset();
  820. ghostPending = false;
  821. ghost = true;
  822. }
  823. CUnitStateDetached::CUnitStateDetached(const IUnitInfo * unit_, const IBonusBearer * bonus_)
  824. : CUnitState(),
  825. unit(unit_),
  826. bonus(bonus_)
  827. {
  828. }
  829. const TBonusListPtr CUnitStateDetached::getAllBonuses(const CSelector & selector, const CSelector & limit, const CBonusSystemNode * root, const std::string & cachingStr) const
  830. {
  831. return bonus->getAllBonuses(selector, limit, root, cachingStr);
  832. }
  833. int64_t CUnitStateDetached::getTreeVersion() const
  834. {
  835. return bonus->getTreeVersion();
  836. }
  837. CUnitStateDetached & CUnitStateDetached::operator=(const CUnitState & other)
  838. {
  839. CUnitState::operator=(other);
  840. return *this;
  841. }
  842. uint32_t CUnitStateDetached::unitId() const
  843. {
  844. return unit->unitId();
  845. }
  846. ui8 CUnitStateDetached::unitSide() const
  847. {
  848. return unit->unitSide();
  849. }
  850. const CCreature * CUnitStateDetached::unitType() const
  851. {
  852. return unit->unitType();
  853. }
  854. PlayerColor CUnitStateDetached::unitOwner() const
  855. {
  856. return unit->unitOwner();
  857. }
  858. SlotID CUnitStateDetached::unitSlot() const
  859. {
  860. return unit->unitSlot();
  861. }
  862. int32_t CUnitStateDetached::unitBaseAmount() const
  863. {
  864. return unit->unitBaseAmount();
  865. }
  866. void CUnitStateDetached::spendMana(const spells::PacketSender * server, const int spellCost) const
  867. {
  868. if(spellCost != 1)
  869. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  870. //this is evil, but
  871. //use of netpacks in detached state is an error
  872. //non const API is more evil for hero
  873. const_cast<CUnitStateDetached *>(this)->casts.use(spellCost);
  874. }
  875. }