CSpellHandler.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. /*
  2. * CSpellHandler.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 <cctype>
  12. #include "CSpellHandler.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../JsonNode.h"
  16. #include "../CModHandler.h"
  17. #include "../StringConstants.h"
  18. #include "../CStack.h"
  19. #include "../battle/BattleInfo.h"
  20. #include "../battle/CBattleInfoCallback.h"
  21. #include "../CGameState.h" //todo: remove
  22. #include "../NetPacks.h" //todo: remove
  23. #include "ISpellMechanics.h"
  24. namespace SpellConfig
  25. {
  26. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  27. static const SpellSchoolInfo SCHOOL[4] =
  28. {
  29. {
  30. ESpellSchool::AIR,
  31. Bonus::AIR_SPELL_DMG_PREMY,
  32. Bonus::AIR_IMMUNITY,
  33. "air",
  34. SecondarySkill::AIR_MAGIC,
  35. Bonus::AIR_SPELLS
  36. },
  37. {
  38. ESpellSchool::FIRE,
  39. Bonus::FIRE_SPELL_DMG_PREMY,
  40. Bonus::FIRE_IMMUNITY,
  41. "fire",
  42. SecondarySkill::FIRE_MAGIC,
  43. Bonus::FIRE_SPELLS
  44. },
  45. {
  46. ESpellSchool::WATER,
  47. Bonus::WATER_SPELL_DMG_PREMY,
  48. Bonus::WATER_IMMUNITY,
  49. "water",
  50. SecondarySkill::WATER_MAGIC,
  51. Bonus::WATER_SPELLS
  52. },
  53. {
  54. ESpellSchool::EARTH,
  55. Bonus::EARTH_SPELL_DMG_PREMY,
  56. Bonus::EARTH_IMMUNITY,
  57. "earth",
  58. SecondarySkill::EARTH_MAGIC,
  59. Bonus::EARTH_SPELLS
  60. }
  61. };
  62. //order as described in http://bugs.vcmi.eu/view.php?id=91
  63. static const ESpellSchool SCHOOL_ORDER[4] =
  64. {
  65. ESpellSchool::AIR, //=0
  66. ESpellSchool::FIRE, //=1
  67. ESpellSchool::EARTH,//=3(!)
  68. ESpellSchool::WATER //=2(!)
  69. };
  70. }
  71. ///CSpell::LevelInfo
  72. CSpell::LevelInfo::LevelInfo()
  73. :description(""),cost(0),power(0),AIValue(0),smartTarget(true), clearTarget(false), clearAffected(false), range("0")
  74. {
  75. }
  76. CSpell::LevelInfo::~LevelInfo()
  77. {
  78. }
  79. ///CSpell
  80. CSpell::CSpell():
  81. id(SpellID::NONE), level(0),
  82. power(0),
  83. combatSpell(false), creatureAbility(false),
  84. positiveness(ESpellPositiveness::NEUTRAL),
  85. defaultProbability(0),
  86. isRising(false), isDamage(false), isOffensive(false), isSpecial(true),
  87. targetType(ETargetType::NO_TARGET),
  88. mechanics(),
  89. adventureMechanics()
  90. {
  91. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  92. }
  93. CSpell::~CSpell()
  94. {
  95. }
  96. void CSpell::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  97. {
  98. mechanics->applyBattle(battle, packet);
  99. }
  100. bool CSpell::adventureCast(const SpellCastEnvironment * env, const AdventureSpellCastParameters & parameters) const
  101. {
  102. assert(env);
  103. if(!adventureMechanics.get())
  104. {
  105. env->complain("Invalid adventure spell cast attempt!");
  106. return false;
  107. }
  108. return adventureMechanics->adventureCast(env, parameters);
  109. }
  110. void CSpell::battleCast(const SpellCastEnvironment * env, const BattleSpellCastParameters & parameters) const
  111. {
  112. assert(env);
  113. mechanics->battleCast(env, parameters);
  114. }
  115. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  116. {
  117. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  118. {
  119. logGlobal->error("CSpell::getLevelInfo invalid school level %d", level);
  120. throw new std::runtime_error("Invalid school level");
  121. }
  122. return levels.at(level);
  123. }
  124. ui32 CSpell::calculateDamage(const ISpellCaster * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  125. {
  126. //check if spell really does damage - if not, return 0
  127. if(!isDamageSpell())
  128. return 0;
  129. return adjustRawDamage(caster, affectedCreature, calculateRawEffectValue(spellSchoolLevel, usedSpellPower));
  130. }
  131. ESpellCastProblem::ESpellCastProblem CSpell::canBeCast(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster) const
  132. {
  133. ESpellCastProblem::ESpellCastProblem genProblem = cb->battleCanCastSpell(caster, mode);
  134. if(genProblem != ESpellCastProblem::OK)
  135. return genProblem;
  136. switch(mode)
  137. {
  138. case ECastingMode::HERO_CASTING:
  139. {
  140. const CGHeroInstance * castingHero = dynamic_cast<const CGHeroInstance *>(caster);//todo: unify hero|creature spell cost
  141. if(!castingHero)
  142. {
  143. logGlobal->debug("CSpell::canBeCast: invalid caster");
  144. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  145. }
  146. if(!castingHero->getArt(ArtifactPosition::SPELLBOOK))
  147. return ESpellCastProblem::NO_SPELLBOOK;
  148. if(!castingHero->canCastThisSpell(this))
  149. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  150. if(castingHero->mana < cb->battleGetSpellCost(this, castingHero)) //not enough mana
  151. return ESpellCastProblem::NOT_ENOUGH_MANA;
  152. }
  153. break;
  154. }
  155. if(!isCombatSpell())
  156. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  157. const PlayerColor player = caster->getOwner();
  158. const auto side = cb->playerToSide(player);
  159. if(!side)
  160. return ESpellCastProblem::INVALID;
  161. //effect like Recanter's Cloak. Blocks also passive casting.
  162. //TODO: check creature abilities to block
  163. //TODO: check any possible caster
  164. if(cb->battleMaxSpellLevel(side.get()) < level)
  165. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  166. const ESpellCastProblem::ESpellCastProblem specificProblem = mechanics->canBeCast(cb, mode, caster);
  167. if(specificProblem != ESpellCastProblem::OK)
  168. return specificProblem;
  169. //check for creature target existence
  170. //allow to cast spell if there is at least one smart target
  171. if(mechanics->requiresCreatureTarget())
  172. {
  173. switch(mode)
  174. {
  175. case ECastingMode::HERO_CASTING:
  176. case ECastingMode::CREATURE_ACTIVE_CASTING:
  177. case ECastingMode::ENCHANTER_CASTING:
  178. case ECastingMode::PASSIVE_CASTING:
  179. {
  180. TargetInfo tinfo(this, caster->getSpellSchoolLevel(this), mode);
  181. bool targetExists = false;
  182. for(const CStack * stack : cb->battleGetAllStacks())
  183. {
  184. const bool immune = !(stack->isValidTarget(!tinfo.onlyAlive) && ESpellCastProblem::OK == isImmuneByStack(caster, stack));
  185. const bool ownerMatches = cb->battleMatchOwner(caster->getOwner(), stack, getPositiveness());
  186. targetExists = !immune && ownerMatches;
  187. if(targetExists)
  188. break;
  189. }
  190. if(!targetExists)
  191. {
  192. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  193. }
  194. }
  195. break;
  196. }
  197. }
  198. return ESpellCastProblem::OK;
  199. }
  200. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  201. {
  202. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  203. }
  204. std::vector<const CStack *> CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster, int spellLvl, BattleHex destination) const
  205. {
  206. return mechanics->getAffectedStacks(cb, mode, caster, spellLvl, destination);
  207. }
  208. CSpell::ETargetType CSpell::getTargetType() const
  209. {
  210. return targetType;
  211. }
  212. void CSpell::forEachSchool(const std::function<void(const SpellSchoolInfo &, bool &)>& cb) const
  213. {
  214. bool stop = false;
  215. for(ESpellSchool iter : SpellConfig::SCHOOL_ORDER)
  216. {
  217. const SpellSchoolInfo & cnf = SpellConfig::SCHOOL[(ui8)iter];
  218. if(school.at(cnf.id))
  219. {
  220. cb(cnf, stop);
  221. if(stop)
  222. break;
  223. }
  224. }
  225. }
  226. bool CSpell::isCombatSpell() const
  227. {
  228. return combatSpell;
  229. }
  230. bool CSpell::isAdventureSpell() const
  231. {
  232. return !combatSpell;
  233. }
  234. bool CSpell::isCreatureAbility() const
  235. {
  236. return creatureAbility;
  237. }
  238. bool CSpell::isPositive() const
  239. {
  240. return positiveness == POSITIVE;
  241. }
  242. bool CSpell::isNegative() const
  243. {
  244. return positiveness == NEGATIVE;
  245. }
  246. bool CSpell::isNeutral() const
  247. {
  248. return positiveness == NEUTRAL;
  249. }
  250. boost::logic::tribool CSpell::getPositiveness() const
  251. {
  252. switch (positiveness)
  253. {
  254. case CSpell::POSITIVE:
  255. return true;
  256. case CSpell::NEGATIVE:
  257. return false;
  258. default:
  259. return boost::logic::indeterminate;
  260. }
  261. }
  262. bool CSpell::isRisingSpell() const
  263. {
  264. return isRising;
  265. }
  266. bool CSpell::isDamageSpell() const
  267. {
  268. return isDamage;
  269. }
  270. bool CSpell::isOffensiveSpell() const
  271. {
  272. return isOffensive;
  273. }
  274. bool CSpell::isSpecialSpell() const
  275. {
  276. return isSpecial;
  277. }
  278. bool CSpell::hasEffects() const
  279. {
  280. return !levels[0].effects.empty() || !levels[0].cumulativeEffects.empty();
  281. }
  282. const std::string & CSpell::getIconImmune() const
  283. {
  284. return iconImmune;
  285. }
  286. const std::string & CSpell::getCastSound() const
  287. {
  288. return castSound;
  289. }
  290. si32 CSpell::getCost(const int skillLevel) const
  291. {
  292. return getLevelInfo(skillLevel).cost;
  293. }
  294. si32 CSpell::getPower(const int skillLevel) const
  295. {
  296. return getLevelInfo(skillLevel).power;
  297. }
  298. si32 CSpell::getProbability(const TFaction factionId) const
  299. {
  300. if(!vstd::contains(probabilities,factionId))
  301. {
  302. return defaultProbability;
  303. }
  304. return probabilities.at(factionId);
  305. }
  306. void CSpell::getEffects(std::vector<Bonus> & lst, const int level, const bool cumulative, const si32 duration, boost::optional<si32 *> maxDuration) const
  307. {
  308. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  309. {
  310. logGlobal->error("invalid school level %d", level);
  311. return;
  312. }
  313. const auto & levelObject = levels.at(level);
  314. if(levelObject.effects.empty() && levelObject.cumulativeEffects.empty())
  315. {
  316. logGlobal->error("This spell (%s) has no effects for level %d", name, level);
  317. return;
  318. }
  319. const auto & effects = cumulative ? levelObject.cumulativeEffects : levelObject.effects;
  320. lst.reserve(lst.size() + effects.size());
  321. for(const auto b : effects)
  322. {
  323. Bonus nb(*b);
  324. //use configured duration if present
  325. if(nb.turnsRemain == 0)
  326. nb.turnsRemain = duration;
  327. if(maxDuration)
  328. vstd::amax(*(maxDuration.get()), nb.turnsRemain);
  329. lst.push_back(nb);
  330. }
  331. }
  332. ESpellCastProblem::ESpellCastProblem CSpell::canBeCastAt(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster, BattleHex destination) const
  333. {
  334. ESpellCastProblem::ESpellCastProblem problem = canBeCast(cb, mode, caster);
  335. if(problem != ESpellCastProblem::OK)
  336. return problem;
  337. return mechanics->canBeCastAt(cb, mode, caster, destination);
  338. }
  339. int CSpell::adjustRawDamage(const ISpellCaster * caster, const CStack * affectedCreature, int rawDamage) const
  340. {
  341. int ret = rawDamage;
  342. //affected creature-specific part
  343. if(nullptr != affectedCreature)
  344. {
  345. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  346. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  347. {
  348. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  349. {
  350. ret *= 100 - affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  351. ret /= 100;
  352. stop = true;//only bonus from one school is used
  353. }
  354. });
  355. CSelector selector = Selector::type(Bonus::SPELL_DAMAGE_REDUCTION).And(Selector::subtype(-1));
  356. //general spell dmg reduction
  357. if(affectedCreature->hasBonus(selector))
  358. {
  359. ret *= 100 - affectedCreature->valOfBonuses(selector);
  360. ret /= 100;
  361. }
  362. //dmg increasing
  363. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  364. {
  365. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  366. ret /= 100;
  367. }
  368. }
  369. if(caster != nullptr)
  370. ret = caster->getSpellBonus(this, ret, affectedCreature);
  371. return ret;
  372. }
  373. int CSpell::calculateRawEffectValue(int effectLevel, int effectPower) const
  374. {
  375. return effectPower * power + getPower(effectLevel);
  376. }
  377. ESpellCastProblem::ESpellCastProblem CSpell::internalIsImmune(const ISpellCaster * caster, const CStack *obj) const
  378. {
  379. //todo: use new bonus API
  380. //1. Check absolute limiters
  381. for(auto b : absoluteLimiters)
  382. {
  383. if (!obj->hasBonusOfType(b))
  384. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  385. }
  386. //2. Check absolute immunities
  387. for(auto b : absoluteImmunities)
  388. {
  389. if (obj->hasBonusOfType(b))
  390. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  391. }
  392. {
  393. //spell-based spell immunity (only ANTIMAGIC in OH3) is treated as absolute
  394. std::stringstream cachingStr;
  395. cachingStr << "type_" << Bonus::LEVEL_SPELL_IMMUNITY << "source_" << Bonus::SPELL_EFFECT;
  396. TBonusListPtr levelImmunitiesFromSpell = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY).And(Selector::sourceType(Bonus::SPELL_EFFECT)), cachingStr.str());
  397. if(levelImmunitiesFromSpell->size() > 0 && levelImmunitiesFromSpell->totalValue() >= level && level)
  398. {
  399. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  400. }
  401. }
  402. {
  403. //SPELL_IMMUNITY absolute case
  404. std::stringstream cachingStr;
  405. cachingStr << "type_" << Bonus::SPELL_IMMUNITY << "subtype_" << id.toEnum() << "addInfo_1";
  406. if(obj->hasBonus(Selector::typeSubtypeInfo(Bonus::SPELL_IMMUNITY, id.toEnum(), 1), cachingStr.str()))
  407. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  408. }
  409. //check receptivity
  410. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  411. return ESpellCastProblem::OK;
  412. //3. Check negation
  413. //Orb of vulnerability
  414. //FIXME: Orb of vulnerability mechanics is not such trivial (issue 1791)
  415. const bool battleWideNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 0);
  416. const bool heroNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 1);
  417. //anyone can cast on artifact holder`s stacks
  418. if(heroNegation)
  419. return ESpellCastProblem::NOT_DECIDED;
  420. //this stack is from other player
  421. //todo: check that caster is always present (not trivial is this case)
  422. //todo: NEGATE_ALL_NATURAL_IMMUNITIES special cases: dispell, chain lightning
  423. else if(battleWideNegation && caster)
  424. {
  425. if(obj->owner != caster->getOwner())
  426. return ESpellCastProblem::NOT_DECIDED;
  427. }
  428. //4. Check negatable limit
  429. for(auto b : limiters)
  430. {
  431. if (!obj->hasBonusOfType(b))
  432. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  433. }
  434. //5. Check negatable immunities
  435. for(auto b : immunities)
  436. {
  437. if (obj->hasBonusOfType(b))
  438. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  439. }
  440. //6. Check elemental immunities
  441. ESpellCastProblem::ESpellCastProblem tmp = ESpellCastProblem::NOT_DECIDED;
  442. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  443. {
  444. auto element = cnf.immunityBonus;
  445. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  446. {
  447. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  448. stop = true;
  449. }
  450. else if(!isPositive()) //negative or indifferent
  451. {
  452. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  453. {
  454. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  455. stop = true;
  456. }
  457. }
  458. });
  459. if(tmp != ESpellCastProblem::NOT_DECIDED)
  460. return tmp;
  461. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  462. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  463. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  464. {
  465. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  466. }
  467. return ESpellCastProblem::NOT_DECIDED;
  468. }
  469. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const ISpellCaster * caster, const CStack * obj) const
  470. {
  471. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  472. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  473. return immuneResult;
  474. return ESpellCastProblem::OK;
  475. }
  476. void CSpell::setIsOffensive(const bool val)
  477. {
  478. isOffensive = val;
  479. if(val)
  480. {
  481. positiveness = CSpell::NEGATIVE;
  482. isDamage = true;
  483. }
  484. }
  485. void CSpell::setIsRising(const bool val)
  486. {
  487. isRising = val;
  488. if(val)
  489. {
  490. positiveness = CSpell::POSITIVE;
  491. }
  492. }
  493. void CSpell::setup()
  494. {
  495. setupMechanics();
  496. }
  497. void CSpell::setupMechanics()
  498. {
  499. mechanics = ISpellMechanics::createMechanics(this);
  500. adventureMechanics = IAdventureSpellMechanics::createMechanics(this);
  501. }
  502. ///CSpell::AnimationInfo
  503. CSpell::AnimationItem::AnimationItem()
  504. :resourceName(""),verticalPosition(VerticalPosition::TOP),pause(0)
  505. {
  506. }
  507. ///CSpell::AnimationInfo
  508. CSpell::AnimationInfo::AnimationInfo()
  509. {
  510. }
  511. CSpell::AnimationInfo::~AnimationInfo()
  512. {
  513. }
  514. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  515. {
  516. std::string res;
  517. double maximum = 0.0;
  518. for(const auto & info : projectile)
  519. {
  520. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  521. {
  522. maximum = info.minimumAngle;
  523. res = info.resourceName;
  524. }
  525. }
  526. return res;
  527. }
  528. ///CSpell::TargetInfo
  529. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  530. {
  531. init(spell, level);
  532. }
  533. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  534. {
  535. init(spell, level);
  536. if(mode == ECastingMode::ENCHANTER_CASTING)
  537. {
  538. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  539. massive = true;
  540. }
  541. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  542. {
  543. alwaysHitDirectly = true;
  544. }
  545. else if(mode == ECastingMode::CREATURE_ACTIVE_CASTING)
  546. {
  547. massive = false;//FIXME: find better solution for Commander spells
  548. }
  549. }
  550. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  551. {
  552. auto & levelInfo = spell->getLevelInfo(level);
  553. type = spell->getTargetType();
  554. smart = levelInfo.smartTarget;
  555. massive = levelInfo.range == "X";
  556. onlyAlive = !spell->isRisingSpell();
  557. alwaysHitDirectly = false;
  558. clearAffected = levelInfo.clearAffected;
  559. clearTarget = levelInfo.clearTarget;
  560. }
  561. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  562. {
  563. int3 diff = pos - center;
  564. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  565. return true;
  566. else
  567. return false;
  568. }
  569. ///CSpellHandler
  570. CSpellHandler::CSpellHandler()
  571. {
  572. }
  573. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  574. {
  575. using namespace SpellConfig;
  576. std::vector<JsonNode> legacyData;
  577. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  578. auto readSchool = [&](JsonMap & schools, const std::string & name)
  579. {
  580. if (parser.readString() == "x")
  581. {
  582. schools[name].Bool() = true;
  583. }
  584. };
  585. auto read = [&,this](bool combat, bool ability)
  586. {
  587. do
  588. {
  589. JsonNode lineNode(JsonNode::DATA_STRUCT);
  590. const si32 id = legacyData.size();
  591. lineNode["index"].Float() = id;
  592. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  593. lineNode["name"].String() = parser.readString();
  594. parser.readString(); //ignored unused abbreviated name
  595. lineNode["level"].Float() = parser.readNumber();
  596. auto& schools = lineNode["school"].Struct();
  597. readSchool(schools, "earth");
  598. readSchool(schools, "water");
  599. readSchool(schools, "fire");
  600. readSchool(schools, "air");
  601. auto& levels = lineNode["levels"].Struct();
  602. auto getLevel = [&](const size_t idx)->JsonMap&
  603. {
  604. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  605. return levels[LEVEL_NAMES[idx]].Struct();
  606. };
  607. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  608. lineNode["power"].Float() = parser.readNumber();
  609. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  610. auto& chances = lineNode["gainChance"].Struct();
  611. for(size_t i = 0; i < GameConstants::F_NUMBER; i++){
  612. chances[ETownType::names[i]].Float() = parser.readNumber();
  613. }
  614. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  615. std::vector<std::string> descriptions;
  616. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  617. descriptions.push_back(parser.readString());
  618. parser.readString(); //ignore attributes. All data present in JSON
  619. //save parsed level specific data
  620. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  621. {
  622. auto& level = getLevel(i);
  623. level["description"].String() = descriptions[i];
  624. level["cost"].Float() = costs[i];
  625. level["power"].Float() = powers[i];
  626. level["aiValue"].Float() = AIVals[i];
  627. }
  628. legacyData.push_back(lineNode);
  629. }
  630. while (parser.endLine() && !parser.isNextEntryEmpty());
  631. };
  632. auto skip = [&](int cnt)
  633. {
  634. for(int i=0; i<cnt; i++)
  635. parser.endLine();
  636. };
  637. skip(5);// header
  638. read(false,false); //read adventure map spells
  639. skip(3);
  640. read(true,false); //read battle spells
  641. skip(3);
  642. read(true,true);//read creature abilities
  643. //TODO: maybe move to config
  644. //clone Acid Breath attributes for Acid Breath damage effect
  645. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  646. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  647. legacyData.push_back(temp);
  648. objects.resize(legacyData.size());
  649. return legacyData;
  650. }
  651. const std::string CSpellHandler::getTypeName() const
  652. {
  653. return "spell";
  654. }
  655. CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & identifier)
  656. {
  657. using namespace SpellConfig;
  658. CSpell * spell = new CSpell();
  659. spell->identifier = identifier;
  660. const auto type = json["type"].String();
  661. if(type == "ability")
  662. {
  663. spell->creatureAbility = true;
  664. spell->combatSpell = true;
  665. }
  666. else
  667. {
  668. spell->creatureAbility = false;
  669. spell->combatSpell = type == "combat";
  670. }
  671. spell->name = json["name"].String();
  672. logMod->trace("%s: loading spell %s", __FUNCTION__, spell->name);
  673. const auto schoolNames = json["school"];
  674. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  675. {
  676. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  677. }
  678. spell->level = json["level"].Float();
  679. spell->power = json["power"].Float();
  680. spell->defaultProbability = json["defaultGainChance"].Float();
  681. for(const auto & node : json["gainChance"].Struct())
  682. {
  683. const int chance = node.second.Float();
  684. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  685. {
  686. spell->probabilities[factionID] = chance;
  687. });
  688. }
  689. auto targetType = json["targetType"].String();
  690. if(targetType == "NO_TARGET")
  691. spell->targetType = CSpell::NO_TARGET;
  692. else if(targetType == "CREATURE")
  693. spell->targetType = CSpell::CREATURE;
  694. else if(targetType == "OBSTACLE")
  695. spell->targetType = CSpell::OBSTACLE;
  696. else if(targetType == "LOCATION")
  697. spell->targetType = CSpell::LOCATION;
  698. else
  699. logMod->warn("Spell %s: target type %s - assumed NO_TARGET.", spell->name, (targetType.empty() ? "empty" : "unknown ("+targetType+")"));
  700. for(const auto & counteredSpell: json["counters"].Struct())
  701. if (counteredSpell.second.Bool())
  702. {
  703. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  704. {
  705. spell->counteredSpells.push_back(SpellID(id));
  706. });
  707. }
  708. //TODO: more error checking - f.e. conflicting flags
  709. const auto flags = json["flags"];
  710. //by default all flags are set to false in constructor
  711. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  712. if(flags["offensive"].Bool())
  713. {
  714. spell->setIsOffensive(true);
  715. }
  716. if(flags["rising"].Bool())
  717. {
  718. spell->setIsRising(true);
  719. }
  720. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  721. if(flags["indifferent"].Bool())
  722. {
  723. spell->positiveness = CSpell::NEUTRAL;
  724. }
  725. else if(flags["negative"].Bool())
  726. {
  727. spell->positiveness = CSpell::NEGATIVE;
  728. }
  729. else if(flags["positive"].Bool())
  730. {
  731. spell->positiveness = CSpell::POSITIVE;
  732. }
  733. else if(!implicitPositiveness)
  734. {
  735. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  736. logMod->error("Spell %s: no positiveness specified, assumed NEUTRAL.", spell->name);
  737. }
  738. spell->isSpecial = flags["special"].Bool();
  739. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  740. {
  741. auto it = bonusNameMap.find(name);
  742. if(it == bonusNameMap.end())
  743. {
  744. logMod->error("Spell %s: invalid bonus name %s", spell->name, name);
  745. }
  746. else
  747. {
  748. vec.push_back((Bonus::BonusType)it->second);
  749. }
  750. };
  751. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  752. {
  753. for(auto bonusData: json[name].Struct())
  754. {
  755. const std::string bonusId = bonusData.first;
  756. const bool flag = bonusData.second.Bool();
  757. if(flag)
  758. findBonus(bonusId, vec);
  759. }
  760. };
  761. readBonusStruct("immunity", spell->immunities);
  762. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  763. readBonusStruct("limit", spell->limiters);
  764. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  765. const JsonNode & graphicsNode = json["graphics"];
  766. spell->iconImmune = graphicsNode["iconImmune"].String();
  767. spell->iconBook = graphicsNode["iconBook"].String();
  768. spell->iconEffect = graphicsNode["iconEffect"].String();
  769. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  770. spell->iconScroll = graphicsNode["iconScroll"].String();
  771. const JsonNode & animationNode = json["animation"];
  772. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  773. {
  774. auto queueNode = animationNode[jsonName].Vector();
  775. for(const JsonNode & item : queueNode)
  776. {
  777. CSpell::TAnimation newItem;
  778. if(item.getType() == JsonNode::DATA_STRING)
  779. newItem.resourceName = item.String();
  780. else if(item.getType() == JsonNode::DATA_STRUCT)
  781. {
  782. newItem.resourceName = item["defName"].String();
  783. auto vPosStr = item["verticalPosition"].String();
  784. if("bottom" == vPosStr)
  785. newItem.verticalPosition = VerticalPosition::BOTTOM;
  786. }
  787. else if(item.isNumber())
  788. {
  789. newItem.pause = item.Float();
  790. }
  791. q.push_back(newItem);
  792. }
  793. };
  794. loadAnimationQueue("affect", spell->animationInfo.affect);
  795. loadAnimationQueue("cast", spell->animationInfo.cast);
  796. loadAnimationQueue("hit", spell->animationInfo.hit);
  797. const JsonVector & projectile = animationNode["projectile"].Vector();
  798. for(const JsonNode & item : projectile)
  799. {
  800. CSpell::ProjectileInfo info;
  801. info.resourceName = item["defName"].String();
  802. info.minimumAngle = item["minimumAngle"].Float();
  803. spell->animationInfo.projectile.push_back(info);
  804. }
  805. const JsonNode & soundsNode = json["sounds"];
  806. spell->castSound = soundsNode["cast"].String();
  807. //load level attributes
  808. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  809. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  810. {
  811. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  812. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  813. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  814. levelObject.description = levelNode["description"].String();
  815. levelObject.cost = levelNode["cost"].Float();
  816. levelObject.AIValue = levelNode["aiValue"].Float();
  817. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  818. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  819. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  820. levelObject.range = levelNode["range"].String();
  821. for(const auto & elem : levelNode["effects"].Struct())
  822. {
  823. const JsonNode & bonusNode = elem.second;
  824. auto b = JsonUtils::parseBonus(bonusNode);
  825. const bool usePowerAsValue = bonusNode["val"].isNull();
  826. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  827. //b->sid = spell->id; //for all
  828. b->source = Bonus::SPELL_EFFECT;//for all
  829. if(usePowerAsValue)
  830. b->val = levelPower;
  831. levelObject.effects.push_back(b);
  832. }
  833. for(const auto & elem : levelNode["cumulativeEffects"].Struct())
  834. {
  835. const JsonNode & bonusNode = elem.second;
  836. auto b = JsonUtils::parseBonus(bonusNode);
  837. const bool usePowerAsValue = bonusNode["val"].isNull();
  838. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  839. //b->sid = spell->id; //for all
  840. b->source = Bonus::SPELL_EFFECT;//for all
  841. if(usePowerAsValue)
  842. b->val = levelPower;
  843. levelObject.cumulativeEffects.push_back(b);
  844. }
  845. }
  846. return spell;
  847. }
  848. void CSpellHandler::afterLoadFinalization()
  849. {
  850. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  851. for(auto spell: objects)
  852. {
  853. for(auto & level: spell->levels)
  854. {
  855. for(auto & bonus: level.effects)
  856. bonus->sid = spell->id;
  857. for(auto & bonus: level.cumulativeEffects)
  858. bonus->sid = spell->id;
  859. }
  860. spell->setup();
  861. }
  862. }
  863. void CSpellHandler::beforeValidate(JsonNode & object)
  864. {
  865. //handle "base" level info
  866. JsonNode & levels = object["levels"];
  867. JsonNode & base = levels["base"];
  868. auto inheritNode = [&](const std::string & name){
  869. JsonUtils::inherit(levels[name],base);
  870. };
  871. inheritNode("none");
  872. inheritNode("basic");
  873. inheritNode("advanced");
  874. inheritNode("expert");
  875. }
  876. CSpellHandler::~CSpellHandler()
  877. {
  878. }
  879. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  880. {
  881. std::vector<bool> allowedSpells;
  882. allowedSpells.reserve(objects.size());
  883. for(const CSpell * s : objects)
  884. {
  885. allowedSpells.push_back( !(s->isSpecialSpell() || s->isCreatureAbility()));
  886. }
  887. return allowedSpells;
  888. }
  889. si32 CSpellHandler::decodeSpell(const std::string& identifier)
  890. {
  891. auto rawId = VLC->modh->identifiers.getIdentifier("core", "spell", identifier);
  892. if(rawId)
  893. return rawId.get();
  894. else
  895. return -1;
  896. }
  897. std::string CSpellHandler::encodeSpell(const si32 index)
  898. {
  899. return VLC->spellh->objects[index]->identifier;
  900. }