CBonusSystemNode.cpp 15 KB

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