CommonConstructors.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. #include "StdInc.h"
  2. #include "CommonConstructors.h"
  3. #include "CGTownInstance.h"
  4. #include "CGHeroInstance.h"
  5. #include "CBank.h"
  6. #include "../mapping/CMap.h"
  7. #include "../CHeroHandler.h"
  8. #include "../CCreatureHandler.h"
  9. #include "JsonRandom.h"
  10. #include "../CModHandler.h"
  11. #include "../IGameCallback.h"
  12. /*
  13. * CommonConstructors.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. CObstacleConstructor::CObstacleConstructor()
  22. {
  23. }
  24. bool CObstacleConstructor::isStaticObject()
  25. {
  26. return true;
  27. }
  28. CTownInstanceConstructor::CTownInstanceConstructor():
  29. faction(nullptr)
  30. {
  31. }
  32. void CTownInstanceConstructor::initTypeData(const JsonNode & input)
  33. {
  34. VLC->modh->identifiers.requestIdentifier("faction", input["faction"], [&](si32 index)
  35. {
  36. faction = VLC->townh->factions[index];
  37. });
  38. filtersJson = input["filters"];
  39. }
  40. void CTownInstanceConstructor::afterLoadFinalization()
  41. {
  42. assert(faction);
  43. for (auto entry : filtersJson.Struct())
  44. {
  45. filters[entry.first] = LogicalExpression<BuildingID>(entry.second, [this](const JsonNode & node)
  46. {
  47. return BuildingID(VLC->modh->identifiers.getIdentifier("building." + faction->identifier, node.Vector()[0]).get());
  48. });
  49. }
  50. }
  51. bool CTownInstanceConstructor::objectFilter(const CGObjectInstance * object, const ObjectTemplate & templ) const
  52. {
  53. auto town = dynamic_cast<const CGTownInstance *>(object);
  54. auto buildTest = [&](const BuildingID & id)
  55. {
  56. return town->hasBuilt(id);
  57. };
  58. if (filters.count(templ.stringID))
  59. return filters.at(templ.stringID).test(buildTest);
  60. return false;
  61. }
  62. CGObjectInstance * CTownInstanceConstructor::create(ObjectTemplate tmpl) const
  63. {
  64. CGTownInstance * obj = createTyped(tmpl);
  65. obj->town = faction->town;
  66. obj->tempOwner = PlayerColor::NEUTRAL;
  67. return obj;
  68. }
  69. void CTownInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
  70. {
  71. auto templ = getOverride(object->cb->getTile(object->pos)->terType, object);
  72. if (templ)
  73. object->appearance = templ.get();
  74. }
  75. CHeroInstanceConstructor::CHeroInstanceConstructor()
  76. {
  77. }
  78. void CHeroInstanceConstructor::initTypeData(const JsonNode & input)
  79. {
  80. VLC->modh->identifiers.requestIdentifier("heroClass", input["heroClass"],
  81. [&](si32 index) { heroClass = VLC->heroh->classes.heroClasses[index]; });
  82. filtersJson = input["filters"];
  83. }
  84. void CHeroInstanceConstructor::afterLoadFinalization()
  85. {
  86. for (auto entry : filtersJson.Struct())
  87. {
  88. filters[entry.first] = LogicalExpression<HeroTypeID>(entry.second, [this](const JsonNode & node)
  89. {
  90. return HeroTypeID(VLC->modh->identifiers.getIdentifier("hero", node.Vector()[0]).get());
  91. });
  92. }
  93. }
  94. bool CHeroInstanceConstructor::objectFilter(const CGObjectInstance * object, const ObjectTemplate & templ) const
  95. {
  96. auto hero = dynamic_cast<const CGHeroInstance *>(object);
  97. auto heroTest = [&](const HeroTypeID & id)
  98. {
  99. return hero->type->ID == id;
  100. };
  101. if (filters.count(templ.stringID))
  102. {
  103. return filters.at(templ.stringID).test(heroTest);
  104. }
  105. return false;
  106. }
  107. CGObjectInstance * CHeroInstanceConstructor::create(ObjectTemplate tmpl) const
  108. {
  109. CGHeroInstance * obj = createTyped(tmpl);
  110. obj->type = nullptr; //FIXME: set to valid value. somehow.
  111. return obj;
  112. }
  113. void CHeroInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
  114. {
  115. }
  116. CDwellingInstanceConstructor::CDwellingInstanceConstructor()
  117. {
  118. }
  119. void CDwellingInstanceConstructor::initTypeData(const JsonNode & input)
  120. {
  121. const JsonVector & levels = input["creatures"].Vector();
  122. availableCreatures.resize(levels.size());
  123. for (size_t i=0; i<levels.size(); i++)
  124. {
  125. const JsonVector & creatures = levels[i].Vector();
  126. availableCreatures[i].resize(creatures.size());
  127. for (size_t j=0; j<creatures.size(); j++)
  128. {
  129. VLC->modh->identifiers.requestIdentifier("creature", creatures[j], [=] (si32 index)
  130. {
  131. availableCreatures[i][j] = VLC->creh->creatures[index];
  132. });
  133. }
  134. assert(!availableCreatures[i].empty());
  135. }
  136. guards = input["guards"];
  137. }
  138. bool CDwellingInstanceConstructor::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  139. {
  140. return false;
  141. }
  142. CGObjectInstance * CDwellingInstanceConstructor::create(ObjectTemplate tmpl) const
  143. {
  144. CGDwelling * obj = createTyped(tmpl);
  145. obj->creatures.resize(availableCreatures.size());
  146. for (auto & entry : availableCreatures)
  147. {
  148. for (const CCreature * cre : entry)
  149. obj->creatures.back().second.push_back(cre->idNumber);
  150. }
  151. return obj;
  152. }
  153. void CDwellingInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator &rng) const
  154. {
  155. CGDwelling * dwelling = dynamic_cast<CGDwelling*>(object);
  156. dwelling->creatures.clear();
  157. dwelling->creatures.reserve(availableCreatures.size());
  158. for (auto & entry : availableCreatures)
  159. {
  160. dwelling->creatures.resize(dwelling->creatures.size() + 1);
  161. for (const CCreature * cre : entry)
  162. dwelling->creatures.back().second.push_back(cre->idNumber);
  163. }
  164. bool guarded = false; //TODO: serialize for sanity
  165. if (guards.getType() == JsonNode::DATA_BOOL) //simple switch
  166. {
  167. if (guards.Bool())
  168. {
  169. guarded = true;
  170. }
  171. }
  172. else if (guards.getType() == JsonNode::DATA_VECTOR) //custom guards (eg. Elemental Conflux)
  173. {
  174. for (auto & stack : JsonRandom::loadCreatures(guards, rng))
  175. {
  176. dwelling->putStack(SlotID(dwelling->stacksCount()), new CStackInstance(stack.type->idNumber, stack.count));
  177. }
  178. }
  179. else //default condition - creatures are of level 5 or higher
  180. {
  181. for (auto creatureEntry : availableCreatures)
  182. {
  183. if (creatureEntry.at(0)->level >= 5)
  184. {
  185. guarded = true;
  186. break;
  187. }
  188. }
  189. }
  190. if (guarded)
  191. {
  192. for (auto creatureEntry : availableCreatures)
  193. {
  194. const CCreature * crea = creatureEntry.at(0);
  195. dwelling->putStack (SlotID(dwelling->stacksCount()), new CStackInstance(crea->idNumber, crea->growth * 3));
  196. }
  197. }
  198. }
  199. bool CDwellingInstanceConstructor::producesCreature(const CCreature * crea) const
  200. {
  201. for (auto & entry : availableCreatures)
  202. {
  203. for (const CCreature * cre : entry)
  204. if (crea == cre)
  205. return true;
  206. }
  207. return false;
  208. }
  209. std::vector<const CCreature *> CDwellingInstanceConstructor::getProducedCreatures() const
  210. {
  211. std::vector<const CCreature *> creatures; //no idea why it's 2D, to be honest
  212. for (auto & entry : availableCreatures)
  213. {
  214. for (const CCreature * cre : entry)
  215. creatures.push_back(cre);
  216. }
  217. return creatures;
  218. }
  219. CBankInstanceConstructor::CBankInstanceConstructor()
  220. {
  221. }
  222. void CBankInstanceConstructor::initTypeData(const JsonNode & input)
  223. {
  224. //TODO: name = input["name"].String();
  225. levels = input["levels"].Vector();
  226. bankResetDuration = input["resetDuration"].Float();
  227. }
  228. CGObjectInstance *CBankInstanceConstructor::create(ObjectTemplate tmpl) const
  229. {
  230. return createTyped(tmpl);
  231. }
  232. BankConfig CBankInstanceConstructor::generateConfig(const JsonNode & level, CRandomGenerator & rng) const
  233. {
  234. BankConfig bc;
  235. bc.chance = level["chance"].Float();
  236. bc.guards = JsonRandom::loadCreatures(level["guards"], rng);
  237. bc.upgradeChance = level["upgrade_chance"].Float();
  238. bc.combatValue = level["combat_value"].Float();
  239. std::vector<SpellID> spells;
  240. for (size_t i=0; i<6; i++)
  241. IObjectInterface::cb->getAllowedSpells(spells, i);
  242. bc.resources = Res::ResourceSet(level["reward"]["resources"]);
  243. bc.creatures = JsonRandom::loadCreatures(level["reward"]["creatures"], rng);
  244. bc.artifacts = JsonRandom::loadArtifacts(level["reward"]["artifacts"], rng);
  245. bc.spells = JsonRandom::loadSpells(level["reward"]["spells"], rng, spells);
  246. bc.value = level["value"].Float();
  247. return bc;
  248. }
  249. void CBankInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
  250. {
  251. //logGlobal->debugStream() << "Seed used to configure bank is " << rng.nextInt();
  252. auto bank = dynamic_cast<CBank*>(object);
  253. bank->resetDuration = bankResetDuration;
  254. si32 totalChance = 0;
  255. for (auto & node : levels)
  256. totalChance += node["chance"].Float();
  257. assert(totalChance != 0);
  258. si32 selectedChance = rng.nextInt(totalChance - 1);
  259. //logGlobal->debugStream() << "Selected chance for bank config is " << selectedChance;
  260. int cumulativeChance = 0;
  261. for (auto & node : levels)
  262. {
  263. cumulativeChance += node["chance"].Float();
  264. if (selectedChance < cumulativeChance)
  265. {
  266. bank->setConfig(generateConfig(node, rng));
  267. break;
  268. }
  269. }
  270. }
  271. CBankInfo::CBankInfo(JsonVector config):
  272. config(config)
  273. {
  274. assert(!config.empty());
  275. }
  276. static void addStackToArmy(IObjectInfo::CArmyStructure & army, const CCreature * crea, si32 amount)
  277. {
  278. army.totalStrength += crea->fightValue * amount;
  279. bool walker = true;
  280. if (crea->hasBonusOfType(Bonus::SHOOTER))
  281. {
  282. army.shootersStrength += crea->fightValue * amount;
  283. walker = false;
  284. }
  285. if (crea->hasBonusOfType(Bonus::FLYING))
  286. {
  287. army.flyersStrength += crea->fightValue * amount;
  288. walker = false;
  289. }
  290. if (walker)
  291. army.walkersStrength += crea->fightValue * amount;
  292. }
  293. IObjectInfo::CArmyStructure CBankInfo::minGuards() const
  294. {
  295. std::vector<IObjectInfo::CArmyStructure> armies;
  296. for (auto configEntry : config)
  297. {
  298. auto stacks = JsonRandom::evaluateCreatures(configEntry["guards"]);
  299. IObjectInfo::CArmyStructure army;
  300. for (auto & stack : stacks)
  301. {
  302. assert(!stack.allowedCreatures.empty());
  303. auto weakest = boost::range::min_element(stack.allowedCreatures, [](const CCreature * a, const CCreature * b)
  304. {
  305. return a->fightValue < b->fightValue;
  306. });
  307. addStackToArmy(army, *weakest, stack.minAmount);
  308. }
  309. armies.push_back(army);
  310. }
  311. return *boost::range::min_element(armies);
  312. }
  313. IObjectInfo::CArmyStructure CBankInfo::maxGuards() const
  314. {
  315. std::vector<IObjectInfo::CArmyStructure> armies;
  316. for (auto configEntry : config)
  317. {
  318. auto stacks = JsonRandom::evaluateCreatures(configEntry["guards"]);
  319. IObjectInfo::CArmyStructure army;
  320. for (auto & stack : stacks)
  321. {
  322. assert(!stack.allowedCreatures.empty());
  323. auto strongest = boost::range::max_element(stack.allowedCreatures, [](const CCreature * a, const CCreature * b)
  324. {
  325. return a->fightValue < b->fightValue;
  326. });
  327. addStackToArmy(army, *strongest, stack.maxAmount);
  328. }
  329. armies.push_back(army);
  330. }
  331. return *boost::range::max_element(armies);
  332. }
  333. TPossibleGuards CBankInfo::getPossibleGuards() const
  334. {
  335. TPossibleGuards out;
  336. for (const JsonNode & configEntry : config)
  337. {
  338. const JsonNode & guardsInfo = configEntry["guards"];
  339. auto stacks = JsonRandom::evaluateCreatures(guardsInfo);
  340. IObjectInfo::CArmyStructure army;
  341. for (auto stack : stacks)
  342. {
  343. army.totalStrength += stack.allowedCreatures.front()->AIValue * (stack.minAmount + stack.maxAmount) / 2;
  344. //TODO: add fields for flyers, walkers etc...
  345. }
  346. ui8 chance = configEntry["chance"].Float();
  347. out.push_back(std::make_pair(chance, army));
  348. }
  349. return out;
  350. }
  351. bool CBankInfo::givesResources() const
  352. {
  353. for (const JsonNode & node : config)
  354. if (!node["reward"]["resources"].isNull())
  355. return true;
  356. return false;
  357. }
  358. bool CBankInfo::givesArtifacts() const
  359. {
  360. for (const JsonNode & node : config)
  361. if (!node["reward"]["artifacts"].isNull())
  362. return true;
  363. return false;
  364. }
  365. bool CBankInfo::givesCreatures() const
  366. {
  367. for (const JsonNode & node : config)
  368. if (!node["reward"]["creatures"].isNull())
  369. return true;
  370. return false;
  371. }
  372. bool CBankInfo::givesSpells() const
  373. {
  374. for (const JsonNode & node : config)
  375. if (!node["reward"]["spells"].isNull())
  376. return true;
  377. return false;
  378. }
  379. std::unique_ptr<IObjectInfo> CBankInstanceConstructor::getObjectInfo(ObjectTemplate tmpl) const
  380. {
  381. return std::unique_ptr<IObjectInfo>(new CBankInfo(levels));
  382. }