CCreatureHandler.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. #include "StdInc.h"
  2. #include "CCreatureHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/CResourceLoader.h"
  5. #include "VCMI_Lib.h"
  6. #include "CGameState.h"
  7. #include "CTownHandler.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. using namespace boost::assign;
  11. /*
  12. * CCreatureHandler.cpp, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. int CCreature::getQuantityID(const int & quantity)
  21. {
  22. if (quantity<5)
  23. return 1;
  24. if (quantity<10)
  25. return 2;
  26. if (quantity<20)
  27. return 3;
  28. if (quantity<50)
  29. return 4;
  30. if (quantity<100)
  31. return 5;
  32. if (quantity<250)
  33. return 6;
  34. if (quantity<500)
  35. return 7;
  36. if (quantity<1000)
  37. return 8;
  38. return 9;
  39. }
  40. int CCreature::estimateCreatureCount(ui32 countID)
  41. {
  42. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  43. if (countID > 9)
  44. assert("Wrong countID!");
  45. return creature_count[countID];
  46. }
  47. bool CCreature::isDoubleWide() const
  48. {
  49. return doubleWide;
  50. }
  51. bool CCreature::isFlying() const
  52. {
  53. return hasBonusOfType(Bonus::FLYING);
  54. }
  55. bool CCreature::isShooting() const
  56. {
  57. return hasBonusOfType(Bonus::SHOOTER);
  58. }
  59. bool CCreature::isUndead() const
  60. {
  61. return hasBonusOfType(Bonus::UNDEAD);
  62. }
  63. /**
  64. * Determines if the creature is of a good alignment.
  65. * @return true if the creture is good, false otherwise.
  66. */
  67. bool CCreature::isGood () const
  68. {
  69. return VLC->townh->factions[faction]->alignment == EAlignment::GOOD;
  70. }
  71. /**
  72. * Determines if the creature is of an evil alignment.
  73. * @return true if the creature is evil, false otherwise.
  74. */
  75. bool CCreature::isEvil () const
  76. {
  77. return VLC->townh->factions[faction]->alignment == EAlignment::EVIL;
  78. }
  79. si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
  80. {
  81. int ret = 2147483645;
  82. int resAmnt = std::min(res.size(),cost.size());
  83. for(int i=0;i<resAmnt;i++)
  84. if(cost[i])
  85. ret = std::min(ret,(int)(res[i]/cost[i]));
  86. return ret;
  87. }
  88. CCreature::CCreature()
  89. {
  90. doubleWide = false;
  91. setNodeType(CBonusSystemNode::CREATURE);
  92. }
  93. void CCreature::addBonus(int val, Bonus::BonusType type, int subtype /*= -1*/)
  94. {
  95. Bonus *added = new Bonus(Bonus::PERMANENT, type, Bonus::CREATURE_ABILITY, val, idNumber, subtype, Bonus::BASE_NUMBER);
  96. addNewBonus(added);
  97. }
  98. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  99. {
  100. //TODO upgrade of upgrade?
  101. return vstd::contains(upgrades, anotherCre->idNumber);
  102. }
  103. bool CCreature::valid() const
  104. {
  105. return this == VLC->creh->creatures[idNumber];
  106. }
  107. std::string CCreature::nodeName() const
  108. {
  109. return "\"" + namePl + "\"";
  110. }
  111. bool CCreature::isItNativeTerrain(int terrain) const
  112. {
  113. return VLC->townh->factions[faction]->nativeTerrain == terrain;
  114. }
  115. static void AddAbility(CCreature *cre, const JsonVector &ability_vec)
  116. {
  117. Bonus *nsf = new Bonus();
  118. std::string type = ability_vec[0].String();
  119. auto it = bonusNameMap.find(type);
  120. if (it == bonusNameMap.end()) {
  121. if (type == "DOUBLE_WIDE")
  122. cre->doubleWide = true;
  123. else if (type == "ENEMY_MORALE_DECREASING") {
  124. cre->addBonus(-1, Bonus::MORALE);
  125. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  126. }
  127. else if (type == "ENEMY_LUCK_DECREASING") {
  128. cre->addBonus(-1, Bonus::LUCK);
  129. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  130. } else
  131. logGlobal->errorStream() << "Error: invalid ability type " << type << " in creatures config";
  132. return;
  133. }
  134. nsf->type = it->second;
  135. JsonUtils::parseTypedBonusShort(ability_vec,nsf);
  136. nsf->source = Bonus::CREATURE_ABILITY;
  137. nsf->sid = cre->idNumber;
  138. cre->addNewBonus(nsf);
  139. }
  140. CCreatureHandler::CCreatureHandler()
  141. {
  142. VLC->creh = this;
  143. allCreatures.setDescription("All creatures");
  144. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  145. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  146. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  147. loadCommanders();
  148. }
  149. void CCreatureHandler::loadCommanders()
  150. {
  151. const JsonNode config(ResourceID("config/commanders.json"));
  152. BOOST_FOREACH (auto bonus, config["bonusPerLevel"].Vector())
  153. {
  154. commanderLevelPremy.push_back(JsonUtils::parseBonus (bonus.Vector()));
  155. }
  156. int i = 0;
  157. BOOST_FOREACH (auto skill, config["skillLevels"].Vector())
  158. {
  159. skillLevels.push_back (std::vector<ui8>());
  160. BOOST_FOREACH (auto skillLevel, skill["levels"].Vector())
  161. {
  162. skillLevels[i].push_back (skillLevel.Float());
  163. }
  164. ++i;
  165. }
  166. BOOST_FOREACH (auto ability, config["abilityRequirements"].Vector())
  167. {
  168. std::pair <Bonus, std::pair <ui8, ui8> > a;
  169. a.first = *JsonUtils::parseBonus (ability["ability"].Vector());
  170. a.second.first = ability["skills"].Vector()[0].Float();
  171. a.second.second = ability["skills"].Vector()[1].Float();
  172. skillRequirements.push_back (a);
  173. }
  174. }
  175. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses)
  176. {
  177. auto makeBonusNode = [&](std::string type) -> JsonNode
  178. {
  179. JsonNode ret;
  180. ret["type"].String() = type;
  181. return ret;
  182. };
  183. static const std::map<std::string, JsonNode> abilityMap =
  184. boost::assign::map_list_of
  185. ("FLYING_ARMY", makeBonusNode("FLYING"))
  186. ("SHOOTING_ARMY", makeBonusNode("SHOOTER"))
  187. ("SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON"))
  188. ("const_free_attack", makeBonusNode("BLOCKS_RETALIATION"))
  189. ("IS_UNDEAD", makeBonusNode("UNDEAD"))
  190. ("const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY"))
  191. ("const_jousting", makeBonusNode("JOUSTING"))
  192. ("KING_1", makeBonusNode("KING1"))
  193. ("KING_2", makeBonusNode("KING2"))
  194. ("KING_3", makeBonusNode("KING3"))
  195. ("const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY"))
  196. ("CATAPULT", makeBonusNode("CATAPULT"))
  197. ("MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT"))
  198. ("IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY"))
  199. ("HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH"));
  200. auto hasAbility = [&](const std::string name) -> bool
  201. {
  202. return boost::algorithm::find_first(bonuses, name);
  203. };
  204. BOOST_FOREACH(auto a, abilityMap)
  205. {
  206. if(hasAbility(a.first))
  207. creature["abilities"][a.first] = a.second;
  208. }
  209. if(hasAbility("DOUBLE_WIDE"))
  210. creature["doubleWide"].Bool() = true;
  211. if(hasAbility("const_raises_morale"))
  212. {
  213. JsonNode node = makeBonusNode("MORALE");
  214. node["val"].Float() = 1;
  215. node["propagator"].String() = "HERO";
  216. creature["abilities"]["const_raises_morale"] = node;
  217. }
  218. if(hasAbility("const_lowers_morale"))
  219. {
  220. JsonNode node = makeBonusNode("MORALE");
  221. node["val"].Float() = 1;
  222. node["effectRange"].String() = "ONLY_ENEMY_ARMY";
  223. creature["abilities"]["const_lowers_morale"] = node;
  224. }
  225. }
  226. std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
  227. {
  228. creatures.resize(dataSize);
  229. std::vector<JsonNode> h3Data;
  230. h3Data.reserve(dataSize);
  231. CLegacyConfigParser parser("DATA/ZCRTRAIT.TXT");
  232. parser.endLine(); // header
  233. parser.endLine();
  234. for (size_t i=0; i<dataSize; i++)
  235. {
  236. //loop till non-empty line
  237. while (parser.isNextEntryEmpty())
  238. parser.endLine();
  239. JsonNode data;
  240. data["graphics"]["iconIndex"].Float() = h3Data.size() + 2; // +2 for empty\selection images
  241. data["name"]["singular"].String() = parser.readString();
  242. data["name"]["plural"].String() = parser.readString();
  243. for(int v=0; v<7; ++v)
  244. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  245. data["fightValue"].Float() = parser.readNumber();
  246. data["aiValue"].Float() = parser.readNumber();
  247. data["growth"].Float() = parser.readNumber();
  248. data["horde"].Float() = parser.readNumber();
  249. data["hitPoints"].Float() = parser.readNumber();
  250. data["speed"].Float() = parser.readNumber();
  251. data["attack"].Float() = parser.readNumber();
  252. data["defense"].Float() = parser.readNumber();
  253. data["damage"]["min"].Float() = parser.readNumber();
  254. data["damage"]["max"].Float() = parser.readNumber();
  255. if (float shots = parser.readNumber())
  256. data["shots"].Float() = shots;
  257. if (float spells = parser.readNumber())
  258. data["spellPoints"].Float() = spells;
  259. data["advMapAmount"]["min"].Float() = parser.readNumber();
  260. data["advMapAmount"]["max"].Float() = parser.readNumber();
  261. data["abilityText"].String() = parser.readString();
  262. loadBonuses(data, parser.readString()); //Attributes
  263. h3Data.push_back(data);
  264. }
  265. loadAnimationInfo(h3Data);
  266. return h3Data;
  267. }
  268. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  269. {
  270. auto object = loadFromJson(data);
  271. object->idNumber = CreatureID(creatures.size());
  272. creatures.push_back(object);
  273. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  274. BOOST_FOREACH(auto node, data["extraNames"].Vector())
  275. {
  276. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  277. }
  278. }
  279. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  280. {
  281. auto object = loadFromJson(data);
  282. object->idNumber = CreatureID(index);
  283. assert(creatures[index] == nullptr); // ensure that this id was not loaded before
  284. creatures[index] = object;
  285. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  286. BOOST_FOREACH(auto node, data["extraNames"].Vector())
  287. {
  288. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  289. }
  290. }
  291. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  292. {
  293. std::vector<bool> ret;
  294. BOOST_FOREACH(const CCreature * crea, creatures)
  295. {
  296. ret.push_back(crea ? !crea->special : false);
  297. }
  298. return ret;
  299. }
  300. void CCreatureHandler::loadCrExpBon()
  301. {
  302. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  303. {
  304. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  305. Bonus b; //prototype with some default properties
  306. b.source = Bonus::STACK_EXPERIENCE;
  307. b.duration = Bonus::PERMANENT;
  308. b.valType = Bonus::ADDITIVE_VALUE;
  309. b.effectRange = Bonus::NO_LIMIT;
  310. b.additionalInfo = 0;
  311. b.turnsRemain = 0;
  312. BonusList bl;
  313. parser.endLine();
  314. parser.readString(); //ignore index
  315. loadStackExp(b, bl, parser);
  316. BOOST_FOREACH(Bonus * b, bl)
  317. addBonusForAllCreatures(b); //health bonus is common for all
  318. parser.endLine();
  319. for (int i = 1; i < 7; ++i)
  320. {
  321. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  322. {
  323. parser.readString(); //ignore index
  324. bl.clear();
  325. loadStackExp(b, bl, parser);
  326. BOOST_FOREACH(Bonus * b, bl)
  327. addBonusForTier(i, b);
  328. parser.endLine();
  329. }
  330. }
  331. for (int j = 0; j < 4; ++j) //tier 7
  332. {
  333. parser.readString(); //ignore index
  334. bl.clear();
  335. loadStackExp(b, bl, parser);
  336. BOOST_FOREACH(Bonus * b, bl)
  337. {
  338. addBonusForTier(7, b);
  339. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  340. }
  341. parser.endLine();
  342. }
  343. do //parse everything that's left
  344. {
  345. b.sid = parser.readNumber(); //id = this particular creature ID
  346. loadStackExp(b, creatures[b.sid]->getBonusList(), parser); //add directly to CCreature Node
  347. }
  348. while (parser.endLine());
  349. //Calculate rank exp values, formula appears complicated bu no parsing needed
  350. expRanks.resize(8);
  351. int dif = 0;
  352. int it = 8000; //ignore name of this variable
  353. expRanks[0].push_back(it);
  354. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  355. {
  356. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  357. dif += it/5;
  358. }
  359. for (int i = 1; i < 8; ++i)
  360. {
  361. dif = 0;
  362. it = 1000 * i;
  363. expRanks[i].push_back(it);
  364. for (int j = 1; j < 10; ++j)
  365. {
  366. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  367. dif += it/5;
  368. }
  369. }
  370. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  371. expBonParser.endLine(); //header
  372. maxExpPerBattle.resize(8);
  373. for (int i = 1; i < 8; ++i)
  374. {
  375. expBonParser.readString(); //index
  376. expBonParser.readString(); //float multiplier -> hardcoded
  377. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  378. expBonParser.readString(); //already calculated
  379. maxExpPerBattle[i] = expBonParser.readNumber();
  380. expRanks[i].push_back(expRanks[i].back() + expBonParser.readNumber());
  381. expBonParser.endLine();
  382. }
  383. //skeleton gets exp penalty
  384. creatures[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  385. creatures[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  386. //exp for tier >7, rank 11
  387. expRanks[0].push_back(147000);
  388. expAfterUpgrade = 75; //percent
  389. maxExpPerBattle[0] = maxExpPerBattle[7];
  390. }//end of Stack Experience
  391. }
  392. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  393. {
  394. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  395. parser.endLine(); // header
  396. parser.endLine();
  397. for(int dd=0; dd<GameConstants::CREATURES_COUNT; ++dd)
  398. {
  399. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  400. ;
  401. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  402. parser.endLine();
  403. }
  404. }
  405. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  406. {
  407. graphics["map"].String(); //create empty string. Real value will be loaded from H3 txt's
  408. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  409. JsonNode & animationTime = graphics["animationTime"];
  410. animationTime["walk"].Float() = parser.readNumber();
  411. animationTime["attack"].Float() = parser.readNumber();
  412. animationTime["flight"].Float() = parser.readNumber();
  413. JsonNode & missile = graphics["missile"];
  414. JsonNode & offsets = missile["offset"];
  415. offsets["upperX"].Float() = parser.readNumber();
  416. offsets["upperY"].Float() = parser.readNumber();
  417. offsets["middleX"].Float() = parser.readNumber();
  418. offsets["middleY"].Float() = parser.readNumber();
  419. offsets["lowerX"].Float() = parser.readNumber();
  420. offsets["lowerY"].Float() = parser.readNumber();
  421. for(int i=0; i<12; i++)
  422. {
  423. JsonNode entry;
  424. entry.Float() = parser.readNumber();
  425. missile["frameAngles"].Vector().push_back(entry);
  426. }
  427. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  428. missile["attackClimaxFrame"].Float() = parser.readNumber();
  429. // assume that creature is not a shooter and should not have whole missile field
  430. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  431. missile["attackClimaxFrame"].Float() == 0)
  432. graphics.Struct().erase("missile");
  433. }
  434. CCreature * CCreatureHandler::loadFromJson(const JsonNode & node)
  435. {
  436. CCreature * cre = new CCreature();
  437. const JsonNode & name = node["name"];
  438. cre->nameSing = name["singular"].String();
  439. cre->namePl = name["plural"].String();
  440. cre->cost = Res::ResourceSet(node["cost"]);
  441. cre->fightValue = node["fightValue"].Float();
  442. cre->AIValue = node["aiValue"].Float();
  443. cre->growth = node["growth"].Float();
  444. cre->hordeGrowth = node["horde"].Float(); // Needed at least until configurable buildings
  445. cre->addBonus(node["hitPoints"].Float(), Bonus::STACK_HEALTH);
  446. cre->addBonus(node["speed"].Float(), Bonus::STACKS_SPEED);
  447. cre->addBonus(node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  448. cre->addBonus(node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  449. cre->addBonus(node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
  450. cre->addBonus(node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
  451. cre->ammMin = node["advMapAmount"]["min"].Float();
  452. cre->ammMax = node["advMapAmount"]["max"].Float();
  453. assert(cre->ammMin <= cre->ammMax);
  454. if (!node["shots"].isNull())
  455. cre->addBonus(node["shots"].Float(), Bonus::SHOTS);
  456. if (node["spellPoints"].isNull())
  457. cre->addBonus(node["spellPoints"].Float(), Bonus::CASTS);
  458. cre->doubleWide = node["doubleWide"].Bool();
  459. loadStackExperience(cre, node["stackExperience"]);
  460. loadJsonAnimation(cre, node["graphics"]);
  461. loadCreatureJson(cre, node);
  462. return cre;
  463. }
  464. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  465. {
  466. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  467. cre->animation.troopCountLocationOffset = graphics["troopCountLocationOffset"].Float();
  468. const JsonNode & animationTime = graphics["animationTime"];
  469. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  470. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  471. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  472. const JsonNode & missile = graphics["missile"];
  473. const JsonNode & offsets = missile["offset"];
  474. cre->animation.upperRightMissleOffsetX = offsets["upperX"].Float();
  475. cre->animation.upperRightMissleOffsetY = offsets["upperY"].Float();
  476. cre->animation.rightMissleOffsetX = offsets["middleX"].Float();
  477. cre->animation.rightMissleOffsetY = offsets["middleY"].Float();
  478. cre->animation.lowerRightMissleOffsetX = offsets["lowerX"].Float();
  479. cre->animation.lowerRightMissleOffsetY = offsets["lowerY"].Float();
  480. cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float();
  481. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  482. cre->advMapDef = graphics["map"].String();
  483. cre->iconIndex = graphics["iconIndex"].Float();
  484. }
  485. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  486. {
  487. creature->level = config["level"].Float();
  488. creature->animDefName = config["graphics"]["animation"].String();
  489. if (config["abilities"].getType() == JsonNode::DATA_STRUCT)
  490. {
  491. BOOST_FOREACH(auto &ability, config["abilities"].Struct())
  492. {
  493. if (!ability.second.isNull())
  494. {
  495. auto b = JsonUtils::parseBonus(ability.second);
  496. b->source = Bonus::CREATURE_ABILITY;
  497. b->duration = Bonus::PERMANENT;
  498. creature->addNewBonus(b);
  499. }
  500. }
  501. }
  502. else
  503. {
  504. BOOST_FOREACH(const JsonNode &ability, config["abilities"].Vector())
  505. {
  506. if (ability.getType() == JsonNode::DATA_VECTOR)
  507. AddAbility(creature, ability.Vector()); // used only for H3 creatures
  508. else
  509. {
  510. auto b = JsonUtils::parseBonus(ability);
  511. b->source = Bonus::CREATURE_ABILITY;
  512. b->duration = Bonus::PERMANENT;
  513. creature->addNewBonus(b);
  514. }
  515. }
  516. }
  517. VLC->modh->identifiers.requestIdentifier(std::string("faction.") + config["faction"].String(), [=](si32 faction)
  518. {
  519. creature->faction = faction;
  520. });
  521. BOOST_FOREACH(const JsonNode &value, config["upgrades"].Vector())
  522. {
  523. VLC->modh->identifiers.requestIdentifier(std::string("creature.") + value.String(), [=](si32 identifier)
  524. {
  525. creature->upgrades.insert(CreatureID(identifier));
  526. });
  527. }
  528. if(config["hasDoubleWeek"].Bool())
  529. doubledCreatures.insert(creature->idNumber);
  530. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  531. creature->special = config["special"].Bool() || config["disabled"].Bool();
  532. const JsonNode & sounds = config["sound"];
  533. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  534. GET_SOUND_VALUE(attack);
  535. GET_SOUND_VALUE(defend);
  536. GET_SOUND_VALUE(killed);
  537. GET_SOUND_VALUE(move);
  538. GET_SOUND_VALUE(shoot);
  539. GET_SOUND_VALUE(wince);
  540. GET_SOUND_VALUE(startMoving);
  541. GET_SOUND_VALUE(endMoving);
  542. #undef GET_SOUND_VALUE
  543. }
  544. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  545. {
  546. BOOST_FOREACH (const JsonNode &exp, input.Vector())
  547. {
  548. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  549. bonus->source = Bonus::STACK_EXPERIENCE;
  550. bonus->duration = Bonus::PERMANENT;
  551. const JsonVector &values = exp["values"].Vector();
  552. int lowerLimit = 1;//, upperLimit = 255;
  553. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  554. {
  555. BOOST_FOREACH (const JsonNode &val, values)
  556. {
  557. if (val.Bool() == true)
  558. {
  559. bonus->limiter = make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  560. creature->addNewBonus (new Bonus(*bonus)); //bonuses must be unique objects
  561. break; //TODO: allow bonuses to turn off?
  562. }
  563. ++lowerLimit;
  564. }
  565. }
  566. else
  567. {
  568. int lastVal = 0;
  569. BOOST_FOREACH (const JsonNode &val, values)
  570. {
  571. if (val.Float() != lastVal)
  572. {
  573. bonus->val = val.Float() - lastVal;
  574. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  575. creature->addNewBonus (new Bonus(*bonus));
  576. }
  577. lastVal = val.Float();
  578. ++lowerLimit;
  579. }
  580. }
  581. delete bonus;
  582. }
  583. }
  584. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  585. {
  586. bool enable = false; //some bonuses are activated with values 2 or 1
  587. std::string buf = parser.readString();
  588. std::string mod = parser.readString();
  589. switch (buf[0])
  590. {
  591. case 'H':
  592. b.type = Bonus::STACK_HEALTH;
  593. b.valType = Bonus::PERCENT_TO_BASE;
  594. break;
  595. case 'A':
  596. b.type = Bonus::PRIMARY_SKILL;
  597. b.subtype = PrimarySkill::ATTACK;
  598. break;
  599. case 'D':
  600. b.type = Bonus::PRIMARY_SKILL;
  601. b.subtype = PrimarySkill::DEFENSE;
  602. break;
  603. case 'M': //Max damage
  604. b.type = Bonus::CREATURE_DAMAGE;
  605. b.subtype = 2;
  606. break;
  607. case 'm': //Min damage
  608. b.type = Bonus::CREATURE_DAMAGE;
  609. b.subtype = 1;
  610. break;
  611. case 'S':
  612. b.type = Bonus::STACKS_SPEED; break;
  613. case 'O':
  614. b.type = Bonus::SHOTS; break;
  615. case 'b':
  616. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  617. case 'C':
  618. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  619. case 'd':
  620. b.type = Bonus::DEFENSIVE_STANCE; break;
  621. case 'e':
  622. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  623. b.subtype = 0;
  624. break;
  625. case 'E':
  626. b.type = Bonus::DEATH_STARE;
  627. b.subtype = 0; //Gorgon
  628. break;
  629. case 'F':
  630. b.type = Bonus::FEAR; break;
  631. case 'g':
  632. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  633. b.subtype = -1; //all magic schools
  634. break;
  635. case 'P':
  636. b.type = Bonus::CASTS; break;
  637. case 'R':
  638. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  639. case 'W':
  640. b.type = Bonus::MAGIC_RESISTANCE;
  641. b.subtype = 0; //otherwise creature window goes crazy
  642. break;
  643. case 'f': //on-off skill
  644. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  645. switch (mod[0])
  646. {
  647. case 'A':
  648. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  649. case 'b':
  650. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  651. case 'B':
  652. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  653. case 'c':
  654. b.type = Bonus::JOUSTING; break;
  655. case 'D':
  656. b.type = Bonus::ADDITIONAL_ATTACK; break;
  657. case 'f':
  658. b.type = Bonus::FEARLESS; break;
  659. case 'F':
  660. b.type = Bonus::FLYING; break;
  661. case 'm':
  662. b.type = Bonus::SELF_MORALE; break;
  663. case 'M':
  664. b.type = Bonus::NO_MORALE; break;
  665. case 'p': //Mind spells
  666. case 'P':
  667. b.type = Bonus::MIND_IMMUNITY; break;
  668. case 'r':
  669. b.type = Bonus::REBIRTH; //on/off? makes sense?
  670. b.subtype = 0;
  671. b.val = 20; //arbitrary value
  672. break;
  673. case 'R':
  674. b.type = Bonus::BLOCKS_RETALIATION; break;
  675. case 's':
  676. b.type = Bonus::FREE_SHOOTING; break;
  677. case 'u':
  678. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  679. case 'U':
  680. b.type = Bonus::UNDEAD; break;
  681. default:
  682. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  683. return;
  684. break;
  685. }
  686. break;
  687. case 'w': //specific spell immunities, enabled/disabled
  688. enable = true;
  689. switch (mod[0])
  690. {
  691. case 'B': //Blind
  692. b.type = Bonus::SPELL_IMMUNITY;
  693. b.subtype = SpellID::BLIND;
  694. break;
  695. case 'H': //Hypnotize
  696. b.type = Bonus::SPELL_IMMUNITY;
  697. b.subtype = SpellID::HYPNOTIZE;
  698. break;
  699. case 'I': //Implosion
  700. b.type = Bonus::SPELL_IMMUNITY;
  701. b.subtype = SpellID::IMPLOSION;
  702. break;
  703. case 'K': //Berserk
  704. b.type = Bonus::SPELL_IMMUNITY;
  705. b.subtype = SpellID::BERSERK;
  706. break;
  707. case 'M': //Meteor Shower
  708. b.type = Bonus::SPELL_IMMUNITY;
  709. b.subtype = SpellID::METEOR_SHOWER;
  710. break;
  711. case 'N': //dispell beneficial spells
  712. b.type = Bonus::SPELL_IMMUNITY;
  713. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  714. break;
  715. case 'R': //Armageddon
  716. b.type = Bonus::SPELL_IMMUNITY;
  717. b.subtype = SpellID::ARMAGEDDON;
  718. break;
  719. case 'S': //Slow
  720. b.type = Bonus::SPELL_IMMUNITY;
  721. b.subtype = SpellID::SLOW;
  722. break;
  723. case '6':
  724. case '7':
  725. case '8':
  726. case '9':
  727. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  728. b.val = std::atoi(mod.c_str()) - 5;
  729. break;
  730. case ':':
  731. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  732. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  733. break;
  734. case 'F':
  735. b.type = Bonus::FIRE_IMMUNITY;
  736. b.subtype = 1; //not positive
  737. break;
  738. case 'O':
  739. b.type = Bonus::FIRE_IMMUNITY;
  740. b.subtype = 2; //only direct damage
  741. break;
  742. case 'f':
  743. b.type = Bonus::FIRE_IMMUNITY;
  744. b.subtype = 0; //all
  745. break;
  746. case 'C':
  747. b.type = Bonus::WATER_IMMUNITY;
  748. b.subtype = 1; //not positive
  749. break;
  750. case 'W':
  751. b.type = Bonus::WATER_IMMUNITY;
  752. b.subtype = 2; //only direct damage
  753. break;
  754. case 'w':
  755. b.type = Bonus::WATER_IMMUNITY;
  756. b.subtype = 0; //all
  757. break;
  758. case 'E':
  759. b.type = Bonus::EARTH_IMMUNITY;
  760. b.subtype = 2; //only direct damage
  761. break;
  762. case 'e':
  763. b.type = Bonus::EARTH_IMMUNITY;
  764. b.subtype = 0; //all
  765. break;
  766. case 'A':
  767. b.type = Bonus::AIR_IMMUNITY;
  768. b.subtype = 2; //only direct damage
  769. break;
  770. case 'a':
  771. b.type = Bonus::AIR_IMMUNITY;
  772. b.subtype = 0; //all
  773. break;
  774. case 'D':
  775. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  776. break;
  777. case '0':
  778. b.type = Bonus::RECEPTIVE;
  779. break;
  780. case 'm':
  781. b.type = Bonus::MIND_IMMUNITY;
  782. break;
  783. default:
  784. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  785. return;
  786. }
  787. break;
  788. case 'i':
  789. enable = true;
  790. b.type = Bonus::NO_DISTANCE_PENALTY;
  791. break;
  792. case 'o':
  793. enable = true;
  794. b.type = Bonus::NO_WALL_PENALTY;
  795. break;
  796. case 'a':
  797. case 'c':
  798. case 'K':
  799. case 'k':
  800. b.type = Bonus::SPELL_AFTER_ATTACK;
  801. b.subtype = stringToNumber(mod);
  802. break;
  803. case 'h':
  804. b.type= Bonus::HATE;
  805. b.subtype = stringToNumber(mod);
  806. break;
  807. case 'p':
  808. case 'J':
  809. b.type = Bonus::SPELL_BEFORE_ATTACK;
  810. b.subtype = stringToNumber(mod);
  811. b.additionalInfo = 3; //always expert?
  812. break;
  813. case 'r':
  814. b.type = Bonus::HP_REGENERATION;
  815. b.val = stringToNumber(mod);
  816. break;
  817. case 's':
  818. b.type = Bonus::ENCHANTED;
  819. b.subtype = stringToNumber(mod);
  820. b.valType = Bonus::INDEPENDENT_MAX;
  821. break;
  822. default:
  823. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  824. return;
  825. break;
  826. }
  827. switch (mod[0])
  828. {
  829. case '+':
  830. case '=': //should we allow percent values to stack or pick highest?
  831. b.valType = Bonus::ADDITIVE_VALUE;
  832. break;
  833. }
  834. //limiters, range
  835. si32 lastVal, curVal, lastLev = 0;
  836. if (enable) //0 and 2 means non-active, 1 - active
  837. {
  838. if (b.type != Bonus::REBIRTH)
  839. b.val = 0; //on-off ability, no value specified
  840. curVal = parser.readNumber();// 0 level is never active
  841. for (int i = 1; i < 11; ++i)
  842. {
  843. curVal = parser.readNumber();
  844. if (curVal == 1)
  845. {
  846. b.limiter.reset (new RankRangeLimiter(i));
  847. bl.push_back(new Bonus(b));
  848. break; //never turned off it seems
  849. }
  850. }
  851. }
  852. else
  853. {
  854. lastVal = parser.readNumber(); //basic value, not particularly useful but existent
  855. for (int i = 1; i < 11; ++i)
  856. {
  857. curVal = parser.readNumber();
  858. if (b.type == Bonus::HATE)
  859. curVal *= 10; //odd fix
  860. if (curVal > lastVal) //threshold, add new bonus
  861. {
  862. b.val = curVal - lastVal;
  863. lastVal = curVal;
  864. b.limiter.reset (new RankRangeLimiter(i));
  865. bl.push_back(new Bonus(b));
  866. lastLev = i; //start new range from here, i = previous rank
  867. }
  868. else if (curVal < lastVal)
  869. {
  870. b.val = lastVal;
  871. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  872. }
  873. }
  874. }
  875. }
  876. int CCreatureHandler::stringToNumber(std::string & s)
  877. {
  878. boost::algorithm::replace_first(s,"#",""); //drop hash character
  879. return std::atoi(s.c_str());
  880. }
  881. CCreatureHandler::~CCreatureHandler()
  882. {
  883. }
  884. CreatureID CCreatureHandler::pickRandomMonster(const boost::function<int()> &randGen, int tier) const
  885. {
  886. int r = 0;
  887. if(tier == -1) //pick any allowed creature
  888. {
  889. do
  890. {
  891. r = vstd::pickRandomElementOf(creatures, randGen)->idNumber;
  892. } while (VLC->creh->creatures[r] && VLC->creh->creatures[r]->special); // find first "not special" creature
  893. }
  894. else
  895. {
  896. assert(vstd::iswithin(tier, 1, 7));
  897. std::vector<CreatureID> allowed;
  898. BOOST_FOREACH(const CBonusSystemNode *b, creaturesOfLevel[tier].getChildrenNodes())
  899. {
  900. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  901. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  902. if(crea && !crea->special)
  903. allowed.push_back(crea->idNumber);
  904. }
  905. if(!allowed.size())
  906. {
  907. logGlobal->warnStream() << "Cannot pick a random creature of tier " << tier << "!";
  908. return CreatureID::NONE;
  909. }
  910. return vstd::pickRandomElementOf(allowed, randGen);
  911. }
  912. return CreatureID(r);
  913. }
  914. void CCreatureHandler::addBonusForTier(int tier, Bonus *b)
  915. {
  916. assert(vstd::iswithin(tier, 1, 7));
  917. creaturesOfLevel[tier].addNewBonus(b);
  918. }
  919. void CCreatureHandler::addBonusForAllCreatures(Bonus *b)
  920. {
  921. allCreatures.addNewBonus(b);
  922. }
  923. void CCreatureHandler::buildBonusTreeForTiers()
  924. {
  925. BOOST_FOREACH(CCreature *c, creatures)
  926. {
  927. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  928. c->attachTo(&creaturesOfLevel[c->level]);
  929. else
  930. c->attachTo(&creaturesOfLevel[0]);
  931. }
  932. BOOST_FOREACH(CBonusSystemNode &b, creaturesOfLevel)
  933. b.attachTo(&allCreatures);
  934. }
  935. void CCreatureHandler::deserializationFix()
  936. {
  937. buildBonusTreeForTiers();
  938. }