CCreatureHandler.cpp 29 KB

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