CommonConstructors.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. for (auto & node : levels)
  261. {
  262. if (selectedChance < node["chance"].Float())
  263. {
  264. bank->setConfig(generateConfig(node, rng));
  265. }
  266. else
  267. {
  268. selectedChance -= node["chance"].Float();
  269. }
  270. }
  271. }
  272. CBankInfo::CBankInfo(JsonVector config):
  273. config(config)
  274. {
  275. assert(!config.empty());
  276. }
  277. static void addStackToArmy(IObjectInfo::CArmyStructure & army, const CCreature * crea, si32 amount)
  278. {
  279. army.totalStrength += crea->fightValue * amount;
  280. bool walker = true;
  281. if (crea->hasBonusOfType(Bonus::SHOOTER))
  282. {
  283. army.shootersStrength += crea->fightValue * amount;
  284. walker = false;
  285. }
  286. if (crea->hasBonusOfType(Bonus::FLYING))
  287. {
  288. army.flyersStrength += crea->fightValue * amount;
  289. walker = false;
  290. }
  291. if (walker)
  292. army.walkersStrength += crea->fightValue * amount;
  293. }
  294. IObjectInfo::CArmyStructure CBankInfo::minGuards() const
  295. {
  296. std::vector<IObjectInfo::CArmyStructure> armies;
  297. for (auto configEntry : config)
  298. {
  299. auto stacks = JsonRandom::evaluateCreatures(configEntry["guards"]);
  300. IObjectInfo::CArmyStructure army;
  301. for (auto & stack : stacks)
  302. {
  303. assert(!stack.allowedCreatures.empty());
  304. auto weakest = boost::range::min_element(stack.allowedCreatures, [](const CCreature * a, const CCreature * b)
  305. {
  306. return a->fightValue < b->fightValue;
  307. });
  308. addStackToArmy(army, *weakest, stack.minAmount);
  309. }
  310. armies.push_back(army);
  311. }
  312. return *boost::range::min_element(armies);
  313. }
  314. IObjectInfo::CArmyStructure CBankInfo::maxGuards() const
  315. {
  316. std::vector<IObjectInfo::CArmyStructure> armies;
  317. for (auto configEntry : config)
  318. {
  319. auto stacks = JsonRandom::evaluateCreatures(configEntry["guards"]);
  320. IObjectInfo::CArmyStructure army;
  321. for (auto & stack : stacks)
  322. {
  323. assert(!stack.allowedCreatures.empty());
  324. auto strongest = boost::range::max_element(stack.allowedCreatures, [](const CCreature * a, const CCreature * b)
  325. {
  326. return a->fightValue < b->fightValue;
  327. });
  328. addStackToArmy(army, *strongest, stack.maxAmount);
  329. }
  330. armies.push_back(army);
  331. }
  332. return *boost::range::max_element(armies);
  333. }
  334. TPossibleGuards CBankInfo::getPossibleGuards() const
  335. {
  336. TPossibleGuards out;
  337. for (const JsonNode & configEntry : config)
  338. {
  339. const JsonNode & guardsInfo = configEntry["guards"];
  340. auto stacks = JsonRandom::evaluateCreatures(guardsInfo);
  341. IObjectInfo::CArmyStructure army;
  342. for (auto stack : stacks)
  343. {
  344. army.totalStrength += stack.allowedCreatures.front()->AIValue * (stack.minAmount + stack.maxAmount) / 2;
  345. //TODO: add fields for flyers, walkers etc...
  346. }
  347. ui8 chance = configEntry["chance"].Float();
  348. out.push_back(std::make_pair(chance, army));
  349. }
  350. return out;
  351. }
  352. bool CBankInfo::givesResources() const
  353. {
  354. for (const JsonNode & node : config)
  355. if (!node["reward"]["resources"].isNull())
  356. return true;
  357. return false;
  358. }
  359. bool CBankInfo::givesArtifacts() const
  360. {
  361. for (const JsonNode & node : config)
  362. if (!node["reward"]["artifacts"].isNull())
  363. return true;
  364. return false;
  365. }
  366. bool CBankInfo::givesCreatures() const
  367. {
  368. for (const JsonNode & node : config)
  369. if (!node["reward"]["creatures"].isNull())
  370. return true;
  371. return false;
  372. }
  373. bool CBankInfo::givesSpells() const
  374. {
  375. for (const JsonNode & node : config)
  376. if (!node["reward"]["spells"].isNull())
  377. return true;
  378. return false;
  379. }
  380. std::unique_ptr<IObjectInfo> CBankInstanceConstructor::getObjectInfo(ObjectTemplate tmpl) const
  381. {
  382. return std::unique_ptr<IObjectInfo>(new CBankInfo(levels));
  383. }