CSpellHandler.cpp 26 KB

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