ResourceManager.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. * ResourceManager.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 "ResourceManager.h"
  12. #include "Goals/Goals.h"
  13. #include "../../CCallback.h"
  14. #include "../../lib/mapObjects/MapObjects.h"
  15. ResourceObjective::ResourceObjective(const TResources & Res, Goals::TSubgoal Goal)
  16. : resources(Res), goal(Goal)
  17. {
  18. }
  19. bool ResourceObjective::operator<(const ResourceObjective & ro) const
  20. {
  21. return goal->priority < ro.goal->priority;
  22. }
  23. ResourceManager::ResourceManager(CPlayerSpecificInfoCallback * CB, VCAI * AI)
  24. : ai(AI), cb(CB)
  25. {
  26. }
  27. void ResourceManager::init(CPlayerSpecificInfoCallback * CB)
  28. {
  29. cb = CB;
  30. }
  31. void ResourceManager::setAI(VCAI * AI)
  32. {
  33. ai = AI;
  34. }
  35. bool ResourceManager::canAfford(const TResources & cost) const
  36. {
  37. return freeResources().canAfford(cost);
  38. }
  39. TResources ResourceManager::estimateIncome() const
  40. {
  41. TResources ret;
  42. for (const CGTownInstance * t : cb->getTownsInfo())
  43. {
  44. ret += t->dailyIncome();
  45. }
  46. for (const CGObjectInstance * obj : ai->getFlaggedObjects())
  47. {
  48. if (obj->ID == Obj::MINE)
  49. {
  50. auto mine = dynamic_cast<const CGMine*>(obj);
  51. ret += mine->dailyIncome();
  52. }
  53. }
  54. return ret;
  55. }
  56. void ResourceManager::reserveResources(const TResources & res, Goals::TSubgoal goal)
  57. {
  58. if (!goal->invalid())
  59. tryPush(ResourceObjective(res, goal));
  60. else
  61. logAi->warn("Attempt to reserve resources for Invalid goal");
  62. }
  63. Goals::TSubgoal ResourceManager::collectResourcesForOurGoal(ResourceObjective &o) const
  64. {
  65. auto allResources = cb->getResourceAmount();
  66. auto income = estimateIncome();
  67. GameResID resourceType = EGameResID::NONE;
  68. TResource amountToCollect = 0;
  69. using resPair = std::pair<GameResID, TResource>;
  70. std::map<GameResID, TResource> missingResources;
  71. //TODO: unit test for complex resource sets
  72. //sum missing resources of given type for ALL reserved objectives
  73. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  74. {
  75. //choose specific resources we need for this goal (not 0)
  76. for (auto r = ResourceSet::nziterator(o.resources); r.valid(); r++)
  77. missingResources[r->resType] += it->resources[r->resType]; //goal it costs r units of resType
  78. }
  79. for (auto it = ResourceSet::nziterator(o.resources); it.valid(); it++)
  80. {
  81. missingResources[it->resType] -= allResources[it->resType]; //missing = (what we need) - (what we have)
  82. vstd::amax(missingResources[it->resType], 0); // if we have more resources than reserved, we don't need them
  83. }
  84. vstd::erase_if(missingResources, [=](const resPair & p) -> bool
  85. {
  86. return !(p.second); //in case evaluated to 0 or less
  87. });
  88. if (missingResources.empty()) //FIXME: should be unit-tested out
  89. {
  90. logAi->error("We don't need to collect resources %s for goal %s", o.resources.toString(), o.goal->name());
  91. return o.goal;
  92. }
  93. for (const resPair p : missingResources)
  94. {
  95. if (!income[p.first]) //prioritize resources with 0 income
  96. {
  97. resourceType = p.first;
  98. amountToCollect = p.second;
  99. break;
  100. }
  101. }
  102. if (resourceType == EGameResID::NONE) //no needed resources has 0 income,
  103. {
  104. //find the one which takes longest to collect
  105. using timePair = std::pair<GameResID, float>;
  106. std::map<GameResID, float> daysToEarn;
  107. for (auto it : missingResources)
  108. daysToEarn[it.first] = (float)missingResources[it.first] / income[it.first];
  109. auto incomeComparer = [](const timePair & lhs, const timePair & rhs) -> bool
  110. {
  111. //theoretically income can be negative, but that falls into this comparison
  112. return lhs.second < rhs.second;
  113. };
  114. resourceType = boost::max_element(daysToEarn, incomeComparer)->first;
  115. amountToCollect = missingResources[resourceType];
  116. }
  117. //this is abstract goal and might take some time to complete
  118. return Goals::sptr(Goals::CollectRes(resourceType, amountToCollect).setisAbstract(true));
  119. }
  120. Goals::TSubgoal ResourceManager::whatToDo() const //suggest any goal
  121. {
  122. if (queue.size())
  123. {
  124. auto o = queue.top();
  125. auto allResources = cb->getResourceAmount(); //we don't consider savings, it's out top-priority goal
  126. if (allResources.canAfford(o.resources))
  127. return o.goal;
  128. else //we can't afford even top-priority goal, need to collect resources
  129. return collectResourcesForOurGoal(o);
  130. }
  131. else
  132. return Goals::sptr(Goals::Invalid()); //nothing else to do
  133. }
  134. Goals::TSubgoal ResourceManager::whatToDo(TResources &res, Goals::TSubgoal goal)
  135. {
  136. logAi->trace("ResourceManager: checking goal %s which requires resources %s", goal->name(), res.toString());
  137. TResources accumulatedResources;
  138. auto allResources = cb->getResourceAmount();
  139. ResourceObjective ro(res, goal);
  140. tryPush(ro);
  141. //check if we can afford all the objectives with higher priority first
  142. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  143. {
  144. accumulatedResources += it->resources;
  145. logAi->trace(
  146. "ResourceManager: checking goal %s, accumulatedResources=%s, available=%s",
  147. it->goal->name(),
  148. accumulatedResources.toString(),
  149. allResources.toString());
  150. if(!accumulatedResources.canBeAfforded(allResources))
  151. {
  152. //can't afford
  153. break;
  154. }
  155. else //can afford all goals up to this point
  156. {
  157. if(it->goal == goal)
  158. {
  159. logAi->debug("ResourceManager: can afford goal %s", goal->name());
  160. return goal; //can afford immediately
  161. }
  162. }
  163. }
  164. logAi->debug("ResourceManager: can not afford goal %s", goal->name());
  165. return collectResourcesForOurGoal(ro);
  166. }
  167. bool ResourceManager::containsObjective(Goals::TSubgoal goal) const
  168. {
  169. logAi->trace("Entering ResourceManager.containsObjective goal=%s", goal->name());
  170. dumpToLog();
  171. //TODO: unit tests for once
  172. for (auto objective : queue)
  173. {
  174. if (objective.goal == goal)
  175. return true;
  176. }
  177. return false;
  178. }
  179. bool ResourceManager::notifyGoalCompleted(Goals::TSubgoal goal)
  180. {
  181. logAi->trace("Entering ResourceManager.notifyGoalCompleted goal=%s", goal->name());
  182. if (goal->invalid())
  183. logAi->warn("Attempt to complete Invalid goal");
  184. std::function<bool(const Goals::TSubgoal &)> equivalentGoalsCheck = [goal](const Goals::TSubgoal & x) -> bool
  185. {
  186. return x == goal || x->fulfillsMe(goal);
  187. };
  188. bool removedGoal = removeOutdatedObjectives(equivalentGoalsCheck);
  189. dumpToLog();
  190. return removedGoal;
  191. }
  192. bool ResourceManager::updateGoal(Goals::TSubgoal goal)
  193. {
  194. //we update priority of goal if it is easier or more difficult to complete
  195. if (goal->invalid())
  196. logAi->warn("Attempt to update Invalid goal");
  197. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  198. {
  199. return ro.goal == goal;
  200. });
  201. if (it != queue.end())
  202. {
  203. it->goal->setpriority(goal->priority);
  204. auto handle = queue.s_handle_from_iterator(it);
  205. queue.update(handle); //restore order
  206. return true;
  207. }
  208. else
  209. return false;
  210. }
  211. void ResourceManager::dumpToLog() const
  212. {
  213. for(auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  214. {
  215. logAi->trace("ResourceManager contains goal %s which requires resources %s", it->goal->name(), it->resources.toString());
  216. }
  217. }
  218. bool ResourceManager::tryPush(const ResourceObjective & o)
  219. {
  220. auto goal = o.goal;
  221. logAi->trace("ResourceManager: Trying to add goal %s which requires resources %s", goal->name(), o.resources.toString());
  222. dumpToLog();
  223. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  224. {
  225. return ro.goal == goal;
  226. });
  227. if (it != queue.end())
  228. {
  229. auto handle = queue.s_handle_from_iterator(it);
  230. vstd::amax(goal->priority, it->goal->priority); //increase priority if case
  231. //update resources with new value
  232. queue.update(handle, ResourceObjective(o.resources, goal)); //restore order
  233. return false;
  234. }
  235. else
  236. {
  237. queue.push(o); //add new objective
  238. logAi->debug("Reserved resources (%s) for %s", o.resources.toString(), goal->name());
  239. return true;
  240. }
  241. }
  242. bool ResourceManager::hasTasksLeft() const
  243. {
  244. return !queue.empty();
  245. }
  246. bool ResourceManager::removeOutdatedObjectives(std::function<bool(const Goals::TSubgoal &)> predicate)
  247. {
  248. bool removedAnything = false;
  249. while(true)
  250. { //unfortunately we can't use remove_if on heap
  251. auto it = boost::find_if(queue, [&](const ResourceObjective & ro) -> bool
  252. {
  253. return predicate(ro.goal);
  254. });
  255. if(it != queue.end()) //removed at least one
  256. {
  257. logAi->debug("Removing goal %s from ResourceManager.", it->goal->name());
  258. queue.erase(queue.s_handle_from_iterator(it));
  259. removedAnything = true;
  260. }
  261. else
  262. { //found nothing more to remove
  263. break;
  264. }
  265. }
  266. return removedAnything;
  267. }
  268. TResources ResourceManager::reservedResources() const
  269. {
  270. TResources res;
  271. for (auto it : queue) //subtract the value of reserved goals
  272. res += it.resources;
  273. return res;
  274. }
  275. TResources ResourceManager::freeResources() const
  276. {
  277. TResources myRes = cb->getResourceAmount();
  278. myRes -= reservedResources(); //subtract the value of reserved goals
  279. for (auto & val : myRes)
  280. vstd::amax(val, 0); //never negative
  281. return myRes;
  282. }
  283. TResource ResourceManager::freeGold() const
  284. {
  285. return freeResources()[EGameResID::GOLD];
  286. }
  287. TResources ResourceManager::allResources() const
  288. {
  289. return cb->getResourceAmount();
  290. }
  291. TResource ResourceManager::allGold() const
  292. {
  293. return cb->getResourceAmount()[EGameResID::GOLD];
  294. }