CSpellHandler.cpp 25 KB

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