CHeroHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. * CHeroHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CHeroHandler.h"
  12. #include "CHero.h"
  13. #include "../../GameLibrary.h"
  14. #include "../../constants/StringConstants.h"
  15. #include "../../CCreatureHandler.h"
  16. #include "../../IGameSettings.h"
  17. #include "../../bonuses/Limiters.h"
  18. #include "../../bonuses/Updaters.h"
  19. #include "../../json/JsonBonus.h"
  20. #include "../../json/JsonUtils.h"
  21. #include "../../modding/IdentifierStorage.h"
  22. #include "../../texts/CGeneralTextHandler.h"
  23. #include "../../texts/CLegacyConfigParser.h"
  24. VCMI_LIB_NAMESPACE_BEGIN
  25. CHeroHandler::~CHeroHandler() = default;
  26. CHeroHandler::CHeroHandler()
  27. {
  28. loadExperience();
  29. }
  30. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  31. {
  32. static const std::vector<std::string> typeNames = { "hero" };
  33. return typeNames;
  34. }
  35. std::shared_ptr<CHero> CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  36. {
  37. assert(identifier.find(':') == std::string::npos);
  38. assert(!scope.empty());
  39. auto hero = std::make_shared<CHero>();
  40. hero->ID = HeroTypeID(index);
  41. hero->identifier = identifier;
  42. hero->modScope = scope;
  43. hero->gender = node["female"].Bool() ? EHeroGender::FEMALE : EHeroGender::MALE;
  44. hero->special = node["special"].Bool();
  45. //Default - both false
  46. hero->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  47. hero->onlyOnMapWithoutWater = node["onlyOnMapWithoutWater"].Bool();
  48. LIBRARY->generaltexth->registerString(scope, hero->getNameTextID(), node["texts"]["name"]);
  49. LIBRARY->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"]);
  50. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"]);
  51. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"]);
  52. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"]);
  53. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  54. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  55. hero->portraitSmall = node["images"]["small"].String();
  56. hero->portraitLarge = node["images"]["large"].String();
  57. hero->battleImage = AnimationPath::fromJson(node["battleImage"]);
  58. loadHeroArmy(hero.get(), node);
  59. loadHeroSkills(hero.get(), node);
  60. loadHeroSpecialty(hero.get(), node);
  61. LIBRARY->identifiers()->requestIdentifier("heroClass", node["class"],
  62. [=](si32 classID)
  63. {
  64. hero->heroClass = HeroClassID(classID).toHeroClass();
  65. });
  66. return hero;
  67. }
  68. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node) const
  69. {
  70. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  71. hero->initialArmy.resize(node["army"].Vector().size());
  72. for (size_t i=0; i< hero->initialArmy.size(); i++)
  73. {
  74. const JsonNode & source = node["army"].Vector()[i];
  75. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  76. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  77. if (hero->initialArmy[i].minAmount > hero->initialArmy[i].maxAmount)
  78. {
  79. logMod->error("Hero %s has minimal army size (%d) greater than maximal size (%d)!", hero->getJsonKey(), hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  80. std::swap(hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  81. }
  82. LIBRARY->identifiers()->requestIdentifier("creature", source["creature"], [=](si32 creature)
  83. {
  84. hero->initialArmy[i].creature = CreatureID(creature);
  85. });
  86. }
  87. }
  88. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node) const
  89. {
  90. for(const JsonNode &set : node["skills"].Vector())
  91. {
  92. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  93. if (skillLevel < MasteryLevel::LEVELS_SIZE)
  94. {
  95. size_t currentIndex = hero->secSkillsInit.size();
  96. hero->secSkillsInit.emplace_back(SecondarySkill(-1), skillLevel);
  97. LIBRARY->identifiers()->requestIdentifier("skill", set["skill"], [=](si32 id)
  98. {
  99. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  100. });
  101. }
  102. else
  103. {
  104. logMod->error("Unknown skill level: %s", set["level"].String());
  105. }
  106. }
  107. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  108. hero->haveSpellBook = !node["spellbook"].isNull();
  109. for(const JsonNode & spell : node["spellbook"].Vector())
  110. {
  111. LIBRARY->identifiers()->requestIdentifier("spell", spell,
  112. [=](si32 spellID)
  113. {
  114. hero->spells.insert(SpellID(spellID));
  115. });
  116. }
  117. }
  118. /// creates standard H3 hero specialty for creatures
  119. static std::vector<std::shared_ptr<Bonus>> createCreatureSpecialty(CreatureID baseCreatureID)
  120. {
  121. std::vector<std::shared_ptr<Bonus>> result;
  122. std::set<CreatureID> targets;
  123. targets.insert(baseCreatureID);
  124. // go through entire upgrade chain and collect all creatures to which baseCreatureID can be upgraded
  125. for (;;)
  126. {
  127. std::set<CreatureID> oldTargets = targets;
  128. for(const auto & upgradeSourceID : oldTargets)
  129. {
  130. const CCreature * upgradeSource = upgradeSourceID.toCreature();
  131. targets.insert(upgradeSource->upgrades.begin(), upgradeSource->upgrades.end());
  132. }
  133. if (oldTargets.size() == targets.size())
  134. break;
  135. }
  136. for(CreatureID cid : targets)
  137. {
  138. const auto & specCreature = *cid.toCreature();
  139. int stepSize = specCreature.getLevel() ? specCreature.getLevel() : 5;
  140. {
  141. auto bonus = std::make_shared<Bonus>();
  142. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  143. bonus->type = BonusType::STACKS_SPEED;
  144. bonus->val = 1;
  145. result.push_back(bonus);
  146. }
  147. {
  148. auto bonus = std::make_shared<Bonus>();
  149. bonus->type = BonusType::PRIMARY_SKILL;
  150. bonus->subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  151. bonus->val = 0;
  152. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  153. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  154. result.push_back(bonus);
  155. }
  156. {
  157. auto bonus = std::make_shared<Bonus>();
  158. bonus->type = BonusType::PRIMARY_SKILL;
  159. bonus->subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  160. bonus->val = 0;
  161. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  162. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  163. result.push_back(bonus);
  164. }
  165. }
  166. return result;
  167. }
  168. void CHeroHandler::beforeValidate(JsonNode & object)
  169. {
  170. //handle "base" specialty info
  171. JsonNode & specialtyNode = object["specialty"];
  172. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  173. {
  174. const JsonNode & base = specialtyNode["base"];
  175. if(!base.isNull())
  176. {
  177. if(specialtyNode["bonuses"].isNull())
  178. {
  179. logMod->warn("specialty has base without bonuses");
  180. }
  181. else
  182. {
  183. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  184. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  185. JsonUtils::inherit(bonuses[keyValue.first], base);
  186. }
  187. }
  188. }
  189. }
  190. void CHeroHandler::afterLoadFinalization()
  191. {
  192. for(const auto & functor : callAfterLoadFinalization)
  193. functor();
  194. callAfterLoadFinalization.clear();
  195. }
  196. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  197. {
  198. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  199. {
  200. bonus->duration = BonusDuration::PERMANENT;
  201. bonus->source = BonusSource::HERO_SPECIAL;
  202. bonus->sid = BonusSourceID(hero->getId());
  203. return bonus;
  204. };
  205. //new format, using bonus system
  206. const JsonNode & specialtyNode = node["specialty"];
  207. if(specialtyNode.getType() != JsonNode::JsonType::DATA_STRUCT)
  208. {
  209. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  210. return;
  211. }
  212. //creature specialty - alias for simplicity
  213. if(!specialtyNode["creature"].isNull())
  214. {
  215. JsonNode creatureNode = specialtyNode["creature"];
  216. std::function<void()> specialtyLoader = [creatureNode, hero, prepSpec]
  217. {
  218. LIBRARY->identifiers()->requestIdentifier("creature", creatureNode, [hero, prepSpec](si32 creature)
  219. {
  220. for (const auto & bonus : createCreatureSpecialty(CreatureID(creature)))
  221. hero->specialty.push_back(prepSpec(bonus));
  222. });
  223. };
  224. callAfterLoadFinalization.push_back(specialtyLoader);
  225. }
  226. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  227. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  228. }
  229. void CHeroHandler::loadExperience()
  230. {
  231. expPerLevel.push_back(0);
  232. expPerLevel.push_back(1000);
  233. expPerLevel.push_back(2000);
  234. expPerLevel.push_back(3200);
  235. expPerLevel.push_back(4600);
  236. expPerLevel.push_back(6200);
  237. expPerLevel.push_back(8000);
  238. expPerLevel.push_back(10000);
  239. expPerLevel.push_back(12200);
  240. expPerLevel.push_back(14700);
  241. expPerLevel.push_back(17500);
  242. expPerLevel.push_back(20600);
  243. expPerLevel.push_back(24320);
  244. expPerLevel.push_back(28784);
  245. expPerLevel.push_back(34140);
  246. for (;;)
  247. {
  248. auto i = expPerLevel.size() - 1;
  249. auto currExp = expPerLevel[i];
  250. auto prevExp = expPerLevel[i-1];
  251. auto prevDiff = currExp - prevExp;
  252. auto nextDiff = prevDiff + prevDiff / 5;
  253. auto maxExp = std::numeric_limits<decltype(currExp)>::max();
  254. if (currExp > maxExp - nextDiff)
  255. break; // overflow point reached
  256. expPerLevel.push_back (currExp + nextDiff);
  257. }
  258. }
  259. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  260. static std::string genRefName(std::string input)
  261. {
  262. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  263. input[0] = std::tolower(input[0]); // to camelCase
  264. return input;
  265. }
  266. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  267. {
  268. size_t dataSize = LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_HERO);
  269. objects.resize(dataSize);
  270. std::vector<JsonNode> h3Data;
  271. h3Data.reserve(dataSize);
  272. CLegacyConfigParser specParser(TextPath::builtin("DATA/HEROSPEC.TXT"));
  273. CLegacyConfigParser bioParser(TextPath::builtin("DATA/HEROBIOS.TXT"));
  274. CLegacyConfigParser parser(TextPath::builtin("DATA/HOTRAITS.TXT"));
  275. parser.endLine(); //ignore header
  276. parser.endLine();
  277. specParser.endLine(); //ignore header
  278. specParser.endLine();
  279. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  280. {
  281. JsonNode heroData;
  282. heroData["texts"]["name"].String() = parser.readString();
  283. heroData["texts"]["biography"].String() = bioParser.readString();
  284. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  285. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  286. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  287. for(int x=0;x<3;x++)
  288. {
  289. JsonNode armySlot;
  290. armySlot["min"].Float() = parser.readNumber();
  291. armySlot["max"].Float() = parser.readNumber();
  292. armySlot["creature"].String() = genRefName(parser.readString());
  293. heroData["army"].Vector().push_back(armySlot);
  294. }
  295. parser.endLine();
  296. specParser.endLine();
  297. bioParser.endLine();
  298. h3Data.push_back(heroData);
  299. }
  300. return h3Data;
  301. }
  302. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  303. {
  304. size_t index = objects.size();
  305. static const int specialFramesCount = 2; // reserved for 2 special frames
  306. auto object = loadFromJson(scope, data, name, index);
  307. object->imageIndex = static_cast<si32>(index) + specialFramesCount;
  308. objects.emplace_back(object);
  309. registerObject(scope, "hero", name, object->getIndex());
  310. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  311. registerObject(scope, "hero", compatID.String(), object->getIndex());
  312. }
  313. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  314. {
  315. auto object = loadFromJson(scope, data, name, index);
  316. object->imageIndex = static_cast<si32>(index);
  317. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  318. objects[index] = object;
  319. registerObject(scope, "hero", name, object->getIndex());
  320. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  321. registerObject(scope, "hero", compatID.String(), object->getIndex());
  322. }
  323. ui32 CHeroHandler::level (TExpType experience) const
  324. {
  325. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  326. }
  327. TExpType CHeroHandler::reqExp (ui32 level) const
  328. {
  329. if(!level)
  330. return 0;
  331. if (level <= expPerLevel.size())
  332. {
  333. return expPerLevel[level-1];
  334. }
  335. else
  336. {
  337. logGlobal->warn("A hero has reached unsupported amount of experience");
  338. return expPerLevel[expPerLevel.size()-1];
  339. }
  340. }
  341. ui32 CHeroHandler::maxSupportedLevel() const
  342. {
  343. return expPerLevel.size();
  344. }
  345. std::set<HeroTypeID> CHeroHandler::getDefaultAllowed() const
  346. {
  347. std::set<HeroTypeID> result;
  348. for(auto & hero : objects)
  349. if (hero && !hero->special)
  350. result.insert(hero->getId());
  351. return result;
  352. }
  353. VCMI_LIB_NAMESPACE_END