CSpellHandler.cpp 28 KB

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