CBonusSystemNode.cpp 15 KB

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