CBonusSystemNode.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. * CBonusSystemNode.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 "CBonusSystemNode.h"
  12. #include "Limiters.h"
  13. #include "Updaters.h"
  14. #include "Propagators.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. std::atomic<int64_t> CBonusSystemNode::treeChanged(1);
  17. constexpr bool CBonusSystemNode::cachingEnabled = true;
  18. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  19. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  20. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  21. {
  22. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  23. }
  24. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  25. {
  26. auto ret = bonuses.getFirst(selector);
  27. if(ret)
  28. return ret;
  29. FOREACH_PARENT(pname)
  30. {
  31. ret = pname->getBonusLocalFirst(selector);
  32. if (ret)
  33. return ret;
  34. }
  35. return nullptr;
  36. }
  37. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  38. {
  39. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  40. }
  41. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  42. {
  43. for(const auto & elem : parents)
  44. {
  45. const CBonusSystemNode *parent = elem;
  46. out.insert(parent);
  47. }
  48. }
  49. void CBonusSystemNode::getParents(TNodes &out)
  50. {
  51. for (auto & elem : parents)
  52. {
  53. const CBonusSystemNode *parent = elem;
  54. out.insert(const_cast<CBonusSystemNode*>(parent));
  55. }
  56. }
  57. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  58. {
  59. for(auto * parent : parents)
  60. {
  61. out.insert(parent);
  62. parent->getAllParents(out);
  63. }
  64. }
  65. void CBonusSystemNode::getAllBonusesRec(BonusList &out, const CSelector & selector) const
  66. {
  67. //out has been reserved sufficient capacity at getAllBonuses() call
  68. BonusList beforeUpdate;
  69. TCNodes lparents;
  70. getAllParents(lparents);
  71. if(!lparents.empty())
  72. {
  73. //estimate on how many bonuses are missing yet - must be positive
  74. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  75. }
  76. else
  77. {
  78. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  79. }
  80. for(const auto * parent : lparents)
  81. {
  82. parent->getAllBonusesRec(beforeUpdate, selector);
  83. }
  84. bonuses.getAllBonuses(beforeUpdate);
  85. for(const auto & b : beforeUpdate)
  86. {
  87. //We should not run updaters on non-selected bonuses
  88. auto updated = selector(b.get()) && b->updater
  89. ? getUpdatedBonus(b, b->updater)
  90. : b;
  91. //do not add bonus with updater
  92. bool bonusExists = false;
  93. for(const auto & bonus : out)
  94. {
  95. if (bonus == updated)
  96. bonusExists = true;
  97. if (bonus->updater && bonus->updater == updated->updater)
  98. bonusExists = true;
  99. }
  100. if (!bonusExists)
  101. out.push_back(updated);
  102. }
  103. }
  104. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  105. {
  106. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  107. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  108. {
  109. // Exclusive access for one thread
  110. boost::lock_guard<boost::mutex> lock(sync);
  111. // If the bonus system tree changes(state of a single node or the relations to each other) then
  112. // cache all bonus objects. Selector objects doesn't matter.
  113. if (cachedLast != treeChanged)
  114. {
  115. BonusList allBonuses;
  116. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  117. cachedBonuses.clear();
  118. cachedRequests.clear();
  119. getAllBonusesRec(allBonuses, Selector::all);
  120. limitBonuses(allBonuses, cachedBonuses);
  121. cachedBonuses.stackBonuses();
  122. cachedLast = treeChanged;
  123. }
  124. // If a bonus system request comes with a caching string then look up in the map if there are any
  125. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  126. if(!cachingStr.empty())
  127. {
  128. auto it = cachedRequests.find(cachingStr);
  129. if(it != cachedRequests.end())
  130. {
  131. //Cached list contains bonuses for our query with applied limiters
  132. return it->second;
  133. }
  134. }
  135. //We still don't have the bonuses (didn't returned them from cache)
  136. //Perform bonus selection
  137. auto ret = std::make_shared<BonusList>();
  138. cachedBonuses.getBonuses(*ret, selector, limit);
  139. // Save the results in the cache
  140. if(!cachingStr.empty())
  141. cachedRequests[cachingStr] = ret;
  142. return ret;
  143. }
  144. else
  145. {
  146. return getAllBonusesWithoutCaching(selector, limit, root);
  147. }
  148. }
  149. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  150. {
  151. auto ret = std::make_shared<BonusList>();
  152. // Get bonus results without caching enabled.
  153. BonusList beforeLimiting;
  154. BonusList afterLimiting;
  155. getAllBonusesRec(beforeLimiting, selector);
  156. if(!root || root == this)
  157. {
  158. limitBonuses(beforeLimiting, afterLimiting);
  159. }
  160. else if(root)
  161. {
  162. //We want to limit our query against an external node. We get all its bonuses,
  163. // add the ones we're considering and see if they're cut out by limiters
  164. BonusList rootBonuses;
  165. BonusList limitedRootBonuses;
  166. getAllBonusesRec(rootBonuses, selector);
  167. for(const auto & b : beforeLimiting)
  168. rootBonuses.push_back(b);
  169. root->limitBonuses(rootBonuses, limitedRootBonuses);
  170. for(const auto & b : beforeLimiting)
  171. if(vstd::contains(limitedRootBonuses, b))
  172. afterLimiting.push_back(b);
  173. }
  174. afterLimiting.getBonuses(*ret, selector, limit);
  175. ret->stackBonuses();
  176. return ret;
  177. }
  178. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr & updater) const
  179. {
  180. assert(updater);
  181. return updater->createUpdatedBonus(b, * this);
  182. }
  183. CBonusSystemNode::CBonusSystemNode(bool isHypotetic):
  184. bonuses(true),
  185. exportedBonuses(true),
  186. nodeType(UNKNOWN),
  187. cachedLast(0),
  188. isHypotheticNode(isHypotetic)
  189. {
  190. }
  191. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType):
  192. bonuses(true),
  193. exportedBonuses(true),
  194. nodeType(NodeType),
  195. cachedLast(0),
  196. isHypotheticNode(false)
  197. {
  198. }
  199. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other) noexcept:
  200. bonuses(std::move(other.bonuses)),
  201. exportedBonuses(std::move(other.exportedBonuses)),
  202. nodeType(other.nodeType),
  203. description(other.description),
  204. cachedLast(0),
  205. isHypotheticNode(other.isHypotheticNode)
  206. {
  207. std::swap(parents, other.parents);
  208. std::swap(children, other.children);
  209. //fixing bonus tree without recalculation
  210. if(!isHypothetic())
  211. {
  212. for(CBonusSystemNode * n : parents)
  213. {
  214. n->children -= &other;
  215. n->children.push_back(this);
  216. }
  217. }
  218. for(CBonusSystemNode * n : children)
  219. {
  220. n->parents -= &other;
  221. n->parents.push_back(this);
  222. }
  223. //cache ignored
  224. //cachedBonuses
  225. //cachedRequests
  226. }
  227. CBonusSystemNode::~CBonusSystemNode()
  228. {
  229. detachFromAll();
  230. if(!children.empty())
  231. {
  232. while(!children.empty())
  233. children.front()->detachFrom(*this);
  234. }
  235. }
  236. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  237. {
  238. assert(!vstd::contains(parents, &parent));
  239. parents.push_back(&parent);
  240. if(!isHypothetic())
  241. {
  242. if(parent.actsAsBonusSourceOnly())
  243. parent.newRedDescendant(*this);
  244. else
  245. newRedDescendant(parent);
  246. parent.newChildAttached(*this);
  247. }
  248. CBonusSystemNode::treeHasChanged();
  249. }
  250. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  251. {
  252. assert(vstd::contains(parents, &parent));
  253. if(!isHypothetic())
  254. {
  255. if(parent.actsAsBonusSourceOnly())
  256. parent.removedRedDescendant(*this);
  257. else
  258. removedRedDescendant(parent);
  259. }
  260. if (vstd::contains(parents, &parent))
  261. {
  262. parents -= &parent;
  263. }
  264. else
  265. {
  266. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  267. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  268. }
  269. if(!isHypothetic())
  270. {
  271. parent.childDetached(*this);
  272. }
  273. CBonusSystemNode::treeHasChanged();
  274. }
  275. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  276. {
  277. removeBonuses(s);
  278. for(CBonusSystemNode * child : children)
  279. child->removeBonusesRecursive(s);
  280. }
  281. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  282. {
  283. BonusList bl;
  284. exportedBonuses.getBonuses(bl, s, Selector::all);
  285. for(const auto & b : bl)
  286. {
  287. b->turnsRemain--;
  288. if(b->turnsRemain <= 0)
  289. removeBonus(b);
  290. }
  291. for(CBonusSystemNode *child : children)
  292. child->reduceBonusDurations(s);
  293. }
  294. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  295. {
  296. //turnsRemain shouldn't be zero for following durations
  297. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  298. {
  299. assert(b->turnsRemain);
  300. }
  301. assert(!vstd::contains(exportedBonuses, b));
  302. exportedBonuses.push_back(b);
  303. exportBonus(b);
  304. CBonusSystemNode::treeHasChanged();
  305. }
  306. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  307. {
  308. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  309. if(bonus)
  310. bonus->val += b->val;
  311. else
  312. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  313. }
  314. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  315. {
  316. exportedBonuses -= b;
  317. if(b->propagator)
  318. unpropagateBonus(b);
  319. else
  320. bonuses -= b;
  321. CBonusSystemNode::treeHasChanged();
  322. }
  323. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  324. {
  325. BonusList toRemove;
  326. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  327. for(const auto & bonus : toRemove)
  328. removeBonus(bonus);
  329. }
  330. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  331. {
  332. switch(nodeType)
  333. {
  334. case CREATURE:
  335. case ARTIFACT:
  336. case ARTIFACT_INSTANCE:
  337. return true;
  338. default:
  339. return false;
  340. }
  341. }
  342. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  343. {
  344. if(b->propagator->shouldBeAttached(this))
  345. {
  346. auto propagated = b->propagationUpdater
  347. ? source.getUpdatedBonus(b, b->propagationUpdater)
  348. : b;
  349. bonuses.push_back(propagated);
  350. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  351. }
  352. FOREACH_RED_CHILD(child)
  353. child->propagateBonus(b, source);
  354. }
  355. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  356. {
  357. if(b->propagator->shouldBeAttached(this))
  358. {
  359. bonuses -= b;
  360. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  361. }
  362. FOREACH_RED_CHILD(child)
  363. child->unpropagateBonus(b);
  364. }
  365. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  366. {
  367. assert(!vstd::contains(children, &child));
  368. children.push_back(&child);
  369. }
  370. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  371. {
  372. if(vstd::contains(children, &child))
  373. children -= &child;
  374. else
  375. {
  376. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  377. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  378. }
  379. }
  380. void CBonusSystemNode::detachFromAll()
  381. {
  382. while(!parents.empty())
  383. detachFrom(*parents.front());
  384. }
  385. bool CBonusSystemNode::isIndependentNode() const
  386. {
  387. return parents.empty() && children.empty();
  388. }
  389. std::string CBonusSystemNode::nodeName() const
  390. {
  391. return !description.empty()
  392. ? description
  393. : std::string("Bonus system node of type ") + typeid(*this).name();
  394. }
  395. std::string CBonusSystemNode::nodeShortInfo() const
  396. {
  397. std::ostringstream str;
  398. str << "'" << typeid(* this).name() << "'";
  399. description.length() > 0
  400. ? str << " (" << description << ")"
  401. : str << " (no description)";
  402. return str.str();
  403. }
  404. void CBonusSystemNode::deserializationFix()
  405. {
  406. exportBonuses();
  407. }
  408. void CBonusSystemNode::getRedParents(TNodes & out)
  409. {
  410. FOREACH_PARENT(pname)
  411. {
  412. if(pname->actsAsBonusSourceOnly())
  413. {
  414. out.insert(pname);
  415. }
  416. }
  417. if(!actsAsBonusSourceOnly())
  418. {
  419. for(CBonusSystemNode *child : children)
  420. {
  421. out.insert(child);
  422. }
  423. }
  424. }
  425. void CBonusSystemNode::getRedChildren(TNodes &out)
  426. {
  427. FOREACH_PARENT(pname)
  428. {
  429. if(!pname->actsAsBonusSourceOnly())
  430. {
  431. out.insert(pname);
  432. }
  433. }
  434. if(actsAsBonusSourceOnly())
  435. {
  436. for(CBonusSystemNode *child : children)
  437. {
  438. out.insert(child);
  439. }
  440. }
  441. }
  442. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  443. {
  444. for(const auto & b : exportedBonuses)
  445. {
  446. if(b->propagator)
  447. descendant.propagateBonus(b, *this);
  448. }
  449. TNodes redParents;
  450. getRedAncestors(redParents); //get all red parents recursively
  451. for(auto * parent : redParents)
  452. {
  453. for(const auto & b : parent->exportedBonuses)
  454. {
  455. if(b->propagator)
  456. descendant.propagateBonus(b, *this);
  457. }
  458. }
  459. }
  460. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  461. {
  462. for(const auto & b : exportedBonuses)
  463. if(b->propagator)
  464. descendant.unpropagateBonus(b);
  465. TNodes redParents;
  466. getRedAncestors(redParents); //get all red parents recursively
  467. for(auto * parent : redParents)
  468. {
  469. for(const auto & b : parent->exportedBonuses)
  470. if(b->propagator)
  471. descendant.unpropagateBonus(b);
  472. }
  473. }
  474. void CBonusSystemNode::getRedAncestors(TNodes &out)
  475. {
  476. getRedParents(out);
  477. TNodes redParents;
  478. getRedParents(redParents);
  479. for(CBonusSystemNode * parent : redParents)
  480. parent->getRedAncestors(out);
  481. }
  482. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  483. {
  484. if(b->propagator)
  485. propagateBonus(b, *this);
  486. else
  487. bonuses.push_back(b);
  488. CBonusSystemNode::treeHasChanged();
  489. }
  490. void CBonusSystemNode::exportBonuses()
  491. {
  492. for(const auto & b : exportedBonuses)
  493. exportBonus(b);
  494. }
  495. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  496. {
  497. return nodeType;
  498. }
  499. const BonusList& CBonusSystemNode::getBonusList() const
  500. {
  501. return bonuses;
  502. }
  503. const TNodesVector& CBonusSystemNode::getParentNodes() const
  504. {
  505. return parents;
  506. }
  507. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  508. {
  509. return children;
  510. }
  511. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  512. {
  513. nodeType = type;
  514. }
  515. BonusList & CBonusSystemNode::getExportedBonusList()
  516. {
  517. return exportedBonuses;
  518. }
  519. const BonusList & CBonusSystemNode::getExportedBonusList() const
  520. {
  521. return exportedBonuses;
  522. }
  523. const std::string& CBonusSystemNode::getDescription() const
  524. {
  525. return description;
  526. }
  527. void CBonusSystemNode::setDescription(const std::string &description)
  528. {
  529. this->description = description;
  530. }
  531. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  532. {
  533. assert(&allBonuses != &out); //todo should it work in-place?
  534. BonusList undecided = allBonuses;
  535. BonusList & accepted = out;
  536. while(true)
  537. {
  538. int undecidedCount = static_cast<int>(undecided.size());
  539. for(int i = 0; i < undecided.size(); i++)
  540. {
  541. auto b = undecided[i];
  542. BonusLimitationContext context = {*b, *this, out, undecided};
  543. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  544. if(decision == ILimiter::EDecision::DISCARD)
  545. {
  546. undecided.erase(i);
  547. i--; continue;
  548. }
  549. else if(decision == ILimiter::EDecision::ACCEPT)
  550. {
  551. accepted.push_back(b);
  552. undecided.erase(i);
  553. i--; continue;
  554. }
  555. else
  556. assert(decision == ILimiter::EDecision::NOT_SURE);
  557. }
  558. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  559. return;
  560. }
  561. }
  562. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  563. {
  564. auto ret = std::make_shared<BonusList>();
  565. limitBonuses(allBonuses, *ret);
  566. return ret;
  567. }
  568. void CBonusSystemNode::treeHasChanged()
  569. {
  570. treeChanged++;
  571. }
  572. int64_t CBonusSystemNode::getTreeVersion() const
  573. {
  574. return treeChanged;
  575. }
  576. VCMI_LIB_NAMESPACE_END