ObjectManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /*
  2. * ObjectManager.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 "ObjectManager.h"
  12. #include "CMapGenerator.h"
  13. #include "TileInfo.h"
  14. #include "RmgMap.h"
  15. #include "RoadPlacer.h"
  16. #include "RiverPlacer.h"
  17. #include "WaterAdopter.h"
  18. #include "../CCreatureHandler.h"
  19. #include "../mapObjects/CommonConstructors.h"
  20. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  21. #include "../mapping/CMap.h"
  22. #include "../mapping/CMapEditManager.h"
  23. #include "Functions.h"
  24. #include "RmgObject.h"
  25. void ObjectManager::process()
  26. {
  27. zone.fractalize();
  28. createRequiredObjects();
  29. }
  30. void ObjectManager::init()
  31. {
  32. DEPENDENCY(WaterAdopter);
  33. POSTFUNCTION(RoadPlacer);
  34. createDistancesPriorityQueue();
  35. }
  36. void ObjectManager::createDistancesPriorityQueue()
  37. {
  38. tilesByDistance.clear();
  39. for (auto & tile : zone.areaPossible().getTilesVector())
  40. {
  41. tilesByDistance.push(std::make_pair(tile, map.getNearestObjectDistance(tile)));
  42. }
  43. }
  44. void ObjectManager::addRequiredObject(CGObjectInstance * obj, si32 strength)
  45. {
  46. requiredObjects.push_back(std::make_pair(obj, strength));
  47. }
  48. void ObjectManager::addCloseObject(CGObjectInstance * obj, si32 strength)
  49. {
  50. closeObjects.push_back(std::make_pair(obj, strength));
  51. }
  52. void ObjectManager::addNearbyObject(CGObjectInstance * obj, CGObjectInstance * nearbyTarget)
  53. {
  54. nearbyObjects.push_back(std::make_pair(obj, nearbyTarget));
  55. }
  56. void ObjectManager::updateDistances(const rmg::Object & obj)
  57. {
  58. tilesByDistance.clear();
  59. for (auto tile : zone.areaPossible().getTiles()) //don't need to mark distance for not possible tiles
  60. {
  61. ui32 d = obj.getArea().distanceSqr(tile); //optimization, only relative distance is interesting
  62. map.setNearestObjectDistance(tile, std::min((float)d, map.getNearestObjectDistance(tile)));
  63. tilesByDistance.push(std::make_pair(tile, map.getNearestObjectDistance(tile)));
  64. }
  65. }
  66. const rmg::Area & ObjectManager::getVisitableArea() const
  67. {
  68. return objectsVisitableArea;
  69. }
  70. std::vector<CGObjectInstance*> ObjectManager::getMines() const
  71. {
  72. std::vector<CGObjectInstance*> mines;
  73. for (auto object : objects)
  74. {
  75. if (object->ID == Obj::MINE)
  76. {
  77. mines.push_back(object);
  78. }
  79. }
  80. return mines;
  81. }
  82. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, std::function<float(const int3)> weightFunction, OptimizeType optimizer) const
  83. {
  84. float bestWeight = 0.f;
  85. int3 result(-1, -1, -1);
  86. if(optimizer & OptimizeType::DISTANCE)
  87. {
  88. auto open = tilesByDistance;
  89. while(!open.empty())
  90. {
  91. auto node = open.top();
  92. open.pop();
  93. int3 tile = node.first;
  94. if(!searchArea.contains(tile))
  95. continue;
  96. obj.setPosition(tile);
  97. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  98. continue;
  99. float weight = weightFunction(tile);
  100. if(weight > bestWeight)
  101. {
  102. bestWeight = weight;
  103. result = tile;
  104. if(!(optimizer & OptimizeType::WEIGHT))
  105. break;
  106. }
  107. }
  108. }
  109. else
  110. {
  111. for(const auto & tile : searchArea.getTiles())
  112. {
  113. obj.setPosition(tile);
  114. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  115. continue;
  116. float weight = weightFunction(tile);
  117. if(weight > bestWeight)
  118. {
  119. bestWeight = weight;
  120. result = tile;
  121. if(!(optimizer & OptimizeType::WEIGHT))
  122. break;
  123. }
  124. }
  125. }
  126. if(result.valid())
  127. obj.setPosition(result);
  128. return result;
  129. }
  130. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, OptimizeType optimizer) const
  131. {
  132. return findPlaceForObject(searchArea, obj, [this, min_dist, &obj](const int3 & tile)
  133. {
  134. auto ti = map.getTile(tile);
  135. float dist = ti.getNearestObjectDistance();
  136. if(dist < min_dist)
  137. return -1.f;
  138. for(auto & t : obj.getArea().getTilesVector())
  139. {
  140. if(map.getTile(t).getNearestObjectDistance() < min_dist)
  141. return -1.f;
  142. }
  143. return dist;
  144. }, optimizer);
  145. }
  146. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, bool isGuarded, bool onlyStraight, OptimizeType optimizer) const
  147. {
  148. return placeAndConnectObject(searchArea, obj, [this, min_dist, &obj](const int3 & tile)
  149. {
  150. auto ti = map.getTile(tile);
  151. float dist = ti.getNearestObjectDistance();
  152. if(dist < min_dist)
  153. return -1.f;
  154. for(auto & t : obj.getArea().getTilesVector())
  155. {
  156. if(map.getTile(t).getNearestObjectDistance() < min_dist)
  157. return -1.f;
  158. }
  159. return dist;
  160. }, isGuarded, onlyStraight, optimizer);
  161. }
  162. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, std::function<float(const int3)> weightFunction, bool isGuarded, bool onlyStraight, OptimizeType optimizer) const
  163. {
  164. int3 pos;
  165. auto possibleArea = searchArea;
  166. while(true)
  167. {
  168. pos = findPlaceForObject(possibleArea, obj, weightFunction, optimizer);
  169. if(!pos.valid())
  170. {
  171. return rmg::Path::invalid();
  172. }
  173. possibleArea.erase(pos); //do not place again at this point
  174. auto accessibleArea = obj.getAccessibleArea(isGuarded) * (zone.areaPossible() + zone.freePaths());
  175. //we should exclude tiles which will be covered
  176. if(isGuarded)
  177. {
  178. auto & guardedArea = obj.instances().back()->getAccessibleArea();
  179. accessibleArea.intersect(guardedArea);
  180. accessibleArea.add(obj.instances().back()->getPosition(true));
  181. }
  182. auto path = zone.searchPath(accessibleArea, onlyStraight, [&obj, isGuarded](const int3 & t)
  183. {
  184. if(isGuarded)
  185. {
  186. auto & guardedArea = obj.instances().back()->getAccessibleArea();
  187. auto & unguardedArea = obj.getAccessibleArea(isGuarded);
  188. if(unguardedArea.contains(t) && !guardedArea.contains(t))
  189. return false;
  190. //guard position is always target
  191. if(obj.instances().back()->getPosition(true) == t)
  192. return true;
  193. }
  194. return !obj.getArea().contains(t);
  195. });
  196. if(path.valid())
  197. {
  198. return path;
  199. }
  200. }
  201. }
  202. bool ObjectManager::createRequiredObjects()
  203. {
  204. logGlobal->trace("Creating required objects");
  205. RandomGeneratorUtil::randomShuffle(requiredObjects, generator.rand);
  206. for(const auto & object : requiredObjects)
  207. {
  208. auto * obj = object.first;
  209. int3 pos;
  210. rmg::Object rmgObject(*obj);
  211. rmgObject.setTemplate(zone.getTerrainType());
  212. bool guarded = addGuard(rmgObject, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY));
  213. auto path = placeAndConnectObject(zone.areaPossible(), rmgObject, 3, guarded, false, OptimizeType::DISTANCE);
  214. if(!path.valid())
  215. {
  216. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  217. return false;
  218. }
  219. zone.connectPath(path);
  220. placeObject(rmgObject, guarded, true);
  221. for(const auto & nearby : nearbyObjects)
  222. {
  223. if(nearby.second != obj)
  224. continue;
  225. rmg::Object rmgNearObject(*nearby.first);
  226. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  227. possibleArea.intersect(zone.areaPossible());
  228. if(possibleArea.empty())
  229. {
  230. rmgNearObject.clear();
  231. continue;
  232. }
  233. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), generator.rand));
  234. placeObject(rmgNearObject, false, false);
  235. }
  236. }
  237. for(const auto & object : closeObjects)
  238. {
  239. auto * obj = object.first;
  240. int3 pos;
  241. auto possibleArea = zone.areaPossible();
  242. rmg::Object rmgObject(*obj);
  243. rmgObject.setTemplate(zone.getTerrainType());
  244. bool guarded = addGuard(rmgObject, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY));
  245. auto path = placeAndConnectObject(zone.areaPossible(), rmgObject,
  246. [this, &rmgObject](const int3 & tile)
  247. {
  248. float dist = rmgObject.getArea().distanceSqr(zone.getPos());
  249. dist *= (dist > 12.f * 12.f) ? 10.f : 1.f; //tiles closer 12 are preferrable
  250. dist = 1000000.f - dist; //some big number
  251. return dist + map.getNearestObjectDistance(tile);
  252. }, guarded, false, OptimizeType::WEIGHT);
  253. if(!path.valid())
  254. {
  255. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  256. return false;
  257. }
  258. zone.connectPath(path);
  259. placeObject(rmgObject, guarded, true);
  260. for(const auto & nearby : nearbyObjects)
  261. {
  262. if(nearby.second != obj)
  263. continue;
  264. rmg::Object rmgNearObject(*nearby.first);
  265. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  266. possibleArea.intersect(zone.areaPossible());
  267. if(possibleArea.empty())
  268. {
  269. rmgNearObject.clear();
  270. continue;
  271. }
  272. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), generator.rand));
  273. placeObject(rmgNearObject, false, false);
  274. }
  275. }
  276. //create object on specific positions
  277. //TODO: implement guards
  278. for (const auto &obj : instantObjects)
  279. {
  280. rmg::Object rmgObject(*obj.first);
  281. rmgObject.setPosition(obj.second);
  282. placeObject(rmgObject, false, false);
  283. }
  284. requiredObjects.clear();
  285. closeObjects.clear();
  286. nearbyObjects.clear();
  287. instantObjects.clear();
  288. return true;
  289. }
  290. void ObjectManager::placeObject(rmg::Object & object, bool guarded, bool updateDistance)
  291. {
  292. object.finalize(map);
  293. zone.areaPossible().subtract(object.getArea());
  294. bool keepVisitable = zone.freePaths().contains(object.getVisitablePosition());
  295. zone.freePaths().subtract(object.getArea()); //just to avoid areas overlapping
  296. if(keepVisitable)
  297. zone.freePaths().add(object.getVisitablePosition());
  298. zone.areaUsed().unite(object.getArea());
  299. zone.areaUsed().erase(object.getVisitablePosition());
  300. if(guarded)
  301. {
  302. auto guardedArea = object.instances().back()->getAccessibleArea();
  303. guardedArea.add(object.instances().back()->getVisitablePosition());
  304. auto areaToBlock = object.getAccessibleArea(true);
  305. areaToBlock.subtract(guardedArea);
  306. zone.areaPossible().subtract(areaToBlock);
  307. for(auto & i : areaToBlock.getTilesVector())
  308. if(map.isOnMap(i) && map.isPossible(i))
  309. map.setOccupied(i, ETileType::BLOCKED);
  310. }
  311. if(updateDistance)
  312. updateDistances(object);
  313. for(auto * instance : object.instances())
  314. {
  315. objectsVisitableArea.add(instance->getVisitablePosition());
  316. objects.push_back(&instance->object());
  317. if(auto * m = zone.getModificator<RoadPlacer>())
  318. {
  319. if(instance->object().appearance->isVisitableFromTop())
  320. m->areaForRoads().add(instance->getVisitablePosition());
  321. else
  322. {
  323. m->areaIsolated().add(instance->getVisitablePosition() + int3(0, -1, 0));
  324. }
  325. }
  326. }
  327. switch(object.instances().front()->object().ID)
  328. {
  329. case Obj::TOWN:
  330. case Obj::RANDOM_TOWN:
  331. case Obj::MONOLITH_TWO_WAY:
  332. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  333. case Obj::MONOLITH_ONE_WAY_EXIT:
  334. case Obj::SUBTERRANEAN_GATE:
  335. case Obj::SHIPYARD:
  336. if(auto * m = zone.getModificator<RoadPlacer>())
  337. m->addRoadNode(object.instances().front()->getVisitablePosition());
  338. break;
  339. case Obj::WATER_WHEEL:
  340. if(auto * m = zone.getModificator<RiverPlacer>())
  341. m->addRiverNode(object.instances().front()->getVisitablePosition());
  342. break;
  343. default:
  344. break;
  345. }
  346. }
  347. CGCreature * ObjectManager::chooseGuard(si32 strength, bool zoneGuard)
  348. {
  349. //precalculate actual (randomized) monster strength based on this post
  350. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  351. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  352. int monsterStrength = (zoneGuard ? 0 : zone.zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  353. static const std::array<int, 5> value1{2500, 1500, 1000, 500, 0};
  354. static const std::array<int, 5> value2{7500, 7500, 7500, 5000, 5000};
  355. static const std::array<float, 5> multiplier1{0.5, 0.75, 1.0, 1.5, 1.5};
  356. static const std::array<float, 5> multiplier2{0.5, 0.75, 1.0, 1.0, 1.5};
  357. int strength1 = static_cast<int>(std::max(0.f, (strength - value1.at(monsterStrength)) * multiplier1.at(monsterStrength)));
  358. int strength2 = static_cast<int>(std::max(0.f, (strength - value2.at(monsterStrength)) * multiplier2.at(monsterStrength)));
  359. strength = strength1 + strength2;
  360. if (strength < generator.getConfig().minGuardStrength)
  361. return nullptr; //no guard at all
  362. CreatureID creId = CreatureID::NONE;
  363. int amount = 0;
  364. std::vector<CreatureID> possibleCreatures;
  365. for(auto cre : VLC->creh->objects)
  366. {
  367. if(cre->special)
  368. continue;
  369. if(!cre->AIValue) //bug #2681
  370. continue;
  371. if(!vstd::contains(zone.getMonsterTypes(), cre->faction))
  372. continue;
  373. if(((si32)(cre->AIValue * (cre->ammMin + cre->ammMax) / 2) < strength) && (strength < (si32)cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100
  374. {
  375. possibleCreatures.push_back(cre->idNumber);
  376. }
  377. }
  378. if(possibleCreatures.size())
  379. {
  380. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, generator.rand);
  381. amount = strength / VLC->creh->objects[creId]->AIValue;
  382. if (amount >= 4)
  383. amount = static_cast<int>(amount * generator.rand.nextDouble(0.75, 1.25));
  384. }
  385. else //just pick any available creature
  386. {
  387. creId = CreatureID(132); //Azure Dragon
  388. amount = strength / VLC->creh->objects[creId]->AIValue;
  389. }
  390. auto guardFactory = VLC->objtypeh->getHandlerFor(Obj::MONSTER, creId);
  391. auto guard = (CGCreature *) guardFactory->create();
  392. guard->character = CGCreature::HOSTILE;
  393. auto hlp = new CStackInstance(creId, amount);
  394. //will be set during initialization
  395. guard->putStack(SlotID(0), hlp);
  396. return guard;
  397. }
  398. bool ObjectManager::addGuard(rmg::Object & object, si32 strength, bool zoneGuard)
  399. {
  400. auto * guard = chooseGuard(strength, zoneGuard);
  401. if(!guard)
  402. return false;
  403. rmg::Area visitablePos({object.getVisitablePosition()});
  404. visitablePos.unite(visitablePos.getBorderOutside());
  405. auto accessibleArea = object.getAccessibleArea();
  406. accessibleArea.intersect(visitablePos);
  407. if(accessibleArea.empty())
  408. {
  409. delete guard;
  410. return false;
  411. }
  412. auto guardTiles = accessibleArea.getTilesVector();
  413. auto guardPos = *std::min_element(guardTiles.begin(), guardTiles.end(), [&object](const int3 & l, const int3 & r)
  414. {
  415. auto p = object.getVisitablePosition();
  416. if(l.y > r.y)
  417. return true;
  418. if(l.y == r.y)
  419. return abs(l.x - p.x) < abs(r.x - p.x);
  420. return false;
  421. });
  422. auto & instance = object.addInstance(*guard);
  423. instance.setPosition(guardPos - object.getPosition());
  424. return true;
  425. }