CSpellHandler.cpp 27 KB

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