ObjectManager.cpp 15 KB

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