CCreatureHandler.cpp 40 KB

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