ISpellMechanics.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /*
  2. * ISpellMechanics.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 "ISpellMechanics.h"
  12. #include "../VCMI_Lib.h"
  13. #include "../bonuses/Bonus.h"
  14. #include "../battle/CBattleInfoCallback.h"
  15. #include "../battle/IBattleState.h"
  16. #include "../battle/Unit.h"
  17. #include "../mapObjects/CGHeroInstance.h"
  18. #include "../serializer/JsonDeserializer.h"
  19. #include "../serializer/JsonSerializer.h"
  20. #include "TargetCondition.h"
  21. #include "Problem.h"
  22. #include "AdventureSpellMechanics.h"
  23. #include "BattleSpellMechanics.h"
  24. #include "effects/Effects.h"
  25. #include "effects/Registry.h"
  26. #include "effects/Damage.h"
  27. #include "effects/Timed.h"
  28. #include "CSpellHandler.h"
  29. #include "../CHeroHandler.h"//todo: remove
  30. #include "../IGameCallback.h"//todo: remove
  31. #include "../BattleFieldHandler.h"
  32. #include <vstd/RNG.h>
  33. VCMI_LIB_NAMESPACE_BEGIN
  34. namespace spells
  35. {
  36. static std::shared_ptr<TargetCondition> makeCondition(const CSpell * s)
  37. {
  38. auto res = std::make_shared<TargetCondition>();
  39. JsonDeserializer deser(nullptr, s->targetCondition);
  40. res->serializeJson(deser, TargetConditionItemFactory::getDefault());
  41. return res;
  42. }
  43. class CustomMechanicsFactory : public ISpellMechanicsFactory
  44. {
  45. public:
  46. std::unique_ptr<Mechanics> create(const IBattleCast * event) const override
  47. {
  48. auto * ret = new BattleSpellMechanics(event, effects, targetCondition);
  49. return std::unique_ptr<Mechanics>(ret);
  50. }
  51. protected:
  52. std::shared_ptr<effects::Effects> effects;
  53. CustomMechanicsFactory(const CSpell * s)
  54. : ISpellMechanicsFactory(s), effects(new effects::Effects)
  55. {
  56. targetCondition = makeCondition(s);
  57. }
  58. void loadEffects(const JsonNode & config, const int level)
  59. {
  60. JsonDeserializer deser(nullptr, config);
  61. effects->serializeJson(VLC->spellEffects(), deser, level);
  62. }
  63. private:
  64. std::shared_ptr<IReceptiveCheck> targetCondition;
  65. };
  66. class ConfigurableMechanicsFactory : public CustomMechanicsFactory
  67. {
  68. public:
  69. ConfigurableMechanicsFactory(const CSpell * s)
  70. : CustomMechanicsFactory(s)
  71. {
  72. for(int level = 0; level < GameConstants::SPELL_SCHOOL_LEVELS; level++)
  73. loadEffects(s->getLevelInfo(level).battleEffects, level);
  74. }
  75. };
  76. //to be used for spells configured with old format
  77. class FallbackMechanicsFactory : public CustomMechanicsFactory
  78. {
  79. public:
  80. FallbackMechanicsFactory(const CSpell * s)
  81. : CustomMechanicsFactory(s)
  82. {
  83. for(int level = 0; level < GameConstants::SPELL_SCHOOL_LEVELS; level++)
  84. {
  85. const CSpell::LevelInfo & levelInfo = s->getLevelInfo(level);
  86. assert(levelInfo.battleEffects.isNull());
  87. if(s->isOffensive())
  88. {
  89. //default constructed object should be enough
  90. effects->add("directDamage", std::make_shared<effects::Damage>(), level);
  91. }
  92. std::shared_ptr<effects::Effect> effect;
  93. if(!levelInfo.effects.empty())
  94. {
  95. auto * timed = new effects::Timed();
  96. timed->cumulative = false;
  97. timed->bonus = levelInfo.effects;
  98. effect.reset(timed);
  99. }
  100. if(!levelInfo.cumulativeEffects.empty())
  101. {
  102. auto * timed = new effects::Timed();
  103. timed->cumulative = true;
  104. timed->bonus = levelInfo.cumulativeEffects;
  105. effect.reset(timed);
  106. }
  107. if(effect)
  108. effects->add("timed", effect, level);
  109. }
  110. }
  111. };
  112. BattleCast::BattleCast(const CBattleInfoCallback * cb_, const Caster * caster_, const Mode mode_, const CSpell * spell_):
  113. spell(spell_),
  114. cb(cb_),
  115. caster(caster_),
  116. mode(mode_),
  117. smart(boost::logic::indeterminate),
  118. massive(boost::logic::indeterminate)
  119. {
  120. }
  121. BattleCast::BattleCast(const BattleCast & orig, const Caster * caster_)
  122. : spell(orig.spell),
  123. cb(orig.cb),
  124. caster(caster_),
  125. mode(Mode::MAGIC_MIRROR),
  126. magicSkillLevel(orig.magicSkillLevel),
  127. effectPower(orig.effectPower),
  128. effectDuration(orig.effectDuration),
  129. effectValue(orig.effectValue),
  130. smart(true),
  131. massive(false)
  132. {
  133. }
  134. BattleCast::~BattleCast() = default;
  135. const CSpell * BattleCast::getSpell() const
  136. {
  137. return spell;
  138. }
  139. Mode BattleCast::getMode() const
  140. {
  141. return mode;
  142. }
  143. const Caster * BattleCast::getCaster() const
  144. {
  145. return caster;
  146. }
  147. const CBattleInfoCallback * BattleCast::getBattle() const
  148. {
  149. return cb;
  150. }
  151. BattleCast::OptionalValue BattleCast::getSpellLevel() const
  152. {
  153. return magicSkillLevel;
  154. }
  155. BattleCast::OptionalValue BattleCast::getEffectPower() const
  156. {
  157. return effectPower;
  158. }
  159. BattleCast::OptionalValue BattleCast::getEffectDuration() const
  160. {
  161. return effectDuration;
  162. }
  163. BattleCast::OptionalValue64 BattleCast::getEffectValue() const
  164. {
  165. return effectValue;
  166. }
  167. boost::logic::tribool BattleCast::isSmart() const
  168. {
  169. return smart;
  170. }
  171. boost::logic::tribool BattleCast::isMassive() const
  172. {
  173. return massive;
  174. }
  175. void BattleCast::setSpellLevel(BattleCast::Value value)
  176. {
  177. magicSkillLevel = std::make_optional(value);
  178. }
  179. void BattleCast::setEffectPower(BattleCast::Value value)
  180. {
  181. effectPower = std::make_optional(value);
  182. }
  183. void BattleCast::setEffectDuration(BattleCast::Value value)
  184. {
  185. effectDuration = std::make_optional(value);
  186. }
  187. void BattleCast::setEffectValue(BattleCast::Value64 value)
  188. {
  189. effectValue = std::make_optional(value);
  190. }
  191. void BattleCast::applyEffects(ServerCallback * server, const Target & target, bool indirect, bool ignoreImmunity) const
  192. {
  193. auto m = spell->battleMechanics(this);
  194. m->applyEffects(server, target, indirect, ignoreImmunity);
  195. }
  196. void BattleCast::cast(ServerCallback * server, Target target)
  197. {
  198. if(target.empty())
  199. target.emplace_back();
  200. auto m = spell->battleMechanics(this);
  201. const battle::Unit * mainTarget = nullptr;
  202. if(target.front().unitValue)
  203. {
  204. mainTarget = target.front().unitValue;
  205. }
  206. else if(target.front().hexValue.isValid())
  207. {
  208. mainTarget = cb->battleGetUnitByPos(target.front().hexValue, true);
  209. }
  210. bool tryMagicMirror = (mainTarget != nullptr) && (mode == Mode::HERO || mode == Mode::CREATURE_ACTIVE);//TODO: recheck
  211. tryMagicMirror = tryMagicMirror && (mainTarget->unitOwner() != caster->getCasterOwner()) && !spell->isPositive();//TODO: recheck
  212. m->cast(server, target);
  213. //Magic Mirror effect
  214. if(tryMagicMirror)
  215. {
  216. const std::string magicMirrorCacheStr = "type_MAGIC_MIRROR";
  217. static const auto magicMirrorSelector = Selector::type()(BonusType::MAGIC_MIRROR);
  218. const int mirrorChance = mainTarget->valOfBonuses(magicMirrorSelector, magicMirrorCacheStr);
  219. if(server->getRNG()->nextInt(0, 99) < mirrorChance)
  220. {
  221. auto mirrorTargets = cb->battleGetUnitsIf([this](const battle::Unit * unit)
  222. {
  223. //Get all caster stacks. Magic mirror can reflect to immune creature (with no effect)
  224. return unit->unitOwner() == caster->getCasterOwner() && unit->isValidTarget(true);
  225. });
  226. if(!mirrorTargets.empty())
  227. {
  228. const auto * mirrorDestination = (*RandomGeneratorUtil::nextItem(mirrorTargets, *server->getRNG()));
  229. Target mirrorTarget;
  230. mirrorTarget.emplace_back(mirrorDestination);
  231. BattleCast mirror(*this, mainTarget);
  232. mirror.cast(server, mirrorTarget);
  233. }
  234. }
  235. }
  236. }
  237. void BattleCast::castEval(ServerCallback * server, Target target)
  238. {
  239. //TODO: make equivalent to normal cast
  240. if(target.empty())
  241. target.emplace_back();
  242. auto m = spell->battleMechanics(this);
  243. //TODO: reflection
  244. //TODO: random effects evaluation
  245. m->castEval(server, target);
  246. }
  247. bool BattleCast::castIfPossible(ServerCallback * server, Target target)
  248. {
  249. if(spell->canBeCast(cb, mode, caster))
  250. {
  251. cast(server, std::move(target));
  252. return true;
  253. }
  254. return false;
  255. }
  256. std::vector<Target> BattleCast::findPotentialTargets(bool fast) const
  257. {
  258. //TODO: for more than 2 destinations per target much more efficient algorithm is required
  259. auto m = spell->battleMechanics(this);
  260. auto targetTypes = m->getTargetTypes();
  261. if(targetTypes.empty() || targetTypes.size() > 2)
  262. {
  263. return std::vector<Target>();
  264. }
  265. else
  266. {
  267. std::vector<Target> previous;
  268. std::vector<Target> next;
  269. for(size_t index = 0; index < targetTypes.size(); index++)
  270. {
  271. std::swap(previous, next);
  272. next.clear();
  273. std::vector<Destination> destinations;
  274. if(previous.empty())
  275. {
  276. Target empty;
  277. destinations = m->getPossibleDestinations(index, targetTypes.at(index), empty, fast);
  278. for(auto & destination : destinations)
  279. {
  280. Target target;
  281. target.emplace_back(destination);
  282. next.push_back(target);
  283. }
  284. }
  285. else
  286. {
  287. for(const Target & current : previous)
  288. {
  289. destinations = m->getPossibleDestinations(index, targetTypes.at(index), current, fast);
  290. for(auto & destination : destinations)
  291. {
  292. Target target = current;
  293. target.emplace_back(destination);
  294. next.push_back(target);
  295. }
  296. }
  297. }
  298. if(next.empty())
  299. break;
  300. }
  301. return next;
  302. }
  303. }
  304. ///ISpellMechanicsFactory
  305. ISpellMechanicsFactory::ISpellMechanicsFactory(const CSpell * s)
  306. : spell(s)
  307. {
  308. }
  309. //must be instantiated in .cpp file for access to complete types of all member fields
  310. ISpellMechanicsFactory::~ISpellMechanicsFactory() = default;
  311. std::unique_ptr<ISpellMechanicsFactory> ISpellMechanicsFactory::get(const CSpell * s)
  312. {
  313. if(s->hasBattleEffects())
  314. return std::make_unique<ConfigurableMechanicsFactory>(s);
  315. else
  316. return std::make_unique<FallbackMechanicsFactory>(s);
  317. }
  318. ///Mechanics
  319. Mechanics::Mechanics()
  320. : caster(nullptr),
  321. casterSide(BattleSide::NONE)
  322. {
  323. }
  324. Mechanics::~Mechanics() = default;
  325. BaseMechanics::BaseMechanics(const IBattleCast * event):
  326. owner(event->getSpell()),
  327. mode(event->getMode()),
  328. smart(event->isSmart()),
  329. massive(event->isMassive()),
  330. cb(event->getBattle())
  331. {
  332. caster = event->getCaster();
  333. casterSide = cb->playerToSide(caster->getCasterOwner());
  334. {
  335. auto value = event->getSpellLevel();
  336. rangeLevel = value.value_or(caster->getSpellSchoolLevel(owner));
  337. vstd::abetween(rangeLevel, 0, 3);
  338. }
  339. {
  340. auto value = event->getSpellLevel();
  341. effectLevel = value.value_or(caster->getEffectLevel(owner));
  342. vstd::abetween(effectLevel, 0, 3);
  343. }
  344. {
  345. auto value = event->getEffectPower();
  346. effectPower = value.value_or(caster->getEffectPower(owner));
  347. vstd::amax(effectPower, 0);
  348. }
  349. {
  350. auto value = event->getEffectDuration();
  351. effectDuration = value.value_or(caster->getEnchantPower(owner));
  352. vstd::amax(effectDuration, 0); //???
  353. }
  354. {
  355. auto value = event->getEffectValue();
  356. auto casterValue = caster->getEffectValue(owner) ? caster->getEffectValue(owner) : owner->calculateRawEffectValue(effectLevel, effectPower, 1);
  357. effectValue = value.value_or(casterValue);
  358. vstd::amax(effectValue, 0);
  359. }
  360. }
  361. BaseMechanics::~BaseMechanics() = default;
  362. bool BaseMechanics::adaptGenericProblem(Problem & target) const
  363. {
  364. MetaString text;
  365. // %s recites the incantations but they seem to have no effect.
  366. text.appendLocalString(EMetaText::GENERAL_TXT, 541);
  367. assert(caster);
  368. caster->getCasterName(text);
  369. target.add(std::move(text), spells::Problem::NORMAL);
  370. return false;
  371. }
  372. bool BaseMechanics::adaptProblem(ESpellCastProblem source, Problem & target) const
  373. {
  374. if(source == ESpellCastProblem::OK)
  375. return true;
  376. switch(source)
  377. {
  378. case ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED:
  379. {
  380. MetaString text;
  381. //TODO: refactor
  382. const auto * hero = dynamic_cast<const CGHeroInstance *>(caster);
  383. if(!hero)
  384. return adaptGenericProblem(target);
  385. //Recanter's Cloak or similar effect. Try to retrieve bonus
  386. const auto b = hero->getFirstBonus(Selector::type()(BonusType::BLOCK_MAGIC_ABOVE));
  387. //TODO what about other values and non-artifact sources?
  388. if(b && b->val == 2 && b->source == BonusSource::ARTIFACT)
  389. {
  390. //The %s prevents %s from casting 3rd level or higher spells.
  391. text.appendLocalString(EMetaText::GENERAL_TXT, 536);
  392. text.replaceName(b->sid.as<ArtifactID>());
  393. caster->getCasterName(text);
  394. target.add(std::move(text), spells::Problem::NORMAL);
  395. }
  396. else if(b && b->source == BonusSource::TERRAIN_OVERLAY && VLC->battlefields()->getById(b->sid.as<BattleField>())->identifier == "cursed_ground")
  397. {
  398. text.appendLocalString(EMetaText::GENERAL_TXT, 537);
  399. target.add(std::move(text), spells::Problem::NORMAL);
  400. }
  401. else
  402. {
  403. return adaptGenericProblem(target);
  404. }
  405. }
  406. break;
  407. case ESpellCastProblem::WRONG_SPELL_TARGET:
  408. case ESpellCastProblem::STACK_IMMUNE_TO_SPELL:
  409. case ESpellCastProblem::NO_APPROPRIATE_TARGET:
  410. {
  411. MetaString text;
  412. text.appendLocalString(EMetaText::GENERAL_TXT, 185);
  413. target.add(std::move(text), spells::Problem::NORMAL);
  414. }
  415. break;
  416. case ESpellCastProblem::INVALID:
  417. {
  418. MetaString text;
  419. text.appendRawString("Internal error during check of spell cast.");
  420. target.add(std::move(text), spells::Problem::CRITICAL);
  421. }
  422. break;
  423. default:
  424. return adaptGenericProblem(target);
  425. }
  426. return false;
  427. }
  428. int32_t BaseMechanics::getSpellIndex() const
  429. {
  430. return getSpellId().toEnum();
  431. }
  432. SpellID BaseMechanics::getSpellId() const
  433. {
  434. return owner->getId();
  435. }
  436. std::string BaseMechanics::getSpellName() const
  437. {
  438. return owner->getNameTranslated();
  439. }
  440. int32_t BaseMechanics::getSpellLevel() const
  441. {
  442. return owner->getLevel();
  443. }
  444. bool BaseMechanics::isSmart() const
  445. {
  446. if(boost::logic::indeterminate(smart))
  447. {
  448. const CSpell::TargetInfo targetInfo(owner, getRangeLevel(), mode);
  449. return targetInfo.smart;
  450. }
  451. else
  452. {
  453. return (bool)smart;
  454. }
  455. }
  456. bool BaseMechanics::isMassive() const
  457. {
  458. if(boost::logic::indeterminate(massive))
  459. {
  460. const CSpell::TargetInfo targetInfo(owner, getRangeLevel(), mode);
  461. return targetInfo.massive;
  462. }
  463. else
  464. {
  465. return (bool)massive;
  466. }
  467. }
  468. bool BaseMechanics::requiresClearTiles() const
  469. {
  470. const CSpell::TargetInfo targetInfo(owner, getRangeLevel(), mode);
  471. return targetInfo.clearAffected;
  472. }
  473. bool BaseMechanics::alwaysHitFirstTarget() const
  474. {
  475. return mode == Mode::SPELL_LIKE_ATTACK;
  476. }
  477. bool BaseMechanics::isNegativeSpell() const
  478. {
  479. return owner->isNegative();
  480. }
  481. bool BaseMechanics::isPositiveSpell() const
  482. {
  483. return owner->isPositive();
  484. }
  485. bool BaseMechanics::isMagicalEffect() const
  486. {
  487. return owner->isMagical();
  488. }
  489. int64_t BaseMechanics::adjustEffectValue(const battle::Unit * target) const
  490. {
  491. return owner->adjustRawDamage(caster, target, getEffectValue());
  492. }
  493. int64_t BaseMechanics::applySpellBonus(int64_t value, const battle::Unit * target) const
  494. {
  495. return caster->getSpellBonus(owner, value, target);
  496. }
  497. int64_t BaseMechanics::applySpecificSpellBonus(int64_t value) const
  498. {
  499. return caster->getSpecificSpellBonus(owner, value);
  500. }
  501. int64_t BaseMechanics::calculateRawEffectValue(int32_t basePowerMultiplier, int32_t levelPowerMultiplier) const
  502. {
  503. return owner->calculateRawEffectValue(getEffectLevel(), basePowerMultiplier, levelPowerMultiplier);
  504. }
  505. bool BaseMechanics::ownerMatches(const battle::Unit * unit) const
  506. {
  507. return ownerMatches(unit, owner->getPositiveness());
  508. }
  509. bool BaseMechanics::ownerMatches(const battle::Unit * unit, const boost::logic::tribool positivness) const
  510. {
  511. return cb->battleMatchOwner(caster->getCasterOwner(), unit, positivness);
  512. }
  513. IBattleCast::Value BaseMechanics::getEffectLevel() const
  514. {
  515. return effectLevel;
  516. }
  517. IBattleCast::Value BaseMechanics::getRangeLevel() const
  518. {
  519. return rangeLevel;
  520. }
  521. IBattleCast::Value BaseMechanics::getEffectPower() const
  522. {
  523. return effectPower;
  524. }
  525. IBattleCast::Value BaseMechanics::getEffectDuration() const
  526. {
  527. return effectDuration;
  528. }
  529. IBattleCast::Value64 BaseMechanics::getEffectValue() const
  530. {
  531. return effectValue;
  532. }
  533. PlayerColor BaseMechanics::getCasterColor() const
  534. {
  535. return caster->getCasterOwner();
  536. }
  537. std::vector<AimType> BaseMechanics::getTargetTypes() const
  538. {
  539. std::vector<AimType> ret;
  540. detail::ProblemImpl ignored;
  541. if(canBeCast(ignored))
  542. {
  543. auto spellTargetType = owner->getTargetType();
  544. if(isMassive())
  545. spellTargetType = AimType::NO_TARGET;
  546. else if(spellTargetType == AimType::OBSTACLE)
  547. spellTargetType = AimType::LOCATION;
  548. ret.push_back(spellTargetType);
  549. }
  550. return ret;
  551. }
  552. const CreatureService * BaseMechanics::creatures() const
  553. {
  554. return VLC->creatures(); //todo: redirect
  555. }
  556. #if SCRIPTING_ENABLED
  557. const scripting::Service * BaseMechanics::scripts() const
  558. {
  559. return VLC->scripts(); //todo: redirect
  560. }
  561. #endif
  562. const Service * BaseMechanics::spells() const
  563. {
  564. return VLC->spells(); //todo: redirect
  565. }
  566. const CBattleInfoCallback * BaseMechanics::battle() const
  567. {
  568. return cb;
  569. }
  570. } //namespace spells
  571. ///IAdventureSpellMechanics
  572. IAdventureSpellMechanics::IAdventureSpellMechanics(const CSpell * s)
  573. : owner(s)
  574. {
  575. }
  576. std::unique_ptr<IAdventureSpellMechanics> IAdventureSpellMechanics::createMechanics(const CSpell * s)
  577. {
  578. switch(s->id.toEnum())
  579. {
  580. case SpellID::SUMMON_BOAT:
  581. return std::make_unique<SummonBoatMechanics>(s);
  582. case SpellID::SCUTTLE_BOAT:
  583. return std::make_unique<ScuttleBoatMechanics>(s);
  584. case SpellID::DIMENSION_DOOR:
  585. return std::make_unique<DimensionDoorMechanics>(s);
  586. case SpellID::FLY:
  587. case SpellID::WATER_WALK:
  588. case SpellID::VISIONS:
  589. case SpellID::DISGUISE:
  590. return std::make_unique<AdventureSpellMechanics>(s); //implemented using bonus system
  591. case SpellID::TOWN_PORTAL:
  592. return std::make_unique<TownPortalMechanics>(s);
  593. case SpellID::VIEW_EARTH:
  594. return std::make_unique<ViewEarthMechanics>(s);
  595. case SpellID::VIEW_AIR:
  596. return std::make_unique<ViewAirMechanics>(s);
  597. default:
  598. return s->isCombat() ? std::unique_ptr<IAdventureSpellMechanics>() : std::make_unique<AdventureSpellMechanics>(s);
  599. }
  600. }
  601. VCMI_LIB_NAMESPACE_END