StackWithBonuses.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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. BattleID HypotheticBattle::getBattleID() const
  267. {
  268. return subject->getBattle()->getBattleID();
  269. }
  270. int32_t HypotheticBattle::getActiveStackID() const
  271. {
  272. return activeUnitId;
  273. }
  274. void HypotheticBattle::nextRound()
  275. {
  276. //TODO:HypotheticBattle::nextRound
  277. for(auto unit : battleAliveUnits())
  278. {
  279. auto forUpdate = getForUpdate(unit->unitId());
  280. //TODO: update Bonus::NTurns effects
  281. forUpdate->afterNewRound();
  282. }
  283. }
  284. void HypotheticBattle::nextTurn(uint32_t unitId)
  285. {
  286. activeUnitId = unitId;
  287. auto unit = getForUpdate(unitId);
  288. unit->removeUnitBonus(Bonus::UntilGetsTurn);
  289. unit->afterGetsTurn();
  290. }
  291. void HypotheticBattle::addUnit(uint32_t id, const JsonNode & data)
  292. {
  293. battle::UnitInfo info;
  294. info.load(id, data);
  295. std::shared_ptr<StackWithBonuses> newUnit = std::make_shared<StackWithBonuses>(this, info);
  296. stackStates[newUnit->unitId()] = newUnit;
  297. }
  298. void HypotheticBattle::moveUnit(uint32_t id, BattleHex destination)
  299. {
  300. std::shared_ptr<StackWithBonuses> changed = getForUpdate(id);
  301. changed->position = destination;
  302. }
  303. void HypotheticBattle::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  304. {
  305. std::shared_ptr<StackWithBonuses> changed = getForUpdate(id);
  306. changed->load(data);
  307. if(healthDelta < 0)
  308. {
  309. changed->removeUnitBonus(Bonus::UntilBeingAttacked);
  310. }
  311. }
  312. void HypotheticBattle::removeUnit(uint32_t id)
  313. {
  314. std::set<uint32_t> ids;
  315. ids.insert(id);
  316. while(!ids.empty())
  317. {
  318. auto toRemoveId = *ids.begin();
  319. auto toRemove = getForUpdate(toRemoveId);
  320. if(!toRemove->ghost)
  321. {
  322. toRemove->onRemoved();
  323. //TODO: emulate detachFromAll() somehow
  324. //stack may be removed instantly (not being killed first)
  325. //handle clone remove also here
  326. if(toRemove->cloneID >= 0)
  327. {
  328. ids.insert(toRemove->cloneID);
  329. toRemove->cloneID = -1;
  330. }
  331. //TODO: cleanup remaining clone links if any
  332. // for(auto s : stacks)
  333. // {
  334. // if(s->cloneID == toRemoveId)
  335. // s->cloneID = -1;
  336. // }
  337. }
  338. ids.erase(toRemoveId);
  339. }
  340. }
  341. void HypotheticBattle::updateUnit(uint32_t id, const JsonNode & data)
  342. {
  343. //TODO:
  344. }
  345. void HypotheticBattle::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  346. {
  347. getForUpdate(id)->addUnitBonus(bonus);
  348. bonusTreeVersion++;
  349. }
  350. void HypotheticBattle::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  351. {
  352. getForUpdate(id)->updateUnitBonus(bonus);
  353. bonusTreeVersion++;
  354. }
  355. void HypotheticBattle::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  356. {
  357. getForUpdate(id)->removeUnitBonus(bonus);
  358. bonusTreeVersion++;
  359. }
  360. void HypotheticBattle::setWallState(EWallPart partOfWall, EWallState state)
  361. {
  362. //TODO:HypotheticBattle::setWallState
  363. }
  364. void HypotheticBattle::addObstacle(const ObstacleChanges & changes)
  365. {
  366. //TODO:HypotheticBattle::addObstacle
  367. }
  368. void HypotheticBattle::updateObstacle(const ObstacleChanges& changes)
  369. {
  370. //TODO:HypotheticBattle::updateObstacle
  371. }
  372. void HypotheticBattle::removeObstacle(uint32_t id)
  373. {
  374. //TODO:HypotheticBattle::removeObstacle
  375. }
  376. uint32_t HypotheticBattle::nextUnitId() const
  377. {
  378. return nextId++;
  379. }
  380. int64_t HypotheticBattle::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  381. {
  382. return (damage.min + damage.max) / 2;
  383. }
  384. std::vector<SpellID> HypotheticBattle::getUsedSpells(ui8 side) const
  385. {
  386. // TODO
  387. return {};
  388. }
  389. int3 HypotheticBattle::getLocation() const
  390. {
  391. // TODO
  392. return int3(-1, -1, -1);
  393. }
  394. bool HypotheticBattle::isCreatureBank() const
  395. {
  396. // TODO
  397. return false;
  398. }
  399. int64_t HypotheticBattle::getTreeVersion() const
  400. {
  401. return getBonusBearer()->getTreeVersion() + bonusTreeVersion;
  402. }
  403. #if SCRIPTING_ENABLED
  404. Pool * HypotheticBattle::getContextPool() const
  405. {
  406. return pool.get();
  407. }
  408. #endif
  409. ServerCallback * HypotheticBattle::getServerCallback()
  410. {
  411. return serverCallback.get();
  412. }
  413. HypotheticBattle::HypotheticServerCallback::HypotheticServerCallback(HypotheticBattle * owner_)
  414. :owner(owner_)
  415. {
  416. }
  417. void HypotheticBattle::HypotheticServerCallback::complain(const std::string & problem)
  418. {
  419. logAi->error(problem);
  420. }
  421. bool HypotheticBattle::HypotheticServerCallback::describeChanges() const
  422. {
  423. return false;
  424. }
  425. vstd::RNG * HypotheticBattle::HypotheticServerCallback::getRNG()
  426. {
  427. return &rngStub;
  428. }
  429. void HypotheticBattle::HypotheticServerCallback::apply(CPackForClient * pack)
  430. {
  431. logAi->error("Package of type %s is not allowed in battle evaluation", typeid(pack).name());
  432. }
  433. void HypotheticBattle::HypotheticServerCallback::apply(BattleLogMessage * pack)
  434. {
  435. pack->applyBattle(owner);
  436. }
  437. void HypotheticBattle::HypotheticServerCallback::apply(BattleStackMoved * pack)
  438. {
  439. pack->applyBattle(owner);
  440. }
  441. void HypotheticBattle::HypotheticServerCallback::apply(BattleUnitsChanged * pack)
  442. {
  443. pack->applyBattle(owner);
  444. }
  445. void HypotheticBattle::HypotheticServerCallback::apply(SetStackEffect * pack)
  446. {
  447. pack->applyBattle(owner);
  448. }
  449. void HypotheticBattle::HypotheticServerCallback::apply(StacksInjured * pack)
  450. {
  451. pack->applyBattle(owner);
  452. }
  453. void HypotheticBattle::HypotheticServerCallback::apply(BattleObstaclesChanged * pack)
  454. {
  455. pack->applyBattle(owner);
  456. }
  457. void HypotheticBattle::HypotheticServerCallback::apply(CatapultAttack * pack)
  458. {
  459. pack->applyBattle(owner);
  460. }
  461. HypotheticBattle::HypotheticEnvironment::HypotheticEnvironment(HypotheticBattle * owner_, const Environment * upperEnvironment)
  462. : owner(owner_),
  463. env(upperEnvironment)
  464. {
  465. }
  466. const Services * HypotheticBattle::HypotheticEnvironment::services() const
  467. {
  468. return env->services();
  469. }
  470. const Environment::BattleCb * HypotheticBattle::HypotheticEnvironment::battle(const BattleID & battleID) const
  471. {
  472. assert(battleID == owner->getBattleID());
  473. return owner;
  474. }
  475. const Environment::GameCb * HypotheticBattle::HypotheticEnvironment::game() const
  476. {
  477. return env->game();
  478. }
  479. vstd::CLoggerBase * HypotheticBattle::HypotheticEnvironment::logger() const
  480. {
  481. return env->logger();
  482. }
  483. events::EventBus * HypotheticBattle::HypotheticEnvironment::eventBus() const
  484. {
  485. return owner->eventBus.get();
  486. }