CSpellHandler.cpp 27 KB

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