CUnitState.cpp 19 KB

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