CCreatureHandler.cpp 40 KB

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