CSpellHandler.cpp 26 KB

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