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