CSpellHandler.cpp 26 KB

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