StackWithBonuses.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /*
  2. * StackWithBonuses.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "StackWithBonuses.h"
  12. #include <vcmi/events/EventBus.h>
  13. #include "../../lib/NetPacks.h"
  14. #include "../../lib/CStack.h"
  15. #include "../../lib/ScriptHandler.h"
  16. #if SCRIPTING_ENABLED
  17. using scripting::Pool;
  18. #endif
  19. void actualizeEffect(TBonusListPtr target, const Bonus & ef)
  20. {
  21. for(auto & bonus : *target) //TODO: optimize
  22. {
  23. if(bonus->source == BonusSource::SPELL_EFFECT && bonus->type == ef.type && bonus->subtype == ef.subtype)
  24. {
  25. if(bonus->turnsRemain < ef.turnsRemain)
  26. {
  27. bonus.reset(new Bonus(*bonus));
  28. bonus->turnsRemain = ef.turnsRemain;
  29. }
  30. }
  31. }
  32. }
  33. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::CUnitState * Stack)
  34. : battle::CUnitState(),
  35. origBearer(Stack->getBonusBearer()),
  36. owner(Owner),
  37. type(Stack->unitType()),
  38. baseAmount(Stack->unitBaseAmount()),
  39. id(Stack->unitId()),
  40. side(Stack->unitSide()),
  41. player(Stack->unitOwner()),
  42. slot(Stack->unitSlot()),
  43. treeVersionLocal(0)
  44. {
  45. localInit(Owner);
  46. battle::CUnitState::operator=(*Stack);
  47. }
  48. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::Unit * Stack)
  49. : battle::CUnitState(),
  50. origBearer(Stack->getBonusBearer()),
  51. owner(Owner),
  52. type(Stack->unitType()),
  53. baseAmount(Stack->unitBaseAmount()),
  54. id(Stack->unitId()),
  55. side(Stack->unitSide()),
  56. player(Stack->unitOwner()),
  57. slot(Stack->unitSlot()),
  58. treeVersionLocal(0)
  59. {
  60. localInit(Owner);
  61. auto state = Stack->acquireState();
  62. battle::CUnitState::operator=(*state);
  63. }
  64. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::UnitInfo & info)
  65. : battle::CUnitState(),
  66. origBearer(nullptr),
  67. owner(Owner),
  68. baseAmount(info.count),
  69. id(info.id),
  70. side(info.side),
  71. slot(SlotID::SUMMONED_SLOT_PLACEHOLDER),
  72. treeVersionLocal(0)
  73. {
  74. type = info.type.toCreature();
  75. origBearer = type;
  76. player = Owner->getSidePlayer(side);
  77. localInit(Owner);
  78. position = info.position;
  79. summoned = info.summoned;
  80. }
  81. StackWithBonuses::~StackWithBonuses() = default;
  82. StackWithBonuses & StackWithBonuses::operator=(const battle::CUnitState & other)
  83. {
  84. battle::CUnitState::operator=(other);
  85. return *this;
  86. }
  87. const CCreature * StackWithBonuses::unitType() const
  88. {
  89. return type;
  90. }
  91. int32_t StackWithBonuses::unitBaseAmount() const
  92. {
  93. return baseAmount;
  94. }
  95. uint32_t StackWithBonuses::unitId() const
  96. {
  97. return id;
  98. }
  99. ui8 StackWithBonuses::unitSide() const
  100. {
  101. return side;
  102. }
  103. PlayerColor StackWithBonuses::unitOwner() const
  104. {
  105. return player;
  106. }
  107. SlotID StackWithBonuses::unitSlot() const
  108. {
  109. return slot;
  110. }
  111. TConstBonusListPtr StackWithBonuses::getAllBonuses(const CSelector & selector, const CSelector & limit,
  112. const CBonusSystemNode * root, const std::string & cachingStr) const
  113. {
  114. TBonusListPtr ret = std::make_shared<BonusList>();
  115. TConstBonusListPtr originalList = origBearer->getAllBonuses(selector, limit, root, cachingStr);
  116. vstd::copy_if(*originalList, std::back_inserter(*ret), [this](const std::shared_ptr<Bonus> & b)
  117. {
  118. return !vstd::contains(bonusesToRemove, b);
  119. });
  120. for(const Bonus & bonus : bonusesToUpdate)
  121. {
  122. if(selector(&bonus) && (!limit || limit(&bonus)))
  123. {
  124. if(ret->getFirst(Selector::source(BonusSource::SPELL_EFFECT, bonus.sid).And(Selector::typeSubtype(bonus.type, bonus.subtype))))
  125. {
  126. actualizeEffect(ret, bonus);
  127. }
  128. else
  129. {
  130. auto b = std::make_shared<Bonus>(bonus);
  131. ret->push_back(b);
  132. }
  133. }
  134. }
  135. for(auto & bonus : bonusesToAdd)
  136. {
  137. auto b = std::make_shared<Bonus>(bonus);
  138. if(selector(b.get()) && (!limit || !limit(b.get())))
  139. ret->push_back(b);
  140. }
  141. //TODO limiters?
  142. return ret;
  143. }
  144. int64_t StackWithBonuses::getTreeVersion() const
  145. {
  146. auto result = owner->getTreeVersion();
  147. if(bonusesToAdd.empty() && bonusesToUpdate.empty() && bonusesToRemove.empty())
  148. return result;
  149. else
  150. return result + treeVersionLocal;
  151. }
  152. void StackWithBonuses::addUnitBonus(const std::vector<Bonus> & bonus)
  153. {
  154. vstd::concatenate(bonusesToAdd, bonus);
  155. treeVersionLocal++;
  156. }
  157. void StackWithBonuses::updateUnitBonus(const std::vector<Bonus> & bonus)
  158. {
  159. //TODO: optimize, actualize to last value
  160. vstd::concatenate(bonusesToUpdate, bonus);
  161. treeVersionLocal++;
  162. }
  163. void StackWithBonuses::removeUnitBonus(const std::vector<Bonus> & bonus)
  164. {
  165. for(auto & one : bonus)
  166. {
  167. CSelector selector([&one](const Bonus * b) -> bool
  168. {
  169. //compare everything but turnsRemain, limiter and propagator
  170. return one.duration == b->duration
  171. && one.type == b->type
  172. && one.subtype == b->subtype
  173. && one.source == b->source
  174. && one.val == b->val
  175. && one.sid == b->sid
  176. && one.valType == b->valType
  177. && one.additionalInfo == b->additionalInfo
  178. && one.effectRange == b->effectRange
  179. && one.description == b->description;
  180. });
  181. removeUnitBonus(selector);
  182. }
  183. }
  184. void StackWithBonuses::removeUnitBonus(const CSelector & selector)
  185. {
  186. TConstBonusListPtr toRemove = origBearer->getBonuses(selector);
  187. for(auto b : *toRemove)
  188. bonusesToRemove.insert(b);
  189. vstd::erase_if(bonusesToAdd, [&](const Bonus & b){return selector(&b);});
  190. vstd::erase_if(bonusesToUpdate, [&](const Bonus & b){return selector(&b);});
  191. treeVersionLocal++;
  192. }
  193. std::string StackWithBonuses::getDescription() const
  194. {
  195. std::ostringstream oss;
  196. oss << unitOwner().toString();
  197. oss << " battle stack [" << unitId() << "]: " << getCount() << " of ";
  198. if(type)
  199. oss << type->getJsonKey();
  200. else
  201. oss << "[UNDEFINED TYPE]";
  202. oss << " from slot " << slot;
  203. return oss.str();
  204. }
  205. void StackWithBonuses::spendMana(ServerCallback * server, const int spellCost) const
  206. {
  207. //TODO: evaluate cast use
  208. }
  209. HypotheticBattle::HypotheticBattle(const Environment * ENV, Subject realBattle)
  210. : BattleProxy(realBattle),
  211. env(ENV),
  212. bonusTreeVersion(1)
  213. {
  214. auto activeUnit = realBattle->battleActiveUnit();
  215. activeUnitId = activeUnit ? activeUnit->unitId() : -1;
  216. nextId = 0x00F00000;
  217. eventBus.reset(new events::EventBus());
  218. localEnvironment.reset(new HypotheticEnvironment(this, env));
  219. serverCallback.reset(new HypotheticServerCallback(this));
  220. #if SCRIPTING_ENABLED
  221. pool.reset(new scripting::PoolImpl(localEnvironment.get(), serverCallback.get()));
  222. #endif
  223. }
  224. bool HypotheticBattle::unitHasAmmoCart(const battle::Unit * unit) const
  225. {
  226. //FIXME: check ammocart alive state here
  227. return false;
  228. }
  229. PlayerColor HypotheticBattle::unitEffectiveOwner(const battle::Unit * unit) const
  230. {
  231. return battleGetOwner(unit);
  232. }
  233. std::shared_ptr<StackWithBonuses> HypotheticBattle::getForUpdate(uint32_t id)
  234. {
  235. auto iter = stackStates.find(id);
  236. if(iter == stackStates.end())
  237. {
  238. const battle::Unit * s = subject->battleGetUnitByID(id);
  239. auto ret = std::make_shared<StackWithBonuses>(this, s);
  240. stackStates[id] = ret;
  241. return ret;
  242. }
  243. else
  244. {
  245. return iter->second;
  246. }
  247. }
  248. battle::Units HypotheticBattle::getUnitsIf(battle::UnitFilter predicate) const
  249. {
  250. battle::Units proxyed = BattleProxy::getUnitsIf(predicate);
  251. battle::Units ret;
  252. ret.reserve(proxyed.size());
  253. for(auto unit : proxyed)
  254. {
  255. //unit was not changed, trust proxyed data
  256. if(stackStates.find(unit->unitId()) == stackStates.end())
  257. ret.push_back(unit);
  258. }
  259. for(auto id_unit : stackStates)
  260. {
  261. if(predicate(id_unit.second.get()))
  262. ret.push_back(id_unit.second.get());
  263. }
  264. return ret;
  265. }
  266. int32_t HypotheticBattle::getActiveStackID() const
  267. {
  268. return activeUnitId;
  269. }
  270. void HypotheticBattle::nextRound(int32_t roundNr)
  271. {
  272. //TODO:HypotheticBattle::nextRound
  273. for(auto unit : battleAliveUnits())
  274. {
  275. auto forUpdate = getForUpdate(unit->unitId());
  276. //TODO: update Bonus::NTurns effects
  277. forUpdate->afterNewRound();
  278. }
  279. }
  280. void HypotheticBattle::nextTurn(uint32_t unitId)
  281. {
  282. activeUnitId = unitId;
  283. auto unit = getForUpdate(unitId);
  284. unit->removeUnitBonus(Bonus::UntilGetsTurn);
  285. unit->afterGetsTurn();
  286. }
  287. void HypotheticBattle::addUnit(uint32_t id, const JsonNode & data)
  288. {
  289. battle::UnitInfo info;
  290. info.load(id, data);
  291. std::shared_ptr<StackWithBonuses> newUnit = std::make_shared<StackWithBonuses>(this, info);
  292. stackStates[newUnit->unitId()] = newUnit;
  293. }
  294. void HypotheticBattle::moveUnit(uint32_t id, BattleHex destination)
  295. {
  296. std::shared_ptr<StackWithBonuses> changed = getForUpdate(id);
  297. changed->position = destination;
  298. }
  299. void HypotheticBattle::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  300. {
  301. std::shared_ptr<StackWithBonuses> changed = getForUpdate(id);
  302. changed->load(data);
  303. if(healthDelta < 0)
  304. {
  305. changed->removeUnitBonus(Bonus::UntilBeingAttacked);
  306. }
  307. }
  308. void HypotheticBattle::removeUnit(uint32_t id)
  309. {
  310. std::set<uint32_t> ids;
  311. ids.insert(id);
  312. while(!ids.empty())
  313. {
  314. auto toRemoveId = *ids.begin();
  315. auto toRemove = getForUpdate(toRemoveId);
  316. if(!toRemove->ghost)
  317. {
  318. toRemove->onRemoved();
  319. //TODO: emulate detachFromAll() somehow
  320. //stack may be removed instantly (not being killed first)
  321. //handle clone remove also here
  322. if(toRemove->cloneID >= 0)
  323. {
  324. ids.insert(toRemove->cloneID);
  325. toRemove->cloneID = -1;
  326. }
  327. //TODO: cleanup remaining clone links if any
  328. // for(auto s : stacks)
  329. // {
  330. // if(s->cloneID == toRemoveId)
  331. // s->cloneID = -1;
  332. // }
  333. }
  334. ids.erase(toRemoveId);
  335. }
  336. }
  337. void HypotheticBattle::updateUnit(uint32_t id, const JsonNode & data)
  338. {
  339. //TODO:
  340. }
  341. void HypotheticBattle::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  342. {
  343. getForUpdate(id)->addUnitBonus(bonus);
  344. bonusTreeVersion++;
  345. }
  346. void HypotheticBattle::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  347. {
  348. getForUpdate(id)->updateUnitBonus(bonus);
  349. bonusTreeVersion++;
  350. }
  351. void HypotheticBattle::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  352. {
  353. getForUpdate(id)->removeUnitBonus(bonus);
  354. bonusTreeVersion++;
  355. }
  356. void HypotheticBattle::setWallState(EWallPart partOfWall, EWallState state)
  357. {
  358. //TODO:HypotheticBattle::setWallState
  359. }
  360. void HypotheticBattle::addObstacle(const ObstacleChanges & changes)
  361. {
  362. //TODO:HypotheticBattle::addObstacle
  363. }
  364. void HypotheticBattle::updateObstacle(const ObstacleChanges& changes)
  365. {
  366. //TODO:HypotheticBattle::updateObstacle
  367. }
  368. void HypotheticBattle::removeObstacle(uint32_t id)
  369. {
  370. //TODO:HypotheticBattle::removeObstacle
  371. }
  372. uint32_t HypotheticBattle::nextUnitId() const
  373. {
  374. return nextId++;
  375. }
  376. int64_t HypotheticBattle::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  377. {
  378. return (damage.min + damage.max) / 2;
  379. }
  380. int64_t HypotheticBattle::getTreeVersion() const
  381. {
  382. return getBonusBearer()->getTreeVersion() + bonusTreeVersion;
  383. }
  384. #if SCRIPTING_ENABLED
  385. Pool * HypotheticBattle::getContextPool() const
  386. {
  387. return pool.get();
  388. }
  389. #endif
  390. ServerCallback * HypotheticBattle::getServerCallback()
  391. {
  392. return serverCallback.get();
  393. }
  394. HypotheticBattle::HypotheticServerCallback::HypotheticServerCallback(HypotheticBattle * owner_)
  395. :owner(owner_)
  396. {
  397. }
  398. void HypotheticBattle::HypotheticServerCallback::complain(const std::string & problem)
  399. {
  400. logAi->error(problem);
  401. }
  402. bool HypotheticBattle::HypotheticServerCallback::describeChanges() const
  403. {
  404. return false;
  405. }
  406. vstd::RNG * HypotheticBattle::HypotheticServerCallback::getRNG()
  407. {
  408. return &rngStub;
  409. }
  410. void HypotheticBattle::HypotheticServerCallback::apply(CPackForClient * pack)
  411. {
  412. logAi->error("Package of type %s is not allowed in battle evaluation", typeid(pack).name());
  413. }
  414. void HypotheticBattle::HypotheticServerCallback::apply(BattleLogMessage * pack)
  415. {
  416. pack->applyBattle(owner);
  417. }
  418. void HypotheticBattle::HypotheticServerCallback::apply(BattleStackMoved * pack)
  419. {
  420. pack->applyBattle(owner);
  421. }
  422. void HypotheticBattle::HypotheticServerCallback::apply(BattleUnitsChanged * pack)
  423. {
  424. pack->applyBattle(owner);
  425. }
  426. void HypotheticBattle::HypotheticServerCallback::apply(SetStackEffect * pack)
  427. {
  428. pack->applyBattle(owner);
  429. }
  430. void HypotheticBattle::HypotheticServerCallback::apply(StacksInjured * pack)
  431. {
  432. pack->applyBattle(owner);
  433. }
  434. void HypotheticBattle::HypotheticServerCallback::apply(BattleObstaclesChanged * pack)
  435. {
  436. pack->applyBattle(owner);
  437. }
  438. void HypotheticBattle::HypotheticServerCallback::apply(CatapultAttack * pack)
  439. {
  440. pack->applyBattle(owner);
  441. }
  442. HypotheticBattle::HypotheticEnvironment::HypotheticEnvironment(HypotheticBattle * owner_, const Environment * upperEnvironment)
  443. : owner(owner_),
  444. env(upperEnvironment)
  445. {
  446. }
  447. const Services * HypotheticBattle::HypotheticEnvironment::services() const
  448. {
  449. return env->services();
  450. }
  451. const Environment::BattleCb * HypotheticBattle::HypotheticEnvironment::battle() const
  452. {
  453. return owner;
  454. }
  455. const Environment::GameCb * HypotheticBattle::HypotheticEnvironment::game() const
  456. {
  457. return env->game();
  458. }
  459. vstd::CLoggerBase * HypotheticBattle::HypotheticEnvironment::logger() const
  460. {
  461. return env->logger();
  462. }
  463. events::EventBus * HypotheticBattle::HypotheticEnvironment::eventBus() const
  464. {
  465. return owner->eventBus.get();
  466. }