2
0

ResourceManager.cpp 9.0 KB

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