CCreatureHandler.cpp 40 KB

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