CSpellHandler.cpp 20 KB

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