CHeroHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. #include "StdInc.h"
  2. #include "CHeroHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "Filesystem/CResourceLoader.h"
  5. #include "VCMI_Lib.h"
  6. #include "JsonNode.h"
  7. #include "StringConstants.h"
  8. #include "BattleHex.h"
  9. #include "CModHandler.h"
  10. #include "CTownHandler.h"
  11. #include "CObjectHandler.h" //for hero specialty
  12. /*
  13. * CHeroHandler.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. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles) const //picks secondary skill out from given possibilities
  22. {
  23. if(possibles.size()==1)
  24. return *possibles.begin();
  25. int totalProb = 0;
  26. for(auto i=possibles.begin(); i!=possibles.end(); i++)
  27. {
  28. totalProb += secSkillProbability[*i];
  29. }
  30. int ran = rand()%totalProb;
  31. for(auto i=possibles.begin(); i!=possibles.end(); i++)
  32. {
  33. ran -= secSkillProbability[*i];
  34. if(ran<0)
  35. return *i;
  36. }
  37. throw std::runtime_error("Cannot pick secondary skill!");
  38. }
  39. EAlignment::EAlignment CHeroClass::getAlignment() const
  40. {
  41. return EAlignment::EAlignment(VLC->townh->factions[faction].alignment);
  42. }
  43. std::vector<BattleHex> CObstacleInfo::getBlocked(BattleHex hex) const
  44. {
  45. std::vector<BattleHex> ret;
  46. if(isAbsoluteObstacle)
  47. {
  48. assert(!hex.isValid());
  49. range::copy(blockedTiles, std::back_inserter(ret));
  50. return ret;
  51. }
  52. BOOST_FOREACH(int offset, blockedTiles)
  53. {
  54. BattleHex toBlock = hex + offset;
  55. if((hex.getY() & 1) && !(toBlock.getY() & 1))
  56. toBlock += BattleHex::LEFT;
  57. if(!toBlock.isValid())
  58. tlog1 << "Misplaced obstacle!\n";
  59. else
  60. ret.push_back(toBlock);
  61. }
  62. return ret;
  63. }
  64. bool CObstacleInfo::isAppropriate(ETerrainType terrainType, int specialBattlefield /*= -1*/) const
  65. {
  66. if(specialBattlefield != -1)
  67. return vstd::contains(allowedSpecialBfields, specialBattlefield);
  68. return vstd::contains(allowedTerrains, terrainType);
  69. }
  70. void CHeroClassHandler::load()
  71. {
  72. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  73. parser.endLine(); // header
  74. parser.endLine();
  75. std::vector<JsonNode> h3Data;
  76. do
  77. {
  78. JsonNode entry;
  79. entry["name"].String() = parser.readString();
  80. parser.readNumber(); // unused aggression
  81. for (size_t i=0; i < GameConstants::PRIMARY_SKILLS; i++)
  82. entry["primarySkills"][PrimarySkill::names[i]].Float() = parser.readNumber();
  83. for (size_t i=0; i < GameConstants::PRIMARY_SKILLS; i++)
  84. entry["lowLevelChance"][PrimarySkill::names[i]].Float() = parser.readNumber();
  85. for (size_t i=0; i < GameConstants::PRIMARY_SKILLS; i++)
  86. entry["highLevelChance"][PrimarySkill::names[i]].Float() = parser.readNumber();
  87. for (size_t i=0; i < GameConstants::SKILL_QUANTITY; i++)
  88. entry["secondarySkills"][NSecondarySkill::names[i]].Float() = parser.readNumber();
  89. for(size_t i = 0; i < GameConstants::F_NUMBER; i++)
  90. entry["tavern"][ETownType::names[i]].Float() = parser.readNumber();
  91. h3Data.push_back(entry);
  92. }
  93. while (parser.endLine() && !parser.isNextEntryEmpty());
  94. JsonNode classConf = JsonNode(ResourceID("config/heroClasses.json"));
  95. heroClasses.resize(GameConstants::F_NUMBER * 2);
  96. BOOST_FOREACH(auto & node, classConf.Struct())
  97. {
  98. int numeric = node.second["id"].Float();
  99. JsonNode & classData = h3Data[numeric];
  100. JsonUtils::merge(classData, node.second);
  101. heroClasses[numeric] = loadClass(classData);
  102. heroClasses[numeric]->id = numeric;
  103. VLC->modh->identifiers.registerObject ("heroClass." + node.first, numeric);
  104. }
  105. for (size_t i=0; i < heroClasses.size(); i++)
  106. {
  107. if (heroClasses[i] == nullptr)
  108. tlog0 << "Warning: class with id " << i << " is missing!\n";
  109. }
  110. }
  111. void CHeroClassHandler::load(std::string objectID, const JsonNode & input)
  112. {
  113. CHeroClass * heroClass = loadClass(input);
  114. heroClass->identifier = objectID;
  115. heroClass->id = heroClasses.size();
  116. heroClasses.push_back(heroClass);
  117. tlog5 << "Added hero class: " << objectID << "\n";
  118. VLC->modh->identifiers.registerObject("heroClass." + heroClass->identifier, heroClass->id);
  119. }
  120. CHeroClass *CHeroClassHandler::loadClass(const JsonNode & node)
  121. {
  122. CHeroClass * heroClass = new CHeroClass;
  123. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  124. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  125. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  126. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  127. heroClass->name = node["name"].String();
  128. BOOST_FOREACH(const std::string & pSkill, PrimarySkill::names)
  129. {
  130. heroClass->primarySkillInitial.push_back(node["primarySkills"][pSkill].Float());
  131. heroClass->primarySkillLowLevel.push_back(node["lowLevelChance"][pSkill].Float());
  132. heroClass->primarySkillHighLevel.push_back(node["highLevelChance"][pSkill].Float());
  133. }
  134. BOOST_FOREACH(const std::string & secSkill, NSecondarySkill::names)
  135. {
  136. heroClass->secSkillProbability.push_back(node["secondarySkills"][secSkill].Float());
  137. }
  138. BOOST_FOREACH(auto & tavern, node["tavern"].Struct())
  139. {
  140. int value = tavern.second.Float();
  141. VLC->modh->identifiers.requestIdentifier("faction." + tavern.first,
  142. [=](si32 factionID)
  143. {
  144. heroClass->selectionProbability[factionID] = value;
  145. });
  146. }
  147. VLC->modh->identifiers.requestIdentifier("faction." + node["faction"].String(),
  148. [=](si32 factionID)
  149. {
  150. heroClass->faction = factionID;
  151. });
  152. return heroClass;
  153. }
  154. CHeroClassHandler::~CHeroClassHandler()
  155. {
  156. BOOST_FOREACH(auto heroClass, heroClasses)
  157. {
  158. delete heroClass.get();
  159. }
  160. }
  161. CHeroHandler::~CHeroHandler()
  162. {
  163. BOOST_FOREACH(auto hero, heroes)
  164. delete hero.get();
  165. }
  166. CHeroHandler::CHeroHandler()
  167. {
  168. }
  169. void CHeroHandler::load(std::string objectID, const JsonNode & input)
  170. {
  171. CHero * hero = loadHero(input);
  172. hero->ID = heroes.size();
  173. heroes.push_back(hero);
  174. tlog5 << "Added hero: " << objectID << "\n";
  175. VLC->modh->identifiers.registerObject("hero." + objectID, hero->ID);
  176. }
  177. CHero * CHeroHandler::loadHero(const JsonNode & node)
  178. {
  179. CHero * hero = new CHero;
  180. hero->sex = node["female"].Bool();
  181. hero->special = node["special"].Bool();
  182. hero->name = node["texts"]["name"].String();
  183. hero->biography = node["texts"]["biography"].String();
  184. hero->specName = node["texts"]["specialty"]["name"].String();
  185. hero->specTooltip = node["texts"]["specialty"]["tooltip"].String();
  186. hero->specDescr = node["texts"]["specialty"]["description"].String();
  187. hero->imageIndex = node["images"]["index"].Float();
  188. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  189. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  190. hero->portraitSmall = node["images"]["small"].String();
  191. hero->portraitLarge = node["images"]["large"].String();
  192. loadHeroArmy(hero, node);
  193. loadHeroSkills(hero, node);
  194. loadHeroSpecialty(hero, node);
  195. VLC->modh->identifiers.requestIdentifier("heroClass." + node["class"].String(),
  196. [=](si32 classID)
  197. {
  198. hero->heroClass = classes.heroClasses[classID];
  199. });
  200. return hero;
  201. }
  202. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  203. {
  204. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  205. hero->initialArmy.resize(node["army"].Vector().size());
  206. for (size_t i=0; i< hero->initialArmy.size(); i++)
  207. {
  208. const JsonNode & source = node["army"].Vector()[i];
  209. hero->initialArmy[i].minAmount = source["min"].Float();
  210. hero->initialArmy[i].maxAmount = source["max"].Float();
  211. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  212. VLC->modh->identifiers.requestIdentifier("creature." + source["creature"].String(), [=](si32 creature)
  213. {
  214. hero->initialArmy[i].creature = CreatureID(creature);
  215. });
  216. }
  217. }
  218. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  219. {
  220. BOOST_FOREACH(const JsonNode &set, node["skills"].Vector())
  221. {
  222. SecondarySkill skillID = SecondarySkill(
  223. boost::range::find(NSecondarySkill::names, set["skill"].String()) - boost::begin(NSecondarySkill::names));
  224. int skillLevel = boost::range::find(NSecondarySkill::levels, set["level"].String()) - boost::begin(NSecondarySkill::levels);
  225. hero->secSkillsInit.push_back(std::make_pair(skillID, skillLevel));
  226. }
  227. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  228. hero->haveSpellBook = !node["spellbook"].isNull();
  229. BOOST_FOREACH(const JsonNode & spell, node["spellbook"].Vector())
  230. {
  231. if (spell.getType() == JsonNode::DATA_FLOAT) // for compatibility
  232. {
  233. hero->spells.insert(SpellID(spell.Float()));
  234. }
  235. else
  236. {
  237. VLC->modh->identifiers.requestIdentifier("spell." + spell.String(),
  238. [=](si32 spellID)
  239. {
  240. hero->spells.insert(SpellID(spellID));
  241. });
  242. }
  243. }
  244. }
  245. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  246. {
  247. //deprecated, used only for original spciealties
  248. BOOST_FOREACH(const JsonNode &specialty, node["specialties"].Vector())
  249. {
  250. SSpecialtyInfo spec;
  251. spec.type = specialty["type"].Float();
  252. spec.val = specialty["val"].Float();
  253. spec.subtype = specialty["subtype"].Float();
  254. spec.additionalinfo = specialty["info"].Float();
  255. hero->spec.push_back(spec); //put a copy of dummy
  256. }
  257. //new format, using bonus system
  258. BOOST_FOREACH(const JsonNode &specialty, node["specialty"].Vector())
  259. {
  260. SSpecialtyBonus hs;
  261. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  262. BOOST_FOREACH (const JsonNode & bonus, specialty["bonuses"].Vector())
  263. {
  264. auto b = JsonUtils::parseBonus(bonus);
  265. hs.bonuses.push_back (b);
  266. }
  267. hero->specialty.push_back (hs); //now, how to get CGHeroInstance from it?
  268. }
  269. }
  270. void CHeroHandler::load()
  271. {
  272. VLC->heroh = this;
  273. for (int i = 0; i < GameConstants::SKILL_QUANTITY; ++i)
  274. {
  275. VLC->modh->identifiers.registerObject("skill." + NSecondarySkill::names[i], i);
  276. }
  277. classes.load();
  278. loadHeroes();
  279. loadObstacles();
  280. loadTerrains();
  281. loadBallistics();
  282. loadExperience();
  283. }
  284. void CHeroHandler::loadExperience()
  285. {
  286. expPerLevel.push_back(0);
  287. expPerLevel.push_back(1000);
  288. expPerLevel.push_back(2000);
  289. expPerLevel.push_back(3200);
  290. expPerLevel.push_back(4600);
  291. expPerLevel.push_back(6200);
  292. expPerLevel.push_back(8000);
  293. expPerLevel.push_back(10000);
  294. expPerLevel.push_back(12200);
  295. expPerLevel.push_back(14700);
  296. expPerLevel.push_back(17500);
  297. expPerLevel.push_back(20600);
  298. expPerLevel.push_back(24320);
  299. expPerLevel.push_back(28784);
  300. expPerLevel.push_back(34140);
  301. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  302. {
  303. int i = expPerLevel.size() - 1;
  304. expPerLevel.push_back (expPerLevel[i] + (expPerLevel[i] - expPerLevel[i-1]) * 1.2);
  305. }
  306. expPerLevel.pop_back();//last value is broken
  307. }
  308. void CHeroHandler::loadObstacles()
  309. {
  310. auto loadObstacles = [](const JsonNode &node, bool absolute, std::map<int, CObstacleInfo> &out)
  311. {
  312. BOOST_FOREACH(const JsonNode &obs, node.Vector())
  313. {
  314. int ID = obs["id"].Float();
  315. CObstacleInfo & obi = out[ID];
  316. obi.ID = ID;
  317. obi.defName = obs["defname"].String();
  318. obi.width = obs["width"].Float();
  319. obi.height = obs["height"].Float();
  320. obi.allowedTerrains = obs["allowedTerrain"].convertTo<std::vector<ETerrainType> >();
  321. obi.allowedSpecialBfields = obs["specialBattlefields"].convertTo<std::vector<BFieldType> >();
  322. obi.blockedTiles = obs["blockedTiles"].convertTo<std::vector<si16> >();
  323. obi.isAbsoluteObstacle = absolute;
  324. }
  325. };
  326. const JsonNode config(ResourceID("config/obstacles.json"));
  327. loadObstacles(config["obstacles"], false, obstacles);
  328. loadObstacles(config["absoluteObstacles"], true, absoluteObstacles);
  329. //loadObstacles(config["moats"], true, moats);
  330. }
  331. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  332. static std::string genRefName(std::string input)
  333. {
  334. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  335. input[0] = std::tolower(input[0]); // to camelCase
  336. return input;
  337. }
  338. void CHeroHandler::loadHeroes()
  339. {
  340. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  341. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  342. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  343. parser.endLine(); //ignore header
  344. parser.endLine();
  345. specParser.endLine(); //ignore header
  346. specParser.endLine();
  347. std::vector<JsonNode> h3Data;
  348. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  349. {
  350. JsonNode heroData;
  351. heroData["texts"]["name"].String() = parser.readString();
  352. heroData["texts"]["biography"].String() = bioParser.readString();
  353. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  354. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  355. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  356. heroData["images"]["index"].Float() = i;
  357. for(int x=0;x<3;x++)
  358. {
  359. JsonNode armySlot;
  360. armySlot["min"].Float() = parser.readNumber();
  361. armySlot["max"].Float() = parser.readNumber();
  362. armySlot["creature"].String() = genRefName(parser.readString());
  363. heroData["army"].Vector().push_back(armySlot);
  364. }
  365. parser.endLine();
  366. specParser.endLine();
  367. bioParser.endLine();
  368. h3Data.push_back(heroData);
  369. }
  370. // Load heroes information
  371. heroes.resize(GameConstants::HEROES_QUANTITY);
  372. const JsonNode gameConf(ResourceID("config/gameConfig.json"));
  373. JsonNode config(JsonUtils::assembleFromFiles(gameConf["heroes"].convertTo<std::vector<std::string> >()));
  374. BOOST_FOREACH(auto &entry, config.Struct())
  375. {
  376. ui32 identifier = entry.second["id"].Float();
  377. JsonUtils::merge(h3Data[identifier], entry.second);
  378. CHero * hero = loadHero(h3Data[identifier]);
  379. hero->ID = identifier;
  380. heroes[identifier] = hero;
  381. VLC->modh->identifiers.registerObject("hero." + entry.first, identifier);
  382. }
  383. for (size_t i=0; i < heroes.size(); i++)
  384. {
  385. if (heroes[i] == nullptr)
  386. tlog0 << "Warning: hero with id " << i << " is missing!\n";
  387. }
  388. }
  389. void CHeroHandler::loadBallistics()
  390. {
  391. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  392. ballParser.endLine(); //header
  393. ballParser.endLine();
  394. do
  395. {
  396. ballParser.readString();
  397. ballParser.readString();
  398. CHeroHandler::SBallisticsLevelInfo bli;
  399. bli.keep = ballParser.readNumber();
  400. bli.tower = ballParser.readNumber();
  401. bli.gate = ballParser.readNumber();
  402. bli.wall = ballParser.readNumber();
  403. bli.shots = ballParser.readNumber();
  404. bli.noDmg = ballParser.readNumber();
  405. bli.oneDmg = ballParser.readNumber();
  406. bli.twoDmg = ballParser.readNumber();
  407. bli.sum = ballParser.readNumber();
  408. ballistics.push_back(bli);
  409. }
  410. while (ballParser.endLine());
  411. }
  412. ui32 CHeroHandler::level (ui64 experience) const
  413. {
  414. return boost::range::upper_bound(expPerLevel, experience) - boost::begin(expPerLevel);
  415. }
  416. ui64 CHeroHandler::reqExp (ui32 level) const
  417. {
  418. if(!level)
  419. return 0;
  420. if (level <= expPerLevel.size())
  421. {
  422. return expPerLevel[level-1];
  423. }
  424. else
  425. {
  426. tlog3 << "A hero has reached unsupported amount of experience\n";
  427. return expPerLevel[expPerLevel.size()-1];
  428. }
  429. }
  430. void CHeroHandler::loadTerrains()
  431. {
  432. const JsonNode config(ResourceID("config/terrains.json"));
  433. terrCosts.reserve(GameConstants::TERRAIN_TYPES);
  434. BOOST_FOREACH(const std::string & name, GameConstants::TERRAIN_NAMES)
  435. terrCosts.push_back(config[name]["moveCost"].Float());
  436. }
  437. std::vector<bool> CHeroHandler::getDefaultAllowedHeroes() const
  438. {
  439. // Look Data/HOTRAITS.txt for reference
  440. std::vector<bool> allowedHeroes;
  441. allowedHeroes.reserve(heroes.size());
  442. BOOST_FOREACH(const CHero * hero, heroes)
  443. {
  444. allowedHeroes.push_back(!hero->special);
  445. }
  446. return allowedHeroes;
  447. }
  448. std::vector<bool> CHeroHandler::getDefaultAllowedAbilities() const
  449. {
  450. std::vector<bool> allowedAbilities;
  451. allowedAbilities.resize(GameConstants::SKILL_QUANTITY, true);
  452. return allowedAbilities;
  453. }