CCreatureHandler.cpp 40 KB

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