ObstacleProxy.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * ObstacleProxy.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 "ObstacleProxy.h"
  12. #include "../mapping/CMap.h"
  13. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  14. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  15. #include "../mapObjects/CGObjectInstance.h"
  16. #include "../mapObjects/ObjectTemplate.h"
  17. #include "../mapObjects/ObstacleSetHandler.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. void ObstacleProxy::collectPossibleObstacles(TerrainId terrain)
  20. {
  21. //get all possible obstacles for this terrain
  22. for(auto primaryID : VLC->objtypeh->knownObjects())
  23. {
  24. for(auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  25. {
  26. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  27. if(handler->isStaticObject())
  28. {
  29. for(const auto & temp : handler->getTemplates())
  30. {
  31. if(temp->canBePlacedAt(terrain) && temp->getBlockMapOffset().valid())
  32. obstaclesBySize[temp->getBlockedOffsets().size()].push_back(temp);
  33. }
  34. }
  35. }
  36. }
  37. sortObstacles();
  38. }
  39. void ObstacleProxy::sortObstacles()
  40. {
  41. for(const auto & o : obstaclesBySize)
  42. {
  43. possibleObstacles.emplace_back(o);
  44. }
  45. boost::sort(possibleObstacles, [](const ObstaclePair &p1, const ObstaclePair &p2) -> bool
  46. {
  47. return p1.first > p2.first; //bigger obstacles first
  48. });
  49. }
  50. bool ObstacleProxy::prepareBiome(TerrainId terrain, CRandomGenerator & rand)
  51. {
  52. // FIXME: All the mountains have same ID and mostly same subID, how to differentiate them?
  53. possibleObstacles.clear();
  54. std::vector<ObstacleSet> obstacleSets;
  55. size_t selectedSets = 0;
  56. size_t smallSets = 0;
  57. const size_t MINIMUM_SETS = 6;
  58. const size_t MAXIMUM_SETS = 9;
  59. const size_t MIN_SMALL_SETS = 3;
  60. const size_t MAX_SMALL_SETS = 5;
  61. TObstacleTypes mountainSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter(ObstacleSet::EObstacleType::MOUNTAINS, terrain));
  62. if (!mountainSets.empty())
  63. {
  64. obstacleSets.push_back(*RandomGeneratorUtil::nextItem(mountainSets, rand));
  65. selectedSets++;
  66. logGlobal->info("Mountain set added");
  67. }
  68. else
  69. {
  70. logGlobal->warn("No mountain sets found for terrain %s", terrain.encode(terrain.getNum()));
  71. // FIXME: Do we ever want to generate obstacles without any mountains?
  72. }
  73. TObstacleTypes treeSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter(ObstacleSet::EObstacleType::TREES, terrain));
  74. // 1 or 2 tree sets
  75. size_t treeSetsCount = std::min<size_t>(treeSets.size(), rand.nextInt(1, 2));
  76. for (size_t i = 0; i < treeSetsCount; i++)
  77. {
  78. obstacleSets.push_back(*RandomGeneratorUtil::nextItem(treeSets, rand));
  79. selectedSets++;
  80. }
  81. logGlobal->info("Added %d tree sets", treeSetsCount);
  82. // Some obstacle types may be completely missing from water, but it's not a problem
  83. TObstacleTypes largeSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter({ObstacleSet::EObstacleType::LAKES, ObstacleSet::EObstacleType::CRATERS},
  84. terrain));
  85. // We probably don't want to have lakes and craters at the same time, choose one of them
  86. if (!largeSets.empty())
  87. {
  88. obstacleSets.push_back(*RandomGeneratorUtil::nextItem(largeSets, rand));
  89. selectedSets++;
  90. // TODO: Convert to string
  91. logGlobal->info("Added large set of type %s", obstacleSets.back().getType());
  92. }
  93. TObstacleTypes rockSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter(ObstacleSet::EObstacleType::ROCKS, terrain));
  94. size_t rockSetsCount = std::min<size_t>(rockSets.size(), rand.nextInt(1, 2));
  95. for (size_t i = 0; i < rockSetsCount; i++)
  96. {
  97. obstacleSets.push_back(*RandomGeneratorUtil::nextItem(rockSets, rand));
  98. selectedSets++;
  99. }
  100. logGlobal->info("Added %d rock sets", rockSetsCount);
  101. TObstacleTypes plantSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter(ObstacleSet::EObstacleType::PLANTS, terrain));
  102. // 1 or 2 sets (3 - rock sets)
  103. size_t plantSetsCount = std::min<size_t>(plantSets.size(), rand.nextInt(1, std::max<size_t>(3 - rockSetsCount, 2)));
  104. for (size_t i = 0; i < plantSetsCount; i++)
  105. {
  106. {
  107. obstacleSets.push_back(*RandomGeneratorUtil::nextItem(plantSets, rand));
  108. selectedSets++;
  109. }
  110. }
  111. logGlobal->info("Added %d plant sets", plantSetsCount);
  112. //3 to 5 of total small sets (rocks, plants, structures, animals and others)
  113. //This gives total of 6 to 9 different sets
  114. size_t maxSmallSets = std::min<size_t>(MAX_SMALL_SETS, std::max(MIN_SMALL_SETS, MAXIMUM_SETS - selectedSets));
  115. size_t smallSetsCount = rand.nextInt(MIN_SMALL_SETS, maxSmallSets);
  116. TObstacleTypes smallObstacleSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter({ObstacleSet::EObstacleType::STRUCTURES, ObstacleSet::EObstacleType::ANIMALS},
  117. terrain));
  118. RandomGeneratorUtil::randomShuffle(smallObstacleSets, rand);
  119. TObstacleTypes otherSets = VLC->biomeHandler->getObstacles(ObstacleSetFilter(ObstacleSet::EObstacleType::OTHER,
  120. terrain));
  121. RandomGeneratorUtil::randomShuffle(otherSets, rand);
  122. while (smallSetsCount > 0)
  123. {
  124. if (!smallObstacleSets.empty())
  125. {
  126. obstacleSets.push_back(smallObstacleSets.back());
  127. smallObstacleSets.pop_back();
  128. selectedSets++;
  129. smallSetsCount--;
  130. logGlobal->info("Added small set of type %s", obstacleSets.back().getType());
  131. }
  132. else if(otherSets.empty())
  133. {
  134. logGlobal->warn("No other sets found for terrain %s", terrain.encode(terrain.getNum()));
  135. break;
  136. }
  137. if (smallSetsCount > 0)
  138. {
  139. // Fill with whatever's left
  140. if (!otherSets.empty())
  141. {
  142. obstacleSets.push_back(otherSets.back());
  143. otherSets.pop_back();
  144. selectedSets++;
  145. smallSetsCount--;
  146. logGlobal->info("Added set of other obstacles");
  147. }
  148. }
  149. }
  150. // Copy this set to our possible obstacles
  151. if (selectedSets >= MINIMUM_SETS ||
  152. (terrain == TerrainId::WATER && selectedSets > 0))
  153. {
  154. obstaclesBySize.clear();
  155. for (const auto & os : obstacleSets)
  156. {
  157. for (const auto & temp : os.getObstacles())
  158. {
  159. if(temp->getBlockMapOffset().valid())
  160. {
  161. obstaclesBySize[temp->getBlockedOffsets().size()].push_back(temp);
  162. }
  163. }
  164. }
  165. sortObstacles();
  166. return true;
  167. }
  168. else
  169. {
  170. return false; // Proceed with old method
  171. }
  172. }
  173. void ObstacleProxy::addBlockedTile(const int3& tile)
  174. {
  175. blockedArea.add(tile);
  176. }
  177. void ObstacleProxy::setBlockedArea(const rmg::Area& area)
  178. {
  179. blockedArea = area;
  180. }
  181. void ObstacleProxy::clearBlockedArea()
  182. {
  183. blockedArea.clear();
  184. }
  185. bool ObstacleProxy::isProhibited(const rmg::Area& objArea) const
  186. {
  187. return false;
  188. };
  189. int ObstacleProxy::getWeightedObjects(const int3 & tile, CRandomGenerator & rand, IGameCallback * cb, std::list<rmg::Object> & allObjects, std::vector<std::pair<rmg::Object*, int3>> & weightedObjects)
  190. {
  191. int maxWeight = std::numeric_limits<int>::min();
  192. for(auto & possibleObstacle : possibleObstacles)
  193. {
  194. if(!possibleObstacle.first)
  195. continue;
  196. auto shuffledObstacles = possibleObstacle.second;
  197. RandomGeneratorUtil::randomShuffle(shuffledObstacles, rand);
  198. for(const auto & temp : shuffledObstacles)
  199. {
  200. auto handler = VLC->objtypeh->getHandlerFor(temp->id, temp->subid);
  201. auto * obj = handler->create(nullptr, temp);
  202. allObjects.emplace_back(*obj);
  203. rmg::Object * rmgObject = &allObjects.back();
  204. for(const auto & offset : obj->getBlockedOffsets())
  205. {
  206. auto newPos = tile - offset;
  207. if(!isInTheMap(newPos))
  208. continue;
  209. rmgObject->setPosition(newPos);
  210. bool isInTheMapEntirely = true;
  211. for (const auto & t : rmgObject->getArea().getTiles())
  212. {
  213. if (!isInTheMap(t))
  214. {
  215. isInTheMapEntirely = false;
  216. break;
  217. }
  218. }
  219. if (!isInTheMapEntirely)
  220. {
  221. continue;
  222. }
  223. if(isProhibited(rmgObject->getArea()))
  224. continue;
  225. int coverageBlocked = 0;
  226. int coveragePossible = 0;
  227. //do not use area intersection in optimization purposes
  228. for(const auto & t : rmgObject->getArea().getTilesVector())
  229. {
  230. auto coverage = verifyCoverage(t);
  231. if(coverage.first)
  232. ++coverageBlocked;
  233. if(coverage.second)
  234. ++coveragePossible;
  235. }
  236. int coverageOverlap = possibleObstacle.first - coverageBlocked - coveragePossible;
  237. int weight = possibleObstacle.first + coverageBlocked - coverageOverlap * possibleObstacle.first;
  238. assert(coverageOverlap >= 0);
  239. if(weight > maxWeight)
  240. {
  241. weightedObjects.clear();
  242. maxWeight = weight;
  243. weightedObjects.emplace_back(rmgObject, rmgObject->getPosition());
  244. if(weight > 0)
  245. break;
  246. }
  247. else if(weight == maxWeight)
  248. weightedObjects.emplace_back(rmgObject, rmgObject->getPosition());
  249. }
  250. }
  251. if(maxWeight > 0)
  252. break;
  253. }
  254. return maxWeight;
  255. }
  256. std::set<CGObjectInstance*> ObstacleProxy::createObstacles(CRandomGenerator & rand, IGameCallback * cb)
  257. {
  258. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  259. auto blockedTiles = blockedArea.getTilesVector();
  260. int tilePos = 0;
  261. std::set<CGObjectInstance*> objs;
  262. while(!blockedArea.empty() && tilePos < blockedArea.getTilesVector().size())
  263. {
  264. auto tile = blockedArea.getTilesVector()[tilePos];
  265. std::list<rmg::Object> allObjects;
  266. std::vector<std::pair<rmg::Object*, int3>> weightedObjects;
  267. int maxWeight = getWeightedObjects(tile, rand, cb, allObjects, weightedObjects);
  268. if(weightedObjects.empty())
  269. {
  270. tilePos += 1;
  271. continue;
  272. }
  273. auto objIter = RandomGeneratorUtil::nextItem(weightedObjects, rand);
  274. objIter->first->setPosition(objIter->second);
  275. placeObject(*objIter->first, objs);
  276. blockedArea.subtract(objIter->first->getArea());
  277. tilePos = 0;
  278. postProcess(*objIter->first);
  279. if(maxWeight < 0)
  280. logGlobal->warn("Placed obstacle with negative weight at %s", objIter->second.toString());
  281. for(auto & o : allObjects)
  282. {
  283. if(&o != objIter->first)
  284. o.clear();
  285. }
  286. }
  287. return objs;
  288. }
  289. //FIXME: Only editor placer obstacles directly
  290. void ObstacleProxy::finalInsertion(CMapEditManager * manager, std::set<CGObjectInstance*> & instances)
  291. {
  292. manager->insertObjects(instances); //insert as one operation - for undo purposes
  293. }
  294. std::pair<bool, bool> ObstacleProxy::verifyCoverage(const int3 & t) const
  295. {
  296. return {blockedArea.contains(t), false};
  297. }
  298. void ObstacleProxy::placeObject(rmg::Object & object, std::set<CGObjectInstance*> & instances)
  299. {
  300. for (auto * instance : object.instances())
  301. {
  302. instances.insert(&instance->object());
  303. }
  304. }
  305. EditorObstaclePlacer::EditorObstaclePlacer(CMap* map):
  306. map(map)
  307. {
  308. }
  309. bool EditorObstaclePlacer::isInTheMap(const int3& tile)
  310. {
  311. return map->isInTheMap(tile);
  312. }
  313. std::set<CGObjectInstance*> EditorObstaclePlacer::placeObstacles(CRandomGenerator & rand)
  314. {
  315. auto obstacles = createObstacles(rand, map->cb);
  316. finalInsertion(map->getEditManager(), obstacles);
  317. return obstacles;
  318. }
  319. VCMI_LIB_NAMESPACE_END