CBonusSystemNode.cpp 15 KB

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