ObstacleProxy.cpp 11 KB

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