CCreatureHandler.cpp 40 KB

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