CCreatureHandler.cpp 38 KB

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