CBonusSystemNode.cpp 15 KB

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