CSpellHandler.cpp 25 KB

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