CCreatureHandler.cpp 31 KB

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