CCreatureHandler.cpp 38 KB

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