CSpellHandler.cpp 25 KB

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