CSpellHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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::isRisingSpell() const
  266. {
  267. return isRising;
  268. }
  269. bool CSpell::isDamageSpell() const
  270. {
  271. return isDamage;
  272. }
  273. bool CSpell::isOffensiveSpell() const
  274. {
  275. return isOffensive;
  276. }
  277. bool CSpell::isSpecialSpell() const
  278. {
  279. return isSpecial;
  280. }
  281. bool CSpell::hasEffects() const
  282. {
  283. return !levels[0].effects.empty();
  284. }
  285. const std::string& CSpell::getIconImmune() const
  286. {
  287. return iconImmune;
  288. }
  289. const std::string& CSpell::getCastSound() const
  290. {
  291. return castSound;
  292. }
  293. si32 CSpell::getCost(const int skillLevel) const
  294. {
  295. return getLevelInfo(skillLevel).cost;
  296. }
  297. si32 CSpell::getPower(const int skillLevel) const
  298. {
  299. return getLevelInfo(skillLevel).power;
  300. }
  301. //si32 CSpell::calculatePower(const int skillLevel) const
  302. //{
  303. // return power + getPower(skillLevel);
  304. //}
  305. si32 CSpell::getProbability(const TFaction factionId) const
  306. {
  307. if(!vstd::contains(probabilities,factionId))
  308. {
  309. return defaultProbability;
  310. }
  311. return probabilities.at(factionId);
  312. }
  313. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  314. {
  315. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  316. {
  317. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  318. return;
  319. }
  320. const std::vector<Bonus> & effects = levels[level].effects;
  321. if(effects.empty())
  322. {
  323. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  324. return;
  325. }
  326. lst.reserve(lst.size() + effects.size());
  327. for(const Bonus & b : effects)
  328. {
  329. lst.push_back(Bonus(b));
  330. }
  331. }
  332. bool CSpell::isImmuneBy(const IBonusBearer* obj) const
  333. {
  334. //todo: use new bonus API
  335. //1. Check limiters
  336. for(auto b : limiters)
  337. {
  338. if (!obj->hasBonusOfType(b))
  339. return true;
  340. }
  341. //2. Check absolute immunities
  342. //todo: check config: some creatures are unaffected always, for example undead to resurrection.
  343. for(auto b : absoluteImmunities)
  344. {
  345. if (obj->hasBonusOfType(b))
  346. return true;
  347. }
  348. //3. Check negation
  349. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  350. return false;
  351. //4. Check negatable immunities
  352. for(auto b : immunities)
  353. {
  354. if (obj->hasBonusOfType(b))
  355. return true;
  356. }
  357. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  358. {
  359. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  360. return true;
  361. else if(!isPositive()) //negative or indifferent
  362. {
  363. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  364. return true;
  365. }
  366. return false;
  367. };
  368. //4. Check elemental immunities
  369. if(fire)
  370. {
  371. if(battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  372. return true;
  373. }
  374. if(water)
  375. {
  376. if(battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  377. return true;
  378. }
  379. if(earth)
  380. {
  381. if(battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  382. return true;
  383. }
  384. if(air)
  385. {
  386. if(battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  387. return true;
  388. }
  389. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  390. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  391. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  392. {
  393. return true;
  394. }
  395. return false;
  396. }
  397. void CSpell::setIsOffensive(const bool val)
  398. {
  399. isOffensive = val;
  400. if(val)
  401. {
  402. positiveness = CSpell::NEGATIVE;
  403. isDamage = true;
  404. }
  405. }
  406. void CSpell::setIsRising(const bool val)
  407. {
  408. isRising = val;
  409. if(val)
  410. {
  411. positiveness = CSpell::POSITIVE;
  412. }
  413. }
  414. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  415. {
  416. int3 diff = pos - center;
  417. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  418. return true;
  419. else
  420. return false;
  421. }
  422. CSpellHandler::CSpellHandler()
  423. {
  424. }
  425. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  426. {
  427. using namespace SpellConfig;
  428. std::vector<JsonNode> legacyData;
  429. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  430. auto readSchool = [&](JsonMap& schools, const std::string& name)
  431. {
  432. if (parser.readString() == "x")
  433. {
  434. schools[name].Bool() = true;
  435. }
  436. };
  437. auto read = [&,this](bool combat, bool ability)
  438. {
  439. do
  440. {
  441. JsonNode lineNode(JsonNode::DATA_STRUCT);
  442. const si32 id = legacyData.size();
  443. lineNode["index"].Float() = id;
  444. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  445. lineNode["name"].String() = parser.readString();
  446. parser.readString(); //ignored unused abbreviated name
  447. lineNode["level"].Float() = parser.readNumber();
  448. auto& schools = lineNode["school"].Struct();
  449. readSchool(schools, "earth");
  450. readSchool(schools, "water");
  451. readSchool(schools, "fire");
  452. readSchool(schools, "air");
  453. auto& levels = lineNode["levels"].Struct();
  454. auto getLevel = [&](const size_t idx)->JsonMap&
  455. {
  456. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  457. return levels[LEVEL_NAMES[idx]].Struct();
  458. };
  459. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  460. lineNode["power"].Float() = parser.readNumber();
  461. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  462. auto& chances = lineNode["gainChance"].Struct();
  463. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  464. chances[ETownType::names[i]].Float() = parser.readNumber();
  465. }
  466. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  467. std::vector<std::string> descriptions;
  468. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  469. descriptions.push_back(parser.readString());
  470. std::string attributes = parser.readString();
  471. std::string targetType = "NO_TARGET";
  472. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  473. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  474. targetType = "CREATURE_EXPERT_MASSIVE";
  475. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  476. targetType = "CREATURE";
  477. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  478. targetType = "OBSTACLE";
  479. //save parsed level specific data
  480. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  481. {
  482. auto& level = getLevel(i);
  483. level["description"].String() = descriptions[i];
  484. level["cost"].Float() = costs[i];
  485. level["power"].Float() = powers[i];
  486. level["aiValue"].Float() = AIVals[i];
  487. }
  488. if(targetType == "CREATURE_EXPERT_MASSIVE")
  489. {
  490. lineNode["targetType"].String() = "CREATURE";
  491. getLevel(3)["range"].String() = "X";
  492. }
  493. else
  494. {
  495. lineNode["targetType"].String() = targetType;
  496. }
  497. legacyData.push_back(lineNode);
  498. }
  499. while (parser.endLine() && !parser.isNextEntryEmpty());
  500. };
  501. auto skip = [&](int cnt)
  502. {
  503. for(int i=0; i<cnt; i++)
  504. parser.endLine();
  505. };
  506. skip(5);// header
  507. read(false,false); //read adventure map spells
  508. skip(3);
  509. read(true,false); //read battle spells
  510. skip(3);
  511. read(true,true);//read creature abilities
  512. //TODO: maybe move to config
  513. //clone Acid Breath attributes for Acid Breath damage effect
  514. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  515. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  516. legacyData.push_back(temp);
  517. objects.resize(legacyData.size());
  518. return legacyData;
  519. }
  520. const std::string CSpellHandler::getTypeName() const
  521. {
  522. return "spell";
  523. }
  524. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  525. {
  526. using namespace SpellConfig;
  527. CSpell * spell = new CSpell();
  528. const auto type = json["type"].String();
  529. if(type == "ability")
  530. {
  531. spell->creatureAbility = true;
  532. spell->combatSpell = true;
  533. }
  534. else
  535. {
  536. spell->creatureAbility = false;
  537. spell->combatSpell = type == "combat";
  538. }
  539. spell->name = json["name"].String();
  540. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  541. const auto schoolNames = json["school"];
  542. spell->air = schoolNames["air"].Bool();
  543. spell->earth = schoolNames["earth"].Bool();
  544. spell->fire = schoolNames["fire"].Bool();
  545. spell->water = schoolNames["water"].Bool();
  546. spell->level = json["level"].Float();
  547. spell->power = json["power"].Float();
  548. spell->defaultProbability = json["defaultGainChance"].Float();
  549. for(const auto & node : json["gainChance"].Struct())
  550. {
  551. const int chance = node.second.Float();
  552. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  553. {
  554. spell->probabilities[factionID] = chance;
  555. });
  556. }
  557. auto targetType = json["targetType"].String();
  558. if(targetType == "NO_TARGET")
  559. spell->targetType = CSpell::NO_TARGET;
  560. else if(targetType == "CREATURE")
  561. spell->targetType = CSpell::CREATURE;
  562. else if(targetType == "OBSTACLE")
  563. spell->targetType = CSpell::OBSTACLE;
  564. spell->mainEffectAnim = json["anim"].Float();
  565. for(const auto & counteredSpell: json["counters"].Struct())
  566. if (counteredSpell.second.Bool())
  567. {
  568. JsonNode tmp(JsonNode::DATA_STRING);
  569. tmp.meta = json.meta;
  570. tmp.String() = counteredSpell.first;
  571. VLC->modh->identifiers.requestIdentifier(tmp,[=](si32 id){
  572. spell->counteredSpells.push_back(SpellID(id));
  573. });
  574. }
  575. //TODO: more error checking - f.e. conflicting flags
  576. const auto flags = json["flags"];
  577. //by default all flags are set to false in constructor
  578. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  579. if(flags["offensive"].Bool())
  580. {
  581. spell->setIsOffensive(true);
  582. }
  583. if(flags["rising"].Bool())
  584. {
  585. spell->setIsRising(true);
  586. }
  587. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  588. if(flags["indifferent"].Bool())
  589. {
  590. spell->positiveness = CSpell::NEUTRAL;
  591. }
  592. else if(flags["negative"].Bool())
  593. {
  594. spell->positiveness = CSpell::NEGATIVE;
  595. }
  596. else if(flags["positive"].Bool())
  597. {
  598. spell->positiveness = CSpell::POSITIVE;
  599. }
  600. else if(!implicitPositiveness)
  601. {
  602. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  603. logGlobal->errorStream() << "No positiveness specified, assumed NEUTRAL";
  604. }
  605. spell->isSpecial = flags["special"].Bool();
  606. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  607. {
  608. auto it = bonusNameMap.find(name);
  609. if(it == bonusNameMap.end())
  610. {
  611. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  612. }
  613. else
  614. {
  615. vec.push_back((Bonus::BonusType)it->second);
  616. }
  617. };
  618. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  619. {
  620. for(auto bonusData: json[name].Struct())
  621. {
  622. const std::string bonusId = bonusData.first;
  623. const bool flag = bonusData.second.Bool();
  624. if(flag)
  625. findBonus(bonusId, vec);
  626. }
  627. };
  628. readBonusStruct("immunity", spell->immunities);
  629. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  630. readBonusStruct("limit", spell->limiters);
  631. const JsonNode & graphicsNode = json["graphics"];
  632. spell->iconImmune = graphicsNode["iconImmune"].String();
  633. spell->iconBook = graphicsNode["iconBook"].String();
  634. spell->iconEffect = graphicsNode["iconEffect"].String();
  635. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  636. spell->iconScroll = graphicsNode["iconScroll"].String();
  637. const JsonNode & soundsNode = json["sounds"];
  638. spell->castSound = soundsNode["cast"].String();
  639. //load level attributes
  640. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  641. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  642. {
  643. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  644. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  645. const si32 levelPower = levelNode["power"].Float();
  646. levelObject.description = levelNode["description"].String();
  647. levelObject.cost = levelNode["cost"].Float();
  648. levelObject.power = levelPower;
  649. levelObject.AIValue = levelNode["aiValue"].Float();
  650. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  651. levelObject.range = levelNode["range"].String();
  652. for(const auto & elem : levelNode["effects"].Struct())
  653. {
  654. const JsonNode & bonusNode = elem.second;
  655. Bonus * b = JsonUtils::parseBonus(bonusNode);
  656. const bool usePowerAsValue = bonusNode["val"].isNull();
  657. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  658. //b->sid = spell->id; //for all
  659. b->source = Bonus::SPELL_EFFECT;//for all
  660. if(usePowerAsValue)
  661. b->val = levelPower;
  662. levelObject.effects.push_back(*b);
  663. }
  664. }
  665. return spell;
  666. }
  667. void CSpellHandler::afterLoadFinalization()
  668. {
  669. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  670. for(auto spell: objects)
  671. for(auto & level: spell->levels)
  672. for(auto & bonus: level.effects)
  673. bonus.sid = spell->id;
  674. }
  675. CSpellHandler::~CSpellHandler()
  676. {
  677. }
  678. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  679. {
  680. std::vector<bool> allowedSpells;
  681. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  682. return allowedSpells;
  683. }