CCreatureHandler.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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. creature->special = config["special"].Bool() || config["disabled"].Bool();
  754. const JsonNode & sounds = config["sound"];
  755. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  756. GET_SOUND_VALUE(attack);
  757. GET_SOUND_VALUE(defend);
  758. GET_SOUND_VALUE(killed);
  759. GET_SOUND_VALUE(move);
  760. GET_SOUND_VALUE(shoot);
  761. GET_SOUND_VALUE(wince);
  762. GET_SOUND_VALUE(startMoving);
  763. GET_SOUND_VALUE(endMoving);
  764. #undef GET_SOUND_VALUE
  765. }
  766. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  767. {
  768. for (const JsonNode &exp : input.Vector())
  769. {
  770. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  771. bonus->source = Bonus::STACK_EXPERIENCE;
  772. bonus->duration = Bonus::PERMANENT;
  773. const JsonVector &values = exp["values"].Vector();
  774. int lowerLimit = 1;//, upperLimit = 255;
  775. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  776. {
  777. for (const JsonNode &val : values)
  778. {
  779. if (val.Bool() == true)
  780. {
  781. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  782. creature->addNewBonus (std::make_shared<Bonus>(*bonus)); //bonuses must be unique objects
  783. break; //TODO: allow bonuses to turn off?
  784. }
  785. ++lowerLimit;
  786. }
  787. }
  788. else
  789. {
  790. int lastVal = 0;
  791. for (const JsonNode &val : values)
  792. {
  793. if (val.Float() != lastVal)
  794. {
  795. bonus->val = (int)val.Float() - lastVal;
  796. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  797. creature->addNewBonus (std::make_shared<Bonus>(*bonus));
  798. }
  799. lastVal = static_cast<int>(val.Float());
  800. ++lowerLimit;
  801. }
  802. }
  803. }
  804. }
  805. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  806. {
  807. bool enable = false; //some bonuses are activated with values 2 or 1
  808. std::string buf = parser.readString();
  809. std::string mod = parser.readString();
  810. switch (buf[0])
  811. {
  812. case 'H':
  813. b.type = Bonus::STACK_HEALTH;
  814. b.valType = Bonus::PERCENT_TO_BASE;
  815. break;
  816. case 'A':
  817. b.type = Bonus::PRIMARY_SKILL;
  818. b.subtype = PrimarySkill::ATTACK;
  819. break;
  820. case 'D':
  821. b.type = Bonus::PRIMARY_SKILL;
  822. b.subtype = PrimarySkill::DEFENSE;
  823. break;
  824. case 'M': //Max damage
  825. b.type = Bonus::CREATURE_DAMAGE;
  826. b.subtype = 2;
  827. break;
  828. case 'm': //Min damage
  829. b.type = Bonus::CREATURE_DAMAGE;
  830. b.subtype = 1;
  831. break;
  832. case 'S':
  833. b.type = Bonus::STACKS_SPEED; break;
  834. case 'O':
  835. b.type = Bonus::SHOTS; break;
  836. case 'b':
  837. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  838. case 'C':
  839. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  840. case 'd':
  841. b.type = Bonus::DEFENSIVE_STANCE; break;
  842. case 'e':
  843. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  844. b.subtype = 0;
  845. break;
  846. case 'E':
  847. b.type = Bonus::DEATH_STARE;
  848. b.subtype = 0; //Gorgon
  849. break;
  850. case 'F':
  851. b.type = Bonus::FEAR; break;
  852. case 'g':
  853. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  854. b.subtype = -1; //all magic schools
  855. break;
  856. case 'P':
  857. b.type = Bonus::CASTS; break;
  858. case 'R':
  859. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  860. case 'W':
  861. b.type = Bonus::MAGIC_RESISTANCE;
  862. b.subtype = 0; //otherwise creature window goes crazy
  863. break;
  864. case 'f': //on-off skill
  865. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  866. switch (mod[0])
  867. {
  868. case 'A':
  869. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  870. case 'b':
  871. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  872. case 'B':
  873. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  874. case 'c':
  875. b.type = Bonus::JOUSTING; break;
  876. case 'D':
  877. b.type = Bonus::ADDITIONAL_ATTACK; break;
  878. case 'f':
  879. b.type = Bonus::FEARLESS; break;
  880. case 'F':
  881. b.type = Bonus::FLYING; break;
  882. case 'm':
  883. b.type = Bonus::SELF_MORALE; break;
  884. case 'M':
  885. b.type = Bonus::NO_MORALE; break;
  886. case 'p': //Mind spells
  887. case 'P':
  888. b.type = Bonus::MIND_IMMUNITY; break;
  889. case 'r':
  890. b.type = Bonus::REBIRTH; //on/off? makes sense?
  891. b.subtype = 0;
  892. b.val = 20; //arbitrary value
  893. break;
  894. case 'R':
  895. b.type = Bonus::BLOCKS_RETALIATION; break;
  896. case 's':
  897. b.type = Bonus::FREE_SHOOTING; break;
  898. case 'u':
  899. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  900. case 'U':
  901. b.type = Bonus::UNDEAD; break;
  902. default:
  903. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  904. return;
  905. break;
  906. }
  907. break;
  908. case 'w': //specific spell immunities, enabled/disabled
  909. enable = true;
  910. switch (mod[0])
  911. {
  912. case 'B': //Blind
  913. b.type = Bonus::SPELL_IMMUNITY;
  914. b.subtype = SpellID::BLIND;
  915. b.additionalInfo = 0;//normal immunity
  916. break;
  917. case 'H': //Hypnotize
  918. b.type = Bonus::SPELL_IMMUNITY;
  919. b.subtype = SpellID::HYPNOTIZE;
  920. b.additionalInfo = 0;//normal immunity
  921. break;
  922. case 'I': //Implosion
  923. b.type = Bonus::SPELL_IMMUNITY;
  924. b.subtype = SpellID::IMPLOSION;
  925. b.additionalInfo = 0;//normal immunity
  926. break;
  927. case 'K': //Berserk
  928. b.type = Bonus::SPELL_IMMUNITY;
  929. b.subtype = SpellID::BERSERK;
  930. b.additionalInfo = 0;//normal immunity
  931. break;
  932. case 'M': //Meteor Shower
  933. b.type = Bonus::SPELL_IMMUNITY;
  934. b.subtype = SpellID::METEOR_SHOWER;
  935. b.additionalInfo = 0;//normal immunity
  936. break;
  937. case 'N': //dispell beneficial spells
  938. b.type = Bonus::SPELL_IMMUNITY;
  939. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  940. b.additionalInfo = 0;//normal immunity
  941. break;
  942. case 'R': //Armageddon
  943. b.type = Bonus::SPELL_IMMUNITY;
  944. b.subtype = SpellID::ARMAGEDDON;
  945. b.additionalInfo = 0;//normal immunity
  946. break;
  947. case 'S': //Slow
  948. b.type = Bonus::SPELL_IMMUNITY;
  949. b.subtype = SpellID::SLOW;
  950. b.additionalInfo = 0;//normal immunity
  951. break;
  952. case '6':
  953. case '7':
  954. case '8':
  955. case '9':
  956. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  957. b.val = std::atoi(mod.c_str()) - 5;
  958. break;
  959. case ':':
  960. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  961. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  962. break;
  963. case 'F':
  964. b.type = Bonus::FIRE_IMMUNITY;
  965. b.subtype = 1; //not positive
  966. break;
  967. case 'O':
  968. b.type = Bonus::FIRE_IMMUNITY;
  969. b.subtype = 2; //only direct damage
  970. break;
  971. case 'f':
  972. b.type = Bonus::FIRE_IMMUNITY;
  973. b.subtype = 0; //all
  974. break;
  975. case 'C':
  976. b.type = Bonus::WATER_IMMUNITY;
  977. b.subtype = 1; //not positive
  978. break;
  979. case 'W':
  980. b.type = Bonus::WATER_IMMUNITY;
  981. b.subtype = 2; //only direct damage
  982. break;
  983. case 'w':
  984. b.type = Bonus::WATER_IMMUNITY;
  985. b.subtype = 0; //all
  986. break;
  987. case 'E':
  988. b.type = Bonus::EARTH_IMMUNITY;
  989. b.subtype = 2; //only direct damage
  990. break;
  991. case 'e':
  992. b.type = Bonus::EARTH_IMMUNITY;
  993. b.subtype = 0; //all
  994. break;
  995. case 'A':
  996. b.type = Bonus::AIR_IMMUNITY;
  997. b.subtype = 2; //only direct damage
  998. break;
  999. case 'a':
  1000. b.type = Bonus::AIR_IMMUNITY;
  1001. b.subtype = 0; //all
  1002. break;
  1003. case 'D':
  1004. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  1005. break;
  1006. case '0':
  1007. b.type = Bonus::RECEPTIVE;
  1008. break;
  1009. case 'm':
  1010. b.type = Bonus::MIND_IMMUNITY;
  1011. break;
  1012. default:
  1013. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1014. return;
  1015. }
  1016. break;
  1017. case 'i':
  1018. enable = true;
  1019. b.type = Bonus::NO_DISTANCE_PENALTY;
  1020. break;
  1021. case 'o':
  1022. enable = true;
  1023. b.type = Bonus::NO_WALL_PENALTY;
  1024. break;
  1025. case 'a':
  1026. case 'c':
  1027. case 'K':
  1028. case 'k':
  1029. b.type = Bonus::SPELL_AFTER_ATTACK;
  1030. b.subtype = stringToNumber(mod);
  1031. break;
  1032. case 'h':
  1033. b.type= Bonus::HATE;
  1034. b.subtype = stringToNumber(mod);
  1035. break;
  1036. case 'p':
  1037. case 'J':
  1038. b.type = Bonus::SPELL_BEFORE_ATTACK;
  1039. b.subtype = stringToNumber(mod);
  1040. b.additionalInfo = 3; //always expert?
  1041. break;
  1042. case 'r':
  1043. b.type = Bonus::HP_REGENERATION;
  1044. b.val = stringToNumber(mod);
  1045. break;
  1046. case 's':
  1047. b.type = Bonus::ENCHANTED;
  1048. b.subtype = stringToNumber(mod);
  1049. b.valType = Bonus::INDEPENDENT_MAX;
  1050. break;
  1051. default:
  1052. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1053. return;
  1054. break;
  1055. }
  1056. switch (mod[0])
  1057. {
  1058. case '+':
  1059. case '=': //should we allow percent values to stack or pick highest?
  1060. b.valType = Bonus::ADDITIVE_VALUE;
  1061. break;
  1062. }
  1063. //limiters, range
  1064. si32 lastVal, curVal, lastLev = 0;
  1065. if (enable) //0 and 2 means non-active, 1 - active
  1066. {
  1067. if (b.type != Bonus::REBIRTH)
  1068. b.val = 0; //on-off ability, no value specified
  1069. parser.readNumber(); // 0 level is never active
  1070. for (int i = 1; i < 11; ++i)
  1071. {
  1072. curVal = static_cast<si32>(parser.readNumber());
  1073. if (curVal == 1)
  1074. {
  1075. b.limiter.reset (new RankRangeLimiter(i));
  1076. bl.push_back(std::make_shared<Bonus>(b));
  1077. break; //never turned off it seems
  1078. }
  1079. }
  1080. }
  1081. else
  1082. {
  1083. lastVal = static_cast<si32>(parser.readNumber());
  1084. if (b.type == Bonus::HATE)
  1085. lastVal *= 10; //odd fix
  1086. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1087. for (int i = 1; i < 11; ++i)
  1088. {
  1089. curVal = static_cast<si32>(parser.readNumber());
  1090. if (b.type == Bonus::HATE)
  1091. curVal *= 10; //odd fix
  1092. if (curVal > lastVal) //threshold, add new bonus
  1093. {
  1094. b.val = curVal - lastVal;
  1095. lastVal = curVal;
  1096. b.limiter.reset (new RankRangeLimiter(i));
  1097. bl.push_back(std::make_shared<Bonus>(b));
  1098. lastLev = i; //start new range from here, i = previous rank
  1099. }
  1100. else if (curVal < lastVal)
  1101. {
  1102. b.val = lastVal;
  1103. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1104. }
  1105. }
  1106. }
  1107. }
  1108. int CCreatureHandler::stringToNumber(std::string & s)
  1109. {
  1110. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1111. return std::atoi(s.c_str());
  1112. }
  1113. CCreatureHandler::~CCreatureHandler()
  1114. {
  1115. for(auto & p : skillRequirements)
  1116. p.first = nullptr;
  1117. }
  1118. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1119. {
  1120. int r = 0;
  1121. if(tier == -1) //pick any allowed creature
  1122. {
  1123. do
  1124. {
  1125. r = (*RandomGeneratorUtil::nextItem(objects, rand))->idNumber;
  1126. } while (objects[r] && objects[r]->special); // find first "not special" creature
  1127. }
  1128. else
  1129. {
  1130. assert(vstd::iswithin(tier, 1, 7));
  1131. std::vector<CreatureID> allowed;
  1132. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  1133. {
  1134. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  1135. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  1136. if(crea && !crea->special)
  1137. allowed.push_back(crea->idNumber);
  1138. }
  1139. if(!allowed.size())
  1140. {
  1141. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1142. return CreatureID::NONE;
  1143. }
  1144. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1145. }
  1146. assert (r >= 0); //should always be, but it crashed
  1147. return CreatureID(r);
  1148. }
  1149. void CCreatureHandler::addBonusForTier(int tier, const std::shared_ptr<Bonus> & b)
  1150. {
  1151. assert(vstd::iswithin(tier, 1, 7));
  1152. creaturesOfLevel[tier].addNewBonus(b);
  1153. }
  1154. void CCreatureHandler::addBonusForAllCreatures(const std::shared_ptr<Bonus> & b)
  1155. {
  1156. const auto & exportedBonuses = allCreatures.getExportedBonusList();
  1157. for(const auto & bonus : exportedBonuses)
  1158. {
  1159. if(bonus->type == b->type && bonus->subtype == b->subtype)
  1160. return;
  1161. }
  1162. allCreatures.addNewBonus(b);
  1163. }
  1164. void CCreatureHandler::removeBonusesFromAllCreatures()
  1165. {
  1166. allCreatures.removeBonuses(Selector::all);
  1167. }
  1168. void CCreatureHandler::buildBonusTreeForTiers()
  1169. {
  1170. for(CCreature * c : objects)
  1171. {
  1172. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  1173. c->attachTo(creaturesOfLevel[c->level]);
  1174. else
  1175. c->attachTo(creaturesOfLevel[0]);
  1176. }
  1177. for(CBonusSystemNode &b : creaturesOfLevel)
  1178. b.attachTo(allCreatures);
  1179. }
  1180. void CCreatureHandler::afterLoadFinalization()
  1181. {
  1182. }
  1183. void CCreatureHandler::deserializationFix()
  1184. {
  1185. buildBonusTreeForTiers();
  1186. }
  1187. VCMI_LIB_NAMESPACE_END