CCreatureHandler.cpp 40 KB

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