CCreatureHandler.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  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. //FIXME: MOD COMPATIBILITY
  740. if (config["abilities"].getType() == JsonNode::JsonType::DATA_STRUCT)
  741. {
  742. for(const auto & ability : config["abilities"].Struct())
  743. {
  744. if (!ability.second.isNull())
  745. {
  746. auto b = JsonUtils::parseBonus(ability.second, creature->getBonusTextID(ability.first));
  747. b->source = BonusSource::CREATURE_ABILITY;
  748. b->sid = BonusSourceID(creature->getId());
  749. b->duration = BonusDuration::PERMANENT;
  750. creature->addNewBonus(b);
  751. }
  752. }
  753. }
  754. else
  755. {
  756. for(const JsonNode &ability : config["abilities"].Vector())
  757. {
  758. if(ability.getType() == JsonNode::JsonType::DATA_VECTOR)
  759. {
  760. logMod->error("Ignored outdated creature ability format in %s", creature->getJsonKey());
  761. }
  762. else
  763. {
  764. auto b = JsonUtils::parseBonus(ability);
  765. b->source = BonusSource::CREATURE_ABILITY;
  766. b->sid = BonusSourceID(creature->getId());
  767. b->duration = BonusDuration::PERMANENT;
  768. creature->addNewBonus(b);
  769. }
  770. }
  771. }
  772. LIBRARY->identifiers()->requestIdentifier("faction", config["faction"], [=](si32 faction)
  773. {
  774. creature->faction = FactionID(faction);
  775. });
  776. for(const JsonNode &value : config["upgrades"].Vector())
  777. {
  778. LIBRARY->identifiers()->requestIdentifier("creature", value, [=](si32 identifier)
  779. {
  780. creature->upgrades.insert(CreatureID(identifier));
  781. });
  782. }
  783. creature->animation.projectileImageName = AnimationPath::fromJson(config["graphics"]["missile"]["projectile"]);
  784. for(const JsonNode & value : config["graphics"]["missile"]["ray"].Vector())
  785. {
  786. CCreature::CreatureAnimation::RayColor color;
  787. color.start.r = value["start"].Vector()[0].Integer();
  788. color.start.g = value["start"].Vector()[1].Integer();
  789. color.start.b = value["start"].Vector()[2].Integer();
  790. color.start.a = value["start"].Vector()[3].Integer();
  791. color.end.r = value["end"].Vector()[0].Integer();
  792. color.end.g = value["end"].Vector()[1].Integer();
  793. color.end.b = value["end"].Vector()[2].Integer();
  794. color.end.a = value["end"].Vector()[3].Integer();
  795. creature->animation.projectileRay.push_back(color);
  796. }
  797. creature->special = config["special"].Bool() || config["disabled"].Bool();
  798. creature->excludeFromRandomization = config["excludeFromRandomization"].Bool();
  799. const JsonNode & sounds = config["sound"];
  800. creature->sounds.attack = AudioPath::fromJson(sounds["attack"]);
  801. creature->sounds.defend = AudioPath::fromJson(sounds["defend"]);
  802. creature->sounds.killed = AudioPath::fromJson(sounds["killed"]);
  803. creature->sounds.move = AudioPath::fromJson(sounds["move"]);
  804. creature->sounds.shoot = AudioPath::fromJson(sounds["shoot"]);
  805. creature->sounds.wince = AudioPath::fromJson(sounds["wince"]);
  806. creature->sounds.startMoving = AudioPath::fromJson(sounds["startMoving"]);
  807. creature->sounds.endMoving = AudioPath::fromJson(sounds["endMoving"]);
  808. }
  809. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input) const
  810. {
  811. for (const JsonNode &exp : input.Vector())
  812. {
  813. const JsonVector &values = exp["values"].Vector();
  814. int lowerLimit = 1;//, upperLimit = 255;
  815. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  816. {
  817. for (const JsonNode &val : values)
  818. {
  819. if(val.Bool())
  820. {
  821. // parse each bonus separately
  822. // we can not create copies since identifiers resolution does not tracks copies
  823. // leading to unset identifier values in copies
  824. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  825. bonus->source = BonusSource::STACK_EXPERIENCE;
  826. bonus->duration = BonusDuration::PERMANENT;
  827. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  828. creature->addNewBonus (bonus);
  829. break; //TODO: allow bonuses to turn off?
  830. }
  831. ++lowerLimit;
  832. }
  833. }
  834. else
  835. {
  836. int lastVal = 0;
  837. for (const JsonNode &val : values)
  838. {
  839. if (val.Integer() != lastVal)
  840. {
  841. JsonNode bonusInput = exp["bonus"];
  842. bonusInput["val"].Float() = val.Integer() - lastVal;
  843. auto bonus = JsonUtils::parseBonus (bonusInput);
  844. bonus->source = BonusSource::STACK_EXPERIENCE;
  845. bonus->duration = BonusDuration::PERMANENT;
  846. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  847. creature->addNewBonus (bonus);
  848. }
  849. lastVal = static_cast<int>(val.Float());
  850. ++lowerLimit;
  851. }
  852. }
  853. }
  854. }
  855. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) const//help function for parsing CREXPBON.txt
  856. {
  857. bool enable = false; //some bonuses are activated with values 2 or 1
  858. std::string buf = parser.readString();
  859. std::string mod = parser.readString();
  860. switch (buf[0])
  861. {
  862. case 'H':
  863. b.type = BonusType::STACK_HEALTH;
  864. b.valType = BonusValueType::PERCENT_TO_BASE;
  865. break;
  866. case 'A':
  867. b.type = BonusType::PRIMARY_SKILL;
  868. b.subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  869. break;
  870. case 'D':
  871. b.type = BonusType::PRIMARY_SKILL;
  872. b.subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  873. break;
  874. case 'M': //Max damage
  875. b.type = BonusType::CREATURE_DAMAGE;
  876. b.subtype = BonusCustomSubtype::creatureDamageMax;
  877. break;
  878. case 'm': //Min damage
  879. b.type = BonusType::CREATURE_DAMAGE;
  880. b.subtype = BonusCustomSubtype::creatureDamageMin;
  881. break;
  882. case 'S':
  883. b.type = BonusType::STACKS_SPEED; break;
  884. case 'O':
  885. b.type = BonusType::SHOTS; break;
  886. case 'b':
  887. b.type = BonusType::ENEMY_DEFENCE_REDUCTION; break;
  888. case 'C':
  889. b.type = BonusType::CHANGES_SPELL_COST_FOR_ALLY; break;
  890. case 'd':
  891. b.type = BonusType::DEFENSIVE_STANCE; break;
  892. case 'e':
  893. b.type = BonusType::DOUBLE_DAMAGE_CHANCE;
  894. break;
  895. case 'E':
  896. b.type = BonusType::DEATH_STARE;
  897. b.subtype = BonusCustomSubtype::deathStareGorgon;
  898. break;
  899. case 'F':
  900. b.type = BonusType::FEAR; break;
  901. case 'g':
  902. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  903. b.subtype = BonusSubtypeID(SpellSchool::ANY);
  904. break;
  905. case 'P':
  906. b.type = BonusType::CASTS; break;
  907. case 'R':
  908. b.type = BonusType::ADDITIONAL_RETALIATION; break;
  909. case 'W':
  910. b.type = BonusType::MAGIC_RESISTANCE;
  911. break;
  912. case 'f': //on-off skill
  913. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  914. switch (mod[0])
  915. {
  916. case 'A':
  917. b.type = BonusType::ATTACKS_ALL_ADJACENT; break;
  918. case 'b':
  919. b.type = BonusType::RETURN_AFTER_STRIKE; break;
  920. case 'B':
  921. b.type = BonusType::TWO_HEX_ATTACK_BREATH; break;
  922. case 'c':
  923. b.type = BonusType::JOUSTING;
  924. b.val = 5;
  925. break;
  926. case 'D':
  927. b.type = BonusType::ADDITIONAL_ATTACK; break;
  928. case 'f':
  929. b.type = BonusType::FEARLESS; break;
  930. case 'F':
  931. b.type = BonusType::FLYING; break;
  932. case 'm':
  933. b.type = BonusType::MORALE;
  934. b.val = 1;
  935. b.valType = BonusValueType::INDEPENDENT_MAX;
  936. break;
  937. case 'M':
  938. b.type = BonusType::NO_MORALE; break;
  939. case 'p': //Mind spells
  940. case 'P':
  941. b.type = BonusType::MIND_IMMUNITY; break;
  942. case 'r':
  943. b.type = BonusType::REBIRTH; //on/off? makes sense?
  944. b.subtype = BonusCustomSubtype::rebirthRegular;
  945. b.val = 20; //arbitrary value
  946. break;
  947. case 'R':
  948. b.type = BonusType::BLOCKS_RETALIATION; break;
  949. case 's':
  950. b.type = BonusType::FREE_SHOOTING; break;
  951. case 'u':
  952. b.type = BonusType::SPELL_RESISTANCE_AURA; break;
  953. case 'U':
  954. b.type = BonusType::UNDEAD; break;
  955. default:
  956. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  957. return;
  958. break;
  959. }
  960. break;
  961. case 'w': //specific spell immunities, enabled/disabled
  962. enable = true;
  963. switch (mod[0])
  964. {
  965. case 'B': //Blind
  966. b.type = BonusType::SPELL_IMMUNITY;
  967. b.subtype = BonusSubtypeID(SpellID(SpellID::BLIND));
  968. b.additionalInfo = 0;//normal immunity
  969. break;
  970. case 'H': //Hypnotize
  971. b.type = BonusType::SPELL_IMMUNITY;
  972. b.subtype = BonusSubtypeID(SpellID(SpellID::HYPNOTIZE));
  973. b.additionalInfo = 0;//normal immunity
  974. break;
  975. case 'I': //Implosion
  976. b.type = BonusType::SPELL_IMMUNITY;
  977. b.subtype = BonusSubtypeID(SpellID(SpellID::IMPLOSION));
  978. b.additionalInfo = 0;//normal immunity
  979. break;
  980. case 'K': //Berserk
  981. b.type = BonusType::SPELL_IMMUNITY;
  982. b.subtype = BonusSubtypeID(SpellID(SpellID::BERSERK));
  983. b.additionalInfo = 0;//normal immunity
  984. break;
  985. case 'M': //Meteor Shower
  986. b.type = BonusType::SPELL_IMMUNITY;
  987. b.subtype = BonusSubtypeID(SpellID(SpellID::METEOR_SHOWER));
  988. b.additionalInfo = 0;//normal immunity
  989. break;
  990. case 'N': //dispel beneficial spells
  991. b.type = BonusType::SPELL_IMMUNITY;
  992. b.subtype = BonusSubtypeID(SpellID(SpellID::DISPEL_HELPFUL_SPELLS));
  993. b.additionalInfo = 0;//normal immunity
  994. break;
  995. case 'R': //Armageddon
  996. b.type = BonusType::SPELL_IMMUNITY;
  997. b.subtype = BonusSubtypeID(SpellID(SpellID::ARMAGEDDON));
  998. b.additionalInfo = 0;//normal immunity
  999. break;
  1000. case 'S': //Slow
  1001. b.type = BonusType::SPELL_IMMUNITY;
  1002. b.subtype = BonusSubtypeID(SpellID(SpellID::SLOW));
  1003. b.additionalInfo = 0;//normal immunity
  1004. break;
  1005. case '6':
  1006. case '7':
  1007. case '8':
  1008. case '9':
  1009. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  1010. b.val = std::atoi(mod.c_str()) - 5;
  1011. break;
  1012. case ':':
  1013. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  1014. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  1015. break;
  1016. case 'F':
  1017. b.type = BonusType::NEGATIVE_EFFECTS_IMMUNITY;
  1018. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1019. break;
  1020. case 'O':
  1021. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1022. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1023. b.val = 100; //Full damage immunity
  1024. break;
  1025. case 'f':
  1026. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1027. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1028. break;
  1029. case 'C':
  1030. b.type = BonusType::NEGATIVE_EFFECTS_IMMUNITY;
  1031. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1032. break;
  1033. case 'W':
  1034. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1035. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1036. b.val = 100; //Full damage immunity
  1037. break;
  1038. case 'w':
  1039. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1040. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1041. break;
  1042. case 'E':
  1043. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1044. b.subtype = BonusSubtypeID(SpellSchool::EARTH);
  1045. b.val = 100; //Full damage immunity
  1046. break;
  1047. case 'e':
  1048. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1049. b.subtype = BonusSubtypeID(SpellSchool::EARTH);
  1050. break;
  1051. case 'A':
  1052. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1053. b.subtype = BonusSubtypeID(SpellSchool::AIR);
  1054. b.val = 100; //Full damage immunity
  1055. break;
  1056. case 'a':
  1057. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1058. b.subtype = BonusSubtypeID(SpellSchool::AIR);
  1059. break;
  1060. case 'D':
  1061. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1062. b.subtype = BonusSubtypeID(SpellSchool::ANY);
  1063. b.val = 100; //Full damage immunity
  1064. break;
  1065. case '0':
  1066. b.type = BonusType::RECEPTIVE;
  1067. break;
  1068. case 'm':
  1069. b.type = BonusType::MIND_IMMUNITY;
  1070. break;
  1071. default:
  1072. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1073. return;
  1074. }
  1075. break;
  1076. case 'i':
  1077. enable = true;
  1078. b.type = BonusType::NO_DISTANCE_PENALTY;
  1079. break;
  1080. case 'o':
  1081. enable = true;
  1082. b.type = BonusType::NO_WALL_PENALTY;
  1083. break;
  1084. case 'a':
  1085. case 'c':
  1086. case 'K':
  1087. case 'k':
  1088. b.type = BonusType::SPELL_AFTER_ATTACK;
  1089. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1090. break;
  1091. case 'h':
  1092. b.type = BonusType::HATE;
  1093. b.subtype = BonusSubtypeID(CreatureID(stringToNumber(mod)));
  1094. break;
  1095. case 'p':
  1096. case 'J':
  1097. b.type = BonusType::SPELL_BEFORE_ATTACK;
  1098. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1099. b.additionalInfo = 3; //always expert?
  1100. break;
  1101. case 'r':
  1102. b.type = BonusType::HP_REGENERATION;
  1103. b.val = stringToNumber(mod);
  1104. break;
  1105. case 's':
  1106. b.type = BonusType::ENCHANTED;
  1107. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1108. b.valType = BonusValueType::INDEPENDENT_MAX;
  1109. break;
  1110. default:
  1111. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1112. return;
  1113. break;
  1114. }
  1115. switch (mod[0])
  1116. {
  1117. case '+':
  1118. case '=': //should we allow percent values to stack or pick highest?
  1119. b.valType = BonusValueType::ADDITIVE_VALUE;
  1120. break;
  1121. }
  1122. //limiters, range
  1123. si32 lastVal;
  1124. si32 curVal;
  1125. si32 lastLev = 0;
  1126. if (enable) //0 and 2 means non-active, 1 - active
  1127. {
  1128. if (b.type != BonusType::REBIRTH)
  1129. b.val = 0; //on-off ability, no value specified
  1130. parser.readNumber(); // 0 level is never active
  1131. for (int i = 1; i < 11; ++i)
  1132. {
  1133. curVal = static_cast<si32>(parser.readNumber());
  1134. if (curVal == 1)
  1135. {
  1136. b.limiter.reset (new RankRangeLimiter(i));
  1137. bl.push_back(std::make_shared<Bonus>(b));
  1138. break; //never turned off it seems
  1139. }
  1140. }
  1141. }
  1142. else
  1143. {
  1144. lastVal = static_cast<si32>(parser.readNumber());
  1145. if (b.type == BonusType::HATE)
  1146. lastVal *= 10; //odd fix
  1147. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1148. for (int i = 1; i < 11; ++i)
  1149. {
  1150. curVal = static_cast<si32>(parser.readNumber());
  1151. if (b.type == BonusType::HATE)
  1152. curVal *= 10; //odd fix
  1153. if (curVal > lastVal) //threshold, add new bonus
  1154. {
  1155. b.val = curVal - lastVal;
  1156. lastVal = curVal;
  1157. b.limiter.reset (new RankRangeLimiter(i));
  1158. bl.push_back(std::make_shared<Bonus>(b));
  1159. lastLev = i; //start new range from here, i = previous rank
  1160. }
  1161. else if (curVal < lastVal)
  1162. {
  1163. b.val = lastVal;
  1164. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1165. }
  1166. }
  1167. }
  1168. }
  1169. int CCreatureHandler::stringToNumber(std::string & s) const
  1170. {
  1171. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1172. return std::atoi(s.c_str());
  1173. }
  1174. CCreatureHandler::~CCreatureHandler()
  1175. {
  1176. for(auto & p : skillRequirements)
  1177. p.first.clear();
  1178. }
  1179. void CCreatureHandler::afterLoadFinalization()
  1180. {
  1181. }
  1182. std::set<CreatureID> CCreatureHandler::getDefaultAllowed() const
  1183. {
  1184. std::set<CreatureID> result;
  1185. for(auto & creature : objects)
  1186. if (creature && !creature->special)
  1187. result.insert(creature->getId());
  1188. return result;
  1189. }
  1190. VCMI_LIB_NAMESPACE_END