ObjectManager.cpp 14 KB

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