CBonusSystemNode.cpp 15 KB

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