CCreatureHandler.cpp 40 KB

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