CSpellHandler.cpp 21 KB

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