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