ResourceManager.cpp 9.2 KB

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