CHeroHandler.cpp 15 KB

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