CUnitState.cpp 21 KB

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