CHeroHandler.cpp 16 KB

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