ObstacleProxy.cpp 11 KB

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