CCreatureHandler.cpp 41 KB

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