CCreatureHandler.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. /*
  2. * CCreatureHandler.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 "CCreatureHandler.h"
  12. #include "CGeneralTextHandler.h"
  13. #include "ResourceSet.h"
  14. #include "filesystem/Filesystem.h"
  15. #include "VCMI_Lib.h"
  16. #include "CGameState.h"
  17. #include "CTownHandler.h"
  18. #include "CModHandler.h"
  19. #include "GameSettings.h"
  20. #include "StringConstants.h"
  21. #include "bonuses/Limiters.h"
  22. #include "bonuses/Updaters.h"
  23. #include "serializer/JsonDeserializer.h"
  24. #include "serializer/JsonUpdater.h"
  25. #include "mapObjectConstructors/AObjectTypeHandler.h"
  26. #include "mapObjectConstructors/CObjectClassesHandler.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. const std::map<CCreature::CreatureQuantityId, std::string> CCreature::creatureQuantityRanges =
  29. {
  30. {CCreature::CreatureQuantityId::FEW, "1-4"},
  31. {CCreature::CreatureQuantityId::SEVERAL, "5-9"},
  32. {CCreature::CreatureQuantityId::PACK, "10-19"},
  33. {CCreature::CreatureQuantityId::LOTS, "20-49"},
  34. {CCreature::CreatureQuantityId::HORDE, "50-99"},
  35. {CCreature::CreatureQuantityId::THRONG, "100-249"},
  36. {CCreature::CreatureQuantityId::SWARM, "250-499"},
  37. {CCreature::CreatureQuantityId::ZOUNDS, "500-999"},
  38. {CCreature::CreatureQuantityId::LEGION, "1000+"}
  39. };
  40. int32_t CCreature::getIndex() const
  41. {
  42. return idNumber.toEnum();
  43. }
  44. int32_t CCreature::getIconIndex() const
  45. {
  46. return iconIndex;
  47. }
  48. std::string CCreature::getJsonKey() const
  49. {
  50. return modScope + ':' + identifier;
  51. }
  52. void CCreature::registerIcons(const IconRegistar & cb) const
  53. {
  54. cb(getIconIndex(), 0, "CPRSMALL", smallIconName);
  55. cb(getIconIndex(), 0, "TWCRPORT", largeIconName);
  56. }
  57. CreatureID CCreature::getId() const
  58. {
  59. return idNumber;
  60. }
  61. const IBonusBearer * CCreature::getBonusBearer() const
  62. {
  63. return this;
  64. }
  65. int32_t CCreature::getAdvMapAmountMin() const
  66. {
  67. return ammMin;
  68. }
  69. int32_t CCreature::getAdvMapAmountMax() const
  70. {
  71. return ammMax;
  72. }
  73. int32_t CCreature::getAIValue() const
  74. {
  75. return AIValue;
  76. }
  77. int32_t CCreature::getFightValue() const
  78. {
  79. return fightValue;
  80. }
  81. int32_t CCreature::getLevel() const
  82. {
  83. return level;
  84. }
  85. int32_t CCreature::getGrowth() const
  86. {
  87. return growth;
  88. }
  89. int32_t CCreature::getHorde() const
  90. {
  91. return hordeGrowth;
  92. }
  93. FactionID CCreature::getFaction() const
  94. {
  95. return FactionID(faction);
  96. }
  97. int32_t CCreature::getBaseAttack() const
  98. {
  99. static const auto SELECTOR = Selector::typeSubtype(BonusType::PRIMARY_SKILL, PrimarySkill::ATTACK).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  100. return getExportedBonusList().valOfBonuses(SELECTOR);
  101. }
  102. int32_t CCreature::getBaseDefense() const
  103. {
  104. static const auto SELECTOR = Selector::typeSubtype(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  105. return getExportedBonusList().valOfBonuses(SELECTOR);
  106. }
  107. int32_t CCreature::getBaseDamageMin() const
  108. {
  109. static const auto SELECTOR = Selector::typeSubtype(BonusType::CREATURE_DAMAGE, 1).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  110. return getExportedBonusList().valOfBonuses(SELECTOR);
  111. }
  112. int32_t CCreature::getBaseDamageMax() const
  113. {
  114. static const auto SELECTOR = Selector::typeSubtype(BonusType::CREATURE_DAMAGE, 2).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  115. return getExportedBonusList().valOfBonuses(SELECTOR);
  116. }
  117. int32_t CCreature::getBaseHitPoints() const
  118. {
  119. static const auto SELECTOR = Selector::type()(BonusType::STACK_HEALTH).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  120. return getExportedBonusList().valOfBonuses(SELECTOR);
  121. }
  122. int32_t CCreature::getBaseSpellPoints() const
  123. {
  124. static const auto SELECTOR = Selector::type()(BonusType::CASTS).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  125. return getExportedBonusList().valOfBonuses(SELECTOR);
  126. }
  127. int32_t CCreature::getBaseSpeed() const
  128. {
  129. static const auto SELECTOR = Selector::type()(BonusType::STACKS_SPEED).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  130. return getExportedBonusList().valOfBonuses(SELECTOR);
  131. }
  132. int32_t CCreature::getBaseShots() const
  133. {
  134. static const auto SELECTOR = Selector::type()(BonusType::SHOTS).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  135. return getExportedBonusList().valOfBonuses(SELECTOR);
  136. }
  137. int32_t CCreature::getRecruitCost(GameResID resIndex) const
  138. {
  139. if(resIndex >= 0 && resIndex < cost.size())
  140. return cost[resIndex];
  141. else
  142. return 0;
  143. }
  144. TResources CCreature::getFullRecruitCost() const
  145. {
  146. return cost;
  147. }
  148. bool CCreature::hasUpgrades() const
  149. {
  150. return !upgrades.empty();
  151. }
  152. std::string CCreature::getNameTranslated() const
  153. {
  154. return getNameSingularTranslated();
  155. }
  156. std::string CCreature::getNamePluralTranslated() const
  157. {
  158. return VLC->generaltexth->translate(getNamePluralTextID());
  159. }
  160. std::string CCreature::getNameSingularTranslated() const
  161. {
  162. return VLC->generaltexth->translate(getNameSingularTextID());
  163. }
  164. std::string CCreature::getNameTextID() const
  165. {
  166. return getNameSingularTextID();
  167. }
  168. std::string CCreature::getNamePluralTextID() const
  169. {
  170. return TextIdentifier("creatures", modScope, identifier, "name", "plural" ).get();
  171. }
  172. std::string CCreature::getNameSingularTextID() const
  173. {
  174. return TextIdentifier("creatures", modScope, identifier, "name", "singular" ).get();
  175. }
  176. CCreature::CreatureQuantityId CCreature::getQuantityID(const int & quantity)
  177. {
  178. if (quantity<5)
  179. return CCreature::CreatureQuantityId::FEW;
  180. if (quantity<10)
  181. return CCreature::CreatureQuantityId::SEVERAL;
  182. if (quantity<20)
  183. return CCreature::CreatureQuantityId::PACK;
  184. if (quantity<50)
  185. return CCreature::CreatureQuantityId::LOTS;
  186. if (quantity<100)
  187. return CCreature::CreatureQuantityId::HORDE;
  188. if (quantity<250)
  189. return CCreature::CreatureQuantityId::THRONG;
  190. if (quantity<500)
  191. return CCreature::CreatureQuantityId::SWARM;
  192. if (quantity<1000)
  193. return CCreature::CreatureQuantityId::ZOUNDS;
  194. return CCreature::CreatureQuantityId::LEGION;
  195. }
  196. std::string CCreature::getQuantityRangeStringForId(const CCreature::CreatureQuantityId & quantityId)
  197. {
  198. if(creatureQuantityRanges.find(quantityId) != creatureQuantityRanges.end())
  199. return creatureQuantityRanges.at(quantityId);
  200. logGlobal->error("Wrong quantityId: %d", (int)quantityId);
  201. assert(0);
  202. return "[ERROR]";
  203. }
  204. int CCreature::estimateCreatureCount(ui32 countID)
  205. {
  206. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  207. if(countID > 9)
  208. {
  209. logGlobal->error("Wrong countID %d!", countID);
  210. return 0;
  211. }
  212. else
  213. return creature_count[countID];
  214. }
  215. bool CCreature::isDoubleWide() const
  216. {
  217. return doubleWide;
  218. }
  219. /**
  220. * Determines if the creature is of a good alignment.
  221. * @return true if the creture is good, false otherwise.
  222. */
  223. bool CCreature::isGood () const
  224. {
  225. return VLC->factions()->getByIndex(faction)->getAlignment() == EAlignment::GOOD;
  226. }
  227. /**
  228. * Determines if the creature is of an evil alignment.
  229. * @return true if the creature is evil, false otherwise.
  230. */
  231. bool CCreature::isEvil () const
  232. {
  233. return VLC->factions()->getByIndex(faction)->getAlignment() == EAlignment::EVIL;
  234. }
  235. si32 CCreature::maxAmount(const TResources &res) const //how many creatures can be bought
  236. {
  237. int ret = 2147483645;
  238. int resAmnt = static_cast<int>(std::min(res.size(),cost.size()));
  239. for(int i=0;i<resAmnt;i++)
  240. if(cost[i])
  241. ret = std::min(ret, (res[i] / cost[i]));
  242. return ret;
  243. }
  244. CCreature::CCreature()
  245. {
  246. setNodeType(CBonusSystemNode::CREATURE);
  247. fightValue = AIValue = growth = hordeGrowth = ammMin = ammMax = 0;
  248. }
  249. void CCreature::addBonus(int val, BonusType type, int subtype)
  250. {
  251. auto selector = Selector::typeSubtype(type, subtype).And(Selector::source(BonusSource::CREATURE_ABILITY, getIndex()));
  252. BonusList & exported = getExportedBonusList();
  253. BonusList existing;
  254. exported.getBonuses(existing, selector, Selector::all);
  255. if(existing.empty())
  256. {
  257. auto added = std::make_shared<Bonus>(BonusDuration::PERMANENT, type, BonusSource::CREATURE_ABILITY, val, getIndex(), subtype, BonusValueType::BASE_NUMBER);
  258. addNewBonus(added);
  259. }
  260. else
  261. {
  262. std::shared_ptr<Bonus> b = existing[0];
  263. b->val = val;
  264. }
  265. }
  266. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  267. {
  268. //TODO upgrade of upgrade?
  269. return vstd::contains(upgrades, anotherCre->getId());
  270. }
  271. bool CCreature::valid() const
  272. {
  273. return this == VLC->creh->objects[idNumber];
  274. }
  275. std::string CCreature::nodeName() const
  276. {
  277. return "\"" + getNamePluralTextID() + "\"";
  278. }
  279. void CCreature::updateFrom(const JsonNode & data)
  280. {
  281. JsonUpdater handler(nullptr, data);
  282. {
  283. auto configScope = handler.enterStruct("config");
  284. const JsonNode & configNode = handler.getCurrent();
  285. serializeJson(handler);
  286. if(!configNode["hitPoints"].isNull())
  287. addBonus(configNode["hitPoints"].Integer(), BonusType::STACK_HEALTH);
  288. if(!configNode["speed"].isNull())
  289. addBonus(configNode["speed"].Integer(), BonusType::STACKS_SPEED);
  290. if(!configNode["attack"].isNull())
  291. addBonus(configNode["attack"].Integer(), BonusType::PRIMARY_SKILL, PrimarySkill::ATTACK);
  292. if(!configNode["defense"].isNull())
  293. addBonus(configNode["defense"].Integer(), BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  294. if(!configNode["damage"]["min"].isNull())
  295. addBonus(configNode["damage"]["min"].Integer(), BonusType::CREATURE_DAMAGE, 1);
  296. if(!configNode["damage"]["max"].isNull())
  297. addBonus(configNode["damage"]["max"].Integer(), BonusType::CREATURE_DAMAGE, 2);
  298. if(!configNode["shots"].isNull())
  299. addBonus(configNode["shots"].Integer(), BonusType::SHOTS);
  300. if(!configNode["spellPoints"].isNull())
  301. addBonus(configNode["spellPoints"].Integer(), BonusType::CASTS);
  302. }
  303. handler.serializeBonuses("bonuses", this);
  304. }
  305. void CCreature::serializeJson(JsonSerializeFormat & handler)
  306. {
  307. handler.serializeInt("fightValue", fightValue);
  308. handler.serializeInt("aiValue", AIValue);
  309. handler.serializeInt("growth", growth);
  310. handler.serializeInt("horde", hordeGrowth);// Needed at least until configurable buildings
  311. {
  312. auto advMapNode = handler.enterStruct("advMapAmount");
  313. handler.serializeInt("min", ammMin);
  314. handler.serializeInt("max", ammMax);
  315. }
  316. if(handler.updating)
  317. {
  318. cost.serializeJson(handler, "cost");
  319. handler.serializeInt("faction", faction);//TODO: unify with deferred resolve
  320. }
  321. handler.serializeInt("level", level);
  322. handler.serializeBool("doubleWide", doubleWide);
  323. if(!handler.saving)
  324. {
  325. if(ammMin > ammMax)
  326. logMod->error("Invalid creature '%s' configuration, advMapAmount.min > advMapAmount.max", identifier);
  327. }
  328. }
  329. CCreatureHandler::CCreatureHandler()
  330. : expAfterUpgrade(0)
  331. {
  332. VLC->creh = this;
  333. loadCommanders();
  334. }
  335. const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const
  336. {
  337. std::optional<si32> index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier);
  338. if(!index)
  339. throw std::runtime_error("Creature not found "+identifier);
  340. return objects[*index];
  341. }
  342. void CCreatureHandler::loadCommanders()
  343. {
  344. ResourceID configResource("config/commanders.json");
  345. std::string modSource = VLC->modh->findResourceOrigin(configResource);
  346. JsonNode data(configResource);
  347. data.setMeta(modSource);
  348. const JsonNode & config = data; // switch to const data accessors
  349. for (auto bonus : config["bonusPerLevel"].Vector())
  350. {
  351. commanderLevelPremy.push_back(JsonUtils::parseBonus(bonus.Vector()));
  352. }
  353. int i = 0;
  354. for (auto skill : config["skillLevels"].Vector())
  355. {
  356. skillLevels.emplace_back();
  357. for (auto skillLevel : skill["levels"].Vector())
  358. {
  359. skillLevels[i].push_back(static_cast<ui8>(skillLevel.Float()));
  360. }
  361. ++i;
  362. }
  363. for (auto ability : config["abilityRequirements"].Vector())
  364. {
  365. std::pair <std::shared_ptr<Bonus>, std::pair <ui8, ui8> > a;
  366. a.first = JsonUtils::parseBonus (ability["ability"].Vector());
  367. a.second.first = static_cast<ui8>(ability["skills"].Vector()[0].Float());
  368. a.second.second = static_cast<ui8>(ability["skills"].Vector()[1].Float());
  369. skillRequirements.push_back (a);
  370. }
  371. }
  372. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses) const
  373. {
  374. auto makeBonusNode = [&](const std::string & type, double val = 0) -> JsonNode
  375. {
  376. JsonNode ret;
  377. ret["type"].String() = type;
  378. ret["val"].Float() = val;
  379. return ret;
  380. };
  381. static const std::map<std::string, JsonNode> abilityMap =
  382. {
  383. {"FLYING_ARMY", makeBonusNode("FLYING")},
  384. {"SHOOTING_ARMY", makeBonusNode("SHOOTER")},
  385. {"SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON")},
  386. {"const_free_attack", makeBonusNode("BLOCKS_RETALIATION")},
  387. {"IS_UNDEAD", makeBonusNode("UNDEAD")},
  388. {"const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY")},
  389. {"const_jousting", makeBonusNode("JOUSTING", 5)},
  390. {"KING_1", makeBonusNode("KING")}, // Slayer with no expertise
  391. {"KING_2", makeBonusNode("KING", 2)}, // Advanced Slayer or better
  392. {"KING_3", makeBonusNode("KING", 3)}, // Expert Slayer only
  393. {"const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY")},
  394. {"MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT")},
  395. {"IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY")},
  396. {"HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH")}
  397. };
  398. auto hasAbility = [&](const std::string & name) -> bool
  399. {
  400. return boost::algorithm::find_first(bonuses, name);
  401. };
  402. for(const auto & a : abilityMap)
  403. {
  404. if(hasAbility(a.first))
  405. creature["abilities"][a.first] = a.second;
  406. }
  407. if(hasAbility("DOUBLE_WIDE"))
  408. creature["doubleWide"].Bool() = true;
  409. if(hasAbility("const_raises_morale"))
  410. {
  411. JsonNode node = makeBonusNode("MORALE");
  412. node["val"].Float() = 1;
  413. node["propagator"].String() = "HERO";
  414. creature["abilities"]["const_raises_morale"] = node;
  415. }
  416. }
  417. std::vector<JsonNode> CCreatureHandler::loadLegacyData()
  418. {
  419. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_CREATURE);
  420. objects.resize(dataSize);
  421. std::vector<JsonNode> h3Data;
  422. h3Data.reserve(dataSize);
  423. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  424. parser.endLine(); // header
  425. // this file is a bit different in some of Russian localisations:
  426. //ENG: Singular Plural Wood ...
  427. //RUS: Singular Plural Plural2 Wood ...
  428. // Try to detect which version this is by header
  429. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  430. size_t namesCount = 2;
  431. {
  432. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  433. throw std::runtime_error("Incorrect format of CrTraits.txt");
  434. if (parser.readString() == "Plural2")
  435. namesCount = 3;
  436. parser.endLine();
  437. }
  438. for (size_t i=0; i<dataSize; i++)
  439. {
  440. //loop till non-empty line
  441. while (parser.isNextEntryEmpty())
  442. parser.endLine();
  443. JsonNode data;
  444. data["name"]["singular"].String() = parser.readString();
  445. if (namesCount == 3)
  446. parser.readString();
  447. data["name"]["plural"].String() = parser.readString();
  448. for(int v=0; v<7; ++v)
  449. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  450. data["fightValue"].Float() = parser.readNumber();
  451. data["aiValue"].Float() = parser.readNumber();
  452. data["growth"].Float() = parser.readNumber();
  453. data["horde"].Float() = parser.readNumber();
  454. data["hitPoints"].Float() = parser.readNumber();
  455. data["speed"].Float() = parser.readNumber();
  456. data["attack"].Float() = parser.readNumber();
  457. data["defense"].Float() = parser.readNumber();
  458. data["damage"]["min"].Float() = parser.readNumber();
  459. data["damage"]["max"].Float() = parser.readNumber();
  460. if (float shots = parser.readNumber())
  461. data["shots"].Float() = shots;
  462. if (float spells = parser.readNumber())
  463. data["spellPoints"].Float() = spells;
  464. data["advMapAmount"]["min"].Float() = parser.readNumber();
  465. data["advMapAmount"]["max"].Float() = parser.readNumber();
  466. data["abilityText"].String() = parser.readString();
  467. loadBonuses(data, parser.readString()); //Attributes
  468. h3Data.push_back(data);
  469. }
  470. loadAnimationInfo(h3Data);
  471. return h3Data;
  472. }
  473. CCreature * CCreatureHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  474. {
  475. assert(identifier.find(':') == std::string::npos);
  476. assert(!scope.empty());
  477. auto * cre = new CCreature();
  478. if(node["hasDoubleWeek"].Bool())
  479. {
  480. doubledCreatures.insert(CreatureID(index));
  481. }
  482. cre->idNumber = CreatureID(index);
  483. cre->iconIndex = cre->getIndex() + 2;
  484. cre->identifier = identifier;
  485. cre->modScope = scope;
  486. JsonDeserializer handler(nullptr, node);
  487. cre->serializeJson(handler);
  488. cre->cost = ResourceSet(node["cost"]);
  489. VLC->generaltexth->registerString(scope, cre->getNameSingularTextID(), node["name"]["singular"].String());
  490. VLC->generaltexth->registerString(scope, cre->getNamePluralTextID(), node["name"]["plural"].String());
  491. cre->addBonus(node["hitPoints"].Integer(), BonusType::STACK_HEALTH);
  492. cre->addBonus(node["speed"].Integer(), BonusType::STACKS_SPEED);
  493. cre->addBonus(node["attack"].Integer(), BonusType::PRIMARY_SKILL, PrimarySkill::ATTACK);
  494. cre->addBonus(node["defense"].Integer(), BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  495. cre->addBonus(node["damage"]["min"].Integer(), BonusType::CREATURE_DAMAGE, 1);
  496. cre->addBonus(node["damage"]["max"].Integer(), BonusType::CREATURE_DAMAGE, 2);
  497. assert(node["damage"]["min"].Integer() <= node["damage"]["max"].Integer());
  498. if(!node["shots"].isNull())
  499. cre->addBonus(node["shots"].Integer(), BonusType::SHOTS);
  500. loadStackExperience(cre, node["stackExperience"]);
  501. loadJsonAnimation(cre, node["graphics"]);
  502. loadCreatureJson(cre, node);
  503. for(const auto & extraName : node["extraNames"].Vector())
  504. {
  505. for(const auto & type_name : getTypeNames())
  506. registerObject(scope, type_name, extraName.String(), cre->getIndex());
  507. }
  508. JsonNode advMapFile = node["graphics"]["map"];
  509. JsonNode advMapMask = node["graphics"]["mapMask"];
  510. VLC->modh->identifiers.requestIdentifier(scope, "object", "monster", [=](si32 index)
  511. {
  512. JsonNode conf;
  513. conf.setMeta(scope);
  514. VLC->objtypeh->loadSubObject(cre->identifier, conf, Obj::MONSTER, cre->getId().num);
  515. if (!advMapFile.isNull())
  516. {
  517. JsonNode templ;
  518. templ["animation"] = advMapFile;
  519. if (!advMapMask.isNull())
  520. templ["mask"] = advMapMask;
  521. templ.setMeta(scope);
  522. // if creature has custom advMapFile, reset any potentially imported H3M templates and use provided file instead
  523. VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->getId().num)->clearTemplates();
  524. VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->getId().num)->addTemplate(templ);
  525. }
  526. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  527. if (VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->getId().num)->getTemplates().empty())
  528. VLC->objtypeh->removeSubObject(Obj::MONSTER, cre->getId().num);
  529. });
  530. return cre;
  531. }
  532. const std::vector<std::string> & CCreatureHandler::getTypeNames() const
  533. {
  534. static const std::vector<std::string> typeNames = { "creature" };
  535. return typeNames;
  536. }
  537. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  538. {
  539. std::vector<bool> ret;
  540. ret.reserve(objects.size());
  541. for(const CCreature * crea : objects)
  542. {
  543. ret.push_back(crea ? !crea->special : false);
  544. }
  545. return ret;
  546. }
  547. void CCreatureHandler::loadCrExpMod()
  548. {
  549. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) //reading default stack experience values
  550. {
  551. //Calculate rank exp values, formula appears complicated bu no parsing needed
  552. expRanks.resize(8);
  553. int dif = 0;
  554. int it = 8000; //ignore name of this variable
  555. expRanks[0].push_back(it);
  556. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  557. {
  558. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  559. dif += it/5;
  560. }
  561. for (int i = 1; i < 8; ++i) //used for tiers 1-7
  562. {
  563. dif = 0;
  564. it = 1000 * i;
  565. expRanks[i].push_back(it);
  566. for (int j = 1; j < 10; ++j)
  567. {
  568. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  569. dif += it/5;
  570. }
  571. }
  572. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  573. expBonParser.endLine(); //header
  574. maxExpPerBattle.resize(8);
  575. for (int i = 1; i < 8; ++i)
  576. {
  577. expBonParser.readString(); //index
  578. expBonParser.readString(); //float multiplier -> hardcoded
  579. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  580. expBonParser.readString(); //already calculated
  581. maxExpPerBattle[i] = static_cast<ui32>(expBonParser.readNumber());
  582. expRanks[i].push_back(expRanks[i].back() + static_cast<ui32>(expBonParser.readNumber()));
  583. expBonParser.endLine();
  584. }
  585. //skeleton gets exp penalty
  586. objects[56].get()->addBonus(-50, BonusType::EXP_MULTIPLIER, -1);
  587. objects[57].get()->addBonus(-50, BonusType::EXP_MULTIPLIER, -1);
  588. //exp for tier >7, rank 11
  589. expRanks[0].push_back(147000);
  590. expAfterUpgrade = 75; //percent
  591. maxExpPerBattle[0] = maxExpPerBattle[7];
  592. }
  593. }
  594. void CCreatureHandler::loadCrExpBon(CBonusSystemNode & globalEffects)
  595. {
  596. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) //reading default stack experience bonuses
  597. {
  598. logGlobal->debug("\tLoading stack experience bonuses");
  599. auto addBonusForAllCreatures = [&](std::shared_ptr<Bonus> b) {
  600. auto limiter = std::make_shared<CreatureLevelLimiter>();
  601. b->addLimiter(limiter);
  602. globalEffects.addNewBonus(b);
  603. };
  604. auto addBonusForTier = [&](int tier, std::shared_ptr<Bonus> b) {
  605. assert(vstd::iswithin(tier, 1, 7));
  606. //bonuses from level 7 are given to high-level creatures too
  607. auto max = tier == GameConstants::CREATURES_PER_TOWN ? std::numeric_limits<int>::max() : tier + 1;
  608. auto limiter = std::make_shared<CreatureLevelLimiter>(tier, max);
  609. b->addLimiter(limiter);
  610. globalEffects.addNewBonus(b);
  611. };
  612. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  613. Bonus b; //prototype with some default properties
  614. b.source = BonusSource::STACK_EXPERIENCE;
  615. b.duration = BonusDuration::PERMANENT;
  616. b.valType = BonusValueType::ADDITIVE_VALUE;
  617. b.effectRange = BonusLimitEffect::NO_LIMIT;
  618. b.additionalInfo = 0;
  619. b.turnsRemain = 0;
  620. BonusList bl;
  621. parser.endLine();
  622. parser.readString(); //ignore index
  623. loadStackExp(b, bl, parser);
  624. for(const auto & b : bl)
  625. addBonusForAllCreatures(b); //health bonus is common for all
  626. parser.endLine();
  627. for (int i = 1; i < 7; ++i)
  628. {
  629. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  630. {
  631. parser.readString(); //ignore index
  632. bl.clear();
  633. loadStackExp(b, bl, parser);
  634. for(const auto & b : bl)
  635. addBonusForTier(i, b);
  636. parser.endLine();
  637. }
  638. }
  639. for (int j = 0; j < 4; ++j) //tier 7
  640. {
  641. parser.readString(); //ignore index
  642. bl.clear();
  643. loadStackExp(b, bl, parser);
  644. for(const auto & b : bl)
  645. addBonusForTier(7, b);
  646. parser.endLine();
  647. }
  648. do //parse everything that's left
  649. {
  650. auto sid = static_cast<ui32>(parser.readNumber()); //id = this particular creature ID
  651. b.sid = sid;
  652. bl.clear();
  653. loadStackExp(b, bl, parser);
  654. for(const auto & b : bl)
  655. {
  656. objects[sid]->addNewBonus(b); //add directly to CCreature Node
  657. }
  658. }
  659. while (parser.endLine());
  660. }//end of Stack Experience
  661. }
  662. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data) const
  663. {
  664. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  665. parser.endLine(); // header
  666. parser.endLine();
  667. for(int dd = 0; dd < VLC->settings()->getInteger(EGameSettings::TEXTS_CREATURE); ++dd)
  668. {
  669. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  670. ;
  671. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  672. parser.endLine();
  673. }
  674. }
  675. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser) const
  676. {
  677. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  678. JsonNode & animationTime = graphics["animationTime"];
  679. animationTime["walk"].Float() = parser.readNumber();
  680. animationTime["attack"].Float() = parser.readNumber();
  681. parser.readNumber(); // unused value "Flight animation time" - H3 actually uses "Walk animation time" even for flying creatures
  682. animationTime["idle"].Float() = 10.0;
  683. JsonNode & missile = graphics["missile"];
  684. JsonNode & offsets = missile["offset"];
  685. offsets["upperX"].Float() = parser.readNumber();
  686. offsets["upperY"].Float() = parser.readNumber();
  687. offsets["middleX"].Float() = parser.readNumber();
  688. offsets["middleY"].Float() = parser.readNumber();
  689. offsets["lowerX"].Float() = parser.readNumber();
  690. offsets["lowerY"].Float() = parser.readNumber();
  691. for(int i=0; i<12; i++)
  692. {
  693. JsonNode entry;
  694. entry.Float() = parser.readNumber();
  695. missile["frameAngles"].Vector().push_back(entry);
  696. }
  697. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  698. missile["attackClimaxFrame"].Float() = parser.readNumber();
  699. // assume that creature is not a shooter and should not have whole missile field
  700. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  701. missile["attackClimaxFrame"].Float() == 0)
  702. graphics.Struct().erase("missile");
  703. }
  704. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics) const
  705. {
  706. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  707. cre->animation.troopCountLocationOffset = static_cast<int>(graphics["troopCountLocationOffset"].Float());
  708. const JsonNode & animationTime = graphics["animationTime"];
  709. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  710. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  711. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  712. const JsonNode & missile = graphics["missile"];
  713. const JsonNode & offsets = missile["offset"];
  714. cre->animation.upperRightMissleOffsetX = static_cast<int>(offsets["upperX"].Float());
  715. cre->animation.upperRightMissleOffsetY = static_cast<int>(offsets["upperY"].Float());
  716. cre->animation.rightMissleOffsetX = static_cast<int>(offsets["middleX"].Float());
  717. cre->animation.rightMissleOffsetY = static_cast<int>(offsets["middleY"].Float());
  718. cre->animation.lowerRightMissleOffsetX = static_cast<int>(offsets["lowerX"].Float());
  719. cre->animation.lowerRightMissleOffsetY = static_cast<int>(offsets["lowerY"].Float());
  720. cre->animation.attackClimaxFrame = static_cast<int>(missile["attackClimaxFrame"].Float());
  721. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  722. cre->smallIconName = graphics["iconSmall"].String();
  723. cre->largeIconName = graphics["iconLarge"].String();
  724. }
  725. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config) const
  726. {
  727. creature->animDefName = config["graphics"]["animation"].String();
  728. //FIXME: MOD COMPATIBILITY
  729. if (config["abilities"].getType() == JsonNode::JsonType::DATA_STRUCT)
  730. {
  731. for(const auto & ability : config["abilities"].Struct())
  732. {
  733. if (!ability.second.isNull())
  734. {
  735. auto b = JsonUtils::parseBonus(ability.second);
  736. b->source = BonusSource::CREATURE_ABILITY;
  737. b->sid = creature->getIndex();
  738. b->duration = BonusDuration::PERMANENT;
  739. creature->addNewBonus(b);
  740. }
  741. }
  742. }
  743. else
  744. {
  745. for(const JsonNode &ability : config["abilities"].Vector())
  746. {
  747. if(ability.getType() == JsonNode::JsonType::DATA_VECTOR)
  748. {
  749. logMod->error("Ignored outdated creature ability format in %s", creature->getJsonKey());
  750. }
  751. else
  752. {
  753. auto b = JsonUtils::parseBonus(ability);
  754. b->source = BonusSource::CREATURE_ABILITY;
  755. b->sid = creature->getIndex();
  756. b->duration = BonusDuration::PERMANENT;
  757. creature->addNewBonus(b);
  758. }
  759. }
  760. }
  761. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  762. {
  763. creature->faction = FactionID(faction);
  764. });
  765. for(const JsonNode &value : config["upgrades"].Vector())
  766. {
  767. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  768. {
  769. creature->upgrades.insert(CreatureID(identifier));
  770. });
  771. }
  772. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  773. for(const JsonNode & value : config["graphics"]["missile"]["ray"].Vector())
  774. {
  775. CCreature::CreatureAnimation::RayColor color;
  776. color.start.r = value["start"].Vector()[0].Integer();
  777. color.start.g = value["start"].Vector()[1].Integer();
  778. color.start.b = value["start"].Vector()[2].Integer();
  779. color.start.a = value["start"].Vector()[3].Integer();
  780. color.end.r = value["end"].Vector()[0].Integer();
  781. color.end.g = value["end"].Vector()[1].Integer();
  782. color.end.b = value["end"].Vector()[2].Integer();
  783. color.end.a = value["end"].Vector()[3].Integer();
  784. creature->animation.projectileRay.push_back(color);
  785. }
  786. creature->special = config["special"].Bool() || config["disabled"].Bool();
  787. const JsonNode & sounds = config["sound"];
  788. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  789. GET_SOUND_VALUE(attack);
  790. GET_SOUND_VALUE(defend);
  791. GET_SOUND_VALUE(killed);
  792. GET_SOUND_VALUE(move);
  793. GET_SOUND_VALUE(shoot);
  794. GET_SOUND_VALUE(wince);
  795. GET_SOUND_VALUE(startMoving);
  796. GET_SOUND_VALUE(endMoving);
  797. #undef GET_SOUND_VALUE
  798. }
  799. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input) const
  800. {
  801. for (const JsonNode &exp : input.Vector())
  802. {
  803. const JsonVector &values = exp["values"].Vector();
  804. int lowerLimit = 1;//, upperLimit = 255;
  805. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  806. {
  807. for (const JsonNode &val : values)
  808. {
  809. if(val.Bool())
  810. {
  811. // parse each bonus separately
  812. // we can not create copies since identifiers resolution does not tracks copies
  813. // leading to unset identifier values in copies
  814. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  815. bonus->source = BonusSource::STACK_EXPERIENCE;
  816. bonus->duration = BonusDuration::PERMANENT;
  817. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  818. creature->addNewBonus (bonus);
  819. break; //TODO: allow bonuses to turn off?
  820. }
  821. ++lowerLimit;
  822. }
  823. }
  824. else
  825. {
  826. int lastVal = 0;
  827. for (const JsonNode &val : values)
  828. {
  829. if (val.Float() != lastVal)
  830. {
  831. JsonNode bonusInput = exp["bonus"];
  832. bonusInput["val"].Float() = static_cast<int>(val.Float()) - lastVal;
  833. auto bonus = JsonUtils::parseBonus (bonusInput);
  834. bonus->source = BonusSource::STACK_EXPERIENCE;
  835. bonus->duration = BonusDuration::PERMANENT;
  836. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  837. creature->addNewBonus (bonus);
  838. }
  839. lastVal = static_cast<int>(val.Float());
  840. ++lowerLimit;
  841. }
  842. }
  843. }
  844. }
  845. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) const//help function for parsing CREXPBON.txt
  846. {
  847. bool enable = false; //some bonuses are activated with values 2 or 1
  848. std::string buf = parser.readString();
  849. std::string mod = parser.readString();
  850. switch (buf[0])
  851. {
  852. case 'H':
  853. b.type = BonusType::STACK_HEALTH;
  854. b.valType = BonusValueType::PERCENT_TO_BASE;
  855. break;
  856. case 'A':
  857. b.type = BonusType::PRIMARY_SKILL;
  858. b.subtype = PrimarySkill::ATTACK;
  859. break;
  860. case 'D':
  861. b.type = BonusType::PRIMARY_SKILL;
  862. b.subtype = PrimarySkill::DEFENSE;
  863. break;
  864. case 'M': //Max damage
  865. b.type = BonusType::CREATURE_DAMAGE;
  866. b.subtype = 2;
  867. break;
  868. case 'm': //Min damage
  869. b.type = BonusType::CREATURE_DAMAGE;
  870. b.subtype = 1;
  871. break;
  872. case 'S':
  873. b.type = BonusType::STACKS_SPEED; break;
  874. case 'O':
  875. b.type = BonusType::SHOTS; break;
  876. case 'b':
  877. b.type = BonusType::ENEMY_DEFENCE_REDUCTION; break;
  878. case 'C':
  879. b.type = BonusType::CHANGES_SPELL_COST_FOR_ALLY; break;
  880. case 'd':
  881. b.type = BonusType::DEFENSIVE_STANCE; break;
  882. case 'e':
  883. b.type = BonusType::DOUBLE_DAMAGE_CHANCE;
  884. b.subtype = 0;
  885. break;
  886. case 'E':
  887. b.type = BonusType::DEATH_STARE;
  888. b.subtype = 0; //Gorgon
  889. break;
  890. case 'F':
  891. b.type = BonusType::FEAR; break;
  892. case 'g':
  893. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  894. b.subtype = SpellSchool(ESpellSchool::ANY);
  895. break;
  896. case 'P':
  897. b.type = BonusType::CASTS; break;
  898. case 'R':
  899. b.type = BonusType::ADDITIONAL_RETALIATION; break;
  900. case 'W':
  901. b.type = BonusType::MAGIC_RESISTANCE;
  902. b.subtype = 0; //otherwise creature window goes crazy
  903. break;
  904. case 'f': //on-off skill
  905. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  906. switch (mod[0])
  907. {
  908. case 'A':
  909. b.type = BonusType::ATTACKS_ALL_ADJACENT; break;
  910. case 'b':
  911. b.type = BonusType::RETURN_AFTER_STRIKE; break;
  912. case 'B':
  913. b.type = BonusType::TWO_HEX_ATTACK_BREATH; break;
  914. case 'c':
  915. b.type = BonusType::JOUSTING;
  916. b.val = 5;
  917. break;
  918. case 'D':
  919. b.type = BonusType::ADDITIONAL_ATTACK; break;
  920. case 'f':
  921. b.type = BonusType::FEARLESS; break;
  922. case 'F':
  923. b.type = BonusType::FLYING; break;
  924. case 'm':
  925. b.type = BonusType::MORALE; break;
  926. b.val = 1;
  927. b.valType = BonusValueType::INDEPENDENT_MAX;
  928. break;
  929. case 'M':
  930. b.type = BonusType::NO_MORALE; break;
  931. case 'p': //Mind spells
  932. case 'P':
  933. b.type = BonusType::MIND_IMMUNITY; break;
  934. case 'r':
  935. b.type = BonusType::REBIRTH; //on/off? makes sense?
  936. b.subtype = 0;
  937. b.val = 20; //arbitrary value
  938. break;
  939. case 'R':
  940. b.type = BonusType::BLOCKS_RETALIATION; break;
  941. case 's':
  942. b.type = BonusType::FREE_SHOOTING; break;
  943. case 'u':
  944. b.type = BonusType::SPELL_RESISTANCE_AURA; break;
  945. case 'U':
  946. b.type = BonusType::UNDEAD; break;
  947. default:
  948. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  949. return;
  950. break;
  951. }
  952. break;
  953. case 'w': //specific spell immunities, enabled/disabled
  954. enable = true;
  955. switch (mod[0])
  956. {
  957. case 'B': //Blind
  958. b.type = BonusType::SPELL_IMMUNITY;
  959. b.subtype = SpellID::BLIND;
  960. b.additionalInfo = 0;//normal immunity
  961. break;
  962. case 'H': //Hypnotize
  963. b.type = BonusType::SPELL_IMMUNITY;
  964. b.subtype = SpellID::HYPNOTIZE;
  965. b.additionalInfo = 0;//normal immunity
  966. break;
  967. case 'I': //Implosion
  968. b.type = BonusType::SPELL_IMMUNITY;
  969. b.subtype = SpellID::IMPLOSION;
  970. b.additionalInfo = 0;//normal immunity
  971. break;
  972. case 'K': //Berserk
  973. b.type = BonusType::SPELL_IMMUNITY;
  974. b.subtype = SpellID::BERSERK;
  975. b.additionalInfo = 0;//normal immunity
  976. break;
  977. case 'M': //Meteor Shower
  978. b.type = BonusType::SPELL_IMMUNITY;
  979. b.subtype = SpellID::METEOR_SHOWER;
  980. b.additionalInfo = 0;//normal immunity
  981. break;
  982. case 'N': //dispell beneficial spells
  983. b.type = BonusType::SPELL_IMMUNITY;
  984. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  985. b.additionalInfo = 0;//normal immunity
  986. break;
  987. case 'R': //Armageddon
  988. b.type = BonusType::SPELL_IMMUNITY;
  989. b.subtype = SpellID::ARMAGEDDON;
  990. b.additionalInfo = 0;//normal immunity
  991. break;
  992. case 'S': //Slow
  993. b.type = BonusType::SPELL_IMMUNITY;
  994. b.subtype = SpellID::SLOW;
  995. b.additionalInfo = 0;//normal immunity
  996. break;
  997. case '6':
  998. case '7':
  999. case '8':
  1000. case '9':
  1001. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  1002. b.val = std::atoi(mod.c_str()) - 5;
  1003. break;
  1004. case ':':
  1005. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  1006. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  1007. break;
  1008. case 'F':
  1009. b.type = BonusType::FIRE_IMMUNITY;
  1010. b.subtype = 1; //not positive
  1011. break;
  1012. case 'O':
  1013. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1014. b.subtype = SpellSchool(ESpellSchool::FIRE);
  1015. b.val = 100; //Full damage immunity
  1016. break;
  1017. case 'f':
  1018. b.type = BonusType::FIRE_IMMUNITY;
  1019. b.subtype = 0; //all
  1020. break;
  1021. case 'C':
  1022. b.type = BonusType::WATER_IMMUNITY;
  1023. b.subtype = 1; //not positive
  1024. break;
  1025. case 'W':
  1026. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1027. b.subtype = SpellSchool(ESpellSchool::WATER);
  1028. b.val = 100; //Full damage immunity
  1029. break;
  1030. case 'w':
  1031. b.type = BonusType::WATER_IMMUNITY;
  1032. b.subtype = 0; //all
  1033. break;
  1034. case 'E':
  1035. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1036. b.subtype = SpellSchool(ESpellSchool::EARTH);
  1037. b.val = 100; //Full damage immunity
  1038. break;
  1039. case 'e':
  1040. b.type = BonusType::EARTH_IMMUNITY;
  1041. b.subtype = 0; //all
  1042. break;
  1043. case 'A':
  1044. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1045. b.subtype = SpellSchool(ESpellSchool::AIR);
  1046. b.val = 100; //Full damage immunity
  1047. break;
  1048. case 'a':
  1049. b.type = BonusType::AIR_IMMUNITY;
  1050. b.subtype = 0; //all
  1051. break;
  1052. case 'D':
  1053. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1054. b.subtype = SpellSchool(ESpellSchool::ANY);
  1055. b.val = 100; //Full damage immunity
  1056. break;
  1057. case '0':
  1058. b.type = BonusType::RECEPTIVE;
  1059. break;
  1060. case 'm':
  1061. b.type = BonusType::MIND_IMMUNITY;
  1062. break;
  1063. default:
  1064. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1065. return;
  1066. }
  1067. break;
  1068. case 'i':
  1069. enable = true;
  1070. b.type = BonusType::NO_DISTANCE_PENALTY;
  1071. break;
  1072. case 'o':
  1073. enable = true;
  1074. b.type = BonusType::NO_WALL_PENALTY;
  1075. break;
  1076. case 'a':
  1077. case 'c':
  1078. case 'K':
  1079. case 'k':
  1080. b.type = BonusType::SPELL_AFTER_ATTACK;
  1081. b.subtype = stringToNumber(mod);
  1082. break;
  1083. case 'h':
  1084. b.type = BonusType::HATE;
  1085. b.subtype = stringToNumber(mod);
  1086. break;
  1087. case 'p':
  1088. case 'J':
  1089. b.type = BonusType::SPELL_BEFORE_ATTACK;
  1090. b.subtype = stringToNumber(mod);
  1091. b.additionalInfo = 3; //always expert?
  1092. break;
  1093. case 'r':
  1094. b.type = BonusType::HP_REGENERATION;
  1095. b.val = stringToNumber(mod);
  1096. break;
  1097. case 's':
  1098. b.type = BonusType::ENCHANTED;
  1099. b.subtype = stringToNumber(mod);
  1100. b.valType = BonusValueType::INDEPENDENT_MAX;
  1101. break;
  1102. default:
  1103. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1104. return;
  1105. break;
  1106. }
  1107. switch (mod[0])
  1108. {
  1109. case '+':
  1110. case '=': //should we allow percent values to stack or pick highest?
  1111. b.valType = BonusValueType::ADDITIVE_VALUE;
  1112. break;
  1113. }
  1114. //limiters, range
  1115. si32 lastVal;
  1116. si32 curVal;
  1117. si32 lastLev = 0;
  1118. if (enable) //0 and 2 means non-active, 1 - active
  1119. {
  1120. if (b.type != BonusType::REBIRTH)
  1121. b.val = 0; //on-off ability, no value specified
  1122. parser.readNumber(); // 0 level is never active
  1123. for (int i = 1; i < 11; ++i)
  1124. {
  1125. curVal = static_cast<si32>(parser.readNumber());
  1126. if (curVal == 1)
  1127. {
  1128. b.limiter.reset (new RankRangeLimiter(i));
  1129. bl.push_back(std::make_shared<Bonus>(b));
  1130. break; //never turned off it seems
  1131. }
  1132. }
  1133. }
  1134. else
  1135. {
  1136. lastVal = static_cast<si32>(parser.readNumber());
  1137. if (b.type == BonusType::HATE)
  1138. lastVal *= 10; //odd fix
  1139. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1140. for (int i = 1; i < 11; ++i)
  1141. {
  1142. curVal = static_cast<si32>(parser.readNumber());
  1143. if (b.type == BonusType::HATE)
  1144. curVal *= 10; //odd fix
  1145. if (curVal > lastVal) //threshold, add new bonus
  1146. {
  1147. b.val = curVal - lastVal;
  1148. lastVal = curVal;
  1149. b.limiter.reset (new RankRangeLimiter(i));
  1150. bl.push_back(std::make_shared<Bonus>(b));
  1151. lastLev = i; //start new range from here, i = previous rank
  1152. }
  1153. else if (curVal < lastVal)
  1154. {
  1155. b.val = lastVal;
  1156. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1157. }
  1158. }
  1159. }
  1160. }
  1161. int CCreatureHandler::stringToNumber(std::string & s) const
  1162. {
  1163. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1164. return std::atoi(s.c_str());
  1165. }
  1166. CCreatureHandler::~CCreatureHandler()
  1167. {
  1168. for(auto & p : skillRequirements)
  1169. p.first = nullptr;
  1170. }
  1171. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1172. {
  1173. int r = 0;
  1174. if(tier == -1) //pick any allowed creature
  1175. {
  1176. do
  1177. {
  1178. r = (*RandomGeneratorUtil::nextItem(objects, rand))->getId();
  1179. } while (objects[r] && objects[r]->special); // find first "not special" creature
  1180. }
  1181. else
  1182. {
  1183. assert(vstd::iswithin(tier, 1, 7));
  1184. std::vector<CreatureID> allowed;
  1185. for(const auto & creature : objects)
  1186. {
  1187. if(!creature->special && creature->level == tier)
  1188. allowed.push_back(creature->getId());
  1189. }
  1190. if(allowed.empty())
  1191. {
  1192. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1193. return CreatureID::NONE;
  1194. }
  1195. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1196. }
  1197. assert (r >= 0); //should always be, but it crashed
  1198. return CreatureID(r);
  1199. }
  1200. void CCreatureHandler::afterLoadFinalization()
  1201. {
  1202. }
  1203. VCMI_LIB_NAMESPACE_END