CSpellHandler.cpp 28 KB

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