CUnitState.cpp 20 KB

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