ResourceManager.cpp 9.4 KB

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