CCreatureHandler.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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,(int)(res[i]/cost[i]));
  233. return ret;
  234. }
  235. CCreature::CCreature()
  236. {
  237. setNodeType(CBonusSystemNode::CREATURE);
  238. faction = 0;
  239. level = 0;
  240. fightValue = AIValue = growth = hordeGrowth = ammMin = ammMax = 0;
  241. doubleWide = false;
  242. special = true;
  243. iconIndex = -1;
  244. }
  245. void CCreature::addBonus(int val, Bonus::BonusType type, int subtype)
  246. {
  247. auto selector = Selector::typeSubtype(type, subtype).And(Selector::source(Bonus::CREATURE_ABILITY, getIndex()));
  248. BonusList & exported = getExportedBonusList();
  249. BonusList existing;
  250. exported.getBonuses(existing, selector, Selector::all);
  251. if(existing.empty())
  252. {
  253. auto added = std::make_shared<Bonus>(Bonus::PERMANENT, type, Bonus::CREATURE_ABILITY, val, getIndex(), subtype, Bonus::BASE_NUMBER);
  254. addNewBonus(added);
  255. }
  256. else
  257. {
  258. std::shared_ptr<Bonus> b = existing[0];
  259. b->val = val;
  260. }
  261. }
  262. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  263. {
  264. //TODO upgrade of upgrade?
  265. return vstd::contains(upgrades, anotherCre->idNumber);
  266. }
  267. bool CCreature::valid() const
  268. {
  269. return this == VLC->creh->objects[idNumber];
  270. }
  271. std::string CCreature::nodeName() const
  272. {
  273. return "\"" + getNamePluralTextID() + "\"";
  274. }
  275. bool CCreature::isItNativeTerrain(TerrainId terrain) const
  276. {
  277. auto native = getNativeTerrain();
  278. return native == terrain || native == ETerrainId::ANY_TERRAIN;
  279. }
  280. TerrainId CCreature::getNativeTerrain() const
  281. {
  282. const std::string cachingStringNoTerrainPenalty = "type_NO_TERRAIN_PENALTY";
  283. static const auto selectorNoTerrainPenalty = Selector::type()(Bonus::NO_TERRAIN_PENALTY);
  284. //this code is used in the CreatureTerrainLimiter::limit to setup battle bonuses
  285. //and in the CGHeroInstance::getNativeTerrain() to setup mevement bonuses or/and penalties.
  286. return hasBonus(selectorNoTerrainPenalty, selectorNoTerrainPenalty)
  287. ? TerrainId(ETerrainId::ANY_TERRAIN)
  288. : (*VLC->townh)[faction]->nativeTerrain;
  289. }
  290. void CCreature::updateFrom(const JsonNode & data)
  291. {
  292. JsonUpdater handler(nullptr, data);
  293. {
  294. auto configScope = handler.enterStruct("config");
  295. const JsonNode & configNode = handler.getCurrent();
  296. serializeJson(handler);
  297. if(!configNode["hitPoints"].isNull())
  298. addBonus(configNode["hitPoints"].Integer(), Bonus::STACK_HEALTH);
  299. if(!configNode["speed"].isNull())
  300. addBonus(configNode["speed"].Integer(), Bonus::STACKS_SPEED);
  301. if(!configNode["attack"].isNull())
  302. addBonus(configNode["attack"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  303. if(!configNode["defense"].isNull())
  304. addBonus(configNode["defense"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  305. if(!configNode["damage"]["min"].isNull())
  306. addBonus(configNode["damage"]["min"].Integer(), Bonus::CREATURE_DAMAGE, 1);
  307. if(!configNode["damage"]["max"].isNull())
  308. addBonus(configNode["damage"]["max"].Integer(), Bonus::CREATURE_DAMAGE, 2);
  309. if(!configNode["shots"].isNull())
  310. addBonus(configNode["shots"].Integer(), Bonus::SHOTS);
  311. if(!configNode["spellPoints"].isNull())
  312. addBonus(configNode["spellPoints"].Integer(), Bonus::CASTS);
  313. }
  314. handler.serializeBonuses("bonuses", this);
  315. }
  316. void CCreature::serializeJson(JsonSerializeFormat & handler)
  317. {
  318. handler.serializeInt("fightValue", fightValue);
  319. handler.serializeInt("aiValue", AIValue);
  320. handler.serializeInt("growth", growth);
  321. handler.serializeInt("horde", hordeGrowth);// Needed at least until configurable buildings
  322. {
  323. auto advMapNode = handler.enterStruct("advMapAmount");
  324. handler.serializeInt("min", ammMin);
  325. handler.serializeInt("max", ammMax);
  326. }
  327. if(handler.updating)
  328. {
  329. cost.serializeJson(handler, "cost");
  330. handler.serializeInt("faction", faction);//TODO: unify with deferred resolve
  331. }
  332. handler.serializeInt("level", level);
  333. handler.serializeBool("doubleWide", doubleWide);
  334. if(!handler.saving)
  335. {
  336. if(ammMin > ammMax)
  337. logMod->error("Invalid creature '%s' configuration, advMapAmount.min > advMapAmount.max", identifier);
  338. }
  339. }
  340. void CCreature::fillWarMachine()
  341. {
  342. switch (idNumber)
  343. {
  344. case CreatureID::CATAPULT: //Catapult
  345. warMachine = ArtifactID::CATAPULT;
  346. break;
  347. case CreatureID::BALLISTA: //Ballista
  348. warMachine = ArtifactID::BALLISTA;
  349. break;
  350. case CreatureID::FIRST_AID_TENT: //First Aid tent
  351. warMachine = ArtifactID::FIRST_AID_TENT;
  352. break;
  353. case CreatureID::AMMO_CART: //Ammo cart
  354. warMachine = ArtifactID::AMMO_CART;
  355. break;
  356. }
  357. warMachine = ArtifactID::NONE; //this creature is not artifact
  358. }
  359. CCreatureHandler::CCreatureHandler()
  360. : expAfterUpgrade(0)
  361. {
  362. VLC->creh = this;
  363. allCreatures.setDescription("All creatures");
  364. allCreatures.setNodeType(CBonusSystemNode::ENodeTypes::ALL_CREATURES);
  365. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  366. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  367. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  368. loadCommanders();
  369. }
  370. const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const
  371. {
  372. boost::optional<si32> index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier);
  373. if(!index)
  374. throw std::runtime_error("Creature not found "+identifier);
  375. return objects[*index];
  376. }
  377. void CCreatureHandler::loadCommanders()
  378. {
  379. JsonNode data(ResourceID("config/commanders.json"));
  380. data.setMeta(CModHandler::scopeBuiltin()); // assume that commanders are in core mod (for proper bonuses resolution)
  381. const JsonNode & config = data; // switch to const data accessors
  382. for (auto bonus : config["bonusPerLevel"].Vector())
  383. {
  384. commanderLevelPremy.push_back(JsonUtils::parseBonus(bonus.Vector()));
  385. }
  386. int i = 0;
  387. for (auto skill : config["skillLevels"].Vector())
  388. {
  389. skillLevels.push_back (std::vector<ui8>());
  390. for (auto skillLevel : skill["levels"].Vector())
  391. {
  392. skillLevels[i].push_back ((ui8)skillLevel.Float());
  393. }
  394. ++i;
  395. }
  396. for (auto ability : config["abilityRequirements"].Vector())
  397. {
  398. std::pair <std::shared_ptr<Bonus>, std::pair <ui8, ui8> > a;
  399. a.first = JsonUtils::parseBonus (ability["ability"].Vector());
  400. a.second.first = static_cast<ui8>(ability["skills"].Vector()[0].Float());
  401. a.second.second = static_cast<ui8>(ability["skills"].Vector()[1].Float());
  402. skillRequirements.push_back (a);
  403. }
  404. }
  405. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses)
  406. {
  407. auto makeBonusNode = [&](std::string type) -> JsonNode
  408. {
  409. JsonNode ret;
  410. ret["type"].String() = type;
  411. return ret;
  412. };
  413. static const std::map<std::string, JsonNode> abilityMap =
  414. {
  415. {"FLYING_ARMY", makeBonusNode("FLYING")},
  416. {"SHOOTING_ARMY", makeBonusNode("SHOOTER")},
  417. {"SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON")},
  418. {"const_free_attack", makeBonusNode("BLOCKS_RETALIATION")},
  419. {"IS_UNDEAD", makeBonusNode("UNDEAD")},
  420. {"const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY")},
  421. {"const_jousting", makeBonusNode("JOUSTING")},
  422. {"KING_1", makeBonusNode("KING1")},
  423. {"KING_2", makeBonusNode("KING2")},
  424. {"KING_3", makeBonusNode("KING3")},
  425. {"const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY")},
  426. {"CATAPULT", makeBonusNode("CATAPULT")},
  427. {"MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT")},
  428. {"IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY")},
  429. {"HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH")}
  430. };
  431. auto hasAbility = [&](const std::string name) -> bool
  432. {
  433. return boost::algorithm::find_first(bonuses, name);
  434. };
  435. for(auto a : abilityMap)
  436. {
  437. if(hasAbility(a.first))
  438. creature["abilities"][a.first] = a.second;
  439. }
  440. if(hasAbility("DOUBLE_WIDE"))
  441. creature["doubleWide"].Bool() = true;
  442. if(hasAbility("const_raises_morale"))
  443. {
  444. JsonNode node = makeBonusNode("MORALE");
  445. node["val"].Float() = 1;
  446. node["propagator"].String() = "HERO";
  447. creature["abilities"]["const_raises_morale"] = node;
  448. }
  449. }
  450. std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
  451. {
  452. objects.resize(dataSize);
  453. std::vector<JsonNode> h3Data;
  454. h3Data.reserve(dataSize);
  455. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  456. parser.endLine(); // header
  457. // this file is a bit different in some of Russian localisations:
  458. //ENG: Singular Plural Wood ...
  459. //RUS: Singular Plural Plural2 Wood ...
  460. // Try to detect which version this is by header
  461. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  462. size_t namesCount;
  463. {
  464. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  465. throw std::runtime_error("Incorrect format of CrTraits.txt");
  466. if (parser.readString() == "Plural2")
  467. namesCount = 3;
  468. else
  469. namesCount = 2;
  470. parser.endLine();
  471. }
  472. for (size_t i=0; i<dataSize; i++)
  473. {
  474. //loop till non-empty line
  475. while (parser.isNextEntryEmpty())
  476. parser.endLine();
  477. JsonNode data;
  478. data["name"]["singular"].String() = parser.readString();
  479. if (namesCount == 3)
  480. parser.readString();
  481. data["name"]["plural"].String() = parser.readString();
  482. for(int v=0; v<7; ++v)
  483. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  484. data["fightValue"].Float() = parser.readNumber();
  485. data["aiValue"].Float() = parser.readNumber();
  486. data["growth"].Float() = parser.readNumber();
  487. data["horde"].Float() = parser.readNumber();
  488. data["hitPoints"].Float() = parser.readNumber();
  489. data["speed"].Float() = parser.readNumber();
  490. data["attack"].Float() = parser.readNumber();
  491. data["defense"].Float() = parser.readNumber();
  492. data["damage"]["min"].Float() = parser.readNumber();
  493. data["damage"]["max"].Float() = parser.readNumber();
  494. if (float shots = parser.readNumber())
  495. data["shots"].Float() = shots;
  496. if (float spells = parser.readNumber())
  497. data["spellPoints"].Float() = spells;
  498. data["advMapAmount"]["min"].Float() = parser.readNumber();
  499. data["advMapAmount"]["max"].Float() = parser.readNumber();
  500. data["abilityText"].String() = parser.readString();
  501. loadBonuses(data, parser.readString()); //Attributes
  502. h3Data.push_back(data);
  503. }
  504. loadAnimationInfo(h3Data);
  505. return h3Data;
  506. }
  507. CCreature * CCreatureHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  508. {
  509. assert(identifier.find(':') == std::string::npos);
  510. assert(!scope.empty());
  511. auto cre = new CCreature();
  512. if(node["hasDoubleWeek"].Bool())
  513. {
  514. doubledCreatures.insert(CreatureID(index));
  515. }
  516. cre->idNumber = CreatureID(index);
  517. cre->iconIndex = cre->getIndex() + 2;
  518. cre->identifier = identifier;
  519. cre->modScope = scope;
  520. JsonDeserializer handler(nullptr, node);
  521. cre->serializeJson(handler);
  522. cre->cost = Res::ResourceSet(node["cost"]);
  523. VLC->generaltexth->registerString(cre->getNameSingularTextID(), node["name"]["singular"].String());
  524. VLC->generaltexth->registerString(cre->getNamePluralTextID(), node["name"]["plural"].String());
  525. cre->addBonus(node["hitPoints"].Integer(), Bonus::STACK_HEALTH);
  526. cre->addBonus(node["speed"].Integer(), Bonus::STACKS_SPEED);
  527. cre->addBonus(node["attack"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  528. cre->addBonus(node["defense"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  529. cre->addBonus(node["damage"]["min"].Integer(), Bonus::CREATURE_DAMAGE, 1);
  530. cre->addBonus(node["damage"]["max"].Integer(), Bonus::CREATURE_DAMAGE, 2);
  531. assert(node["damage"]["min"].Integer() <= node["damage"]["max"].Integer());
  532. if(!node["shots"].isNull())
  533. cre->addBonus(node["shots"].Integer(), Bonus::SHOTS);
  534. loadStackExperience(cre, node["stackExperience"]);
  535. loadJsonAnimation(cre, node["graphics"]);
  536. loadCreatureJson(cre, node);
  537. for(auto & extraName : node["extraNames"].Vector())
  538. {
  539. for(auto type_name : getTypeNames())
  540. registerObject(scope, type_name, extraName.String(), cre->getIndex());
  541. }
  542. VLC->modh->identifiers.requestIdentifier(scope, "object", "monster", [=](si32 index)
  543. {
  544. JsonNode conf;
  545. conf.setMeta(scope);
  546. VLC->objtypeh->loadSubObject(cre->identifier, conf, Obj::MONSTER, cre->idNumber.num);
  547. if (!cre->advMapDef.empty())
  548. {
  549. JsonNode templ;
  550. templ["animation"].String() = cre->advMapDef;
  551. templ.setMeta(scope);
  552. VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->idNumber.num)->addTemplate(templ);
  553. }
  554. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  555. if (VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->idNumber.num)->getTemplates().empty())
  556. VLC->objtypeh->removeSubObject(Obj::MONSTER, cre->idNumber.num);
  557. });
  558. return cre;
  559. }
  560. const std::vector<std::string> & CCreatureHandler::getTypeNames() const
  561. {
  562. static const std::vector<std::string> typeNames = { "creature" };
  563. return typeNames;
  564. }
  565. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  566. {
  567. std::vector<bool> ret;
  568. for(const CCreature * crea : objects)
  569. {
  570. ret.push_back(crea ? !crea->special : false);
  571. }
  572. return ret;
  573. }
  574. void CCreatureHandler::loadCrExpBon()
  575. {
  576. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  577. {
  578. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  579. Bonus b; //prototype with some default properties
  580. b.source = Bonus::STACK_EXPERIENCE;
  581. b.duration = Bonus::PERMANENT;
  582. b.valType = Bonus::ADDITIVE_VALUE;
  583. b.effectRange = Bonus::NO_LIMIT;
  584. b.additionalInfo = 0;
  585. b.turnsRemain = 0;
  586. BonusList bl;
  587. parser.endLine();
  588. parser.readString(); //ignore index
  589. loadStackExp(b, bl, parser);
  590. for(auto b : bl)
  591. addBonusForAllCreatures(b); //health bonus is common for all
  592. parser.endLine();
  593. for (int i = 1; i < 7; ++i)
  594. {
  595. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  596. {
  597. parser.readString(); //ignore index
  598. bl.clear();
  599. loadStackExp(b, bl, parser);
  600. for(auto b : bl)
  601. addBonusForTier(i, b);
  602. parser.endLine();
  603. }
  604. }
  605. for (int j = 0; j < 4; ++j) //tier 7
  606. {
  607. parser.readString(); //ignore index
  608. bl.clear();
  609. loadStackExp(b, bl, parser);
  610. for(auto b : bl)
  611. {
  612. addBonusForTier(7, b);
  613. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  614. }
  615. parser.endLine();
  616. }
  617. do //parse everything that's left
  618. {
  619. auto sid = static_cast<ui32>(parser.readNumber()); //id = this particular creature ID
  620. b.sid = sid;
  621. bl.clear();
  622. loadStackExp(b, bl, parser);
  623. for(auto b : bl)
  624. {
  625. objects[sid]->addNewBonus(b); //add directly to CCreature Node
  626. }
  627. }
  628. while (parser.endLine());
  629. //Calculate rank exp values, formula appears complicated bu no parsing needed
  630. expRanks.resize(8);
  631. int dif = 0;
  632. int it = 8000; //ignore name of this variable
  633. expRanks[0].push_back(it);
  634. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  635. {
  636. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  637. dif += it/5;
  638. }
  639. for (int i = 1; i < 8; ++i)
  640. {
  641. dif = 0;
  642. it = 1000 * i;
  643. expRanks[i].push_back(it);
  644. for (int j = 1; j < 10; ++j)
  645. {
  646. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  647. dif += it/5;
  648. }
  649. }
  650. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  651. expBonParser.endLine(); //header
  652. maxExpPerBattle.resize(8);
  653. for (int i = 1; i < 8; ++i)
  654. {
  655. expBonParser.readString(); //index
  656. expBonParser.readString(); //float multiplier -> hardcoded
  657. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  658. expBonParser.readString(); //already calculated
  659. maxExpPerBattle[i] = static_cast<ui32>(expBonParser.readNumber());
  660. expRanks[i].push_back(expRanks[i].back() + (ui32)expBonParser.readNumber());
  661. expBonParser.endLine();
  662. }
  663. //skeleton gets exp penalty
  664. objects[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  665. objects[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  666. //exp for tier >7, rank 11
  667. expRanks[0].push_back(147000);
  668. expAfterUpgrade = 75; //percent
  669. maxExpPerBattle[0] = maxExpPerBattle[7];
  670. }//end of Stack Experience
  671. }
  672. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  673. {
  674. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  675. parser.endLine(); // header
  676. parser.endLine();
  677. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++dd)
  678. {
  679. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  680. ;
  681. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  682. parser.endLine();
  683. }
  684. }
  685. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  686. {
  687. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  688. JsonNode & animationTime = graphics["animationTime"];
  689. animationTime["walk"].Float() = parser.readNumber();
  690. animationTime["attack"].Float() = parser.readNumber();
  691. animationTime["flight"].Float() = parser.readNumber();
  692. animationTime["idle"].Float() = 10.0;
  693. JsonNode & missile = graphics["missile"];
  694. JsonNode & offsets = missile["offset"];
  695. offsets["upperX"].Float() = parser.readNumber();
  696. offsets["upperY"].Float() = parser.readNumber();
  697. offsets["middleX"].Float() = parser.readNumber();
  698. offsets["middleY"].Float() = parser.readNumber();
  699. offsets["lowerX"].Float() = parser.readNumber();
  700. offsets["lowerY"].Float() = parser.readNumber();
  701. for(int i=0; i<12; i++)
  702. {
  703. JsonNode entry;
  704. entry.Float() = parser.readNumber();
  705. missile["frameAngles"].Vector().push_back(entry);
  706. }
  707. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  708. missile["attackClimaxFrame"].Float() = parser.readNumber();
  709. // assume that creature is not a shooter and should not have whole missile field
  710. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  711. missile["attackClimaxFrame"].Float() == 0)
  712. graphics.Struct().erase("missile");
  713. }
  714. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  715. {
  716. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  717. cre->animation.troopCountLocationOffset = static_cast<int>(graphics["troopCountLocationOffset"].Float());
  718. const JsonNode & animationTime = graphics["animationTime"];
  719. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  720. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  721. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  722. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  723. const JsonNode & missile = graphics["missile"];
  724. const JsonNode & offsets = missile["offset"];
  725. cre->animation.upperRightMissleOffsetX = static_cast<int>(offsets["upperX"].Float());
  726. cre->animation.upperRightMissleOffsetY = static_cast<int>(offsets["upperY"].Float());
  727. cre->animation.rightMissleOffsetX = static_cast<int>(offsets["middleX"].Float());
  728. cre->animation.rightMissleOffsetY = static_cast<int>(offsets["middleY"].Float());
  729. cre->animation.lowerRightMissleOffsetX = static_cast<int>(offsets["lowerX"].Float());
  730. cre->animation.lowerRightMissleOffsetY = static_cast<int>(offsets["lowerY"].Float());
  731. cre->animation.attackClimaxFrame = static_cast<int>(missile["attackClimaxFrame"].Float());
  732. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  733. cre->advMapDef = graphics["map"].String();
  734. cre->smallIconName = graphics["iconSmall"].String();
  735. cre->largeIconName = graphics["iconLarge"].String();
  736. }
  737. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  738. {
  739. creature->animDefName = config["graphics"]["animation"].String();
  740. //FIXME: MOD COMPATIBILITY
  741. if (config["abilities"].getType() == JsonNode::JsonType::DATA_STRUCT)
  742. {
  743. for(auto &ability : config["abilities"].Struct())
  744. {
  745. if (!ability.second.isNull())
  746. {
  747. auto b = JsonUtils::parseBonus(ability.second);
  748. b->source = Bonus::CREATURE_ABILITY;
  749. b->sid = creature->getIndex();
  750. b->duration = Bonus::PERMANENT;
  751. creature->addNewBonus(b);
  752. }
  753. }
  754. }
  755. else
  756. {
  757. for(const JsonNode &ability : config["abilities"].Vector())
  758. {
  759. if(ability.getType() == JsonNode::JsonType::DATA_VECTOR)
  760. {
  761. logMod->error("Ignored outdated creature ability format in %s", creature->getJsonKey());
  762. }
  763. else
  764. {
  765. auto b = JsonUtils::parseBonus(ability);
  766. b->source = Bonus::CREATURE_ABILITY;
  767. b->sid = creature->getIndex();
  768. b->duration = Bonus::PERMANENT;
  769. creature->addNewBonus(b);
  770. }
  771. }
  772. }
  773. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  774. {
  775. creature->faction = faction;
  776. });
  777. for(const JsonNode &value : config["upgrades"].Vector())
  778. {
  779. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  780. {
  781. creature->upgrades.insert(CreatureID(identifier));
  782. });
  783. }
  784. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  785. for(const JsonNode & value : config["graphics"]["missile"]["ray"].Vector())
  786. {
  787. CCreature::CreatureAnimation::RayColor color;
  788. color.r1 = value["start"].Vector()[0].Integer();
  789. color.g1 = value["start"].Vector()[1].Integer();
  790. color.b1 = value["start"].Vector()[2].Integer();
  791. color.a1 = value["start"].Vector()[3].Integer();
  792. color.r2 = value["end"].Vector()[0].Integer();
  793. color.g2 = value["end"].Vector()[1].Integer();
  794. color.b2 = value["end"].Vector()[2].Integer();
  795. color.a2 = value["end"].Vector()[3].Integer();
  796. creature->animation.projectileRay.push_back(color);
  797. }
  798. creature->special = config["special"].Bool() || config["disabled"].Bool();
  799. const JsonNode & sounds = config["sound"];
  800. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  801. GET_SOUND_VALUE(attack);
  802. GET_SOUND_VALUE(defend);
  803. GET_SOUND_VALUE(killed);
  804. GET_SOUND_VALUE(move);
  805. GET_SOUND_VALUE(shoot);
  806. GET_SOUND_VALUE(wince);
  807. GET_SOUND_VALUE(startMoving);
  808. GET_SOUND_VALUE(endMoving);
  809. #undef GET_SOUND_VALUE
  810. }
  811. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  812. {
  813. for (const JsonNode &exp : input.Vector())
  814. {
  815. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  816. bonus->source = Bonus::STACK_EXPERIENCE;
  817. bonus->duration = Bonus::PERMANENT;
  818. const JsonVector &values = exp["values"].Vector();
  819. int lowerLimit = 1;//, upperLimit = 255;
  820. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  821. {
  822. for (const JsonNode &val : values)
  823. {
  824. if (val.Bool() == true)
  825. {
  826. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  827. creature->addNewBonus (std::make_shared<Bonus>(*bonus)); //bonuses must be unique objects
  828. break; //TODO: allow bonuses to turn off?
  829. }
  830. ++lowerLimit;
  831. }
  832. }
  833. else
  834. {
  835. int lastVal = 0;
  836. for (const JsonNode &val : values)
  837. {
  838. if (val.Float() != lastVal)
  839. {
  840. bonus->val = (int)val.Float() - lastVal;
  841. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  842. creature->addNewBonus (std::make_shared<Bonus>(*bonus));
  843. }
  844. lastVal = static_cast<int>(val.Float());
  845. ++lowerLimit;
  846. }
  847. }
  848. }
  849. }
  850. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  851. {
  852. bool enable = false; //some bonuses are activated with values 2 or 1
  853. std::string buf = parser.readString();
  854. std::string mod = parser.readString();
  855. switch (buf[0])
  856. {
  857. case 'H':
  858. b.type = Bonus::STACK_HEALTH;
  859. b.valType = Bonus::PERCENT_TO_BASE;
  860. break;
  861. case 'A':
  862. b.type = Bonus::PRIMARY_SKILL;
  863. b.subtype = PrimarySkill::ATTACK;
  864. break;
  865. case 'D':
  866. b.type = Bonus::PRIMARY_SKILL;
  867. b.subtype = PrimarySkill::DEFENSE;
  868. break;
  869. case 'M': //Max damage
  870. b.type = Bonus::CREATURE_DAMAGE;
  871. b.subtype = 2;
  872. break;
  873. case 'm': //Min damage
  874. b.type = Bonus::CREATURE_DAMAGE;
  875. b.subtype = 1;
  876. break;
  877. case 'S':
  878. b.type = Bonus::STACKS_SPEED; break;
  879. case 'O':
  880. b.type = Bonus::SHOTS; break;
  881. case 'b':
  882. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  883. case 'C':
  884. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  885. case 'd':
  886. b.type = Bonus::DEFENSIVE_STANCE; break;
  887. case 'e':
  888. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  889. b.subtype = 0;
  890. break;
  891. case 'E':
  892. b.type = Bonus::DEATH_STARE;
  893. b.subtype = 0; //Gorgon
  894. break;
  895. case 'F':
  896. b.type = Bonus::FEAR; break;
  897. case 'g':
  898. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  899. b.subtype = -1; //all magic schools
  900. break;
  901. case 'P':
  902. b.type = Bonus::CASTS; break;
  903. case 'R':
  904. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  905. case 'W':
  906. b.type = Bonus::MAGIC_RESISTANCE;
  907. b.subtype = 0; //otherwise creature window goes crazy
  908. break;
  909. case 'f': //on-off skill
  910. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  911. switch (mod[0])
  912. {
  913. case 'A':
  914. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  915. case 'b':
  916. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  917. case 'B':
  918. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  919. case 'c':
  920. b.type = Bonus::JOUSTING; break;
  921. case 'D':
  922. b.type = Bonus::ADDITIONAL_ATTACK; break;
  923. case 'f':
  924. b.type = Bonus::FEARLESS; break;
  925. case 'F':
  926. b.type = Bonus::FLYING; break;
  927. case 'm':
  928. b.type = Bonus::SELF_MORALE; break;
  929. case 'M':
  930. b.type = Bonus::NO_MORALE; break;
  931. case 'p': //Mind spells
  932. case 'P':
  933. b.type = Bonus::MIND_IMMUNITY; break;
  934. case 'r':
  935. b.type = Bonus::REBIRTH; //on/off? makes sense?
  936. b.subtype = 0;
  937. b.val = 20; //arbitrary value
  938. break;
  939. case 'R':
  940. b.type = Bonus::BLOCKS_RETALIATION; break;
  941. case 's':
  942. b.type = Bonus::FREE_SHOOTING; break;
  943. case 'u':
  944. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  945. case 'U':
  946. b.type = Bonus::UNDEAD; break;
  947. default:
  948. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  949. return;
  950. break;
  951. }
  952. break;
  953. case 'w': //specific spell immunities, enabled/disabled
  954. enable = true;
  955. switch (mod[0])
  956. {
  957. case 'B': //Blind
  958. b.type = Bonus::SPELL_IMMUNITY;
  959. b.subtype = SpellID::BLIND;
  960. b.additionalInfo = 0;//normal immunity
  961. break;
  962. case 'H': //Hypnotize
  963. b.type = Bonus::SPELL_IMMUNITY;
  964. b.subtype = SpellID::HYPNOTIZE;
  965. b.additionalInfo = 0;//normal immunity
  966. break;
  967. case 'I': //Implosion
  968. b.type = Bonus::SPELL_IMMUNITY;
  969. b.subtype = SpellID::IMPLOSION;
  970. b.additionalInfo = 0;//normal immunity
  971. break;
  972. case 'K': //Berserk
  973. b.type = Bonus::SPELL_IMMUNITY;
  974. b.subtype = SpellID::BERSERK;
  975. b.additionalInfo = 0;//normal immunity
  976. break;
  977. case 'M': //Meteor Shower
  978. b.type = Bonus::SPELL_IMMUNITY;
  979. b.subtype = SpellID::METEOR_SHOWER;
  980. b.additionalInfo = 0;//normal immunity
  981. break;
  982. case 'N': //dispell beneficial spells
  983. b.type = Bonus::SPELL_IMMUNITY;
  984. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  985. b.additionalInfo = 0;//normal immunity
  986. break;
  987. case 'R': //Armageddon
  988. b.type = Bonus::SPELL_IMMUNITY;
  989. b.subtype = SpellID::ARMAGEDDON;
  990. b.additionalInfo = 0;//normal immunity
  991. break;
  992. case 'S': //Slow
  993. b.type = Bonus::SPELL_IMMUNITY;
  994. b.subtype = SpellID::SLOW;
  995. b.additionalInfo = 0;//normal immunity
  996. break;
  997. case '6':
  998. case '7':
  999. case '8':
  1000. case '9':
  1001. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  1002. b.val = std::atoi(mod.c_str()) - 5;
  1003. break;
  1004. case ':':
  1005. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  1006. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  1007. break;
  1008. case 'F':
  1009. b.type = Bonus::FIRE_IMMUNITY;
  1010. b.subtype = 1; //not positive
  1011. break;
  1012. case 'O':
  1013. b.type = Bonus::FIRE_IMMUNITY;
  1014. b.subtype = 2; //only direct damage
  1015. break;
  1016. case 'f':
  1017. b.type = Bonus::FIRE_IMMUNITY;
  1018. b.subtype = 0; //all
  1019. break;
  1020. case 'C':
  1021. b.type = Bonus::WATER_IMMUNITY;
  1022. b.subtype = 1; //not positive
  1023. break;
  1024. case 'W':
  1025. b.type = Bonus::WATER_IMMUNITY;
  1026. b.subtype = 2; //only direct damage
  1027. break;
  1028. case 'w':
  1029. b.type = Bonus::WATER_IMMUNITY;
  1030. b.subtype = 0; //all
  1031. break;
  1032. case 'E':
  1033. b.type = Bonus::EARTH_IMMUNITY;
  1034. b.subtype = 2; //only direct damage
  1035. break;
  1036. case 'e':
  1037. b.type = Bonus::EARTH_IMMUNITY;
  1038. b.subtype = 0; //all
  1039. break;
  1040. case 'A':
  1041. b.type = Bonus::AIR_IMMUNITY;
  1042. b.subtype = 2; //only direct damage
  1043. break;
  1044. case 'a':
  1045. b.type = Bonus::AIR_IMMUNITY;
  1046. b.subtype = 0; //all
  1047. break;
  1048. case 'D':
  1049. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  1050. break;
  1051. case '0':
  1052. b.type = Bonus::RECEPTIVE;
  1053. break;
  1054. case 'm':
  1055. b.type = Bonus::MIND_IMMUNITY;
  1056. break;
  1057. default:
  1058. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1059. return;
  1060. }
  1061. break;
  1062. case 'i':
  1063. enable = true;
  1064. b.type = Bonus::NO_DISTANCE_PENALTY;
  1065. break;
  1066. case 'o':
  1067. enable = true;
  1068. b.type = Bonus::NO_WALL_PENALTY;
  1069. break;
  1070. case 'a':
  1071. case 'c':
  1072. case 'K':
  1073. case 'k':
  1074. b.type = Bonus::SPELL_AFTER_ATTACK;
  1075. b.subtype = stringToNumber(mod);
  1076. break;
  1077. case 'h':
  1078. b.type= Bonus::HATE;
  1079. b.subtype = stringToNumber(mod);
  1080. break;
  1081. case 'p':
  1082. case 'J':
  1083. b.type = Bonus::SPELL_BEFORE_ATTACK;
  1084. b.subtype = stringToNumber(mod);
  1085. b.additionalInfo = 3; //always expert?
  1086. break;
  1087. case 'r':
  1088. b.type = Bonus::HP_REGENERATION;
  1089. b.val = stringToNumber(mod);
  1090. break;
  1091. case 's':
  1092. b.type = Bonus::ENCHANTED;
  1093. b.subtype = stringToNumber(mod);
  1094. b.valType = Bonus::INDEPENDENT_MAX;
  1095. break;
  1096. default:
  1097. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1098. return;
  1099. break;
  1100. }
  1101. switch (mod[0])
  1102. {
  1103. case '+':
  1104. case '=': //should we allow percent values to stack or pick highest?
  1105. b.valType = Bonus::ADDITIVE_VALUE;
  1106. break;
  1107. }
  1108. //limiters, range
  1109. si32 lastVal, curVal, lastLev = 0;
  1110. if (enable) //0 and 2 means non-active, 1 - active
  1111. {
  1112. if (b.type != Bonus::REBIRTH)
  1113. b.val = 0; //on-off ability, no value specified
  1114. parser.readNumber(); // 0 level is never active
  1115. for (int i = 1; i < 11; ++i)
  1116. {
  1117. curVal = static_cast<si32>(parser.readNumber());
  1118. if (curVal == 1)
  1119. {
  1120. b.limiter.reset (new RankRangeLimiter(i));
  1121. bl.push_back(std::make_shared<Bonus>(b));
  1122. break; //never turned off it seems
  1123. }
  1124. }
  1125. }
  1126. else
  1127. {
  1128. lastVal = static_cast<si32>(parser.readNumber());
  1129. if (b.type == Bonus::HATE)
  1130. lastVal *= 10; //odd fix
  1131. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1132. for (int i = 1; i < 11; ++i)
  1133. {
  1134. curVal = static_cast<si32>(parser.readNumber());
  1135. if (b.type == Bonus::HATE)
  1136. curVal *= 10; //odd fix
  1137. if (curVal > lastVal) //threshold, add new bonus
  1138. {
  1139. b.val = curVal - lastVal;
  1140. lastVal = curVal;
  1141. b.limiter.reset (new RankRangeLimiter(i));
  1142. bl.push_back(std::make_shared<Bonus>(b));
  1143. lastLev = i; //start new range from here, i = previous rank
  1144. }
  1145. else if (curVal < lastVal)
  1146. {
  1147. b.val = lastVal;
  1148. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1149. }
  1150. }
  1151. }
  1152. }
  1153. int CCreatureHandler::stringToNumber(std::string & s)
  1154. {
  1155. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1156. return std::atoi(s.c_str());
  1157. }
  1158. CCreatureHandler::~CCreatureHandler()
  1159. {
  1160. for(auto & p : skillRequirements)
  1161. p.first = nullptr;
  1162. }
  1163. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1164. {
  1165. int r = 0;
  1166. if(tier == -1) //pick any allowed creature
  1167. {
  1168. do
  1169. {
  1170. r = (*RandomGeneratorUtil::nextItem(objects, rand))->idNumber;
  1171. } while (objects[r] && objects[r]->special); // find first "not special" creature
  1172. }
  1173. else
  1174. {
  1175. assert(vstd::iswithin(tier, 1, 7));
  1176. std::vector<CreatureID> allowed;
  1177. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  1178. {
  1179. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  1180. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  1181. if(crea && !crea->special)
  1182. allowed.push_back(crea->idNumber);
  1183. }
  1184. if(!allowed.size())
  1185. {
  1186. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1187. return CreatureID::NONE;
  1188. }
  1189. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1190. }
  1191. assert (r >= 0); //should always be, but it crashed
  1192. return CreatureID(r);
  1193. }
  1194. void CCreatureHandler::addBonusForTier(int tier, const std::shared_ptr<Bonus> & b)
  1195. {
  1196. assert(vstd::iswithin(tier, 1, 7));
  1197. creaturesOfLevel[tier].addNewBonus(b);
  1198. }
  1199. void CCreatureHandler::addBonusForAllCreatures(const std::shared_ptr<Bonus> & b)
  1200. {
  1201. const auto & exportedBonuses = allCreatures.getExportedBonusList();
  1202. for(const auto & bonus : exportedBonuses)
  1203. {
  1204. if(bonus->type == b->type && bonus->subtype == b->subtype)
  1205. return;
  1206. }
  1207. allCreatures.addNewBonus(b);
  1208. }
  1209. void CCreatureHandler::removeBonusesFromAllCreatures()
  1210. {
  1211. allCreatures.removeBonuses(Selector::all);
  1212. }
  1213. void CCreatureHandler::buildBonusTreeForTiers()
  1214. {
  1215. for(CCreature * c : objects)
  1216. {
  1217. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  1218. c->attachTo(creaturesOfLevel[c->level]);
  1219. else
  1220. c->attachTo(creaturesOfLevel[0]);
  1221. }
  1222. for(CBonusSystemNode &b : creaturesOfLevel)
  1223. b.attachTo(allCreatures);
  1224. }
  1225. void CCreatureHandler::afterLoadFinalization()
  1226. {
  1227. }
  1228. void CCreatureHandler::deserializationFix()
  1229. {
  1230. buildBonusTreeForTiers();
  1231. }
  1232. VCMI_LIB_NAMESPACE_END