ObstacleProxy.cpp 10 KB

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