CSpellHandler.cpp 26 KB

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