CSpellHandler.cpp 27 KB

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