CBonusSystemNode.cpp 15 KB

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