CCreatureHandler.cpp 40 KB

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