CSpellHandler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. #include "StdInc.h"
  2. #include "CSpellHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "JsonNode.h"
  6. #include <cctype>
  7. #include "BattleHex.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. #include "mapObjects/CGHeroInstance.h"
  11. #include "BattleState.h"
  12. /*
  13. * CSpellHandler.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. namespace SpellConfig
  22. {
  23. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  24. }
  25. namespace SRSLPraserHelpers
  26. {
  27. static int XYToHex(int x, int y)
  28. {
  29. return x + 17 * y;
  30. }
  31. static int XYToHex(std::pair<int, int> xy)
  32. {
  33. return XYToHex(xy.first, xy.second);
  34. }
  35. static int hexToY(int battleFieldPosition)
  36. {
  37. return battleFieldPosition/17;
  38. }
  39. static int hexToX(int battleFieldPosition)
  40. {
  41. int pos = battleFieldPosition - hexToY(battleFieldPosition) * 17;
  42. return pos;
  43. }
  44. static std::pair<int, int> hexToPair(int battleFieldPosition)
  45. {
  46. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  47. }
  48. //moves hex by one hex in given direction
  49. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  50. static std::pair<int, int> gotoDir(int x, int y, int direction)
  51. {
  52. switch(direction)
  53. {
  54. case 0: //top left
  55. return std::make_pair((y%2) ? x-1 : x, y-1);
  56. case 1: //top right
  57. return std::make_pair((y%2) ? x : x+1, y-1);
  58. case 2: //right
  59. return std::make_pair(x+1, y);
  60. case 3: //right bottom
  61. return std::make_pair((y%2) ? x : x+1, y+1);
  62. case 4: //left bottom
  63. return std::make_pair((y%2) ? x-1 : x, y+1);
  64. case 5: //left
  65. return std::make_pair(x-1, y);
  66. default:
  67. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  68. }
  69. }
  70. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  71. {
  72. return gotoDir(xy.first, xy.second, direction);
  73. }
  74. static bool isGoodHex(std::pair<int, int> xy)
  75. {
  76. return xy.first >=0 && xy.first < 17 && xy.second >= 0 && xy.second < 11;
  77. }
  78. //helper function for std::set<ui16> CSpell::rangeInHexes(unsigned int centralHex, ui8 schoolLvl ) const
  79. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  80. {
  81. std::set<ui16> ret;
  82. if(low == 0)
  83. {
  84. ret.insert(center);
  85. }
  86. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  87. for(auto & elem : mainPointForLayer)
  88. elem = hexToPair(center);
  89. for(int it=1; it<=high; ++it) //it - distance to the center
  90. {
  91. for(int b=0; b<6; ++b)
  92. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  93. if(it>=low)
  94. {
  95. std::pair<int, int> curHex;
  96. //adding lines (A-b, B-c, C-d, etc)
  97. for(int v=0; v<6; ++v)
  98. {
  99. curHex = mainPointForLayer[v];
  100. for(int h=0; h<it; ++h)
  101. {
  102. if(isGoodHex(curHex))
  103. ret.insert(XYToHex(curHex));
  104. curHex = gotoDir(curHex, (v+2)%6);
  105. }
  106. }
  107. } //if(it>=low)
  108. }
  109. return ret;
  110. }
  111. }
  112. ///CSpellMechanics
  113. CSpellMechanics::CSpellMechanics(CSpell * s):
  114. owner(s)
  115. {
  116. }
  117. CSpellMechanics::~CSpellMechanics()
  118. {
  119. }
  120. ESpellCastProblem::ESpellCastProblem CSpellMechanics::isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj)
  121. {
  122. //by default use general algorithm
  123. return owner->isImmuneBy(obj);
  124. }
  125. namespace
  126. {
  127. class CloneMechnics: public CSpellMechanics
  128. {
  129. public:
  130. CloneMechnics(CSpell * s): CSpellMechanics(s){};
  131. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  132. };
  133. class DispellHelpfulMechanics: public CSpellMechanics
  134. {
  135. public:
  136. DispellHelpfulMechanics(CSpell * s): CSpellMechanics(s){};
  137. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  138. };
  139. ///all rising spells
  140. class RisingSpellMechanics: public CSpellMechanics
  141. {
  142. public:
  143. RisingSpellMechanics(CSpell * s): CSpellMechanics(s){};
  144. };
  145. ///all rising spells but SACRIFICE
  146. class SpecialRisingSpellMechanics: public RisingSpellMechanics
  147. {
  148. public:
  149. SpecialRisingSpellMechanics(CSpell * s): RisingSpellMechanics(s){};
  150. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  151. };
  152. ///CloneMechanics
  153. ESpellCastProblem::ESpellCastProblem CloneMechnics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack * obj)
  154. {
  155. //can't clone already cloned creature
  156. if (vstd::contains(obj->state, EBattleStackState::CLONED))
  157. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  158. //TODO: how about stacks casting Clone?
  159. //currently Clone casted by stack is assumed Expert level
  160. ui8 schoolLevel;
  161. if (caster)
  162. {
  163. schoolLevel = caster->getSpellSchoolLevel(owner);
  164. }
  165. else
  166. {
  167. schoolLevel = 3;
  168. }
  169. if (schoolLevel < 3)
  170. {
  171. int maxLevel = (std::max(schoolLevel, (ui8)1) + 4);
  172. int creLevel = obj->getCreature()->level;
  173. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, any level for expert
  174. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  175. }
  176. //use default algorithm only if there is no mechanics-related problem
  177. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  178. }
  179. ///DispellHelpfulMechanics
  180. ESpellCastProblem::ESpellCastProblem DispellHelpfulMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  181. {
  182. TBonusListPtr spellBon = obj->getSpellBonuses();
  183. bool hasPositiveSpell = false;
  184. for(const Bonus * b : *spellBon)
  185. {
  186. if(SpellID(b->sid).toSpell()->isPositive())
  187. {
  188. hasPositiveSpell = true;
  189. break;
  190. }
  191. }
  192. if(!hasPositiveSpell)
  193. {
  194. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  195. }
  196. //use default algorithm only if there is no mechanics-related problem
  197. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  198. }
  199. ///SpecialRisingSpellMechanics
  200. ESpellCastProblem::ESpellCastProblem SpecialRisingSpellMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  201. {
  202. // // following does apply to resurrect and animate dead(?) only
  203. // // for sacrifice health calculation and health limit check don't matter
  204. //
  205. // if(obj->count >= obj->baseAmount)
  206. // return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  207. //
  208. // if (caster) //FIXME: Archangels can cast immune stack
  209. // {
  210. // auto maxHealth = calculateHealedHP (caster, spell, obj);
  211. // if (maxHealth < obj->MaxHealth()) //must be able to rise at least one full creature
  212. // return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  213. // }
  214. }
  215. }
  216. ///CSpell::LevelInfo
  217. CSpell::LevelInfo::LevelInfo()
  218. :description(""),cost(0),power(0),AIValue(0),smartTarget(true),range("0")
  219. {
  220. }
  221. CSpell::LevelInfo::~LevelInfo()
  222. {
  223. }
  224. ///CSpell
  225. CSpell::CSpell():
  226. id(SpellID::NONE), level(0),
  227. earth(false), water(false), fire(false), air(false),
  228. combatSpell(false), creatureAbility(false),
  229. positiveness(ESpellPositiveness::NEUTRAL),
  230. mainEffectAnim(-1),
  231. defaultProbability(0),
  232. isRising(false), isDamage(false), isOffensive(false),
  233. targetType(ETargetType::NO_TARGET),
  234. mechanics(nullptr)
  235. {
  236. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  237. }
  238. CSpell::~CSpell()
  239. {
  240. delete mechanics;
  241. }
  242. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  243. {
  244. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  245. {
  246. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  247. throw new std::runtime_error("Invalid school level");
  248. }
  249. return levels.at(level);
  250. }
  251. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  252. {
  253. using namespace SRSLPraserHelpers;
  254. std::vector<BattleHex> ret;
  255. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  256. {
  257. //Special case - shape of obstacle depends on caster's side
  258. //TODO make it possible through spell_info config
  259. BattleHex::EDir firstStep, secondStep;
  260. if(side)
  261. {
  262. firstStep = BattleHex::TOP_LEFT;
  263. secondStep = BattleHex::TOP_RIGHT;
  264. }
  265. else
  266. {
  267. firstStep = BattleHex::TOP_RIGHT;
  268. secondStep = BattleHex::TOP_LEFT;
  269. }
  270. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  271. auto addIfValid = [&](BattleHex hex)
  272. {
  273. if(hex.isValid())
  274. ret.push_back(hex);
  275. else if(outDroppedHexes)
  276. *outDroppedHexes = true;
  277. };
  278. ret.push_back(centralHex);
  279. addIfValid(centralHex.moveInDir(firstStep, false));
  280. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  281. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  282. return ret;
  283. }
  284. std::string rng = getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  285. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  286. {
  287. std::string number1, number2;
  288. int beg, end;
  289. bool readingFirst = true;
  290. for(auto & elem : rng)
  291. {
  292. if(std::isdigit(elem) ) //reading number
  293. {
  294. if(readingFirst)
  295. number1 += elem;
  296. else
  297. number2 += elem;
  298. }
  299. else if(elem == ',') //comma
  300. {
  301. //calculating variables
  302. if(readingFirst)
  303. {
  304. beg = atoi(number1.c_str());
  305. number1 = "";
  306. }
  307. else
  308. {
  309. end = atoi(number2.c_str());
  310. number2 = "";
  311. }
  312. //obtaining new hexes
  313. std::set<ui16> curLayer;
  314. if(readingFirst)
  315. {
  316. curLayer = getInRange(centralHex, beg, beg);
  317. }
  318. else
  319. {
  320. curLayer = getInRange(centralHex, beg, end);
  321. readingFirst = true;
  322. }
  323. //adding abtained hexes
  324. for(auto & curLayer_it : curLayer)
  325. {
  326. ret.push_back(curLayer_it);
  327. }
  328. }
  329. else if(elem == '-') //dash
  330. {
  331. beg = atoi(number1.c_str());
  332. number1 = "";
  333. readingFirst = false;
  334. }
  335. }
  336. }
  337. //remove duplicates (TODO check if actually needed)
  338. range::unique(ret);
  339. return ret;
  340. }
  341. CSpell::ETargetType CSpell::getTargetType() const
  342. {
  343. return targetType;
  344. }
  345. const CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  346. {
  347. TargetInfo info;
  348. auto & levelInfo = getLevelInfo(level);
  349. info.type = getTargetType();
  350. info.smart = levelInfo.smartTarget;
  351. info.massive = levelInfo.range == "X";
  352. info.onlyAlive = !isRisingSpell();
  353. return info;
  354. }
  355. bool CSpell::isCombatSpell() const
  356. {
  357. return combatSpell;
  358. }
  359. bool CSpell::isAdventureSpell() const
  360. {
  361. return !combatSpell;
  362. }
  363. bool CSpell::isCreatureAbility() const
  364. {
  365. return creatureAbility;
  366. }
  367. bool CSpell::isPositive() const
  368. {
  369. return positiveness == POSITIVE;
  370. }
  371. bool CSpell::isNegative() const
  372. {
  373. return positiveness == NEGATIVE;
  374. }
  375. bool CSpell::isNeutral() const
  376. {
  377. return positiveness == NEUTRAL;
  378. }
  379. bool CSpell::isRisingSpell() const
  380. {
  381. return isRising;
  382. }
  383. bool CSpell::isDamageSpell() const
  384. {
  385. return isDamage;
  386. }
  387. bool CSpell::isOffensiveSpell() const
  388. {
  389. return isOffensive;
  390. }
  391. bool CSpell::isSpecialSpell() const
  392. {
  393. return isSpecial;
  394. }
  395. bool CSpell::hasEffects() const
  396. {
  397. return !levels[0].effects.empty();
  398. }
  399. const std::string& CSpell::getIconImmune() const
  400. {
  401. return iconImmune;
  402. }
  403. const std::string& CSpell::getCastSound() const
  404. {
  405. return castSound;
  406. }
  407. si32 CSpell::getCost(const int skillLevel) const
  408. {
  409. return getLevelInfo(skillLevel).cost;
  410. }
  411. si32 CSpell::getPower(const int skillLevel) const
  412. {
  413. return getLevelInfo(skillLevel).power;
  414. }
  415. //si32 CSpell::calculatePower(const int skillLevel) const
  416. //{
  417. // return power + getPower(skillLevel);
  418. //}
  419. si32 CSpell::getProbability(const TFaction factionId) const
  420. {
  421. if(!vstd::contains(probabilities,factionId))
  422. {
  423. return defaultProbability;
  424. }
  425. return probabilities.at(factionId);
  426. }
  427. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  428. {
  429. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  430. {
  431. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  432. return;
  433. }
  434. const std::vector<Bonus> & effects = levels[level].effects;
  435. if(effects.empty())
  436. {
  437. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  438. return;
  439. }
  440. lst.reserve(lst.size() + effects.size());
  441. for(const Bonus & b : effects)
  442. {
  443. lst.push_back(Bonus(b));
  444. }
  445. }
  446. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  447. {
  448. //0. check receptivity
  449. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  450. return ESpellCastProblem::OK;
  451. //todo: use new bonus API
  452. //1. Check absolute limiters
  453. for(auto b : absoluteLimiters)
  454. {
  455. if (!obj->hasBonusOfType(b))
  456. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  457. }
  458. //2. Check absolute immunities
  459. for(auto b : absoluteImmunities)
  460. {
  461. if (obj->hasBonusOfType(b))
  462. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  463. }
  464. //3. Check negation
  465. //FIXME: Orb of vulnerability mechanics is not such trivial
  466. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  467. return ESpellCastProblem::NOT_DECIDED;
  468. //4. Check negatable limit
  469. for(auto b : limiters)
  470. {
  471. if (!obj->hasBonusOfType(b))
  472. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  473. }
  474. //5. Check negatable immunities
  475. for(auto b : immunities)
  476. {
  477. if (obj->hasBonusOfType(b))
  478. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  479. }
  480. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  481. {
  482. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  483. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  484. else if(!isPositive()) //negative or indifferent
  485. {
  486. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  487. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  488. }
  489. return ESpellCastProblem::NOT_DECIDED;
  490. };
  491. //6. Check elemental immunities
  492. if(fire)
  493. {
  494. if(battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  495. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  496. }
  497. if(water)
  498. {
  499. if(battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  500. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  501. }
  502. if(earth)
  503. {
  504. if(battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  505. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  506. }
  507. if(air)
  508. {
  509. if(battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  510. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  511. }
  512. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  513. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  514. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  515. {
  516. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  517. }
  518. return ESpellCastProblem::NOT_DECIDED;
  519. }
  520. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj) const
  521. {
  522. return mechanics->isImmuneByStack(caster,mode,obj);
  523. }
  524. void CSpell::setIsOffensive(const bool val)
  525. {
  526. isOffensive = val;
  527. if(val)
  528. {
  529. positiveness = CSpell::NEGATIVE;
  530. isDamage = true;
  531. }
  532. }
  533. void CSpell::setIsRising(const bool val)
  534. {
  535. isRising = val;
  536. if(val)
  537. {
  538. positiveness = CSpell::POSITIVE;
  539. }
  540. }
  541. void CSpell::setupMechanics()
  542. {
  543. if(nullptr != mechanics)
  544. {
  545. logGlobal->errorStream() << "Spell " << this->name << " mechanics already set";
  546. delete mechanics;
  547. mechanics = nullptr;
  548. }
  549. switch (id)
  550. {
  551. case SpellID::CLONE:
  552. mechanics = new CloneMechnics(this);
  553. break;
  554. case SpellID::DISPEL_HELPFUL_SPELLS:
  555. mechanics = new DispellHelpfulMechanics(this);
  556. break;
  557. default:
  558. mechanics = new CSpellMechanics(this);
  559. break;
  560. }
  561. }
  562. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  563. {
  564. int3 diff = pos - center;
  565. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  566. return true;
  567. else
  568. return false;
  569. }
  570. ///CSpellHandler
  571. CSpellHandler::CSpellHandler()
  572. {
  573. }
  574. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  575. {
  576. using namespace SpellConfig;
  577. std::vector<JsonNode> legacyData;
  578. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  579. auto readSchool = [&](JsonMap& schools, const std::string& name)
  580. {
  581. if (parser.readString() == "x")
  582. {
  583. schools[name].Bool() = true;
  584. }
  585. };
  586. auto read = [&,this](bool combat, bool ability)
  587. {
  588. do
  589. {
  590. JsonNode lineNode(JsonNode::DATA_STRUCT);
  591. const si32 id = legacyData.size();
  592. lineNode["index"].Float() = id;
  593. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  594. lineNode["name"].String() = parser.readString();
  595. parser.readString(); //ignored unused abbreviated name
  596. lineNode["level"].Float() = parser.readNumber();
  597. auto& schools = lineNode["school"].Struct();
  598. readSchool(schools, "earth");
  599. readSchool(schools, "water");
  600. readSchool(schools, "fire");
  601. readSchool(schools, "air");
  602. auto& levels = lineNode["levels"].Struct();
  603. auto getLevel = [&](const size_t idx)->JsonMap&
  604. {
  605. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  606. return levels[LEVEL_NAMES[idx]].Struct();
  607. };
  608. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  609. lineNode["power"].Float() = parser.readNumber();
  610. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  611. auto& chances = lineNode["gainChance"].Struct();
  612. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  613. chances[ETownType::names[i]].Float() = parser.readNumber();
  614. }
  615. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  616. std::vector<std::string> descriptions;
  617. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  618. descriptions.push_back(parser.readString());
  619. std::string attributes = parser.readString();
  620. std::string targetType = "NO_TARGET";
  621. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  622. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  623. targetType = "CREATURE_EXPERT_MASSIVE";
  624. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  625. targetType = "CREATURE";
  626. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  627. targetType = "OBSTACLE";
  628. //save parsed level specific data
  629. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  630. {
  631. auto& level = getLevel(i);
  632. level["description"].String() = descriptions[i];
  633. level["cost"].Float() = costs[i];
  634. level["power"].Float() = powers[i];
  635. level["aiValue"].Float() = AIVals[i];
  636. }
  637. if(targetType == "CREATURE_EXPERT_MASSIVE")
  638. {
  639. lineNode["targetType"].String() = "CREATURE";
  640. getLevel(3)["range"].String() = "X";
  641. }
  642. else
  643. {
  644. lineNode["targetType"].String() = targetType;
  645. }
  646. legacyData.push_back(lineNode);
  647. }
  648. while (parser.endLine() && !parser.isNextEntryEmpty());
  649. };
  650. auto skip = [&](int cnt)
  651. {
  652. for(int i=0; i<cnt; i++)
  653. parser.endLine();
  654. };
  655. skip(5);// header
  656. read(false,false); //read adventure map spells
  657. skip(3);
  658. read(true,false); //read battle spells
  659. skip(3);
  660. read(true,true);//read creature abilities
  661. //TODO: maybe move to config
  662. //clone Acid Breath attributes for Acid Breath damage effect
  663. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  664. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  665. legacyData.push_back(temp);
  666. objects.resize(legacyData.size());
  667. return legacyData;
  668. }
  669. const std::string CSpellHandler::getTypeName() const
  670. {
  671. return "spell";
  672. }
  673. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  674. {
  675. using namespace SpellConfig;
  676. CSpell * spell = new CSpell();
  677. const auto type = json["type"].String();
  678. if(type == "ability")
  679. {
  680. spell->creatureAbility = true;
  681. spell->combatSpell = true;
  682. }
  683. else
  684. {
  685. spell->creatureAbility = false;
  686. spell->combatSpell = type == "combat";
  687. }
  688. spell->name = json["name"].String();
  689. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  690. const auto schoolNames = json["school"];
  691. spell->air = schoolNames["air"].Bool();
  692. spell->earth = schoolNames["earth"].Bool();
  693. spell->fire = schoolNames["fire"].Bool();
  694. spell->water = schoolNames["water"].Bool();
  695. spell->level = json["level"].Float();
  696. spell->power = json["power"].Float();
  697. spell->defaultProbability = json["defaultGainChance"].Float();
  698. for(const auto & node : json["gainChance"].Struct())
  699. {
  700. const int chance = node.second.Float();
  701. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  702. {
  703. spell->probabilities[factionID] = chance;
  704. });
  705. }
  706. const std::string targetType = json["targetType"].String();
  707. if(targetType == "NO_TARGET")
  708. spell->targetType = CSpell::NO_TARGET;
  709. else if(targetType == "CREATURE")
  710. spell->targetType = CSpell::CREATURE;
  711. else if(targetType == "OBSTACLE")
  712. spell->targetType = CSpell::OBSTACLE;
  713. else
  714. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  715. spell->mainEffectAnim = json["anim"].Float();
  716. for(const auto & counteredSpell: json["counters"].Struct())
  717. if (counteredSpell.second.Bool())
  718. {
  719. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  720. {
  721. spell->counteredSpells.push_back(SpellID(id));
  722. });
  723. }
  724. //TODO: more error checking - f.e. conflicting flags
  725. const auto flags = json["flags"];
  726. //by default all flags are set to false in constructor
  727. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  728. if(flags["offensive"].Bool())
  729. {
  730. spell->setIsOffensive(true);
  731. }
  732. if(flags["rising"].Bool())
  733. {
  734. spell->setIsRising(true);
  735. }
  736. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  737. if(flags["indifferent"].Bool())
  738. {
  739. spell->positiveness = CSpell::NEUTRAL;
  740. }
  741. else if(flags["negative"].Bool())
  742. {
  743. spell->positiveness = CSpell::NEGATIVE;
  744. }
  745. else if(flags["positive"].Bool())
  746. {
  747. spell->positiveness = CSpell::POSITIVE;
  748. }
  749. else if(!implicitPositiveness)
  750. {
  751. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  752. logGlobal->warnStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL";
  753. }
  754. spell->isSpecial = flags["special"].Bool();
  755. auto findBonus = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  756. {
  757. auto it = bonusNameMap.find(name);
  758. if(it == bonusNameMap.end())
  759. {
  760. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  761. }
  762. else
  763. {
  764. vec.push_back((Bonus::BonusType)it->second);
  765. }
  766. };
  767. auto readBonusStruct = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  768. {
  769. for(auto bonusData: json[name].Struct())
  770. {
  771. const std::string bonusId = bonusData.first;
  772. const bool flag = bonusData.second.Bool();
  773. if(flag)
  774. findBonus(bonusId, vec);
  775. }
  776. };
  777. readBonusStruct("immunity", spell->immunities);
  778. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  779. readBonusStruct("limit", spell->limiters);
  780. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  781. const JsonNode & graphicsNode = json["graphics"];
  782. spell->iconImmune = graphicsNode["iconImmune"].String();
  783. spell->iconBook = graphicsNode["iconBook"].String();
  784. spell->iconEffect = graphicsNode["iconEffect"].String();
  785. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  786. spell->iconScroll = graphicsNode["iconScroll"].String();
  787. const JsonNode & soundsNode = json["sounds"];
  788. spell->castSound = soundsNode["cast"].String();
  789. //load level attributes
  790. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  791. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  792. {
  793. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  794. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  795. const si32 levelPower = levelNode["power"].Float();
  796. levelObject.description = levelNode["description"].String();
  797. levelObject.cost = levelNode["cost"].Float();
  798. levelObject.power = levelPower;
  799. levelObject.AIValue = levelNode["aiValue"].Float();
  800. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  801. levelObject.range = levelNode["range"].String();
  802. for(const auto & elem : levelNode["effects"].Struct())
  803. {
  804. const JsonNode & bonusNode = elem.second;
  805. Bonus * b = JsonUtils::parseBonus(bonusNode);
  806. const bool usePowerAsValue = bonusNode["val"].isNull();
  807. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  808. //b->sid = spell->id; //for all
  809. b->source = Bonus::SPELL_EFFECT;//for all
  810. if(usePowerAsValue)
  811. b->val = levelPower;
  812. levelObject.effects.push_back(*b);
  813. }
  814. }
  815. return spell;
  816. }
  817. void CSpellHandler::afterLoadFinalization()
  818. {
  819. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  820. for(auto spell: objects)
  821. {
  822. for(auto & level: spell->levels)
  823. for(auto & bonus: level.effects)
  824. bonus.sid = spell->id;
  825. spell->setupMechanics();
  826. }
  827. }
  828. void CSpellHandler::beforeValidate(JsonNode & object)
  829. {
  830. //handle "base" level info
  831. JsonNode& levels = object["levels"];
  832. JsonNode& base = levels["base"];
  833. auto inheritNode = [&](const std::string & name){
  834. JsonUtils::inherit(levels[name],base);
  835. };
  836. inheritNode("none");
  837. inheritNode("basic");
  838. inheritNode("advanced");
  839. inheritNode("expert");
  840. }
  841. CSpellHandler::~CSpellHandler()
  842. {
  843. }
  844. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  845. {
  846. std::vector<bool> allowedSpells;
  847. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  848. return allowedSpells;
  849. }