CCreatureHandler.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. #include "StdInc.h"
  2. #include "CCreatureHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "VCMI_Lib.h"
  6. #include "CGameState.h"
  7. #include "CTownHandler.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. #include "mapObjects/CObjectClassesHandler.h"
  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. auto added = std::make_shared<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. void CCreature::setId(CreatureID ID)
  116. {
  117. idNumber = ID;
  118. for(auto bonus : getExportedBonusList())
  119. {
  120. if(bonus->source == Bonus::CREATURE_ABILITY)
  121. bonus->sid = ID;
  122. }
  123. CBonusSystemNode::treeHasChanged();
  124. }
  125. static void AddAbility(CCreature *cre, const JsonVector &ability_vec)
  126. {
  127. auto nsf = std::make_shared<Bonus>();
  128. std::string type = ability_vec[0].String();
  129. auto it = bonusNameMap.find(type);
  130. if (it == bonusNameMap.end()) {
  131. if (type == "DOUBLE_WIDE")
  132. cre->doubleWide = true;
  133. else if (type == "ENEMY_MORALE_DECREASING") {
  134. cre->addBonus(-1, Bonus::MORALE);
  135. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  136. }
  137. else if (type == "ENEMY_LUCK_DECREASING") {
  138. cre->addBonus(-1, Bonus::LUCK);
  139. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  140. } else
  141. logGlobal->errorStream() << "Error: invalid ability type " << type << " in creatures config";
  142. return;
  143. }
  144. nsf->type = it->second;
  145. JsonUtils::parseTypedBonusShort(ability_vec,nsf);
  146. nsf->source = Bonus::CREATURE_ABILITY;
  147. nsf->sid = cre->idNumber;
  148. cre->addNewBonus(nsf);
  149. }
  150. CCreatureHandler::CCreatureHandler()
  151. : expAfterUpgrade(0)
  152. {
  153. VLC->creh = this;
  154. allCreatures.setDescription("All creatures");
  155. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  156. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  157. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  158. loadCommanders();
  159. }
  160. const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const
  161. {
  162. boost::optional<si32> index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier);
  163. if(!index)
  164. throw std::runtime_error("Creature not found "+identifier);
  165. return creatures[*index];
  166. }
  167. void CCreatureHandler::loadCommanders()
  168. {
  169. JsonNode data(ResourceID("config/commanders.json"));
  170. data.setMeta("core"); // assume that commanders are in core mod (for proper bonuses resolution)
  171. const JsonNode & config = data; // switch to const data accessors
  172. for (auto bonus : config["bonusPerLevel"].Vector())
  173. {
  174. commanderLevelPremy.push_back(JsonUtils::parseBonus(bonus.Vector()));
  175. }
  176. int i = 0;
  177. for (auto skill : config["skillLevels"].Vector())
  178. {
  179. skillLevels.push_back (std::vector<ui8>());
  180. for (auto skillLevel : skill["levels"].Vector())
  181. {
  182. skillLevels[i].push_back (skillLevel.Float());
  183. }
  184. ++i;
  185. }
  186. for (auto ability : config["abilityRequirements"].Vector())
  187. {
  188. std::pair <std::shared_ptr<Bonus>, std::pair <ui8, ui8> > a;
  189. a.first = JsonUtils::parseBonus (ability["ability"].Vector());
  190. a.second.first = ability["skills"].Vector()[0].Float();
  191. a.second.second = ability["skills"].Vector()[1].Float();
  192. skillRequirements.push_back (a);
  193. }
  194. }
  195. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses)
  196. {
  197. auto makeBonusNode = [&](std::string type) -> JsonNode
  198. {
  199. JsonNode ret;
  200. ret["type"].String() = type;
  201. return ret;
  202. };
  203. static const std::map<std::string, JsonNode> abilityMap =
  204. {
  205. {"FLYING_ARMY", makeBonusNode("FLYING")},
  206. {"SHOOTING_ARMY", makeBonusNode("SHOOTER")},
  207. {"SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON")},
  208. {"const_free_attack", makeBonusNode("BLOCKS_RETALIATION")},
  209. {"IS_UNDEAD", makeBonusNode("UNDEAD")},
  210. {"const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY")},
  211. {"const_jousting", makeBonusNode("JOUSTING")},
  212. {"KING_1", makeBonusNode("KING1")},
  213. {"KING_2", makeBonusNode("KING2")},
  214. {"KING_3", makeBonusNode("KING3")},
  215. {"const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY")},
  216. {"CATAPULT", makeBonusNode("CATAPULT")},
  217. {"MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT")},
  218. {"IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY")},
  219. {"HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH")}
  220. };
  221. auto hasAbility = [&](const std::string name) -> bool
  222. {
  223. return boost::algorithm::find_first(bonuses, name);
  224. };
  225. for(auto a : abilityMap)
  226. {
  227. if(hasAbility(a.first))
  228. creature["abilities"][a.first] = a.second;
  229. }
  230. if(hasAbility("DOUBLE_WIDE"))
  231. creature["doubleWide"].Bool() = true;
  232. if(hasAbility("const_raises_morale"))
  233. {
  234. JsonNode node = makeBonusNode("MORALE");
  235. node["val"].Float() = 1;
  236. node["propagator"].String() = "HERO";
  237. creature["abilities"]["const_raises_morale"] = node;
  238. }
  239. if(hasAbility("const_lowers_morale"))
  240. {
  241. JsonNode node = makeBonusNode("MORALE");
  242. node["val"].Float() = -1;
  243. node["effectRange"].String() = "ONLY_ENEMY_ARMY";
  244. creature["abilities"]["const_lowers_morale"] = node;
  245. }
  246. }
  247. std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
  248. {
  249. creatures.resize(dataSize);
  250. std::vector<JsonNode> h3Data;
  251. h3Data.reserve(dataSize);
  252. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  253. parser.endLine(); // header
  254. // this file is a bit different in some of Russian localisations:
  255. //ENG: Singular Plural Wood ...
  256. //RUS: Singular Plural Plural2 Wood ...
  257. // Try to detect which version this is by header
  258. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  259. size_t namesCount;
  260. {
  261. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  262. throw std::runtime_error("Incorrect format of CrTraits.txt");
  263. if (parser.readString() == "Plural2")
  264. namesCount = 3;
  265. else
  266. namesCount = 2;
  267. parser.endLine();
  268. }
  269. for (size_t i=0; i<dataSize; i++)
  270. {
  271. //loop till non-empty line
  272. while (parser.isNextEntryEmpty())
  273. parser.endLine();
  274. JsonNode data;
  275. data["name"]["singular"].String() = parser.readString();
  276. if (namesCount == 3)
  277. parser.readString();
  278. data["name"]["plural"].String() = parser.readString();
  279. for(int v=0; v<7; ++v)
  280. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  281. data["fightValue"].Float() = parser.readNumber();
  282. data["aiValue"].Float() = parser.readNumber();
  283. data["growth"].Float() = parser.readNumber();
  284. data["horde"].Float() = parser.readNumber();
  285. data["hitPoints"].Float() = parser.readNumber();
  286. data["speed"].Float() = parser.readNumber();
  287. data["attack"].Float() = parser.readNumber();
  288. data["defense"].Float() = parser.readNumber();
  289. data["damage"]["min"].Float() = parser.readNumber();
  290. data["damage"]["max"].Float() = parser.readNumber();
  291. if (float shots = parser.readNumber())
  292. data["shots"].Float() = shots;
  293. if (float spells = parser.readNumber())
  294. data["spellPoints"].Float() = spells;
  295. data["advMapAmount"]["min"].Float() = parser.readNumber();
  296. data["advMapAmount"]["max"].Float() = parser.readNumber();
  297. data["abilityText"].String() = parser.readString();
  298. loadBonuses(data, parser.readString()); //Attributes
  299. h3Data.push_back(data);
  300. }
  301. loadAnimationInfo(h3Data);
  302. return h3Data;
  303. }
  304. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  305. {
  306. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  307. object->setId(CreatureID(creatures.size()));
  308. object->iconIndex = object->idNumber + 2;
  309. creatures.push_back(object);
  310. VLC->modh->identifiers.requestIdentifier(scope, "object", "monster", [=](si32 index)
  311. {
  312. JsonNode conf;
  313. conf.setMeta(scope);
  314. VLC->objtypeh->loadSubObject(object->identifier, conf, Obj::MONSTER, object->idNumber.num);
  315. if (!object->advMapDef.empty())
  316. {
  317. JsonNode templ;
  318. templ["animation"].String() = object->advMapDef;
  319. VLC->objtypeh->getHandlerFor(Obj::MONSTER, object->idNumber.num)->addTemplate(templ);
  320. }
  321. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  322. if (VLC->objtypeh->getHandlerFor(Obj::MONSTER, object->idNumber.num)->getTemplates().empty())
  323. VLC->objtypeh->removeSubObject(Obj::MONSTER, object->idNumber.num);
  324. });
  325. registerObject(scope, "creature", name, object->idNumber);
  326. for(auto node : data["extraNames"].Vector())
  327. {
  328. registerObject(scope, "creature", node.String(), object->idNumber);
  329. }
  330. }
  331. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  332. {
  333. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  334. object->setId(CreatureID(index));
  335. object->iconIndex = object->idNumber + 2;
  336. if(data["hasDoubleWeek"].Bool()) //
  337. {
  338. doubledCreatures.insert (object->idNumber); //we need to have id (or identifier) before it is inserted
  339. }
  340. assert(creatures[index] == nullptr); // ensure that this id was not loaded before
  341. creatures[index] = object;
  342. VLC->modh->identifiers.requestIdentifier(scope, "object", "monster", [=](si32 index)
  343. {
  344. JsonNode conf;
  345. conf.setMeta(scope);
  346. VLC->objtypeh->loadSubObject(object->identifier, conf, Obj::MONSTER, object->idNumber.num);
  347. if (!object->advMapDef.empty())
  348. {
  349. JsonNode templ;
  350. templ["animation"].String() = object->advMapDef;
  351. VLC->objtypeh->getHandlerFor(Obj::MONSTER, object->idNumber.num)->addTemplate(templ);
  352. }
  353. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  354. if (VLC->objtypeh->getHandlerFor(Obj::MONSTER, object->idNumber.num)->getTemplates().empty())
  355. VLC->objtypeh->removeSubObject(Obj::MONSTER, object->idNumber.num);
  356. });
  357. registerObject(scope, "creature", name, object->idNumber);
  358. for(auto & node : data["extraNames"].Vector())
  359. {
  360. registerObject(scope, "creature", node.String(), object->idNumber);
  361. }
  362. }
  363. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  364. {
  365. std::vector<bool> ret;
  366. for(const CCreature * crea : creatures)
  367. {
  368. ret.push_back(crea ? !crea->special : false);
  369. }
  370. return ret;
  371. }
  372. void CCreatureHandler::loadCrExpBon()
  373. {
  374. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  375. {
  376. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  377. Bonus b; //prototype with some default properties
  378. b.source = Bonus::STACK_EXPERIENCE;
  379. b.duration = Bonus::PERMANENT;
  380. b.valType = Bonus::ADDITIVE_VALUE;
  381. b.effectRange = Bonus::NO_LIMIT;
  382. b.additionalInfo = 0;
  383. b.turnsRemain = 0;
  384. BonusList bl;
  385. parser.endLine();
  386. parser.readString(); //ignore index
  387. loadStackExp(b, bl, parser);
  388. for(auto b : bl)
  389. addBonusForAllCreatures(b); //health bonus is common for all
  390. parser.endLine();
  391. for (int i = 1; i < 7; ++i)
  392. {
  393. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  394. {
  395. parser.readString(); //ignore index
  396. bl.clear();
  397. loadStackExp(b, bl, parser);
  398. for(auto b : bl)
  399. addBonusForTier(i, b);
  400. parser.endLine();
  401. }
  402. }
  403. for (int j = 0; j < 4; ++j) //tier 7
  404. {
  405. parser.readString(); //ignore index
  406. bl.clear();
  407. loadStackExp(b, bl, parser);
  408. for(auto b : bl)
  409. {
  410. addBonusForTier(7, b);
  411. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  412. }
  413. parser.endLine();
  414. }
  415. do //parse everything that's left
  416. {
  417. auto sid = parser.readNumber(); //id = this particular creature ID
  418. b.sid = sid;
  419. bl.clear();
  420. loadStackExp(b, bl, parser);
  421. for(auto b : bl)
  422. {
  423. creatures[sid]->addNewBonus(b); //add directly to CCreature Node
  424. }
  425. }
  426. while (parser.endLine());
  427. //Calculate rank exp values, formula appears complicated bu no parsing needed
  428. expRanks.resize(8);
  429. int dif = 0;
  430. int it = 8000; //ignore name of this variable
  431. expRanks[0].push_back(it);
  432. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  433. {
  434. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  435. dif += it/5;
  436. }
  437. for (int i = 1; i < 8; ++i)
  438. {
  439. dif = 0;
  440. it = 1000 * i;
  441. expRanks[i].push_back(it);
  442. for (int j = 1; j < 10; ++j)
  443. {
  444. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  445. dif += it/5;
  446. }
  447. }
  448. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  449. expBonParser.endLine(); //header
  450. maxExpPerBattle.resize(8);
  451. for (int i = 1; i < 8; ++i)
  452. {
  453. expBonParser.readString(); //index
  454. expBonParser.readString(); //float multiplier -> hardcoded
  455. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  456. expBonParser.readString(); //already calculated
  457. maxExpPerBattle[i] = expBonParser.readNumber();
  458. expRanks[i].push_back(expRanks[i].back() + expBonParser.readNumber());
  459. expBonParser.endLine();
  460. }
  461. //skeleton gets exp penalty
  462. creatures[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  463. creatures[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  464. //exp for tier >7, rank 11
  465. expRanks[0].push_back(147000);
  466. expAfterUpgrade = 75; //percent
  467. maxExpPerBattle[0] = maxExpPerBattle[7];
  468. }//end of Stack Experience
  469. }
  470. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  471. {
  472. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  473. parser.endLine(); // header
  474. parser.endLine();
  475. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++dd)
  476. {
  477. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  478. ;
  479. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  480. parser.endLine();
  481. }
  482. }
  483. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  484. {
  485. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  486. JsonNode & animationTime = graphics["animationTime"];
  487. animationTime["walk"].Float() = parser.readNumber();
  488. animationTime["attack"].Float() = parser.readNumber();
  489. animationTime["flight"].Float() = parser.readNumber();
  490. animationTime["idle"].Float() = 10.0;
  491. JsonNode & missile = graphics["missile"];
  492. JsonNode & offsets = missile["offset"];
  493. offsets["upperX"].Float() = parser.readNumber();
  494. offsets["upperY"].Float() = parser.readNumber();
  495. offsets["middleX"].Float() = parser.readNumber();
  496. offsets["middleY"].Float() = parser.readNumber();
  497. offsets["lowerX"].Float() = parser.readNumber();
  498. offsets["lowerY"].Float() = parser.readNumber();
  499. for(int i=0; i<12; i++)
  500. {
  501. JsonNode entry;
  502. entry.Float() = parser.readNumber();
  503. missile["frameAngles"].Vector().push_back(entry);
  504. }
  505. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  506. missile["attackClimaxFrame"].Float() = parser.readNumber();
  507. // assume that creature is not a shooter and should not have whole missile field
  508. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  509. missile["attackClimaxFrame"].Float() == 0)
  510. graphics.Struct().erase("missile");
  511. }
  512. CCreature * CCreatureHandler::loadFromJson(const JsonNode & node, const std::string & identifier)
  513. {
  514. auto cre = new CCreature();
  515. const JsonNode & name = node["name"];
  516. cre->identifier = identifier;
  517. cre->nameSing = name["singular"].String();
  518. cre->namePl = name["plural"].String();
  519. cre->cost = Res::ResourceSet(node["cost"]);
  520. cre->fightValue = node["fightValue"].Float();
  521. cre->AIValue = node["aiValue"].Float();
  522. cre->growth = node["growth"].Float();
  523. cre->hordeGrowth = node["horde"].Float(); // Needed at least until configurable buildings
  524. cre->addBonus(node["hitPoints"].Float(), Bonus::STACK_HEALTH);
  525. cre->addBonus(node["speed"].Float(), Bonus::STACKS_SPEED);
  526. cre->addBonus(node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  527. cre->addBonus(node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  528. cre->addBonus(node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
  529. cre->addBonus(node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
  530. assert(node["damage"]["min"].Float() <= node["damage"]["max"].Float());
  531. cre->ammMin = node["advMapAmount"]["min"].Float();
  532. cre->ammMax = node["advMapAmount"]["max"].Float();
  533. assert(cre->ammMin <= cre->ammMax);
  534. if (!node["shots"].isNull())
  535. cre->addBonus(node["shots"].Float(), Bonus::SHOTS);
  536. if (node["spellPoints"].isNull())
  537. cre->addBonus(node["spellPoints"].Float(), Bonus::CASTS);
  538. cre->doubleWide = node["doubleWide"].Bool();
  539. loadStackExperience(cre, node["stackExperience"]);
  540. loadJsonAnimation(cre, node["graphics"]);
  541. loadCreatureJson(cre, node);
  542. return cre;
  543. }
  544. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  545. {
  546. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  547. cre->animation.troopCountLocationOffset = graphics["troopCountLocationOffset"].Float();
  548. const JsonNode & animationTime = graphics["animationTime"];
  549. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  550. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  551. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  552. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  553. const JsonNode & missile = graphics["missile"];
  554. const JsonNode & offsets = missile["offset"];
  555. cre->animation.upperRightMissleOffsetX = offsets["upperX"].Float();
  556. cre->animation.upperRightMissleOffsetY = offsets["upperY"].Float();
  557. cre->animation.rightMissleOffsetX = offsets["middleX"].Float();
  558. cre->animation.rightMissleOffsetY = offsets["middleY"].Float();
  559. cre->animation.lowerRightMissleOffsetX = offsets["lowerX"].Float();
  560. cre->animation.lowerRightMissleOffsetY = offsets["lowerY"].Float();
  561. cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float();
  562. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  563. cre->advMapDef = graphics["map"].String();
  564. cre->smallIconName = graphics["iconSmall"].String();
  565. cre->largeIconName = graphics["iconLarge"].String();
  566. }
  567. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  568. {
  569. creature->level = config["level"].Float();
  570. creature->animDefName = config["graphics"]["animation"].String();
  571. //FIXME: MOD COMPATIBILITY
  572. if (config["abilities"].getType() == JsonNode::DATA_STRUCT)
  573. {
  574. for(auto &ability : config["abilities"].Struct())
  575. {
  576. if (!ability.second.isNull())
  577. {
  578. auto b = JsonUtils::parseBonus(ability.second);
  579. b->source = Bonus::CREATURE_ABILITY;
  580. b->duration = Bonus::PERMANENT;
  581. creature->addNewBonus(b);
  582. }
  583. }
  584. }
  585. else
  586. {
  587. for(const JsonNode &ability : config["abilities"].Vector())
  588. {
  589. if (ability.getType() == JsonNode::DATA_VECTOR)
  590. {
  591. assert(0); // should be unused now
  592. AddAbility(creature, ability.Vector()); // used only for H3 creatures
  593. }
  594. else
  595. {
  596. auto b = JsonUtils::parseBonus(ability);
  597. b->source = Bonus::CREATURE_ABILITY;
  598. b->duration = Bonus::PERMANENT;
  599. creature->addNewBonus(b);
  600. }
  601. }
  602. }
  603. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  604. {
  605. creature->faction = faction;
  606. });
  607. for(const JsonNode &value : config["upgrades"].Vector())
  608. {
  609. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  610. {
  611. creature->upgrades.insert(CreatureID(identifier));
  612. });
  613. }
  614. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  615. creature->special = config["special"].Bool() || config["disabled"].Bool();
  616. const JsonNode & sounds = config["sound"];
  617. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  618. GET_SOUND_VALUE(attack);
  619. GET_SOUND_VALUE(defend);
  620. GET_SOUND_VALUE(killed);
  621. GET_SOUND_VALUE(move);
  622. GET_SOUND_VALUE(shoot);
  623. GET_SOUND_VALUE(wince);
  624. GET_SOUND_VALUE(startMoving);
  625. GET_SOUND_VALUE(endMoving);
  626. #undef GET_SOUND_VALUE
  627. }
  628. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  629. {
  630. for (const JsonNode &exp : input.Vector())
  631. {
  632. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  633. bonus->source = Bonus::STACK_EXPERIENCE;
  634. bonus->duration = Bonus::PERMANENT;
  635. const JsonVector &values = exp["values"].Vector();
  636. int lowerLimit = 1;//, upperLimit = 255;
  637. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  638. {
  639. for (const JsonNode &val : values)
  640. {
  641. if (val.Bool() == true)
  642. {
  643. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  644. creature->addNewBonus (std::make_shared<Bonus>(*bonus)); //bonuses must be unique objects
  645. break; //TODO: allow bonuses to turn off?
  646. }
  647. ++lowerLimit;
  648. }
  649. }
  650. else
  651. {
  652. int lastVal = 0;
  653. for (const JsonNode &val : values)
  654. {
  655. if (val.Float() != lastVal)
  656. {
  657. bonus->val = val.Float() - lastVal;
  658. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  659. creature->addNewBonus (std::make_shared<Bonus>(*bonus));
  660. }
  661. lastVal = val.Float();
  662. ++lowerLimit;
  663. }
  664. }
  665. }
  666. }
  667. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  668. {
  669. bool enable = false; //some bonuses are activated with values 2 or 1
  670. std::string buf = parser.readString();
  671. std::string mod = parser.readString();
  672. switch (buf[0])
  673. {
  674. case 'H':
  675. b.type = Bonus::STACK_HEALTH;
  676. b.valType = Bonus::PERCENT_TO_BASE;
  677. break;
  678. case 'A':
  679. b.type = Bonus::PRIMARY_SKILL;
  680. b.subtype = PrimarySkill::ATTACK;
  681. break;
  682. case 'D':
  683. b.type = Bonus::PRIMARY_SKILL;
  684. b.subtype = PrimarySkill::DEFENSE;
  685. break;
  686. case 'M': //Max damage
  687. b.type = Bonus::CREATURE_DAMAGE;
  688. b.subtype = 2;
  689. break;
  690. case 'm': //Min damage
  691. b.type = Bonus::CREATURE_DAMAGE;
  692. b.subtype = 1;
  693. break;
  694. case 'S':
  695. b.type = Bonus::STACKS_SPEED; break;
  696. case 'O':
  697. b.type = Bonus::SHOTS; break;
  698. case 'b':
  699. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  700. case 'C':
  701. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  702. case 'd':
  703. b.type = Bonus::DEFENSIVE_STANCE; break;
  704. case 'e':
  705. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  706. b.subtype = 0;
  707. break;
  708. case 'E':
  709. b.type = Bonus::DEATH_STARE;
  710. b.subtype = 0; //Gorgon
  711. break;
  712. case 'F':
  713. b.type = Bonus::FEAR; break;
  714. case 'g':
  715. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  716. b.subtype = -1; //all magic schools
  717. break;
  718. case 'P':
  719. b.type = Bonus::CASTS; break;
  720. case 'R':
  721. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  722. case 'W':
  723. b.type = Bonus::MAGIC_RESISTANCE;
  724. b.subtype = 0; //otherwise creature window goes crazy
  725. break;
  726. case 'f': //on-off skill
  727. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  728. switch (mod[0])
  729. {
  730. case 'A':
  731. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  732. case 'b':
  733. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  734. case 'B':
  735. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  736. case 'c':
  737. b.type = Bonus::JOUSTING; break;
  738. case 'D':
  739. b.type = Bonus::ADDITIONAL_ATTACK; break;
  740. case 'f':
  741. b.type = Bonus::FEARLESS; break;
  742. case 'F':
  743. b.type = Bonus::FLYING; break;
  744. case 'm':
  745. b.type = Bonus::SELF_MORALE; break;
  746. case 'M':
  747. b.type = Bonus::NO_MORALE; break;
  748. case 'p': //Mind spells
  749. case 'P':
  750. b.type = Bonus::MIND_IMMUNITY; break;
  751. case 'r':
  752. b.type = Bonus::REBIRTH; //on/off? makes sense?
  753. b.subtype = 0;
  754. b.val = 20; //arbitrary value
  755. break;
  756. case 'R':
  757. b.type = Bonus::BLOCKS_RETALIATION; break;
  758. case 's':
  759. b.type = Bonus::FREE_SHOOTING; break;
  760. case 'u':
  761. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  762. case 'U':
  763. b.type = Bonus::UNDEAD; break;
  764. default:
  765. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  766. return;
  767. break;
  768. }
  769. break;
  770. case 'w': //specific spell immunities, enabled/disabled
  771. enable = true;
  772. switch (mod[0])
  773. {
  774. case 'B': //Blind
  775. b.type = Bonus::SPELL_IMMUNITY;
  776. b.subtype = SpellID::BLIND;
  777. b.additionalInfo = 0;//normal immunity
  778. break;
  779. case 'H': //Hypnotize
  780. b.type = Bonus::SPELL_IMMUNITY;
  781. b.subtype = SpellID::HYPNOTIZE;
  782. b.additionalInfo = 0;//normal immunity
  783. break;
  784. case 'I': //Implosion
  785. b.type = Bonus::SPELL_IMMUNITY;
  786. b.subtype = SpellID::IMPLOSION;
  787. b.additionalInfo = 0;//normal immunity
  788. break;
  789. case 'K': //Berserk
  790. b.type = Bonus::SPELL_IMMUNITY;
  791. b.subtype = SpellID::BERSERK;
  792. b.additionalInfo = 0;//normal immunity
  793. break;
  794. case 'M': //Meteor Shower
  795. b.type = Bonus::SPELL_IMMUNITY;
  796. b.subtype = SpellID::METEOR_SHOWER;
  797. b.additionalInfo = 0;//normal immunity
  798. break;
  799. case 'N': //dispell beneficial spells
  800. b.type = Bonus::SPELL_IMMUNITY;
  801. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  802. b.additionalInfo = 0;//normal immunity
  803. break;
  804. case 'R': //Armageddon
  805. b.type = Bonus::SPELL_IMMUNITY;
  806. b.subtype = SpellID::ARMAGEDDON;
  807. b.additionalInfo = 0;//normal immunity
  808. break;
  809. case 'S': //Slow
  810. b.type = Bonus::SPELL_IMMUNITY;
  811. b.subtype = SpellID::SLOW;
  812. b.additionalInfo = 0;//normal immunity
  813. break;
  814. case '6':
  815. case '7':
  816. case '8':
  817. case '9':
  818. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  819. b.val = std::atoi(mod.c_str()) - 5;
  820. break;
  821. case ':':
  822. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  823. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  824. break;
  825. case 'F':
  826. b.type = Bonus::FIRE_IMMUNITY;
  827. b.subtype = 1; //not positive
  828. break;
  829. case 'O':
  830. b.type = Bonus::FIRE_IMMUNITY;
  831. b.subtype = 2; //only direct damage
  832. break;
  833. case 'f':
  834. b.type = Bonus::FIRE_IMMUNITY;
  835. b.subtype = 0; //all
  836. break;
  837. case 'C':
  838. b.type = Bonus::WATER_IMMUNITY;
  839. b.subtype = 1; //not positive
  840. break;
  841. case 'W':
  842. b.type = Bonus::WATER_IMMUNITY;
  843. b.subtype = 2; //only direct damage
  844. break;
  845. case 'w':
  846. b.type = Bonus::WATER_IMMUNITY;
  847. b.subtype = 0; //all
  848. break;
  849. case 'E':
  850. b.type = Bonus::EARTH_IMMUNITY;
  851. b.subtype = 2; //only direct damage
  852. break;
  853. case 'e':
  854. b.type = Bonus::EARTH_IMMUNITY;
  855. b.subtype = 0; //all
  856. break;
  857. case 'A':
  858. b.type = Bonus::AIR_IMMUNITY;
  859. b.subtype = 2; //only direct damage
  860. break;
  861. case 'a':
  862. b.type = Bonus::AIR_IMMUNITY;
  863. b.subtype = 0; //all
  864. break;
  865. case 'D':
  866. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  867. break;
  868. case '0':
  869. b.type = Bonus::RECEPTIVE;
  870. break;
  871. case 'm':
  872. b.type = Bonus::MIND_IMMUNITY;
  873. break;
  874. default:
  875. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  876. return;
  877. }
  878. break;
  879. case 'i':
  880. enable = true;
  881. b.type = Bonus::NO_DISTANCE_PENALTY;
  882. break;
  883. case 'o':
  884. enable = true;
  885. b.type = Bonus::NO_WALL_PENALTY;
  886. break;
  887. case 'a':
  888. case 'c':
  889. case 'K':
  890. case 'k':
  891. b.type = Bonus::SPELL_AFTER_ATTACK;
  892. b.subtype = stringToNumber(mod);
  893. break;
  894. case 'h':
  895. b.type= Bonus::HATE;
  896. b.subtype = stringToNumber(mod);
  897. break;
  898. case 'p':
  899. case 'J':
  900. b.type = Bonus::SPELL_BEFORE_ATTACK;
  901. b.subtype = stringToNumber(mod);
  902. b.additionalInfo = 3; //always expert?
  903. break;
  904. case 'r':
  905. b.type = Bonus::HP_REGENERATION;
  906. b.val = stringToNumber(mod);
  907. break;
  908. case 's':
  909. b.type = Bonus::ENCHANTED;
  910. b.subtype = stringToNumber(mod);
  911. b.valType = Bonus::INDEPENDENT_MAX;
  912. break;
  913. default:
  914. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  915. return;
  916. break;
  917. }
  918. switch (mod[0])
  919. {
  920. case '+':
  921. case '=': //should we allow percent values to stack or pick highest?
  922. b.valType = Bonus::ADDITIVE_VALUE;
  923. break;
  924. }
  925. //limiters, range
  926. si32 lastVal, curVal, lastLev = 0;
  927. if (enable) //0 and 2 means non-active, 1 - active
  928. {
  929. if (b.type != Bonus::REBIRTH)
  930. b.val = 0; //on-off ability, no value specified
  931. curVal = parser.readNumber();// 0 level is never active
  932. for (int i = 1; i < 11; ++i)
  933. {
  934. curVal = parser.readNumber();
  935. if (curVal == 1)
  936. {
  937. b.limiter.reset (new RankRangeLimiter(i));
  938. bl.push_back(std::make_shared<Bonus>(b));
  939. break; //never turned off it seems
  940. }
  941. }
  942. }
  943. else
  944. {
  945. lastVal = parser.readNumber();
  946. if (b.type == Bonus::HATE)
  947. lastVal *= 10; //odd fix
  948. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  949. for (int i = 1; i < 11; ++i)
  950. {
  951. curVal = parser.readNumber();
  952. if (b.type == Bonus::HATE)
  953. curVal *= 10; //odd fix
  954. if (curVal > lastVal) //threshold, add new bonus
  955. {
  956. b.val = curVal - lastVal;
  957. lastVal = curVal;
  958. b.limiter.reset (new RankRangeLimiter(i));
  959. bl.push_back(std::make_shared<Bonus>(b));
  960. lastLev = i; //start new range from here, i = previous rank
  961. }
  962. else if (curVal < lastVal)
  963. {
  964. b.val = lastVal;
  965. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  966. }
  967. }
  968. }
  969. }
  970. int CCreatureHandler::stringToNumber(std::string & s)
  971. {
  972. boost::algorithm::replace_first(s,"#",""); //drop hash character
  973. return std::atoi(s.c_str());
  974. }
  975. CCreatureHandler::~CCreatureHandler()
  976. {
  977. for(auto & creature : creatures)
  978. creature.dellNull();
  979. for(auto & p : skillRequirements)
  980. p.first = nullptr;
  981. }
  982. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  983. {
  984. int r = 0;
  985. if(tier == -1) //pick any allowed creature
  986. {
  987. do
  988. {
  989. r = (*RandomGeneratorUtil::nextItem(creatures, rand))->idNumber;
  990. } while (VLC->creh->creatures[r] && VLC->creh->creatures[r]->special); // find first "not special" creature
  991. }
  992. else
  993. {
  994. assert(vstd::iswithin(tier, 1, 7));
  995. std::vector<CreatureID> allowed;
  996. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  997. {
  998. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  999. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  1000. if(crea && !crea->special)
  1001. allowed.push_back(crea->idNumber);
  1002. }
  1003. if(!allowed.size())
  1004. {
  1005. logGlobal->warnStream() << "Cannot pick a random creature of tier " << tier << "!";
  1006. return CreatureID::NONE;
  1007. }
  1008. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1009. }
  1010. assert (r >= 0); //should always be, but it crashed
  1011. return CreatureID(r);
  1012. }
  1013. void CCreatureHandler::addBonusForTier(int tier, std::shared_ptr<Bonus> b)
  1014. {
  1015. assert(vstd::iswithin(tier, 1, 7));
  1016. creaturesOfLevel[tier].addNewBonus(b);
  1017. }
  1018. void CCreatureHandler::addBonusForAllCreatures(std::shared_ptr<Bonus> b)
  1019. {
  1020. allCreatures.addNewBonus(b);
  1021. }
  1022. void CCreatureHandler::buildBonusTreeForTiers()
  1023. {
  1024. for(CCreature *c : creatures)
  1025. {
  1026. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  1027. c->attachTo(&creaturesOfLevel[c->level]);
  1028. else
  1029. c->attachTo(&creaturesOfLevel[0]);
  1030. }
  1031. for(CBonusSystemNode &b : creaturesOfLevel)
  1032. b.attachTo(&allCreatures);
  1033. }
  1034. void CCreatureHandler::afterLoadFinalization()
  1035. {
  1036. }
  1037. void CCreatureHandler::deserializationFix()
  1038. {
  1039. buildBonusTreeForTiers();
  1040. }