ResourceManager.cpp 9.2 KB

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